All files / blong-gogo/src ApiSchema.ts

33.94% Statements 111/327
55% Branches 11/20
54.54% Functions 6/11
33.94% Lines 111/327

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 3281x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 11x 11x 11x 11x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                     1x 1x           1x 1x 1x 1x 1x                                                                                                           1x 1x 3x             3x 1x                                                               1x 1x 1x 1x                                                                                           1x 1x                       1x 1x                         1x 1x                                       1x 1x 183x 183x                       1x 1x 79x 79x 79x 4x 79x 79x 79x 4x 4x 4x 4x 4x 4x 15x 4x 4x 4x 1x  
import type {
    ApiSchema as ApiSchemaType,
    GatewaySchema,
    IApiSchema,
    ILog,
    IPlatformApi,
    PathItemObject,
    SchemaObject,
} from '@feasibleone/blong/types';
import {Internal} from '@feasibleone/blong/types';
import {type Dirent} from 'node:fs';
 
import {identifier} from './lib.ts';
import loadApi from './loadApi.ts';
 
interface IConfig {
    logLevel?: Parameters<ILog['logger']>[0];
    generate?: boolean;
}
 
export default class ApiSchema extends Internal implements IApiSchema {
    #config: IConfig = {
        logLevel: 'debug',
        generate: true,
    };
    #platform: IPlatformApi;
 
    #loaded: Record<string, GatewaySchema> = {};
    #namespace: Record<string, Record<string, GatewaySchema>> = {};
    #generateFile: Set<string> = new Set();
    #generateDir: Record<
        string,
        {
            dir: string;
            existing: Set<string>;
        }
    > = {};
 
    public constructor(config: IConfig, {log, platform}: {log: ILog; platform: IPlatformApi}) {
        super({log});
        this.#platform = platform;
        this.merge(this.#config, config);
    }
 
    public method(operation: {
        operationId?: string;
        'x-blong-method'?: string;
    }): string | undefined {
        return operation?.['x-blong-method'] || operation.operationId;
    }
 
    public loadApi(
        locations: string | string[] | object | object[] | {assets: object},
        source: string = process.cwd(),
    ): ReturnType<typeof loadApi> {
        return loadApi(locations, source, this.#platform);
    }
 
    public async schema(
        {
            namespace,
            url,
        }: {
            namespace?: Record<string, string | string[]> | string[];
            url?: string;
        },
        source: string,
    ): Promise<Record<string, GatewaySchema>> {
        const result: Record<string, GatewaySchema> = {};
        if (url) {
            const dir = this.#platform.dirname(url.startsWith('file://') ? url.slice(7) : url);
            const files = await this.#platform.scan(dir);
            namespace = namespace || {};
            for (const file of files) {
                if (
                    file.isFile() &&
                    (file.name.endsWith('.yaml') ||
                        file.name.endsWith('.yml') ||
                        file.name.endsWith('.json'))
                ) {
                    const [name] = this.#platform.basename(file.name).split('.');
                    (namespace as Record<string, string[]>)[name] ||= [];
                    (namespace as Record<string, string[]>)[name].push(
                        this.#platform.join(dir, file.name),
                    );
                }
            }
        }
        if (Array.isArray(namespace))
            return namespace.reduce(
                (acc, name) => ({
                    ...acc,
                    ...this.#namespace[name],
                }),
                {},
            );
 
        if (!namespace) return result;
 
        for (const [name, locations] of Object.entries(namespace)) {
            const bundle = await loadApi(locations, source, this.#platform);
            const blongMeta = (bundle as Record<string, unknown>)['x-blong'] as
                | {namespace?: string; destination?: string}
                | undefined;
            const {namespace: nsName = name, destination} = blongMeta ?? {};
            this.#namespace[nsName] ||= {};
            Object.entries(bundle.paths ?? {}).forEach(
                ([path, methods]: [string, PathItemObject]) => {
                    (['get', 'post', 'put', 'delete'] as const).forEach(httpMethod => {
                        const operation = methods[httpMethod];
                        if (!operation) return;
                        const bodyParam = (
                            operation.parameters as {in?: string; schema: unknown}[]
                        )?.find?.(param => param?.in === 'body')?.schema;
                        const method = this.method(operation);
                        const definition: GatewaySchema = {
                            rpc: false,
                            auth: false,
                            ...(bodyParam ? {body: bodyParam} : {}),
                            ...('requestBody' in operation && {
                                body:
                                    'openapi' in bundle
                                        ? 'content' in (operation.requestBody ?? {}) &&
                                          (
                                              operation.requestBody as {
                                                  content?: Record<string, {schema?: unknown}>;
                                              }
                                          )?.content?.['application/json']
                                        : operation.requestBody,
                            }),
                            basePath: `/rest/${nsName}`,
                            response: (
                                (
                                    operation.responses?.['200'] as {
                                        content?: Record<string, {schema?: unknown}>;
                                    }
                                )?.content?.['application/json'] as {schema?: unknown} | undefined
                            )?.schema as ApiSchemaType | undefined,
                            description: operation.description,
                            summary: operation.summary,
                            destination,
                            method: httpMethod.toUpperCase() as Uppercase<typeof httpMethod>,
                            subject: nsName,
                            operation,
                            path: path.replaceAll('{', ':').replaceAll('}', ''),
                        };
                        this.#loaded[`${nsName}${method}`.toLowerCase()] = definition;
                        this.#namespace[nsName][`${nsName}.${method}`.toLowerCase()] = definition;
                        result[`${nsName}.${method}`.toLowerCase()] = definition;
                    });
                },
            );
        }
        const generate = [];
        for (const [prefix, record] of Object.entries(this.#generateDir)) {
            for (const [method, operation] of Object.entries(this.#loaded)) {
                const filename =
                    (operation.subject ?? '') + this.method(operation.operation ?? {}) + '.ts';
                if (method.startsWith(prefix) && !record.existing.has(filename.toLowerCase())) {
                    generate.push(this.#platform.join(record.dir, filename));
                }
            }
        }
        for (const filename of generate.concat(Array.from(this.#generateFile))) {
            const method = this.#platform.basename(filename, this.#platform.extname(filename));
            const schema = this.#loaded[method.toLowerCase()];
            if (schema) {
                // console.log(schema.operation.responses);
                this.log?.warn?.(`Writing ${filename}`);
                this.#platform.writeFileSync(
                    filename,
                    `import unchanged from '@feasibleone/blong';
import {type IMeta, handler} from '@feasibleone/blong/types';

// #region API
type Handler = (params: {
${this._params(schema)}
}) => Promise<{
${this._response(schema)}
}>;
// #endregion

export default handler(
    () =>
        async function ${method}(
            params: Parameters<Handler>[0],
            $meta: IMeta
        ): ReturnType<Handler> {
            return {};
        }
);
`,
                );
            }
        }
        return result;
    }
 
    private _params(schema: GatewaySchema): string {
        return (
            schema?.operation?.parameters
                ?.map((param: (typeof schema.operation.parameters)[0]) => {
                    if ('$ref' in param) return '';
                    if (!('in' in param)) return;
                    switch (param.in) {
                        case 'header':
                        case 'path':
                        case 'query':
                            return `    ${identifier(param.name)}${
                                param.required ? ':' : '?:'
                            } ${this._paramType(param)};${
                                param.description
                                    ? ` // ${param.description.replaceAll(/[\r\n]/g, '')}`
                                    : ''
                            }`;
                        case 'body':
                            if (param.schema?.type === 'object') {
                                return Object.entries(
                                    (param.schema.properties as Record<
                                        string,
                                        {description?: string}
                                    >) ?? {},
                                )
                                    .map(
                                        ([name, property]: [string, {description?: string}]) =>
                                            `    ${name}${param.required ? ':' : '?:'} ${this._type(
                                                property,
                                            )};${
                                                property.description
                                                    ? ` // ${property.description.replaceAll(
                                                          /[\r\n]/g,
                                                          '',
                                                      )}`
                                                    : ''
                                            }`,
                                    )
                                    .join('\n');
                            }
                    }
                })
                .filter(Boolean)
                .join('\n') ?? ''
        );
    }
 
    private _response({operation}: GatewaySchema): string {
        if (!operation?.responses || !(200 in operation.responses)) return '';
        const resp200 = operation.responses[200] as Record<string, unknown> | undefined;
        if (!resp200 || !('schema' in resp200)) return '';
        const schema = resp200?.['schema'];
        if (!schema || typeof schema !== 'object' || !('properties' in schema)) return '';
        return Object.entries((schema as {properties: Record<string, unknown>}).properties ?? {})
            .map(([name, property]) => {
                return `    ${name}: ${this._type(property as SchemaObject)},`;
            })
            .join('\n');
    }
 
    private _paramType(param: object): string {
        if (!('type' in param)) return 'unknown';
        switch (param.type) {
            case 'string':
                return 'string';
            case 'integer':
                return 'number';
            case 'boolean':
                return 'boolean';
            default:
                return 'unknown';
        }
    }
 
    private _type(schema: SchemaObject): string {
        switch (schema.type) {
            case 'string':
                return 'string';
            case 'integer':
                return 'number';
            case 'boolean':
                return 'boolean';
            case 'array':
                return `${this._type(schema.items as SchemaObject)}[]`;
            case 'object':
                return `{${Object.entries(
                    (schema as {properties?: Record<string, unknown>}).properties ?? {},
                )
                    .map(([name, property]) => `${name}: ${this._type(property as SchemaObject)}`)
                    .join('; ')}}`;
            default:
                return 'unknown';
        }
    }
 
    public async generateFile(filename: string): Promise<boolean> {
        if (this.#config.generate === false) return false;
        if (this.#platform.statSync(filename).size !== 0) return false;
        const content = this.#platform
            .readFileSync(filename, {encoding: 'utf-8'})
            .toString('utf-8');
        if (content.includes('import unchanged from')) {
            this.#generateFile.add(filename);
            return false;
        }

        this.#generateFile.add(filename);
        return true;
    }
 
    public async generateDir(dir: string, files: Dirent[]): Promise<boolean> {
        if (this.#config.generate === false) return false;
        const [object, orchestrator, subject] = dir.split('/').reverse();
        if (orchestrator !== 'orchestrator') return false;
        this.log?.info?.(`Generating dir ${dir}`);
        const prefix = subject.toLowerCase() + object.toLowerCase();
        let record = this.#generateDir[prefix];
        if (!record) {
            record = this.#generateDir[prefix] = {
                dir,
                existing: new Set(),
            };
        }
        files.forEach(file =>
            record.existing.add(this.#platform.basename(file.name).toLowerCase()),
        );
        return true;
    }
}