Skip to content

Commit

Permalink
feat: add json-schema-generator
Browse files Browse the repository at this point in the history
BREAKING CHANGE: the new json-schema-generator might not produce the exact same resolut like previous generator vega/ts-json-schema-generator
  • Loading branch information
Jnig committed Jan 12, 2024
1 parent bd80ec8 commit a0176c4
Show file tree
Hide file tree
Showing 32 changed files with 818 additions and 761 deletions.
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug tests",
"request": "launch",
"runtimeArgs": ["run-script", "test"],
"runtimeExecutable": "npm",
"skipFiles": ["<node_internals>/**"],
"type": "node",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}/packages/cli/"
}
]
}
8 changes: 8 additions & 0 deletions fastify-flux.code-workspace
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}
1 change: 1 addition & 0 deletions packages/cli/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export default {
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: 'src/',
testPathIgnorePatterns: ["sample-*"]
};
3 changes: 0 additions & 3 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"@apidevtools/json-schema-ref-parser": "11.1.0",
"@types/lodash": "4.14.202",
"chalk": "5.3.0",
"chokidar": "3.5.3",
Expand All @@ -25,10 +24,8 @@
"lodash": "4.17.21",
"p-map": "7.0.1",
"pidtree": "0.6.0",
"piscina": "4.2.1",
"source-map-support": "0.5.21",
"swagger-typescript-api": "13.0.3",
"ts-json-schema-generator": "1.5.0",
"ts-morph": "21.0.1",
"typescript": "5.3.3"
},
Expand Down
17 changes: 4 additions & 13 deletions packages/cli/src/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
import { Command } from 'commander';

import {
runWorkerControllerGeneration,
runWorkerEsbuild,
runWorkerSchemaGeneration,
runWorkerTypecheck,
} from '../piscina/index.js';
import { writeControllerJson, esbuildHelper, runTypecheck } from '../helper/index.js';

async function handler(options: { typecheck: true }) {
if (options.typecheck) {
await runWorkerTypecheck();
await runTypecheck();
}

await Promise.all([
runWorkerEsbuild(),
runWorkerControllerGeneration(),
runWorkerSchemaGeneration(),
]);
await esbuildHelper()
await writeControllerJson();
}

export function addBuildCommand(program: Command) {
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/commands/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Command } from 'commander';
import pMap from 'p-map';
import { getConfig } from '../helper/config.js';

import { runWorkerSdkGeneration } from '../piscina/index.js';
import { generateSdk } from '../helper/generateSdk.js';

async function handler() {
const config = await getConfig();
Expand All @@ -11,7 +10,8 @@ async function handler() {
return;
}

await runWorkerSdkGeneration(project.sdk);

await generateSdk(project.sdk);
});
}

Expand Down
24 changes: 8 additions & 16 deletions packages/cli/src/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,14 @@ import { execa } from 'execa';
import chokidar from 'chokidar';
import pMap from 'p-map';
import _ from 'lodash';
import {
runWorkerControllerGeneration,
runWorkerEsbuild,
runWorkerSchemaGeneration,
runWorkerSdkGeneration,
runWorkerTypecheck,
} from '../piscina/index.js';
import { log } from '../log.js';
import { getConfig } from '../helper/config.js';
import { FluxProjectConfig } from '../types.js';
import { killProcess } from '../helper/killProcess.js';
import { existsSync, mkdirSync } from 'fs';
import { esbuildHelper } from '../helper/esbuild.js';
import { runTypecheck, writeControllerJson } from '../helper/index.js';
import { generateSdk } from '../helper/generateSdk.js';

interface Options {
watch: boolean;
Expand Down Expand Up @@ -97,19 +93,15 @@ class WatchHandler {

async build() {
this.excecHandler.cancelAll();

const esbuildSuccess = await runWorkerEsbuild();
const esbuildSuccess = await esbuildHelper()
if (!esbuildSuccess) {
log({ component: 'cli', warning: 'Skipping restart... esbuild failed.' });
return;
}

await Promise.all([
runWorkerControllerGeneration(),
runWorkerSchemaGeneration(),
]);
await writeControllerJson(),

this.excecHandler.restartAll();
this.excecHandler.restartAll();
}

async handle(change: string) {
Expand All @@ -118,7 +110,7 @@ class WatchHandler {
await this.build();

if (this.options.typecheck) {
runWorkerTypecheck();
runTypecheck();
}
}

Expand All @@ -134,7 +126,7 @@ async function startSdkWatch() {

const { sdk } = project;

const handler = async () => await runWorkerSdkGeneration(sdk);
const handler = async () => await generateSdk(sdk);

chokidar
.watch(sdk.input, {
Expand Down
25 changes: 23 additions & 2 deletions packages/cli/src/helper/generateMeta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,23 @@ import { join } from 'node:path';
import pMap from 'p-map';
import { getConfig } from './config.js';
import { getControllerFunctions } from './getControllerFunctions.js';
import { Project, } from 'ts-morph';



function getProject() {
const tsConfigFilePath = join(process.cwd(), 'tsconfig.json')
const project = new Project({ tsConfigFilePath });
const config = project.getCompilerOptions();
if (!config.strict && !config.strictNullChecks) {
throw new Error('tsconfig.json must have strict or strictNullChecks enabled.')
}

return project;
}

export async function generateMeta() {
const project = getProject()
const config = await getConfig();
const controllers = await fg(join(config.entry, '/**/*[cC]ontroller.ts'), {
absolute: true,
Expand All @@ -14,9 +29,14 @@ export async function generateMeta() {
const results = await pMap(
controllers,
async (file) => {
const definitions = await getControllerFunctions(file);
try {
const definitions = await getControllerFunctions(file, project);

return definitions;
return definitions;
} catch (err: any) {
err.message = `Error in file ${file}: ${err.message}`
throw err;
}
},
{ concurrency: 2 },
);
Expand All @@ -29,6 +49,7 @@ export async function generateMeta() {
functionName: method,
params: x.functions[method].params,
returnType: x.functions[method].returnType,
returnSchema: x.functions[method].returnSchema,
}),
);
});
Expand Down
14 changes: 11 additions & 3 deletions packages/cli/src/helper/getControllerFunctions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Project, SyntaxKind } from 'ts-morph';
import { Project, SyntaxKind, } from 'ts-morph';
import { log } from '../log.js';
import { ts2Json } from '../schema/ts2Json.js';
import { join } from 'node:path';

export function cleanInterfaceName(name: string | undefined) {
if (!name) {
Expand All @@ -10,12 +12,12 @@ export function cleanInterfaceName(name: string | undefined) {
.replace('Promise<', '')
.replace('>', '')
.replace('void', '')
.replace('[]', '')
.split('.')
.slice(-1)[0];
}

export function getControllerFunctions(file: string) {
const project = new Project();
export async function getControllerFunctions(file: string, project: Project) {
project.addSourceFileAtPath(file);
const parsed = project.getSourceFile(file);
if (!parsed) {
Expand Down Expand Up @@ -52,18 +54,24 @@ export function getControllerFunctions(file: string) {

const mapped = declarations.reduce<any>((acc, y) => {
const params = y.getParameters().map((x) => {


return {
name: x.getNameNode().getText(),
type: cleanInterfaceName(x.getTypeNode()?.getText()),
schema: ['query', 'body'].includes(x.getNameNode().getText()) ? ts2Json(x.getTypeNodeOrThrow()) : undefined,
};
});


const name = y.getNameNode().getText();
const returnType = cleanInterfaceName(y.getReturnTypeNode()?.getText());
const returnSchema = ts2Json(y.getReturnTypeNodeOrThrow());

acc[name] = {
params,
returnType,
returnSchema
};

return acc;
Expand Down
23 changes: 12 additions & 11 deletions packages/cli/src/helper/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import _ from 'lodash'
import { execa } from 'execa';
import { log } from '../log.js';

import { getConfig } from './config.js';
import { generateMeta } from './generateMeta.js';
import { generateSchema } from '../schema/generateSchema.js';
import { writeFile } from './writeFile.js';

export async function writeControllerJson() {
Expand All @@ -12,18 +15,16 @@ export async function writeControllerJson() {
writeFile(join(config.outdir, 'flux-controller.json'), meta);
}

export async function writeSchemaJson() {
const config = await getConfig();
let schema = await generateSchema(config.entry, { removeDateTime: false });
if (!schema) {
schema = '{}';
}

writeFile(join(config.outdir, 'flux-schema.json'), schema);
}

export function getRootDir() {
return join(dirname(fileURLToPath(import.meta.url)), '../../');
}

export async function runTypecheck() {
try {
await execa('tsc', ['--noEmit']);
} catch (err: any) {
log({ component: 'cli', error: 'Typecheck failed', details: err.message });
}
}

export * from './esbuild.js';
31 changes: 0 additions & 31 deletions packages/cli/src/piscina/index.ts

This file was deleted.

44 changes: 0 additions & 44 deletions packages/cli/src/piscina/worker.ts

This file was deleted.

0 comments on commit a0176c4

Please sign in to comment.