@tufjs/repo-mock
Version:
HTTP mocking for TUF repository requests
75 lines (74 loc) • 2.7 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeTUFRepo = exports.tufHandlers = void 0;
exports.mockRepo = mockRepo;
exports.clearMock = clearMock;
const fs_1 = __importDefault(require("fs"));
const nock_1 = __importDefault(require("nock"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const handler_1 = require("./handler");
const mock_1 = require("./mock");
const repo_1 = require("./repo");
var handler_2 = require("./handler");
Object.defineProperty(exports, "tufHandlers", { enumerable: true, get: function () { return handler_2.tufHandlers; } });
var repo_2 = require("./repo");
Object.defineProperty(exports, "initializeTUFRepo", { enumerable: true, get: function () { return repo_2.initializeTUFRepo; } });
function mockRepo(baseURL, targets, options = {}) {
const tufRepo = (0, repo_1.initializeTUFRepo)(targets);
const handlers = (0, handler_1.tufHandlers)(tufRepo, options);
handlers.forEach((handler) => {
// Don't set-up a mock for the 1.root.json file as this should never be
// fetched in a normal TUF flow.
if (handler.path.endsWith('1.root.json')) {
return;
}
(0, mock_1.mock)(baseURL, handler);
});
return JSON.stringify(tufRepo.rootMeta.toJSON());
}
function clearMock() {
nock_1.default.cleanAll();
}
class Scope {
targets;
options;
baseURL;
cachePath;
constructor(targets, options = {}) {
this.targets = targets;
this.options = options;
this.baseURL =
options.baseURL ??
`http://${Math.random().toString(36).substring(2)}.com`;
if (options.cachePath) {
fs_1.default.mkdirSync(options.cachePath, { recursive: true });
this.cachePath = options.cachePath;
}
else {
this.cachePath = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'tuf-cache-test-'));
}
this.setup();
}
reset() {
this.teardown();
this.setup();
}
teardown() {
clearMock();
fs_1.default.rmSync(this.cachePath, { recursive: true });
}
setup() {
const rootJSON = mockRepo(this.baseURL, this.targets, this.options);
fs_1.default.writeFileSync(path_1.default.join(this.cachePath, 'root.json'), rootJSON);
}
}
exports.default = (targets, options = {}) => {
if (!Array.isArray(targets)) {
targets = [targets];
}
return new Scope(targets, options);
};