xref: /expo/packages/@expo/env/build/env.js (revision e83cd14c)
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.createControlledEnvironment = createControlledEnvironment;
7exports.getFiles = getFiles;
8function dotenv() {
9  const data = _interopRequireWildcard(require("dotenv"));
10  dotenv = function () {
11    return data;
12  };
13  return data;
14}
15function _dotenvExpand() {
16  const data = require("dotenv-expand");
17  _dotenvExpand = function () {
18    return data;
19  };
20  return data;
21}
22function fs() {
23  const data = _interopRequireWildcard(require("fs"));
24  fs = function () {
25    return data;
26  };
27  return data;
28}
29function path() {
30  const data = _interopRequireWildcard(require("path"));
31  path = function () {
32    return data;
33  };
34  return data;
35}
36function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
37function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
38/**
39 * Copyright © 2023 650 Industries.
40 *
41 * This source code is licensed under the MIT license found in the
42 * LICENSE file in the root directory of this source tree.
43 */
44
45const debug = require('debug')('expo:env');
46function createControlledEnvironment() {
47  const IS_DEBUG = require('debug').enabled('expo:env');
48  let userDefinedEnvironment = undefined;
49  let memoEnvironment = undefined;
50  function _getForce(projectRoot) {
51    if (!userDefinedEnvironment) {
52      userDefinedEnvironment = {
53        ...process.env
54      };
55    }
56
57    // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
58    const dotenvFiles = getFiles(process.env.NODE_ENV);
59    const loadedEnvFiles = [];
60    const parsed = {};
61
62    // Load environment variables from .env* files. Suppress warnings using silent
63    // if this file is missing. dotenv will never modify any environment variables
64    // that have already been set. Variable expansion is supported in .env files.
65    // https://github.com/motdotla/dotenv
66    // https://github.com/motdotla/dotenv-expand
67    dotenvFiles.forEach(dotenvFile => {
68      const absoluteDotenvFile = path().resolve(projectRoot, dotenvFile);
69      if (!fs().existsSync(absoluteDotenvFile)) {
70        return;
71      }
72      try {
73        const results = (0, _dotenvExpand().expand)(dotenv().config({
74          debug: IS_DEBUG,
75          path: absoluteDotenvFile,
76          // We will handle overriding ourselves to allow for HMR.
77          override: true
78        }));
79        if (results.parsed) {
80          loadedEnvFiles.push(absoluteDotenvFile);
81          debug(`Loaded environment variables from: ${absoluteDotenvFile}`);
82          for (const key of Object.keys(results.parsed || {})) {
83            var _userDefinedEnvironme;
84            if (typeof parsed[key] === 'undefined' &&
85            // Custom override logic to prevent overriding variables that
86            // were set before the CLI process began.
87            typeof ((_userDefinedEnvironme = userDefinedEnvironment) === null || _userDefinedEnvironme === void 0 ? void 0 : _userDefinedEnvironme[key]) === 'undefined') {
88              parsed[key] = results.parsed[key];
89            }
90          }
91        } else {
92          debug(`Failed to load environment variables from: ${absoluteDotenvFile}`);
93        }
94      } catch (error) {
95        if (error instanceof Error) {
96          console.error(`Failed to load environment variables from ${absoluteDotenvFile}: ${error.message}`);
97        } else {
98          throw error;
99        }
100      }
101    });
102    if (!loadedEnvFiles.length) {
103      debug(`No environment variables loaded from .env files.`);
104    }
105    return parsed;
106  }
107
108  /** Get the environment variables without mutating the environment. This returns memoized values unless the `force` property is provided. */
109  function get(projectRoot, {
110    force
111  } = {}) {
112    if (!force && memoEnvironment) {
113      return memoEnvironment;
114    }
115    memoEnvironment = _getForce(projectRoot);
116    return memoEnvironment;
117  }
118
119  /** Load environment variables from .env files and mutate the current `process.env` with the results. */
120  function load(projectRoot, {
121    force
122  } = {}) {
123    const env = get(projectRoot, {
124      force
125    });
126    process.env = {
127      ...process.env,
128      ...env
129    };
130    return process.env;
131  }
132  return {
133    load,
134    get,
135    _getForce
136  };
137}
138function getFiles(mode) {
139  if (!mode) {
140    throw new Error('The NODE_ENV environment variable is required but was not specified. Ensure the project is bundled with Expo CLI.');
141  }
142  if (!mode || !['development', 'test', 'production'].includes(mode)) {
143    throw new Error(`Environment variable "NODE_ENV=${mode}" is invalid. Valid values are "development", "test", and "production`);
144  }
145
146  // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
147  const dotenvFiles = [`.env.${mode}.local`,
148  // Don't include `.env.local` for `test` environment
149  // since normally you expect tests to produce the same
150  // results for everyone
151  mode !== 'test' && `.env.local`, `.env.${mode}`, '.env'].filter(Boolean);
152  return dotenvFiles;
153}
154//# sourceMappingURL=env.js.map