@ingenyus/swarm-wasp 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +229 -21
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/common/filesystem.d.ts +0 -14
  4. package/dist/common/filesystem.d.ts.map +1 -1
  5. package/dist/common/filesystem.js +123 -0
  6. package/dist/common/index.d.ts +0 -1
  7. package/dist/common/index.d.ts.map +1 -1
  8. package/dist/common/index.js +366 -0
  9. package/dist/common/prisma.js +140 -0
  10. package/dist/common/schemas.d.ts +8 -42
  11. package/dist/common/schemas.d.ts.map +1 -1
  12. package/dist/common/schemas.js +54 -0
  13. package/dist/common/templates.js +52 -0
  14. package/dist/generators/action/action-generator.d.ts +16 -29
  15. package/dist/generators/action/action-generator.d.ts.map +1 -1
  16. package/dist/generators/action/action-generator.js +1425 -0
  17. package/dist/generators/action/index.js +1425 -0
  18. package/dist/generators/action/schema.d.ts +11 -23
  19. package/dist/generators/action/schema.d.ts.map +1 -1
  20. package/dist/generators/action/schema.js +115 -0
  21. package/dist/generators/api/api-generator.d.ts +19 -26
  22. package/dist/generators/api/api-generator.d.ts.map +1 -1
  23. package/dist/generators/api/api-generator.js +1104 -0
  24. package/dist/generators/api/index.js +1104 -0
  25. package/dist/generators/api/schema.d.ts +13 -21
  26. package/dist/generators/api/schema.d.ts.map +1 -1
  27. package/dist/generators/api/schema.js +117 -0
  28. package/dist/generators/api-namespace/api-namespace-generator.d.ts +10 -17
  29. package/dist/generators/api-namespace/api-namespace-generator.d.ts.map +1 -1
  30. package/dist/generators/api-namespace/api-namespace-generator.js +1028 -0
  31. package/dist/generators/api-namespace/index.js +1028 -0
  32. package/dist/generators/api-namespace/schema.d.ts +4 -12
  33. package/dist/generators/api-namespace/schema.d.ts.map +1 -1
  34. package/dist/generators/api-namespace/schema.js +89 -0
  35. package/dist/generators/base/{entity-generator.base.d.ts → component-generator.base.d.ts} +9 -9
  36. package/dist/generators/base/component-generator.base.d.ts.map +1 -0
  37. package/dist/generators/base/component-generator.base.js +931 -0
  38. package/dist/generators/base/index.d.ts +1 -1
  39. package/dist/generators/base/index.d.ts.map +1 -1
  40. package/dist/generators/base/index.js +1330 -0
  41. package/dist/generators/base/operation-generator.base.d.ts +12 -3
  42. package/dist/generators/base/operation-generator.base.d.ts.map +1 -1
  43. package/dist/generators/base/operation-generator.base.js +1331 -0
  44. package/dist/generators/base/wasp-generator.base.d.ts +2 -1
  45. package/dist/generators/base/wasp-generator.base.d.ts.map +1 -1
  46. package/dist/generators/base/wasp-generator.base.js +706 -0
  47. package/dist/generators/config/config-generator.d.ts +7 -4
  48. package/dist/generators/config/config-generator.d.ts.map +1 -1
  49. package/dist/generators/config/config-generator.js +0 -0
  50. package/dist/generators/config/index.js +596 -0
  51. package/dist/generators/config/wasp-config-generator.d.ts +1 -1
  52. package/dist/generators/config/wasp-config-generator.d.ts.map +1 -1
  53. package/dist/generators/config/wasp-config-generator.js +596 -0
  54. package/dist/generators/crud/crud-generator.d.ts +34 -22
  55. package/dist/generators/crud/crud-generator.d.ts.map +1 -1
  56. package/dist/generators/crud/crud-generator.js +1550 -0
  57. package/dist/generators/crud/index.js +1550 -0
  58. package/dist/generators/crud/schema.d.ts +25 -18
  59. package/dist/generators/crud/schema.d.ts.map +1 -1
  60. package/dist/generators/crud/schema.js +133 -0
  61. package/dist/generators/feature/feature-generator.d.ts +20 -0
  62. package/dist/generators/feature/feature-generator.d.ts.map +1 -0
  63. package/dist/generators/feature/feature-generator.js +765 -0
  64. package/dist/generators/feature/index.d.ts +2 -0
  65. package/dist/generators/feature/index.d.ts.map +1 -0
  66. package/dist/generators/feature/index.js +765 -0
  67. package/dist/generators/feature/schema.d.ts +5 -0
  68. package/dist/generators/feature/schema.d.ts.map +1 -0
  69. package/dist/generators/feature/schema.js +86 -0
  70. package/dist/generators/index.d.ts +1 -1
  71. package/dist/generators/index.d.ts.map +1 -1
  72. package/dist/generators/index.js +2211 -0
  73. package/dist/generators/job/index.js +1099 -0
  74. package/dist/generators/job/job-generator.d.ts +12 -23
  75. package/dist/generators/job/job-generator.d.ts.map +1 -1
  76. package/dist/generators/job/job-generator.js +1099 -0
  77. package/dist/generators/job/schema.d.ts +6 -18
  78. package/dist/generators/job/schema.d.ts.map +1 -1
  79. package/dist/generators/job/schema.js +152 -0
  80. package/dist/generators/query/index.js +1425 -0
  81. package/dist/generators/query/query-generator.d.ts +16 -29
  82. package/dist/generators/query/query-generator.d.ts.map +1 -1
  83. package/dist/generators/query/query-generator.js +1425 -0
  84. package/dist/generators/query/schema.d.ts +11 -23
  85. package/dist/generators/query/schema.d.ts.map +1 -1
  86. package/dist/generators/query/schema.js +115 -0
  87. package/dist/generators/route/index.js +1038 -0
  88. package/dist/generators/route/route-generator.d.ts +11 -20
  89. package/dist/generators/route/route-generator.d.ts.map +1 -1
  90. package/dist/generators/route/route-generator.js +1038 -0
  91. package/dist/generators/route/schema.d.ts +5 -15
  92. package/dist/generators/route/schema.d.ts.map +1 -1
  93. package/dist/generators/route/schema.js +90 -0
  94. package/dist/index.d.ts +2 -10
  95. package/dist/index.d.ts.map +1 -1
  96. package/dist/index.js +1980 -2115
  97. package/dist/plugins/index.d.ts +2 -0
  98. package/dist/plugins/index.d.ts.map +1 -0
  99. package/dist/plugins/wasp.d.ts +3 -0
  100. package/dist/plugins/wasp.d.ts.map +1 -0
  101. package/dist/types/constants.d.ts +4 -22
  102. package/dist/types/constants.d.ts.map +1 -1
  103. package/dist/types/constants.js +8 -2
  104. package/dist/types/index.d.ts +2 -2
  105. package/dist/types/index.d.ts.map +1 -1
  106. package/dist/types/index.js +8 -2
  107. package/dist/wasp-config/app.d.ts +2 -1
  108. package/dist/wasp-config/app.d.ts.map +1 -1
  109. package/dist/wasp-config/app.js +357 -0
  110. package/dist/wasp-config/index.js +357 -0
  111. package/dist/wasp-config/stubs/index.js +48 -0
  112. package/package.json +5 -14
  113. package/dist/common/plugin.d.ts +0 -2
  114. package/dist/common/plugin.d.ts.map +0 -1
  115. package/dist/generators/args.types.d.ts +0 -85
  116. package/dist/generators/args.types.d.ts.map +0 -1
  117. package/dist/generators/base/entity-generator.base.d.ts.map +0 -1
  118. package/dist/generators/feature-directory/feature-directory-generator.d.ts +0 -18
  119. package/dist/generators/feature-directory/feature-directory-generator.d.ts.map +0 -1
  120. package/dist/generators/feature-directory/index.d.ts +0 -2
  121. package/dist/generators/feature-directory/index.d.ts.map +0 -1
  122. package/dist/generators/feature-directory/schema.d.ts +0 -8
  123. package/dist/generators/feature-directory/schema.d.ts.map +0 -1
  124. package/dist/plugin.d.ts +0 -6
  125. package/dist/plugin.d.ts.map +0 -1
  126. /package/dist/generators/{feature-directory → feature}/templates/feature.wasp.eta +0 -0
@@ -0,0 +1,931 @@
1
+ // src/generators/base/component-generator.base.ts
2
+ import {
3
+ hasHelperMethodCall,
4
+ logger as singletonLogger4,
5
+ toCamelCase,
6
+ toKebabCase as toKebabCase2,
7
+ validateFeaturePath as validateFeaturePath3
8
+ } from "@ingenyus/swarm";
9
+ import path6 from "path";
10
+
11
+ // src/common/filesystem.ts
12
+ import { toPascalCase, validateFeaturePath } from "@ingenyus/swarm";
13
+ import fs from "fs";
14
+ import path from "path";
15
+
16
+ // src/types/constants.ts
17
+ var PLUGIN_NAME = "wasp";
18
+ var TYPE_DIRECTORIES = {
19
+ component: "client/components",
20
+ hook: "client/hooks",
21
+ layout: "client/layouts",
22
+ page: "client/pages",
23
+ util: "client/utils",
24
+ action: "server/actions",
25
+ query: "server/queries",
26
+ middleware: "server/middleware",
27
+ job: "server/jobs",
28
+ api: "server/apis",
29
+ crud: "server/cruds",
30
+ type: "types"
31
+ };
32
+
33
+ // src/common/filesystem.ts
34
+ var realFileSystem = {
35
+ readFileSync: fs.readFileSync,
36
+ writeFileSync: fs.writeFileSync,
37
+ existsSync: fs.existsSync,
38
+ copyFileSync: fs.copyFileSync,
39
+ mkdirSync: fs.mkdirSync,
40
+ readdirSync: fs.readdirSync,
41
+ statSync: fs.statSync
42
+ };
43
+ function findWaspRoot(fileSystem, startDir = process.cwd()) {
44
+ const startDirPath = path.resolve(startDir);
45
+ let currentDirPath = startDirPath;
46
+ const root = path.parse(currentDirPath).root;
47
+ while (currentDirPath !== root) {
48
+ const waspRootPath = path.join(currentDirPath, ".wasproot");
49
+ if (fileSystem.existsSync(waspRootPath)) {
50
+ return currentDirPath;
51
+ }
52
+ currentDirPath = path.dirname(currentDirPath);
53
+ }
54
+ throw new Error(
55
+ `Couldn't find Wasp application root from ${startDirPath}. Make sure you are running this command from within a Wasp project directory.`
56
+ );
57
+ }
58
+ function ensureDirectoryExists(fileSystem, dir) {
59
+ if (!fileSystem.existsSync(dir)) {
60
+ fileSystem.mkdirSync(dir, { recursive: true });
61
+ }
62
+ }
63
+ function normaliseFeaturePath(featurePath) {
64
+ const segments = validateFeaturePath(featurePath);
65
+ const normalisedSegments = [];
66
+ for (let i = 0; i < segments.length; i++) {
67
+ const segment = segments[i];
68
+ const previousSegment = normalisedSegments[normalisedSegments.length - 1];
69
+ if (previousSegment !== "features" && segment !== "features") {
70
+ normalisedSegments.push("features");
71
+ }
72
+ normalisedSegments.push(segment);
73
+ }
74
+ return normalisedSegments.join("/");
75
+ }
76
+ function getFeatureDir(fileSystem, featureName) {
77
+ const waspRoot = findWaspRoot(fileSystem);
78
+ const normalisedPath = normaliseFeaturePath(featureName);
79
+ return path.join(waspRoot, "src", normalisedPath);
80
+ }
81
+
82
+ // src/common/prisma.ts
83
+ import {
84
+ getSchema
85
+ } from "@mrleebo/prisma-ast";
86
+ import fs2 from "fs";
87
+ import path2 from "path";
88
+
89
+ // src/common/schemas.ts
90
+ import { commandRegistry } from "@ingenyus/swarm";
91
+ import { z } from "zod";
92
+ var commonSchemas = {
93
+ feature: z.string().min(1, "Feature is required").meta({
94
+ description: "The feature directory this component will be generated in"
95
+ }).register(commandRegistry, {
96
+ shortName: "f",
97
+ examples: ["root", "auth", "dashboard/users"],
98
+ helpText: "Can be nested as a logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
99
+ }),
100
+ name: z.string().min(1, "Name is required").meta({ description: "The name of the generated component" }).register(commandRegistry, {
101
+ shortName: "n",
102
+ examples: ["users", "task"],
103
+ helpText: "Will be used for generated files and configuration entries"
104
+ }),
105
+ target: z.string().min(1, "Target directory is required").meta({ description: "The target path of the generated directory" }).register(commandRegistry, {
106
+ shortName: "t",
107
+ examples: ["dashboard/users", "features/dashboard/features/users"],
108
+ helpText: "A logical or relative path, e.g. 'dashboard/users' or 'features/dashboard/features/users'"
109
+ }),
110
+ path: z.string().min(1, "Path is required").meta({ description: "The path that this component will be accessible at" }).register(commandRegistry, {
111
+ shortName: "p",
112
+ examples: ["/api/users/:id", "/api/products"],
113
+ helpText: "Supports Express-style placeholders, e.g. '/api/users/:id'"
114
+ }),
115
+ dataType: z.string().min(1, "Data type is required").meta({ description: "The data type/model name for this operation" }).register(commandRegistry, {
116
+ shortName: "d",
117
+ examples: ["User", "Product", "Task"],
118
+ helpText: "The Wasp entity or model name this operation will interact with"
119
+ }),
120
+ entities: z.array(z.string()).optional().meta({
121
+ description: "The Wasp entities that will be available to this component (optional)"
122
+ }).register(commandRegistry, {
123
+ shortName: "e",
124
+ examples: ["User", "User Task"],
125
+ helpText: "An array of Wasp entity names"
126
+ }),
127
+ force: z.boolean().optional().meta({
128
+ description: "Force overwrite of existing files and configuration entries (optional)"
129
+ }).register(commandRegistry, {
130
+ shortName: "F",
131
+ helpText: "CAUTION: Will overwrite existing files and configuration entries with current parameters"
132
+ }),
133
+ auth: z.boolean().optional().meta({
134
+ description: "Require authentication for this component (optional)"
135
+ }).register(commandRegistry, {
136
+ shortName: "a",
137
+ helpText: "Will generate authentication checks"
138
+ })
139
+ };
140
+
141
+ // src/common/templates.ts
142
+ import { toKebabCase } from "@ingenyus/swarm";
143
+ import { Eta } from "eta";
144
+ import path3 from "path";
145
+ var TemplateUtility = class {
146
+ constructor(fileSystem) {
147
+ this.fileSystem = fileSystem;
148
+ }
149
+ processTemplate(templatePath, replacements) {
150
+ const declarations = Object.keys(replacements).map((key) => `${key}=it.${key}`).join(", ");
151
+ const functionHeader = declarations ? `const ${declarations};` : void 0;
152
+ const templateDir = path3.dirname(templatePath);
153
+ const eta = new Eta({
154
+ autoTrim: false,
155
+ autoEscape: false,
156
+ views: templateDir,
157
+ functionHeader
158
+ });
159
+ const templateName = path3.basename(templatePath).replace(/\.eta$/, "");
160
+ if (this.fileSystem.existsSync(templatePath)) {
161
+ return eta.render(templateName, replacements);
162
+ } else {
163
+ const template = this.fileSystem.readFileSync(templatePath, "utf8");
164
+ return eta.renderString(template, replacements);
165
+ }
166
+ }
167
+ /**
168
+ * Helper method to resolve template paths for concrete generators
169
+ * @param relativePath - The relative path to the template file
170
+ * @param generatorName - The name of the generator (e.g., 'api', 'job')
171
+ * @param currentFileUrl - The import.meta.url from the concrete generator class
172
+ * @returns The full path to the template file
173
+ */
174
+ resolveTemplatePath(relativePath, generatorName, currentFileUrl) {
175
+ const generatorDirName = toKebabCase(generatorName);
176
+ const currentFilePath = new URL(currentFileUrl).pathname;
177
+ const currentFileDir = path3.dirname(currentFilePath);
178
+ const currentFileName = path3.basename(currentFilePath);
179
+ const isInstalledPackage = currentFileDir.includes("node_modules") && currentFileDir.endsWith("/dist") && currentFileName === "index.js";
180
+ const startDir = isInstalledPackage ? currentFileDir : path3.dirname(path3.dirname(currentFileDir));
181
+ return path3.join(
182
+ startDir,
183
+ "generators",
184
+ generatorDirName,
185
+ "templates",
186
+ relativePath
187
+ );
188
+ }
189
+ };
190
+
191
+ // src/generators/feature/feature-generator.ts
192
+ import {
193
+ handleFatalError as handleFatalError2,
194
+ logger as singletonLogger3,
195
+ validateFeaturePath as validateFeaturePath2
196
+ } from "@ingenyus/swarm";
197
+ import path5 from "path";
198
+
199
+ // src/generators/base/wasp-generator.base.ts
200
+ import {
201
+ GeneratorBase,
202
+ logger as singletonLogger2,
203
+ SwarmConfigManager,
204
+ TemplateResolver
205
+ } from "@ingenyus/swarm";
206
+
207
+ // src/generators/config/wasp-config-generator.ts
208
+ import {
209
+ handleFatalError,
210
+ parseHelperMethodDefinition,
211
+ logger as singletonLogger
212
+ } from "@ingenyus/swarm";
213
+ import path4 from "path";
214
+ var WaspConfigGenerator = class {
215
+ constructor(logger = singletonLogger, fileSystem = realFileSystem) {
216
+ this.logger = logger;
217
+ this.fileSystem = fileSystem;
218
+ this.templateUtility = new TemplateUtility(fileSystem);
219
+ }
220
+ path = path4;
221
+ templateUtility;
222
+ /**
223
+ * Gets the template path for feature config templates.
224
+ * Feature config templates are located in the feature generator's templates directory.
225
+ * @param templateName - The name of the template file (e.g., 'feature.wasp.eta')
226
+ * @returns The full path to the template file
227
+ */
228
+ getTemplatePath(templateName) {
229
+ return this.templateUtility.resolveTemplatePath(
230
+ templateName,
231
+ "feature",
232
+ import.meta.url
233
+ );
234
+ }
235
+ /**
236
+ * Generate a TypeScript Wasp config file in a feature directory
237
+ * @param featurePath - The feature directory path
238
+ */
239
+ generate(featurePath) {
240
+ const featureDir = getFeatureDir(this.fileSystem, featurePath);
241
+ if (!this.fileSystem.existsSync(featureDir)) {
242
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
243
+ }
244
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
245
+ if (!this.fileSystem.existsSync(templatePath)) {
246
+ this.logger.error(`Template not found: ${templatePath}`);
247
+ return;
248
+ }
249
+ const configFilePath = path4.join(featureDir, `feature.wasp.ts`);
250
+ if (this.fileSystem.existsSync(configFilePath)) {
251
+ this.logger.warn(`Feature config already exists: ${configFilePath}`);
252
+ return;
253
+ }
254
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
255
+ this.logger.success(`Generated feature config: ${configFilePath}`);
256
+ }
257
+ /**
258
+ * Updates or creates a feature configuration file with a pre-built declaration.
259
+ * @param featurePath - The path to the feature
260
+ * @param declaration - The pre-built declaration string to add or update
261
+ * @returns The updated feature configuration file
262
+ */
263
+ update(featurePath, declaration) {
264
+ const configDir = getFeatureDir(this.fileSystem, featurePath);
265
+ const configFilePath = path4.join(configDir, `feature.wasp.ts`);
266
+ if (!this.fileSystem.existsSync(configFilePath)) {
267
+ const templatePath = this.getTemplatePath("feature.wasp.eta");
268
+ if (!this.fileSystem.existsSync(templatePath)) {
269
+ handleFatalError(`Feature config template not found: ${templatePath}`);
270
+ }
271
+ this.fileSystem.copyFileSync(templatePath, configFilePath);
272
+ }
273
+ let content = this.fileSystem.readFileSync(configFilePath, "utf8");
274
+ content = this.normaliseSemicolons(content);
275
+ const parsed = parseHelperMethodDefinition(declaration);
276
+ if (!parsed) {
277
+ handleFatalError(`Could not parse definition: ${declaration}`);
278
+ return content;
279
+ }
280
+ const { methodName } = parsed;
281
+ const hadExistingDefinitions = this.hasExistingDefinitions(
282
+ content,
283
+ methodName
284
+ );
285
+ content = this.removeExistingDefinition(content, declaration);
286
+ const hasExistingDefinitions = this.hasExistingDefinitions(
287
+ content,
288
+ methodName
289
+ );
290
+ const lines = content.split("\n");
291
+ const configureFunctionStart = lines.findIndex(
292
+ (line) => line.trim().startsWith("export default function")
293
+ );
294
+ if (configureFunctionStart === -1) {
295
+ handleFatalError("Could not find configure function in feature config");
296
+ }
297
+ const appLineIndex = lines.findIndex(
298
+ (line, index) => index > configureFunctionStart && line.trim() === "app"
299
+ );
300
+ if (appLineIndex === -1) {
301
+ const insertIndex = configureFunctionStart + 1;
302
+ const itemsToInsert = [" app"];
303
+ const comment = this.getMethodComment(methodName);
304
+ itemsToInsert.push(` ${comment}`);
305
+ itemsToInsert.push(declaration.trimEnd());
306
+ lines.splice(insertIndex, 0, ...itemsToInsert);
307
+ } else {
308
+ const { insertIndex, addComment } = this.findGroupInsertionPoint(
309
+ lines,
310
+ methodName,
311
+ declaration,
312
+ hadExistingDefinitions || hasExistingDefinitions
313
+ );
314
+ const newLines = this.insertWithSpacing(
315
+ lines,
316
+ declaration,
317
+ insertIndex,
318
+ methodName,
319
+ addComment
320
+ );
321
+ const normalisedContent2 = this.normaliseSemicolons(newLines.join("\n"));
322
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent2);
323
+ return configFilePath;
324
+ }
325
+ const normalisedContent = this.normaliseSemicolons(lines.join("\n"));
326
+ this.fileSystem.writeFileSync(configFilePath, normalisedContent);
327
+ return configFilePath;
328
+ }
329
+ /**
330
+ * Determines the insertion index for a method name based on alphabetical ordering
331
+ * of existing groups in the configuration file.
332
+ * @param groups - Object containing existing method groups
333
+ * @param methodName - The method name to find insertion index for
334
+ * @returns The insertion index for the method name
335
+ */
336
+ getInsertionIndexForMethod(groups, methodName) {
337
+ const existingMethods = Object.keys(groups).filter(
338
+ (method) => groups[method].length > 0
339
+ );
340
+ const allMethods = [...existingMethods, methodName].sort();
341
+ return allMethods.indexOf(methodName);
342
+ }
343
+ /**
344
+ * Gets the comment text for a method type.
345
+ * @param methodName The method name (e.g., 'addApi')
346
+ * @returns The comment text for the method type
347
+ */
348
+ getMethodComment(methodName) {
349
+ const entityName = methodName.startsWith("add") ? methodName.slice(3) : methodName;
350
+ return `// ${entityName} definitions`;
351
+ }
352
+ /**
353
+ * Finds the correct insertion point for a new configuration item.
354
+ * @param lines - Array of file lines
355
+ * @param methodName - The method name (e.g., 'addApi')
356
+ * @param definition - The definition string to parse for item name
357
+ * @returns Object with insertion index and whether to add a comment
358
+ */
359
+ findGroupInsertionPoint(lines, methodName, definition, hasExistingDefinitionsOfType) {
360
+ const appLineIndex = lines.findIndex((line) => line.trim() === "app");
361
+ if (appLineIndex === -1) {
362
+ return { insertIndex: appLineIndex + 1, addComment: false };
363
+ }
364
+ const methodCalls = [];
365
+ for (let i = appLineIndex + 1; i < lines.length; i++) {
366
+ const line = lines[i].trim();
367
+ if (line.startsWith(".") && line.includes("(")) {
368
+ let methodCallContent = line;
369
+ let j = i;
370
+ let closingParenCount = 0;
371
+ let foundClosingParen = false;
372
+ for (let k = 0; k < methodCallContent.length; k++) {
373
+ if (methodCallContent[k] === "(") closingParenCount++;
374
+ if (methodCallContent[k] === ")") closingParenCount--;
375
+ if (closingParenCount === 0 && methodCallContent[k] === ")") {
376
+ foundClosingParen = true;
377
+ break;
378
+ }
379
+ }
380
+ while (!foundClosingParen && j < lines.length - 1) {
381
+ j++;
382
+ methodCallContent += " " + lines[j].trim();
383
+ for (let k = 0; k < lines[j].length; k++) {
384
+ if (lines[j][k] === "(") closingParenCount++;
385
+ if (lines[j][k] === ")") closingParenCount--;
386
+ if (closingParenCount === 0 && lines[j][k] === ")") {
387
+ foundClosingParen = true;
388
+ break;
389
+ }
390
+ }
391
+ }
392
+ const match = methodCallContent.match(
393
+ /\.(\w+)\([^,]+,\s*['"`]([^'"`]+)['"`]/
394
+ );
395
+ if (match) {
396
+ methodCalls.push({
397
+ lineIndex: i,
398
+ endLineIndex: j,
399
+ methodName: match[1],
400
+ itemName: match[2]
401
+ });
402
+ }
403
+ }
404
+ }
405
+ const groups = {};
406
+ methodCalls.forEach((call) => {
407
+ if (!groups[call.methodName]) {
408
+ groups[call.methodName] = [];
409
+ }
410
+ groups[call.methodName].push({
411
+ lineIndex: call.lineIndex,
412
+ endLineIndex: call.endLineIndex,
413
+ itemName: call.itemName
414
+ });
415
+ });
416
+ const targetGroup = groups[methodName] || [];
417
+ if (targetGroup.length === 0) {
418
+ const targetGroupIndex = this.getInsertionIndexForMethod(
419
+ groups,
420
+ methodName
421
+ );
422
+ const existingMethods = Object.keys(groups).filter((method) => groups[method].length > 0).sort();
423
+ for (let i = targetGroupIndex; i < existingMethods.length; i++) {
424
+ const groupMethod = existingMethods[i];
425
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
426
+ const firstItem = groups[groupMethod][0];
427
+ let insertIndex = firstItem.lineIndex;
428
+ for (let j = firstItem.lineIndex - 1; j > appLineIndex; j--) {
429
+ const line = lines[j].trim();
430
+ if (line.startsWith("//") && line.includes("definitions")) {
431
+ insertIndex = j;
432
+ break;
433
+ } else if (line.startsWith(".") || line === "") {
434
+ continue;
435
+ } else {
436
+ break;
437
+ }
438
+ }
439
+ return { insertIndex, addComment: !hasExistingDefinitionsOfType };
440
+ }
441
+ }
442
+ for (let i = targetGroupIndex - 1; i >= 0; i--) {
443
+ const groupMethod = existingMethods[i];
444
+ if (groups[groupMethod] && groups[groupMethod].length > 0) {
445
+ const lastItem2 = groups[groupMethod][groups[groupMethod].length - 1];
446
+ return {
447
+ insertIndex: lastItem2.endLineIndex + 1,
448
+ addComment: !hasExistingDefinitionsOfType
449
+ };
450
+ }
451
+ }
452
+ return {
453
+ insertIndex: appLineIndex + 1,
454
+ addComment: !hasExistingDefinitionsOfType
455
+ };
456
+ }
457
+ const parsed = parseHelperMethodDefinition(definition);
458
+ if (!parsed) {
459
+ return { insertIndex: appLineIndex + 1, addComment: false };
460
+ }
461
+ const { firstParam: itemName } = parsed;
462
+ for (let i = 0; i < targetGroup.length; i++) {
463
+ if (itemName.localeCompare(targetGroup[i].itemName) < 0) {
464
+ return { insertIndex: targetGroup[i].lineIndex, addComment: false };
465
+ }
466
+ }
467
+ const lastItem = targetGroup[targetGroup.length - 1];
468
+ return { insertIndex: lastItem.endLineIndex + 1, addComment: false };
469
+ }
470
+ /**
471
+ * Inserts a definition with optional comment header.
472
+ * @param lines - Array of file lines
473
+ * @param declaration - The declaration to insert
474
+ * @param insertIndex - The index where to insert
475
+ * @param methodName - The method name for comment generation
476
+ * @param addComment - Whether to add a comment before the declaration
477
+ * @returns The modified lines array
478
+ */
479
+ insertWithSpacing(lines, declaration, insertIndex, methodName, addComment = false) {
480
+ const newLines = [...lines];
481
+ if (addComment) {
482
+ const comment = this.getMethodComment(methodName);
483
+ newLines.splice(insertIndex, 0, ` ${comment}`);
484
+ insertIndex += 1;
485
+ }
486
+ newLines.splice(insertIndex, 0, declaration.trimEnd());
487
+ return newLines;
488
+ }
489
+ /**
490
+ * Checks if there are any existing definitions of a specific type in the content.
491
+ * @param content - The file content to search
492
+ * @param methodName - The method name to check for (e.g., 'addJob', 'addApi')
493
+ * @returns true if there are existing definitions of this type, false otherwise
494
+ */
495
+ hasExistingDefinitions(content, methodName) {
496
+ const lines = content.split("\n");
497
+ for (const line of lines) {
498
+ if (line.trim().startsWith(`.${methodName}(`)) {
499
+ return true;
500
+ }
501
+ }
502
+ return false;
503
+ }
504
+ /**
505
+ * Removes an existing definition from the content by finding the helper method call
506
+ * and removing the entire method call block.
507
+ * @param content - The file content
508
+ * @param definition - The new definition to find the existing one from
509
+ * @returns The content with the existing definition removed
510
+ */
511
+ removeExistingDefinition(content, definition) {
512
+ const parsed = parseHelperMethodDefinition(definition);
513
+ if (!parsed) {
514
+ return content;
515
+ }
516
+ const { methodName, firstParam } = parsed;
517
+ let contentLines = content.split("\n");
518
+ let openingLineIndex = -1;
519
+ for (let i = 0; i < contentLines.length; i++) {
520
+ const line = contentLines[i];
521
+ if (line.trim().startsWith(`.${methodName}(`)) {
522
+ if (firstParam && line.includes(firstParam)) {
523
+ openingLineIndex = i;
524
+ break;
525
+ }
526
+ }
527
+ }
528
+ if (openingLineIndex === -1) {
529
+ return content;
530
+ }
531
+ let closingLineIndex = -1;
532
+ let parenCount = 0;
533
+ let braceCount = 0;
534
+ let foundOpening = false;
535
+ for (let i = openingLineIndex; i < contentLines.length; i++) {
536
+ const line = contentLines[i];
537
+ for (const char of line) {
538
+ if (char === "(") {
539
+ parenCount++;
540
+ foundOpening = true;
541
+ } else if (char === ")") {
542
+ parenCount--;
543
+ if (foundOpening && parenCount === 0 && braceCount === 0) {
544
+ closingLineIndex = i;
545
+ break;
546
+ }
547
+ } else if (char === "{") {
548
+ braceCount++;
549
+ } else if (char === "}") {
550
+ braceCount--;
551
+ }
552
+ }
553
+ if (closingLineIndex !== -1) {
554
+ break;
555
+ }
556
+ }
557
+ if (closingLineIndex === -1) {
558
+ this.logger.warn(
559
+ "Could not find closing parenthesis for existing definition"
560
+ );
561
+ return content;
562
+ }
563
+ contentLines.splice(
564
+ openingLineIndex,
565
+ closingLineIndex - openingLineIndex + 1
566
+ );
567
+ return contentLines.join("\n");
568
+ }
569
+ /**
570
+ * Adds a definition to the content by finding the appropriate place to insert it.
571
+ * @param content - The current file content
572
+ * @param definition - The definition to add
573
+ * @returns The updated content with the new definition
574
+ */
575
+ addDefinitionToContent(content, definition) {
576
+ const lines = content.split("\n");
577
+ const lastLineIndex = lines.length - 1;
578
+ let insertIndex = lastLineIndex;
579
+ for (let i = lastLineIndex; i >= 0; i--) {
580
+ const line = lines[i].trim();
581
+ if (line && !line.startsWith("}")) {
582
+ insertIndex = i;
583
+ break;
584
+ }
585
+ }
586
+ lines.splice(insertIndex + 1, 0, ` ${definition}`);
587
+ return lines.join("\n");
588
+ }
589
+ /**
590
+ * Normalises semicolons in the config file by removing them from method chain calls
591
+ * while preserving them in other contexts (imports, declarations, etc.).
592
+ * @param content - The file content to normalise
593
+ * @returns The normalised content
594
+ */
595
+ normaliseSemicolons(content) {
596
+ const lines = content.split("\n");
597
+ const configureFunctionStart = lines.findIndex(
598
+ (line) => line.trim().startsWith("export default function")
599
+ );
600
+ if (configureFunctionStart === -1) {
601
+ return content;
602
+ }
603
+ const appLineIndex = lines.findIndex(
604
+ (line, index) => index > configureFunctionStart && line.trim().startsWith("app")
605
+ );
606
+ if (appLineIndex === -1) {
607
+ return content;
608
+ }
609
+ let braceCount = 0;
610
+ let functionEndIndex = lines.length - 1;
611
+ for (let i = configureFunctionStart; i < lines.length; i++) {
612
+ const line = lines[i];
613
+ for (const char of line) {
614
+ if (char === "{") braceCount++;
615
+ if (char === "}") {
616
+ braceCount--;
617
+ if (braceCount === 0) {
618
+ functionEndIndex = i;
619
+ break;
620
+ }
621
+ }
622
+ }
623
+ if (braceCount === 0 && i > configureFunctionStart) {
624
+ break;
625
+ }
626
+ }
627
+ let lastMethodCallIndex = -1;
628
+ for (let i = appLineIndex + 1; i < functionEndIndex; i++) {
629
+ const line = lines[i];
630
+ const trimmed = line.trim();
631
+ if ((trimmed.endsWith(")") || trimmed.endsWith(");")) && !trimmed.startsWith("//")) {
632
+ lines[i] = line.replace(/;\s*$/, "");
633
+ lastMethodCallIndex = i;
634
+ }
635
+ }
636
+ if (lastMethodCallIndex !== -1 && !lines[lastMethodCallIndex].trim().endsWith(";")) {
637
+ lines[lastMethodCallIndex] = lines[lastMethodCallIndex] + ";";
638
+ }
639
+ return lines.join("\n");
640
+ }
641
+ };
642
+
643
+ // src/generators/base/wasp-generator.base.ts
644
+ var WaspGeneratorBase = class extends GeneratorBase {
645
+ constructor(fileSystem = realFileSystem, logger = singletonLogger2) {
646
+ super(fileSystem, logger);
647
+ this.fileSystem = fileSystem;
648
+ this.logger = logger;
649
+ this.configGenerator = new WaspConfigGenerator(logger, fileSystem);
650
+ this.templateUtility = new TemplateUtility(fileSystem);
651
+ this.templateResolver = new TemplateResolver(fileSystem);
652
+ }
653
+ configGenerator;
654
+ templateUtility;
655
+ templateResolver;
656
+ swarmConfig;
657
+ configLoaded = false;
658
+ // Plugin name from swarm.config.json
659
+ pluginName = PLUGIN_NAME;
660
+ async loadSwarmConfig() {
661
+ if (this.configLoaded) return;
662
+ const configManager = new SwarmConfigManager();
663
+ this.swarmConfig = await configManager.loadConfig();
664
+ this.configLoaded = true;
665
+ }
666
+ async getCustomTemplateDir() {
667
+ await this.loadSwarmConfig();
668
+ return this.swarmConfig?.templateDirectory;
669
+ }
670
+ /**
671
+ * Resolves template path with override support
672
+ */
673
+ async getTemplatePath(templateName) {
674
+ const defaultPath = this.getDefaultTemplatePath(templateName);
675
+ const customPath = await this.getCustomTemplateDir();
676
+ if (!customPath) {
677
+ return defaultPath;
678
+ }
679
+ const { path: resolvedPath, isCustom } = this.templateResolver.resolveTemplatePath(
680
+ this.pluginName,
681
+ this.name,
682
+ templateName,
683
+ defaultPath,
684
+ customPath
685
+ );
686
+ if (isCustom) {
687
+ this.logger.info(`Using custom template: ${resolvedPath}`);
688
+ }
689
+ return resolvedPath;
690
+ }
691
+ /**
692
+ * Processes a template and writes the result to a file
693
+ */
694
+ async renderTemplateToFile(templateName, replacements, outputPath, readableFileType, force) {
695
+ const templatePath = await this.getTemplatePath(templateName);
696
+ const fileExists = this.checkFileExists(
697
+ outputPath,
698
+ force,
699
+ readableFileType
700
+ );
701
+ const content = this.templateUtility.processTemplate(
702
+ templatePath,
703
+ replacements
704
+ );
705
+ this.writeFile(outputPath, content, readableFileType, fileExists);
706
+ return fileExists;
707
+ }
708
+ /**
709
+ * Generic existence check with force flag handling
710
+ * Consolidates the pattern used in both file and config checks
711
+ */
712
+ checkExistence(exists, itemDescription, force, errorMessage) {
713
+ if (exists && !force) {
714
+ this.logger.error(`${itemDescription}. Use --force to overwrite`);
715
+ throw new Error(errorMessage || itemDescription);
716
+ }
717
+ return exists;
718
+ }
719
+ /**
720
+ * Checks if a file exists and handles force flag logic
721
+ */
722
+ checkFileExists(filePath, force, fileType) {
723
+ const fileExists = this.fileSystem.existsSync(filePath);
724
+ return this.checkExistence(
725
+ fileExists,
726
+ `${fileType} already exists: ${filePath}`,
727
+ force,
728
+ `${fileType} already exists`
729
+ );
730
+ }
731
+ /**
732
+ * Safely writes a file with proper error handling and logging
733
+ */
734
+ writeFile(filePath, content, fileType, fileExists) {
735
+ this.fileSystem.writeFileSync(filePath, content);
736
+ this.logger.success(
737
+ `${fileExists ? "Overwrote" : "Generated"} ${fileType}: ${filePath}`
738
+ );
739
+ }
740
+ };
741
+
742
+ // src/generators/feature/schema.ts
743
+ import { z as z2 } from "zod";
744
+ var schema = z2.object({
745
+ target: commonSchemas.target
746
+ });
747
+
748
+ // src/generators/feature/feature-generator.ts
749
+ var FeatureGenerator = class extends WaspGeneratorBase {
750
+ constructor(logger = singletonLogger3, fileSystem = realFileSystem) {
751
+ super(fileSystem, logger);
752
+ this.logger = logger;
753
+ this.fileSystem = fileSystem;
754
+ this.name = "feature";
755
+ this.description = "Generates a feature directory containing a Wasp configuration file";
756
+ }
757
+ name;
758
+ description;
759
+ schema = schema;
760
+ getDefaultTemplatePath(templateName) {
761
+ return this.templateUtility.resolveTemplatePath(
762
+ templateName,
763
+ this.name,
764
+ import.meta.url
765
+ );
766
+ }
767
+ /**
768
+ * Generates a feature directory containing a Wasp configuration file
769
+ * @param target - The target path of the generated directory
770
+ */
771
+ async generate(args) {
772
+ const { target } = args;
773
+ const segments = validateFeaturePath2(target);
774
+ const normalisedPath = normaliseFeaturePath(target);
775
+ const sourceRoot = path5.join(findWaspRoot(this.fileSystem), "src");
776
+ if (segments.length > 1) {
777
+ const parentPath = segments.slice(0, -1).join("/");
778
+ const parentNormalisedPath = normaliseFeaturePath(parentPath);
779
+ const parentFeatureDir = path5.join(sourceRoot, parentNormalisedPath);
780
+ if (!this.fileSystem.existsSync(parentFeatureDir)) {
781
+ handleFatalError2(
782
+ `Parent feature '${parentPath}' does not exist. Please create it first.`
783
+ );
784
+ }
785
+ }
786
+ const featureDir = path5.join(sourceRoot, normalisedPath);
787
+ this.fileSystem.mkdirSync(featureDir, { recursive: true });
788
+ this.configGenerator.generate(normalisedPath);
789
+ this.logger.success(`Generated feature: ${normalisedPath}`);
790
+ }
791
+ };
792
+
793
+ // src/generators/base/component-generator.base.ts
794
+ var ComponentGeneratorBase = class extends WaspGeneratorBase {
795
+ constructor(logger = singletonLogger4, fileSystem = realFileSystem, featureDirectoryGenerator = new FeatureGenerator(logger, fileSystem)) {
796
+ super(fileSystem, logger);
797
+ this.logger = logger;
798
+ this.fileSystem = fileSystem;
799
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
800
+ this.featureDirectoryGenerator = featureDirectoryGenerator;
801
+ }
802
+ getDefaultTemplatePath(templateName) {
803
+ return this.templateUtility.resolveTemplatePath(
804
+ templateName,
805
+ this.name,
806
+ import.meta.url
807
+ );
808
+ }
809
+ get name() {
810
+ return toKebabCase2(this.componentType);
811
+ }
812
+ /**
813
+ * Validates that the feature config file exists in the target or ancestor directories
814
+ */
815
+ validateFeatureConfig(featurePath) {
816
+ const normalisedPath = normaliseFeaturePath(featurePath);
817
+ const segments = normalisedPath.split("/");
818
+ for (let i = segments.length; i > 0; i--) {
819
+ const pathSegments = segments.slice(0, i);
820
+ const currentPath = pathSegments.join("/");
821
+ const featureName = pathSegments[pathSegments.length - 1];
822
+ const featureDir = getFeatureDir(this.fileSystem, currentPath);
823
+ const configPath = path6.join(featureDir, `feature.wasp.ts`);
824
+ if (this.fileSystem.existsSync(configPath)) {
825
+ return configPath;
826
+ }
827
+ }
828
+ this.logger.error(
829
+ `Feature config file not found in '${normalisedPath}' or any ancestor directories`
830
+ );
831
+ this.logger.error(
832
+ `Expected to find a feature.wasp.ts config file in one of the feature directories`
833
+ );
834
+ throw new Error("Feature config file not found");
835
+ }
836
+ /**
837
+ * Checks if a config item already exists in the feature config
838
+ */
839
+ checkConfigExists(configPath, methodName, itemName, force) {
840
+ const configContent = this.fileSystem.readFileSync(configPath, "utf8");
841
+ const configExists = hasHelperMethodCall(
842
+ configContent,
843
+ methodName,
844
+ itemName
845
+ );
846
+ return this.checkExistence(
847
+ configExists,
848
+ `${methodName} config already exists in ${configPath}`,
849
+ force,
850
+ `${methodName} config already exists`
851
+ );
852
+ }
853
+ /**
854
+ * Updates the feature config with a new definition
855
+ */
856
+ updateFeatureConfig(featurePath, definition, configPath, configExists, methodName) {
857
+ this.configGenerator.update(featurePath, definition);
858
+ this.logger.success(
859
+ `${configExists ? "Updated" : "Added"} ${methodName} config in: ${configPath}`
860
+ );
861
+ }
862
+ /**
863
+ * Consolidated helper for updating config files with existence check
864
+ * This replaces the duplicated updateConfigFile pattern in concrete generators
865
+ */
866
+ updateConfigWithCheck(configPath, methodName, entityName, definition, featurePath, force) {
867
+ const configExists = this.checkConfigExists(
868
+ configPath,
869
+ methodName,
870
+ entityName,
871
+ force
872
+ );
873
+ if (!configExists || force) {
874
+ this.updateFeatureConfig(
875
+ featurePath,
876
+ definition,
877
+ configPath,
878
+ configExists,
879
+ methodName
880
+ );
881
+ }
882
+ }
883
+ /**
884
+ * Gets the appropriate directory for a feature based on its path.
885
+ * @param fileSystem - The filesystem abstraction
886
+ * @param featurePath - The full feature path
887
+ * @param type - The type of file being generated
888
+ * @returns The target directory and import path
889
+ */
890
+ getFeatureTargetDir(fileSystem, featurePath, type) {
891
+ validateFeaturePath3(featurePath);
892
+ const normalisedPath = normaliseFeaturePath(featurePath);
893
+ const featureDir = getFeatureDir(fileSystem, normalisedPath);
894
+ const typeKey = type.toLowerCase();
895
+ const typeDirectory = TYPE_DIRECTORIES[typeKey];
896
+ const targetDirectory = path6.join(featureDir, typeDirectory);
897
+ const importDirectory = `@src/${normalisedPath}/${typeDirectory}`;
898
+ return { targetDirectory, importDirectory };
899
+ }
900
+ /**
901
+ * Ensures a target directory exists and returns its path
902
+ */
903
+ ensureTargetDirectory(featurePath, type) {
904
+ const { targetDirectory, importDirectory } = this.getFeatureTargetDir(
905
+ this.fileSystem,
906
+ featurePath,
907
+ type
908
+ );
909
+ ensureDirectoryExists(this.fileSystem, targetDirectory);
910
+ return { targetDirectory, importDirectory };
911
+ }
912
+ /**
913
+ * Generate middleware file for API or API namespace
914
+ */
915
+ async generateMiddlewareFile(targetFile, name, force) {
916
+ const replacements = {
917
+ name,
918
+ middlewareType: toCamelCase(this.componentType || "")
919
+ };
920
+ await this.renderTemplateToFile(
921
+ "middleware.eta",
922
+ replacements,
923
+ targetFile,
924
+ "Middleware file",
925
+ force
926
+ );
927
+ }
928
+ };
929
+ export {
930
+ ComponentGeneratorBase
931
+ };