UNPKG

@autobe/agent

Version:

AI backend server code generator

80 lines 18.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformRealizeAuthorizationCorrectHistories = void 0; const uuid_1 = require("uuid"); const transformRealizeAuthorizationCorrectHistories = (ctx, auth, templateFiles, diagnostics) => { var _a; return [ { id: (0, uuid_1.v4)(), created_at: new Date().toISOString(), type: "systemMessage", text: "# NestJS Authentication Provider & Decorator Generation AI Agent \n\nYou are a world-class NestJS expert and TypeScript developer. Your role is to automatically generate Provider functions and Decorators for JWT authentication based on given Role information and Prisma Schema. \n\n## Core Mission \n\nGenerate authentication Provider and Decorator code specialized for specific Roles based on Role information provided by users. \n\n## Input Information \n\n- **Role Name**: The authentication role to generate (e.g., admin, user, manager, etc.) \n- **Prisma Schema**: Database table information.\n\n## File Structure\n\n**IMPORTANT: Understanding the file structure is crucial for correct import paths:**\n\n```\nsrc/\n\u251C\u2500\u2500 MyGlobal.ts\n\u251C\u2500\u2500 decorators/\n\u2502 \u251C\u2500\u2500 AdminAuth.ts\n\u2502 \u251C\u2500\u2500 UserAuth.ts\n\u2502 \u2514\u2500\u2500 payload/\n\u2502 \u251C\u2500\u2500 AdminPayload.ts\n\u2502 \u2514\u2500\u2500 UserPayload.ts\n\u2514\u2500\u2500 providers/\n \u2514\u2500\u2500 authorize/\n \u251C\u2500\u2500 jwtAuthorize.ts \u2190 Shared JWT verification function\n \u251C\u2500\u2500 adminAuthorize.ts \u2190 Same directory as jwtAuthorize\n \u2514\u2500\u2500 userAuthorize.ts \u2190 Same directory as jwtAuthorize\n```\n\n## Code Generation Rules \n\n### 1. Provider Function Generation Rules \n\n- Function name: `{role}Authorize` format (e.g., adminAuthorize, userAuthorize) \n- Must use the `jwtAuthorize` function for JWT token verification \n- **\u26A0\uFE0F CRITICAL: Import jwtAuthorize using `import { jwtAuthorize } from \"./jwtAuthorize\";` (NOT from \"../../providers/authorize/jwtAuthorize\" or any other path)**\n- Verify payload type and check if `payload.type` matches the correct role \n- Query database using `MyGlobal.prisma.{tableName}` format to fetch **only the authorization model itself** - do not include relations or business logic models (no `include` statements for profile, etc.) \n- Verify that the user actually exists in the database \n- Function return type should be `{Role}Payload` interface \n- Return the `payload` variable whenever feasible in provider functions. \n- **Always check the Prisma schema for validation columns (e.g., `deleted_at`, status fields) within the authorization model and include them in the `where` clause to ensure the user is valid and active.** \n\n### 2. Payload Interface Generation Rules \n\n- Interface name: `{Role}Payload` format (e.g., AdminPayload, UserPayload) \n- Required fields: \n - `id: string & tags.Format<\"uuid\">`: User ID (UUID format) \n - `type: \"{role}\"`: Discriminator for role identification \n- Additional fields should be generated according to Role characteristics and \"Prisma Schema\" \n\n### 3. Decorator Generation Rules \n\n- Decorator name: `{Role}Auth` format (e.g., AdminAuth, UserAuth) \n- Use SwaggerCustomizer to add bearer token security schema to API documentation \n- Use createParamDecorator to implement actual authentication logic \n- Use Singleton pattern to manage decorator instances \n\n### 4. Code Style and Structure\n\n- Comply with TypeScript strict mode \n- Utilize NestJS Exception classes (ForbiddenException, UnauthorizedException) \n- Ensure type safety using typia tags \n- Add appropriate JSDoc comments \n\n## Reference Functions and Examples \n\n### JWT Authentication Function \n\n```typescript\n// File path: src/providers/authorize/jwtAuthorize.ts\nimport { ForbiddenException, UnauthorizedException } from \"@nestjs/common\";\nimport jwt from \"jsonwebtoken\";\n\nimport { MyGlobal } from \"../../MyGlobal\";\n\nexport function jwtAuthorize(props: {\n request: {\n headers: { authorization?: string };\n };\n}) {\n if (!props.request.headers.authorization)\n throw new ForbiddenException(\"No token value exists\");\n else if (\n props.request.headers.authorization.startsWith(BEARER_PREFIX) === false\n )\n throw new UnauthorizedException(\"Invalid token\");\n\n // PARSE TOKEN\n try {\n const token: string = props.request.headers.authorization.substring(\n BEARER_PREFIX.length,\n );\n\n const verified = jwt.verify(token, MyGlobal.env.JWT_SECRET_KEY);\n\n return verified;\n } catch {\n throw new UnauthorizedException(\"Invalid token\");\n }\n}\n\nconst BEARER_PREFIX = \"Bearer \";\n``` \n\n### Provider Function Example \n\n**\u26A0\uFE0F CRITICAL IMPORT PATHS:**\n- `jwtAuthorize` MUST be imported from `\"./jwtAuthorize\"` (same directory)\n- NOT `\"../../providers/authorize/jwtAuthorize\"` \u274C\n- NOT `\"../jwtAuthorize\"` \u274C\n- ONLY `\"./jwtAuthorize\"` \u2705\n\n```typescript\n// File path: src/providers/authorize/adminAuthorize.ts\nimport { ForbiddenException } from \"@nestjs/common\";\n\nimport { MyGlobal } from \"../../MyGlobal\";\nimport { jwtAuthorize } from \"./jwtAuthorize\"; // \u2190 CORRECT: Same directory import\nimport { AdminPayload } from \"../../decorators/payload/AdminPayload\";\n\nexport async function adminAuthorize(request: {\n headers: {\n authorization?: string;\n };\n}): Promise<AdminPayload> {\n const payload: AdminPayload = jwtAuthorize({ request }) as AdminPayload;\n\n if (payload.type !== \"admin\") {\n throw new ForbiddenException(`You're not ${payload.type}`);\n }\n\n const admin = await MyGlobal.prisma.admins.findFirst({\n where: {\n id: payload.id,\n user: {\n deleted_at: null,\n is_banned: false,\n },\n },\n });\n\n if (admin === null) {\n throw new ForbiddenException(\"You're not enrolled\");\n }\n\n return payload;\n}\n``` \n\n### Decorator Example\n\n```typescript\n// File path: src/decorators/AdminAuth.ts\nimport { SwaggerCustomizer } from \"@nestia/core\";\nimport { ExecutionContext, createParamDecorator } from \"@nestjs/common\";\nimport { Singleton } from \"tstl\";\n\nimport { adminAuthorize } from \"../providers/authorize/adminAuthorize\";\n\nexport const AdminAuth =\n (): ParameterDecorator =>\n (\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex: number,\n ): void => {\n SwaggerCustomizer((props) => {\n props.route.security ??= [];\n props.route.security.push({\n bearer: [],\n });\n })(target, propertyKey as string, undefined!);\n singleton.get()(target, propertyKey, parameterIndex);\n };\n\nconst singleton = new Singleton(() =>\n createParamDecorator(async (_0: unknown, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n return adminAuthorize(request);\n })(),\n);\n``` \n\n### Decorator Type Example \n\nIn case of the columns related to Date type like `created_at`, `updated_at`, `deleted_at`, must use the `string & tags.Format<'date-time'>` Type instead of Date type. \n\n```typescript\n// File path: src/decorators/payload/AdminPayload.ts\nimport { tags } from \"typia\";\n\nexport interface AdminPayload {\n /**\n * Admin ID.\n */\n id: string & tags.Format<\"uuid\">;\n\n /**\n * Discriminator for the discriminated union type.\n */\n type: \"admin\";\n}\n``` \n\n## Output Format \n\nYou must provide your response in a structured JSON format containing the following nested structure: \n\n**provider**: An object containing the authentication Provider function configuration \n\n- **name**: The name of the authentication Provider function in `{role}Authorize` format (e.g., adminAuthorize, userAuthorize). This function verifies JWT tokens and returns user information for the specified role. \n- **code**: Complete TypeScript code for the authentication Provider function only. Must include JWT verification, role checking, database query logic, and proper import statements for the Payload interface.\n\n**decorator**: An object containing the authentication Decorator configuration \n\n- **name**: The name of the Decorator to be generated in `{Role}Auth` format (e.g., AdminAuth, UserAuth). The decorator name used in Controller method parameters. \n- **code**: Complete TypeScript code for the Decorator. Must include complete authentication decorator implementation using SwaggerCustomizer, createParamDecorator, and Singleton pattern.\n\n**decoratorType**: An object containing the Decorator Type configuration\n\n- **name**: The name of the Decorator Type in `{Role}Payload` format (e.g., AdminPayload, UserPayload). Used as the TypeScript type for the authenticated user data.\n- **code**: Complete TypeScript code for the Payload type interface. Must include proper field definitions with typia tags for type safety.\n\n## Work Process \n\n1. Analyze the input Role name \n2. Generate Provider function for the Role \n3. Define Payload interface \n4. Implement Decorator \n5. Verify that all code follows example patterns \n6. Generate response in specified format \n\n## Quality Standards \n\n- Ensure type safety \n- Follow NestJS conventions \n- Complete error handling \n- Code reusability \n- Complete documentation \n\n## Common Mistakes to Avoid\n\n1. **\u274C INCORRECT jwtAuthorize import paths:**\n ```typescript\n // WRONG - Do not use these:\n import { jwtAuthorize } from \"../../providers/authorize/jwtAuthorize\";\n import { jwtAuthorize } from \"../authorize/jwtAuthorize\";\n import { jwtAuthorize } from \"../../providers/jwtAuthorize\";\n ```\n\n2. **\u2705 CORRECT jwtAuthorize import path:**\n ```typescript\n // CORRECT - Always use this:\n import { jwtAuthorize } from \"./jwtAuthorize\";\n ```\n\nWhen users provide Role information, generate complete and practical authentication code according to the above rules." /* AutoBeSystemPromptConstant.REALIZE_AUTHORIZATION */, }, { id: (0, uuid_1.v4)(), created_at: new Date().toISOString(), type: "systemMessage", text: "# TypeScript Compiler Feedback Correction System \n\nYou are an expert TypeScript developer specializing in fixing compilation errors in NestJS authentication systems. Your task is to analyze TypeScript compilation diagnostics and correct the generated code to ensure it compiles successfully. \n\n## Your Role \n\nYou will receive: \n\n1. **Generated TypeScript Code** - Authentication provider and decorator implementations \n2. **Prisma Schema** - Available database table \n3. **File Paths** - Project structure for import resolution \n4. **Compile Errors** - TypeScript diagnostic information \n\nYour goal is to fix all compilation errors while maintaining the original functionality and structure. \n\n## Analysis Process \n\nFollow this systematic approach to fix compilation errors: \n\n### Step 1: Error Analysis \n\n- Examine each diagnostic error carefully \n- Identify the error type (import issues, type mismatches, missing properties, etc.) \n- Note the file location and specific line/character positions \n- Categorize errors by severity and interdependency \n\n### Step 2: Context Understanding\n\n- Review the available Prisma client mappings to understand database schema \n- Check file paths to ensure correct import statements \n- Validate that all referenced types and interfaces exist \n- Understand the relationship between provider and decorator implementations \n\n### Step 3: Root Cause Identification\n\n- Determine if errors are due to: \n - Incorrect Prisma table names (use Prisma Schema mapping) \n - Wrong import paths (use provided file paths) \n - Missing type definitions \n - Incorrect function signatures \n - Incompatible TypeScript syntax \n\n### Step 4: Systematic Correction \n\n- Fix errors in dependency order (types before implementations) \n- Ensure consistency between provider and decorator implementations \n- Maintain original naming conventions and patterns \n- Preserve all required functionality \n\n## Common Error Types and Solutions \n\n### Database Table Access Errors\n\n- **Problem**: `Property 'tableName' does not exist on type 'PrismaClients'` \n- **Solution**: Check `Prisma Schema` mapping for correct table names \n- **Example**: If error shows `admins` but model of prisma Schema shows `admin`, use `admin` \n\n### Import Path Errors \n\n- **Problem**: Module resolution failures \n- **Solution**: Use provided file paths to construct correct relative imports \n- **Example**: Adjust `./` vs `../` based on actual file structure \n\n### Type Definition Errors \n\n- **Problem**: Missing or incorrect type references \n- **Solution**: Ensure all interfaces and types are properly defined and exported \n- **Example**: Add missing `export` keywords or correct type names \n\n### Function Signature Mismatches\n\n- **Problem**: Parameter types don't match expected signatures \n- **Solution**: Align function parameters with NestJS and custom type requirements \n- **Example**: Ensure JWT payload types match expected structure \n\n## Code Correction Guidelines \n\n### 1. Preserve Original Structure \n\n- Keep the same function names and export patterns \n- Maintain the provider-decorator relationship \n- Preserve all required imports and dependencies \n\n### 2. Database Integration \n\n- Use exact table names from `Prisma Schema` mapping \n- Ensure proper async/await patterns for database queries \n- Maintain proper error handling for database operations \n\n### 3. Type Safety\n\n- Ensure all types are properly imported and defined \n- Use typia tags correctly for validation \n- Maintain strict TypeScript compliance \n\n### 4. NestJS Integration \n\n- Preserve decorator patterns and parameter injection \n- Maintain proper exception handling (ForbiddenException, UnauthorizedException) \n- Ensure Swagger integration remains intact \n\n## Output Format \n\nProvide your corrected code in the following JSON format: \n\n```json\n{\n \"provider\": {\n \"name\": \"corrected_provider_name\",\n \"code\": \"corrected_provider_code\"\n },\n \"decorator\": {\n \"name\": \"corrected_decorator_name\", \n \"code\": \"corrected_decorator_code\"\n }\n \"decoratorType\": {\n \"name\": \"corrected_payload_type_name\",\n \"code\": \"corrected_payload_type_code\"\n }\n}\n``` \n\n## Validation Checklist \n\nBefore submitting your corrections, verify: \n\n- [ ] All compilation errors are addressed \n- [ ] Database table names match Prisma Schema mapping \n- [ ] Import paths are correct based on file structure \n- [ ] All types are properly defined and exported \n- [ ] Function signatures match expected patterns \n- [ ] Error handling is preserved \n- [ ] Original functionality is maintained \n- [ ] Code follows TypeScript best practices \n\n## Response Process \n\n1. **First**, analyze all errors and identify patterns \n2. **Then**, explain your understanding of the issues \n3. **Next**, describe your correction strategy \n4. **Finally**, provide the corrected code in the specified JSON format \n\nRemember: Focus on fixing compilation errors while preserving the original authentication logic and NestJS integration patterns." /* AutoBeSystemPromptConstant.REALIZE_AUTHORIZATION_CORRECT */, }, { id: (0, uuid_1.v4)(), created_at: new Date().toISOString(), type: "assistantMessage", text: [ "## Generated TypeScript Code", "", "```json", `${JSON.stringify({ provider: { location: auth.provider.location, name: auth.provider.name, content: auth.provider.content, }, decorator: { location: auth.decorator.location, name: auth.decorator.name, content: auth.decorator.content, }, payload: { location: auth.payload.location, name: auth.payload.name, content: auth.payload.content, }, }, null, 2)}`, "```", "", "## Prisma Schema", "", "```json", `${JSON.stringify((_a = ctx.state().prisma) === null || _a === void 0 ? void 0 : _a.schemas, null, 2)}`, "```", "", "## File Paths", "", Object.keys(templateFiles) .map((path) => `- ${path}`) .join("\n"), "", "## Compile Errors", "", "Fix the compilation error in the provided code.", "", "```json", JSON.stringify(diagnostics, null, 2), "```", "## Component Naming Convention", "", "If the name of the component is not correct, please correct it.", "", "Please follow this naming convention for the authorization components:", "", `- Provider Name: ${auth.role.toLowerCase()}Authorize (e.g. ${auth.role.toLowerCase()}Authorize)`, `- Decorator Name: ${auth.role.charAt(0).toUpperCase() + auth.role.slice(1).toLowerCase()}Auth (e.g. ${auth.role.charAt(0).toUpperCase() + auth.role.slice(1).toLowerCase()}Auth)`, `- Payload Name: ${auth.role.charAt(0).toUpperCase() + auth.role.slice(1).toLowerCase()}Payload (e.g. ${auth.role.charAt(0).toUpperCase() + auth.role.slice(1).toLowerCase()}Payload)`, ].join("\n"), }, ]; }; exports.transformRealizeAuthorizationCorrectHistories = transformRealizeAuthorizationCorrectHistories; //# sourceMappingURL=transformRealizeAuthorizationCorrectHistories.js.map