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