"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SIGNATURE_FILE_NAME=void 0,exports.encryptLocalFile=encryptLocalFile;const tslib_1=require("tslib"),fs_1=tslib_1.__importDefault(require("fs")),log=tslib_1.__importStar(require("../../utils/log")),crypto_1=tslib_1.__importDefault(require("crypto")),genTempFile_1=require("../genTempFile");async function encryptLocalFile(e,r){return new Promise((t,i)=>{let n={},o={};try{n=(0,genTempFile_1.genTempFile)(),o=(0,genTempFile_1.genTempFile)()}catch(e){throw log.error("Error:",e),new Error(e.message)}const l=fs_1.default.createReadStream(e),a=fs_1.default.createWriteStream(n.name);if(!r.crypt_key){const e="[encryptLocalFile failed] no crypt_key";return log.error(e),void i(e)}const c=crypto_1.default.randomBytes(12),s=crypto_1.default.createCipheriv("aes-256-gcm",Buffer.from(r.crypt_key,"base64"),c);l.pipe(s).pipe(a).on("finish",async()=>{try{const e=s.getAuthTag(),r=fs_1.default.statSync(n.name).size;log.info("nonce, nonce size: ",c,c.length),log.info("tag, tag size: ",e,null==e?void 0:e.length),log.info("encrypted file size in bytes: ",r);const l=Buffer.alloc(1);l.writeUInt8(e.length+c.length,0);const a=Buffer.concat([l,e,c]),p=await prependToFile(n.name,o.name,a);!0===p?t(o.name):(log.error("[encryptLocalFile failed] prependToFile",p),i(p))}catch(e){e.message="[encryptLocalFile failed] encryptLocalFile failed when finish: "+e.message,i(e)}}).on("error",e=>{i(e)})})}async function prependToFile(e,r,t){return new Promise(i=>{const n=fs_1.default.createReadStream(e),o=fs_1.default.createWriteStream(r);o.write(t),n.pipe(o),o.on("finish",()=>{i(!0)}),o.on("error",e=>{i(e)})})}exports.SIGNATURE_FILE_NAME="ci.signature";