@x-dome/joi-to-typescript 4.15.0

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.
Files changed (86) hide show
  1. package/.yarnrc.yml +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +343 -0
  4. package/SECURITY.md +9 -0
  5. package/dist/main/analyseSchemaFile.d.ts +12 -0
  6. package/dist/main/analyseSchemaFile.d.ts.map +1 -0
  7. package/dist/main/analyseSchemaFile.js +149 -0
  8. package/dist/main/convertFilesInDirectory.d.ts +7 -0
  9. package/dist/main/convertFilesInDirectory.d.ts.map +1 -0
  10. package/dist/main/convertFilesInDirectory.js +83 -0
  11. package/dist/main/index.d.ts +12 -0
  12. package/dist/main/index.d.ts.map +1 -0
  13. package/dist/main/index.js +68 -0
  14. package/dist/main/joiDescribeTypes.d.ts +92 -0
  15. package/dist/main/joiDescribeTypes.d.ts.map +1 -0
  16. package/dist/main/joiDescribeTypes.js +2 -0
  17. package/dist/main/joiUtils.d.ts +28 -0
  18. package/dist/main/joiUtils.d.ts.map +1 -0
  19. package/dist/main/joiUtils.js +115 -0
  20. package/dist/main/parse.d.ts +15 -0
  21. package/dist/main/parse.d.ts.map +1 -0
  22. package/dist/main/parse.js +666 -0
  23. package/dist/main/types.d.ts +281 -0
  24. package/dist/main/types.d.ts.map +1 -0
  25. package/dist/main/types.js +42 -0
  26. package/dist/main/utils.d.ts +16 -0
  27. package/dist/main/utils.d.ts.map +1 -0
  28. package/dist/main/utils.js +45 -0
  29. package/dist/main/write.d.ts +20 -0
  30. package/dist/main/write.d.ts.map +1 -0
  31. package/dist/main/write.js +122 -0
  32. package/dist/main/writeInterfaceFile.d.ts +8 -0
  33. package/dist/main/writeInterfaceFile.d.ts.map +1 -0
  34. package/dist/main/writeInterfaceFile.js +82 -0
  35. package/dist/module/analyseSchemaFile.d.ts +12 -0
  36. package/dist/module/analyseSchemaFile.d.ts.map +1 -0
  37. package/dist/module/analyseSchemaFile.js +109 -0
  38. package/dist/module/convertFilesInDirectory.d.ts +7 -0
  39. package/dist/module/convertFilesInDirectory.d.ts.map +1 -0
  40. package/dist/module/convertFilesInDirectory.js +77 -0
  41. package/dist/module/index.d.ts +12 -0
  42. package/dist/module/index.d.ts.map +1 -0
  43. package/dist/module/index.js +61 -0
  44. package/dist/module/joiDescribeTypes.d.ts +92 -0
  45. package/dist/module/joiDescribeTypes.d.ts.map +1 -0
  46. package/dist/module/joiDescribeTypes.js +1 -0
  47. package/dist/module/joiUtils.d.ts +28 -0
  48. package/dist/module/joiUtils.d.ts.map +1 -0
  49. package/dist/module/joiUtils.js +107 -0
  50. package/dist/module/parse.d.ts +15 -0
  51. package/dist/module/parse.d.ts.map +1 -0
  52. package/dist/module/parse.js +657 -0
  53. package/dist/module/types.d.ts +281 -0
  54. package/dist/module/types.d.ts.map +1 -0
  55. package/dist/module/types.js +36 -0
  56. package/dist/module/utils.d.ts +16 -0
  57. package/dist/module/utils.d.ts.map +1 -0
  58. package/dist/module/utils.js +40 -0
  59. package/dist/module/write.d.ts +20 -0
  60. package/dist/module/write.d.ts.map +1 -0
  61. package/dist/module/write.js +113 -0
  62. package/dist/module/writeInterfaceFile.d.ts +8 -0
  63. package/dist/module/writeInterfaceFile.d.ts.map +1 -0
  64. package/dist/module/writeInterfaceFile.js +76 -0
  65. package/dist/types/analyseSchemaFile.d.ts +12 -0
  66. package/dist/types/analyseSchemaFile.d.ts.map +1 -0
  67. package/dist/types/convertFilesInDirectory.d.ts +7 -0
  68. package/dist/types/convertFilesInDirectory.d.ts.map +1 -0
  69. package/dist/types/index.d.ts +12 -0
  70. package/dist/types/index.d.ts.map +1 -0
  71. package/dist/types/joiDescribeTypes.d.ts +92 -0
  72. package/dist/types/joiDescribeTypes.d.ts.map +1 -0
  73. package/dist/types/joiUtils.d.ts +28 -0
  74. package/dist/types/joiUtils.d.ts.map +1 -0
  75. package/dist/types/parse.d.ts +15 -0
  76. package/dist/types/parse.d.ts.map +1 -0
  77. package/dist/types/types.d.ts +281 -0
  78. package/dist/types/types.d.ts.map +1 -0
  79. package/dist/types/utils.d.ts +16 -0
  80. package/dist/types/utils.d.ts.map +1 -0
  81. package/dist/types/write.d.ts +20 -0
  82. package/dist/types/write.d.ts.map +1 -0
  83. package/dist/types/writeInterfaceFile.d.ts +8 -0
  84. package/dist/types/writeInterfaceFile.d.ts.map +1 -0
  85. package/joi-to-typescript-4.15.0.tgz +0 -0
  86. package/package.json +60 -0
package/.yarnrc.yml ADDED
@@ -0,0 +1,5 @@
1
+ compressionLevel: mixed
2
+
3
+ enableGlobalCache: false
4
+
5
+ nodeLinker: node-modules
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Jono
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,343 @@
1
+ # joi-to-typescript
2
+
3
+ [![NPM version][npm-image]][npm-url] ![Latest Build](https://github.com/mrjono1/joi-to-typescript/workflows/Node.js%20CI/badge.svg) ![NPM Release Build](https://github.com/mrjono1/joi-to-typescript/workflows/Node.js%20Package/badge.svg) ![GitHub top language](https://img.shields.io/github/languages/top/mrjono1/joi-to-typescript) [![codecov](https://codecov.io/gh/mrjono1/joi-to-typescript/branch/master/graph/badge.svg?token=7UtmWfj5cA)](https://codecov.io/gh/mrjono1/joi-to-typescript)
4
+ [![npm downloads](https://img.shields.io/npm/dm/joi-to-typescript.svg?style=flat-square)](https://npm-stat.com/charts.html?package=joi-to-typescript)
5
+ [![Known Vulnerabilities](https://snyk.io/test/npm/joi-to-typescript/badge.svg)](https://snyk.io/test/npm/joi-to-typescript)
6
+
7
+ [joi-to-typescript on GitHub](https://github.com/mrjono1/joi-to-typescript)
8
+
9
+ [npm-image]: https://img.shields.io/npm/v/joi-to-typescript.svg?style=flat
10
+ [npm-url]: https://www.npmjs.com/package/joi-to-typescript
11
+
12
+ Convert [Joi](https://github.com/sideway/joi) Schemas to TypeScript interfaces
13
+
14
+ This will allow you to use generate TypeScript interfaces from Joi Schemas giving you confidence the schema and interface match. You no longer have to manually create the same structure again, saving you time and reducing errors.
15
+
16
+ Works with any TypeScript project and also perfectly with [Hapi](https://github.com/hapijs/hapi) API requests/responses.
17
+
18
+ For generating Open Api/Swagger this project works with
19
+
20
+ - [joi-to-swagger](https://github.com/Twipped/joi-to-swagger) using `.meta({className:''})`
21
+ - [hapi-swagger](https://github.com/glennjones/hapi-swagger) using `.label('')`
22
+
23
+ The use of `.meta({className:'')` is preferred over `.label('')`, because `Joi.label()` is intended to be used for meaningful error message, using it for another purpose makes Joi lose a standard feature, this is especially noticeable for frontend usages of Joi. The choice of the property `className` is because this property is used by joi-to-swagger making this project work with other projects.
24
+
25
+ ## Installation Notes
26
+
27
+ This package is intended as a development time tool, so it should be installed in the `devDependencies`
28
+
29
+ ```bash
30
+ yarn add joi-to-typescript --dev
31
+ # or
32
+ npm install joi-to-typescript --save-dev
33
+ ```
34
+
35
+ You will also need to install `joi` in the `dependencies`
36
+
37
+ ```bash
38
+ yarn add joi
39
+ # or
40
+ npm install joi
41
+ ```
42
+
43
+ - This has been built for `"joi": "^17"` and will not work for older versions
44
+ - Supported node versions 18, 20
45
+
46
+ ## Suggested Usage
47
+
48
+ 1. Create a Schemas Folder eg. `src/schemas`
49
+ 1. Create a interfaces Folder eg. `src/interfaces`
50
+ 1. Create Joi Schemas in the Schemas folder with a file name suffix of Schemas eg. `AddressSchema.ts`
51
+ - The file name suffix ensures that type file and schema file imports are not confusing
52
+
53
+ ## Example
54
+
55
+ #### Example Project
56
+
57
+ Explore the [Example Projects](https://github.com/mrjono1/joi-to-typescript/tree/master/examples) for recommended setup, execute `yarn types` to run each one.
58
+
59
+ #### Example Schema
60
+
61
+ This example can be found in `src/__tests__/readme`
62
+
63
+ ```typescript
64
+ import Joi from 'joi';
65
+
66
+ // Input
67
+ export const JobSchema = Joi.object({
68
+ businessName: Joi.string().required(),
69
+ jobTitle: Joi.string().required()
70
+ }).meta({ className: 'Job' });
71
+
72
+ export const WalletSchema = Joi.object({
73
+ usd: Joi.number().required(),
74
+ eur: Joi.number().required()
75
+ })
76
+ .unknown()
77
+ .meta({ className: 'Wallet', unknownType: 'number' });
78
+
79
+ export const PersonSchema = Joi.object({
80
+ firstName: Joi.string().required(),
81
+ lastName: Joi.string().required().description('Last Name'),
82
+ job: JobSchema,
83
+ wallet: WalletSchema
84
+ }).meta({ className: 'Person' });
85
+
86
+ export const PeopleSchema = Joi.array()
87
+ .items(PersonSchema)
88
+ .required()
89
+ .meta({ className: 'People' })
90
+ .description('A list of People');
91
+
92
+ // Output
93
+ /**
94
+ * This file was automatically generated by joi-to-typescript
95
+ * Do not modify this file manually
96
+ */
97
+
98
+ export interface Job {
99
+ businessName: string;
100
+ jobTitle: string;
101
+ }
102
+
103
+ /**
104
+ * A list of People
105
+ */
106
+ export type People = Person[];
107
+
108
+ export interface Person {
109
+ firstName: string;
110
+ job?: Job;
111
+ /**
112
+ * Last Name
113
+ */
114
+ lastName: string;
115
+ wallet?: Wallet;
116
+ }
117
+
118
+ export interface Wallet {
119
+ /**
120
+ * Number Property
121
+ */
122
+ [x: string]: number;
123
+ eur: number;
124
+ usd: number;
125
+ }
126
+ ```
127
+
128
+ ##### Points of Interest
129
+
130
+ - `export const PersonSchema` schema must be exported
131
+ - `export const PersonSchema` includes a suffix of Schema so the schema and interface are not confused when using `import` statements (recommended not required)
132
+ - `.meta({ className: 'Person' });` Sets `interface` name using TypeScript conventions (TitleCase Interface name, camelCase property name)
133
+ - `.meta({ unknownType: 'number' });` assert unknown type to `number`
134
+
135
+ #### Upgrade Notice
136
+
137
+ - Version 1 used `.label('Person')` as the way to define the `interface` name, to use this option set `{ useLabelAsInterfaceName: true }`
138
+
139
+ #### Example Call
140
+
141
+ ```typescript
142
+ import { convertFromDirectory } from 'joi-to-typescript';
143
+
144
+ convertFromDirectory({
145
+ schemaDirectory: './src/schemas',
146
+ typeOutputDirectory: './src/interfaces',
147
+ debug: true
148
+ });
149
+
150
+ // or to get an interface as a string. Please note that this method is limited
151
+ import { convertSchema } from 'joi-to-typescript';
152
+ const resultingInterface = convertSchema({}, JobSchema);
153
+ resultingInterface?.content = // the interface as a string
154
+ ```
155
+
156
+ ## Settings
157
+
158
+ ```typescript
159
+ export interface Settings {
160
+ /**
161
+ * The input/schema directory
162
+ * Directory must exist
163
+ */
164
+ schemaDirectory: string;
165
+ /**
166
+ * The output/type directory
167
+ * Will also attempt to create this directory
168
+ */
169
+ typeOutputDirectory: string;
170
+ /**
171
+ * Use .label('InterfaceName') instead of .meta({className:'InterfaceName'}) for interface names
172
+ */
173
+ useLabelAsInterfaceName: boolean;
174
+ /**
175
+ * If defined, when a schema name ends with "schema", replaces the ending in the generated type by default
176
+ * with this string.
177
+ * E.g. when this setting is "Interface", a `TestSchema` object generates a `TestInterface` type
178
+ */
179
+ defaultInterfaceSuffix?: string;
180
+ /**
181
+ * Should interface properties be defaulted to optional or required
182
+ * @default false
183
+ */
184
+ defaultToRequired: boolean;
185
+ /**
186
+ * What schema file name suffix will be removed when creating the interface file name
187
+ * @default "Schema"
188
+ * This ensures that an interface and Schema with the file name are not confused
189
+ */
190
+ schemaFileSuffix: string;
191
+ /**
192
+ * If provided, appends this suffix to the generated interface filenames
193
+ * @default ""
194
+ */
195
+ interfaceFileSuffix: string;
196
+ /**
197
+ * If `true` the console will include more information
198
+ * @default false
199
+ */
200
+ debug: boolean;
201
+ /**
202
+ * File Header content for generated files
203
+ */
204
+ fileHeader: string;
205
+ /**
206
+ * If true will sort properties on interface by name
207
+ * @default true
208
+ */
209
+ sortPropertiesByName: boolean;
210
+ /**
211
+ * If true will not output to subDirectories in output/interface directory. It will flatten the structure.
212
+ */
213
+ flattenTree: boolean;
214
+ /**
215
+ * If true will only read the files in the root directory of the input/schema directory. Will not parse through sub-directories.
216
+ */
217
+ rootDirectoryOnly: boolean;
218
+ /**
219
+ * If true will write all exports *'s to root index.ts in output/interface directory.
220
+ */
221
+ indexAllToRoot: boolean;
222
+ /**
223
+ * Comment every interface and property even with just a duplicate of the interface and property name
224
+ * @default false
225
+ */
226
+ commentEverything: boolean;
227
+ /**
228
+ * List of files or folders that should be ignored from conversion. These can either be
229
+ * filenames (AddressSchema.ts) or filepaths postfixed with a / (addressSchemas/)
230
+ * @default []
231
+ */
232
+ ignoreFiles: string[];
233
+ /**
234
+ * The indentation characters
235
+ * @default ' ' (two spaces)
236
+ */
237
+ indentationChacters: string;
238
+ /**
239
+ * If set to true, will use double quotes for strings
240
+ * @default false
241
+ */
242
+ doublequoteEscape: boolean;
243
+ /**
244
+ * If a field has a default and is optional, consider it as required
245
+ * @default false
246
+ */
247
+ treatDefaultedOptionalAsRequired: boolean;
248
+ /**
249
+ * If a field has a default, modify the resulting field to equal
250
+ * `field: <default> | type` rather than `field: type`
251
+ * @default false
252
+ */
253
+ supplyDefaultsInType: boolean;
254
+ /**
255
+ * If a field has a default value, add its stringified representation
256
+ * to the JsDoc using the @default annotation
257
+ * @default false
258
+ */
259
+ supplyDefaultsInJsDoc: boolean;
260
+ /**
261
+ * Filter files you wish to parse
262
+ * The class `InputFileFilter` contains some default options
263
+ * @default *.ts files
264
+ */
265
+ inputFileFilter: RegExp;
266
+ /**
267
+ * If true, skips the creation of index.ts files in the generated interface directories
268
+ * @default false
269
+ */
270
+ omitIndexFiles: boolean
271
+ /**
272
+ * If provided, prepends the content returned by the function to the
273
+ * generated interface/type code (including and JSDoc).
274
+ */
275
+ tsContentHeader?: (type: ConvertedType) => string;
276
+ /**
277
+ * If provided, appends the content returned by the function to the
278
+ * generated interface/type code.
279
+ */
280
+ tsContentFooter?: (type: ConvertedType) => string;
281
+ /**
282
+ * If defined, place every member of a union on a new line
283
+ */
284
+ unionNewLine?: boolean;
285
+ /**
286
+ * If defined, place every member of a tuple on a new line
287
+ */
288
+ tupleNewLine?: boolean;
289
+ }
290
+ ```
291
+
292
+ ## Joi Features Supported
293
+
294
+ - `.meta({className:'InterfaceName'})` - interface Name and in jsDoc
295
+ - `.description('What this interface is for')` - jsdoc
296
+ - `.optional()` - optional properties `?`
297
+ - `.required()` - required properties
298
+ - `.valid(['red', 'green', 'blue'])` - enumerations - `allow` can be used for enumerations but `valid` works better see `_tests_/allow/allow.ts` for more information
299
+ - `.allow('')` - will be ignored on a string
300
+ - `.allow(null)` - will add as an optional type eg `string | null`
301
+ - `.array()`, `.object()`, `.string()`, `.number()`, `.boolean()` - standard Joi schemas
302
+ - `.alternatives()` - try is supported, conditionals would be converted to `any`
303
+ - `.unknown(true)` - will add a property `[x: string]: unknown;` to the interface
304
+ - Assert `unknown` to some type with a stringified type or a Joi schema, e.g.:
305
+ ```typescript
306
+ .meta({ unknownType: 'some-type' })
307
+ ```
308
+ ```typescript
309
+ .meta({ unknownType: Joi.object({ id: Joi.string() }) })`
310
+ ```
311
+ - `.example()` - jsdoc
312
+ - `.cast()` - currently will honor casting to string and number types, map and set to be added later
313
+ - `.forbidden()` will set the type to `undefined`
314
+ - `.meta({ readonly: true })` to create readonly properties like `readonly property: string;`
315
+ - `.ordered()`
316
+ - And many others
317
+
318
+ ## Contributing
319
+
320
+ - Raise or comment on an [Issue](https://github.com/mrjono1/joi-to-typescript/issues) with a bug or feature request
321
+ - Contribute code via Raising a [Pull Request](https://github.com/mrjono1/joi-to-typescript/pulls)
322
+ - Start a [Discussion](https://github.com/mrjono1/joi-to-typescript/discussions)
323
+
324
+ ### Recommended Development Environment
325
+
326
+ Recommended Editor is VS Code, this project is setup with VSCode settings in the `./.vscode` directory to keep development consistent.
327
+
328
+ Best developed on macOS, Linux, or on Windows via WSL.
329
+
330
+ Install [nodejs](https://nodejs.org/) via [nvm](https://github.com/nvm-sh/nvm) so you can have multiple versions installed
331
+
332
+ ```bash
333
+ nvm use # using NVM to select node version
334
+ yarn install # using yarn
335
+ yarn test # run local tests
336
+
337
+ yarn coverage # test coverage report
338
+ yarn lint # lint the code
339
+ ```
340
+
341
+ ### Change Log
342
+
343
+ See [GitHub Releases](https://github.com/mrjono1/joi-to-typescript/releases)
package/SECURITY.md ADDED
@@ -0,0 +1,9 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Only the latest version will get security updates
6
+
7
+ ## Reporting a Vulnerability
8
+
9
+ If a security vulnerability is found please raise an [Issue](https://github.com/mrjono1/joi-to-typescript/issues) to report or a [Pull Request](https://github.com/mrjono1/joi-to-typescript/pulls) to fix the issue
@@ -0,0 +1,12 @@
1
+ import { AnySchema } from 'joi';
2
+ import { Settings, ConvertedType, GenerateTypeFile } from './types';
3
+ export declare function convertSchemaInternal(settings: Settings, joi: AnySchema, exportedName?: string, rootSchema?: boolean): ConvertedType | undefined;
4
+ /**
5
+ * Analyse a schema file
6
+ *
7
+ * @param settings - Settings
8
+ * @param schemaFileName - Schema File Name
9
+ * @returns Schema analysis results
10
+ */
11
+ export declare function analyseSchemaFile(settings: Settings, schemaFileName: string): Promise<undefined | GenerateTypeFile>;
12
+ //# sourceMappingURL=analyseSchemaFile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyseSchemaFile.d.ts","sourceRoot":"","sources":["../../src/analyseSchemaFile.ts"],"names":[],"mappings":"AAAA,OAAY,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAGrC,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAMpE,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,QAAQ,EAClB,GAAG,EAAE,SAAS,EACd,YAAY,CAAC,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,OAAO,GACnB,aAAa,GAAG,SAAS,CAmD3B;AACD;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,QAAQ,EAClB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,SAAS,GAAG,gBAAgB,CAAC,CAwEvC"}
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.convertSchemaInternal = convertSchemaInternal;
40
+ exports.analyseSchemaFile = analyseSchemaFile;
41
+ const joi_1 = __importDefault(require("joi"));
42
+ const path_1 = __importDefault(require("path"));
43
+ const write_1 = require("./write");
44
+ const parse_1 = require("./parse");
45
+ const joiUtils_1 = require("./joiUtils");
46
+ function convertSchemaInternal(settings, joi, exportedName, rootSchema) {
47
+ const details = joi.describe();
48
+ const interfaceOrTypeName = (0, joiUtils_1.getInterfaceOrTypeName)(settings, details) || exportedName;
49
+ if (!interfaceOrTypeName) {
50
+ if (settings.useLabelAsInterfaceName) {
51
+ throw new Error(`At least one "object" does not have .label(''). Details: ${JSON.stringify(details)}`);
52
+ }
53
+ else {
54
+ throw new Error(`At least one "object" does not have .meta({className:''}). Details: ${JSON.stringify(details)}`);
55
+ }
56
+ }
57
+ if (settings.debug && interfaceOrTypeName.toLowerCase().endsWith('schema')) {
58
+ if (settings.useLabelAsInterfaceName) {
59
+ // eslint-disable-next-line no-console
60
+ console.debug(`It is recommended you update the Joi Schema '${interfaceOrTypeName}' similar to: ${interfaceOrTypeName} = Joi.object().label('${interfaceOrTypeName.replace('Schema', '')}')`);
61
+ }
62
+ else {
63
+ // eslint-disable-next-line no-console
64
+ console.debug(`It is recommended you update the Joi Schema '${interfaceOrTypeName}' similar to: ${interfaceOrTypeName} = Joi.object().meta({className:'${interfaceOrTypeName.replace('Schema', '')}'})`);
65
+ }
66
+ }
67
+ (0, joiUtils_1.ensureInterfaceorTypeName)(settings, details, interfaceOrTypeName);
68
+ const parsedSchema = (0, parse_1.parseSchema)(details, settings, false, undefined, rootSchema);
69
+ if (parsedSchema) {
70
+ const customTypes = (0, parse_1.getAllCustomTypes)(parsedSchema);
71
+ const content = (0, parse_1.typeContentToTs)(settings, parsedSchema, true);
72
+ return {
73
+ schema: joi,
74
+ interfaceOrTypeName,
75
+ customTypes,
76
+ content
77
+ };
78
+ }
79
+ // The only type that could return this is alternatives
80
+ // see parseAlternatives for why this is ignored
81
+ /* istanbul ignore next */
82
+ return undefined;
83
+ }
84
+ /**
85
+ * Analyse a schema file
86
+ *
87
+ * @param settings - Settings
88
+ * @param schemaFileName - Schema File Name
89
+ * @returns Schema analysis results
90
+ */
91
+ async function analyseSchemaFile(settings, schemaFileName) {
92
+ const allConvertedTypes = [];
93
+ const fullFilePath = path_1.default.resolve(path_1.default.join(settings.schemaDirectory, schemaFileName));
94
+ const schemaFile = await Promise.resolve(`${fullFilePath}`).then(s => __importStar(require(s)));
95
+ // Create Type File Name
96
+ const typeFileName = (0, write_1.getTypeFileNameFromSchema)(schemaFileName, settings);
97
+ const fullOutputFilePath = path_1.default.join(settings.typeOutputDirectory, typeFileName);
98
+ for (const exportedName in schemaFile) {
99
+ const joiSchema = schemaFile[exportedName];
100
+ if (!joi_1.default.isSchema(joiSchema)) {
101
+ continue;
102
+ }
103
+ const convertedType = convertSchemaInternal(settings, joiSchema, exportedName, true);
104
+ if (convertedType) {
105
+ allConvertedTypes.push({ ...convertedType, location: fullOutputFilePath });
106
+ }
107
+ }
108
+ if (allConvertedTypes.length === 0) {
109
+ if (settings.debug) {
110
+ // eslint-disable-next-line no-console
111
+ console.debug(`${schemaFileName} - Skipped - no Joi Schemas found`);
112
+ }
113
+ return;
114
+ }
115
+ if (settings.debug) {
116
+ // eslint-disable-next-line no-console
117
+ console.debug(`${schemaFileName} - Processing`);
118
+ }
119
+ // Clean up type list
120
+ // Sort Types
121
+ const typesToBeWritten = allConvertedTypes.sort((interface1, interface2) => 0 - (interface1.interfaceOrTypeName > interface2.interfaceOrTypeName ? -1 : 1));
122
+ // Write types
123
+ const typeContent = typesToBeWritten.map(typeToBeWritten => {
124
+ const content = typeToBeWritten.content;
125
+ return [
126
+ ...(settings.tsContentHeader ? [settings.tsContentHeader(typeToBeWritten)] : []),
127
+ content,
128
+ ...(settings.tsContentFooter ? [settings.tsContentFooter(typeToBeWritten)] : [])
129
+ ].join('\n');
130
+ });
131
+ // Get imports for the current file
132
+ const allExternalTypes = [];
133
+ const allCurrentFileTypeNames = typesToBeWritten.map(typeToBeWritten => typeToBeWritten.interfaceOrTypeName);
134
+ for (const typeToBeWritten of typesToBeWritten) {
135
+ for (const customType of typeToBeWritten.customTypes) {
136
+ if (!allCurrentFileTypeNames.includes(customType) && !allExternalTypes.includes(typeToBeWritten)) {
137
+ allExternalTypes.push(typeToBeWritten);
138
+ }
139
+ }
140
+ }
141
+ const fileContent = `${typeContent.join('\n\n').concat('\n')}`;
142
+ return {
143
+ externalTypes: allExternalTypes,
144
+ internalTypes: typesToBeWritten,
145
+ fileContent,
146
+ typeFileName,
147
+ typeFileLocation: settings.typeOutputDirectory
148
+ };
149
+ }
@@ -0,0 +1,7 @@
1
+ import { Settings, GenerateTypeFile, GenerateTypesDir } from './types';
2
+ /**
3
+ * Create types from schemas from a directory
4
+ * @param settings Settings
5
+ */
6
+ export declare function convertFilesInDirectory(appSettings: Settings, ogTypeOutputDir: string, fileTypesToExport?: GenerateTypeFile[]): Promise<GenerateTypesDir>;
7
+ //# sourceMappingURL=convertFilesInDirectory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertFilesInDirectory.d.ts","sourceRoot":"","sources":["../../src/convertFilesInDirectory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAIvE;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,QAAQ,EACrB,eAAe,EAAE,MAAM,EACvB,iBAAiB,GAAE,gBAAgB,EAAO,GACzC,OAAO,CAAC,gBAAgB,CAAC,CAgF3B"}
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.convertFilesInDirectory = convertFilesInDirectory;
7
+ const path_1 = __importDefault(require("path"));
8
+ const fs_1 = require("fs");
9
+ const write_1 = require("./write");
10
+ const analyseSchemaFile_1 = require("./analyseSchemaFile");
11
+ /**
12
+ * Create types from schemas from a directory
13
+ * @param settings Settings
14
+ */
15
+ async function convertFilesInDirectory(appSettings, ogTypeOutputDir, fileTypesToExport = []) {
16
+ // Check and resolve directories
17
+ const resolvedSchemaDirectory = path_1.default.resolve(appSettings.schemaDirectory);
18
+ if (!(0, fs_1.existsSync)(resolvedSchemaDirectory)) {
19
+ throw new Error(`schemaDirectory "${resolvedSchemaDirectory}" does not exist`);
20
+ }
21
+ const resolvedTypeOutputDirectory = path_1.default.resolve(appSettings.typeOutputDirectory);
22
+ if (!(0, fs_1.existsSync)(resolvedTypeOutputDirectory)) {
23
+ (0, fs_1.mkdirSync)(resolvedTypeOutputDirectory, { recursive: true });
24
+ }
25
+ let fileNamesToExport = [];
26
+ const currentDirFileTypesToExport = fileTypesToExport;
27
+ // Load files and get all types
28
+ const files = (0, fs_1.readdirSync)(resolvedSchemaDirectory);
29
+ for (const schemaFileName of files) {
30
+ const subDirectoryPath = path_1.default.join(resolvedSchemaDirectory, schemaFileName);
31
+ if (!appSettings.rootDirectoryOnly && (0, fs_1.lstatSync)(subDirectoryPath).isDirectory()) {
32
+ if (appSettings.ignoreFiles.includes(`${schemaFileName}/`)) {
33
+ if (appSettings.debug) {
34
+ // eslint-disable-next-line no-console
35
+ console.debug(`Skipping ${subDirectoryPath} because it's in your ignore files list`);
36
+ }
37
+ continue;
38
+ }
39
+ const typeOutputDirectory = appSettings.flattenTree
40
+ ? resolvedTypeOutputDirectory
41
+ : path_1.default.join(resolvedTypeOutputDirectory, schemaFileName);
42
+ const thisDirsFileNamesToExport = await convertFilesInDirectory({
43
+ ...appSettings,
44
+ schemaDirectory: subDirectoryPath,
45
+ typeOutputDirectory
46
+ }, ogTypeOutputDir, currentDirFileTypesToExport);
47
+ if (appSettings.indexAllToRoot || appSettings.flattenTree) {
48
+ fileNamesToExport = fileNamesToExport.concat(thisDirsFileNamesToExport.typeFileNames);
49
+ }
50
+ }
51
+ else {
52
+ if (!appSettings.inputFileFilter.test(schemaFileName)) {
53
+ if (appSettings.debug) {
54
+ // eslint-disable-next-line no-console
55
+ console.debug(`Skipping ${schemaFileName} because it's excluded via inputFileFilter`);
56
+ }
57
+ continue;
58
+ }
59
+ if (appSettings.ignoreFiles.includes(schemaFileName)) {
60
+ if (appSettings.debug) {
61
+ // eslint-disable-next-line no-console
62
+ console.debug(`Skipping ${schemaFileName} because it's in your ignore files list`);
63
+ }
64
+ continue;
65
+ }
66
+ const exportType = await (0, analyseSchemaFile_1.analyseSchemaFile)(appSettings, schemaFileName);
67
+ if (exportType) {
68
+ let dirTypeFileName = exportType.typeFileName;
69
+ if (appSettings.indexAllToRoot) {
70
+ const findIndexEnd = resolvedTypeOutputDirectory.indexOf(ogTypeOutputDir) + ogTypeOutputDir.length + 1;
71
+ dirTypeFileName = path_1.default.join(resolvedTypeOutputDirectory.substring(findIndexEnd), (0, write_1.getTypeFileNameFromSchema)(schemaFileName, appSettings));
72
+ }
73
+ fileNamesToExport.push(dirTypeFileName);
74
+ currentDirFileTypesToExport.push(exportType);
75
+ }
76
+ }
77
+ }
78
+ if (!appSettings.omitIndexFiles && (!appSettings.indexAllToRoot && !appSettings.flattenTree)) {
79
+ // Write index.ts
80
+ (0, write_1.writeIndexFile)(appSettings, fileNamesToExport);
81
+ }
82
+ return { typeFileNames: fileNamesToExport, types: currentDirFileTypesToExport };
83
+ }
@@ -0,0 +1,12 @@
1
+ import { AnySchema } from 'joi';
2
+ import { Settings, ConvertedType } from './types';
3
+ export { Settings };
4
+ export declare function convertSchema(settings: Partial<Settings>, joi: AnySchema, exportedName?: string, root?: boolean): ConvertedType | undefined;
5
+ /**
6
+ * Create types from schemas from a directory
7
+ *
8
+ * @param settings - Configuration settings
9
+ * @returns The success or failure of this operation
10
+ */
11
+ export declare function convertFromDirectory(settings: Partial<Settings>): Promise<boolean>;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAGhC,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAmB,MAAM,SAAS,CAAC;AAMnE,OAAO,EAAE,QAAQ,EAAE,CAAC;AAoCpB,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,EAC3B,GAAG,EAAE,SAAS,EACd,YAAY,CAAC,EAAE,MAAM,EACrB,IAAI,CAAC,EAAE,OAAO,GACb,aAAa,GAAG,SAAS,CAG3B;AAED;;;;;GAKG;AACH,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAoBxF"}