Socket
Socket
Sign inDemoInstall

json-schema-to-typescript

Package Overview
Dependencies
Maintainers
1
Versions
114
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

json-schema-to-typescript - npm Package Compare versions

Comparing version 4.1.1 to 4.1.2

dist/test/e2e/deterministicOrdering.d.ts

97

dist/src/cli.js

@@ -11,8 +11,35 @@ #!/usr/bin/env node

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("mz/fs");
const path_1 = require("path");
const stdin = require("stdin");
const index_1 = require("./index");
const minimist = require("minimist");
var fs_1 = require("mz/fs");
var path_1 = require("path");
var stdin = require("stdin");
var index_1 = require("./index");
var minimist = require("minimist");
main(minimist(process.argv.slice(2), {

@@ -26,18 +53,35 @@ alias: {

function main(argv) {
return __awaiter(this, void 0, void 0, function* () {
if (argv.help) {
printHelp();
process.exit(0);
}
const argIn = argv._[0] || argv.input;
const argOut = argv._[1] || argv.output;
try {
const schema = JSON.parse(yield readInput(argIn));
const ts = yield index_1.compile(schema, argIn);
yield writeOutput(ts, argOut);
}
catch (e) {
process.stderr.write(e.message);
process.exit(1);
}
return __awaiter(this, void 0, void 0, function () {
var argIn, argOut, schema, _a, _b, _c, ts, e_1;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
if (argv.help) {
printHelp();
process.exit(0);
}
argIn = argv._[0] || argv.input;
argOut = argv._[1] || argv.output;
_d.label = 1;
case 1:
_d.trys.push([1, 5, , 6]);
_b = (_a = JSON).parse;
return [4 /*yield*/, readInput(argIn)];
case 2:
schema = _b.apply(_a, [_d.sent()]);
return [4 /*yield*/, index_1.compile(schema, argIn)];
case 3:
ts = _d.sent();
return [4 /*yield*/, writeOutput(ts, argOut)];
case 4:
_d.sent();
return [3 /*break*/, 6];
case 5:
e_1 = _d.sent();
process.stderr.write(e_1.message);
process.exit(1);
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
});

@@ -64,12 +108,5 @@ }

function printHelp() {
const pkg = require('../package.json');
process.stdout.write(`
${pkg.name} ${pkg.version}
Usage: json2ts [--input, -i] [IN_FILE] [--output, -o] [OUT_FILE]
With no IN_FILE, or when IN_FILE is -, read standard input.
With no OUT_FILE and when IN_FILE is specified, create .d.ts file in the same directory.
With no OUT_FILE nor IN_FILE, write to standard output.
`);
var pkg = require('../package.json');
process.stdout.write("\n" + pkg.name + " " + pkg.version + "\nUsage: json2ts [--input, -i] [IN_FILE] [--output, -o] [OUT_FILE]\n\nWith no IN_FILE, or when IN_FILE is -, read standard input.\nWith no OUT_FILE and when IN_FILE is specified, create .d.ts file in the same directory.\nWith no OUT_FILE nor IN_FILE, write to standard output.\n");
}
//# sourceMappingURL=cli.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_color_1 = require("cli-color");
const lodash_1 = require("lodash");
const index_1 = require("./index");
const AST_1 = require("./types/AST");
const utils_1 = require("./utils");
function generate(ast, options = index_1.DEFAULT_OPTIONS) {
var cli_color_1 = require("cli-color");
var lodash_1 = require("lodash");
var index_1 = require("./index");
var AST_1 = require("./types/AST");
var utils_1 = require("./utils");
function generate(ast, options) {
if (options === void 0) { options = index_1.DEFAULT_OPTIONS; }
return [

@@ -19,3 +20,4 @@ declareNamedTypes(ast, options),

exports.generate = generate;
function declareEnums(ast, options, processed = new Set()) {
function declareEnums(ast, options, processed) {
if (processed === void 0) { processed = new Set(); }
if (processed.has(ast)) {

@@ -25,3 +27,3 @@ return '';

processed.add(ast);
let type = '';
var type = '';
switch (ast.type) {

@@ -32,3 +34,6 @@ case 'ENUM':

case 'INTERFACE':
type = ast.params.reduce((prev, { ast }) => prev + declareEnums(ast, options, processed), '');
type = ast.params.reduce(function (prev, _a) {
var ast = _a.ast;
return prev + declareEnums(ast, options, processed);
}, '');
break;

@@ -40,3 +45,4 @@ default:

}
function declareNamedInterfaces(ast, options, rootASTName, processed = new Set()) {
function declareNamedInterfaces(ast, options, rootASTName, processed) {
if (processed === void 0) { processed = new Set(); }
if (processed.has(ast)) {

@@ -46,3 +52,3 @@ return '';

processed.add(ast);
let type = '';
var type = '';
switch (ast.type) {

@@ -52,3 +58,6 @@ case 'INTERFACE':

AST_1.hasStandaloneName(ast) && (ast.standaloneName === rootASTName || options.declareReferenced) && generateStandaloneInterface(ast, options),
ast.params.map(({ ast }) => declareNamedInterfaces(ast, options, rootASTName, processed)).filter(Boolean).join('\n')
ast.params.map(function (_a) {
var ast = _a.ast;
return declareNamedInterfaces(ast, options, rootASTName, processed);
}).filter(Boolean).join('\n')
].filter(Boolean).join('\n');

@@ -58,3 +67,3 @@ break;

case 'UNION':
type = ast.params.map(_ => declareNamedInterfaces(_, options, rootASTName, processed)).filter(Boolean).join('\n');
type = ast.params.map(function (_) { return declareNamedInterfaces(_, options, rootASTName, processed); }).filter(Boolean).join('\n');
break;

@@ -66,3 +75,4 @@ default:

}
function declareNamedTypes(ast, options, processed = new Set()) {
function declareNamedTypes(ast, options, processed) {
if (processed === void 0) { processed = new Set(); }
if (processed.has(ast)) {

@@ -72,3 +82,3 @@ return '';

processed.add(ast);
let type = '';
var type = '';
switch (ast.type) {

@@ -79,3 +89,6 @@ case 'ENUM':

case 'INTERFACE':
type = ast.params.map(({ ast }) => declareNamedTypes(ast, options, processed)).filter(Boolean).join('\n');
type = ast.params.map(function (_a) {
var ast = _a.ast;
return declareNamedTypes(ast, options, processed);
}).filter(Boolean).join('\n');
break;

@@ -89,3 +102,3 @@ case 'INTERSECTION':

AST_1.hasStandaloneName(ast) ? generateStandaloneType(ast, options) : undefined,
ast.params.map(ast => declareNamedTypes(ast, options, processed)).filter(Boolean).join('\n')
ast.params.map(function (ast) { return declareNamedTypes(ast, options, processed); }).filter(Boolean).join('\n')
].filter(Boolean).join('\n');

@@ -118,3 +131,3 @@ break;

case 'TUPLE': return '['
+ ast.params.map(_ => generateType(_, options, indentDepth + 1)).join(', ')
+ ast.params.map(function (_) { return generateType(_, options, indentDepth + 1); }).join(', ')
+ ']';

@@ -128,19 +141,25 @@ case 'UNION': return generateSetOperation(ast, options, indentDepth);

function generateSetOperation(ast, options, indentDepth) {
const members = ast.params.map(_ => generateType(_, options, indentDepth));
const separator = ast.type === 'UNION' ? '|' : '&';
var members = ast.params.map(function (_) { return generateType(_, options, indentDepth); });
var separator = ast.type === 'UNION' ? '|' : '&';
return members.length === 1 ? members[0] : '(' + members.join(' ' + separator + ' ') + ')';
}
function generateInterface(ast, options, indentDepth) {
return `{`
return "{"
+ '\n'
+ options.indentWith.repeat(indentDepth)
+ ast.params
.map(({ isRequired, keyName, ast }) => [isRequired, keyName, ast, generateType(ast, options, indentDepth)])
.map(([isRequired, keyName, ast, type]) => (AST_1.hasComment(ast) && !ast.standaloneName ? generateComment(ast.comment, options, indentDepth + 1) + '\n' : '')
+ options.indentWith
+ escapeKeyName(keyName)
+ (isRequired ? '' : '?')
+ ': '
+ (AST_1.hasStandaloneName(ast) ? utils_1.toSafeString(type) : type)
+ (options.enableTrailingSemicolonForInterfaceProperties ? ';' : ''))
.map(function (_a) {
var isRequired = _a.isRequired, keyName = _a.keyName, ast = _a.ast;
return [isRequired, keyName, ast, generateType(ast, options, indentDepth)];
})
.map(function (_a) {
var isRequired = _a[0], keyName = _a[1], ast = _a[2], type = _a[3];
return (AST_1.hasComment(ast) && !ast.standaloneName ? generateComment(ast.comment, options, indentDepth + 1) + '\n' : '')
+ options.indentWith
+ escapeKeyName(keyName)
+ (isRequired ? '' : '?')
+ ': '
+ (AST_1.hasStandaloneName(ast) ? utils_1.toSafeString(type) : type)
+ (options.enableTrailingSemicolonForInterfaceProperties ? ';' : '');
})
.join('\n' + options.indentWith.repeat(indentDepth))

@@ -153,15 +172,18 @@ + '\n'

+ [
'/**',
...comment.split('\n').map(_ => ' * ' + _),
'/**'
].concat(comment.split('\n').map(function (_) { return ' * ' + _; }), [
' */'
].join('\n' + options.indentWith.repeat(indentDepth));
]).join('\n' + options.indentWith.repeat(indentDepth));
}
function generateStandaloneEnum(ast, options) {
return (AST_1.hasComment(ast) ? generateComment(ast.comment, options, 0) + '\n' : '')
+ 'export ' + (options.enableConstEnums ? 'const ' : '') + `enum ${utils_1.toSafeString(ast.standaloneName)} {`
+ 'export ' + (options.enableConstEnums ? 'const ' : '') + ("enum " + utils_1.toSafeString(ast.standaloneName) + " {")
+ '\n'
+ ast.params.map(({ ast, keyName }) => options.indentWith
+ keyName
+ ' = '
+ generateType(ast, options, 0))
+ ast.params.map(function (_a) {
var ast = _a.ast, keyName = _a.keyName;
return options.indentWith
+ keyName
+ ' = '
+ generateType(ast, options, 0);
})
.join(',\n')

@@ -173,3 +195,3 @@ + '\n'

return (AST_1.hasComment(ast) ? generateComment(ast.comment, options, 0) + '\n' : '')
+ `export interface ${utils_1.toSafeString(ast.standaloneName)} `
+ ("export interface " + utils_1.toSafeString(ast.standaloneName) + " ")
+ generateInterface(ast, options, 0)

@@ -180,3 +202,3 @@ + (options.enableTrailingSemicolonForInterfaces ? ';' : '');

return (AST_1.hasComment(ast) ? generateComment(ast.comment, options, 0) + '\n' : '')
+ `export type ${utils_1.toSafeString(ast.standaloneName)} = ${generateType(lodash_1.omit(ast, 'standaloneName'), options, 0)}`
+ ("export type " + utils_1.toSafeString(ast.standaloneName) + " = " + generateType(lodash_1.omit(ast, 'standaloneName'), options, 0))
+ (options.enableTrailingSemicolonForTypes ? ';' : '');

@@ -183,0 +205,0 @@ }

"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -10,12 +28,39 @@ return new (P || (P = Promise))(function (resolve, reject) {

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const path_1 = require("path");
const generator_1 = require("./generator");
const normalizer_1 = require("./normalizer");
const optimizer_1 = require("./optimizer");
const parser_1 = require("./parser");
const resolver_1 = require("./resolver");
const utils_1 = require("./utils");
const validator_1 = require("./validator");
var fs_1 = require("fs");
var path_1 = require("path");
var generator_1 = require("./generator");
var normalizer_1 = require("./normalizer");
var optimizer_1 = require("./optimizer");
var parser_1 = require("./parser");
var resolver_1 = require("./resolver");
var utils_1 = require("./utils");
var validator_1 = require("./validator");
exports.DEFAULT_OPTIONS = {

@@ -31,22 +76,39 @@ cwd: process.cwd(),

};
function compileFromFile(filename, options = exports.DEFAULT_OPTIONS) {
const contents = utils_1.Try(() => fs_1.readFileSync(filename), () => { throw new ReferenceError(`Unable to read file "${filename}"`); });
const schema = utils_1.Try(() => JSON.parse(contents.toString()), () => { throw new TypeError(`Error parsing JSON in file "${filename}"`); });
return compile(schema, utils_1.stripExtension(filename), Object.assign({}, options, { cwd: path_1.dirname(filename) }));
function compileFromFile(filename, options) {
if (options === void 0) { options = exports.DEFAULT_OPTIONS; }
var contents = utils_1.Try(function () { return fs_1.readFileSync(filename); }, function () { throw new ReferenceError("Unable to read file \"" + filename + "\""); });
var schema = utils_1.Try(function () { return JSON.parse(contents.toString()); }, function () { throw new TypeError("Error parsing JSON in file \"" + filename + "\""); });
return compile(schema, utils_1.stripExtension(filename), __assign({}, options, { cwd: path_1.dirname(filename) }));
}
exports.compileFromFile = compileFromFile;
function compile(schema, name, options = exports.DEFAULT_OPTIONS) {
return __awaiter(this, void 0, void 0, function* () {
const errors = validator_1.validate(schema, name);
if (errors.length) {
errors.forEach(_ => utils_1.error(_));
throw new ValidationError;
}
return generator_1.generate(optimizer_1.optimize(parser_1.parse(yield resolver_1.dereference(normalizer_1.normalize(schema, name), options.cwd))), Object.assign({}, exports.DEFAULT_OPTIONS, options));
function compile(schema, name, options) {
if (options === void 0) { options = exports.DEFAULT_OPTIONS; }
return __awaiter(this, void 0, void 0, function () {
var errors, _a, _b, _c, _d, _e, _f;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
errors = validator_1.validate(schema, name);
if (errors.length) {
errors.forEach(function (_) { return utils_1.error(_); });
throw new ValidationError;
}
_a = generator_1.generate;
_c = optimizer_1.optimize;
_e = parser_1.parse;
return [4 /*yield*/, resolver_1.dereference(normalizer_1.normalize(schema, name), options.cwd)];
case 1: return [2 /*return*/, _a.apply(void 0, [_c.apply(void 0, [_e.apply(void 0, [_g.sent()])]), __assign({}, exports.DEFAULT_OPTIONS, options)])];
}
});
});
}
exports.compile = compile;
class ValidationError extends Error {
}
var ValidationError = (function (_super) {
__extends(ValidationError, _super);
function ValidationError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ValidationError;
}(Error));
exports.ValidationError = ValidationError;
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_color_1 = require("cli-color");
const lodash_1 = require("lodash");
const utils_1 = require("./utils");
const stringify = require("json-stringify-safe");
const rules = new Map();
rules.set('Destructure unary types', schema => {
var cli_color_1 = require("cli-color");
var lodash_1 = require("lodash");
var utils_1 = require("./utils");
var stringify = require("json-stringify-safe");
var rules = new Map();
rules.set('Destructure unary types', function (schema) {
if (schema.type && Array.isArray(schema.type) && schema.type.length === 1) {

@@ -14,3 +14,3 @@ schema.type = schema.type[0];

});
rules.set('Add empty `required` property if none is defined', schema => {
rules.set('Add empty `required` property if none is defined', function (schema) {
if (willBeInterface(schema) && !('required' in schema)) {

@@ -21,3 +21,3 @@ schema.required = [];

});
rules.set('Transform `required`=false to `required`=[]', schema => {
rules.set('Transform `required`=false to `required`=[]', function (schema) {
if (willBeInterface(schema) && schema.required === false) {

@@ -29,3 +29,3 @@ schema.required = [];

// TODO: default to empty schema (as per spec) instead
rules.set('Default additionalProperties to true', schema => {
rules.set('Default additionalProperties to true', function (schema) {
if (willBeInterface(schema) && !('additionalProperties' in schema)) {

@@ -36,3 +36,3 @@ schema.additionalProperties = true;

});
rules.set('Default top level `id`', (schema, rootSchema, fileName) => {
rules.set('Default top level `id`', function (schema, rootSchema, fileName) {
if (!schema.id && stringify(schema) === stringify(rootSchema)) {

@@ -44,6 +44,6 @@ schema.id = utils_1.toSafeString(utils_1.justName(fileName));

function normalize(schema, filename) {
let _schema = lodash_1.cloneDeep(schema);
rules.forEach((rule, key) => {
_schema = utils_1.mapDeep(_schema, schema => rule(schema, _schema, filename));
utils_1.log(cli_color_1.whiteBright.bgYellow('normalizer'), `Applied rule: "${key}"`);
var _schema = lodash_1.cloneDeep(schema);
rules.forEach(function (rule, key) {
_schema = utils_1.mapDeep(_schema, function (schema) { return rule(schema, _schema, filename); });
utils_1.log(cli_color_1.whiteBright.bgYellow('normalizer'), "Applied rule: \"" + key + "\"");
});

@@ -50,0 +50,0 @@ return _schema;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_color_1 = require("cli-color");
const lodash_1 = require("lodash");
const AST_1 = require("./types/AST");
const utils_1 = require("./utils");
const stringify = require("json-stringify-safe");
function optimize(ast, processed = new Map()) {
var cli_color_1 = require("cli-color");
var lodash_1 = require("lodash");
var AST_1 = require("./types/AST");
var utils_1 = require("./utils");
var stringify = require("json-stringify-safe");
function optimize(ast, processed) {
if (processed === void 0) { processed = new Map(); }
utils_1.log(cli_color_1.whiteBright.bgCyan('optimizer'), ast, processed.has(ast) ? '(FROM CACHE)' : '');

@@ -17,3 +18,5 @@ if (processed.has(ast)) {

return Object.assign(ast, {
params: ast.params.map(_ => Object.assign(_, { ast: optimize(_.ast, processed) }))
params: ast.params.map(function (_) {
return Object.assign(_, { ast: optimize(_.ast, processed) });
})
});

@@ -23,3 +26,3 @@ case 'INTERSECTION':

// [A, B, C, Any] -> Any
if (ast.params.some(_ => _.type === 'ANY')) {
if (ast.params.some(function (_) { return _.type === 'ANY'; })) {
utils_1.log(cli_color_1.whiteBright.bgCyan('optimizer'), ast, '<- T_ANY');

@@ -29,5 +32,7 @@ return AST_1.T_ANY;

// [A, B, B] -> [A, B]
ast.params = lodash_1.uniqBy(ast.params, _ => `${_.type}------${stringify(_.params)}`);
ast.params = lodash_1.uniqBy(ast.params, function (_) {
return _.type + "------" + stringify(_.params);
});
return Object.assign(ast, {
params: ast.params.map(_ => optimize(_, processed))
params: ast.params.map(function (_) { return optimize(_, processed); })
});

@@ -34,0 +39,0 @@ default:

"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
const cli_color_1 = require("cli-color");
const lodash_1 = require("lodash");
const typeOfSchema_1 = require("./typeOfSchema");
const AST_1 = require("./types/AST");
const utils_1 = require("./utils");
function parse(schema, rootSchema = schema, keyName, processed = new Map()) {
var cli_color_1 = require("cli-color");
var lodash_1 = require("lodash");
var typeOfSchema_1 = require("./typeOfSchema");
var AST_1 = require("./types/AST");
var utils_1 = require("./utils");
function parse(schema, rootSchema, keyName, processed) {
if (rootSchema === void 0) { rootSchema = schema; }
if (processed === void 0) { processed = new Map(); }
// If we've seen this node before, return it.

@@ -13,10 +23,10 @@ if (processed.has(schema)) {

}
const definitions = getDefinitions(rootSchema);
const keyNameFromDefinition = lodash_1.findKey(definitions, _ => _ === schema);
var definitions = getDefinitions(rootSchema);
var keyNameFromDefinition = lodash_1.findKey(definitions, function (_) { return _ === schema; });
// Cache processed ASTs before they are actually computed, then update
// them in place using set(). This is to avoid cycles.
// TODO: Investigate alternative approaches (lazy-computing nodes, etc.)
let ast = {};
var ast = {};
processed.set(schema, ast);
const set = (_ast) => Object.assign(ast, _ast);
var set = function (_ast) { return Object.assign(ast, _ast); };
return isSchema(schema)

@@ -29,3 +39,3 @@ ? parseNonLiteral(schema, rootSchema, keyName, keyNameFromDefinition, set, processed)

return set({
keyName,
keyName: keyName,
params: schema,

@@ -42,4 +52,4 @@ standaloneName: keyNameFromDefinition,

comment: schema.description,
keyName,
params: schema.allOf.map(_ => parse(_, rootSchema, undefined, processed)),
keyName: keyName,
params: schema.allOf.map(function (_) { return parse(_, rootSchema, undefined, processed); }),
standaloneName: schema.title || keyNameFromDefinition,

@@ -51,3 +61,3 @@ type: 'INTERSECTION'

comment: schema.description,
keyName,
keyName: keyName,
standaloneName: schema.title || keyNameFromDefinition,

@@ -59,4 +69,4 @@ type: 'ANY'

comment: schema.description,
keyName,
params: schema.anyOf.map(_ => parse(_, rootSchema, undefined, processed)),
keyName: keyName,
params: schema.anyOf.map(function (_) { return parse(_, rootSchema, undefined, processed); }),
standaloneName: schema.title || keyNameFromDefinition,

@@ -68,3 +78,3 @@ type: 'UNION'

comment: schema.description,
keyName,
keyName: keyName,
standaloneName: schema.title || keyNameFromDefinition,

@@ -76,7 +86,7 @@ type: 'BOOLEAN'

comment: schema.description,
keyName,
params: schema.enum.map((_, n) => ({
keyName: keyName,
params: schema.enum.map(function (_, n) { return ({
ast: parse(_, rootSchema, undefined, processed),
keyName: schema.tsEnumNames[n]
})),
}); }),
standaloneName: keyName,

@@ -88,3 +98,3 @@ type: 'ENUM'

comment: schema.description,
keyName,
keyName: keyName,
params: parseSchema(schema, rootSchema, processed),

@@ -97,3 +107,3 @@ standaloneName: computeSchemaName(schema),

comment: schema.description,
keyName,
keyName: keyName,
standaloneName: schema.title || keyNameFromDefinition,

@@ -105,3 +115,3 @@ type: 'NULL'

comment: schema.description,
keyName,
keyName: keyName,
standaloneName: schema.title || keyNameFromDefinition,

@@ -113,3 +123,3 @@ type: 'NUMBER'

comment: schema.description,
keyName,
keyName: keyName,
standaloneName: schema.title || keyNameFromDefinition,

@@ -121,4 +131,4 @@ type: 'OBJECT'

comment: schema.description,
keyName,
params: schema.oneOf.map(_ => parse(_, rootSchema, undefined, processed)),
keyName: keyName,
params: schema.oneOf.map(function (_) { return parse(_, rootSchema, undefined, processed); }),
standaloneName: schema.title || keyNameFromDefinition,

@@ -132,3 +142,3 @@ type: 'UNION'

comment: schema.description,
keyName,
keyName: keyName,
standaloneName: schema.title || keyNameFromDefinition,

@@ -141,4 +151,4 @@ type: 'STRING'

comment: schema.description,
keyName,
params: schema.items.map(_ => parse(_, rootSchema, undefined, processed)),
keyName: keyName,
params: schema.items.map(function (_) { return parse(_, rootSchema, undefined, processed); }),
standaloneName: schema.title || keyNameFromDefinition,

@@ -151,3 +161,3 @@ type: 'TUPLE'

comment: schema.description,
keyName,
keyName: keyName,
params: parse(schema.items, rootSchema, undefined, processed),

@@ -161,4 +171,4 @@ standaloneName: schema.title || keyNameFromDefinition,

comment: schema.description,
keyName,
params: schema.type.map(_ => parse({ required: [], type: _ }, rootSchema, undefined, processed)),
keyName: keyName,
params: schema.type.map(function (_) { return parse({ required: [], type: _ }, rootSchema, undefined, processed); }),
standaloneName: schema.title || keyNameFromDefinition,

@@ -170,4 +180,4 @@ type: 'UNION'

comment: schema.description,
keyName,
params: schema.enum.map(_ => parse(_, rootSchema, undefined, processed)),
keyName: keyName,
params: schema.enum.map(function (_) { return parse(_, rootSchema, undefined, processed); }),
standaloneName: schema.title || keyNameFromDefinition,

@@ -179,3 +189,3 @@ type: 'UNION'

comment: schema.description,
keyName,
keyName: keyName,
params: parseSchema(schema, rootSchema, processed),

@@ -189,3 +199,3 @@ standaloneName: computeSchemaName(schema)

comment: schema.description,
keyName,
keyName: keyName,
params: AST_1.T_ANY,

@@ -207,7 +217,7 @@ standaloneName: schema.title || keyNameFromDefinition,

function parseSchema(schema, rootSchema, processed) {
const asts = lodash_1.map(schema.properties, (value, key) => ({
var asts = lodash_1.map(schema.properties, function (value, key) { return ({
ast: parse(value, rootSchema, key, processed),
isRequired: (schema.required || []).includes(key),
isRequired: lodash_1.includes(schema.required || [], key),
keyName: key
}));
}); });
// handle additionalProperties

@@ -237,3 +247,4 @@ switch (schema.additionalProperties) {

*/
function getDefinitions(schema, processed = new Set()) {
function getDefinitions(schema, processed) {
if (processed === void 0) { processed = new Set(); }
if (processed.has(schema)) {

@@ -244,6 +255,6 @@ return {};

if (Array.isArray(schema)) {
return schema.reduce((prev, cur) => (Object.assign({}, prev, getDefinitions(cur, processed))), {});
return schema.reduce(function (prev, cur) { return (__assign({}, prev, getDefinitions(cur, processed))); }, {});
}
if (lodash_1.isPlainObject(schema)) {
return Object.assign({}, (hasDefinitions(schema) ? schema.definitions : {}), Object.keys(schema).reduce((prev, cur) => (Object.assign({}, prev, getDefinitions(schema[cur], processed))), {}));
return __assign({}, (hasDefinitions(schema) ? schema.definitions : {}), Object.keys(schema).reduce(function (prev, cur) { return (__assign({}, prev, getDefinitions(schema[cur], processed))); }, {}));
}

@@ -258,3 +269,3 @@ return {};

&& 'definitions' in schema
&& Object.keys(schema.definitions).every(_ => lodash_1.isPlainObject(schema.definitions[_]));
&& Object.keys(schema.definitions).every(function (_) { return lodash_1.isPlainObject(schema.definitions[_]); });
}

@@ -261,0 +272,0 @@ function isSchema(schema) {

@@ -10,11 +10,41 @@ "use strict";

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
const $RefParser = require("json-schema-ref-parser");
const cli_color_1 = require("cli-color");
const utils_1 = require("./utils");
var $RefParser = require("json-schema-ref-parser");
var cli_color_1 = require("cli-color");
var utils_1 = require("./utils");
function dereference(schema, cwd) {
return __awaiter(this, void 0, void 0, function* () {
utils_1.log(cli_color_1.whiteBright.bgGreen('resolver'), schema, cwd);
const parser = new $RefParser;
return parser.dereference(schema);
return __awaiter(this, void 0, void 0, function () {
var parser;
return __generator(this, function (_a) {
utils_1.log(cli_color_1.whiteBright.bgGreen('resolver'), schema, cwd);
parser = new $RefParser;
return [2 /*return*/, parser.dereference(schema)];
});
});

@@ -21,0 +51,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
var lodash_1 = require("lodash");
/**

@@ -5,0 +5,0 @@ * Duck types a JSONSchema schema or property to determine which kind of AST node to parse it into.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_color_1 = require("cli-color");
const lodash_1 = require("lodash");
const path_1 = require("path");
var cli_color_1 = require("cli-color");
var lodash_1 = require("lodash");
var path_1 = require("path");
// TODO: pull out into a separate package

@@ -20,3 +20,3 @@ function Try(fn, err) {

function dft(object, cb) {
for (let key in object) {
for (var key in object) {
if (!object.hasOwnProperty(key))

@@ -31,3 +31,5 @@ continue;

function mapDeep(object, fn, key) {
return fn(lodash_1.mapValues(object, (_, key) => lodash_1.isPlainObject(_) ? mapDeep(_, fn, key) : _), key);
return fn(lodash_1.mapValues(object, function (_, key) {
return lodash_1.isPlainObject(_) ? mapDeep(_, fn, key) : _;
}), key);
}

@@ -59,9 +61,17 @@ exports.mapDeep = mapDeep;

exports.toSafeString = toSafeString;
function error(...messages) {
console.error(cli_color_1.whiteBright.bgRedBright('error'), ...messages);
function error() {
var messages = [];
for (var _i = 0; _i < arguments.length; _i++) {
messages[_i] = arguments[_i];
}
console.error.apply(console, [cli_color_1.whiteBright.bgRedBright('error')].concat(messages));
}
exports.error = error;
function log(...messages) {
function log() {
var messages = [];
for (var _i = 0; _i < arguments.length; _i++) {
messages[_i] = arguments[_i];
}
if (process.env.DEBUG) {
console.info(cli_color_1.whiteBright.bgCyan('debug'), ...messages);
console.info.apply(console, [cli_color_1.whiteBright.bgCyan('debug')].concat(messages));
}

@@ -68,0 +78,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
const rules = new Map();
rules.set('Enum members and tsEnumNames must be of the same length', schema => {
var utils_1 = require("./utils");
var rules = new Map();
rules.set('Enum members and tsEnumNames must be of the same length', function (schema) {
if (schema.enum && schema.tsEnumNames && schema.enum.length !== schema.tsEnumNames.length) {

@@ -10,4 +10,4 @@ return false;

});
rules.set('tsEnumNames must be an array of strings', schema => {
if (schema.tsEnumNames && schema.tsEnumNames.some(_ => typeof _ !== 'string')) {
rules.set('tsEnumNames must be an array of strings', function (schema) {
if (schema.tsEnumNames && schema.tsEnumNames.some(function (_) { return typeof _ !== 'string'; })) {
return false;

@@ -17,7 +17,7 @@ }

function validate(schema, filename) {
const errors = [];
rules.forEach((rule, ruleName) => {
utils_1.mapDeep(schema, (schema, key) => {
var errors = [];
rules.forEach(function (rule, ruleName) {
utils_1.mapDeep(schema, function (schema, key) {
if (rule(schema) === false) {
errors.push(`Error at key "${key}" in file "${filename}": ${ruleName}`);
errors.push("Error at key \"" + key + "\" in file \"" + filename + "\": " + ruleName);
}

@@ -24,0 +24,0 @@ return schema;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_color_1 = require("cli-color");
const fastDiff = require("fast-diff");
var cli_color_1 = require("cli-color");
var fastDiff = require("fast-diff");
function diff(a, b) {
return fastDiff(b, a).map((edit) => {
return fastDiff(b, a).map(function (edit) {
if (edit[0] === fastDiff.INSERT) {

@@ -8,0 +8,0 @@ return cli_color_1.green(showHiddenChars(edit[1]));

@@ -15,7 +15,3 @@ "use strict";

};
exports.output = `export interface AdditionalProperties {
foo?: string;
[k: string]: number;
}
`;
exports.output = "export interface AdditionalProperties {\n foo?: string;\n [k: string]: number;\n}\n";
//# sourceMappingURL=additionalProperties.js.map

@@ -35,13 +35,3 @@ "use strict";

};
exports.output = `export interface AllOf {
foo: (Foo & Bar);
}
export interface Foo {
a: string;
b: number;
}
export interface Bar {
a: string;
}
`;
exports.output = "export interface AllOf {\n foo: (Foo & Bar);\n}\nexport interface Foo {\n a: string;\n b: number;\n}\nexport interface Bar {\n a: string;\n}\n";
//# sourceMappingURL=allOf.js.map

@@ -39,18 +39,3 @@ "use strict";

};
exports.output = `export interface AnyOf {
foo: (Foo | Bar | Baz);
}
export interface Foo {
a: string;
b?: number;
}
export interface Bar {
a?: ("a" | "b" | "c");
[k: string]: any;
}
export interface Baz {
baz?: Bar;
[k: string]: any;
}
`;
exports.output = "export interface AnyOf {\n foo: (Foo | Bar | Baz);\n}\nexport interface Foo {\n a: string;\n b?: number;\n}\nexport interface Bar {\n a?: (\"a\" | \"b\" | \"c\");\n [k: string]: any;\n}\nexport interface Baz {\n baz?: Bar;\n [k: string]: any;\n}\n";
//# sourceMappingURL=anyOf.js.map

@@ -31,17 +31,3 @@ "use strict";

};
exports.output = `export type RootAnyOf = (Foo | Bar | Baz);
export interface Foo {
a: string;
b?: number;
}
export interface Bar {
a?: ("a" | "b" | "c");
[k: string]: any;
}
export interface Baz {
baz?: Bar;
[k: string]: any;
}
`;
exports.output = "export type RootAnyOf = (Foo | Bar | Baz);\n\nexport interface Foo {\n a: string;\n b?: number;\n}\nexport interface Bar {\n a?: (\"a\" | \"b\" | \"c\");\n [k: string]: any;\n}\nexport interface Baz {\n baz?: Bar;\n [k: string]: any;\n}\n";
//# sourceMappingURL=anyOfRoot.js.map

@@ -33,10 +33,3 @@ "use strict";

};
exports.output = `export interface ArrayOfType {
foo?: string[];
bar?: string[];
baz?: (string | number)[];
moo?: [number, string];
[k: string]: any;
}
`;
exports.output = "export interface ArrayOfType {\n foo?: string[];\n bar?: string[];\n baz?: (string | number)[];\n moo?: [number, string];\n [k: string]: any;\n}\n";
//# sourceMappingURL=arrayOfType.js.map

@@ -30,15 +30,3 @@ "use strict";

};
exports.output = `export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
height?: number;
favoriteFoods?: any[];
likesDogs?: boolean;
[k: string]: any;
}
`;
exports.output = "export interface ExampleSchema {\n firstName: string;\n lastName: string;\n /**\n * Age in years\n */\n age?: number;\n height?: number;\n favoriteFoods?: any[];\n likesDogs?: boolean;\n [k: string]: any;\n}\n";
//# sourceMappingURL=basics.js.map

@@ -18,11 +18,3 @@ "use strict";

// TODO: dont generate extraneous parens around union types
exports.output = `/**
* My cool schema
*/
export interface ExampleSchema {
value: (number | string);
anotherValue?: (null | string);
[k: string]: any;
}
`;
exports.output = "/**\n * My cool schema\n */\nexport interface ExampleSchema {\n value: (number | string);\n anotherValue?: (null | string);\n [k: string]: any;\n}\n";
//# sourceMappingURL=disjointType.js.map

@@ -48,34 +48,10 @@ "use strict";

};
exports.outputs = [false, true].map(enableConstEnums => {
exports.outputs = [false, true].map(function (enableConstEnums) {
return {
settings: {
enableConstEnums
enableConstEnums: enableConstEnums
},
output: `export interface Enum {
stringEnum: ("a" | "b" | "c");
impliedStringEnum: ("a" | "b" | "c");
booleanEnum: true;
impliedBooleanEnum: true;
integerEnum: (-1 | 0 | 1);
impliedIntegerEnum: (-1 | 0 | 1);
numberEnum?: (-1.1 | 0 | 1.2);
namedIntegerEnum?: NamedIntegerEnum;
impliedNamedIntegerEnum: ImpliedNamedIntegerEnum;
impliedHeterogeneousEnum?: (-20.1 | null | "foo" | false);
}
export${enableConstEnums ? ' const ' : ' '}enum NamedIntegerEnum {
One = 1,
Two = 2,
Three = 3
}
export${enableConstEnums ? ' const ' : ' '}enum ImpliedNamedIntegerEnum {
Four = 4,
Five = 5,
Six = 6
}
`
output: "export interface Enum {\n stringEnum: (\"a\" | \"b\" | \"c\");\n impliedStringEnum: (\"a\" | \"b\" | \"c\");\n booleanEnum: true;\n impliedBooleanEnum: true;\n integerEnum: (-1 | 0 | 1);\n impliedIntegerEnum: (-1 | 0 | 1);\n numberEnum?: (-1.1 | 0 | 1.2);\n namedIntegerEnum?: NamedIntegerEnum;\n impliedNamedIntegerEnum: ImpliedNamedIntegerEnum;\n impliedHeterogeneousEnum?: (-20.1 | null | \"foo\" | false);\n}\n\nexport" + (enableConstEnums ? ' const ' : ' ') + "enum NamedIntegerEnum {\n One = 1,\n Two = 2,\n Three = 3\n}\nexport" + (enableConstEnums ? ' const ' : ' ') + "enum ImpliedNamedIntegerEnum {\n Four = 4,\n Five = 5,\n Six = 6\n}\n\n"
};
});
//# sourceMappingURL=enum.js.map

@@ -153,55 +153,3 @@ "use strict";

};
exports.output = `export type PositiveInteger = number;
export type PositiveIntegerDefault0 = PositiveInteger;
export type SchemaArray = HttpJsonSchemaOrgDraft04Schema[];
export type StringArray = string[];
export type SimpleTypes = ("array" | "boolean" | "integer" | "null" | "number" | "object" | "string");
/**
* Core schema meta-schema
*/
export interface HttpJsonSchemaOrgDraft04Schema {
id?: string;
$schema?: string;
title?: string;
description?: string;
default?: any;
multipleOf?: number;
maximum?: number;
exclusiveMaximum?: boolean;
minimum?: number;
exclusiveMinimum?: boolean;
maxLength?: PositiveInteger;
minLength?: PositiveIntegerDefault0;
pattern?: string;
additionalItems?: (boolean | HttpJsonSchemaOrgDraft04Schema);
items?: (HttpJsonSchemaOrgDraft04Schema | SchemaArray);
maxItems?: PositiveInteger;
minItems?: PositiveIntegerDefault0;
uniqueItems?: boolean;
maxProperties?: PositiveInteger;
minProperties?: PositiveIntegerDefault0;
required?: StringArray;
additionalProperties?: (boolean | HttpJsonSchemaOrgDraft04Schema);
definitions?: {
[k: string]: HttpJsonSchemaOrgDraft04Schema;
};
properties?: {
[k: string]: HttpJsonSchemaOrgDraft04Schema;
};
patternProperties?: {
[k: string]: HttpJsonSchemaOrgDraft04Schema;
};
dependencies?: {
[k: string]: (HttpJsonSchemaOrgDraft04Schema | StringArray);
};
enum?: any[];
type?: (SimpleTypes | SimpleTypes[]);
allOf?: SchemaArray;
anyOf?: SchemaArray;
oneOf?: SchemaArray;
not?: HttpJsonSchemaOrgDraft04Schema;
[k: string]: any;
}
`;
exports.output = "export type PositiveInteger = number;\nexport type PositiveIntegerDefault0 = PositiveInteger;\nexport type SchemaArray = HttpJsonSchemaOrgDraft04Schema[];\nexport type StringArray = string[];\nexport type SimpleTypes = (\"array\" | \"boolean\" | \"integer\" | \"null\" | \"number\" | \"object\" | \"string\");\n\n/**\n * Core schema meta-schema\n */\nexport interface HttpJsonSchemaOrgDraft04Schema {\n id?: string;\n $schema?: string;\n title?: string;\n description?: string;\n default?: any;\n multipleOf?: number;\n maximum?: number;\n exclusiveMaximum?: boolean;\n minimum?: number;\n exclusiveMinimum?: boolean;\n maxLength?: PositiveInteger;\n minLength?: PositiveIntegerDefault0;\n pattern?: string;\n additionalItems?: (boolean | HttpJsonSchemaOrgDraft04Schema);\n items?: (HttpJsonSchemaOrgDraft04Schema | SchemaArray);\n maxItems?: PositiveInteger;\n minItems?: PositiveIntegerDefault0;\n uniqueItems?: boolean;\n maxProperties?: PositiveInteger;\n minProperties?: PositiveIntegerDefault0;\n required?: StringArray;\n additionalProperties?: (boolean | HttpJsonSchemaOrgDraft04Schema);\n definitions?: {\n [k: string]: HttpJsonSchemaOrgDraft04Schema;\n };\n properties?: {\n [k: string]: HttpJsonSchemaOrgDraft04Schema;\n };\n patternProperties?: {\n [k: string]: HttpJsonSchemaOrgDraft04Schema;\n };\n dependencies?: {\n [k: string]: (HttpJsonSchemaOrgDraft04Schema | StringArray);\n };\n enum?: any[];\n type?: (SimpleTypes | SimpleTypes[]);\n allOf?: SchemaArray;\n anyOf?: SchemaArray;\n oneOf?: SchemaArray;\n not?: HttpJsonSchemaOrgDraft04Schema;\n [k: string]: any;\n}\n";
//# sourceMappingURL=JSONSchema.js.map

@@ -19,15 +19,3 @@ "use strict";

// TODO: 2nd block comment should annotate UserIdArray, not users
exports.output = `/**
* Array of authorized user ids.
*/
export type UserIdArray = string[];
/**
* My cool schema
*/
export interface ExampleSchema {
users?: UserIdArray;
[k: string]: any;
}
`;
exports.output = "/**\n * Array of authorized user ids.\n */\nexport type UserIdArray = string[];\n\n/**\n * My cool schema\n */\nexport interface ExampleSchema {\n users?: UserIdArray;\n [k: string]: any;\n}\n";
//# sourceMappingURL=namedProperty.js.map

@@ -22,11 +22,3 @@ "use strict";

};
exports.output = `export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
}
`;
exports.output = "export interface ExampleSchema {\n firstName: string;\n lastName: string;\n /**\n * Age in years\n */\n age?: number;\n}\n";
//# sourceMappingURL=notExtensible.js.map

@@ -39,18 +39,3 @@ "use strict";

};
exports.output = `export interface OneOf {
foo: (Foo | Bar | Baz);
}
export interface Foo {
a: string;
b?: number;
}
export interface Bar {
a?: ("a" | "b" | "c");
[k: string]: any;
}
export interface Baz {
baz?: Bar;
[k: string]: any;
}
`;
exports.output = "export interface OneOf {\n foo: (Foo | Bar | Baz);\n}\nexport interface Foo {\n a: string;\n b?: number;\n}\nexport interface Bar {\n a?: (\"a\" | \"b\" | \"c\");\n [k: string]: any;\n}\nexport interface Baz {\n baz?: Bar;\n [k: string]: any;\n}\n";
//# sourceMappingURL=oneOf.js.map

@@ -25,8 +25,3 @@ "use strict";

};
exports.output = `export interface OptimizableSchema {
bar: (string | number);
foo: any;
[k: string]: any;
}
`;
exports.output = "export interface OptimizableSchema {\n bar: (string | number);\n foo: any;\n [k: string]: any;\n}\n";
//# sourceMappingURL=optimize.js.map

@@ -446,139 +446,3 @@ "use strict";

};
exports.output = `/**
* This is version 1.03 of the JSON-stat 2.0 Schema (2016-05-04)
*/
export type JsonStat20Schema = ({
class: "dataset";
version: Version;
href?: Href;
label?: Label;
note?: Strarray;
link?: Link;
updated?: Updated;
source?: Source;
error?: Error;
extension?: Extension;
id: Strarray;
size: number[];
role?: {
time?: Strarray;
geo?: Strarray;
metric?: Strarray;
};
dimension: {
[k: string]: {
href?: Href;
label?: Label;
note?: Strarray;
link?: Link;
extension?: Extension;
category: Category;
};
};
value: ((number | null | string)[] | {
[k: string]: (number | null | string);
});
status?: (string | string[] | {
[k: string]: string;
});
} | {
class: "dimension";
version: Version;
href?: Href;
label?: Label;
note?: Strarray;
link?: Link;
updated?: Updated;
source?: Source;
error?: Error;
extension?: Extension;
category: Category;
} | {
class: "collection";
version: Version;
href?: Href;
label?: Label;
note?: Strarray;
link: {
item?: {
type?: string;
class?: ("dataset" | "collection" | "dimension");
href?: Href;
label?: Label;
note?: Strarray;
link?: Link;
updated?: Updated;
source?: Source;
extension?: Extension;
category?: Category;
id?: Strarray;
size?: number[];
role?: {
time?: Strarray;
geo?: Strarray;
metric?: Strarray;
};
dimension?: {
[k: string]: {
href?: Href;
label?: Label;
note?: Strarray;
link?: Link;
extension?: Extension;
category: Category;
};
};
value?: ((number | null | string)[] | {
[k: string]: (number | null | string);
});
status?: (string | string[] | {
[k: string]: string;
});
}[];
};
updated?: Updated;
source?: Source;
error?: Error;
extension?: Extension;
});
export type Version = "2.0";
export type Href = string;
export type Label = string;
export type Strarray = string[];
export type Updated = string;
export type Source = string;
export type Error = any[];
export interface Link {
}
export interface Extension {
[k: string]: any;
}
export interface Category {
index?: (Strarray | {
[k: string]: number;
});
label?: {
[k: string]: string;
};
note?: {
[k: string]: Strarray;
};
unit?: {
[k: string]: {
label?: Label;
decimals?: number;
position?: ("start" | "end");
[k: string]: any;
};
};
coordinates?: {
[k: string]: [number, number];
};
child?: {
[k: string]: Strarray;
};
}
`;
exports.output = "/**\n * This is version 1.03 of the JSON-stat 2.0 Schema (2016-05-04)\n */\nexport type JsonStat20Schema = ({\n class: \"dataset\";\n version: Version;\n href?: Href;\n label?: Label;\n note?: Strarray;\n link?: Link;\n updated?: Updated;\n source?: Source;\n error?: Error;\n extension?: Extension;\n id: Strarray;\n size: number[];\n role?: {\n time?: Strarray;\n geo?: Strarray;\n metric?: Strarray;\n };\n dimension: {\n [k: string]: {\n href?: Href;\n label?: Label;\n note?: Strarray;\n link?: Link;\n extension?: Extension;\n category: Category;\n };\n };\n value: ((number | null | string)[] | {\n [k: string]: (number | null | string);\n });\n status?: (string | string[] | {\n [k: string]: string;\n });\n } | {\n class: \"dimension\";\n version: Version;\n href?: Href;\n label?: Label;\n note?: Strarray;\n link?: Link;\n updated?: Updated;\n source?: Source;\n error?: Error;\n extension?: Extension;\n category: Category;\n } | {\n class: \"collection\";\n version: Version;\n href?: Href;\n label?: Label;\n note?: Strarray;\n link: {\n item?: {\n type?: string;\n class?: (\"dataset\" | \"collection\" | \"dimension\");\n href?: Href;\n label?: Label;\n note?: Strarray;\n link?: Link;\n updated?: Updated;\n source?: Source;\n extension?: Extension;\n category?: Category;\n id?: Strarray;\n size?: number[];\n role?: {\n time?: Strarray;\n geo?: Strarray;\n metric?: Strarray;\n };\n dimension?: {\n [k: string]: {\n href?: Href;\n label?: Label;\n note?: Strarray;\n link?: Link;\n extension?: Extension;\n category: Category;\n };\n };\n value?: ((number | null | string)[] | {\n [k: string]: (number | null | string);\n });\n status?: (string | string[] | {\n [k: string]: string;\n });\n }[];\n };\n updated?: Updated;\n source?: Source;\n error?: Error;\n extension?: Extension;\n });\nexport type Version = \"2.0\";\nexport type Href = string;\nexport type Label = string;\nexport type Strarray = string[];\nexport type Updated = string;\nexport type Source = string;\nexport type Error = any[];\n\nexport interface Link {\n\n}\nexport interface Extension {\n [k: string]: any;\n}\nexport interface Category {\n index?: (Strarray | {\n [k: string]: number;\n });\n label?: {\n [k: string]: string;\n };\n note?: {\n [k: string]: Strarray;\n };\n unit?: {\n [k: string]: {\n label?: Label;\n decimals?: number;\n position?: (\"start\" | \"end\");\n [k: string]: any;\n };\n };\n coordinates?: {\n [k: string]: [number, number];\n };\n child?: {\n [k: string]: Strarray;\n };\n}\n";
//# sourceMappingURL=realWorld.jsonStat.js.map

@@ -0,1 +1,2 @@

export declare let exclude: boolean;
/**

@@ -2,0 +3,0 @@ * @see https://github.com/bcherny/json-schema-to-typescript/issues/49

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exclude = true;
/**

@@ -11,3 +12,3 @@ * @see https://github.com/bcherny/json-schema-to-typescript/issues/49

foo: {
$ref: 'https://raw.githubusercontent.com/OAI/OpenAPI-Specification/ae9322eb2df1555acf3163e30cd84779d98afec5/schemas/v2.0/schema.json'
$ref: 'https://raw.githubusercontent.com/bcherny/OpenAPI-Specification/ae9322eb2df1555acf3163e30cd84779d98afec5/schemas/v2.0/schema.json'
}

@@ -18,464 +19,3 @@ },

};
exports.output = `/**
* The transfer protocol of the API.
*/
export type SchemesList = ("http" | "https" | "ws" | "wss")[];
export type MediaTypeList = MimeType[];
export type Title = string;
export type Description = string;
export type Default = any;
export type MultipleOf = number;
export type Maximum = number;
export type ExclusiveMaximum = boolean;
export type Minimum = number;
export type ExclusiveMinimum = boolean;
export type MaxLength = number;
export type MinLength = MaxLength;
export type Pattern = string;
export type UniqueItems = boolean;
export type Enum = any[];
export type Parameter = (BodyParameter | NonBodyParameter);
export type NonBodyParameter = (HeaderParameterSubSchema | FormDataParameterSubSchema | QueryParameterSubSchema | PathParameterSubSchema);
export type CollectionFormat = ("csv" | "ssv" | "tsv" | "pipes");
export type CollectionFormatWithMulti = ("csv" | "ssv" | "tsv" | "pipes" | "multi");
export type Security = SecurityRequirement[];
export interface Referencing {
foo: AJsonSchemaForSwagger20Api;
}
export interface AJsonSchemaForSwagger20Api {
/**
* The Swagger version of this document.
*/
swagger: "2.0";
info: Info;
/**
* The host (name or ip) of the API. Example: 'swagger.io'
*/
host?: string;
/**
* The base path to the API. Example: '/api'.
*/
basePath?: string;
schemes?: SchemesList;
/**
* A list of MIME types accepted by the API.
*/
consumes?: MediaTypeList;
/**
* A list of MIME types the API can produce.
*/
produces?: MediaTypeList;
paths: Paths;
definitions?: Definitions;
parameters?: ParameterDefinitions;
responses?: ResponseDefinitions;
security?: Security;
securityDefinitions?: SecurityDefinitions;
tags?: Tag[];
externalDocs?: ExternalDocs;
}
/**
* General information about the API.
*/
export interface Info {
/**
* A unique and precise title of the API.
*/
title: string;
/**
* A semantic version number of the API.
*/
version: string;
/**
* A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed.
*/
description?: string;
/**
* The terms of service for the API.
*/
termsOfService?: string;
contact?: Contact;
license?: License;
}
/**
* Contact information for the owners of the API.
*/
export interface Contact {
/**
* The identifying name of the contact person/organization.
*/
name?: string;
/**
* The URL pointing to the contact information.
*/
url?: string;
/**
* The email address of the contact person/organization.
*/
email?: string;
}
export interface License {
/**
* The name of the license type. It's encouraged to use an OSI compatible license.
*/
name: string;
/**
* The URL pointing to the license.
*/
url?: string;
}
/**
* Relative paths to the individual endpoints. They must be relative to the 'basePath'.
*/
export interface Paths {
}
/**
* One or more JSON objects describing the schemas being consumed and produced by the API.
*/
export interface Definitions {
[k: string]: Schema;
}
/**
* A deterministic version of a JSON Schema object.
*/
export interface Schema {
$ref?: string;
format?: string;
title?: Title;
description?: Description;
default?: Default;
multipleOf?: MultipleOf;
maximum?: Maximum;
exclusiveMaximum?: ExclusiveMaximum;
minimum?: Minimum;
exclusiveMinimum?: ExclusiveMinimum;
maxLength?: MaxLength;
minLength?: MinLength;
pattern?: Pattern;
maxItems?: MaxLength;
minItems?: MinLength;
uniqueItems?: UniqueItems;
maxProperties?: MaxLength;
minProperties?: MinLength;
required?: string[];
enum?: Enum;
additionalProperties?: (Schema | boolean);
type?: (("array" | "boolean" | "integer" | "null" | "number" | "object" | "string") | ("array" | "boolean" | "integer" | "null" | "number" | "object" | "string")[]);
items?: (Schema | Schema[]);
allOf?: Schema[];
properties?: {
[k: string]: Schema;
};
discriminator?: string;
readOnly?: boolean;
xml?: Xml;
externalDocs?: ExternalDocs;
example?: any;
}
export interface Xml {
name?: string;
namespace?: string;
prefix?: string;
attribute?: boolean;
wrapped?: boolean;
}
/**
* information about external documentation
*/
export interface ExternalDocs {
description?: string;
url: string;
}
/**
* One or more JSON representations for parameters
*/
export interface ParameterDefinitions {
[k: string]: Parameter;
}
export interface BodyParameter {
/**
* A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
*/
description?: string;
/**
* The name of the parameter.
*/
name: string;
/**
* Determines the location of the parameter.
*/
in: "body";
/**
* Determines whether or not this parameter is required or optional.
*/
required?: boolean;
schema: Schema;
}
export interface HeaderParameterSubSchema {
/**
* Determines whether or not this parameter is required or optional.
*/
required?: boolean;
/**
* Determines the location of the parameter.
*/
in?: "header";
/**
* A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
*/
description?: string;
/**
* The name of the parameter.
*/
name?: string;
type?: ("string" | "number" | "boolean" | "integer" | "array");
format?: string;
items?: PrimitivesItems;
collectionFormat?: CollectionFormat;
default?: Default;
maximum?: Maximum;
exclusiveMaximum?: ExclusiveMaximum;
minimum?: Minimum;
exclusiveMinimum?: ExclusiveMinimum;
maxLength?: MaxLength;
minLength?: MinLength;
pattern?: Pattern;
maxItems?: MaxLength;
minItems?: MinLength;
uniqueItems?: UniqueItems;
enum?: Enum;
multipleOf?: MultipleOf;
}
export interface PrimitivesItems {
type?: ("string" | "number" | "integer" | "boolean" | "array");
format?: string;
items?: PrimitivesItems;
collectionFormat?: CollectionFormat;
default?: Default;
maximum?: Maximum;
exclusiveMaximum?: ExclusiveMaximum;
minimum?: Minimum;
exclusiveMinimum?: ExclusiveMinimum;
maxLength?: MaxLength;
minLength?: MinLength;
pattern?: Pattern;
maxItems?: MaxLength;
minItems?: MinLength;
uniqueItems?: UniqueItems;
enum?: Enum;
multipleOf?: MultipleOf;
}
export interface FormDataParameterSubSchema {
/**
* Determines whether or not this parameter is required or optional.
*/
required?: boolean;
/**
* Determines the location of the parameter.
*/
in?: "formData";
/**
* A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
*/
description?: string;
/**
* The name of the parameter.
*/
name?: string;
/**
* allows sending a parameter by name only or with an empty value.
*/
allowEmptyValue?: boolean;
type?: ("string" | "number" | "boolean" | "integer" | "array" | "file");
format?: string;
items?: PrimitivesItems;
collectionFormat?: CollectionFormatWithMulti;
default?: Default;
maximum?: Maximum;
exclusiveMaximum?: ExclusiveMaximum;
minimum?: Minimum;
exclusiveMinimum?: ExclusiveMinimum;
maxLength?: MaxLength;
minLength?: MinLength;
pattern?: Pattern;
maxItems?: MaxLength;
minItems?: MinLength;
uniqueItems?: UniqueItems;
enum?: Enum;
multipleOf?: MultipleOf;
}
export interface QueryParameterSubSchema {
/**
* Determines whether or not this parameter is required or optional.
*/
required?: boolean;
/**
* Determines the location of the parameter.
*/
in?: "query";
/**
* A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
*/
description?: string;
/**
* The name of the parameter.
*/
name?: string;
/**
* allows sending a parameter by name only or with an empty value.
*/
allowEmptyValue?: boolean;
type?: ("string" | "number" | "boolean" | "integer" | "array");
format?: string;
items?: PrimitivesItems;
collectionFormat?: CollectionFormatWithMulti;
default?: Default;
maximum?: Maximum;
exclusiveMaximum?: ExclusiveMaximum;
minimum?: Minimum;
exclusiveMinimum?: ExclusiveMinimum;
maxLength?: MaxLength;
minLength?: MinLength;
pattern?: Pattern;
maxItems?: MaxLength;
minItems?: MinLength;
uniqueItems?: UniqueItems;
enum?: Enum;
multipleOf?: MultipleOf;
}
export interface PathParameterSubSchema {
/**
* Determines whether or not this parameter is required or optional.
*/
required: true;
/**
* Determines the location of the parameter.
*/
in?: "path";
/**
* A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
*/
description?: string;
/**
* The name of the parameter.
*/
name?: string;
type?: ("string" | "number" | "boolean" | "integer" | "array");
format?: string;
items?: PrimitivesItems;
collectionFormat?: CollectionFormat;
default?: Default;
maximum?: Maximum;
exclusiveMaximum?: ExclusiveMaximum;
minimum?: Minimum;
exclusiveMinimum?: ExclusiveMinimum;
maxLength?: MaxLength;
minLength?: MinLength;
pattern?: Pattern;
maxItems?: MaxLength;
minItems?: MinLength;
uniqueItems?: UniqueItems;
enum?: Enum;
multipleOf?: MultipleOf;
}
/**
* One or more JSON representations for parameters
*/
export interface ResponseDefinitions {
[k: string]: Response;
}
export interface Response {
description: string;
schema?: (Schema | FileSchema);
headers?: Headers;
examples?: Examples;
}
/**
* A deterministic version of a JSON Schema object.
*/
export interface FileSchema {
format?: string;
title?: Title;
description?: Description;
default?: Default;
required?: string[];
type: "file";
readOnly?: boolean;
externalDocs?: ExternalDocs;
example?: any;
}
export interface Headers {
[k: string]: Header;
}
export interface Header {
type: ("string" | "number" | "integer" | "boolean" | "array");
format?: string;
items?: PrimitivesItems;
collectionFormat?: CollectionFormat;
default?: Default;
maximum?: Maximum;
exclusiveMaximum?: ExclusiveMaximum;
minimum?: Minimum;
exclusiveMinimum?: ExclusiveMinimum;
maxLength?: MaxLength;
minLength?: MinLength;
pattern?: Pattern;
maxItems?: MaxLength;
minItems?: MinLength;
uniqueItems?: UniqueItems;
enum?: Enum;
multipleOf?: MultipleOf;
description?: string;
}
export interface Examples {
[k: string]: any;
}
export interface SecurityDefinitions {
[k: string]: (BasicAuthenticationSecurity | ApiKeySecurity | Oauth2ImplicitSecurity | Oauth2PasswordSecurity | Oauth2ApplicationSecurity | Oauth2AccessCodeSecurity);
}
export interface BasicAuthenticationSecurity {
type: "basic";
description?: string;
}
export interface ApiKeySecurity {
type: "apiKey";
name: string;
in: ("header" | "query");
description?: string;
}
export interface Oauth2ImplicitSecurity {
type: "oauth2";
flow: "implicit";
scopes?: Oauth2Scopes;
authorizationUrl: string;
description?: string;
}
export interface Oauth2Scopes {
[k: string]: string;
}
export interface Oauth2PasswordSecurity {
type: "oauth2";
flow: "password";
scopes?: Oauth2Scopes;
tokenUrl: string;
description?: string;
}
export interface Oauth2ApplicationSecurity {
type: "oauth2";
flow: "application";
scopes?: Oauth2Scopes;
tokenUrl: string;
description?: string;
}
export interface Oauth2AccessCodeSecurity {
type: "oauth2";
flow: "accessCode";
scopes?: Oauth2Scopes;
authorizationUrl: string;
tokenUrl: string;
description?: string;
}
`;
exports.output = "/**\n * The transfer protocol of the API.\n */\nexport type SchemesList = (\"http\" | \"https\" | \"ws\" | \"wss\")[];\nexport type MediaTypeList = MimeType[];\nexport type Title = string;\nexport type Description = string;\nexport type Default = any;\nexport type MultipleOf = number;\nexport type Maximum = number;\nexport type ExclusiveMaximum = boolean;\nexport type Minimum = number;\nexport type ExclusiveMinimum = boolean;\nexport type MaxLength = number;\nexport type MinLength = MaxLength;\nexport type Pattern = string;\nexport type UniqueItems = boolean;\nexport type Enum = any[];\nexport type Parameter = (BodyParameter | NonBodyParameter);\nexport type NonBodyParameter = (HeaderParameterSubSchema | FormDataParameterSubSchema | QueryParameterSubSchema | PathParameterSubSchema);\nexport type CollectionFormat = (\"csv\" | \"ssv\" | \"tsv\" | \"pipes\");\nexport type CollectionFormatWithMulti = (\"csv\" | \"ssv\" | \"tsv\" | \"pipes\" | \"multi\");\nexport type Security = SecurityRequirement[];\n\nexport interface Referencing {\n foo: AJsonSchemaForSwagger20Api;\n}\nexport interface AJsonSchemaForSwagger20Api {\n /**\n * The Swagger version of this document.\n */\n swagger: \"2.0\";\n info: Info;\n /**\n * The host (name or ip) of the API. Example: 'swagger.io'\n */\n host?: string;\n /**\n * The base path to the API. Example: '/api'.\n */\n basePath?: string;\n schemes?: SchemesList;\n /**\n * A list of MIME types accepted by the API.\n */\n consumes?: MediaTypeList;\n /**\n * A list of MIME types the API can produce.\n */\n produces?: MediaTypeList;\n paths: Paths;\n definitions?: Definitions;\n parameters?: ParameterDefinitions;\n responses?: ResponseDefinitions;\n security?: Security;\n securityDefinitions?: SecurityDefinitions;\n tags?: Tag[];\n externalDocs?: ExternalDocs;\n}\n/**\n * General information about the API.\n */\nexport interface Info {\n /**\n * A unique and precise title of the API.\n */\n title: string;\n /**\n * A semantic version number of the API.\n */\n version: string;\n /**\n * A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed.\n */\n description?: string;\n /**\n * The terms of service for the API.\n */\n termsOfService?: string;\n contact?: Contact;\n license?: License;\n}\n/**\n * Contact information for the owners of the API.\n */\nexport interface Contact {\n /**\n * The identifying name of the contact person/organization.\n */\n name?: string;\n /**\n * The URL pointing to the contact information.\n */\n url?: string;\n /**\n * The email address of the contact person/organization.\n */\n email?: string;\n}\nexport interface License {\n /**\n * The name of the license type. It's encouraged to use an OSI compatible license.\n */\n name: string;\n /**\n * The URL pointing to the license.\n */\n url?: string;\n}\n/**\n * Relative paths to the individual endpoints. They must be relative to the 'basePath'.\n */\nexport interface Paths {\n\n}\n/**\n * One or more JSON objects describing the schemas being consumed and produced by the API.\n */\nexport interface Definitions {\n [k: string]: Schema;\n}\n/**\n * A deterministic version of a JSON Schema object.\n */\nexport interface Schema {\n $ref?: string;\n format?: string;\n title?: Title;\n description?: Description;\n default?: Default;\n multipleOf?: MultipleOf;\n maximum?: Maximum;\n exclusiveMaximum?: ExclusiveMaximum;\n minimum?: Minimum;\n exclusiveMinimum?: ExclusiveMinimum;\n maxLength?: MaxLength;\n minLength?: MinLength;\n pattern?: Pattern;\n maxItems?: MaxLength;\n minItems?: MinLength;\n uniqueItems?: UniqueItems;\n maxProperties?: MaxLength;\n minProperties?: MinLength;\n required?: string[];\n enum?: Enum;\n additionalProperties?: (Schema | boolean);\n type?: ((\"array\" | \"boolean\" | \"integer\" | \"null\" | \"number\" | \"object\" | \"string\") | (\"array\" | \"boolean\" | \"integer\" | \"null\" | \"number\" | \"object\" | \"string\")[]);\n items?: (Schema | Schema[]);\n allOf?: Schema[];\n properties?: {\n [k: string]: Schema;\n };\n discriminator?: string;\n readOnly?: boolean;\n xml?: Xml;\n externalDocs?: ExternalDocs;\n example?: any;\n}\nexport interface Xml {\n name?: string;\n namespace?: string;\n prefix?: string;\n attribute?: boolean;\n wrapped?: boolean;\n}\n/**\n * information about external documentation\n */\nexport interface ExternalDocs {\n description?: string;\n url: string;\n}\n/**\n * One or more JSON representations for parameters\n */\nexport interface ParameterDefinitions {\n [k: string]: Parameter;\n}\nexport interface BodyParameter {\n /**\n * A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.\n */\n description?: string;\n /**\n * The name of the parameter.\n */\n name: string;\n /**\n * Determines the location of the parameter.\n */\n in: \"body\";\n /**\n * Determines whether or not this parameter is required or optional.\n */\n required?: boolean;\n schema: Schema;\n}\nexport interface HeaderParameterSubSchema {\n /**\n * Determines whether or not this parameter is required or optional.\n */\n required?: boolean;\n /**\n * Determines the location of the parameter.\n */\n in?: \"header\";\n /**\n * A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.\n */\n description?: string;\n /**\n * The name of the parameter.\n */\n name?: string;\n type?: (\"string\" | \"number\" | \"boolean\" | \"integer\" | \"array\");\n format?: string;\n items?: PrimitivesItems;\n collectionFormat?: CollectionFormat;\n default?: Default;\n maximum?: Maximum;\n exclusiveMaximum?: ExclusiveMaximum;\n minimum?: Minimum;\n exclusiveMinimum?: ExclusiveMinimum;\n maxLength?: MaxLength;\n minLength?: MinLength;\n pattern?: Pattern;\n maxItems?: MaxLength;\n minItems?: MinLength;\n uniqueItems?: UniqueItems;\n enum?: Enum;\n multipleOf?: MultipleOf;\n}\nexport interface PrimitivesItems {\n type?: (\"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\");\n format?: string;\n items?: PrimitivesItems;\n collectionFormat?: CollectionFormat;\n default?: Default;\n maximum?: Maximum;\n exclusiveMaximum?: ExclusiveMaximum;\n minimum?: Minimum;\n exclusiveMinimum?: ExclusiveMinimum;\n maxLength?: MaxLength;\n minLength?: MinLength;\n pattern?: Pattern;\n maxItems?: MaxLength;\n minItems?: MinLength;\n uniqueItems?: UniqueItems;\n enum?: Enum;\n multipleOf?: MultipleOf;\n}\nexport interface FormDataParameterSubSchema {\n /**\n * Determines whether or not this parameter is required or optional.\n */\n required?: boolean;\n /**\n * Determines the location of the parameter.\n */\n in?: \"formData\";\n /**\n * A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.\n */\n description?: string;\n /**\n * The name of the parameter.\n */\n name?: string;\n /**\n * allows sending a parameter by name only or with an empty value.\n */\n allowEmptyValue?: boolean;\n type?: (\"string\" | \"number\" | \"boolean\" | \"integer\" | \"array\" | \"file\");\n format?: string;\n items?: PrimitivesItems;\n collectionFormat?: CollectionFormatWithMulti;\n default?: Default;\n maximum?: Maximum;\n exclusiveMaximum?: ExclusiveMaximum;\n minimum?: Minimum;\n exclusiveMinimum?: ExclusiveMinimum;\n maxLength?: MaxLength;\n minLength?: MinLength;\n pattern?: Pattern;\n maxItems?: MaxLength;\n minItems?: MinLength;\n uniqueItems?: UniqueItems;\n enum?: Enum;\n multipleOf?: MultipleOf;\n}\nexport interface QueryParameterSubSchema {\n /**\n * Determines whether or not this parameter is required or optional.\n */\n required?: boolean;\n /**\n * Determines the location of the parameter.\n */\n in?: \"query\";\n /**\n * A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.\n */\n description?: string;\n /**\n * The name of the parameter.\n */\n name?: string;\n /**\n * allows sending a parameter by name only or with an empty value.\n */\n allowEmptyValue?: boolean;\n type?: (\"string\" | \"number\" | \"boolean\" | \"integer\" | \"array\");\n format?: string;\n items?: PrimitivesItems;\n collectionFormat?: CollectionFormatWithMulti;\n default?: Default;\n maximum?: Maximum;\n exclusiveMaximum?: ExclusiveMaximum;\n minimum?: Minimum;\n exclusiveMinimum?: ExclusiveMinimum;\n maxLength?: MaxLength;\n minLength?: MinLength;\n pattern?: Pattern;\n maxItems?: MaxLength;\n minItems?: MinLength;\n uniqueItems?: UniqueItems;\n enum?: Enum;\n multipleOf?: MultipleOf;\n}\nexport interface PathParameterSubSchema {\n /**\n * Determines whether or not this parameter is required or optional.\n */\n required: true;\n /**\n * Determines the location of the parameter.\n */\n in?: \"path\";\n /**\n * A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.\n */\n description?: string;\n /**\n * The name of the parameter.\n */\n name?: string;\n type?: (\"string\" | \"number\" | \"boolean\" | \"integer\" | \"array\");\n format?: string;\n items?: PrimitivesItems;\n collectionFormat?: CollectionFormat;\n default?: Default;\n maximum?: Maximum;\n exclusiveMaximum?: ExclusiveMaximum;\n minimum?: Minimum;\n exclusiveMinimum?: ExclusiveMinimum;\n maxLength?: MaxLength;\n minLength?: MinLength;\n pattern?: Pattern;\n maxItems?: MaxLength;\n minItems?: MinLength;\n uniqueItems?: UniqueItems;\n enum?: Enum;\n multipleOf?: MultipleOf;\n}\n/**\n * One or more JSON representations for parameters\n */\nexport interface ResponseDefinitions {\n [k: string]: Response;\n}\nexport interface Response {\n description: string;\n schema?: (Schema | FileSchema);\n headers?: Headers;\n examples?: Examples;\n}\n/**\n * A deterministic version of a JSON Schema object.\n */\nexport interface FileSchema {\n format?: string;\n title?: Title;\n description?: Description;\n default?: Default;\n required?: string[];\n type: \"file\";\n readOnly?: boolean;\n externalDocs?: ExternalDocs;\n example?: any;\n}\nexport interface Headers {\n [k: string]: Header;\n}\nexport interface Header {\n type: (\"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\");\n format?: string;\n items?: PrimitivesItems;\n collectionFormat?: CollectionFormat;\n default?: Default;\n maximum?: Maximum;\n exclusiveMaximum?: ExclusiveMaximum;\n minimum?: Minimum;\n exclusiveMinimum?: ExclusiveMinimum;\n maxLength?: MaxLength;\n minLength?: MinLength;\n pattern?: Pattern;\n maxItems?: MaxLength;\n minItems?: MinLength;\n uniqueItems?: UniqueItems;\n enum?: Enum;\n multipleOf?: MultipleOf;\n description?: string;\n}\nexport interface Examples {\n [k: string]: any;\n}\nexport interface SecurityDefinitions {\n [k: string]: (BasicAuthenticationSecurity | ApiKeySecurity | Oauth2ImplicitSecurity | Oauth2PasswordSecurity | Oauth2ApplicationSecurity | Oauth2AccessCodeSecurity);\n}\nexport interface BasicAuthenticationSecurity {\n type: \"basic\";\n description?: string;\n}\nexport interface ApiKeySecurity {\n type: \"apiKey\";\n name: string;\n in: (\"header\" | \"query\");\n description?: string;\n}\nexport interface Oauth2ImplicitSecurity {\n type: \"oauth2\";\n flow: \"implicit\";\n scopes?: Oauth2Scopes;\n authorizationUrl: string;\n description?: string;\n}\nexport interface Oauth2Scopes {\n [k: string]: string;\n}\nexport interface Oauth2PasswordSecurity {\n type: \"oauth2\";\n flow: \"password\";\n scopes?: Oauth2Scopes;\n tokenUrl: string;\n description?: string;\n}\nexport interface Oauth2ApplicationSecurity {\n type: \"oauth2\";\n flow: \"application\";\n scopes?: Oauth2Scopes;\n tokenUrl: string;\n description?: string;\n}\nexport interface Oauth2AccessCodeSecurity {\n type: \"oauth2\";\n flow: \"accessCode\";\n scopes?: Oauth2Scopes;\n authorizationUrl: string;\n tokenUrl: string;\n description?: string;\n}\n";
//# sourceMappingURL=realWorld.swagger.js.map

@@ -19,18 +19,3 @@ "use strict";

},
output: `export interface Referencing {
foo: ExampleSchema;
}
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
height?: number;
favoriteFoods?: any[];
likesDogs?: boolean;
[k: string]: any;
}
`
output: "export interface Referencing {\n foo: ExampleSchema;\n}\nexport interface ExampleSchema {\n firstName: string;\n lastName: string;\n /**\n * Age in years\n */\n age?: number;\n height?: number;\n favoriteFoods?: any[];\n likesDogs?: boolean;\n [k: string]: any;\n}\n"
},

@@ -41,8 +26,5 @@ {

},
output: `export interface Referencing {
foo: ExampleSchema;
}
`
output: "export interface Referencing {\n foo: ExampleSchema;\n}\n"
}
];
//# sourceMappingURL=ref.1.js.map

@@ -76,49 +76,3 @@ "use strict";

};
exports.output = `/**
* A string with title and enum defined does produce a duplicate Interface
*/
export type FifthDefinitionString = ("one" | "two" | "three");
export interface LocallyReferencedManifest {
/**
* Behaviour is the same if definition is referenced as prop within a container
*/
firstContainer?: {
first?: FirstDefinition;
[k: string]: any;
};
second?: UnrelatedTitle;
third?: ThirdDefinition;
fourth?: FourthDefinitionSimpleObject;
fifth?: FifthDefinitionString;
[k: string]: any;
}
/**
* Title matches definition key for kicks
*/
export interface FirstDefinition {
name?: string;
[k: string]: any;
}
/**
* Title is unrelated to definition key and behaviour is the same
*/
export interface UnrelatedTitle {
name?: string;
[k: string]: any;
}
/**
* Definition has no title and produces no duplicate Interface
*/
export interface ThirdDefinition {
name?: string;
[k: string]: any;
}
/**
* A simple object type with title set and no properties defined produces no duplicate Interface
*/
export interface FourthDefinitionSimpleObject {
[k: string]: any;
}
`;
exports.output = "/**\n * A string with title and enum defined does produce a duplicate Interface\n */\nexport type FifthDefinitionString = (\"one\" | \"two\" | \"three\");\n\nexport interface LocallyReferencedManifest {\n /**\n * Behaviour is the same if definition is referenced as prop within a container\n */\n firstContainer?: {\n first?: FirstDefinition;\n [k: string]: any;\n };\n second?: UnrelatedTitle;\n third?: ThirdDefinition;\n fourth?: FourthDefinitionSimpleObject;\n fifth?: FifthDefinitionString;\n [k: string]: any;\n}\n/**\n * Title matches definition key for kicks\n */\nexport interface FirstDefinition {\n name?: string;\n [k: string]: any;\n}\n/**\n * Title is unrelated to definition key and behaviour is the same\n */\nexport interface UnrelatedTitle {\n name?: string;\n [k: string]: any;\n}\n/**\n * Definition has no title and produces no duplicate Interface\n */\nexport interface ThirdDefinition {\n name?: string;\n [k: string]: any;\n}\n/**\n * A simple object type with title set and no properties defined produces no duplicate Interface\n */\nexport interface FourthDefinitionSimpleObject {\n [k: string]: any;\n}\n";
//# sourceMappingURL=ref.2.js.map

@@ -14,18 +14,3 @@ "use strict";

};
exports.output = `export interface Referencing3 {
foo: ExampleSchema;
}
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
height?: number;
favoriteFoods?: any[];
likesDogs?: boolean;
[k: string]: any;
}
`;
exports.output = "export interface Referencing3 {\n foo: ExampleSchema;\n}\nexport interface ExampleSchema {\n firstName: string;\n lastName: string;\n /**\n * Age in years\n */\n age?: number;\n height?: number;\n favoriteFoods?: any[];\n likesDogs?: boolean;\n [k: string]: any;\n}\n";
//# sourceMappingURL=ref.3.js.map

@@ -16,8 +16,3 @@ "use strict";

};
exports.output = `export interface LocalCycle {
foo: LocalCycle;
bar?: LocalCycle;
[k: string]: any;
}
`;
exports.output = "export interface LocalCycle {\n foo: LocalCycle;\n bar?: LocalCycle;\n [k: string]: any;\n}\n";
//# sourceMappingURL=refWithCycle.1.js.map

@@ -13,15 +13,3 @@ "use strict";

};
exports.output = `export interface Cycle2 {
foo: Cycle3;
[k: string]: any;
}
export interface Cycle3 {
foo?: Cycle4;
}
export interface Cycle4 {
foo?: number;
bar?: Cycle3;
[k: string]: any;
}
`;
exports.output = "export interface Cycle2 {\n foo: Cycle3;\n [k: string]: any;\n}\nexport interface Cycle3 {\n foo?: Cycle4;\n}\nexport interface Cycle4 {\n foo?: number;\n bar?: Cycle3;\n [k: string]: any;\n}\n";
//# sourceMappingURL=refWithCycle.2.js.map

@@ -19,18 +19,3 @@ "use strict";

*/
exports.output = `export interface Referencing {
ref: ExampleSchema;
}
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
height?: number;
favoriteFoods?: any[];
likesDogs?: boolean;
[k: string]: any;
}
`;
exports.output = "export interface Referencing {\n ref: ExampleSchema;\n}\nexport interface ExampleSchema {\n firstName: string;\n lastName: string;\n /**\n * Age in years\n */\n age?: number;\n height?: number;\n favoriteFoods?: any[];\n likesDogs?: boolean;\n [k: string]: any;\n}\n";
//# sourceMappingURL=schemaTitleAsTypeName.js.map

@@ -25,11 +25,3 @@ "use strict";

};
exports.output = `export interface ExampleSchema {
"\`foo\`": string;
"'bar'": string;
"\\\"baz\\\"": string;
"$zoo 2"?: string;
"qux..."?: number;
[k: string]: any;
}
`;
exports.output = "export interface ExampleSchema {\n \"`foo`\": string;\n \"'bar'\": string;\n \"\\\"baz\\\"\": string;\n \"$zoo 2\"?: string;\n \"qux...\"?: number;\n [k: string]: any;\n}\n";
//# sourceMappingURL=specialCharacters.js.map

@@ -37,24 +37,3 @@ "use strict";

};
exports.output = `export interface SchemaWithSubschema {
firstName: string;
friend?: {
knowsFrom: ("work" | "school" | "other");
[k: string]: any;
};
coworker?: {
company?: {
name: string;
};
[k: string]: KString;
};
[k: string]: any;
}
export const enum KString {
red = 10,
green = 20,
blue = 30
}
`;
exports.output = "export interface SchemaWithSubschema {\n firstName: string;\n friend?: {\n knowsFrom: (\"work\" | \"school\" | \"other\");\n [k: string]: any;\n };\n coworker?: {\n company?: {\n name: string;\n };\n [k: string]: KString;\n };\n [k: string]: any;\n}\n\nexport const enum KString {\n red = 10,\n green = 20,\n blue = 30\n}\n\n";
//# sourceMappingURL=subSchema.js.map

@@ -13,6 +13,3 @@ "use strict";

};
exports.output = `export interface UnnamedSchema {
foo: string;
}
`;
exports.output = "export interface UnnamedSchema {\n foo: string;\n}\n";
//# sourceMappingURL=unnamedSchema.js.map

@@ -22,15 +22,3 @@ "use strict";

};
exports.output = `/**
* My cool schema
*/
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
[k: string]: any;
}
`;
exports.output = "/**\n * My cool schema\n */\nexport interface ExampleSchema {\n firstName: string;\n lastName: string;\n /**\n * Age in years\n */\n age?: number;\n [k: string]: any;\n}\n";
//# sourceMappingURL=withDescription.js.map

@@ -23,19 +23,3 @@ "use strict";

};
exports.output = `/**
* My cool schema
*/
export interface ExampleSchema {
/**
* first name single line description
*/
firstName: string;
lastName: string;
/**
* Age description with
* multiple lines
*/
age?: number;
[k: string]: any;
}
`;
exports.output = "/**\n * My cool schema\n */\nexport interface ExampleSchema {\n /**\n * first name single line description\n */\n firstName: string;\n lastName: string;\n /**\n * Age description with\n * multiple lines\n */\n age?: number;\n [k: string]: any;\n}\n";
//# sourceMappingURL=withDescriptionNewlines.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cli_color_1 = require("cli-color");
const diff_1 = require("./diff");
var cli_color_1 = require("cli-color");
var diff_1 = require("./diff");
// // USEFUL FOR DEVELOPMENT

@@ -20,6 +20,8 @@ //

// }
const diffReporter = (a, b) => diff_1.diff(a, b);
function compare(t, caseName, a = '', b = '') {
var diffReporter = function (a, b) { return diff_1.diff(a, b); };
function compare(t, caseName, a, b) {
if (a === void 0) { a = ''; }
if (b === void 0) { b = ''; }
if (a !== b) {
console.log('\n', '─────────────────────────────────────────────────────────', '\n', cli_color_1.bold(cli_color_1.red(`${caseName} failed`)), '\n', '\n', cli_color_1.green('Green') + cli_color_1.white(' = Extraneous character in output'), '\n', ' ' + cli_color_1.red('Red') + cli_color_1.white(' = Missing character in output'), '\n', '\n', diffReporter(a, b), '─────────────────────────────────────────────────────────');
console.log('\n', '─────────────────────────────────────────────────────────', '\n', cli_color_1.bold(cli_color_1.red(caseName + " failed")), '\n', '\n', cli_color_1.green('Green') + cli_color_1.white(' = Extraneous character in output'), '\n', ' ' + cli_color_1.red('Red') + cli_color_1.white(' = Missing character in output'), '\n', '\n', diffReporter(a, b), '─────────────────────────────────────────────────────────');
t.fail();

@@ -26,0 +28,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const testCLI_1 = require("./testCLI");
const testE2E_1 = require("./testE2E");
const testNormalizer_1 = require("./testNormalizer");
var testCLI_1 = require("./testCLI");
var testE2E_1 = require("./testE2E");
var testNormalizer_1 = require("./testNormalizer");
testE2E_1.run();

@@ -7,0 +7,0 @@ if (!testE2E_1.hasOnly()) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = require("ava");
const child_process_1 = require("child_process");
const fs_1 = require("fs");
const expected = `export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
height?: number;
favoriteFoods?: any[];
likesDogs?: boolean;
[k: string]: any;
}
`;
var ava_1 = require("ava");
var child_process_1 = require("child_process");
var fs_1 = require("fs");
var expected = "export interface ExampleSchema {\n firstName: string;\n lastName: string;\n /**\n * Age in years\n */\n age?: number;\n height?: number;\n favoriteFoods?: any[];\n likesDogs?: boolean;\n [k: string]: any;\n}\n";
function run() {
ava_1.test('pipe in, pipe out', t => {
ava_1.test('pipe in, pipe out', function (t) {
t.is(child_process_1.execSync('cat ./test/resources/ReferencedType.json | node dist/src/cli.js', { encoding: 'utf-8' }).toString(), expected);
});
ava_1.test('file in (no flags), pipe out', t => {
ava_1.test('file in (no flags), pipe out', function (t) {
t.is(child_process_1.execSync('node dist/src/cli.js ./test/resources/ReferencedType.json').toString(), expected);
});
ava_1.test('file in (--input), pipe out', t => {
ava_1.test('file in (--input), pipe out', function (t) {
t.is(child_process_1.execSync('node dist/src/cli.js --input ./test/resources/ReferencedType.json').toString(), expected);
});
ava_1.test('file in (-i), pipe out', t => {
ava_1.test('file in (-i), pipe out', function (t) {
t.is(child_process_1.execSync('node dist/src/cli.js -i ./test/resources/ReferencedType.json').toString(), expected);
});
ava_1.test('pipe in, file out (--output)', t => {
ava_1.test('pipe in, file out (--output)', function (t) {
child_process_1.execSync('cat ./test/resources/ReferencedType.json | node dist/src/cli.js --output ./ReferencedType.d.ts').toString();

@@ -37,3 +25,3 @@ t.is(fs_1.readFileSync('./ReferencedType.d.ts', 'utf-8'), expected);

});
ava_1.test('pipe in, file out (-o)', t => {
ava_1.test('pipe in, file out (-o)', function (t) {
child_process_1.execSync('cat ./test/resources/ReferencedType.json | node dist/src/cli.js -o ./ReferencedType.d.ts').toString();

@@ -43,3 +31,3 @@ t.is(fs_1.readFileSync('./ReferencedType.d.ts', 'utf-8'), expected);

});
ava_1.test('file in (no flags), file out (no flags)', t => {
ava_1.test('file in (no flags), file out (no flags)', function (t) {
child_process_1.execSync('node dist/src/cli.js ./test/resources/ReferencedType.json ./ReferencedType.d.ts').toString();

@@ -49,3 +37,3 @@ t.is(fs_1.readFileSync('./ReferencedType.d.ts', 'utf-8'), expected);

});
ava_1.test('file in (-i), file out (-o)', t => {
ava_1.test('file in (-i), file out (-o)', function (t) {
child_process_1.execSync('node dist/src/cli.js -i ./test/resources/ReferencedType.json -o ./ReferencedType.d.ts').toString();

@@ -55,3 +43,3 @@ t.is(fs_1.readFileSync('./ReferencedType.d.ts', 'utf-8'), expected);

});
ava_1.test('file in (--input), file out (--output)', t => {
ava_1.test('file in (--input), file out (--output)', function (t) {
child_process_1.execSync('node dist/src/cli.js --input ./test/resources/ReferencedType.json --output ./ReferencedType.d.ts').toString();

@@ -58,0 +46,0 @@ t.is(fs_1.readFileSync('./ReferencedType.d.ts', 'utf-8'), expected);

"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -10,16 +18,43 @@ return new (P || (P = Promise))(function (resolve, reject) {

};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = require("ava");
const fs_1 = require("fs");
const lodash_1 = require("lodash");
const path_1 = require("path");
const src_1 = require("../src");
const utils_1 = require("../src/utils");
const reporter_1 = require("./reporter");
const dir = __dirname + '/e2e';
var ava_1 = require("ava");
var fs_1 = require("fs");
var lodash_1 = require("lodash");
var path_1 = require("path");
var src_1 = require("../src");
var utils_1 = require("../src/utils");
var reporter_1 = require("./reporter");
var dir = __dirname + '/e2e';
function hasOnly() {
return fs_1.readdirSync(dir)
.filter(_ => /^.*\.js$/.test(_))
.map(_ => require(path_1.join(dir, _)))
.some(_ => _.only);
.filter(function (_) { return /^.*\.js$/.test(_); })
.map(function (_) { return require(path_1.join(dir, _)); })
.some(function (_) { return _.only; });
}

@@ -29,8 +64,8 @@ exports.hasOnly = hasOnly;

// [filename, absolute dirname, contents][]
const modules = fs_1.readdirSync(dir)
.filter(_ => /^.*\.js$/.test(_))
.map(_ => [_, path_1.dirname(path_1.join(dir, _)), require(path_1.join(dir, _))]);
var modules = fs_1.readdirSync(dir)
.filter(function (_) { return /^.*\.js$/.test(_); })
.map(function (_) { return [_, path_1.dirname(path_1.join(dir, _)), require(path_1.join(dir, _))]; });
// exporting `const only=true` will only run that test
// exporting `const exclude=true` will not run that test
const only = lodash_1.find(modules, _ => _[2].only);
var only = lodash_1.find(modules, function (_) { return _[2].only; });
if (only) {

@@ -41,4 +76,4 @@ runOne(only[2], only[0], only[1]);

modules
.filter(_ => !_[2].exclude)
.forEach(_ => runOne(_[2], _[0], _[1]));
.filter(function (_) { return !_[2].exclude; })
.forEach(function (_) { return runOne(_[2], _[0], _[1]); });
}

@@ -48,37 +83,70 @@ }

function runOne(exports, name, dirname) {
utils_1.log(`Running test: "${name}"`);
var _this = this;
utils_1.log("Running test: \"" + name + "\"");
if (isMultiTestCase(exports)) {
exports.outputs.forEach(_ => {
const settings = Object.assign({}, _.settings, { cwd: dirname });
const caseName = `${name}: ${JSON.stringify(_.settings)}`;
ava_1.test(caseName, (t) => __awaiter(this, void 0, void 0, function* () {
if (_.error) {
try {
yield src_1.compile(exports.input, utils_1.stripExtension(name), settings);
exports.outputs.forEach(function (_) {
var settings = __assign({}, _.settings, { cwd: dirname });
var caseName = name + ": " + JSON.stringify(_.settings);
ava_1.test(caseName, function (t) { return __awaiter(_this, void 0, void 0, function () {
var e_1, _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!_.error) return [3 /*break*/, 5];
_c.label = 1;
case 1:
_c.trys.push([1, 3, , 4]);
return [4 /*yield*/, src_1.compile(exports.input, utils_1.stripExtension(name), settings)];
case 2:
_c.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _c.sent();
t.true(e_1 instanceof Error);
return [3 /*break*/, 4];
case 4: return [3 /*break*/, 7];
case 5:
_a = reporter_1.compare;
_b = [t, caseName];
return [4 /*yield*/, src_1.compile(exports.input, utils_1.stripExtension(name), settings)];
case 6:
_a.apply(void 0, _b.concat([_c.sent(), _.output]));
_c.label = 7;
case 7: return [2 /*return*/];
}
catch (e) {
t.true(e instanceof src_1.ValidationError);
}
}
else {
reporter_1.compare(t, caseName, yield src_1.compile(exports.input, utils_1.stripExtension(name), settings), _.output);
}
}));
});
}); });
});
}
else {
const settings = Object.assign({}, exports.settings, { cwd: dirname });
ava_1.test(name, (t) => __awaiter(this, void 0, void 0, function* () {
if (exports.error) {
try {
yield src_1.compile(exports.input, utils_1.stripExtension(name), settings);
var settings_1 = __assign({}, exports.settings, { cwd: dirname });
ava_1.test(name, function (t) { return __awaiter(_this, void 0, void 0, function () {
var e_2, _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!exports.error) return [3 /*break*/, 5];
_c.label = 1;
case 1:
_c.trys.push([1, 3, , 4]);
return [4 /*yield*/, src_1.compile(exports.input, utils_1.stripExtension(name), settings_1)];
case 2:
_c.sent();
return [3 /*break*/, 4];
case 3:
e_2 = _c.sent();
t.true(e_2 instanceof Error);
return [3 /*break*/, 4];
case 4: return [3 /*break*/, 7];
case 5:
_a = reporter_1.compare;
_b = [t, name];
return [4 /*yield*/, src_1.compile(exports.input, utils_1.stripExtension(name), settings_1)];
case 6:
_a.apply(void 0, _b.concat([_c.sent(), exports.output]));
_c.label = 7;
case 7: return [2 /*return*/];
}
catch (e) {
t.true(e instanceof src_1.ValidationError);
}
}
else {
reporter_1.compare(t, name, yield src_1.compile(exports.input, utils_1.stripExtension(name), settings), exports.output);
}
}));
});
}); });
}

@@ -85,0 +153,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = require("ava");
const fs_1 = require("fs");
const lodash_1 = require("lodash");
const path_1 = require("path");
const normalizer_1 = require("../src/normalizer");
const reporter_1 = require("./reporter");
const normalizerDir = __dirname + '/../../test/normalizer';
var ava_1 = require("ava");
var fs_1 = require("fs");
var lodash_1 = require("lodash");
var path_1 = require("path");
var normalizer_1 = require("../src/normalizer");
var reporter_1 = require("./reporter");
var normalizerDir = __dirname + '/../../test/normalizer';
function run() {
fs_1.readdirSync(normalizerDir)
.filter(_ => /^.*\.json$/.test(_))
.map(_ => path_1.join(normalizerDir, _))
.map(_ => [_, require(_)])
.forEach(([filename, json]) => {
const params = { filename };
ava_1.test(json.name, t => reporter_1.compare(t, json.name, lodash_1.template(toString(normalizer_1.normalize(json.in, filename)))(params), lodash_1.template(toString(json.out))(params)));
.filter(function (_) { return /^.*\.json$/.test(_); })
.map(function (_) { return path_1.join(normalizerDir, _); })
.map(function (_) { return [_, require(_)]; })
.forEach(function (_a) {
var filename = _a[0], json = _a[1];
var params = { filename: filename };
ava_1.test(json.name, function (t) {
return reporter_1.compare(t, json.name, lodash_1.template(toString(normalizer_1.normalize(json.in, filename)))(params), lodash_1.template(toString(json.out))(params));
});
});

@@ -19,0 +22,0 @@ }

{
"name": "json-schema-to-typescript",
"version": "4.1.1",
"version": "4.1.2",
"description": "compile json schema to typescript typings",

@@ -10,2 +10,5 @@ "main": "dist/src/index.js",

"typings": "dist/src/index.d.ts",
"engines": {
"node": ">=4.5.0"
},
"scripts": {

@@ -12,0 +15,0 @@ "build": "npm run clean && mkdir dist && npm run build:browser && npm run build:server",

import { whiteBright } from 'cli-color'
import { JSONSchema4Type, JSONSchema4TypeName } from 'json-schema'
import { findKey, isPlainObject, map } from 'lodash'
import { findKey, includes, isPlainObject, map } from 'lodash'
import { typeOfSchema } from './typeOfSchema'

@@ -221,3 +221,3 @@ import { AST, T_ANY, T_ANY_ADDITIONAL_PROPERTIES, TInterfaceParam } from './types/AST'

ast: parse(value, rootSchema, key, processed),
isRequired: (schema.required || []).includes(key),
isRequired: includes(schema.required || [], key),
keyName: key

@@ -224,0 +224,0 @@ }))

@@ -5,4 +5,3 @@ {

"lib": [
"es2015",
"es2016.array.include"
"es2015"
],

@@ -19,3 +18,3 @@ "module": "commonjs",

"strictNullChecks": true,
"target": "es2016"
"target": "es5"
},

@@ -22,0 +21,0 @@ "exclude": [

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc