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