agentlang 0.0.17 → 0.0.19

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 (55) hide show
  1. package/out/cli/main.d.ts.map +1 -1
  2. package/out/cli/main.js +17 -6
  3. package/out/cli/main.js.map +1 -1
  4. package/out/extension/main.cjs +250 -250
  5. package/out/extension/main.cjs.map +2 -2
  6. package/out/language/main.cjs +502 -502
  7. package/out/language/main.cjs.map +2 -2
  8. package/out/language/parser.d.ts +1 -0
  9. package/out/language/parser.d.ts.map +1 -1
  10. package/out/language/parser.js +25 -9
  11. package/out/language/parser.js.map +1 -1
  12. package/out/runtime/agents/impl/anthropic.d.ts +54 -0
  13. package/out/runtime/agents/impl/anthropic.d.ts.map +1 -1
  14. package/out/runtime/agents/impl/anthropic.js +109 -3
  15. package/out/runtime/agents/impl/anthropic.js.map +1 -1
  16. package/out/runtime/auth/cognito.d.ts +3 -1
  17. package/out/runtime/auth/cognito.d.ts.map +1 -1
  18. package/out/runtime/auth/cognito.js +42 -2
  19. package/out/runtime/auth/cognito.js.map +1 -1
  20. package/out/runtime/auth/interface.d.ts +2 -0
  21. package/out/runtime/auth/interface.d.ts.map +1 -1
  22. package/out/runtime/interpreter.js +39 -23
  23. package/out/runtime/interpreter.js.map +1 -1
  24. package/out/runtime/jsmodules.js +1 -1
  25. package/out/runtime/jsmodules.js.map +1 -1
  26. package/out/runtime/loader.d.ts.map +1 -1
  27. package/out/runtime/loader.js +17 -30
  28. package/out/runtime/loader.js.map +1 -1
  29. package/out/runtime/modules/ai.d.ts.map +1 -1
  30. package/out/runtime/modules/ai.js +6 -1
  31. package/out/runtime/modules/ai.js.map +1 -1
  32. package/out/runtime/modules/auth.d.ts +5 -3
  33. package/out/runtime/modules/auth.d.ts.map +1 -1
  34. package/out/runtime/modules/auth.js +42 -2
  35. package/out/runtime/modules/auth.js.map +1 -1
  36. package/package.json +2 -2
  37. package/src/cli/main.ts +15 -6
  38. package/src/language/parser.ts +30 -9
  39. package/src/runtime/agents/impl/anthropic.ts +190 -4
  40. package/src/runtime/auth/cognito.ts +49 -2
  41. package/src/runtime/auth/interface.ts +7 -0
  42. package/src/runtime/interpreter.ts +39 -23
  43. package/src/runtime/jsmodules.ts +1 -1
  44. package/src/runtime/loader.ts +18 -35
  45. package/src/runtime/modules/ai.ts +6 -2
  46. package/src/runtime/modules/auth.ts +51 -6
  47. package/out/cli/docs.d.ts +0 -2
  48. package/out/cli/docs.d.ts.map +0 -1
  49. package/out/cli/docs.js +0 -236
  50. package/out/cli/docs.js.map +0 -1
  51. package/out/cli/openapi-docs.yml +0 -695
  52. package/out/index.d.ts +0 -19
  53. package/out/index.d.ts.map +0 -1
  54. package/out/index.js +0 -25
  55. package/out/index.js.map +0 -1
@@ -35,6 +35,8 @@ let fromEnv: any = undefined;
35
35
  let CognitoIdentityProviderClient: any = undefined;
36
36
  let SignUpCommand: any = undefined;
37
37
  let ConfirmSignUp: any = undefined;
38
+ let ForgotPasswordCommand: any = undefined;
39
+ let ConfirmForgotPasswordCommand: any = undefined;
38
40
  let AdminGetUserCommand: any = undefined;
39
41
  let InitiateAuthCommand: any = undefined;
40
42
  let AuthenticationDetails: any = undefined;
@@ -53,6 +55,8 @@ if (isNodeEnv) {
53
55
  CognitoIdentityProviderClient = cip.CognitoIdentityProviderClient;
54
56
  SignUpCommand = cip.SignUpCommand;
55
57
  ConfirmSignUp = cip.ConfirmSignUpCommand;
58
+ ForgotPasswordCommand = cip.ForgotPasswordCommand;
59
+ ConfirmForgotPasswordCommand = cip.ConfirmForgotPasswordCommand;
56
60
  AdminGetUserCommand = cip.AdminGetUserCommand;
57
61
  InitiateAuthCommand = cip.InitiateAuthCommand;
58
62
 
@@ -396,7 +400,7 @@ export class CognitoAuth implements AgentlangAuth {
396
400
  }
397
401
  }
398
402
 
399
- async confirmSignup(username: string, confirmationCode: string, env: Environment): Promise<void> {
403
+ async confirmSignup(username: string, confirmationCode: string, _: Environment): Promise<void> {
400
404
  try {
401
405
  const client = new CognitoIdentityProviderClient({
402
406
  region: process.env.AWS_REGION || 'us-west-2',
@@ -410,7 +414,50 @@ export class CognitoAuth implements AgentlangAuth {
410
414
  await client.send(command);
411
415
  } catch (error: any) {
412
416
  logger.error(`Failed to confirm signup: ${error.message}`);
413
- throw error;
417
+ handleCognitoError(error, 'confirmSignup');
418
+ }
419
+ }
420
+
421
+ async forgotPassword(username: string, _env: Environment): Promise<void> {
422
+ try {
423
+ const client = new CognitoIdentityProviderClient({
424
+ region: process.env.AWS_REGION || 'us-west-2',
425
+ credentials: fromEnv(),
426
+ });
427
+ const command = new ForgotPasswordCommand({
428
+ ClientId: this.fetchClientId(),
429
+ Username: username,
430
+ });
431
+ await client.send(command);
432
+ } catch (err: any) {
433
+ logger.error(`Forgot password failed for ${username}: ${sanitizeErrorMessage(err.message)}`);
434
+ handleCognitoError(err, 'forgotPassword');
435
+ }
436
+ }
437
+
438
+ async confirmForgotPassword(
439
+ username: string,
440
+ confirmationCode: string,
441
+ newPassword: string,
442
+ _env: Environment
443
+ ): Promise<void> {
444
+ try {
445
+ const client = new CognitoIdentityProviderClient({
446
+ region: process.env.AWS_REGION || 'us-west-2',
447
+ credentials: fromEnv(),
448
+ });
449
+ const command = new ConfirmForgotPasswordCommand({
450
+ ClientId: this.fetchClientId(),
451
+ Username: username,
452
+ ConfirmationCode: confirmationCode,
453
+ Password: newPassword,
454
+ });
455
+ await client.send(command);
456
+ } catch (err: any) {
457
+ logger.error(
458
+ `Confirm forgot password failed for ${username}: ${sanitizeErrorMessage(err.message)}`
459
+ );
460
+ handleCognitoError(err, 'confirmForgotPassword');
414
461
  }
415
462
  }
416
463
 
@@ -31,6 +31,13 @@ export interface AgentlangAuth {
31
31
  cb: SignUpCallback
32
32
  ): any;
33
33
  confirmSignup(username: string, confirmationCode: string, env: Environment): Promise<void>;
34
+ forgotPassword(username: string, env: Environment): Promise<void>;
35
+ confirmForgotPassword(
36
+ username: string,
37
+ confirmationCode: string,
38
+ newPassword: string,
39
+ env: Environment
40
+ ): Promise<void>;
34
41
  login(username: string, password: string, env: Environment, cb: LoginCallback): any;
35
42
  logout(sessionInfo: SessionInfo, env: Environment, cb?: LogoutCallback): any;
36
43
  verifyToken(token: string, env?: Environment): any;
@@ -1299,39 +1299,55 @@ async function walkJoinQueryPattern(
1299
1299
  }
1300
1300
  }
1301
1301
 
1302
+ const MAX_PLANNER_RETRIES = 3;
1303
+
1302
1304
  async function handleAgentInvocation(agentEventInst: Instance, env: Environment): Promise<void> {
1303
1305
  const agent: AgentInstance = await findAgentByName(agentEventInst.name, env);
1304
1306
  await agent.invoke(agentEventInst.lookup('message'), env);
1305
1307
  const r: string | undefined = env.getLastResult();
1306
1308
  const isPlanner = agent.isPlanner();
1307
- const result: string | undefined = isPlanner ? cleanupAgentResponse(r) : r;
1309
+ let result: string | undefined = isPlanner ? cleanupAgentResponse(r) : r;
1308
1310
  if (result) {
1309
1311
  if (isPlanner) {
1310
- logger.debug(`Agent ${agent.name} generated pattern: ${result}`);
1311
- try {
1312
- let rs = result.trim();
1313
- let isWf = rs.startsWith('workflow');
1314
- const isGrp = rs.startsWith('[');
1315
- if (!isWf && !isGrp && rs.indexOf(';') > 0) {
1316
- rs = `workflow T {${rs}}`;
1317
- isWf = true;
1318
- } else if (!isWf && isGrp) {
1319
- const stmts = rs.substring(1, rs.length - 1);
1320
- rs = `workflow T {${stmts}}`;
1321
- isWf = true;
1322
- }
1323
- if (isWf) {
1324
- const wf = await parseWorkflow(rs);
1325
- if (agent.runWorkflows) {
1312
+ let retries = 0;
1313
+ while (true) {
1314
+ logger.debug(`Agent ${agent.name} generated pattern: ${result}`);
1315
+ try {
1316
+ let rs: string = result ? result.trim() : '';
1317
+ let isWf = rs.startsWith('workflow');
1318
+ if (isWf && !agent.runWorkflows) {
1319
+ await parseWorkflow(rs);
1320
+ return;
1321
+ }
1322
+ const isGrp = rs.startsWith('[');
1323
+ if (!isWf && !isGrp && rs.indexOf(';') > 0) {
1324
+ rs = `workflow T {${rs}}`;
1325
+ isWf = true;
1326
+ } else if (!isWf && isGrp) {
1327
+ const stmts = rs.substring(1, rs.length - 1);
1328
+ rs = `workflow T {${stmts}}`;
1329
+ isWf = true;
1330
+ }
1331
+ if (isWf) {
1332
+ const wf = await parseWorkflow(rs);
1326
1333
  await evaluateStatements(wf.statements, env);
1334
+ } else {
1335
+ env.setLastResult(await parseAndEvaluateStatement(rs, undefined, env));
1336
+ }
1337
+ break;
1338
+ } catch (err: any) {
1339
+ if (retries < MAX_PLANNER_RETRIES) {
1340
+ await agent.invoke(`Please fix these errors:\n ${err}`, env);
1341
+ const r: string | undefined = env.getLastResult();
1342
+ result = cleanupAgentResponse(r);
1343
+ ++retries;
1344
+ } else {
1345
+ logger.error(
1346
+ `Failed to evaluate pattern generated by agent ${agent.name} - ${result}, ${err}`
1347
+ );
1348
+ break;
1327
1349
  }
1328
- } else {
1329
- env.setLastResult(await parseAndEvaluateStatement(rs, undefined, env));
1330
1350
  }
1331
- } catch (err: any) {
1332
- logger.error(
1333
- `Failed to evaluate pattern generated by agent ${agent.name} - ${result}, ${err}`
1334
- );
1335
1351
  }
1336
1352
  }
1337
1353
  } else {
@@ -36,7 +36,7 @@ export async function importModule(path: string, name: string, moduleFileName?:
36
36
  }
37
37
  path = `${s}${sep}${path}`;
38
38
  }
39
- if ((path.startsWith(sep) || path.startsWith('.')) && moduleFileName) {
39
+ if (!(path.startsWith(sep) || path.startsWith('.'))) {
40
40
  path = process.cwd() + sep + path;
41
41
  }
42
42
  const m = await import(/* @vite-ignore */ path);
@@ -57,7 +57,7 @@ import { URI } from 'vscode-uri';
57
57
  import { AstNode, LangiumCoreServices, LangiumDocument } from 'langium';
58
58
  import { isNodeEnv, path } from '../utils/runtime.js';
59
59
  import { CoreModules, registerCoreModules } from './modules/core.js';
60
- import { parse, parseModule, parseWorkflow } from '../language/parser.js';
60
+ import { maybeGetValidationErrors, parse, parseModule, parseWorkflow } from '../language/parser.js';
61
61
  import { logger } from './logger.js';
62
62
  import { Environment, evaluateStatements, GlobalEnvironment } from './interpreter.js';
63
63
  import { createPermission, createRole } from './modules/auth.js';
@@ -87,11 +87,6 @@ export async function extractDocument(
87
87
 
88
88
  if (!fileExists) {
89
89
  const errorMsg = `File ${fileName} does not exist.`;
90
- if (chalk) {
91
- console.error(chalk.red(errorMsg));
92
- } else {
93
- console.error(errorMsg);
94
- }
95
90
  throw new Error(errorMsg);
96
91
  }
97
92
  } else if (!isNodeEnv && typeof fileName === 'string') {
@@ -100,7 +95,7 @@ export async function extractDocument(
100
95
  const fileExists = await exists(fullFilePath);
101
96
 
102
97
  if (!fileExists) {
103
- console.error(`File ${fileName} does not exist.`);
98
+ throw new Error(`File ${fileName} does not exist.`);
104
99
  }
105
100
  } else {
106
101
  throw new Error('Invalid input: expected file path (Node.js) or File object/content (browser)');
@@ -116,27 +111,11 @@ export async function extractDocument(
116
111
  });
117
112
 
118
113
  // Handle validation errors
119
- const validationErrors = (document.diagnostics ?? []).filter(e => e.severity === 1);
120
-
121
- if (validationErrors.length > 0) {
122
- console.error(
123
- isNodeEnv && chalk
124
- ? chalk.red('There are validation errors:')
125
- : 'There are validation errors:'
126
- );
127
-
128
- for (const validationError of validationErrors) {
129
- const errorMsg = `line ${validationError.range.start.line + 1}: ${
130
- validationError.message
131
- } [${document.textDocument.getText(validationError.range)}]`;
132
- if (isNodeEnv && chalk) {
133
- console.error(chalk.red(errorMsg));
134
- } else {
135
- console.error(errorMsg);
136
- }
137
- }
114
+ const errs = maybeGetValidationErrors(document);
138
115
 
139
- throw new Error('Validation errors found');
116
+ if (errs) {
117
+ const errorMsg = `${errs.join('\n')}`;
118
+ throw new Error(errorMsg);
140
119
  }
141
120
 
142
121
  return document;
@@ -183,14 +162,18 @@ async function loadApp(appDir: string, fsOptions?: any, callback?: Function): Pr
183
162
  }
184
163
  if (appSpec.dependencies != undefined) {
185
164
  for (const [depName, _] of Object.entries(appSpec.dependencies)) {
186
- const depDirName = `./node_modules/${depName}`;
187
- const files = await fs.readdir(depDirName);
188
- if (
189
- files.find(file => {
190
- return path.extname(file).toLowerCase() == '.al';
191
- })
192
- ) {
193
- await loadApp(depDirName, fsOptions);
165
+ try {
166
+ const depDirName = `./node_modules/${depName}`;
167
+ const files = await fs.readdir(depDirName);
168
+ if (
169
+ files.find(file => {
170
+ return path.extname(file).toLowerCase() == '.al';
171
+ })
172
+ ) {
173
+ await loadApp(depDirName, fsOptions);
174
+ }
175
+ } catch (error) {
176
+ logger.error(`Error loading dependency ${depName}: ${error}`);
194
177
  }
195
178
  }
196
179
  }
@@ -228,8 +228,12 @@ export async function findProviderForLLM(
228
228
  const llm: Instance = result[0];
229
229
  const service = llm.lookup('service');
230
230
  const pclass = provider(service);
231
- const providerConfig: Map<string, any> =
232
- llm.lookup('config') || new Map().set('service', service);
231
+ const configValue = llm.lookup('config');
232
+ const providerConfig: Map<string, any> = configValue
233
+ ? configValue instanceof Map
234
+ ? configValue
235
+ : new Map(Object.entries(configValue))
236
+ : new Map().set('service', service);
233
237
  p = new pclass(providerConfig);
234
238
  if (p) ProviderDb.set(llmName, p);
235
239
  }
@@ -184,6 +184,18 @@ workflow login {
184
184
  await Auth.loginUser(login.email, login.password)
185
185
  }
186
186
 
187
+ workflow forgotPassword {
188
+ await Auth.forgotPasswordUser(forgotPassword.email)
189
+ }
190
+
191
+ workflow confirmForgotPassword {
192
+ await Auth.confirmForgotPasswordUser(
193
+ confirmForgotPassword.email,
194
+ confirmForgotPassword.confirmationCode,
195
+ confirmForgotPassword.newPassword
196
+ )
197
+ }
198
+
187
199
  workflow logout {
188
200
  await Auth.logoutUser()
189
201
  }
@@ -610,7 +622,7 @@ export async function confirmSignupUser(
610
622
  username: string,
611
623
  confirmationCode: string,
612
624
  env: Environment
613
- ): Promise<any> {
625
+ ): Promise<Result> {
614
626
  try {
615
627
  console.log('confirmSignupUser', username, confirmationCode, env);
616
628
  await fetchAuthImpl().confirmSignup(username, confirmationCode, env);
@@ -624,6 +636,31 @@ export async function confirmSignupUser(
624
636
  }
625
637
  }
626
638
 
639
+ export async function forgotPasswordUser(username: string, env: Environment): Promise<Result> {
640
+ try {
641
+ await fetchAuthImpl().forgotPassword(username, env);
642
+ return { status: 'ok', message: 'Password reset code sent' };
643
+ } catch (err: any) {
644
+ logger.error(`Forgot password failed for ${username}: ${err.message}`);
645
+ throw err;
646
+ }
647
+ }
648
+
649
+ export async function confirmForgotPasswordUser(
650
+ username: string,
651
+ confirmationCode: string,
652
+ newPassword: string,
653
+ env: Environment
654
+ ): Promise<Result> {
655
+ try {
656
+ await fetchAuthImpl().confirmForgotPassword(username, confirmationCode, newPassword, env);
657
+ return { status: 'ok', message: 'Password has been reset' };
658
+ } catch (err: any) {
659
+ logger.error(`Confirm forgot password failed for ${username}: ${err.message}`);
660
+ throw err;
661
+ }
662
+ }
663
+
627
664
  export async function loginUser(
628
665
  username: string,
629
666
  password: string,
@@ -656,7 +693,7 @@ export async function loginUser(
656
693
  }
657
694
  }
658
695
 
659
- async function logoutSession(userId: string, sess: Instance, env: Environment): Promise<string> {
696
+ async function logoutSession(userId: string, sess: Instance, env: Environment): Promise<Result> {
660
697
  const sessId = sess.lookup('id');
661
698
  const tok = sess.lookup('authToken');
662
699
  await fetchAuthImpl().logout(
@@ -671,23 +708,29 @@ async function logoutSession(userId: string, sess: Instance, env: Environment):
671
708
  env
672
709
  );
673
710
  await removeSession(sessId, env);
674
- return 'ok';
711
+ return {
712
+ status: 'ok',
713
+ message: 'Logged out successfully',
714
+ };
675
715
  }
676
716
 
677
- export async function logoutUser(env: Environment): Promise<string | undefined> {
717
+ export async function logoutUser(env: Environment): Promise<Result> {
678
718
  const user = env.getActiveUser();
679
719
  const sess = await findUserSession(user, env);
680
720
  if (sess) {
681
721
  return await logoutSession(user, sess, env);
682
722
  }
683
- return undefined;
723
+ return {
724
+ status: 'ok',
725
+ message: 'Logged out successfully',
726
+ };
684
727
  }
685
728
 
686
729
  export async function changePassword(
687
730
  newPassword: string,
688
731
  password: string,
689
732
  env: Environment
690
- ): Promise<string | undefined> {
733
+ ): Promise<Result> {
691
734
  const user = env.getActiveUser();
692
735
  const sess = await findUserSession(user, env);
693
736
  if (sess) {
@@ -900,6 +943,8 @@ export function requireAuth(moduleName: string, eventName: string): boolean {
900
943
  (eventName == 'login' ||
901
944
  eventName == 'signup' ||
902
945
  eventName == 'confirmSignup' ||
946
+ eventName == 'forgotPassword' ||
947
+ eventName == 'confirmForgotPassword' ||
903
948
  eventName == 'refreshToken');
904
949
  return !f;
905
950
  } else {
package/out/cli/docs.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export declare const generateSwaggerDoc: (fileName: string) => Promise<void>;
2
- //# sourceMappingURL=docs.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"docs.d.ts","sourceRoot":"","sources":["../../src/cli/docs.ts"],"names":[],"mappings":"AA8OA,eAAO,MAAM,kBAAkB,GAAU,UAAU,MAAM,KAAG,OAAO,CAAC,IAAI,CAcvE,CAAC"}
package/out/cli/docs.js DELETED
@@ -1,236 +0,0 @@
1
- import { z } from 'zod/v4';
2
- import yaml from 'yaml';
3
- import { OpenApiGeneratorV3, OpenAPIRegistry, extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
4
- import { getUserModuleNames, fetchModule } from '../runtime/module.js';
5
- import * as fs from 'node:fs/promises';
6
- import * as path from 'node:path';
7
- extendZodWithOpenApi(z);
8
- const registry = new OpenAPIRegistry();
9
- const bearerAuth = registry.registerComponent('securitySchemes', 'bearerAuth', {
10
- type: 'http',
11
- scheme: 'bearer',
12
- bearerFormat: 'JWT',
13
- });
14
- function getOpenApiDocumentation(registry, name, version) {
15
- const generator = new OpenApiGeneratorV3(registry.definitions);
16
- return generator.generateDocument({
17
- openapi: '3.0.0',
18
- info: {
19
- version: version,
20
- title: name,
21
- description: 'This is the API',
22
- },
23
- servers: [{ url: 'v1' }],
24
- });
25
- }
26
- function writeDocumentation(registry, docDir, name, version) {
27
- const docs = getOpenApiDocumentation(registry, name, version);
28
- const fileContent = yaml.stringify(docs);
29
- fs.mkdir(path.join(docDir, 'docs'), { recursive: true });
30
- fs.writeFile(`${docDir}/docs/openapi-docs.yml`, fileContent, {
31
- encoding: 'utf-8'
32
- });
33
- }
34
- function generateEntitiesEntries() {
35
- const modules = getUserModuleNames();
36
- return modules.map((moduleName) => {
37
- const module = fetchModule(moduleName);
38
- const entities = module.getEntityEntries();
39
- return entities.map((entity) => {
40
- const entityPath = `${moduleName}/${entity.name}`;
41
- const entitySchema = z.object(Object.fromEntries(Array.from(entity.schema.entries()).map(([key, value]) => [
42
- key,
43
- value.type === 'UUID' ? z.uuid() :
44
- value.type === 'String' ? z.string() :
45
- value.type === 'Int' ? z.number() :
46
- value.type === 'Float' ? z.number() :
47
- value.type === 'Boolean' ? z.boolean() :
48
- value.type === 'Date' ? z.string() :
49
- value.type === 'DateTime' ? z.string() :
50
- z.any()
51
- ]))).openapi(`${entity.name}Schema`);
52
- const sc = z.object({
53
- [entityPath]: entitySchema
54
- });
55
- const scresp = z.array(entitySchema);
56
- registry.registerPath({
57
- method: 'post',
58
- path: `/api/${entityPath}`,
59
- security: [{ [bearerAuth.name]: [] }],
60
- tags: [`${entityPath}`],
61
- request: {
62
- body: {
63
- content: {
64
- 'application/json': {
65
- schema: sc
66
- }
67
- }
68
- }
69
- },
70
- responses: {
71
- 200: {
72
- description: 'Success',
73
- content: {
74
- 'application/json': {
75
- schema: entitySchema
76
- },
77
- },
78
- },
79
- 500: {
80
- description: 'Internal Server Error'
81
- }
82
- },
83
- });
84
- registry.registerPath({
85
- method: 'get',
86
- path: `/api/${entityPath}`,
87
- security: [{ [bearerAuth.name]: [] }],
88
- tags: [`${entityPath}`],
89
- responses: {
90
- 200: {
91
- description: 'Success',
92
- content: {
93
- 'application/json': {
94
- schema: scresp
95
- },
96
- },
97
- },
98
- 404: {
99
- description: 'Not Found'
100
- },
101
- 500: {
102
- description: 'Internal Server Error'
103
- }
104
- },
105
- });
106
- registry.registerPath({
107
- method: 'put',
108
- path: `/api/${entityPath}/{id}`,
109
- tags: [`${entityPath}`],
110
- parameters: [{
111
- name: 'id',
112
- in: 'path',
113
- required: true,
114
- schema: { type: 'string' }
115
- }],
116
- security: [{ [bearerAuth.name]: [] }],
117
- request: {
118
- body: {
119
- content: {
120
- 'application/json': {
121
- schema: sc
122
- }
123
- }
124
- }
125
- },
126
- responses: {
127
- 200: {
128
- description: 'Success',
129
- content: {
130
- 'application/json': {
131
- schema: entitySchema
132
- },
133
- },
134
- },
135
- 404: {
136
- description: 'Not Found'
137
- },
138
- 500: {
139
- description: 'Internal Server Error'
140
- }
141
- },
142
- });
143
- registry.registerPath({
144
- method: 'delete',
145
- path: `/api/${entityPath}/{id}`,
146
- security: [{ [bearerAuth.name]: [] }],
147
- tags: [`${entityPath}`],
148
- parameters: [{
149
- name: 'id',
150
- in: 'path',
151
- required: true,
152
- schema: { type: 'string' }
153
- }],
154
- responses: {
155
- 200: {
156
- description: 'Success'
157
- },
158
- 404: {
159
- description: 'Not Found'
160
- },
161
- 500: {
162
- description: 'Internal Server Error'
163
- }
164
- },
165
- });
166
- });
167
- });
168
- }
169
- function generateEventsEntries() {
170
- const modules = getUserModuleNames();
171
- return modules.map((moduleName) => {
172
- const module = fetchModule(moduleName);
173
- const events = module.getEventEntries();
174
- return events.map((event) => {
175
- const eventPath = `${moduleName}/${event.name}`;
176
- const eventSchema = z.object(Object.fromEntries(Array.from(event.schema.entries()).map(([key, value]) => [
177
- key,
178
- value.type === 'UUID' ? z.uuid() :
179
- value.type === 'String' ? z.string() :
180
- value.type === 'Int' ? z.number() :
181
- value.type === 'Float' ? z.number() :
182
- value.type === 'Boolean' ? z.boolean() :
183
- value.type === 'Date' ? z.string() :
184
- value.type === 'DateTime' ? z.string() :
185
- z.any()
186
- ]))).openapi(`${event.name}Schema`);
187
- const sc = z.object({
188
- [eventPath]: eventSchema
189
- });
190
- registry.registerPath({
191
- method: 'post',
192
- path: `/api/${eventPath}`,
193
- security: [{ [bearerAuth.name]: [] }],
194
- tags: ['Events'],
195
- request: {
196
- body: {
197
- content: {
198
- 'application/json': {
199
- schema: sc
200
- }
201
- }
202
- }
203
- },
204
- responses: {
205
- 200: {
206
- description: 'Success'
207
- },
208
- 404: {
209
- description: 'Not Found'
210
- },
211
- 500: {
212
- description: 'Internal Server Error'
213
- }
214
- }
215
- });
216
- return {
217
- path: eventPath,
218
- name: event.name,
219
- schema: event.schema
220
- };
221
- });
222
- });
223
- }
224
- export const generateSwaggerDoc = async (fileName) => {
225
- console.log('Generating documentation...');
226
- const docDir = path.dirname(fileName) === '.' ? process.cwd() : path.resolve(process.cwd(), fileName);
227
- const packagePath = path.join(docDir, 'package.json');
228
- const packageContent = await fs.readFile(packagePath, 'utf-8');
229
- const pkg = JSON.parse(packageContent);
230
- const name = pkg.name || 'app';
231
- const version = pkg.version || '0.0.1';
232
- generateEntitiesEntries();
233
- generateEventsEntries();
234
- writeDocumentation(registry, docDir, name, version);
235
- };
236
- //# sourceMappingURL=docs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"docs.js","sourceRoot":"","sources":["../../src/cli/docs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAC3B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAC3G,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAiB,MAAM,sBAAsB,CAAC;AACtF,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,oBAAoB,CAAC,CAAC,CAAC,CAAC;AAExB,MAAM,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAC;AAEvC,MAAM,UAAU,GAAG,QAAQ,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,YAAY,EAAE;IAC7E,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ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