1"use strict"; 2var __importDefault = (this && this.__importDefault) || function (mod) { 3 return (mod && mod.__esModule) ? mod : { "default": mod }; 4}; 5Object.defineProperty(exports, "__esModule", { value: true }); 6exports.readTarget = void 0; 7/* 8Copyright 2023 The Sigstore Authors. 9 10Licensed under the Apache License, Version 2.0 (the "License"); 11you may not use this file except in compliance with the License. 12You may obtain a copy of the License at 13 14 http://www.apache.org/licenses/LICENSE-2.0 15 16Unless required by applicable law or agreed to in writing, software 17distributed under the License is distributed on an "AS IS" BASIS, 18WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19See the License for the specific language governing permissions and 20limitations under the License. 21*/ 22const fs_1 = __importDefault(require("fs")); 23const error_1 = require("./error"); 24// Downloads and returns the specified target from the provided TUF Updater. 25async function readTarget(tuf, targetPath) { 26 const path = await getTargetPath(tuf, targetPath); 27 return new Promise((resolve, reject) => { 28 fs_1.default.readFile(path, 'utf-8', (err, data) => { 29 if (err) { 30 reject(new error_1.TUFError({ 31 code: 'TUF_READ_TARGET_ERROR', 32 message: `error reading target ${path}`, 33 cause: err, 34 })); 35 } 36 else { 37 resolve(data); 38 } 39 }); 40 }); 41} 42exports.readTarget = readTarget; 43// Returns the local path to the specified target. If the target is not yet 44// cached locally, the provided TUF Updater will be used to download and 45// cache the target. 46async function getTargetPath(tuf, target) { 47 let targetInfo; 48 try { 49 targetInfo = await tuf.getTargetInfo(target); 50 } 51 catch (err) { 52 throw new error_1.TUFError({ 53 code: 'TUF_REFRESH_METADATA_ERROR', 54 message: 'error refreshing TUF metadata', 55 cause: err, 56 }); 57 } 58 if (!targetInfo) { 59 throw new error_1.TUFError({ 60 code: 'TUF_FIND_TARGET_ERROR', 61 message: `target ${target} not found`, 62 }); 63 } 64 let path = await tuf.findCachedTarget(targetInfo); 65 // An empty path here means the target has not been cached locally, or is 66 // out of date. In either case, we need to download it. 67 if (!path) { 68 try { 69 path = await tuf.downloadTarget(targetInfo); 70 } 71 catch (err) { 72 throw new error_1.TUFError({ 73 code: 'TUF_DOWNLOAD_TARGET_ERROR', 74 message: `error downloading target ${path}`, 75 cause: err, 76 }); 77 } 78 } 79 return path; 80} 81