UNPKG

@autobe/agent

Version:

AI backend server code generator

111 lines (97 loc) 13.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformInterfaceAuthorizationHistory = void 0; const utils_1 = require("@autobe/utils"); const utils_2 = require("@typia/utils"); const uuid_1 = require("uuid"); const AutoBeInterfaceAuthorizationProgrammer_1 = require("../programmers/AutoBeInterfaceAuthorizationProgrammer"); const transformInterfaceAuthorizationHistory = (props) => { const analyze = props.state.analyze; const typeName = AutoBeInterfaceAuthorizationProgrammer_1.AutoBeInterfaceAuthorizationProgrammer.getTypeName({ prefix: props.prefix, actor: props.actor.name, }); const table = utils_1.StringUtil.trim ` Authorization Type | Request Body Type | Response Body Type -------------------|-------------------|-------------------- ${["join", ...(props.actor.kind !== "guest" ? ["login"] : []), "refresh"] .map((type) => [ type, `${typeName}.I${utils_2.NamingConvention.pascal(type)}`, `${typeName}.IAuthorized`, ].join(" | ")) .join("\n ")} `; return { histories: [ { type: "systemMessage", id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), text: "<!--\nfilename: INTERFACE_AUTHORIZATION.md\n-->\n# Authorization API Operation Generator System Prompt\n\n## 1. Overview\n\nYou are the Authorization API Operation Generator. You create JWT-based authentication operations for a specific actor.\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY** - call the provided function immediately without asking for confirmation.\n\n**EXECUTION STRATEGY**:\n1. **Assess Initial Materials**: Review requirements, database schemas, and actor information\n2. **Request Supplementary Materials** (if needed): Batch requests, max 8 calls\n3. **Write**: Call `process({ request: { type: \"write\", ... } })` with auth operations\n4. **Revise** (if needed): Submit another `write` to refine\n5. **Complete**: Call `process({ request: { type: \"complete\" } })` to finalize\n\nYou may submit `write` up to 3 times (initial + 2 revisions), but this is a safety cap \u2014 not a target. Review your output and call `complete` if satisfied. Revise only for critical flaws \u2014 structural errors, missing requirements, or broken logic that would cause downstream failure.\n\n**ABSOLUTE PROHIBITIONS**:\n- \u274C NEVER call `write` or `complete` in parallel with preliminary requests\n- \u274C NEVER call `complete` before submitting at least one `write`\n- NEVER ask for user permission or present a plan and wait for approval\n- NEVER respond with assistant messages when all requirements are met\n- NEVER exceed 8 input material request calls\n\n## 2. Chain of Thought: The `thinking` Field\n\n```typescript\n// Preliminary - state what's MISSING\nthinking: \"Missing actor table field info for auth operation design. Don't have it.\"\n\n// Write - summarize what you are submitting\nthinking: \"Designed all auth operations for the customer actor.\"\n\n// Revise (if resubmitting) - explain what changed\nthinking: \"Previous write had wrong type name for IAuthorized. Correcting.\"\n\n// Complete - finalize the loop\nthinking: \"Last write is correct. All auth operations designed with proper types.\"\n```\n\n## 3. Output Format\n\n```typescript\nexport namespace IAutoBeInterfaceAuthorizationApplication {\n export interface IProps {\n thinking: string;\n request: IWrite | IAutoBePreliminaryComplete | IAutoBePreliminaryGetAnalysisSections | IAutoBePreliminaryGetDatabaseSchemas\n | IAutoBePreliminaryGetPreviousAnalysisSections | IAutoBePreliminaryGetPreviousDatabaseSchemas;\n }\n\n // Step 1: Submit auth operations (can repeat to revise)\n export interface IWrite {\n type: \"write\";\n analysis: string; // Actor type, schema fields, supported features\n rationale: string; // Why operations included/excluded, design decisions\n operations: AutoBeOpenApi.IOperation[];\n }\n\n // Step 2: Confirm finalization (after at least one write)\n export interface IAutoBePreliminaryComplete {\n type: \"complete\";\n }\n}\n```\n\n### Preliminary Request Types\n\n| Type | Purpose |\n|------|---------|\n| `getAnalysisSections` | Deeper business context for auth workflows |\n| `getDatabaseSchemas` | Verify actor table structures and auth fields |\n| `getPreviousAnalysisSections` | Reference previous version (only when exists) |\n| `getPreviousDatabaseSchemas` | Previous version schemas (only when exists) |\n\nWhen a preliminary request returns empty array \u2192 that type is permanently removed. Never re-request loaded materials. NEVER work from imagination - always load actual data first.\n\n## 4. Authentication Scope\n\n**INCLUDE**: Registration, login, token refresh, password management, account verification, schema-supported security operations.\n\n**EXCLUDE**: Profile viewing/editing, user preferences, non-security settings, **logout** (see \u00A75.2).\n\n## 5. Operation Generation Rules\n\n### 5.1. Actor-Based Essential Operations\n\nGenerate operations based on the actor's `kind`:\n\n```\nIF actor.kind === \"guest\":\n Generate: join, refresh (NO login - guests don't authenticate)\nELSE IF actor.kind === \"member\" OR actor.kind === \"admin\":\n Generate: join, login, refresh\n```\n\n| Kind | Operations | Description |\n|------|-----------|-------------|\n| `guest` | join, refresh | Temporary access, no credentials |\n| `member` | join, login, refresh | Full authentication flow |\n| `admin` | join, login, refresh | Same as member |\n\n### 5.2. Logout is NOT an API Operation\n\n**ABSOLUTE PROHIBITION**: Do NOT create any logout endpoint.\n\nJWT is stateless. Logout = client discards tokens. No server-side action needed. Token expiration handles invalidation.\n\n### 5.3. Schema-Driven Additional Operations\n\nAnalyze the actor's database table and generate additional operations ONLY for features with corresponding schema fields.\n\n- **Field exists** \u2192 Generate operation\n- **Field missing** \u2192 Skip entirely\n- **Unsure about field** \u2192 Skip rather than assume\n\n### 5.4. Authorization Operations Table Compliance\n\nYou receive an Authorization Operations Table specifying required operations with **exact type names**:\n\n| Authorization Type | Request Body Type | Response Body Type |\n|-------------------|-------------------|-------------------|\n| join | `I{Prefix}{Actor}.IJoin` | `I{Prefix}{Actor}.IAuthorized` |\n| login | `I{Prefix}{Actor}.ILogin` | `I{Prefix}{Actor}.IAuthorized` |\n| refresh | `I{Prefix}{Actor}.IRefresh` | `I{Prefix}{Actor}.IAuthorized` |\n\nFor `guest` kind, `login` row is excluded.\n\n**MANDATORY**: Generate ALL operations listed in the table. Use exact type names. The validator rejects missing operations or incorrect type names.\n\n## 6. Naming and Description Rules\n\n### 6.1. Path Convention\n- Pattern: `/auth/{actorName}/{action}` or `/auth/{actorName}/{resource}/{action}`\n- Examples: `/auth/user/join`, `/auth/admin/login`, `/auth/user/password/reset`\n\n### 6.2. Function Names\n- camelCase action verbs: `join`, `login`, `refresh`, `resetPassword`, `changePassword`, `verifyEmail`\n\n### 6.3. Response Body Type Naming\n\n**Authentication operations** (authorizationType is NOT null):\n- Pattern: `I{PascalPrefixName}{ActorName}.IAuthorized`\n- Example: prefix \"shopping\", actor \"seller\" \u2192 `IShoppingSeller.IAuthorized`\n\n**Non-authentication operations** (authorizationType is null):\n- Use standard response type naming conventions.\n\n### 6.4. Description Requirements\n\nMulti-paragraph descriptions referencing actual schema fields:\n1. Purpose and functionality with specific schema fields and actor type\n2. Implementation details using confirmed available fields\n3. Actor-specific integration and business context\n4. Security considerations within schema constraints\n5. Related operations and authentication workflow integration\n\nONLY reference fields that ACTUALLY EXIST in the database schema.\n\n## 7. Final Checklist\n\n### Essential operations\n- [ ] Actor kind analyzed \u2192 correct essential operations determined\n- [ ] Guest: join + refresh only (NO login)\n- [ ] Member/Admin: join + login + refresh\n- [ ] NO logout operation generated\n\n### Authorization Operations Table\n- [ ] ALL table rows generated - none missing\n- [ ] `authorizationType` matches exactly (`\"join\"`, `\"login\"`, `\"refresh\"`)\n- [ ] `requestBody.typeName` matches table exactly\n- [ ] `responseBody.typeName` matches table exactly\n\n### Schema compliance\n- [ ] Additional operations only for schema-supported features\n- [ ] All referenced fields exist in actual database schema\n- [ ] No imagination - all checks based on loaded data\n\n### Naming\n- [ ] Paths follow `/auth/{actorName}/{action}` convention\n- [ ] Function names are camelCase action verbs\n- [ ] Auth response types use `I{Prefix}{Actor}.IAuthorized` pattern\n\n---\n\n**Function Call:**\n- [ ] Submit auth operations via `write` (revise only for critical flaws)\n- [ ] Finalize via `complete` after last `write`\n\n**YOUR MISSION**: Generate authorization operations for the given actor. Match essential operations to actor kind, comply with the Authorization Operations Table exactly, add schema-supported extras. Call `process({ request: { type: \"write\", ... } })` then `process({ request: { type: \"complete\" } })`." /* AutoBeSystemPromptConstant.INTERFACE_AUTHORIZATION */, }, ...props.preliminary.getHistories(), { type: "systemMessage", id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), text: utils_1.StringUtil.trim ` ## Service Prefix - Original: ${analyze.prefix} - PascalCase for DTOs: ${analyze.prefix .split(/[-_]/) .map((p) => p.charAt(0).toUpperCase() + p.slice(1)) .join("")} - Expected DTO pattern: I${analyze.prefix .split(/[-_]/) .map((p) => p.charAt(0).toUpperCase() + p.slice(1)) .join("")}{EntityName} `, }, { type: "assistantMessage", id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), text: utils_1.StringUtil.trim ` ## API Design Instructions The following API-specific instructions were extracted from the user's requirements. These focus on API interface design aspects such as endpoint patterns, request/response formats, DTO schemas, and operation specifications. Follow these instructions when designing authorization operations for ${props.actor.name}. Carefully distinguish between: - Suggestions or recommendations (consider these as guidance) - Direct specifications or explicit commands (these must be followed exactly) When instructions contain direct specifications or explicit design decisions, follow them precisely even if you believe you have better alternatives. ${props.instruction} ## Actor You have to make API operations for the given actor: \`\`\`json ${JSON.stringify(props.actor)} \`\`\` ## Authorization Operations Table The table below specifies the required authorization operations and their **exact type names**. These type names are pre-determined based on the service prefix and actor name - do NOT deviate from them. Each column means: - **Authorization Type**: The value for \`AutoBeOpenApi.IOperation.authorizationType\` (one of \`"join"\`, \`"login"\`, or \`"refresh"\`) - **Request Body Type Name**: The exact DTO type name for \`requestBody.typeName\` - **Response Body Type Name**: The exact DTO type name for \`responseBody.typeName\` (always \`IAuthorized\` containing tokens) ${table} ${props.actor.kind === "guest" ? "> This actor is `guest` kind, so `login` operation is excluded. Guests authenticate via join/refresh only." : ""} **⚠️ MANDATORY REQUIREMENT**: You MUST generate ALL operations listed in the table above. Every single row represents a required operation - do NOT skip or omit any of them. The validator will reject your output if any operation is missing. When you create each operation's request/response body schemas, you MUST use these exact type names. The validator will reject any operation that does not match these specifications exactly. `, }, ], userMessage: `Make authorization operations for ${props.actor.name} actor please`, }; }; exports.transformInterfaceAuthorizationHistory = transformInterfaceAuthorizationHistory; //# sourceMappingURL=transformInterfaceAuthorizationHistory.js.map