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