A TypeScript type automatic generation method based on Swagger document
By parsing TypeScript interface files and Swagger documentation, it automatically identifies and transforms the request parameters and response body schema of interface functions, solving the problem of front-end developers manually writing types. It achieves efficient and accurate type generation and consistency between the front-end and back-end, and is suitable for traditional development and AI-assisted coding scenarios.
Patent Information
- Application Number
- CN202611251607.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-18
- Publication Date
- 2026-11-24
AI Technical Summary
In existing technologies, front-end developers need to manually write the interface request parameter types and response body types, which leads to high repetition, error-proneness, and difficulty in synchronizing with back-end interfaces. Furthermore, existing automation tools cannot accurately parse interface functions, generate type definitions that do not correspond to interface functions, cannot be directly called in an artificial intelligence environment, and cannot handle complex schema structures.
It constructs an abstract syntax tree by parsing TypeScript interface files, identifies functions to be processed, locates interface definitions in Swagger documentation, converts the schema into TypeScript type definitions, inserts type definitions into the interface files, supports command-line and model context protocol calls, recursively parses $ref references, and maintains the file format unchanged.
It improves the efficiency of type writing, enhances the consistency between the front-end and back-end, reduces the difficulty of maintenance, adapts to multiple scenarios, maintains code style, and realizes the automation and non-intrusive insertion of type definitions.
Smart Images

Figure CN123157176A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer software technology, specifically to a method for automatically generating TypeScript types based on Swagger documentation, applicable to front-end TypeScript projects that automatically generate interface request parameter types and response body types based on Swagger documentation. Background Technology
[0002] In front-end project development, API files typically contain request function definitions, parameter object passing, and response data processing logic. As the number of business APIs continues to grow, front-end developers need to manually write request parameter types, response body types, and related JSDoc comments (i.e., JavaScript documentation comment specifications) for each API. This process is not only highly repetitive but also prone to problems such as inconsistent naming, missing fields, incorrect optional attribute marking, and insufficient type reuse.
[0003] Meanwhile, backend services typically maintain Swagger documentation (i.e., interface description documentation conforming to the OpenAPI specification) to describe interface paths, request methods, request body schemas (i.e., schema definitions), response body schemas, and model reference relationships. However, there is no natural type synchronization mechanism between Swagger documentation and frontend TypeScript interface files. Developers often need to manually copy, organize, and correct Swagger documentation, interface code, and type definition files, resulting in low development efficiency, high maintenance costs, and potential delays in frontend type updates when backend interface schemas change.
[0004] Through research and analysis, existing technologies already exist for automatically generating code based on Swagger documentation. For example, existing automation tools can read the interface definitions in Swagger documentation, convert the data structures into TypeScript type definitions, and output them as independent type definition files; there are also solutions that can generate front-end request code or front-end page code based on Swagger documentation. An objective analysis of the existing technologies reveals the following common problems: First, type definitions are output as independent type definition files, which cannot form a one-to-one correspondence with interface functions in existing interface files. Developers still need to manually move the type definitions and associate them with specific interface functions. Second, it cannot parse the calls to the request client object and their parameter positions in the front-end interface file, and cannot automatically locate the function that needs to generate the type. Third, the generated type definitions cannot be inserted above the target function according to the existing code style and replace the original any type parameter, thus failing to form a complete closed loop. Fourth, common solutions only support a single command-line entry point and cannot be directly called by the AI model using standard protocols in the AI integrated development environment. Fifth, support for $ref references, nested objects, and composite structures such as oneOf, anyOf, and allOf is incomplete, and the writing logic can easily damage the structure and format of the source file.
[0005] Therefore, there is an urgent need for an automatic type generation method for front-end interface files. This method should be able to: identify the functions to be generated based on parsing the interface file; accurately obtain the request parameter schema and response body schema of the corresponding interface from the Swagger documentation; convert the schema into a TypeScript type definition that conforms to the naming conventions; write the generated result to the target TypeScript interface file and update the function signature; and support command-line calls and Model Context Protocol tool calls so that it can be reused in both normal development processes and AI-assisted coding scenarios. Summary of the Invention
[0006] The technical problems to be solved by this invention include: how to automatically parse front-end interface files and identify interface functions using the 'any' type or undefined types; how to accurately locate the target interface definition from the Swagger document and extract the request parameter schema and response body schema; how to convert the Swagger document schema into TypeScript type definitions that conform to naming conventions; how to recursively parse $ref references and avoid generating the same type repeatedly; how to insert the generated type definition above the interface function, while replacing the original 'any' type parameter and keeping the file format unchanged; how to simultaneously support command-line calls and model context protocol tool calls so as to reuse the same capabilities in traditional development and AI-assisted development; and how to provide structured error returns, dry run previews, and configuration file priority control for the generation process.
[0007] To address the aforementioned technical problems, this invention provides a method for automatically generating TypeScript types based on Swagger documentation, comprising the following steps: Parsing step: Reading and parsing the target TypeScript interface file, constructing an Abstract Syntax Tree (AST), identifying request calls to the requesting client object within the function body based on the AST, and extracting the corresponding call information, including Hypertext Transfer Protocol (HTP) information. The process involves: 1) Analyzing the HTTP method, interface path, and parameter types in the TransferProtocol (HTTP) file, recording the function name and line number of the corresponding function called in the request; 2) Determining if the parameter type is "any" or undefined, marking the corresponding function as a pending function if it is, otherwise skipping it; 3) Locating each pending function by matching it against the Swagger documentation based on the HTTP method and interface path in the call information; 4) Locating the target interface definition corresponding to the request call and extracting the request parameter schema and response body schema corresponding to the HTTP method from the target interface definition; 5) Skipping the pending function and recording the reason for the failure; 6) Converting the request parameter schema and response body schema into TypeScript type definitions, generating parameter type definitions and response type definitions corresponding to the pending functions, and establishing type naming derivation rules based on function names; 7) Writing the definition of the pending function in the target TypeScript interface file based on the abstract syntax tree and line numbers, inserting the parameter type definition and response type definition above the definition location using line number-based local text insertion, and updating the parameter type of the pending function to the name of the parameter type definition.
[0008] Preferably, the parsing step further includes: traversing function declarations and arrow functions in the abstract syntax tree, the arrow functions including exported and non-exported forms, identifying calls to predefined methods of the request client object, the predefined methods including get, post, put, and delete methods; wherein, when identifying request calls to the request client object based on the abstract syntax tree, the TypeScript Compiler API is used to perform syntax analysis on the target TypeScript interface file to distinguish request calls to the request client object within the function body from comments, strings, and local variable names.
[0009] Preferably, the process includes a Swagger documentation retrieval step before the location step: receiving an explicitly passed Swagger documentation address, or reading the Swagger documentation address from a preset configuration file; when the Swagger documentation address is a doc.html page address, automatically converting the Swagger documentation address to an application programming interface (API) documentation address, preferentially accessing the / v3 / api-docs path to obtain the OpenAPI 3.0 format Swagger documentation, and if access fails, falling back to the / v2 / api-docs path to obtain the OpenAPI 2.0 (Swagger) document. The Swagger documentation is in 2.0 format, and its sources include remote HTTP address documentation and local JSON (JavaScript Object Notation) documentation. The location steps further include: locating the target interface definition from the paths node of the Swagger documentation; extracting the request parameter schema from the parameters and requestBody fields of the target interface definition; and extracting the response body schema from the responses field of the target interface definition. When there is a prefix difference between the interface path in the call information and the interface path in the Swagger documentation, the interface path is compensated and corrected using a pre-configured path prefix before matching. If the matching still fails after compensation and correction, the pending function is skipped and the reason for the failure is recorded.
[0010] Preferably, the conversion steps further include: mapping the string type in the Swagger document's schema to the string type in TypeScript, mapping the number and integer types to the number type in TypeScript, and mapping the boolean type to the boolean type in TypeScript; mapping the object type to the interface definition or type alias definition; determining whether a field is optional based on the required array in the schema; generating required attributes for fields in the required array and generating optional attributes for fields not in the required array; and retaining the description field in the schema to generate JSDoc comments; and recursively converting and combining the element types in the items attribute of the array type into an array type composed of element types.
[0011] Preferably, the conversion step further includes: maintaining the parsed $ref reference names through the reference record set, recursively parsing the $ref references in the Swagger document, terminating the current recursive branch when it is detected that the $ref reference name already exists in the reference record set, and generating only once for the same type definition; generating a TypeScript union type for the oneOf and anyOf structures in the Swagger document, and generating a TypeScript cross type for the allOf structure in the Swagger document; when the response body schema contains a wrapper structure for the data field, taking the entire wrapper structure containing the data field as the response body type, and taking the inner actual type as the type of the data field in the response body type.
[0012] Preferably, the type naming derivation rule is as follows: after removing the conventional suffix from the function name of the function to be processed, convert it into a PascalCase base name, wherein the conventional suffix includes Api and API, and the conventional suffix is configurable; concatenate the base name with Params to generate the type name of the corresponding request parameter; concatenate the base name with Result to generate the type name of the corresponding response body; concatenate the base name with Data to generate the type name of the inner structure of the data field in the corresponding response body.
[0013] Preferably, the writing step further includes: checking whether a type definition with the same name as the type to be inserted already exists in the target TypeScript interface file before insertion; if it exists, skipping the insertion of that type and not replacing the parameter type of the corresponding function to be processed; inserting the component-level type generated by resolving the $ref reference above the definition position along with the parameter type definition and the response type definition, with the component-level type inserted before the types that reference them; maintaining the indentation, blank lines, and comment style of the target TypeScript interface file unchanged; and replacing the original any type parameter of the function to be processed with the name of the generated parameter type definition.
[0014] Preferably, the method further includes a configuration management step: before executing the parsing step, a preset configuration file is read. The configuration items in the configuration file include the Swagger documentation address, a list of default target file paths, a path prefix, a client name, and an output style. The default value for the client name is requestClient, and the default value for the output style is interface. For necessary configuration items that do not have valid default values, if a corresponding explicit command-line parameter exists, the explicit parameter is used first. If the explicit parameter is missing, the corresponding configuration item in the configuration file is used. If both the explicit parameter and the corresponding configuration item in the configuration file are missing, a structured error message containing the reason for failure is generated and returned, and the current processing flow is terminated.
[0015] Preferably, the method further includes a preview and output step: In trial run preview mode, the parsing step, the positioning step, and the conversion step are executed, and the insertion position determination operation and the same-name type check operation in the writing step are executed, but the type insertion operation and parameter type update operation in the writing step are not executed, and the change summary and the type content to be generated are returned; In non-preview mode, after executing the writing step, the generated type list, modified file path, statistical summary, and error information are returned as structured response data. The statistical summary includes the total number of functions to be processed, the number of successfully processed functions, the number of skipped functions, the number of failed functions, and the reasons for their failures; When the number of functions to be processed is zero, an empty result prompt is returned; When an exception occurs during execution, structured response data containing error information is returned.
[0016] Preferably, the method further includes a model context protocol exposure step: starting a service through the model context protocol and exposing a type generation tool interface to the artificial intelligence integrated development environment through the service; the type generation tool interface receives input parameters including the target file path, Swagger document address, function filtering information and preview mode identifier, and calls the shared core engine to perform parsing, positioning, transformation and writing steps; and returns a list of generated types, modified file paths, statistical summaries and error information in structured response data, with the error information uniformly placed in the error array of the structured response data.
[0017] Corresponding to the above methods, this invention adopts a collaborative architecture of an interface file parsing module, a Swagger acquisition module, a schema conversion module, a file writing module, a configuration management module, and a model context protocol exposure module, such as... Figure 1 As shown. The interface file parsing module parses the target TypeScript interface file, identifying the request call to the requesting client object and its context information; the Swagger acquisition module retrieves the target interface definition from the Swagger documentation, ensuring compatibility with different documentation sources; the schema conversion module converts the Swagger documentation schema into TypeScript type definitions, including $ref reference resolution and deduplication; the file writing module writes the generated type definitions to the target TypeScript interface file and updates parameter types; the configuration management module reads the preset configuration file and provides runtime parameters to each processing module; the model context protocol exposure module exposes the type generation function as a type generation tool interface through the model context protocol, allowing direct calls from the AI integrated development environment. The command-line entry and the model context protocol exposure module share the same core processing flow.
[0018] Compared with the prior art, the present invention has the following beneficial effects:
[0019] First, it significantly improves the efficiency of type writing. By parsing the target TypeScript interface file to build an abstract syntax tree, it automatically identifies request calls to the requesting client object and automatically determines whether the parameter type is any or undefined, thereby automatically locating the function to be processed. This avoids manual searching and annotation, automating the repetitive work of writing request parameter types and response body types.
[0020] Second, enhance the consistency between front-end and back-end interfaces. By accurately locating the target interface definition in the Swagger document through the HTTP method and interface path in the call information, and supporting path prefix compensation correction, the request parameter schema and response body schema are extracted to ensure that the front-end type definition and the back-end interface definition are from the same source, reducing the risk of inconsistent interface fields, inconsistent naming, and type mismatch.
[0021] Third, it reduces maintenance difficulty. By maintaining the resolved $ref reference names through a collection of reference records, duplicates are automatically removed during recursive resolution, avoiding the burden of manually tracking complex reference relationships. When the backend interface schema changes, the type definition can be quickly updated by re-executing this method, reducing the amount of synchronization work.
[0022] Fourth, it enhances the expressive power of complex schemas. Through recursive parsing and deduplication of $ref references, handling of nested objects, generating union types from oneOf and anyOf structures, generating cross types from allOf structures, and extracting the inner actual type from the wrapper structure containing data fields, it achieves complete and correct transformation of complex schema structures, covering a wider range of Swagger documentation scenarios.
[0023] Fifth, it adapts to multiple use cases. The command-line entry and the model context protocol exposure module share the same core processing flow, enabling developers to run the code in batches on the terminal or have the AI model directly call the type generation tool interface in the AI integrated development environment, thus achieving the reuse of the same capability in different use cases.
[0024] Sixth, maintain code style and maintainability. The generated type definitions follow a unified type naming derivation rule and are written to the target TypeScript interface file through line number-based local text insertion. This is combined with a name-matching mechanism to avoid duplicate insertion, achieving non-intrusive type injection while maintaining the source file indentation, blank lines, and comment style.
[0025] Seventh, improve the security and controllability of the tool. In dry run preview mode, only a change summary and the type content to be generated are returned without actually writing to the file; for fatal exceptions such as missing configuration, a structured error message containing the reason for failure is generated and returned, and the current processing flow is terminated; for local exceptions such as failure to match the target interface definition, the corresponding pending function is skipped and the reason for failure is recorded, forming a complete exception handling closed loop. Attached Figure Description
[0026] Figure 1 This is a schematic diagram of the overall module architecture of the TypeScript type automatic generation method based on Swagger documentation of the present invention.
[0027] Figure 2 This is a schematic diagram illustrating the process of converting the Swagger document's schema into a TypeScript type definition according to the present invention.
[0028] Figure 3 This is a schematic diagram of the command-line mode interaction process of the present invention.
[0029] Figure 4 This is a schematic diagram of the interaction process of the model context protocol mode of the present invention. Detailed Implementation
[0030] The technical solution of the present invention will now be described in detail with reference to the accompanying drawings and specific embodiments. Figure 1 The overall modular architecture of the present invention is illustrated. Figure 2 The detailed process of schema transformation is illustrated. Figure 3 This illustrates the interaction flow in command-line mode. Figure 4 The interaction flow under the Model Context Protocol (MTP) mode is illustrated below. The following examples are for illustrative purposes only and should not be considered as limiting the scope of protection of this invention.
[0031] Example 1: Interface function identification and function tagging based on abstract syntax tree parsing.
[0032] This embodiment describes in detail how to parse the target TypeScript interface file based on the abstract syntax tree and identify the request call of the type to be generated. See also Figure 1 The interface file parsing module in [the system / platform].
[0033] Step 101: Use the TypeScript compiler application programming interface to create an abstract syntax tree parser, read the source code of the target TypeScript interface file, and generate the corresponding abstract syntax tree. The TypeScript compiler application programming interface can perform syntax analysis on the target TypeScript interface file to distinguish between request calls to client objects within function bodies and comments, strings, and local variable names, avoiding misinterpreting similar text appearing in comments or strings as request calls.
[0034] Step 102: Traverse the function declarations and arrow functions in the abstract syntax tree, including exported and non-exported forms of arrow functions, and identify calls to predefined methods of the request client object within the function body. The predefined methods include get, post, put, and delete methods.
[0035] Step 103: Extract the corresponding call information from the identified request call. The call information includes the HTTP method, interface path, and parameter type. The HTTP method is determined from the method name (get, post, put, delete) of the request call, the interface path is extracted from the first parameter of the request call, and the parameter type is extracted from the type annotation of the corresponding parameter of the function to which the request call belongs.
[0036] Step 104: Determine whether the extracted parameter type is "any" or undefined. If yes, mark the function corresponding to the request call as a function to be processed; if no, it means that the function already has a defined type, skip the function, and no processing is required.
[0037] Step 105: Record the function name of the function to be processed, its definition location (line number) in the target TypeScript interface file, the corresponding HTTP method, and the interface path, so that subsequent steps can be performed for Swagger document location, type naming, and file writing.
[0038] This embodiment uses the TypeScript compiler application programming interface for abstract syntax tree analysis to accurately identify function declarations and request calls to client objects, effectively avoiding misjudgment problems that may be caused by regular expression matching and improving the accuracy of function identification.
[0039] Example 2: Obtaining Swagger documentation and defining and locating the target interface.
[0040] This embodiment details how to obtain the Swagger document, and how to locate the target interface definition in the Swagger document and extract the request parameter schema and response body schema based on the call information. See [link to relevant documentation]. Figure 1 The Swagger retrieval module in [the project / company].
[0041] Step 201: Receive the explicitly passed Swagger document address, or read the Swagger document address from a preset configuration file. If an explicitly passed Swagger document address exists, use that address first; if not explicitly passed, fall back to reading the Swagger document address configuration item in the configuration file; if both are missing, generate and return a structured error message containing the reason for failure and terminate the current processing flow.
[0042] Step 202: When the Swagger documentation address is a doc.html page address, automatically convert the Swagger documentation address to an application programming interface (API) documentation address: prioritize accessing the / v3 / api-docs path to obtain the OpenAPI 3.0 format Swagger documentation; if access fails, fall back to the / v2 / api-docs path to obtain the OpenAPI 2.0 (Swagger 2.0) format Swagger documentation. Both remote HTTP address documentation and local JSON document documentation are supported.
[0043] Step 203: Based on the HTTP method and interface path in the call information, perform a match in the paths node of the Swagger document: search for a path template that matches the interface path in the paths node, and then search for the operation object that matches the HTTP method in that path template, thereby locating the target interface definition. If the match is successful, the target interface definition corresponding to the request call is obtained; if the match fails, the corresponding pending function is skipped and the reason for the failure is recorded, and the remaining pending functions are processed.
[0044] Step 204: When there is a prefix difference between the interface path in the call information and the interface path in the Swagger documentation, the interface path is compensated and corrected using the pre-configured path prefix before matching. For example, if the interface path in the front-end code is " / algo / user / list" while the interface path in the Swagger documentation is " / user / list", the path prefix configuration item in the configuration file can be set to " / algo". Before matching, the " / algo" prefix in the front-end interface path will be automatically removed, allowing the matching to proceed successfully. If the matching still fails after compensation and correction, the corresponding pending function is skipped, the reason for the failure is recorded, and the remaining pending functions are processed.
[0045] Step 205: Extract the request parameter schema corresponding to the HTTP method from the target interface definition. Specifically, extract the request parameter schema from the parameters field (applicable to requests using query parameters such as GET methods) and the requestBody field (applicable to requests using request bodies such as POST methods and PUT methods) in the target interface definition.
[0046] Step 206: Extract the response body schema corresponding to the HTTP method from the response field defined in the target interface, specifically extracting the response body structure corresponding to the success status code (e.g., 200 or 201).
[0047] This embodiment achieves precise alignment between the front-end interface path and the Swagger document path through a dual matching mechanism of interface path and HTTP method, combined with automatic conversion of doc.html format address, priority fallback of / v3 / api-docs and / v2 / api-docs, path prefix compensation correction, and a handling method of skipping and recording the failure reason when matching fails. Even when the front-end and back-end path naming is inconsistent or the document version is different, the target interface definition can be accurately located.
[0048] Example 3: Conversion of Swagger document Schema to TypeScript type definition.
[0049] This embodiment describes in detail how to convert the extracted request parameter Schema and response body Schema into TypeScript type definitions, corresponding to... Figure 2 The process shown is as follows: Figure 2 The markers S301 to S307 in the text correspond to steps 301 to 307 below, respectively.
[0050] Step 301: Determine if the Schema is a basic type. If so, map the basic types in the Swagger document's Schema to TypeScript basic types, specifically as follows: string type maps to string type; number and integer types map to number type; boolean type maps to boolean type.
[0051] Step 302: Determine if the Schema is an object type. If so, convert the object type Schema into a TypeScript interface definition or type alias definition. The output style is determined by the output style configuration option in the configuration file, with the default being interface definition. When generating the type definition, retain the description field in the Schema to generate JSDoc comments, and automatically determine whether fields are optional according to the required array: fields in the required array are generated as required properties, and fields not in the required array are generated as optional properties.
[0052] Step 303: Determine if the Schema is an array type. If so, extract the element types from the items attribute of the array type Schema, recursively call the type conversion method to generate the element types, and then combine them into an array type composed of the element types.
[0053] Step 304: Determine if the Schema contains $ref references. If so, maintain the parsed $ref reference names through the reference record set and recursively parse the $ref references in the Swagger document. Specifically, when parsing a $ref reference, first check if the $ref reference name already exists in the reference record set; if it already exists, reuse the generated type name, do not generate it again, and terminate the current recursive branch to avoid infinite recursion caused by circular references; if it does not exist, add the $ref reference name to the reference record set, parse the target Schema pointed to by the $ref reference, generate the corresponding type definition, and use the name of the target Schema in the components / schemas node of the Swagger document as its type name; if the target Schema is not defined in the components / schemas node, generate a unique type name based on the Schema structure characteristics using Pascal's naming style (e.g., generate a unique identifier based on the combination of fields in the Schema), and recursively process the nested $ref references contained in the target Schema. The same type definition is generated only once, and the result of the first generation is reused when referenced in multiple places, ensuring the simplicity of the generated code and avoiding duplicate definitions.
[0054] Step 305: Determine if the schema is a composite structure. For the oneOf and anyOf structures in the Swagger document's schema, generate a TypeScript union type, which is mapped to a TypeScript union type. For the allOf structure, generate a TypeScript cross type, indicating that the combination of all schemas must be satisfied simultaneously.
[0055] Step 306: Determine if the response body schema contains a nested data wrapper structure. If so, use the entire wrapper structure as the response body type, and use the inner actual type as the type of the data field in the response body type. For example, if the response body schema is a wrapper object with an outer data field, and the value of the data field is an object containing id and name fields, then generate the response body type corresponding to the outer wrapper structure (e.g., ××Result), and use the inner object as the type of the data field in the response body type (e.g., ××Data).
[0056] Step 307: Generate type names based on the type naming derivation rules of the function name. Remove the conventional suffix (e.g., Api, API, which is configurable) from the function name of the function to be processed, convert it to a Pascal-style base name, and then generate three type names according to the following rules: concatenate the base name with Params to generate the type name corresponding to the request parameter; concatenate the base name with Result to generate the type name corresponding to the response body; concatenate the base name with Data to generate the type name corresponding to the inner structure of the data field in the response body. For example, the function name getUserListApi is converted to the base name GetUserList, resulting in three type names: GetUserListParams, GetUserListResult, and GetUserListData.
[0057] This embodiment achieves automatic deduplication during recursive parsing by referencing a set of records. It correctly supports complex Swagger document structures by generating union types from oneOf and anyOf structures and cross types from allOf structures through differentiated conversion. It accurately handles common response formats by extracting the inner type of the data wrapper structure. Furthermore, it adopts a unified naming rule based on Pascal's naming style to ensure the naming standardization, correctness, and readability of the generated type definitions.
[0058] Example 4: Non-intrusive file writing and type replacement.
[0059] This embodiment describes in detail how to write the generated parameter type definition and response type definition into the target TypeScript interface file and replace the original any type parameter. See [link to documentation]. Figure 1 The file writing module in [the system / platform].
[0060] Step 401: Based on the abstract syntax tree and the line numbers recorded in step 105, determine the definition position of the function to be processed in the target TypeScript interface file, that is, the start line number and end line number of the function, and use the line above the definition position (that is, the line before the start of the function declaration or function expression) as the insertion position of the type definition.
[0061] Step 402: Before inserting the type definition, check if a type definition with the same name as the type to be inserted already exists in the target TypeScript interface file. Specifically, traverse all type definition nodes in the abstract syntax tree (including interface declarations and type alias declarations) and compare the node names with the name of the type to be inserted.
[0062] Step 403: If a type definition with the same name already exists in the target TypeScript interface file, skip the insertion of that type and do not replace the parameter type of the corresponding function to be processed, so as to avoid overwriting the existing custom type definition; if no type definition with the same name exists, perform the subsequent insertion and replacement operations.
[0063] Step 404: Using line number-based local text insertion, insert the generated parameter type definitions and response type definitions above the function definition location. This method does not rewrite the entire file, but performs local text insertion at the determined target line number position, thereby preserving the indentation, blank lines, and comment style of the target TypeScript interface file to the greatest extent possible.
[0064] Step 405: Update the parameter type of the function to be processed from the original "any" type to the name of the generated parameter type definition. Specifically, locate the parameter type annotation node of the function in the abstract syntax tree and replace its type reference with the name of the generated parameter type definition.
[0065] Step 406: In the trial run preview mode, execute steps 101 to 105, 201 to 206, and 301 to 307 in their entirety, and perform the insertion position determination in step 401 and the same-name type check in step 402. However, do not perform the type insertion operation in step 404 and the parameter type update operation in step 405. Instead, return a change summary and the type content to be generated, allowing users to review the changes that will occur before actually modifying the code, thereby improving the security of tool use.
[0066] Step 407: After performing the write operation in non-preview mode, return the processing result as structured response data, including: a list of generated types, modified file paths, a statistical summary, and error messages. The statistical summary includes: the total number of functions to be processed, the number successfully processed, the number skipped (skipped because a type with the same name already exists or because the parameter type is known), the number of failures, and the reasons for their failures. When the number of functions to be processed is zero, return an empty result message.
[0067] This embodiment achieves non-intrusive file writing through line number-based local text insertion, provides a secure preview mechanism before operation through a dry run preview mode, and provides complete execution result feedback through structured response data, thereby improving the controllability of the tool while ensuring code quality.
[0068] Example 5: Dual-entry interaction process of command line mode and model context protocol mode.
[0069] This embodiment describes in detail how to simultaneously support two interaction modes: command-line invocation and model context protocol tool invocation, with both modes sharing the same core processing flow.
[0070] See the command-line mode interaction process. Figure 3 , Figure 3 The numbers 1 to 12 next to the message arrows indicate the order of the interaction messages. The user initiates a type generation request via the terminal command line, specifying parameters such as the target TypeScript interface file path, Swagger document address, and preview mode identifier (Message 1); the command line entry reads the configuration file and merges the execution parameters according to priority, with explicit command-line parameters having higher priority than those in the configuration file (Messages 2 and 3); subsequently, the command line entry calls the interface file parsing module to parse the target TypeScript interface file (Message 4), and the interface file parsing module identifies and marks the functions to be processed (Message 5); the interface file parsing module provides the call information to the Swagger acquisition module and requests the target interface definition (Message 6); the Swagger acquisition module provides the request parameter schema and response body schema to the schema conversion module (Message 7); the schema conversion module generates parameter type definitions and response type definitions (Message 8) and provides them to the file writing module (Message 9); the file writing module inserts the type definitions and updates the parameter types, but does not actually write them in dry run preview mode (Message 10); the file writing module returns a processing summary, i.e., structured response data, to the command line entry (Message 11); the command line entry outputs the processing result or dry run preview content to the user (Message 12). The command-line mode supports the following command-line parameters: File path parameter, used to specify the target TypeScript interface file path; if not passed, the default target file path in the configuration file is used. Swagger address parameter, used to specify the Swagger documentation address; if not passed, the Swagger documentation address in the configuration file is used. Preview enable parameter, used to enable dry run preview mode; disabled by default. Function filter parameter, used to specify to process only specific functions; multiple function names can be separated by commas. JSON output parameter, used to output the processing results in structured JSON format. Silent success log parameter, used to silently (without output) success logs. Path prefix parameter, used to specify the path prefix and override the corresponding configuration item in the configuration file. Client name parameter, used to specify the name of the request client object and override the corresponding configuration item in the configuration file.
[0071] See Model Context Protocol Pattern Interaction Flow Figure 4 , Figure 4The numbers 1 to 10 next to the message arrows indicate the order of the interaction messages. The user initiates a type generation request through an AI integrated development environment (such as Cursor, Kiro, etc.). The AI integrated development environment calls the type generation tool interface registered with the Model Context Protocol Service, passing in input parameters such as the target file path, Swagger documentation address, function filtering information, and preview mode identifier (Message 1); the Model Context Protocol Service reads the configuration file and determines the parameter priority (Messages 2, 3); subsequently, the Model Context Protocol Service calls the shared core engine: calling the interface file parsing module to parse the target TypeScript interface file (Message 4); the interface file parsing module provides the call information to the Swagger acquisition module and requests the target interface definition (Message 5); the Swagger acquisition module provides the request parameter Schema and response body Schema to the Schema conversion module (Message 6); the Schema conversion module generates parameter type definitions and response type definitions and provides them to the file writing module (Message 7); the file writing module writes the file or executes a preview (Message 8); the file writing module returns structured response data to the Model Context Protocol Service (Message 9); the Model Context Protocol Service returns a list of generated types, modified file paths, statistical summaries, and an error array to the AI integrated development environment (Message 10). Specifically, the Model Context Protocol (MGP) exposure steps include: starting the Standard Input / Output (stdio) service using the MGP software development kit; exposing the type generation tool interface to the AI integrated development environment through the service; receiving input parameters such as the target file path, Swagger document address, function filtering information, and preview mode identifier; reusing the shared core engine to complete parsing, positioning, transformation, and writing; and returning a list of generated types, modified file paths, statistical summaries, and error messages as structured response data.
[0072] This embodiment supports both command line and model context protocol call entry points by sharing the core engine, so that the same set of type generation capabilities can be used in both traditional terminal batch processing scenarios and artificial intelligence-assisted coding scenarios, realizing function reuse and scenario expansion.
[0073] Example 6: Configuration Management and Structured Error Return Mechanism.
[0074] This embodiment details the complete workflow of the configuration management module and its structured error return mechanism. See [link to documentation]. Figure 1 The configuration management module in [the system / platform].
[0075] Configuration Management Steps: Before executing the parsing step, a preset configuration file is read from the current working directory. In this embodiment, the configuration file is named swagger-ts-gen.config.json. If the configuration file exists and is correctly formatted, the following configuration items in the configuration file are parsed: Swagger documentation address; default target file path, i.e., the list of default processed interface file paths; path prefix, i.e., the interface path prefix used for path compensation and correction; client name, i.e., the name of the request client object, with a default value of "requestClient"; output style, i.e., the type output style, which can be either "interface" or "type", with the default being "interface". If the configuration file does not exist or is incorrectly formatted, the explicit command-line parameters are used. The following priority rules are established between command-line parameters and configuration files: For each configuration item, when a corresponding explicit command-line parameter exists, the explicit parameter is used first; when the explicit parameter is missing, the corresponding configuration item in the configuration file is used; when both the explicit parameter and the corresponding configuration item in the configuration file are missing, a structured error message containing the reason for failure is generated and returned, and the current processing flow is terminated. Therefore, the process can still run normally even if the configuration file is missing or incorrectly formatted, but all necessary configuration items can be provided by explicit parameters from the command line.
[0076] Structured Error Return Mechanism: Structured error messages are returned for the following exceptions to avoid throwing uncaught exceptions: Network exceptions (e.g., failure to retrieve Swagger documentation): A structured error message containing the reason for the failure is generated. Target interface definition not found: If the target interface definition cannot be matched in the Swagger documentation, the corresponding pending function is skipped, the reason for failure is recorded, and the remaining pending functions are processed. If matching still fails after path compensation correction, the corresponding pending function is also skipped, and the reason for failure is recorded. Parsing failure: If the target TypeScript interface file is parsed incorrectly, a structured error message containing the reason for failure is generated. Write failure: If a file write error occurs, the error message is included in the structured response data. Configuration loss: If both explicit command-line parameters and corresponding configuration items in the configuration file are missing, a structured error message containing the reason for failure is generated and returned, and the current processing flow is terminated. In model context protocol mode, error messages are uniformly placed in the error array of the structured response data to maintain protocol layer stability.
[0077] This embodiment achieves flexible configuration control through centralized management of configuration files and flexible overriding of command-line parameters. It ensures diagnosability and continuity of batch processing in abnormal situations through a structured error return mechanism that distinguishes between fatal exceptions and local exceptions. It also achieves robust system operation under various abnormal scenarios through complete boundary condition handling.
[0078] The above description is merely a preferred embodiment of the present invention and is not intended to limit the invention. Various modifications and variations can be made to the present invention by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.
Claims
1. A method for automatically generating TypeScript types based on Swagger documentation, characterized in that, Includes the following steps: Parsing steps: Read and parse the target TypeScript interface file, construct an abstract syntax tree, identify request calls to the requesting client object within the function body based on the abstract syntax tree, extract the call information corresponding to the request call, including the HTTP method, interface path, and parameter type, and record the function name and line number of the function corresponding to the request call; determine whether the parameter type is any or undefined. If so, mark the function corresponding to the request call as a function to be processed; otherwise, skip the function corresponding to the request call. Location steps: For each function to be processed, match it in the Swagger document according to the HTTP method and the interface path in the call information; if the match is successful, locate the target interface definition corresponding to the request call, and extract the request parameter schema and response body schema corresponding to the HTTP method from the target interface definition; If the match fails, skip the function to be processed and record the reason for the failure; Conversion steps: Convert the request parameter schema and the response body schema into TypeScript type definitions respectively, generate parameter type definitions and response type definitions corresponding to the function to be processed, and establish type naming derivation rules based on function names; as well as Writing steps: Based on the abstract syntax tree and the line number, determine the definition position of the function to be processed in the target TypeScript interface file, insert the parameter type definition and the response type definition above the definition position by local text insertion based on line number, and update the parameter type of the function to be processed to the name of the parameter type definition.
2. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, The parsing step further includes: traversing function declarations and arrow functions in the abstract syntax tree, the arrow functions including exported and non-exported forms, identifying calls to predefined methods of the request client object, the predefined methods including get, post, put, and delete methods; wherein, when identifying request calls to the request client object based on the abstract syntax tree, the target TypeScript interface file is parsed using the TypeScript compiler application programming interface to distinguish request calls to the request client object within function bodies from comments, strings, and local variable names.
3. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, The positioning step is preceded by a Swagger document retrieval step: receiving an explicitly passed Swagger document address, or reading the Swagger document address from a preset configuration file; when the Swagger document address is a doc.html page address, automatically converting the Swagger document address into an application programming interface document address, preferentially accessing the / v3 / api-docs path to obtain the OpenAPI 3.0 format Swagger document, and if the access fails, falling back to access the / v2 / api-docs path to obtain the OpenAPI 2.0 (Swagger 2.0) format Swagger document, the source of the Swagger document includes remote HTTP address documents and local JSON documents; The location step further includes: locating the target interface definition from the paths node of the Swagger document; extracting the request parameter schema from the parameters and requestBody fields of the target interface definition; and extracting the response body schema from the responses field of the target interface definition; wherein, when there is a prefix difference between the interface path in the call information and the interface path in the Swagger document, the interface path in the call information is compensated and corrected by a pre-configured path prefix before matching; if the matching still fails after compensation and correction, the pending function is skipped and the reason for failure is recorded.
4. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, The conversion steps further include: mapping the string type in the Swagger document's schema to the string type in TypeScript, mapping the number and integer types to the number type in TypeScript, and mapping the boolean type to the boolean type in TypeScript; mapping the object type to an interface definition or type alias definition; determining whether a field is optional based on the required array in the schema; generating required attributes for fields in the required array and generating optional attributes for fields not in the required array; and retaining the description field in the schema to generate JSDoc comments; and recursively converting and combining the element types in the items attribute of the array type into an array type composed of element types.
5. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, The transformation step further includes: maintaining the parsed $ref reference names through a reference record set, and recursively parsing $ref references in the Swagger document: when parsing a $ref reference, first check whether the $ref reference name already exists in the reference record set. If it already exists, reuse the generated type name, do not generate it again, and terminate the current recursive branch; if it does not exist, add the $ref reference name to the reference record set, parse the target schema pointed to by the $ref reference to generate the corresponding type definition, and use the name of the target schema in the components / schemas node of the Swagger document as its type name. If the target schema is not in the components / schemas node of the Swagger document, the type name is not generated again. If defined in the onents / schemas node, a unique type name based on the schema structure characteristics is generated using Pascal's naming style, and nested $ref references contained in the target schema are processed recursively; the same type definition is generated only once; a TypeScript union type is generated for the oneOf and anyOf structures in the Swagger document, and a TypeScript cross type is generated for the allOf structure in the Swagger document; and when the response body schema contains a wrapper structure for a data field, the entire wrapper structure containing the data field is used as the response body type, and the inner actual type is used as the type of the data field in the response body type.
6. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, The type naming derivation rule is as follows: The function name of the function to be processed is converted into a Pascal-style base name after removing the conventional suffix at the end. The conventional suffix includes at least Api and API, and the conventional suffix is configurable. The base name is concatenated with Params to generate the type name of the corresponding request parameter. The base name is concatenated with Result to generate the type name of the corresponding response body. Finally, the base name is concatenated with Data to generate the type name of the inner structure of the data field in the corresponding response body.
7. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, The writing step further includes: checking whether a type definition with the same name as the type to be inserted already exists in the target TypeScript interface file before insertion; if it exists, skipping the insertion of that type and not replacing the parameter type of the corresponding function to be processed; inserting the component-level type generated by resolving the $ref reference above the definition position along with the parameter type definition and the response type definition, with the component-level type inserted before the types that reference them; maintaining the indentation, blank lines, and comment style of the target TypeScript interface file unchanged; and replacing the original any type parameter of the function to be processed with the name of the generated parameter type definition.
8. The method for automatically generating TypeScript types based on Swagger documentation according to any one of claims 1 to 7, characterized in that, It also includes a configuration management step: before performing the parsing step, a preset configuration file is read. The configuration items of the configuration file include the Swagger documentation address, the default target file path list, the path prefix, the client name, and the output style. The default value of the client name is requestClient, and the default value of the output style is interface. For necessary configuration items that do not have valid default values, if a corresponding explicit command-line parameter exists, the explicit parameter is used first; if the explicit parameter is missing, the corresponding configuration item in the configuration file is used; if both the explicit parameter and the corresponding configuration item in the configuration file are missing, a structured error message containing the reason for failure is generated and returned, and the current processing flow is terminated.
9. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, It also includes a preview and output step: In the trial run preview mode, the parsing step, the positioning step and the conversion step are executed, and the insertion position determination operation and the same name type check operation in the writing step are executed, but the type insertion operation and parameter type update operation in the writing step are not executed, and the change summary and the type content to be generated are returned; In non-preview mode, after performing the write step, a list of generated types, modified file paths, statistical summaries, and error messages are returned as structured response data. The statistical summaries include the total number of pending functions, the number of successfully processed functions, the number of skipped functions, the number of failed functions, and the reasons for their failures. When the number of pending functions is zero, an empty result is returned. When an exception occurs during execution, a structured response data containing error information is returned.
10. The method for automatically generating TypeScript types based on Swagger documentation according to claim 1, characterized in that, It also includes a model context protocol exposure step: starting the service through the model context protocol, and exposing a type generation tool interface to the artificial intelligence integrated development environment through the service; the type generation tool interface receives input parameters including the target file path, Swagger document address, function filtering information and preview mode identifier, and calls the shared core engine to execute the parsing step, the positioning step, the conversion step and the writing step; The structured response data returns a list of generated types, modified file paths, statistical summaries, and error messages, with the error messages uniformly placed in the error array of the structured response data.
