|
| 1 | +import type { InternalRoute } from 'elysia' |
| 2 | +import { |
| 3 | + readFileSync, |
| 4 | + mkdirSync, |
| 5 | + writeFileSync, |
| 6 | + rmSync, |
| 7 | + existsSync, |
| 8 | + cpSync |
| 9 | +} from 'fs' |
| 10 | +import { TypeBox } from '@sinclair/typemap' |
| 11 | + |
| 12 | +import { tmpdir } from 'os' |
| 13 | +import { join } from 'path' |
| 14 | +import { spawnSync } from 'child_process' |
| 15 | +import { AdditionalReference, AdditionalReferences } from '../types' |
| 16 | + |
| 17 | +const matchRoute = /: Elysia<(.*)>/gs |
| 18 | +const matchStatus = /(\d{3}):/gs |
| 19 | +const wrapStatusInQuote = (value: string) => value.replace(matchStatus, '"$1":') |
| 20 | + |
| 21 | +const exec = (command: string, cwd: string) => |
| 22 | + spawnSync(command, { |
| 23 | + shell: true, |
| 24 | + cwd, |
| 25 | + stdio: 'inherit' |
| 26 | + }) |
| 27 | + |
| 28 | +interface OpenAPIGeneratorOptions { |
| 29 | + /** |
| 30 | + * Path to tsconfig.json |
| 31 | + * @default tsconfig.json |
| 32 | + */ |
| 33 | + tsconfigPath?: string |
| 34 | + |
| 35 | + /** |
| 36 | + * Name of the Elysia instance |
| 37 | + * |
| 38 | + * If multiple instances are found, |
| 39 | + * instanceName should be provided |
| 40 | + */ |
| 41 | + instanceName?: string |
| 42 | + |
| 43 | + /** |
| 44 | + * Project root directory |
| 45 | + * |
| 46 | + * @default process.cwd() |
| 47 | + */ |
| 48 | + projectRoot?: string |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Auto generate OpenAPI schema from Elysia instance |
| 53 | + * |
| 54 | + * It's expected that this command should run in project root |
| 55 | + * |
| 56 | + * @experimental use at your own risk |
| 57 | + */ |
| 58 | +export const fromTypes = |
| 59 | + ( |
| 60 | + /** |
| 61 | + * Path to file where Elysia instance is |
| 62 | + * |
| 63 | + * The path must export an Elysia instance |
| 64 | + */ |
| 65 | + targetFilePath: string, |
| 66 | + { |
| 67 | + tsconfigPath = 'tsconfig.json', |
| 68 | + instanceName, |
| 69 | + projectRoot = process.cwd() |
| 70 | + }: OpenAPIGeneratorOptions = {} |
| 71 | + ) => |
| 72 | + () => { |
| 73 | + if (!targetFilePath.endsWith('.ts') && !targetFilePath.endsWith('.tsx')) |
| 74 | + throw new Error('Only .ts files are supported') |
| 75 | + |
| 76 | + const tmpRoot = join(tmpdir(), '.ElysiaAutoOpenAPI') |
| 77 | + |
| 78 | + if (existsSync(tmpRoot)) |
| 79 | + rmSync(tmpRoot, { recursive: true, force: true }) |
| 80 | + mkdirSync(tmpRoot, { recursive: true }) |
| 81 | + |
| 82 | + const extendsRef = existsSync(join(projectRoot, 'tsconfig.json')) |
| 83 | + ? `"extends": "${join(projectRoot, 'tsconfig.json')}",` |
| 84 | + : '' |
| 85 | + |
| 86 | + if (!join(projectRoot, targetFilePath)) |
| 87 | + throw new Error('Target file does not exist') |
| 88 | + |
| 89 | + writeFileSync( |
| 90 | + join(tmpRoot, tsconfigPath), |
| 91 | + `{ |
| 92 | + ${extendsRef} |
| 93 | + "compilerOptions": { |
| 94 | + "lib": ["ESNext"], |
| 95 | + "module": "ESNext", |
| 96 | + "noEmit": false, |
| 97 | + "moduleResolution": "bundler", |
| 98 | + "skipLibCheck": true, |
| 99 | + "skipDefaultLibCheck": true, |
| 100 | + "emitDeclarationOnly": true, |
| 101 | + "outDir": "./dist" |
| 102 | + }, |
| 103 | + "include": ["${join(projectRoot, targetFilePath)}"] |
| 104 | + }` |
| 105 | + ) |
| 106 | + |
| 107 | + exec(`tsc`, tmpRoot) |
| 108 | + |
| 109 | + try { |
| 110 | + const declaration = readFileSync( |
| 111 | + join( |
| 112 | + tmpRoot, |
| 113 | + 'dist', |
| 114 | + targetFilePath |
| 115 | + .replace(/.tsx$/, '.ts') |
| 116 | + .replace(/.ts$/, '.d.ts') |
| 117 | + ), |
| 118 | + 'utf8' |
| 119 | + ) |
| 120 | + |
| 121 | + // Check just in case of race-condition |
| 122 | + if (existsSync(tmpRoot)) |
| 123 | + rmSync(tmpRoot, { recursive: true, force: true }) |
| 124 | + |
| 125 | + let instance = declaration.match( |
| 126 | + instanceName |
| 127 | + ? new RegExp(`${instanceName}: Elysia<(.*)`, 'gs') |
| 128 | + : matchRoute |
| 129 | + )?.[0] |
| 130 | + |
| 131 | + if (!instance) return |
| 132 | + |
| 133 | + // Get 5th generic parameter |
| 134 | + // Elysia<'', {}, {}, {}, Routes> |
| 135 | + // ------------------------^ |
| 136 | + // 1 2 3 4 5 |
| 137 | + // We want the 4th one |
| 138 | + for (let i = 0; i < 3; i++) |
| 139 | + instance = instance.slice(instance.indexOf('}, {', 3)) |
| 140 | + |
| 141 | + const routesString = |
| 142 | + wrapStatusInQuote(instance).slice( |
| 143 | + 3, |
| 144 | + instance.indexOf('}, {', 3) |
| 145 | + ) + '}\n}\n' |
| 146 | + |
| 147 | + const routes: AdditionalReference = {} |
| 148 | + |
| 149 | + for (let route of routesString.slice(1).split('} & {')) { |
| 150 | + route = '{' + route + '}' |
| 151 | + let schema = TypeBox(route) |
| 152 | + |
| 153 | + if (schema.type !== 'object') continue |
| 154 | + |
| 155 | + const paths = [] |
| 156 | + |
| 157 | + while (true) { |
| 158 | + const keys = Object.keys(schema.properties) |
| 159 | + if (!keys.length || keys.length > 1) break |
| 160 | + |
| 161 | + paths.push(keys[0]) |
| 162 | + |
| 163 | + schema = schema.properties[keys[0]] as any |
| 164 | + if (!schema?.properties) break |
| 165 | + } |
| 166 | + |
| 167 | + const method = paths.pop()! |
| 168 | + const path = '/' + paths.join('/') |
| 169 | + schema = schema.properties |
| 170 | + |
| 171 | + if (schema?.response?.type === 'object') { |
| 172 | + const responseSchema: Record<string, any> = {} |
| 173 | + |
| 174 | + for (const key in schema.response.properties) |
| 175 | + responseSchema[key] = schema.response.properties[key] |
| 176 | + |
| 177 | + schema.response = responseSchema |
| 178 | + } |
| 179 | + |
| 180 | + if (!routes[path]) routes[path] = {} |
| 181 | + // @ts-ignore |
| 182 | + routes[path][method] = schema |
| 183 | + } |
| 184 | + |
| 185 | + return routes |
| 186 | + } catch (error) { |
| 187 | + console.warn('Failed to generate OpenAPI schema') |
| 188 | + console.warn(error) |
| 189 | + |
| 190 | + return |
| 191 | + } |
| 192 | + } |
0 commit comments