env-replace.js 651 B

12345678910111213141516171819202122232425262728
  1. "use strict";
  2. module.exports = envReplace;
  3. // https://github.com/npm/npm/blob/latest/lib/config/core.js#L409-L423
  4. function envReplace(str) {
  5. if (typeof str !== "string" || !str) {
  6. return str;
  7. }
  8. // Replace any ${ENV} values with the appropriate environment
  9. const regex = /(\\*)\$\{([^}]+)\}/g;
  10. return str.replace(regex, (orig, esc, name) => {
  11. // eslint-disable-next-line no-param-reassign
  12. esc = esc.length > 0 && esc.length % 2;
  13. if (esc) {
  14. return orig;
  15. }
  16. if (process.env[name] === undefined) {
  17. throw new Error(`Failed to replace env in config: ${orig}`);
  18. }
  19. return process.env[name];
  20. });
  21. }