UNPKG

@gatekeeper_technology/report-utils

Version:
196 lines (195 loc) 8.1 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.postToJourneyBackend = exports.generateHTML = exports.validateEmail = exports.storeValidEmail = exports.setCheckWhitelistEnvironments = exports.getToEmailsArray = void 0; const pdf_reports_1 = require("@journeyapps/pdf-reports"); const db_1 = require("@journeyapps/db"); const path_1 = require("path"); const fs_1 = require("fs"); const handlebars_1 = require("handlebars"); let check_whitelist_environments = ["staging", "testing"]; /** * Takes to and cc array of email addresses and ensures uniqueness and that they are part of the whitelist in testing and staging * @param {string[]} to_array Array of email address * @param {string[]} cc_array Array of email address * @param {string} env Environment * @param {string[]} whitelist Whitelisted email addresses * @returns {{to: {email: string}[], cc: {email: string}[]}} */ function getToEmailsArray(to_array, cc_array, env, whitelist) { let _to_emails = getUniqueEmails(to_array); let _cc_emails = getUniqueEmails(cc_array); // If a CC, already exists in the to array, we need to remove it for (const [_index, _cc_mail] of Array.from(_cc_emails.entries())) { if (_to_emails.includes(_cc_mail)) { _cc_emails.splice(_index, 1); } } const check_whitelisting = check_whitelist_environments.includes(env); // Check whitelist in Staging and Testing if (check_whitelisting) { if (!whitelist) { throw Error(`No whitelist set up.`); } // Check whitelist _to_emails = _to_emails.filter((email) => whitelist.includes(email)); _cc_emails = _cc_emails.filter((email) => whitelist.includes(email)); } if (_to_emails.length === 0) { throw Error('[REPORT UTILS] A "to" email address is required to send emails'); } return { to: _to_emails.map((unique_email) => { return { email: unique_email, }; }), cc: _cc_emails.map((unique_email) => { return { email: unique_email, }; }), }; } exports.getToEmailsArray = getToEmailsArray; /** * Sets the environments where email whitelisting should be enabled * * @param {string[]} environments array of environments to check whitelist */ function setCheckWhitelistEnvironments(environments) { if (!Array.isArray(environments)) { throw Error(`[REPORT UTILS] Expected Array, but found ${typeof environments}`); } const valid_environments = ["testing", "staging", "production"]; const lower_case_environments = environments.map((environment) => environment.toLowerCase()); for (let lower_case_environment of lower_case_environments) { const valid = valid_environments.includes(lower_case_environment); if (!valid) { throw Error(`[REPORT UTILS] Invalid environment name given: ${lower_case_environment}`); } } check_whitelist_environments = Object.assign([], lower_case_environments); } exports.setCheckWhitelistEnvironments = setCheckWhitelistEnvironments; /** * This function that takes an array of emails and returns the trimmed unique emails. * If this is Staging and Testing, it also checks the whitelist. */ function getUniqueEmails(_email_arr) { const email_arr = returnNestedArray(_email_arr); const unique_email_object = {}; for (const _email of email_arr) { if (typeof _email !== "string") { console.log(`[REPORT UTILS] Invalid email address: ${JSON.stringify(_email)}`); continue; } const _trimmed_email = _email.trim(); if (_trimmed_email == null || _trimmed_email === "null") { console.log(`[REPORT UTILS] Invalid null email address: ${JSON.stringify(_email)}`); continue; } let _delimiter = null; if (_trimmed_email.includes(";")) { _delimiter = ";"; } else if (_trimmed_email.includes(",")) { _delimiter = ","; } if (_delimiter) { const multiple_emails = _trimmed_email.split(_delimiter); for (let _multiple_email of multiple_emails) { storeValidEmail(unique_email_object, _multiple_email); } } else { storeValidEmail(unique_email_object, _trimmed_email); } } return Object.keys(unique_email_object); } ; function storeValidEmail(email_object, email) { if (email != null) { email = email.toLowerCase(); email = email.trim(); if (validateEmail(email)) { email_object[email] = email; return; } } console.log(`[REPORT UTILS] Invalid email address: ${JSON.stringify(email)}`); } exports.storeValidEmail = storeValidEmail; function validateEmail(email) { const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } exports.validateEmail = validateEmail; function returnNestedArray(array) { if (Array.isArray(array) && array.length === 0) { console.log(`[REPORT UTILS] Returning the empty array.`); return array; } if (typeof array === "string") { return [array]; } else if (Array.isArray(array) && array.length) { if (Array.isArray(array[0]) && typeof array[0] !== "string") { return returnNestedArray(array[0]); } else { return array; } } else { console.log(`[REPORT UTILS] Error: Unexpected array input in returnNestedArray function ${JSON.stringify(array)}`); return array; } } /** * * @param data The data generated by `generateData` function * @param dirName Simply the built in variable `__dirname` * @param fileName The name of the file. * @returns HTML string. */ function generateHTML(data, dirName, fileName) { const htmlData = (0, fs_1.readFileSync)((0, path_1.join)(dirName, fileName), "utf8"); // Generate HTML using handlebars const pdfTemplate = (0, handlebars_1.compile)(htmlData); const pdfHtml = pdfTemplate(data); console.log(`[REPORT UTILS] 🌐 Generated HTML for ${fileName}.`); return pdfHtml; } exports.generateHTML = generateHTML; function postToJourneyBackend(object, fieldName, pdfHtml, fileName, token) { return __awaiter(this, void 0, void 0, function* () { (0, pdf_reports_1.setApiToken)(token); try { const generated_pdf = yield (0, pdf_reports_1.generatePdf)({ html: pdfHtml }); const pdf_buffer = yield generated_pdf.toBuffer(); const attachment = yield db_1.Attachment.create({ filename: fileName, mediaType: 'application/pdf', data: pdf_buffer }); if (!object.hasOwnProperty(fieldName)) { throw Error(`[REPORT UTILS] Could not find field (${fieldName}) on object`); } object[fieldName] = attachment; yield object.save(); console.log("[REPORT UTILS] 💾 Saved the PDF on the Request object"); return true; } catch (error) { console.error(`[REPORT UTILS] ${error.stack}`); return false; } }); } exports.postToJourneyBackend = postToJourneyBackend;