@json-schema-tools/dereferencer
Version:
Dereference (aka parse refs) from JSON Schemas
263 lines (262 loc) • 12 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__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;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
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, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, 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 };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NonStringRefError = void 0;
var traverse_1 = __importDefault(require("@json-schema-tools/traverse"));
var reference_resolver_1 = __importDefault(require("@json-schema-tools/reference-resolver"));
var fast_safe_stringify_1 = __importDefault(require("fast-safe-stringify"));
/**
* Error thrown by the constructor when given a ref that isn't a string
*
*
* @example
* ```typescript
*
* import Dereferencer, { NonStringRefError } from "@json-schema-tools/dereferencer";
*
* try { const dereffer = new Dereferencer({}); }
* catch(e) {
* if (e instanceof NonStringRefError) { ... }
* }
* ```
*
*/
var NonStringRefError = /** @class */ (function () {
function NonStringRefError(s) {
this.name = "NonStringRefError";
this.message = [
"NonStringRefError",
"Found an improperly formatted $ref in schema. $ref must be a string",
"schema in question: ".concat((0, fast_safe_stringify_1.default)(s)),
].join("\n");
}
return NonStringRefError;
}());
exports.NonStringRefError = NonStringRefError;
var copyOrNot = function (s1, s2) {
if (s1.$ref !== undefined &&
Object.keys(s1).length > 1 &&
(s2 !== true && s2 !== false)) {
var reflessCopy = __assign(__assign({}, s2), s1);
delete reflessCopy.$ref;
return reflessCopy;
}
else {
return s2;
}
};
/**
* When instantiated, represents a fully configured dereferencer. When constructed, references are pulled out.
* No references are fetched until .resolve is called.
*/
var Dereferencer = /** @class */ (function () {
function Dereferencer(schema, options) {
if (options === void 0) { options = {}; }
this.options = options;
this.refCache = {};
var workingSchema;
if (this.options.mutate === true) {
workingSchema = schema;
}
else {
workingSchema = schema === true || schema === false ? schema : __assign({}, schema);
}
if (this.options.recursive === undefined) {
this.options.recursive = true;
}
if (this.options.rootSchema === undefined) {
this.options.rootSchema = workingSchema;
}
if (schema !== true && schema !== false && schema.$id) {
this.options.rootSchema = workingSchema;
}
if (this.options.refCache) {
this.refCache = this.options.refCache;
}
if (this.options.protocolHandlerMap) {
for (var _i = 0, _a = Object.keys(this.options.protocolHandlerMap); _i < _a.length; _i++) {
var k = _a[_i];
reference_resolver_1.default.protocolHandlerMap[k] = this.options.protocolHandlerMap[k];
}
}
this.schema = workingSchema; // shallow copy breaks recursive
this.refs = this.collectRefs();
}
/**
* Fetches the schemas for all the refs in the configured input schema(s)
*
* @returns a promise that will resolve a fully dereferenced schema, where all the
* promises for each ref has been resolved as well.
*
*
*/
Dereferencer.prototype.resolve = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._resolve()];
case 1:
_a.sent();
delete this.schema.definitions;
delete this.schema.components;
return [2 /*return*/, this.schema];
}
});
});
};
Dereferencer.prototype._resolve = function () {
return __awaiter(this, void 0, void 0, function () {
var unfetchedRefs, proms, _i, unfetchedRefs_1, ref, fetched, refProm, subDerefferOpts, subDereffer, subFetchedProm, subFetched;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.schema === true || this.schema === false) {
return [2 /*return*/, Promise.resolve(this.schema)];
}
if (this.refs.length === 0) {
return [2 /*return*/, Promise.resolve(this.schema)];
}
unfetchedRefs = this.refs.filter(function (r) { return _this.refCache[r] === undefined; });
proms = [];
_i = 0, unfetchedRefs_1 = unfetchedRefs;
_a.label = 1;
case 1:
if (!(_i < unfetchedRefs_1.length)) return [3 /*break*/, 11];
ref = unfetchedRefs_1[_i];
fetched = void 0;
if (!(this.refCache[ref] !== undefined)) return [3 /*break*/, 2];
fetched = this.refCache[ref];
return [3 /*break*/, 5];
case 2:
if (!(ref === "#")) return [3 /*break*/, 3];
if (this.options.rootSchema === undefined) {
throw new Error("options.rootSchema was not provided, but one of the schemas references '#'");
}
fetched = this.options.rootSchema;
return [3 /*break*/, 5];
case 3:
refProm = reference_resolver_1.default.resolve(ref, this.options.rootSchema);
proms.push(refProm);
return [4 /*yield*/, refProm];
case 4:
fetched = (_a.sent());
_a.label = 5;
case 5:
if (!(this.options.recursive === true && fetched !== true && fetched !== false && ref !== "#")) return [3 /*break*/, 9];
subDerefferOpts = __assign(__assign({}, this.options), { refCache: this.refCache });
subDereffer = new Dereferencer(fetched, subDerefferOpts);
if (!(subDereffer.refs.length !== 0)) return [3 /*break*/, 7];
subFetchedProm = subDereffer._resolve();
proms.push(subFetchedProm);
return [4 /*yield*/, subFetchedProm];
case 6:
subFetched = _a.sent();
this.refCache[ref] = copyOrNot(fetched, subFetched);
return [3 /*break*/, 8];
case 7:
this.refCache[ref] = fetched;
_a.label = 8;
case 8: return [3 /*break*/, 10];
case 9:
this.refCache[ref] = fetched;
_a.label = 10;
case 10:
_i++;
return [3 /*break*/, 1];
case 11:
if (this.schema.$ref !== undefined) {
this.schema = copyOrNot(this.schema, this.refCache[this.schema.$ref]);
}
else {
(0, traverse_1.default)(this.schema, function (s) {
if (s === true || s === false) {
return s;
}
if (s.$ref !== undefined) {
var reffedSchema = _this.refCache[s.$ref];
return copyOrNot(s, reffedSchema);
}
return s;
}, { mutable: true });
}
return [4 /*yield*/, Promise.all(proms)];
case 12:
_a.sent();
return [2 /*return*/, this.schema];
}
});
});
};
/**
* First-pass traversal to collect all the refs that we can find. This allows us to
* optimize the async work required as well.
*/
Dereferencer.prototype.collectRefs = function () {
var refs = [];
(0, traverse_1.default)(this.schema, function (s) {
if (s === true || s === false) {
return s;
}
if (s.$ref && refs.indexOf(s.$ref) === -1) {
if (typeof s.$ref !== "string") {
throw new NonStringRefError(s);
}
refs.push(s.$ref);
}
return s;
});
return refs;
};
return Dereferencer;
}());
exports.default = Dereferencer;