var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // ../../node_modules/dotenv/lib/main.js var require_main = __commonJS({ "../../node_modules/dotenv/lib/main.js"(exports2, module2) { var fs = require("fs"); var path = require("path"); function log(message) { console.log(`[dotenv][DEBUG] ${message}`); } var NEWLINE = "\n"; var RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/; var RE_NEWLINES = /\\n/g; var NEWLINES_MATCH = /\n|\r|\r\n/; function parse(src, options) { const debug = Boolean(options && options.debug); const obj = {}; src.toString().split(NEWLINES_MATCH).forEach(function(line, idx) { const keyValueArr = line.match(RE_INI_KEY_VAL); if (keyValueArr != null) { const key = keyValueArr[1]; let val = keyValueArr[2] || ""; const end = val.length - 1; const isDoubleQuoted = val[0] === '"' && val[end] === '"'; const isSingleQuoted = val[0] === "'" && val[end] === "'"; if (isSingleQuoted || isDoubleQuoted) { val = val.substring(1, end); if (isDoubleQuoted) { val = val.replace(RE_NEWLINES, NEWLINE); } } else { val = val.trim(); } obj[key] = val; } else if (debug) { log(`did not match key and value when parsing line ${idx + 1}: ${line}`); } }); return obj; } function config(options) { let dotenvPath = path.resolve(process.cwd(), ".env"); let encoding = "utf8"; let debug = false; if (options) { if (options.path != null) { dotenvPath = options.path; } if (options.encoding != null) { encoding = options.encoding; } if (options.debug != null) { debug = true; } } try { const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }); Object.keys(parsed).forEach(function(key) { if (!Object.prototype.hasOwnProperty.call(process.env, key)) { process.env[key] = parsed[key]; } else if (debug) { log(`"${key}" is already defined in \`process.env\` and will not be overwritten`); } }); return { parsed }; } catch (e) { return { error: e }; } } module2.exports.config = config; module2.exports.parse = parse; } }); // src/index.ts var src_exports = {}; __export(src_exports, { default: () => src_default }); module.exports = __toCommonJS(src_exports); // src/dynamicEnvironmentsSupport.ts var import_node_fs = require("fs"); var import_node_path = require("path"); var import_dotenv = __toESM(require_main(), 1); var import_vite = require("vite"); var logger = (0, import_vite.createLogger)("info", { prefix: "[dynamicEnvironmentsSupport]" }); var { FORCE_ENVIRONMENT } = process.env; var getLast = (array) => array[array.length - 1]; var getDynamicEnvironment = ({ path, ignorePrefixes = [] }) => { if (!(0, import_node_fs.existsSync)(path)) { throw new Error(`File does not exist (${path})`); } const config = import_dotenv.default.parse((0, import_node_fs.readFileSync)(path)); const dynamicEnvironment = Object.fromEntries( Object.entries(config).filter(([key]) => !ignorePrefixes.some((prefix) => key.startsWith(prefix))) ); return dynamicEnvironment; }; var generateScript = (environment) => `window.dynamicEnvironment = Object.freeze(${JSON.stringify(environment)});`; var DEFAULT_SCRIPT_LINK = "/dynamicEnvironment.js"; var DEFAULT_DYNAMIC_ENVIRONMENTS_DIR = (0, import_node_path.resolve)(process.cwd(), "environments/dynamic"); var DEFAULT_OUTPUT_DIR = (0, import_node_path.resolve)(process.cwd(), "build-env"); var dynamicEnvironmentsSupport = ({ scriptLink = DEFAULT_SCRIPT_LINK, ignorePrefixes = ["VITE_"], dynamicEnvironmentsDir = DEFAULT_DYNAMIC_ENVIRONMENTS_DIR, envOutputDir = DEFAULT_OUTPUT_DIR } = {}) => { let outDir; let envDir; let envConfig; let forceEnvironmentScriptContent; return { name: "@37bytes/vite-dynamic-environments", config: (config, nextEnvConfig) => { outDir = config.build?.outDir ?? "dist"; envConfig = nextEnvConfig; if (config.envDir) { envDir = (0, import_node_path.resolve)(process.cwd(), config.envDir); } else { envDir = process.cwd(); } }, // режим разработки configureServer(server) { server.middlewares.use(scriptLink, (request, response) => { if (!envDir) { throw new Error("envDir is falsy"); } const dynamicEnvironment = getDynamicEnvironment({ ignorePrefixes, path: (0, import_node_path.resolve)(envDir, `.env.${envConfig.mode}`) }); response.writeHead(200, { "Content-Type": "application/json" }); response.end(generateScript(dynamicEnvironment)); }); }, // очистка outputDir buildStart: () => { (0, import_node_fs.rmSync)(envOutputDir, { recursive: true, force: true }); }, // генерация .js для каждого динамического окружения buildEnd: () => { const fullPathToDynamicEnvironments = (0, import_node_path.resolve)(process.cwd(), dynamicEnvironmentsDir); (0, import_node_fs.readdirSync)(fullPathToDynamicEnvironments).forEach((fileName) => { if (!fileName.startsWith(".env.")) { return; } const fullPathToFile = (0, import_node_path.join)(fullPathToDynamicEnvironments, fileName); if ((0, import_node_fs.statSync)(fullPathToFile).isDirectory()) { return; } const environmentName = getLast(fileName.split(".")); const dynamicEnvironment = getDynamicEnvironment({ ignorePrefixes, path: fullPathToFile }); if (!(0, import_node_fs.existsSync)(envOutputDir)) { (0, import_node_fs.mkdirSync)(envOutputDir, { recursive: true }); } const scriptContent = generateScript(dynamicEnvironment); (0, import_node_fs.writeFileSync)((0, import_node_path.join)(envOutputDir, `dynamicEnvironment.${environmentName}.js`), scriptContent); if (FORCE_ENVIRONMENT === environmentName) { logger.info( `process.env.FORCE_ENVIRONMENT defined! preparing dynamicEnvironment.js for "${environmentName}"...` ); forceEnvironmentScriptContent = scriptContent; } }); }, // автоматическое добавление скрипта в html transformIndexHtml: (html) => { if (!html.includes("")) { throw new Error("dynamicEnvironmentsPlugin: '' not found in html"); } return html.replace("", ``); }, writeBundle: () => { if (forceEnvironmentScriptContent) { logger.info(`writing prepared dynamicEnvironment.js in "${outDir}"...`); (0, import_node_fs.writeFileSync)((0, import_node_path.join)((0, import_node_path.resolve)(outDir, "dynamicEnvironment.js")), forceEnvironmentScriptContent); } } }; }; var dynamicEnvironmentsSupport_default = dynamicEnvironmentsSupport; // src/index.ts var src_default = dynamicEnvironmentsSupport_default;