|
| 1 | +import { compile } from "json-schema-to-typescript"; |
| 2 | +import fs from "fs"; |
| 3 | +import type { JSONSchema4 } from "json-schema"; |
| 4 | + |
| 5 | +interface Serverless { |
| 6 | + configSchemaHandler: { |
| 7 | + schema: JSONSchema4; |
| 8 | + }; |
| 9 | +} |
| 10 | + |
| 11 | +class ConfigSchemaHandlerTypescriptDefinitionsPlugin { |
| 12 | + private schema: JSONSchema4; |
| 13 | + |
| 14 | + constructor(serverless: Serverless) { |
| 15 | + this.schema = serverless.configSchemaHandler.schema; |
| 16 | + } |
| 17 | + |
| 18 | + commands = { |
| 19 | + schema: { |
| 20 | + usage: "Get JSON schema definition and generate TS definitions", |
| 21 | + lifecycleEvents: ["generate"], |
| 22 | + }, |
| 23 | + }; |
| 24 | + |
| 25 | + hooks = { |
| 26 | + "schema:generate": this.generateSchema.bind(this), |
| 27 | + }; |
| 28 | + |
| 29 | + async generateSchema() { |
| 30 | + /** |
| 31 | + * https://github.com/serverless/typescript/issues/4 |
| 32 | + * JSON Schema v6 `const` keyword converted to `enum` |
| 33 | + */ |
| 34 | + const normalizedSchema = replaceAllConstForEnum(this.schema); |
| 35 | + |
| 36 | + /** |
| 37 | + * ignoreMinAndMaxItems: true -> maxItems: 100 in provider.s3.corsConfiguration definition is generating 100 tuples |
| 38 | + */ |
| 39 | + const compiledDefinitions = await compile(normalizedSchema, "AWS", { |
| 40 | + ignoreMinAndMaxItems: true, |
| 41 | + unreachableDefinitions: true, |
| 42 | + }); |
| 43 | + fs.writeFileSync("index.d.ts", compiledDefinitions); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +const replaceAllConstForEnum = (schema: JSONSchema4): JSONSchema4 => { |
| 48 | + if ("object" !== typeof schema) { |
| 49 | + return schema; |
| 50 | + } |
| 51 | + |
| 52 | + return Object.fromEntries( |
| 53 | + Object.entries(schema).map(([key, value]) => { |
| 54 | + if (key === "const") { |
| 55 | + return ["enum", [value]]; |
| 56 | + } |
| 57 | + |
| 58 | + if (Array.isArray(value)) { |
| 59 | + return [key, value.map(replaceAllConstForEnum)]; |
| 60 | + } |
| 61 | + |
| 62 | + if ("object" === typeof value && value !== null) { |
| 63 | + return [key, replaceAllConstForEnum(value)]; |
| 64 | + } |
| 65 | + |
| 66 | + return [key, value]; |
| 67 | + }) |
| 68 | + ); |
| 69 | +}; |
| 70 | + |
| 71 | +module.exports = ConfigSchemaHandlerTypescriptDefinitionsPlugin; |
0 commit comments