@@ -4,8 +4,11 @@ import { execSync } from "node:child_process";
44import { copyFileSync , mkdirSync , readdirSync , readFileSync , writeFileSync } from "node:fs" ;
55import { join } from "node:path" ;
66
7+ import { quicktype , InputData , JSONSchemaInput , FetchingJSONSchemaStore } from "quicktype-core" ;
8+
79const oxfmtDirPath = join ( import . meta. dirname , ".." ) ,
8- distDirPath = join ( oxfmtDirPath , "dist" ) ;
10+ distDirPath = join ( oxfmtDirPath , "dist" ) ,
11+ jsonSchemaPath = join ( oxfmtDirPath , ".." , ".." , "npm/oxfmt/configuration_schema.json" ) ;
912
1013// Modify `bindings.js` to use correct package names
1114console . log ( "Modifying bindings.js..." ) ;
@@ -28,6 +31,14 @@ for (const filename of readdirSync(join(oxfmtDirPath, "src-js"))) {
2831 if ( ! filename . endsWith ( ".node" ) ) continue ;
2932 copyFile ( join ( oxfmtDirPath , "src-js" , filename ) , join ( distDirPath , filename ) ) ;
3033}
34+ try {
35+ const { lines } = await quicktypeJSONSchema ( "OxfmtConfig" , readFileSync ( jsonSchemaPath , "utf8" ) ) ;
36+ writeFileSync ( join ( distDirPath , "config.d.ts" ) , lines . join ( "\n" ) ) ;
37+ console . log ( "Translated oxfmt config JSON schema into TypeScript" ) ;
38+ } catch ( error ) {
39+ console . error ( "Translating oxfmt config JSON schema into TypeScript failed:" , error ) ;
40+ process . exit ( 1 ) ;
41+ }
3142
3243console . log ( "Build complete!" ) ;
3344
@@ -42,3 +53,29 @@ function copyFile(srcPath, destPath) {
4253 copyFileSync ( srcPath , destPath ) ;
4354 console . log ( `- Copied ${ srcPath . split ( "/" ) . pop ( ) } ` ) ;
4455}
56+
57+ /**
58+ * Quicktype a JSON schema into a target language.
59+ * @param {string } targetLanguage - The target language to quicktype to.
60+ * @param {string } typeName - The name of the type to quicktype.
61+ * @param {string } jsonSchemaString - The JSON schema string to quicktype.
62+ * @returns {Promise<import('quicktype-core').SerializedRenderResult> } The quicktyped code.
63+ */
64+ async function quicktypeJSONSchema ( typeName , jsonSchemaString ) {
65+ const schemaInput = new JSONSchemaInput ( new FetchingJSONSchemaStore ( ) ) ;
66+
67+ // We could add multiple schemas for multiple types,
68+ // but here we're just making one type from JSON schema.
69+ await schemaInput . addSource ( { name : typeName , schema : jsonSchemaString } ) ;
70+
71+ const inputData = new InputData ( ) ;
72+ inputData . addInput ( schemaInput ) ;
73+
74+ return await quicktype ( {
75+ inputData,
76+ lang : "typescript" ,
77+ rendererOptions : {
78+ "prefer-unions" : true ,
79+ } ,
80+ } ) ;
81+ }
0 commit comments