UNPKG

zengenti-buildstartup-package

Version:

Post-build scripts to generate the startup scripts for any configured environments

274 lines (251 loc) 10.3 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("dotenv")); else if(typeof define === 'function' && define.amd) define(["dotenv"], factory); else { var a = typeof exports === 'object' ? factory(require("dotenv")) : factory(root["dotenv"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(global, (__WEBPACK_EXTERNAL_MODULE__254__) => { return /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 84 (module, __unused_webpack_exports, __webpack_require__) { const fs = __webpack_require__(896); const dotenv = __webpack_require__(254); const path = __webpack_require__(928); const _module = path.basename(__filename); let projects = env => [{ id: env.PROJECT, publicUri: env.PUBLIC_URL }]; // Try to resolve a path provided as an argument to a define-config // file containing an exported function called 'projects' // which returns an array of specified projects try { try { projects = require(path.resolve("./webpack/define-config")).projects; } catch (e) { projects = __webpack_require__(90)(path.resolve("./webpack/define-config")).projects; } } catch (ex) { // console.log(ex); } function loadConfig(env) { console.log('Found environment in: "' + env + '"'); // read values from .env file and set process.env.* var envConfig = dotenv.parse(fs.readFileSync(env)); console.log(projects(envConfig)); process.env.dotenv = env; return envConfig; } function readModuleFileSync(filePath) { try { return fs.readFileSync(filePath, "utf8"); } catch (e) { console.log(e); } } function makeReplacements(config, template, isClient) { // replace template with stringified values from .env.* // finally map all entries to context.* variables and write them out const builtTemplate = template.replace(/_PROJECTS_/g, JSON.stringify(projects(config))).replace(/_ALIAS_/g, JSON.stringify(config.ALIAS)).replace(/_INTERNAL_VIP_/g, isClient ? '""' : JSON.stringify(config.INTERNAL_VIP)).replace(/_ACCESS_TOKEN_/g, JSON.stringify(config.ACCESS_TOKEN)).replace(/_PROJECT_/g, JSON.stringify(config.PROJECT)).replace(/_PUBLIC_URL_/g, JSON.stringify(config.PUBLIC_URL)).replace(/_CLIENT_ID_/g, JSON.stringify(config.CLIENT_ID)).replace(/_CLIENT_SECRET_/g, JSON.stringify(config.CLIENT_SECRET)).replace(/_ALL_ENV_VARS_;/, Object.entries(config).map(([k, v]) => ["INTERNAL_VIP"].includes(k) ? null : `context.${k} = ${JSON.stringify(v)};`).filter(v => v).join("\n")); return isClient ? builtTemplate.substring(0, builtTemplate.indexOf("_SERVER_ONLY_")) : builtTemplate.replace("_SERVER_ONLY_;", ""); } function mkdirp(filepath) { var dirname = path.dirname(filepath); if (!fs.existsSync(dirname)) { mkdirp(dirname); } if (!fs.existsSync(filepath)) { fs.mkdirSync(filepath); } } function writeModuleFileSync(filename, contents) { try { mkdirp(path.dirname(filename)); fs.writeFileSync(filename, contents); console.log("--", 'Created "' + filename + '"'); } catch (e) { console.log("--", 'Problem writing file: "' + filename + '"', e); } } function buildStartupRuntime({ alias, projectId, accessToken }) { try { console.log("/* ", _module, "- Building server start script for dynamic environment", "*/"); // the base startup template we are going to make environment specific // replacements on var template = readModuleFileSync(__dirname + "/startup.template.js"); var config = loadConfig(".env"); //load in a default env config //use the passed in vars, if any, to set the loaded config config.ALIAS = alias || config.ALIAS; config.PROJECT = projectId || config.PROJECT; config.ACCESS_TOKEN = accessToken || config.ACCESS_TOKEN; console.log(config); var serverStartup = makeReplacements(config, template); // write a startup.projectId.alias.js file for the environment alias read from // the .env.* file so the script can be used to start the server // and serve the bundle configuration for that specific environment writeModuleFileSync(`dist/server/start.${config.PROJECT.toLowerCase()}.${config.ALIAS.toLowerCase()}.js`, serverStartup); console.log("/* 👏 ", _module, "completed successfully", "*/"); } catch (e) { console.log("/* !! ", _module, "encountered a problem: ", "*/", e.stack); } } module.exports = { setDefaults: function (currentScript, staticPath = "static") { // in a server context check if we are using a standard or // targeted start script and write new defaults for a targeted startup var defaultScript = path.dirname(currentScript) + "/start.js"; if (path.resolve(currentScript) != path.resolve(defaultScript)) { try { console.log('[launcher set default]', currentScript); // in a server context we copy the current (targeted) start script // to be the default so we can serve a static startup bundle to the client // and start the server with default scripts pre-targeted fs.copyFileSync(currentScript, path.dirname(path.dirname(currentScript)) + "/" + staticPath + "/startup.js"); fs.copyFileSync(currentScript, path.dirname(currentScript) + "/start.js"); } catch (err) { console.log(err); } } }, buildStartupRuntime, buildUtils: { loadConfig, makeReplacements, readModuleFileSync, writeModuleFileSync } }; /***/ }, /***/ 90 (module) { function webpackEmptyContext(req) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } webpackEmptyContext.keys = () => ([]); webpackEmptyContext.resolve = webpackEmptyContext; webpackEmptyContext.id = 90; module.exports = webpackEmptyContext; /***/ }, /***/ 896 (module) { "use strict"; module.exports = require("fs"); /***/ }, /***/ 928 (module) { "use strict"; module.exports = require("path"); /***/ }, /***/ 254 (module) { "use strict"; module.exports = __WEBPACK_EXTERNAL_MODULE__254__; /***/ } /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; const fs = __webpack_require__(896); const path = __webpack_require__(928); const _module = path.basename(__filename); var buildUtils = (__webpack_require__(84).buildUtils); var { loadConfig, makeReplacements, readModuleFileSync, writeModuleFileSync } = buildUtils; function readDotEnvFiles() { var envs = []; fs.readdirSync(process.cwd()).forEach(filename => { if (filename.startsWith(".env")) { envs.push(filename); } }); return envs; } try { console.log("/* ", _module, "- Building server start scripts for .env* file(s)", "*/"); // read all files in root called .env* and create separate // startup files for all configured environments, so the production // bundles can be started with any of these scripts var envs = readDotEnvFiles(); // the base startup template we are going to make environment specific // replacements on var template = readModuleFileSync(__dirname + "/start/startup.template.js"); envs.forEach(env => { // for each env we will load the .env.* file into process.env.* variables // then make replacements to the template var config = loadConfig(env); var staticPath = config.STATIC_PATH || "static"; var clientStartup = makeReplacements(config, template, true).replace(/\s+/g, " ").trim(); var serverStartup = makeReplacements(config, template); if (process.env.dotenv == ".env") { // write the 'default' project startup (.env) as just start.js // so it is ready to launch with just a default server start script // and serve a default client bundle writeModuleFileSync("dist/" + staticPath + "/startup.js", clientStartup); writeModuleFileSync("dist/server/start.js", serverStartup); } // write a startup.projectId.alias.js file for the environment alias read from // the .env.* file so the script can be used to start the server // and serve the bundle configuration for that specific environment writeModuleFileSync(`dist/server/start.${config.PROJECT.toLowerCase()}.${config.ALIAS.toLowerCase()}.js`, serverStartup); }); console.log("Deploying server start scripts"); fs.copyFileSync(__dirname + "/start/start.js", "dist/start.js"); fs.copyFileSync(__dirname + "/start/startup.utils.js", "dist/server/startup.utils.js"); // Copying these new files for the ability to generate a targeted server // start script inside the container for an unknown CMS fs.copyFileSync(__dirname + "/start/launcher.js", "dist/server/launcher.js"); fs.copyFileSync(__dirname + "/start/startup.template.js", "dist/server/startup.template.js"); console.log("/* 👏 ", _module, "completed successfully", "*/"); } catch (e) { console.log("/* !! ", _module, "encountered a problem: ", "*/", e.stack); } /******/ return __webpack_exports__; /******/ })() ; }); //# sourceMappingURL=zengenti-buildstartup-package.js.map