@twin.org/ts-to-schema 0.0.2-next.8 → 0.0.3-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Copyright 2024 IOTA Stiftung.
3
3
  // SPDX-License-Identifier: Apache-2.0.
4
- import { CLI } from '../dist/esm/index.mjs';
4
+ import { CLI } from '../dist/es/index.js';
5
5
 
6
6
  const cli = new CLI();
7
7
  const result = await cli.run(process.argv);
package/dist/es/cli.js ADDED
@@ -0,0 +1,37 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { CLIBase } from "@twin.org/cli-core";
6
+ import { buildCommandTsToSchema } from "./commands/tsToSchema.js";
7
+ /**
8
+ * The main entry point for the CLI.
9
+ */
10
+ export class CLI extends CLIBase {
11
+ /**
12
+ * Run the app.
13
+ * @param argv The process arguments.
14
+ * @param localesDirectory The directory for the locales, default to relative to the script.
15
+ * @param options Additional options.
16
+ * @param options.overrideOutputWidth Override the output width.
17
+ * @returns The exit code.
18
+ */
19
+ async run(argv, localesDirectory, options) {
20
+ return this.execute({
21
+ title: "TWIN TypeScript To Schema",
22
+ appName: "ts-to-schema",
23
+ version: "0.0.3-next.1", // x-release-please-version
24
+ icon: "⚙️ ",
25
+ supportsEnvFiles: false,
26
+ overrideOutputWidth: options?.overrideOutputWidth
27
+ }, localesDirectory ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "../locales"), argv);
28
+ }
29
+ /**
30
+ * Configure any options or actions at the root program level.
31
+ * @param program The root program command.
32
+ */
33
+ configureRoot(program) {
34
+ buildCommandTsToSchema(program);
35
+ }
36
+ }
37
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAElE;;GAEG;AACH,MAAM,OAAO,GAAI,SAAQ,OAAO;IAC/B;;;;;;;OAOG;IACI,KAAK,CAAC,GAAG,CACf,IAAc,EACd,gBAAyB,EACzB,OAA0C;QAE1C,OAAO,IAAI,CAAC,OAAO,CAClB;YACC,KAAK,EAAE,2BAA2B;YAClC,OAAO,EAAE,cAAc;YACvB,OAAO,EAAE,cAAc,EAAE,2BAA2B;YACpD,IAAI,EAAE,KAAK;YACX,gBAAgB,EAAE,KAAK;YACvB,mBAAmB,EAAE,OAAO,EAAE,mBAAmB;SACjD,EACD,gBAAgB,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY,CAAC,EACzF,IAAI,CACJ,CAAC;IACH,CAAC;IAED;;;OAGG;IACO,aAAa,CAAC,OAAgB;QACvC,sBAAsB,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACD","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { CLIBase } from \"@twin.org/cli-core\";\nimport type { Command } from \"commander\";\nimport { buildCommandTsToSchema } from \"./commands/tsToSchema.js\";\n\n/**\n * The main entry point for the CLI.\n */\nexport class CLI extends CLIBase {\n\t/**\n\t * Run the app.\n\t * @param argv The process arguments.\n\t * @param localesDirectory The directory for the locales, default to relative to the script.\n\t * @param options Additional options.\n\t * @param options.overrideOutputWidth Override the output width.\n\t * @returns The exit code.\n\t */\n\tpublic async run(\n\t\targv: string[],\n\t\tlocalesDirectory?: string,\n\t\toptions?: { overrideOutputWidth?: number }\n\t): Promise<number> {\n\t\treturn this.execute(\n\t\t\t{\n\t\t\t\ttitle: \"TWIN TypeScript To Schema\",\n\t\t\t\tappName: \"ts-to-schema\",\n\t\t\t\tversion: \"0.0.3-next.1\", // x-release-please-version\n\t\t\t\ticon: \"⚙️ \",\n\t\t\t\tsupportsEnvFiles: false,\n\t\t\t\toverrideOutputWidth: options?.overrideOutputWidth\n\t\t\t},\n\t\t\tlocalesDirectory ?? path.join(path.dirname(fileURLToPath(import.meta.url)), \"../locales\"),\n\t\t\targv\n\t\t);\n\t}\n\n\t/**\n\t * Configure any options or actions at the root program level.\n\t * @param program The root program command.\n\t */\n\tprotected configureRoot(program: Command): void {\n\t\tbuildCommandTsToSchema(program);\n\t}\n}\n"]}
@@ -1,23 +1,21 @@
1
- import path from 'node:path';
2
- import { fileURLToPath } from 'node:url';
3
- import { CLIDisplay, CLIUtils, CLIBase } from '@twin.org/cli-core';
4
- import { mkdir, rm, writeFile } from 'node:fs/promises';
5
- import { I18n, GeneralError, Is, StringHelper } from '@twin.org/core';
6
- import { JsonSchemaHelper } from '@twin.org/tools-core';
7
- import { createGenerator } from 'ts-json-schema-generator';
8
-
9
1
  // Copyright 2024 IOTA Stiftung.
10
2
  // SPDX-License-Identifier: Apache-2.0.
3
+ import { mkdir, rm, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { CLIDisplay, CLIUtils } from "@twin.org/cli-core";
6
+ import { GeneralError, I18n, Is, StringHelper } from "@twin.org/core";
7
+ import { JsonSchemaHelper } from "@twin.org/tools-core";
8
+ import { createGenerator } from "ts-json-schema-generator";
11
9
  /**
12
10
  * Build the root command to be consumed by the CLI.
13
11
  * @param program The command to build on.
14
12
  */
15
- function buildCommandTsToSchema(program) {
13
+ export function buildCommandTsToSchema(program) {
16
14
  program
17
15
  .argument(I18n.formatMessage("commands.ts-to-schema.options.config.param"), I18n.formatMessage("commands.ts-to-schema.options.config.description"))
18
16
  .argument(I18n.formatMessage("commands.ts-to-schema.options.output-folder.param"), I18n.formatMessage("commands.ts-to-schema.options.output-folder.description"))
19
17
  .action(async (config, outputFolder, opts) => {
20
- await actionCommandTsToSchema(config, outputFolder);
18
+ await actionCommandTsToSchema(config, outputFolder, opts);
21
19
  });
22
20
  }
23
21
  /**
@@ -26,7 +24,7 @@ function buildCommandTsToSchema(program) {
26
24
  * @param outputFolder The output folder for the schemas.
27
25
  * @param opts The options for the command.
28
26
  */
29
- async function actionCommandTsToSchema(configFile, outputFolder, opts) {
27
+ export async function actionCommandTsToSchema(configFile, outputFolder, opts) {
30
28
  let outputWorkingDir;
31
29
  try {
32
30
  let config;
@@ -70,9 +68,13 @@ async function actionCommandTsToSchema(configFile, outputFolder, opts) {
70
68
  * @param outputFolder The location of the folder to output the JSON schemas.
71
69
  * @param workingDirectory The folder the app was run from.
72
70
  */
73
- async function tsToSchema(config, outputFolder, workingDirectory) {
71
+ export async function tsToSchema(config, outputFolder, workingDirectory) {
74
72
  await writeFile(path.join(workingDirectory, "tsconfig.json"), JSON.stringify({
75
- compilerOptions: {}
73
+ compilerOptions: {
74
+ module: "nodenext",
75
+ moduleResolution: "nodenext",
76
+ target: "ES2022"
77
+ }
76
78
  }, undefined, "\t"));
77
79
  CLIDisplay.break();
78
80
  CLIDisplay.task(I18n.formatMessage("commands.ts-to-schema.progress.writingSchemas"));
@@ -163,38 +165,4 @@ function finaliseSchema(schemaObject, baseUrl, type) {
163
165
  ...rest
164
166
  };
165
167
  }
166
-
167
- // Copyright 2024 IOTA Stiftung.
168
- // SPDX-License-Identifier: Apache-2.0.
169
- /**
170
- * The main entry point for the CLI.
171
- */
172
- class CLI extends CLIBase {
173
- /**
174
- * Run the app.
175
- * @param argv The process arguments.
176
- * @param localesDirectory The directory for the locales, default to relative to the script.
177
- * @param options Additional options.
178
- * @param options.overrideOutputWidth Override the output width.
179
- * @returns The exit code.
180
- */
181
- async run(argv, localesDirectory, options) {
182
- return this.execute({
183
- title: "TWIN TypeScript To Schema",
184
- appName: "ts-to-schema",
185
- version: "0.0.2-next.8", // x-release-please-version
186
- icon: "⚙️ ",
187
- supportsEnvFiles: false,
188
- overrideOutputWidth: options?.overrideOutputWidth
189
- }, localesDirectory ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "../locales"), argv);
190
- }
191
- /**
192
- * Configure any options or actions at the root program level.
193
- * @param program The root program command.
194
- */
195
- configureRoot(program) {
196
- buildCommandTsToSchema(program);
197
- }
198
- }
199
-
200
- export { CLI, actionCommandTsToSchema, buildCommandTsToSchema, tsToSchema };
168
+ //# sourceMappingURL=tsToSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tsToSchema.js","sourceRoot":"","sources":["../../../src/commands/tsToSchema.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAoB,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAG3D;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAgB;IACtD,OAAO;SACL,QAAQ,CACR,IAAI,CAAC,aAAa,CAAC,4CAA4C,CAAC,EAChE,IAAI,CAAC,aAAa,CAAC,kDAAkD,CAAC,CACtE;SACA,QAAQ,CACR,IAAI,CAAC,aAAa,CAAC,mDAAmD,CAAC,EACvE,IAAI,CAAC,aAAa,CAAC,yDAAyD,CAAC,CAC7E;SACA,MAAM,CAAC,KAAK,EAAE,MAAM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ifier: Apache-2.0.\nimport { mkdir, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { CLIDisplay, CLIUtils } from \"@twin.org/cli-core\";\nimport { GeneralError, I18n, Is, StringHelper } from \"@twin.org/core\";\nimport { type IJsonSchema, JsonSchemaHelper } from \"@twin.org/tools-core\";\nimport type { Command } from \"commander\";\nimport { createGenerator } from \"ts-json-schema-generator\";\nimport type { ITsToSchemaConfig } from \"../models/ITsToSchemaConfig.js\";\n\n/**\n * Build the root command to be consumed by the CLI.\n * @param program The command to build on.\n */\nexport function buildCommandTsToSchema(program: Command): void {\n\tprogram\n\t\t.argument(\n\t\t\tI18n.formatMessage(\"commands.ts-to-schema.options.config.param\"),\n\t\t\tI18n.formatMessage(\"commands.ts-to-schema.options.config.description\")\n\t\t)\n\t\t.argument(\n\t\t\tI18n.formatMessage(\"commands.ts-to-schema.options.output-folder.param\"),\n\t\t\tI18n.formatMessage(\"commands.ts-to-schema.options.output-folder.description\")\n\t\t)\n\t\t.action(async (config, outputFolder, opts) => {\n\t\t\tawait actionCommandTsToSchema(config, outputFolder, opts);\n\t\t});\n}\n\n/**\n * Action the root command.\n * @param configFile The optional configuration file.\n * @param outputFolder The output folder for the schemas.\n * @param opts The options for the command.\n */\nexport async function actionCommandTsToSchema(\n\tconfigFile: string,\n\toutputFolder: string,\n\topts: unknown\n): Promise<void> {\n\tlet outputWorkingDir: string | undefined;\n\ttry {\n\t\tlet config: ITsToSchemaConfig | undefined;\n\n\t\tconst fullConfigFile = path.resolve(configFile);\n\t\tconst fullOutputFolder = path.resolve(outputFolder);\n\t\toutputWorkingDir = path.join(fullOutputFolder, \"working\");\n\n\t\tCLIDisplay.value(I18n.formatMessage(\"commands.ts-to-schema.labels.configJson\"), fullConfigFile);\n\t\tCLIDisplay.value(\n\t\t\tI18n.formatMessage(\"commands.ts-to-schema.labels.outputFolder\"),\n\t\t\tfullOutputFolder\n\t\t);\n\t\tCLIDisplay.value(\n\t\t\tI18n.formatMessage(\"commands.ts-to-schema.labels.outputWorkingDir\"),\n\t\t\toutputWorkingDir\n\t\t);\n\t\tCLIDisplay.break();\n\n\t\ttry {\n\t\t\tCLIDisplay.task(I18n.formatMessage(\"commands.ts-to-schema.progress.loadingConfigJson\"));\n\t\t\tCLIDisplay.break();\n\n\t\t\tconfig = await CLIUtils.readJsonFile<ITsToSchemaConfig>(fullConfigFile);\n\t\t} catch (err) {\n\t\t\tthrow new GeneralError(\"commands\", \"commands.ts-to-schema.configFailed\", undefined, err);\n\t\t}\n\n\t\tif (Is.empty(config)) {\n\t\t\tthrow new GeneralError(\"commands\", \"commands.ts-to-schema.configFailed\");\n\t\t}\n\n\t\tCLIDisplay.task(I18n.formatMessage(\"commands.ts-to-schema.progress.creatingWorkingDir\"));\n\t\tawait mkdir(outputWorkingDir, { recursive: true });\n\t\tCLIDisplay.break();\n\n\t\tawait tsToSchema(config ?? {}, fullOutputFolder, outputWorkingDir);\n\n\t\tCLIDisplay.break();\n\t\tCLIDisplay.done();\n\t} finally {\n\t\ttry {\n\t\t\tif (outputWorkingDir) {\n\t\t\t\tawait rm(outputWorkingDir, { recursive: true });\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\n/**\n * Convert the TypeScript definitions to JSON Schemas.\n * @param config The configuration for the app.\n * @param outputFolder The location of the folder to output the JSON schemas.\n * @param workingDirectory The folder the app was run from.\n */\nexport async function tsToSchema(\n\tconfig: ITsToSchemaConfig,\n\toutputFolder: string,\n\tworkingDirectory: string\n): Promise<void> {\n\tawait writeFile(\n\t\tpath.join(workingDirectory, \"tsconfig.json\"),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tcompilerOptions: {\n\t\t\t\t\tmodule: \"nodenext\",\n\t\t\t\t\tmoduleResolution: \"nodenext\",\n\t\t\t\t\ttarget: \"ES2022\"\n\t\t\t\t}\n\t\t\t},\n\t\t\tundefined,\n\t\t\t\"\\t\"\n\t\t)\n\t);\n\n\tCLIDisplay.break();\n\tCLIDisplay.task(I18n.formatMessage(\"commands.ts-to-schema.progress.writingSchemas\"));\n\tfor (const typeSource of config.types) {\n\t\tconst typeSourceParts = typeSource.split(\"/\");\n\t\tconst type = StringHelper.pascalCase(\n\t\t\ttypeSourceParts[typeSourceParts.length - 1].replace(/(\\.d)?\\.ts$/, \"\"),\n\t\t\tfalse\n\t\t);\n\n\t\tlet schemaObject;\n\t\tif (Is.object<IJsonSchema>(config.overrides?.[type])) {\n\t\t\tCLIDisplay.task(I18n.formatMessage(\"commands.ts-to-schema.progress.overridingSchema\"));\n\t\t\tschemaObject = config.overrides?.[type];\n\t\t} else {\n\t\t\tCLIDisplay.task(I18n.formatMessage(\"commands.ts-to-schema.progress.generatingSchema\"));\n\n\t\t\tconst autoExpandTypes = config.autoExpandTypes ?? [];\n\t\t\tconst defaultExpandTypes = [\"/ObjectOrArray<.*>/\"];\n\t\t\tfor (const defaultType of defaultExpandTypes) {\n\t\t\t\tif (!autoExpandTypes.includes(defaultType)) {\n\t\t\t\t\tautoExpandTypes.push(defaultType);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst schemas = await generateSchemas(typeSource, type, autoExpandTypes, workingDirectory);\n\t\t\tif (Is.empty(schemas[type])) {\n\t\t\t\tthrow new GeneralError(\"commands\", \"commands.ts-to-schema.schemaNotFound\", { type });\n\t\t\t}\n\t\t\tschemaObject = schemas[type];\n\t\t}\n\n\t\tschemaObject = finaliseSchema(schemaObject, config.baseUrl, type);\n\n\t\tlet content = JSON.stringify(schemaObject, undefined, \"\\t\");\n\n\t\tif (Is.objectValue(config.externalReferences)) {\n\t\t\tfor (const external in config.externalReferences) {\n\t\t\t\tcontent = content.replace(\n\t\t\t\t\tnew RegExp(`#/definitions/${external}`, \"g\"),\n\t\t\t\t\tconfig.externalReferences[external]\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// First replace all types that start with II to a single I with the new base url\n\t\tcontent = content.replace(/#\\/definitions\\/II(.*)/g, `${config.baseUrl}I$1`);\n\n\t\t// Then other types starting with capitals (optionally interfaces starting with I)\n\t\tcontent = content.replace(/#\\/definitions\\/I?([A-Z].*)/g, `${config.baseUrl}$1`);\n\n\t\tconst filename = path.join(outputFolder, `${StringHelper.stripPrefix(type)}.json`);\n\t\tCLIDisplay.value(\n\t\t\tI18n.formatMessage(\"commands.ts-to-schema.progress.writingSchema\"),\n\t\t\tfilename,\n\t\t\t1\n\t\t);\n\t\tawait writeFile(filename, `${content}\\n`);\n\t}\n}\n\n/**\n * Generate schemas for the models.\n * @param modelDirWildcards The filenames for all the models.\n * @param types The types of the schema objects.\n * @param autoExpandTypes The types to automatically expand.\n * @param outputWorkingDir The working directory.\n * @returns Nothing.\n * @internal\n */\nasync function generateSchemas(\n\ttypeSource: string,\n\ttype: string,\n\tautoExpandTypes: string[],\n\toutputWorkingDir: string\n): Promise<{\n\t[id: string]: IJsonSchema;\n}> {\n\tconst allSchemas: { [id: string]: IJsonSchema } = {};\n\n\tCLIDisplay.value(I18n.formatMessage(\"commands.ts-to-schema.progress.models\"), typeSource, 1);\n\tconst generator = createGenerator({\n\t\tpath: typeSource,\n\t\ttype,\n\t\ttsconfig: path.join(outputWorkingDir, \"tsconfig.json\"),\n\t\tskipTypeCheck: true,\n\t\texpose: \"all\"\n\t});\n\n\tconst schema = generator.createSchema(\"*\");\n\n\tif (schema.definitions) {\n\t\tfor (const def in schema.definitions) {\n\t\t\tconst defSub = JsonSchemaHelper.normaliseTypeName(def);\n\t\t\tallSchemas[defSub] = schema.definitions[def] as IJsonSchema;\n\t\t}\n\t}\n\n\tconst referencedSchemas: { [id: string]: IJsonSchema } = {};\n\n\tJsonSchemaHelper.extractTypes(allSchemas, [type, ...autoExpandTypes], referencedSchemas);\n\tJsonSchemaHelper.expandTypes(referencedSchemas, autoExpandTypes);\n\n\treturn referencedSchemas;\n}\n\n/**\n * Process the schema object to ensure it has the correct properties.\n * @param schemaObject The schema object to process.\n * @param baseUrl The base URL for the schema references.\n * @param type The type of the schema object.\n * @returns The finalised schema object.\n */\nfunction finaliseSchema(schemaObject: IJsonSchema, baseUrl: string, type: string): IJsonSchema {\n\tJsonSchemaHelper.processArrays(schemaObject);\n\tconst { description, ...rest } = schemaObject;\n\treturn {\n\t\t$schema: JsonSchemaHelper.SCHEMA_VERSION,\n\t\t$id: `${baseUrl}${StringHelper.stripPrefix(type)}`,\n\t\tdescription,\n\t\t...rest\n\t};\n}\n"]}
@@ -0,0 +1,6 @@
1
+ // Copyright 2024 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export * from "./cli.js";
4
+ export * from "./commands/tsToSchema.js";
5
+ export * from "./models/ITsToSchemaConfig.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,UAAU,CAAC;AACzB,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./cli.js\";\nexport * from \"./commands/tsToSchema.js\";\nexport * from \"./models/ITsToSchemaConfig.js\";\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ITsToSchemaConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITsToSchemaConfig.js","sourceRoot":"","sources":["../../../src/models/ITsToSchemaConfig.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IJsonSchema } from \"@twin.org/tools-core\";\n\n/**\n * Configuration for the tool.\n */\nexport interface ITsToSchemaConfig {\n\t/**\n\t * The base url for the type references e.g. https://schema.twindev.org/my-namespace/.\n\t */\n\tbaseUrl: string;\n\n\t/**\n\t * The source files to generate the types from.\n\t */\n\ttypes: string[];\n\n\t/**\n\t * External type references.\n\t */\n\texternalReferences?: { [id: string]: string };\n\n\t/**\n\t * Override for specific types, to be used when the type cannot be generated automatically, or is generated incorrectly.\n\t */\n\toverrides?: {\n\t\t[id: string]: IJsonSchema;\n\t};\n\n\t/**\n\t * The types to automatically expand inline in type definitions, reg ex string matches.\n\t */\n\tautoExpandTypes?: string[];\n}\n"]}
@@ -6,7 +6,6 @@
6
6
  "optionInvalidHex": "The \"{option}\" does not appear to be hex. \"{value}\"",
7
7
  "optionInvalidBase64": "The \"{option}\" does not appear to be base64. \"{value}\"",
8
8
  "optionInvalidHexBase64": "The \"{option}\" does not appear to be hex or base64. \"{value}\"",
9
- "optionInvalidBech32": "The \"{option}\" does not appear to be bech32. \"{value}\"",
10
9
  "optionMinValue": "The \"{option}\" option must be greater than or equal to {minValue}, it is {value}.",
11
10
  "optionMaxValue": "The \"{option}\" option must be less than or equal to {maxValue}, it is {value}."
12
11
  },
@@ -53,9 +52,7 @@
53
52
  "beUrn": "{fieldName} must be a correctly formatted urn",
54
53
  "beUrl": "{fieldName} must be a correctly formatted url",
55
54
  "beJSON": "{fieldName} must be correctly formatted JSON",
56
- "beEmail": "{fieldName} must be a correctly formatted e-mail address",
57
- "failed": "Validation failed",
58
- "failedObject": "Validation of \"{objectName}\" failed"
55
+ "beEmail": "{fieldName} must be a correctly formatted e-mail address"
59
56
  },
60
57
  "guard": {
61
58
  "undefined": "Property \"{property}\" must be defined, it is \"{value}\"",
@@ -86,11 +83,7 @@
86
83
  "function": "Property \"{property}\" must be a function, it is \"{value}\"",
87
84
  "urn": "Property \"{property}\" must be a Urn formatted string, it is \"{value}\"",
88
85
  "url": "Property \"{property}\" must be a Url formatted string, it is \"{value}\"",
89
- "email": "Property \"{property}\" must be string in e-mail format, it is \"{value}\"",
90
- "length32Multiple": "Property \"{property}\" should be a multiple of 32, it is {value}",
91
- "lengthEntropy": "Property \"{property}\" should be a multiple of 4, >=16 and <= 32, it is {value}",
92
- "length3Multiple": "Property \"{property}\" should be a multiple of 3, it is {value}",
93
- "greaterThan0": "Property \"{property}\" must be greater than zero, it is {value}"
86
+ "email": "Property \"{property}\" must be string in e-mail format, it is \"{value}\""
94
87
  },
95
88
  "objectHelper": {
96
89
  "failedBytesToJSON": "Failed converting bytes to JSON",
@@ -106,7 +99,7 @@
106
99
  "noGet": "The requested {typeName} \"{name}\" does not exist in the factory"
107
100
  },
108
101
  "bitString": {
109
- "outOfRange": "The index should be >= 0 and less than the length of the bit string"
102
+ "outOfRange": "The index should be >= 0 and less than the length of the bit string, the index is \"{index}\" and the number of bit is \"{numberBits}\""
110
103
  },
111
104
  "base32": {
112
105
  "invalidCharacter": "Data contains a character \"{invalidCharacter}\" which is not in the charset"
@@ -119,68 +112,6 @@
119
112
  },
120
113
  "jsonHelper": {
121
114
  "failedPatch": "Failed to patch the JSON object, patch index \"{index}\" failed"
122
- },
123
- "bip39": {
124
- "missingMnemonicWord": "The mnemonic contains a word not in the wordlist, \"{value}\"",
125
- "checksumMismatch": "The checksum does not match \"{newChecksum}\" != \"{checksumBits}\""
126
- },
127
- "ed25519": {
128
- "privateKeyLength": "The private key length is incorrect, it should be \"{requiredSize}\" but is \"{actualSize}\"",
129
- "publicKeyLength": "The public key length is incorrect, it should be \"{requiredSize}\" but is \"{actualSize}\""
130
- },
131
- "secp256k1": {
132
- "privateKeyLength": "The private key length is incorrect, it should be \"{requiredSize}\" but is \"{actualSize}\"",
133
- "publicKeyLength": "The public key length is incorrect, it should be \"{requiredSize}\" but is \"{actualSize}\""
134
- },
135
- "x25519": {
136
- "invalidPublicKey": "Invalid Ed25519 Public Key"
137
- },
138
- "blake2b": {
139
- "outputLength64": "The output length should be between 1 and 64, it is \"{outputLength}\"",
140
- "keyLength64": "The key length should be between 1 and 64, it is \"{keyLength}\""
141
- },
142
- "sha512": {
143
- "bitSize": "Only 224, 256, 384 or 512 bits are supported, it is \"{bitSize}\""
144
- },
145
- "sha256": {
146
- "bitSize": "Only 224 or 256 bits are supported, it is \"{bitSize}\""
147
- },
148
- "sha3": {
149
- "bitSize": "Only 224, 256, 384 or 512 bits are supported, it is \"{bitSize}\""
150
- },
151
- "hmacSha256": {
152
- "bitSize": "Only 224 or 256 bits are supported, it is \"{bitSize}\""
153
- },
154
- "hmacSha512": {
155
- "bitSize": "Only 224, 256, 384 or 512 bits are supported, it is \"{bitSize}\""
156
- },
157
- "bech32": {
158
- "decodeFailed": "The address contains decoding failed for address \"{bech32}\"",
159
- "invalidChecksum": "The address contains an invalid checksum in address, \"{bech32}\"",
160
- "separatorMisused": "The separator character '1' should only be used between hrp and data, \"{bech32}\"",
161
- "lowerUpper": "The address my use either lowercase or uppercase, \"{bech32}\"",
162
- "dataTooShort": "The address does not contain enough data to decode, \"{bech32}\""
163
- },
164
- "pbkdf2": {
165
- "keyTooLong": "The requested key length \"{keyLength}\" is too long, based on the \"{macLength}\""
166
- },
167
- "chaCha20Poly1305": {
168
- "noAadWithData": "You can not set the aad when there is already data",
169
- "noAuthTag": "Can not finalise when the auth tag is not set",
170
- "authenticationFailed": "The data could not be authenticated",
171
- "authTagDecrypting": "Can not get the auth tag when decrypting",
172
- "authTagEncrypting": "Can not set the auth tag when encrypting",
173
- "noAuthTagSet": "The auth tag has not been set"
174
- },
175
- "bip44": {
176
- "unsupportedKeyType": "The key type \"{keyType}\" is not supported"
177
- },
178
- "slip0010": {
179
- "invalidSeed": "The seed is invalid \"{seed}\""
180
- },
181
- "rsa": {
182
- "noPrivateKey": "Private key is required for this operation",
183
- "invalidKeySize": "Invalid RSA key size"
184
115
  }
185
116
  },
186
117
  "warn": {
@@ -240,7 +171,8 @@
240
171
  "alreadyExistsError": "Already Exists",
241
172
  "notImplementedError": "Not Implemented",
242
173
  "validationError": "Validation",
243
- "unprocessableError": "Unprocessable"
174
+ "unprocessableError": "Unprocessable",
175
+ "unauthorizedError": "Unauthorized"
244
176
  },
245
177
  "validation": {
246
178
  "defaultFieldName": "The field"
@@ -1,5 +1,5 @@
1
1
  import type { Command } from "commander";
2
- import type { ITsToSchemaConfig } from "../models/ITsToSchemaConfig";
2
+ import type { ITsToSchemaConfig } from "../models/ITsToSchemaConfig.js";
3
3
  /**
4
4
  * Build the root command to be consumed by the CLI.
5
5
  * @param program The command to build on.
@@ -1,3 +1,3 @@
1
- export * from "./cli";
2
- export * from "./commands/tsToSchema";
3
- export * from "./models/ITsToSchemaConfig";
1
+ export * from "./cli.js";
2
+ export * from "./commands/tsToSchema.js";
3
+ export * from "./models/ITsToSchemaConfig.js";
package/docs/changelog.md CHANGED
@@ -1,5 +1,63 @@
1
1
  # @twin.org/ts-to-schema - Changelog
2
2
 
3
+ ## [0.0.3-next.1](https://github.com/twinfoundation/tools/compare/ts-to-schema-v0.0.3-next.0...ts-to-schema-v0.0.3-next.1) (2025-11-10)
4
+
5
+
6
+ ### Features
7
+
8
+ * add context id features ([#54](https://github.com/twinfoundation/tools/issues/54)) ([41ad65d](https://github.com/twinfoundation/tools/commit/41ad65d5ae33d0533d32a2864cd94e5c35e56c76))
9
+ * add support for auto expand types ([dd1e10a](https://github.com/twinfoundation/tools/commit/dd1e10a5b2fea6f80890ff6f3971f48e239cb4c1))
10
+ * add ts-to-schema overrides ([3c54504](https://github.com/twinfoundation/tools/commit/3c5450468eb998204a75576b7791a7ca4027da62))
11
+ * add validate-locales ([97bb11f](https://github.com/twinfoundation/tools/commit/97bb11fd9e6ed400e7fa69671075ba78f36ca6e6))
12
+ * correctly handle auto expand types ([57fce0f](https://github.com/twinfoundation/tools/commit/57fce0f9ec4a0876665d70adc6e885f6feb3caf7))
13
+ * eslint migration to flat config ([25acfcf](https://github.com/twinfoundation/tools/commit/25acfcf4c4e0c496fffeaf67659fe171bc15199a))
14
+ * generate schemas as individual entities ([9f372ab](https://github.com/twinfoundation/tools/commit/9f372abdfc27aba93b303c7b214991919c0c18c3))
15
+ * improve auto expand types ([6181d1d](https://github.com/twinfoundation/tools/commit/6181d1daded1f91323195cf7efbc2f1881f38b41))
16
+ * improve schema type name normalisation ([1a18b26](https://github.com/twinfoundation/tools/commit/1a18b267d87e9179bda01b396b256c450ae2889e))
17
+ * move package to framework repo ([4490bda](https://github.com/twinfoundation/tools/commit/4490bda472d4dc8ddfe931e2fce81f3411de9ab3))
18
+ * use most recent JSON schema specs ([4598cbf](https://github.com/twinfoundation/tools/commit/4598cbf29f7b82dba4a9f3b19f81dfe66f5a6060))
19
+ * use shared store mechanism ([#31](https://github.com/twinfoundation/tools/issues/31)) ([d9fe68b](https://github.com/twinfoundation/tools/commit/d9fe68b903d1268c7cb3c64772df5cb78fd63667))
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * remove debugging ([4def3d1](https://github.com/twinfoundation/tools/commit/4def3d1ef6a41a3b3358f864214e6a7ec3f9c638))
25
+
26
+
27
+ ### Dependencies
28
+
29
+ * The following workspace dependencies were updated
30
+ * dependencies
31
+ * @twin.org/tools-core bumped from 0.0.3-next.0 to 0.0.3-next.1
32
+
33
+ ## [0.0.2-next.10](https://github.com/twinfoundation/tools/compare/ts-to-schema-v0.0.2-next.9...ts-to-schema-v0.0.2-next.10) (2025-10-09)
34
+
35
+
36
+ ### Features
37
+
38
+ * add validate-locales ([97bb11f](https://github.com/twinfoundation/tools/commit/97bb11fd9e6ed400e7fa69671075ba78f36ca6e6))
39
+
40
+
41
+ ### Dependencies
42
+
43
+ * The following workspace dependencies were updated
44
+ * dependencies
45
+ * @twin.org/tools-core bumped from 0.0.2-next.9 to 0.0.2-next.10
46
+
47
+ ## [0.0.2-next.9](https://github.com/twinfoundation/tools/compare/ts-to-schema-v0.0.2-next.8...ts-to-schema-v0.0.2-next.9) (2025-09-23)
48
+
49
+
50
+ ### Miscellaneous Chores
51
+
52
+ * **ts-to-schema:** Synchronize repo versions
53
+
54
+
55
+ ### Dependencies
56
+
57
+ * The following workspace dependencies were updated
58
+ * dependencies
59
+ * @twin.org/tools-core bumped from 0.0.2-next.8 to 0.0.2-next.9
60
+
3
61
  ## [0.0.2-next.8](https://github.com/twinfoundation/tools/compare/ts-to-schema-v0.0.2-next.7...ts-to-schema-v0.0.2-next.8) (2025-09-05)
4
62
 
5
63
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twin.org/ts-to-schema",
3
- "version": "0.0.2-next.8",
3
+ "version": "0.0.3-next.1",
4
4
  "description": "Tool to convert TypeScript definitions to JSON schemas",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,25 +17,23 @@
17
17
  "@twin.org/cli-core": "next",
18
18
  "@twin.org/core": "next",
19
19
  "@twin.org/nameof": "next",
20
- "@twin.org/tools-core": "0.0.2-next.8",
21
- "commander": "14.0.0",
20
+ "@twin.org/tools-core": "0.0.3-next.1",
21
+ "commander": "14.0.2",
22
22
  "glob": "11.0.3",
23
23
  "ts-json-schema-generator": "2.4.0"
24
24
  },
25
- "main": "./dist/cjs/index.cjs",
26
- "module": "./dist/esm/index.mjs",
25
+ "main": "./dist/es/index.js",
27
26
  "types": "./dist/types/index.d.ts",
28
27
  "exports": {
29
28
  ".": {
30
29
  "types": "./dist/types/index.d.ts",
31
- "require": "./dist/cjs/index.cjs",
32
- "import": "./dist/esm/index.mjs"
30
+ "import": "./dist/es/index.js",
31
+ "default": "./dist/es/index.js"
33
32
  }
34
33
  },
35
34
  "files": [
36
35
  "bin",
37
- "dist/cjs",
38
- "dist/esm",
36
+ "dist/es",
39
37
  "dist/locales",
40
38
  "dist/types",
41
39
  "locales",
@@ -43,5 +41,17 @@
43
41
  ],
44
42
  "bin": {
45
43
  "ts-to-schema": "bin/index.js"
46
- }
44
+ },
45
+ "keywords": [
46
+ "twin",
47
+ "trade",
48
+ "iota",
49
+ "framework",
50
+ "blockchain",
51
+ "tools"
52
+ ],
53
+ "bugs": {
54
+ "url": "git+https://github.com/twinfoundation/tools/issues"
55
+ },
56
+ "homepage": "https://twindev.org"
47
57
  }
@@ -1,206 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('node:path');
4
- var node_url = require('node:url');
5
- var cliCore = require('@twin.org/cli-core');
6
- var promises = require('node:fs/promises');
7
- var core = require('@twin.org/core');
8
- var toolsCore = require('@twin.org/tools-core');
9
- var tsJsonSchemaGenerator = require('ts-json-schema-generator');
10
-
11
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
- // Copyright 2024 IOTA Stiftung.
13
- // SPDX-License-Identifier: Apache-2.0.
14
- /**
15
- * Build the root command to be consumed by the CLI.
16
- * @param program The command to build on.
17
- */
18
- function buildCommandTsToSchema(program) {
19
- program
20
- .argument(core.I18n.formatMessage("commands.ts-to-schema.options.config.param"), core.I18n.formatMessage("commands.ts-to-schema.options.config.description"))
21
- .argument(core.I18n.formatMessage("commands.ts-to-schema.options.output-folder.param"), core.I18n.formatMessage("commands.ts-to-schema.options.output-folder.description"))
22
- .action(async (config, outputFolder, opts) => {
23
- await actionCommandTsToSchema(config, outputFolder);
24
- });
25
- }
26
- /**
27
- * Action the root command.
28
- * @param configFile The optional configuration file.
29
- * @param outputFolder The output folder for the schemas.
30
- * @param opts The options for the command.
31
- */
32
- async function actionCommandTsToSchema(configFile, outputFolder, opts) {
33
- let outputWorkingDir;
34
- try {
35
- let config;
36
- const fullConfigFile = path.resolve(configFile);
37
- const fullOutputFolder = path.resolve(outputFolder);
38
- outputWorkingDir = path.join(fullOutputFolder, "working");
39
- cliCore.CLIDisplay.value(core.I18n.formatMessage("commands.ts-to-schema.labels.configJson"), fullConfigFile);
40
- cliCore.CLIDisplay.value(core.I18n.formatMessage("commands.ts-to-schema.labels.outputFolder"), fullOutputFolder);
41
- cliCore.CLIDisplay.value(core.I18n.formatMessage("commands.ts-to-schema.labels.outputWorkingDir"), outputWorkingDir);
42
- cliCore.CLIDisplay.break();
43
- try {
44
- cliCore.CLIDisplay.task(core.I18n.formatMessage("commands.ts-to-schema.progress.loadingConfigJson"));
45
- cliCore.CLIDisplay.break();
46
- config = await cliCore.CLIUtils.readJsonFile(fullConfigFile);
47
- }
48
- catch (err) {
49
- throw new core.GeneralError("commands", "commands.ts-to-schema.configFailed", undefined, err);
50
- }
51
- if (core.Is.empty(config)) {
52
- throw new core.GeneralError("commands", "commands.ts-to-schema.configFailed");
53
- }
54
- cliCore.CLIDisplay.task(core.I18n.formatMessage("commands.ts-to-schema.progress.creatingWorkingDir"));
55
- await promises.mkdir(outputWorkingDir, { recursive: true });
56
- cliCore.CLIDisplay.break();
57
- await tsToSchema(config ?? {}, fullOutputFolder, outputWorkingDir);
58
- cliCore.CLIDisplay.break();
59
- cliCore.CLIDisplay.done();
60
- }
61
- finally {
62
- try {
63
- if (outputWorkingDir) {
64
- await promises.rm(outputWorkingDir, { recursive: true });
65
- }
66
- }
67
- catch { }
68
- }
69
- }
70
- /**
71
- * Convert the TypeScript definitions to JSON Schemas.
72
- * @param config The configuration for the app.
73
- * @param outputFolder The location of the folder to output the JSON schemas.
74
- * @param workingDirectory The folder the app was run from.
75
- */
76
- async function tsToSchema(config, outputFolder, workingDirectory) {
77
- await promises.writeFile(path.join(workingDirectory, "tsconfig.json"), JSON.stringify({
78
- compilerOptions: {}
79
- }, undefined, "\t"));
80
- cliCore.CLIDisplay.break();
81
- cliCore.CLIDisplay.task(core.I18n.formatMessage("commands.ts-to-schema.progress.writingSchemas"));
82
- for (const typeSource of config.types) {
83
- const typeSourceParts = typeSource.split("/");
84
- const type = core.StringHelper.pascalCase(typeSourceParts[typeSourceParts.length - 1].replace(/(\.d)?\.ts$/, ""), false);
85
- let schemaObject;
86
- if (core.Is.object(config.overrides?.[type])) {
87
- cliCore.CLIDisplay.task(core.I18n.formatMessage("commands.ts-to-schema.progress.overridingSchema"));
88
- schemaObject = config.overrides?.[type];
89
- }
90
- else {
91
- cliCore.CLIDisplay.task(core.I18n.formatMessage("commands.ts-to-schema.progress.generatingSchema"));
92
- const autoExpandTypes = config.autoExpandTypes ?? [];
93
- const defaultExpandTypes = ["/ObjectOrArray<.*>/"];
94
- for (const defaultType of defaultExpandTypes) {
95
- if (!autoExpandTypes.includes(defaultType)) {
96
- autoExpandTypes.push(defaultType);
97
- }
98
- }
99
- const schemas = await generateSchemas(typeSource, type, autoExpandTypes, workingDirectory);
100
- if (core.Is.empty(schemas[type])) {
101
- throw new core.GeneralError("commands", "commands.ts-to-schema.schemaNotFound", { type });
102
- }
103
- schemaObject = schemas[type];
104
- }
105
- schemaObject = finaliseSchema(schemaObject, config.baseUrl, type);
106
- let content = JSON.stringify(schemaObject, undefined, "\t");
107
- if (core.Is.objectValue(config.externalReferences)) {
108
- for (const external in config.externalReferences) {
109
- content = content.replace(new RegExp(`#/definitions/${external}`, "g"), config.externalReferences[external]);
110
- }
111
- }
112
- // First replace all types that start with II to a single I with the new base url
113
- content = content.replace(/#\/definitions\/II(.*)/g, `${config.baseUrl}I$1`);
114
- // Then other types starting with capitals (optionally interfaces starting with I)
115
- content = content.replace(/#\/definitions\/I?([A-Z].*)/g, `${config.baseUrl}$1`);
116
- const filename = path.join(outputFolder, `${core.StringHelper.stripPrefix(type)}.json`);
117
- cliCore.CLIDisplay.value(core.I18n.formatMessage("commands.ts-to-schema.progress.writingSchema"), filename, 1);
118
- await promises.writeFile(filename, `${content}\n`);
119
- }
120
- }
121
- /**
122
- * Generate schemas for the models.
123
- * @param modelDirWildcards The filenames for all the models.
124
- * @param types The types of the schema objects.
125
- * @param autoExpandTypes The types to automatically expand.
126
- * @param outputWorkingDir The working directory.
127
- * @returns Nothing.
128
- * @internal
129
- */
130
- async function generateSchemas(typeSource, type, autoExpandTypes, outputWorkingDir) {
131
- const allSchemas = {};
132
- cliCore.CLIDisplay.value(core.I18n.formatMessage("commands.ts-to-schema.progress.models"), typeSource, 1);
133
- const generator = tsJsonSchemaGenerator.createGenerator({
134
- path: typeSource,
135
- type,
136
- tsconfig: path.join(outputWorkingDir, "tsconfig.json"),
137
- skipTypeCheck: true,
138
- expose: "all"
139
- });
140
- const schema = generator.createSchema("*");
141
- if (schema.definitions) {
142
- for (const def in schema.definitions) {
143
- const defSub = toolsCore.JsonSchemaHelper.normaliseTypeName(def);
144
- allSchemas[defSub] = schema.definitions[def];
145
- }
146
- }
147
- const referencedSchemas = {};
148
- toolsCore.JsonSchemaHelper.extractTypes(allSchemas, [type, ...autoExpandTypes], referencedSchemas);
149
- toolsCore.JsonSchemaHelper.expandTypes(referencedSchemas, autoExpandTypes);
150
- return referencedSchemas;
151
- }
152
- /**
153
- * Process the schema object to ensure it has the correct properties.
154
- * @param schemaObject The schema object to process.
155
- * @param baseUrl The base URL for the schema references.
156
- * @param type The type of the schema object.
157
- * @returns The finalised schema object.
158
- */
159
- function finaliseSchema(schemaObject, baseUrl, type) {
160
- toolsCore.JsonSchemaHelper.processArrays(schemaObject);
161
- const { description, ...rest } = schemaObject;
162
- return {
163
- $schema: toolsCore.JsonSchemaHelper.SCHEMA_VERSION,
164
- $id: `${baseUrl}${core.StringHelper.stripPrefix(type)}`,
165
- description,
166
- ...rest
167
- };
168
- }
169
-
170
- // Copyright 2024 IOTA Stiftung.
171
- // SPDX-License-Identifier: Apache-2.0.
172
- /**
173
- * The main entry point for the CLI.
174
- */
175
- class CLI extends cliCore.CLIBase {
176
- /**
177
- * Run the app.
178
- * @param argv The process arguments.
179
- * @param localesDirectory The directory for the locales, default to relative to the script.
180
- * @param options Additional options.
181
- * @param options.overrideOutputWidth Override the output width.
182
- * @returns The exit code.
183
- */
184
- async run(argv, localesDirectory, options) {
185
- return this.execute({
186
- title: "TWIN TypeScript To Schema",
187
- appName: "ts-to-schema",
188
- version: "0.0.2-next.8", // x-release-please-version
189
- icon: "⚙️ ",
190
- supportsEnvFiles: false,
191
- overrideOutputWidth: options?.overrideOutputWidth
192
- }, localesDirectory ?? path.join(path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))), "../locales"), argv);
193
- }
194
- /**
195
- * Configure any options or actions at the root program level.
196
- * @param program The root program command.
197
- */
198
- configureRoot(program) {
199
- buildCommandTsToSchema(program);
200
- }
201
- }
202
-
203
- exports.CLI = CLI;
204
- exports.actionCommandTsToSchema = actionCommandTsToSchema;
205
- exports.buildCommandTsToSchema = buildCommandTsToSchema;
206
- exports.tsToSchema = tsToSchema;