@import-meta-env/unplugin
Advanced tools
Comparing version 0.2.1 to 0.3.0
1400
dist/index.js
@@ -34,12 +34,12 @@ "use strict"; | ||
var isColorSupported = !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && ("FORCE_COLOR" in process.env || process.argv.includes("--color") || process.platform === "win32" || tty.isatty(1) && process.env.TERM !== "dumb" || "CI" in process.env); | ||
var formatter = (open, close, replace = open) => (input) => { | ||
var formatter = (open, close, replace2 = open) => (input) => { | ||
let string = "" + input; | ||
let index = string.indexOf(close, open.length); | ||
return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; | ||
return ~index ? open + replaceClose(string, close, replace2, index) + close : open + string + close; | ||
}; | ||
var replaceClose = (string, close, replace, index) => { | ||
let start = string.substring(0, index) + replace; | ||
var replaceClose = (string, close, replace2, index) => { | ||
let start = string.substring(0, index) + replace2; | ||
let end = string.substring(index + close.length); | ||
let nextIndex = end.indexOf(close); | ||
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end; | ||
return ~nextIndex ? start + replaceClose(end, close, replace2, nextIndex) : start + end; | ||
}; | ||
@@ -79,2 +79,124 @@ var createColors = (enabled = isColorSupported) => ({ | ||
// ../../node_modules/.pnpm/sourcemap-codec@1.4.8/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js | ||
var require_sourcemap_codec_umd = __commonJS({ | ||
"../../node_modules/.pnpm/sourcemap-codec@1.4.8/node_modules/sourcemap-codec/dist/sourcemap-codec.umd.js"(exports, module2) { | ||
(function(global, factory) { | ||
typeof exports === "object" && typeof module2 !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = global || self, factory(global.sourcemapCodec = {})); | ||
})(exports, function(exports2) { | ||
"use strict"; | ||
var charToInteger = {}; | ||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; | ||
for (var i = 0; i < chars.length; i++) { | ||
charToInteger[chars.charCodeAt(i)] = i; | ||
} | ||
function decode(mappings) { | ||
var decoded = []; | ||
var line = []; | ||
var segment = [ | ||
0, | ||
0, | ||
0, | ||
0, | ||
0 | ||
]; | ||
var j = 0; | ||
for (var i2 = 0, shift = 0, value = 0; i2 < mappings.length; i2++) { | ||
var c = mappings.charCodeAt(i2); | ||
if (c === 44) { | ||
segmentify(line, segment, j); | ||
j = 0; | ||
} else if (c === 59) { | ||
segmentify(line, segment, j); | ||
j = 0; | ||
decoded.push(line); | ||
line = []; | ||
segment[0] = 0; | ||
} else { | ||
var integer = charToInteger[c]; | ||
if (integer === void 0) { | ||
throw new Error("Invalid character (" + String.fromCharCode(c) + ")"); | ||
} | ||
var hasContinuationBit = integer & 32; | ||
integer &= 31; | ||
value += integer << shift; | ||
if (hasContinuationBit) { | ||
shift += 5; | ||
} else { | ||
var shouldNegate = value & 1; | ||
value >>>= 1; | ||
if (shouldNegate) { | ||
value = value === 0 ? -2147483648 : -value; | ||
} | ||
segment[j] += value; | ||
j++; | ||
value = shift = 0; | ||
} | ||
} | ||
} | ||
segmentify(line, segment, j); | ||
decoded.push(line); | ||
return decoded; | ||
} | ||
function segmentify(line, segment, j) { | ||
if (j === 4) | ||
line.push([segment[0], segment[1], segment[2], segment[3]]); | ||
else if (j === 5) | ||
line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); | ||
else if (j === 1) | ||
line.push([segment[0]]); | ||
} | ||
function encode2(decoded) { | ||
var sourceFileIndex = 0; | ||
var sourceCodeLine = 0; | ||
var sourceCodeColumn = 0; | ||
var nameIndex = 0; | ||
var mappings = ""; | ||
for (var i2 = 0; i2 < decoded.length; i2++) { | ||
var line = decoded[i2]; | ||
if (i2 > 0) | ||
mappings += ";"; | ||
if (line.length === 0) | ||
continue; | ||
var generatedCodeColumn = 0; | ||
var lineMappings = []; | ||
for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { | ||
var segment = line_1[_i]; | ||
var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); | ||
generatedCodeColumn = segment[0]; | ||
if (segment.length > 1) { | ||
segmentMappings += encodeInteger(segment[1] - sourceFileIndex) + encodeInteger(segment[2] - sourceCodeLine) + encodeInteger(segment[3] - sourceCodeColumn); | ||
sourceFileIndex = segment[1]; | ||
sourceCodeLine = segment[2]; | ||
sourceCodeColumn = segment[3]; | ||
} | ||
if (segment.length === 5) { | ||
segmentMappings += encodeInteger(segment[4] - nameIndex); | ||
nameIndex = segment[4]; | ||
} | ||
lineMappings.push(segmentMappings); | ||
} | ||
mappings += lineMappings.join(","); | ||
} | ||
return mappings; | ||
} | ||
function encodeInteger(num) { | ||
var result = ""; | ||
num = num < 0 ? -num << 1 | 1 : num << 1; | ||
do { | ||
var clamped = num & 31; | ||
num >>>= 5; | ||
if (num > 0) { | ||
clamped |= 32; | ||
} | ||
result += chars[clamped]; | ||
} while (num > 0); | ||
return result; | ||
} | ||
exports2.decode = decode; | ||
exports2.encode = encode2; | ||
Object.defineProperty(exports2, "__esModule", { value: true }); | ||
}); | ||
} | ||
}); | ||
// src/index.ts | ||
@@ -87,10 +209,14 @@ var src_exports = {}; | ||
var import_unplugin = require("unplugin"); | ||
var import_picocolors2 = __toESM(require_picocolors()); | ||
var import_picocolors3 = __toESM(require_picocolors()); | ||
// package.json | ||
var version = "0.2.1"; | ||
var version = "0.3.0"; | ||
// ../shared/constant.ts | ||
var placeholder = `Object.create(globalThis["import_meta_env".slice()] || null)`; | ||
var createPlaceholderRegExp = (suffix) => new RegExp(placeholder.replace(/([\(\)\[\]\|])/g, "\\$1") + suffix, "g"); | ||
var createScriptPlaceholderRegExp = () => new RegExp(`<script id="import-meta-env"><\/script>`, "g"); | ||
var accessor = `Object.create(globalThis.import_meta_env || null)`; | ||
var createAccessorRegExp = (suffix, quote = "double") => new RegExp( | ||
"\\b" + accessor.replace(/([\(\)\[\]\|])/g, "\\$1").replace(/\s/g, "\\s*").replace(/"/g, quote === "double" ? '"' : "'") + suffix, | ||
"g" | ||
); | ||
var envFilePath = ".env"; | ||
@@ -193,6 +319,3 @@ | ||
parser.hooks.expression.for("import.meta.env").tap("ImportMetaPlugin", (expr) => { | ||
const dep = new dependencies.ConstDependency( | ||
placeholder, | ||
expr.range | ||
); | ||
const dep = new dependencies.ConstDependency(accessor, expr.range); | ||
dep.loc = expr.loc; | ||
@@ -217,13 +340,22 @@ parser.state.module.addPresentationalDependency(dep); | ||
// src/vite/preserve-built-in-env.ts | ||
var builtInEnvKeys = ["BASE_URL", "MODE", "DEV", "PROD", "SSR", "LEGACY"]; | ||
var builtInEnvKeys = [ | ||
"BASE_URL", | ||
"MODE", | ||
"DEV", | ||
"PROD", | ||
"SSR", | ||
"LEGACY" | ||
]; | ||
function preserveViteBuiltInEnv({ | ||
code, | ||
envPrefix | ||
}) { | ||
builtInEnvKeys.forEach((key) => { | ||
code = code.replace( | ||
createPlaceholderRegExp(`.${key}`), | ||
`import.meta.env.${key}` | ||
); | ||
}); | ||
let replacements = []; | ||
replacements = replacements.concat( | ||
builtInEnvKeys.map((key) => { | ||
return { | ||
regexp: new RegExp(`\\bimport\\.meta\\.env\\.${key}\\b`), | ||
substitution: `import.meta.env.${key}` | ||
}; | ||
}) | ||
); | ||
const normalizedEnPrefix = (() => { | ||
@@ -238,19 +370,982 @@ if (envPrefix === void 0) { | ||
})(); | ||
normalizedEnPrefix.forEach((prefix) => { | ||
code = code.replace( | ||
createPlaceholderRegExp(`.${prefix}`), | ||
`import.meta.env.${prefix}` | ||
); | ||
}); | ||
code = code.replace( | ||
createPlaceholderRegExp("([^.])"), | ||
`Object.assign({},${placeholder},import.meta.env)$1` | ||
replacements = replacements.concat( | ||
normalizedEnPrefix.map((prefix) => { | ||
return { | ||
regexp: new RegExp(`\\bimport\\.meta\\.env\\.${prefix}`), | ||
substitution: `import.meta.env.${prefix}` | ||
}; | ||
}) | ||
); | ||
code = code.replace( | ||
createPlaceholderRegExp("$"), | ||
`Object.assign({},${placeholder},import.meta.env)` | ||
); | ||
return code; | ||
return replacements; | ||
} | ||
// src/qwik/unwrap-signal-for-import-meta-env-env.ts | ||
function unwrapSignalForImportMetaEnvEnv(options) { | ||
return options.example.map((key) => { | ||
return { | ||
regexp: new RegExp( | ||
`\\b_wrapSignal\\(import\\.meta\\.env, "(${key})"\\)`, | ||
"g" | ||
), | ||
substitution: options.transformMode === "compile-time" ? JSON.stringify(options.env[key]) : `${accessor}.${key}` | ||
}; | ||
}); | ||
} | ||
// ../../node_modules/.pnpm/magic-string@0.26.7/node_modules/magic-string/dist/magic-string.es.mjs | ||
var import_sourcemap_codec = __toESM(require_sourcemap_codec_umd(), 1); | ||
var BitSet = class { | ||
constructor(arg) { | ||
this.bits = arg instanceof BitSet ? arg.bits.slice() : []; | ||
} | ||
add(n2) { | ||
this.bits[n2 >> 5] |= 1 << (n2 & 31); | ||
} | ||
has(n2) { | ||
return !!(this.bits[n2 >> 5] & 1 << (n2 & 31)); | ||
} | ||
}; | ||
var Chunk = class { | ||
constructor(start, end, content) { | ||
this.start = start; | ||
this.end = end; | ||
this.original = content; | ||
this.intro = ""; | ||
this.outro = ""; | ||
this.content = content; | ||
this.storeName = false; | ||
this.edited = false; | ||
{ | ||
this.previous = null; | ||
this.next = null; | ||
} | ||
} | ||
appendLeft(content) { | ||
this.outro += content; | ||
} | ||
appendRight(content) { | ||
this.intro = this.intro + content; | ||
} | ||
clone() { | ||
const chunk = new Chunk(this.start, this.end, this.original); | ||
chunk.intro = this.intro; | ||
chunk.outro = this.outro; | ||
chunk.content = this.content; | ||
chunk.storeName = this.storeName; | ||
chunk.edited = this.edited; | ||
return chunk; | ||
} | ||
contains(index) { | ||
return this.start < index && index < this.end; | ||
} | ||
eachNext(fn) { | ||
let chunk = this; | ||
while (chunk) { | ||
fn(chunk); | ||
chunk = chunk.next; | ||
} | ||
} | ||
eachPrevious(fn) { | ||
let chunk = this; | ||
while (chunk) { | ||
fn(chunk); | ||
chunk = chunk.previous; | ||
} | ||
} | ||
edit(content, storeName, contentOnly) { | ||
this.content = content; | ||
if (!contentOnly) { | ||
this.intro = ""; | ||
this.outro = ""; | ||
} | ||
this.storeName = storeName; | ||
this.edited = true; | ||
return this; | ||
} | ||
prependLeft(content) { | ||
this.outro = content + this.outro; | ||
} | ||
prependRight(content) { | ||
this.intro = content + this.intro; | ||
} | ||
split(index) { | ||
const sliceIndex = index - this.start; | ||
const originalBefore = this.original.slice(0, sliceIndex); | ||
const originalAfter = this.original.slice(sliceIndex); | ||
this.original = originalBefore; | ||
const newChunk = new Chunk(index, this.end, originalAfter); | ||
newChunk.outro = this.outro; | ||
this.outro = ""; | ||
this.end = index; | ||
if (this.edited) { | ||
newChunk.edit("", false); | ||
this.content = ""; | ||
} else { | ||
this.content = originalBefore; | ||
} | ||
newChunk.next = this.next; | ||
if (newChunk.next) | ||
newChunk.next.previous = newChunk; | ||
newChunk.previous = this; | ||
this.next = newChunk; | ||
return newChunk; | ||
} | ||
toString() { | ||
return this.intro + this.content + this.outro; | ||
} | ||
trimEnd(rx) { | ||
this.outro = this.outro.replace(rx, ""); | ||
if (this.outro.length) | ||
return true; | ||
const trimmed = this.content.replace(rx, ""); | ||
if (trimmed.length) { | ||
if (trimmed !== this.content) { | ||
this.split(this.start + trimmed.length).edit("", void 0, true); | ||
} | ||
return true; | ||
} else { | ||
this.edit("", void 0, true); | ||
this.intro = this.intro.replace(rx, ""); | ||
if (this.intro.length) | ||
return true; | ||
} | ||
} | ||
trimStart(rx) { | ||
this.intro = this.intro.replace(rx, ""); | ||
if (this.intro.length) | ||
return true; | ||
const trimmed = this.content.replace(rx, ""); | ||
if (trimmed.length) { | ||
if (trimmed !== this.content) { | ||
this.split(this.end - trimmed.length); | ||
this.edit("", void 0, true); | ||
} | ||
return true; | ||
} else { | ||
this.edit("", void 0, true); | ||
this.outro = this.outro.replace(rx, ""); | ||
if (this.outro.length) | ||
return true; | ||
} | ||
} | ||
}; | ||
function getBtoa() { | ||
if (typeof window !== "undefined" && typeof window.btoa === "function") { | ||
return (str) => window.btoa(unescape(encodeURIComponent(str))); | ||
} else if (typeof Buffer === "function") { | ||
return (str) => Buffer.from(str, "utf-8").toString("base64"); | ||
} else { | ||
return () => { | ||
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported."); | ||
}; | ||
} | ||
} | ||
var btoa = /* @__PURE__ */ getBtoa(); | ||
var SourceMap = class { | ||
constructor(properties) { | ||
this.version = 3; | ||
this.file = properties.file; | ||
this.sources = properties.sources; | ||
this.sourcesContent = properties.sourcesContent; | ||
this.names = properties.names; | ||
this.mappings = (0, import_sourcemap_codec.encode)(properties.mappings); | ||
} | ||
toString() { | ||
return JSON.stringify(this); | ||
} | ||
toUrl() { | ||
return "data:application/json;charset=utf-8;base64," + btoa(this.toString()); | ||
} | ||
}; | ||
function guessIndent(code) { | ||
const lines = code.split("\n"); | ||
const tabbed = lines.filter((line) => /^\t+/.test(line)); | ||
const spaced = lines.filter((line) => /^ {2,}/.test(line)); | ||
if (tabbed.length === 0 && spaced.length === 0) { | ||
return null; | ||
} | ||
if (tabbed.length >= spaced.length) { | ||
return " "; | ||
} | ||
const min = spaced.reduce((previous, current) => { | ||
const numSpaces = /^ +/.exec(current)[0].length; | ||
return Math.min(numSpaces, previous); | ||
}, Infinity); | ||
return new Array(min + 1).join(" "); | ||
} | ||
function getRelativePath(from, to) { | ||
const fromParts = from.split(/[/\\]/); | ||
const toParts = to.split(/[/\\]/); | ||
fromParts.pop(); | ||
while (fromParts[0] === toParts[0]) { | ||
fromParts.shift(); | ||
toParts.shift(); | ||
} | ||
if (fromParts.length) { | ||
let i = fromParts.length; | ||
while (i--) | ||
fromParts[i] = ".."; | ||
} | ||
return fromParts.concat(toParts).join("/"); | ||
} | ||
var toString = Object.prototype.toString; | ||
function isObject(thing) { | ||
return toString.call(thing) === "[object Object]"; | ||
} | ||
function getLocator(source) { | ||
const originalLines = source.split("\n"); | ||
const lineOffsets = []; | ||
for (let i = 0, pos = 0; i < originalLines.length; i++) { | ||
lineOffsets.push(pos); | ||
pos += originalLines[i].length + 1; | ||
} | ||
return function locate(index) { | ||
let i = 0; | ||
let j = lineOffsets.length; | ||
while (i < j) { | ||
const m = i + j >> 1; | ||
if (index < lineOffsets[m]) { | ||
j = m; | ||
} else { | ||
i = m + 1; | ||
} | ||
} | ||
const line = i - 1; | ||
const column = index - lineOffsets[line]; | ||
return { line, column }; | ||
}; | ||
} | ||
var Mappings = class { | ||
constructor(hires) { | ||
this.hires = hires; | ||
this.generatedCodeLine = 0; | ||
this.generatedCodeColumn = 0; | ||
this.raw = []; | ||
this.rawSegments = this.raw[this.generatedCodeLine] = []; | ||
this.pending = null; | ||
} | ||
addEdit(sourceIndex, content, loc, nameIndex) { | ||
if (content.length) { | ||
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; | ||
if (nameIndex >= 0) { | ||
segment.push(nameIndex); | ||
} | ||
this.rawSegments.push(segment); | ||
} else if (this.pending) { | ||
this.rawSegments.push(this.pending); | ||
} | ||
this.advance(content); | ||
this.pending = null; | ||
} | ||
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { | ||
let originalCharIndex = chunk.start; | ||
let first = true; | ||
while (originalCharIndex < chunk.end) { | ||
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { | ||
this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); | ||
} | ||
if (original[originalCharIndex] === "\n") { | ||
loc.line += 1; | ||
loc.column = 0; | ||
this.generatedCodeLine += 1; | ||
this.raw[this.generatedCodeLine] = this.rawSegments = []; | ||
this.generatedCodeColumn = 0; | ||
first = true; | ||
} else { | ||
loc.column += 1; | ||
this.generatedCodeColumn += 1; | ||
first = false; | ||
} | ||
originalCharIndex += 1; | ||
} | ||
this.pending = null; | ||
} | ||
advance(str) { | ||
if (!str) | ||
return; | ||
const lines = str.split("\n"); | ||
if (lines.length > 1) { | ||
for (let i = 0; i < lines.length - 1; i++) { | ||
this.generatedCodeLine++; | ||
this.raw[this.generatedCodeLine] = this.rawSegments = []; | ||
} | ||
this.generatedCodeColumn = 0; | ||
} | ||
this.generatedCodeColumn += lines[lines.length - 1].length; | ||
} | ||
}; | ||
var n = "\n"; | ||
var warned = { | ||
insertLeft: false, | ||
insertRight: false, | ||
storeName: false | ||
}; | ||
var MagicString = class { | ||
constructor(string, options = {}) { | ||
const chunk = new Chunk(0, string.length, string); | ||
Object.defineProperties(this, { | ||
original: { writable: true, value: string }, | ||
outro: { writable: true, value: "" }, | ||
intro: { writable: true, value: "" }, | ||
firstChunk: { writable: true, value: chunk }, | ||
lastChunk: { writable: true, value: chunk }, | ||
lastSearchedChunk: { writable: true, value: chunk }, | ||
byStart: { writable: true, value: {} }, | ||
byEnd: { writable: true, value: {} }, | ||
filename: { writable: true, value: options.filename }, | ||
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, | ||
sourcemapLocations: { writable: true, value: new BitSet() }, | ||
storedNames: { writable: true, value: {} }, | ||
indentStr: { writable: true, value: void 0 } | ||
}); | ||
this.byStart[0] = chunk; | ||
this.byEnd[string.length] = chunk; | ||
} | ||
addSourcemapLocation(char) { | ||
this.sourcemapLocations.add(char); | ||
} | ||
append(content) { | ||
if (typeof content !== "string") | ||
throw new TypeError("outro content must be a string"); | ||
this.outro += content; | ||
return this; | ||
} | ||
appendLeft(index, content) { | ||
if (typeof content !== "string") | ||
throw new TypeError("inserted content must be a string"); | ||
this._split(index); | ||
const chunk = this.byEnd[index]; | ||
if (chunk) { | ||
chunk.appendLeft(content); | ||
} else { | ||
this.intro += content; | ||
} | ||
return this; | ||
} | ||
appendRight(index, content) { | ||
if (typeof content !== "string") | ||
throw new TypeError("inserted content must be a string"); | ||
this._split(index); | ||
const chunk = this.byStart[index]; | ||
if (chunk) { | ||
chunk.appendRight(content); | ||
} else { | ||
this.outro += content; | ||
} | ||
return this; | ||
} | ||
clone() { | ||
const cloned = new MagicString(this.original, { filename: this.filename }); | ||
let originalChunk = this.firstChunk; | ||
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone(); | ||
while (originalChunk) { | ||
cloned.byStart[clonedChunk.start] = clonedChunk; | ||
cloned.byEnd[clonedChunk.end] = clonedChunk; | ||
const nextOriginalChunk = originalChunk.next; | ||
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); | ||
if (nextClonedChunk) { | ||
clonedChunk.next = nextClonedChunk; | ||
nextClonedChunk.previous = clonedChunk; | ||
clonedChunk = nextClonedChunk; | ||
} | ||
originalChunk = nextOriginalChunk; | ||
} | ||
cloned.lastChunk = clonedChunk; | ||
if (this.indentExclusionRanges) { | ||
cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); | ||
} | ||
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); | ||
cloned.intro = this.intro; | ||
cloned.outro = this.outro; | ||
return cloned; | ||
} | ||
generateDecodedMap(options) { | ||
options = options || {}; | ||
const sourceIndex = 0; | ||
const names = Object.keys(this.storedNames); | ||
const mappings = new Mappings(options.hires); | ||
const locate = getLocator(this.original); | ||
if (this.intro) { | ||
mappings.advance(this.intro); | ||
} | ||
this.firstChunk.eachNext((chunk) => { | ||
const loc = locate(chunk.start); | ||
if (chunk.intro.length) | ||
mappings.advance(chunk.intro); | ||
if (chunk.edited) { | ||
mappings.addEdit( | ||
sourceIndex, | ||
chunk.content, | ||
loc, | ||
chunk.storeName ? names.indexOf(chunk.original) : -1 | ||
); | ||
} else { | ||
mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); | ||
} | ||
if (chunk.outro.length) | ||
mappings.advance(chunk.outro); | ||
}); | ||
return { | ||
file: options.file ? options.file.split(/[/\\]/).pop() : null, | ||
sources: [options.source ? getRelativePath(options.file || "", options.source) : null], | ||
sourcesContent: options.includeContent ? [this.original] : [null], | ||
names, | ||
mappings: mappings.raw | ||
}; | ||
} | ||
generateMap(options) { | ||
return new SourceMap(this.generateDecodedMap(options)); | ||
} | ||
_ensureindentStr() { | ||
if (this.indentStr === void 0) { | ||
this.indentStr = guessIndent(this.original); | ||
} | ||
} | ||
_getRawIndentString() { | ||
this._ensureindentStr(); | ||
return this.indentStr; | ||
} | ||
getIndentString() { | ||
this._ensureindentStr(); | ||
return this.indentStr === null ? " " : this.indentStr; | ||
} | ||
indent(indentStr, options) { | ||
const pattern = /^[^\r\n]/gm; | ||
if (isObject(indentStr)) { | ||
options = indentStr; | ||
indentStr = void 0; | ||
} | ||
if (indentStr === void 0) { | ||
this._ensureindentStr(); | ||
indentStr = this.indentStr || " "; | ||
} | ||
if (indentStr === "") | ||
return this; | ||
options = options || {}; | ||
const isExcluded = {}; | ||
if (options.exclude) { | ||
const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude; | ||
exclusions.forEach((exclusion) => { | ||
for (let i = exclusion[0]; i < exclusion[1]; i += 1) { | ||
isExcluded[i] = true; | ||
} | ||
}); | ||
} | ||
let shouldIndentNextCharacter = options.indentStart !== false; | ||
const replacer = (match) => { | ||
if (shouldIndentNextCharacter) | ||
return `${indentStr}${match}`; | ||
shouldIndentNextCharacter = true; | ||
return match; | ||
}; | ||
this.intro = this.intro.replace(pattern, replacer); | ||
let charIndex = 0; | ||
let chunk = this.firstChunk; | ||
while (chunk) { | ||
const end = chunk.end; | ||
if (chunk.edited) { | ||
if (!isExcluded[charIndex]) { | ||
chunk.content = chunk.content.replace(pattern, replacer); | ||
if (chunk.content.length) { | ||
shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n"; | ||
} | ||
} | ||
} else { | ||
charIndex = chunk.start; | ||
while (charIndex < end) { | ||
if (!isExcluded[charIndex]) { | ||
const char = this.original[charIndex]; | ||
if (char === "\n") { | ||
shouldIndentNextCharacter = true; | ||
} else if (char !== "\r" && shouldIndentNextCharacter) { | ||
shouldIndentNextCharacter = false; | ||
if (charIndex === chunk.start) { | ||
chunk.prependRight(indentStr); | ||
} else { | ||
this._splitChunk(chunk, charIndex); | ||
chunk = chunk.next; | ||
chunk.prependRight(indentStr); | ||
} | ||
} | ||
} | ||
charIndex += 1; | ||
} | ||
} | ||
charIndex = chunk.end; | ||
chunk = chunk.next; | ||
} | ||
this.outro = this.outro.replace(pattern, replacer); | ||
return this; | ||
} | ||
insert() { | ||
throw new Error( | ||
"magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)" | ||
); | ||
} | ||
insertLeft(index, content) { | ||
if (!warned.insertLeft) { | ||
console.warn( | ||
"magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead" | ||
); | ||
warned.insertLeft = true; | ||
} | ||
return this.appendLeft(index, content); | ||
} | ||
insertRight(index, content) { | ||
if (!warned.insertRight) { | ||
console.warn( | ||
"magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead" | ||
); | ||
warned.insertRight = true; | ||
} | ||
return this.prependRight(index, content); | ||
} | ||
move(start, end, index) { | ||
if (index >= start && index <= end) | ||
throw new Error("Cannot move a selection inside itself"); | ||
this._split(start); | ||
this._split(end); | ||
this._split(index); | ||
const first = this.byStart[start]; | ||
const last = this.byEnd[end]; | ||
const oldLeft = first.previous; | ||
const oldRight = last.next; | ||
const newRight = this.byStart[index]; | ||
if (!newRight && last === this.lastChunk) | ||
return this; | ||
const newLeft = newRight ? newRight.previous : this.lastChunk; | ||
if (oldLeft) | ||
oldLeft.next = oldRight; | ||
if (oldRight) | ||
oldRight.previous = oldLeft; | ||
if (newLeft) | ||
newLeft.next = first; | ||
if (newRight) | ||
newRight.previous = last; | ||
if (!first.previous) | ||
this.firstChunk = last.next; | ||
if (!last.next) { | ||
this.lastChunk = first.previous; | ||
this.lastChunk.next = null; | ||
} | ||
first.previous = newLeft; | ||
last.next = newRight || null; | ||
if (!newLeft) | ||
this.firstChunk = first; | ||
if (!newRight) | ||
this.lastChunk = last; | ||
return this; | ||
} | ||
overwrite(start, end, content, options) { | ||
options = options || {}; | ||
return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); | ||
} | ||
update(start, end, content, options) { | ||
if (typeof content !== "string") | ||
throw new TypeError("replacement content must be a string"); | ||
while (start < 0) | ||
start += this.original.length; | ||
while (end < 0) | ||
end += this.original.length; | ||
if (end > this.original.length) | ||
throw new Error("end is out of bounds"); | ||
if (start === end) | ||
throw new Error( | ||
"Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead" | ||
); | ||
this._split(start); | ||
this._split(end); | ||
if (options === true) { | ||
if (!warned.storeName) { | ||
console.warn( | ||
"The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string" | ||
); | ||
warned.storeName = true; | ||
} | ||
options = { storeName: true }; | ||
} | ||
const storeName = options !== void 0 ? options.storeName : false; | ||
const overwrite = options !== void 0 ? options.overwrite : false; | ||
if (storeName) { | ||
const original = this.original.slice(start, end); | ||
Object.defineProperty(this.storedNames, original, { | ||
writable: true, | ||
value: true, | ||
enumerable: true | ||
}); | ||
} | ||
const first = this.byStart[start]; | ||
const last = this.byEnd[end]; | ||
if (first) { | ||
let chunk = first; | ||
while (chunk !== last) { | ||
if (chunk.next !== this.byStart[chunk.end]) { | ||
throw new Error("Cannot overwrite across a split point"); | ||
} | ||
chunk = chunk.next; | ||
chunk.edit("", false); | ||
} | ||
first.edit(content, storeName, !overwrite); | ||
} else { | ||
const newChunk = new Chunk(start, end, "").edit(content, storeName); | ||
last.next = newChunk; | ||
newChunk.previous = last; | ||
} | ||
return this; | ||
} | ||
prepend(content) { | ||
if (typeof content !== "string") | ||
throw new TypeError("outro content must be a string"); | ||
this.intro = content + this.intro; | ||
return this; | ||
} | ||
prependLeft(index, content) { | ||
if (typeof content !== "string") | ||
throw new TypeError("inserted content must be a string"); | ||
this._split(index); | ||
const chunk = this.byEnd[index]; | ||
if (chunk) { | ||
chunk.prependLeft(content); | ||
} else { | ||
this.intro = content + this.intro; | ||
} | ||
return this; | ||
} | ||
prependRight(index, content) { | ||
if (typeof content !== "string") | ||
throw new TypeError("inserted content must be a string"); | ||
this._split(index); | ||
const chunk = this.byStart[index]; | ||
if (chunk) { | ||
chunk.prependRight(content); | ||
} else { | ||
this.outro = content + this.outro; | ||
} | ||
return this; | ||
} | ||
remove(start, end) { | ||
while (start < 0) | ||
start += this.original.length; | ||
while (end < 0) | ||
end += this.original.length; | ||
if (start === end) | ||
return this; | ||
if (start < 0 || end > this.original.length) | ||
throw new Error("Character is out of bounds"); | ||
if (start > end) | ||
throw new Error("end must be greater than start"); | ||
this._split(start); | ||
this._split(end); | ||
let chunk = this.byStart[start]; | ||
while (chunk) { | ||
chunk.intro = ""; | ||
chunk.outro = ""; | ||
chunk.edit(""); | ||
chunk = end > chunk.end ? this.byStart[chunk.end] : null; | ||
} | ||
return this; | ||
} | ||
lastChar() { | ||
if (this.outro.length) | ||
return this.outro[this.outro.length - 1]; | ||
let chunk = this.lastChunk; | ||
do { | ||
if (chunk.outro.length) | ||
return chunk.outro[chunk.outro.length - 1]; | ||
if (chunk.content.length) | ||
return chunk.content[chunk.content.length - 1]; | ||
if (chunk.intro.length) | ||
return chunk.intro[chunk.intro.length - 1]; | ||
} while (chunk = chunk.previous); | ||
if (this.intro.length) | ||
return this.intro[this.intro.length - 1]; | ||
return ""; | ||
} | ||
lastLine() { | ||
let lineIndex = this.outro.lastIndexOf(n); | ||
if (lineIndex !== -1) | ||
return this.outro.substr(lineIndex + 1); | ||
let lineStr = this.outro; | ||
let chunk = this.lastChunk; | ||
do { | ||
if (chunk.outro.length > 0) { | ||
lineIndex = chunk.outro.lastIndexOf(n); | ||
if (lineIndex !== -1) | ||
return chunk.outro.substr(lineIndex + 1) + lineStr; | ||
lineStr = chunk.outro + lineStr; | ||
} | ||
if (chunk.content.length > 0) { | ||
lineIndex = chunk.content.lastIndexOf(n); | ||
if (lineIndex !== -1) | ||
return chunk.content.substr(lineIndex + 1) + lineStr; | ||
lineStr = chunk.content + lineStr; | ||
} | ||
if (chunk.intro.length > 0) { | ||
lineIndex = chunk.intro.lastIndexOf(n); | ||
if (lineIndex !== -1) | ||
return chunk.intro.substr(lineIndex + 1) + lineStr; | ||
lineStr = chunk.intro + lineStr; | ||
} | ||
} while (chunk = chunk.previous); | ||
lineIndex = this.intro.lastIndexOf(n); | ||
if (lineIndex !== -1) | ||
return this.intro.substr(lineIndex + 1) + lineStr; | ||
return this.intro + lineStr; | ||
} | ||
slice(start = 0, end = this.original.length) { | ||
while (start < 0) | ||
start += this.original.length; | ||
while (end < 0) | ||
end += this.original.length; | ||
let result = ""; | ||
let chunk = this.firstChunk; | ||
while (chunk && (chunk.start > start || chunk.end <= start)) { | ||
if (chunk.start < end && chunk.end >= end) { | ||
return result; | ||
} | ||
chunk = chunk.next; | ||
} | ||
if (chunk && chunk.edited && chunk.start !== start) | ||
throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); | ||
const startChunk = chunk; | ||
while (chunk) { | ||
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { | ||
result += chunk.intro; | ||
} | ||
const containsEnd = chunk.start < end && chunk.end >= end; | ||
if (containsEnd && chunk.edited && chunk.end !== end) | ||
throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); | ||
const sliceStart = startChunk === chunk ? start - chunk.start : 0; | ||
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; | ||
result += chunk.content.slice(sliceStart, sliceEnd); | ||
if (chunk.outro && (!containsEnd || chunk.end === end)) { | ||
result += chunk.outro; | ||
} | ||
if (containsEnd) { | ||
break; | ||
} | ||
chunk = chunk.next; | ||
} | ||
return result; | ||
} | ||
snip(start, end) { | ||
const clone = this.clone(); | ||
clone.remove(0, start); | ||
clone.remove(end, clone.original.length); | ||
return clone; | ||
} | ||
_split(index) { | ||
if (this.byStart[index] || this.byEnd[index]) | ||
return; | ||
let chunk = this.lastSearchedChunk; | ||
const searchForward = index > chunk.end; | ||
while (chunk) { | ||
if (chunk.contains(index)) | ||
return this._splitChunk(chunk, index); | ||
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; | ||
} | ||
} | ||
_splitChunk(chunk, index) { | ||
if (chunk.edited && chunk.content.length) { | ||
const loc = getLocator(this.original)(index); | ||
throw new Error( | ||
`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")` | ||
); | ||
} | ||
const newChunk = chunk.split(index); | ||
this.byEnd[index] = chunk; | ||
this.byStart[index] = newChunk; | ||
this.byEnd[newChunk.end] = newChunk; | ||
if (chunk === this.lastChunk) | ||
this.lastChunk = newChunk; | ||
this.lastSearchedChunk = chunk; | ||
return true; | ||
} | ||
toString() { | ||
let str = this.intro; | ||
let chunk = this.firstChunk; | ||
while (chunk) { | ||
str += chunk.toString(); | ||
chunk = chunk.next; | ||
} | ||
return str + this.outro; | ||
} | ||
isEmpty() { | ||
let chunk = this.firstChunk; | ||
do { | ||
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) | ||
return false; | ||
} while (chunk = chunk.next); | ||
return true; | ||
} | ||
length() { | ||
let chunk = this.firstChunk; | ||
let length = 0; | ||
do { | ||
length += chunk.intro.length + chunk.content.length + chunk.outro.length; | ||
} while (chunk = chunk.next); | ||
return length; | ||
} | ||
trimLines() { | ||
return this.trim("[\\r\\n]"); | ||
} | ||
trim(charType) { | ||
return this.trimStart(charType).trimEnd(charType); | ||
} | ||
trimEndAborted(charType) { | ||
const rx = new RegExp((charType || "\\s") + "+$"); | ||
this.outro = this.outro.replace(rx, ""); | ||
if (this.outro.length) | ||
return true; | ||
let chunk = this.lastChunk; | ||
do { | ||
const end = chunk.end; | ||
const aborted = chunk.trimEnd(rx); | ||
if (chunk.end !== end) { | ||
if (this.lastChunk === chunk) { | ||
this.lastChunk = chunk.next; | ||
} | ||
this.byEnd[chunk.end] = chunk; | ||
this.byStart[chunk.next.start] = chunk.next; | ||
this.byEnd[chunk.next.end] = chunk.next; | ||
} | ||
if (aborted) | ||
return true; | ||
chunk = chunk.previous; | ||
} while (chunk); | ||
return false; | ||
} | ||
trimEnd(charType) { | ||
this.trimEndAborted(charType); | ||
return this; | ||
} | ||
trimStartAborted(charType) { | ||
const rx = new RegExp("^" + (charType || "\\s") + "+"); | ||
this.intro = this.intro.replace(rx, ""); | ||
if (this.intro.length) | ||
return true; | ||
let chunk = this.firstChunk; | ||
do { | ||
const end = chunk.end; | ||
const aborted = chunk.trimStart(rx); | ||
if (chunk.end !== end) { | ||
if (chunk === this.lastChunk) | ||
this.lastChunk = chunk.next; | ||
this.byEnd[chunk.end] = chunk; | ||
this.byStart[chunk.next.start] = chunk.next; | ||
this.byEnd[chunk.next.end] = chunk.next; | ||
} | ||
if (aborted) | ||
return true; | ||
chunk = chunk.next; | ||
} while (chunk); | ||
return false; | ||
} | ||
trimStart(charType) { | ||
this.trimStartAborted(charType); | ||
return this; | ||
} | ||
hasChanged() { | ||
return this.original !== this.toString(); | ||
} | ||
_replaceRegexp(searchValue, replacement) { | ||
function getReplacement(match, str) { | ||
if (typeof replacement === "string") { | ||
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { | ||
if (i === "$") | ||
return "$"; | ||
if (i === "&") | ||
return match[0]; | ||
const num = +i; | ||
if (num < match.length) | ||
return match[+i]; | ||
return `$${i}`; | ||
}); | ||
} else { | ||
return replacement(...match, match.index, str, match.groups); | ||
} | ||
} | ||
function matchAll(re, str) { | ||
let match; | ||
const matches = []; | ||
while (match = re.exec(str)) { | ||
matches.push(match); | ||
} | ||
return matches; | ||
} | ||
if (searchValue.global) { | ||
const matches = matchAll(searchValue, this.original); | ||
matches.forEach((match) => { | ||
if (match.index != null) | ||
this.overwrite( | ||
match.index, | ||
match.index + match[0].length, | ||
getReplacement(match, this.original) | ||
); | ||
}); | ||
} else { | ||
const match = this.original.match(searchValue); | ||
if (match && match.index != null) | ||
this.overwrite( | ||
match.index, | ||
match.index + match[0].length, | ||
getReplacement(match, this.original) | ||
); | ||
} | ||
return this; | ||
} | ||
_replaceString(string, replacement) { | ||
const { original } = this; | ||
const index = original.indexOf(string); | ||
if (index !== -1) { | ||
this.overwrite(index, index + string.length, replacement); | ||
} | ||
return this; | ||
} | ||
replace(searchValue, replacement) { | ||
if (typeof searchValue === "string") { | ||
return this._replaceString(searchValue, replacement); | ||
} | ||
return this._replaceRegexp(searchValue, replacement); | ||
} | ||
_replaceAllString(string, replacement) { | ||
const { original } = this; | ||
const stringLength = string.length; | ||
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) { | ||
this.overwrite(index, index + stringLength, replacement); | ||
} | ||
return this; | ||
} | ||
replaceAll(searchValue, replacement) { | ||
if (typeof searchValue === "string") { | ||
return this._replaceAllString(searchValue, replacement); | ||
} | ||
if (!searchValue.global) { | ||
throw new TypeError( | ||
"MagicString.prototype.replaceAll called with a non-global RegExp argument" | ||
); | ||
} | ||
return this._replaceRegexp(searchValue, replacement); | ||
} | ||
}; | ||
// src/replace.ts | ||
var replace = ({ | ||
s, | ||
replacement | ||
}) => { | ||
const debug = process.env.DEBUG_IMPORT_META_ENV; | ||
debug && console.debug("---------------"); | ||
debug && console.debug( | ||
"--- replace ---", | ||
replacement.regexp, | ||
replacement.substitution | ||
); | ||
debug && console.debug("--- before ---"); | ||
debug && console.debug(s.toString()); | ||
s.replace(replacement.regexp, replacement.substitution); | ||
debug && console.debug("--- after ---"); | ||
debug && console.debug(s.toString()); | ||
}; | ||
// src/transform-dev.ts | ||
@@ -262,34 +1357,47 @@ function transformDev({ | ||
env, | ||
example, | ||
viteConfig | ||
}) { | ||
const s = new MagicString(code); | ||
if (id.includes("node_modules") === false) { | ||
switch (meta.framework) { | ||
case "vite": | ||
if (viteConfig === void 0) | ||
throw Error("[@import-meta-env/unplugin] internal error"); | ||
code = code.replace( | ||
/import\.meta\.env/g, | ||
"(" + JSON.stringify({ | ||
...env, | ||
...viteConfig.env, | ||
LEGACY: viteConfig.plugins.find( | ||
(plugin) => plugin.name.startsWith("vite:legacy") | ||
) !== void 0 ? viteConfig.command === "serve" || viteConfig.build.ssr ? false : "__VITE_IS_LEGACY__" : void 0, | ||
SSR: !!(process.env.VITEST ? process.env.SSR ?? "1" : viteConfig.build.ssr) | ||
}) + ")" | ||
unwrapSignalForImportMetaEnvEnv({ | ||
example, | ||
transformMode: "compile-time", | ||
env | ||
}).forEach((replacement) => { | ||
replace({ s, replacement }); | ||
}); | ||
example.map((key) => { | ||
if (meta.framework === "vite" && builtInEnvKeys.includes(key)) { | ||
throw Error( | ||
`It seems you want to use a runtime environment variable prefixed by or equal to: \`${key.split(".").pop()}\`, but this conflicts with Vite's environment variables. You can fix this by using a different environment variable name or changing Vite's \`envPrefix\` configuration.` | ||
); | ||
code = preserveViteBuiltInEnv({ | ||
code, | ||
envPrefix: viteConfig.envPrefix | ||
}); | ||
break; | ||
default: | ||
code = code.replace( | ||
/import\.meta\.env/g, | ||
"(" + JSON.stringify(env) + ")" | ||
); | ||
break; | ||
} | ||
return { | ||
regexp: new RegExp(`\\bimport\\.meta\\.env\\.${key}\\b`, "g"), | ||
substitution: JSON.stringify(env[key]) | ||
}; | ||
}).forEach((replacement) => { | ||
replace({ s, replacement }); | ||
}); | ||
if (meta.framework === "vite") { | ||
if (viteConfig === void 0) | ||
throw Error("[@import-meta-env/unplugin] internal error"); | ||
preserveViteBuiltInEnv({ envPrefix: viteConfig.envPrefix }).forEach( | ||
(replacement) => { | ||
try { | ||
replace({ s, replacement }); | ||
} catch (error) { | ||
throw Error( | ||
`It seems you want to use a runtime environment variable prefixed by or equal to: \`${replacement.substitution.split(".").pop()}\`, but this conflicts with Vite's environment variables. You can fix this by using a different environment variable name or changing Vite's \`envPrefix\` configuration.` | ||
); | ||
} | ||
} | ||
); | ||
} | ||
} | ||
return code; | ||
return { | ||
code: s.toString(), | ||
map: s.generateMap() | ||
}; | ||
} | ||
@@ -302,58 +1410,70 @@ | ||
meta, | ||
example, | ||
viteConfig | ||
}) { | ||
const s = new MagicString(code); | ||
if (id.includes("node_modules") === false) { | ||
code = code.replace(/import\.meta\.env/g, placeholder); | ||
unwrapSignalForImportMetaEnvEnv({ | ||
example, | ||
transformMode: "runtime" | ||
}).forEach((replacement) => { | ||
replace({ s, replacement }); | ||
}); | ||
example.map((key) => { | ||
if (meta.framework === "vite" && builtInEnvKeys.includes(key)) { | ||
throw Error( | ||
`It seems you want to use a runtime environment variable prefixed by or equal to: \`${key.split(".").pop()}\`, but this conflicts with Vite's environment variables. You can fix this by using a different environment variable name or changing Vite's \`envPrefix\` configuration.` | ||
); | ||
} | ||
return { | ||
regexp: new RegExp(`\\bimport\\.meta\\.env\\.${key}\\b`, "g"), | ||
substitution: `${accessor}.${key}` | ||
}; | ||
}).forEach((replacement) => { | ||
replace({ s, replacement }); | ||
}); | ||
if (meta.framework === "vite") { | ||
if (viteConfig === void 0) | ||
throw Error("[@import-meta-env/unplugin]: internal error."); | ||
code = preserveViteBuiltInEnv({ code, envPrefix: viteConfig.envPrefix }); | ||
throw Error("[@import-meta-env/unplugin] internal error"); | ||
preserveViteBuiltInEnv({ envPrefix: viteConfig.envPrefix }).forEach( | ||
(replacement) => { | ||
try { | ||
replace({ s, replacement }); | ||
} catch (error) { | ||
throw Error( | ||
`It seems you want to use a runtime environment variable prefixed by or equal to: \`${replacement.substitution.split(".").pop()}\`, but this conflicts with Vite's environment variables. You can fix this by using a different environment variable name or changing Vite's \`envPrefix\` configuration.` | ||
); | ||
} | ||
} | ||
); | ||
} | ||
} | ||
return code; | ||
return { | ||
code: s.toString(), | ||
map: s.generateMap() | ||
}; | ||
} | ||
// src/parse-example.ts | ||
// ../shared/resolve-env-example.ts | ||
var import_fs2 = require("fs"); | ||
var import_path2 = require("path"); | ||
var import_dotenv2 = require("dotenv"); | ||
var parseExample = ({ | ||
var import_picocolors2 = __toESM(require_picocolors()); | ||
var resolveEnvExample = ({ | ||
envExampleFilePath | ||
}) => { | ||
const { parsed, error } = (0, import_dotenv2.config)({ path: envExampleFilePath }); | ||
if (error) { | ||
return {}; | ||
envExampleFilePath = (0, import_path2.resolve)( | ||
process.cwd(), | ||
envExampleFilePath ?? ".env.example" | ||
); | ||
if ((0, import_fs2.existsSync)(envExampleFilePath) === false) { | ||
console.error((0, import_picocolors2.red)("[import-meta-env] No .env.example file found.")); | ||
return Object.freeze([]); | ||
} | ||
return parsed; | ||
const content = (0, import_fs2.readFileSync)(envExampleFilePath, "utf8"); | ||
const parsed = (0, import_dotenv2.parse)(content); | ||
const keys = Object.keys(parsed); | ||
return Object.freeze(keys); | ||
}; | ||
// src/vite/warn-env-prefix.ts | ||
var DEFAULT_PREFIX_KEY = "VITE_"; | ||
var warnEnvPrefix = ({ | ||
envExampleFilePath, | ||
viteConfigEnvPrefix, | ||
warn | ||
}) => { | ||
const example = parseExample({ envExampleFilePath }); | ||
const prefixKeys = [ | ||
...new Set( | ||
typeof viteConfigEnvPrefix === "undefined" ? [DEFAULT_PREFIX_KEY] : typeof viteConfigEnvPrefix === "string" ? [viteConfigEnvPrefix] : viteConfigEnvPrefix | ||
) | ||
]; | ||
const messages = /* @__PURE__ */ new Set(); | ||
Object.keys(example).forEach((key) => { | ||
prefixKeys.forEach((prefixKey) => { | ||
if (key.startsWith(prefixKey)) { | ||
messages.add( | ||
`[import-meta-env]: During production, \`import.meta.env.${key}\` will be statically replaced.` | ||
); | ||
} | ||
}); | ||
}); | ||
if (messages.size) { | ||
messages.forEach((message) => warn(message)); | ||
warn( | ||
`If you want to replace env variables after production, you need to use a key other than \`[${prefixKeys.map((key) => JSON.stringify(key)).join(", ")}]\`.` | ||
); | ||
} | ||
}; | ||
// src/index.ts | ||
@@ -370,4 +1490,5 @@ var createPlugin = (0, import_unplugin.createUnplugin)((options, meta) => { | ||
} | ||
let shouldInlineEnv = options == null ? void 0 : options.shouldInlineEnv; | ||
let env = meta.framework === "esbuild" ? shouldInlineEnv ? resolveEnv({ | ||
const example = resolveEnvExample({ envExampleFilePath }); | ||
let transformMode = options == null ? void 0 : options.transformMode; | ||
let env = meta.framework === "esbuild" ? transformMode === "compile-time" ? resolveEnv({ | ||
envFilePath: envFilePath2, | ||
@@ -384,3 +1505,3 @@ envExampleFilePath | ||
debug && console.debug("apply::"); | ||
shouldInlineEnv = shouldInlineEnv ?? env2.mode !== "production"; | ||
transformMode = transformMode ?? (env2.mode !== "production" ? "compile-time" : "runtime"); | ||
return true; | ||
@@ -390,3 +1511,3 @@ }, | ||
debug && console.debug("configResolved::"); | ||
if (shouldInlineEnv) { | ||
if (transformMode === "compile-time") { | ||
env = resolveEnv({ | ||
@@ -404,3 +1525,6 @@ envFilePath: envFilePath2, | ||
debug && console.debug("=================="); | ||
html = html.replace(createPlaceholderRegExp(""), "import.meta.env"); | ||
html = html.replace(createAccessorRegExp(""), "import.meta.env"); | ||
if (transformMode === "compile-time") { | ||
html = html.replace(createScriptPlaceholderRegExp(), ""); | ||
} | ||
debug && console.debug("=== index.html after ==="); | ||
@@ -415,4 +1539,4 @@ debug && console.debug(html); | ||
debug && console.debug("rollup::buildStart::"); | ||
shouldInlineEnv = shouldInlineEnv ?? process.env.NODE_ENV !== "production"; | ||
if (shouldInlineEnv) { | ||
transformMode = transformMode ?? (process.env.NODE_ENV !== "production" ? "compile-time" : "runtime"); | ||
if (transformMode === "compile-time") { | ||
env = resolveEnv({ | ||
@@ -431,4 +1555,4 @@ envFilePath: envFilePath2, | ||
]; | ||
shouldInlineEnv = shouldInlineEnv ?? developmentModes.includes(compiler.options.mode); | ||
if (shouldInlineEnv) { | ||
transformMode = transformMode ?? (developmentModes.includes(compiler.options.mode) ? "compile-time" : "runtime"); | ||
if (transformMode === "compile-time") { | ||
env = resolveEnv({ | ||
@@ -452,28 +1576,32 @@ envFilePath: envFilePath2, | ||
transform(code, id) { | ||
if (meta.framework === "vite") | ||
warnEnvPrefix({ | ||
envExampleFilePath, | ||
viteConfigEnvPrefix: viteConfig == null ? void 0 : viteConfig.envPrefix, | ||
warn: this.warn.bind(this) | ||
let result; | ||
debug && console.debug("=================="); | ||
if (transformMode === "compile-time") { | ||
debug && console.debug("=== compile-time transform ===", id); | ||
debug && console.debug("=== before ==="); | ||
debug && console.debug(code); | ||
result = transformDev({ | ||
code, | ||
id, | ||
env, | ||
example, | ||
meta, | ||
viteConfig | ||
}); | ||
if (shouldInlineEnv) { | ||
debug && console.debug("transformDev::", id); | ||
debug && console.debug("=== code before ==="); | ||
debug && console.debug(code); | ||
debug && console.debug("=================="); | ||
code = transformDev({ code, id, env, meta, viteConfig }); | ||
debug && console.debug("=== code after ==="); | ||
debug && console.debug(code); | ||
debug && console.debug("=================="); | ||
debug && console.debug(result.code); | ||
} else { | ||
debug && console.debug("transformProd::", id); | ||
debug && console.debug("=== code before ==="); | ||
debug && console.debug("=== runtime transform ===", id); | ||
debug && console.debug("=== before ==="); | ||
debug && console.debug(code); | ||
debug && console.debug("=================="); | ||
code = transformProd({ code, id, meta, viteConfig }); | ||
debug && console.debug("=== code after ==="); | ||
debug && console.debug(code); | ||
debug && console.debug("=================="); | ||
result = transformProd({ code, id, example, meta, viteConfig }); | ||
debug && console.debug("=== after ==="); | ||
debug && console.debug(result.code); | ||
} | ||
return code; | ||
debug && console.debug("=================="); | ||
if (meta.framework === "webpack") { | ||
return result.code; | ||
} else { | ||
return result; | ||
} | ||
}, | ||
@@ -483,3 +1611,3 @@ buildEnd() { | ||
const execCommand = getPackageManagerExecCommand(); | ||
if (shouldInlineEnv) { | ||
if (transformMode === "compile-time") { | ||
} else { | ||
@@ -489,5 +1617,5 @@ console.info( | ||
"", | ||
`${import_picocolors2.default.cyan("import-meta-env v" + version)}`, | ||
`${import_picocolors2.default.green("\u2713")} environment files are generated.`, | ||
import_picocolors2.default.yellow( | ||
`${import_picocolors3.default.cyan("import-meta-env v" + version)}`, | ||
`${import_picocolors3.default.green("\u2713")} environment files are generated.`, | ||
import_picocolors3.default.yellow( | ||
`Remember to inject (\`${execCommand} import-meta-env\`) environment variables before serving your application.` | ||
@@ -494,0 +1622,0 @@ ), |
export declare const virtualFile = "import-meta-env"; | ||
export declare const placeholder = "Object.create(globalThis[\"import_meta_env\".slice()] || null)"; | ||
export declare const createPlaceholderRegExp: (suffix: string) => RegExp; | ||
export declare const scriptPlaceholder = "<script id=\"import-meta-env\"></script>"; | ||
export declare const createScriptPlaceholderRegExp: () => RegExp; | ||
export declare const accessor = "Object.create(globalThis.import_meta_env || null)"; | ||
export declare const createAccessorRegExp: (suffix: string, quote?: "single" | "double") => RegExp; | ||
export declare const envFilePath = ".env"; |
import { UnpluginContextMeta } from "unplugin"; | ||
import { Env } from "./types"; | ||
import { ViteResolvedConfig } from "./vite/types"; | ||
export declare function transformDev({ code, id, meta, env, viteConfig, }: { | ||
export declare function transformDev({ code, id, meta, env, example, viteConfig, }: { | ||
code: string; | ||
@@ -9,3 +9,7 @@ id: string; | ||
env: Env; | ||
example: readonly string[]; | ||
viteConfig?: ViteResolvedConfig; | ||
}): string; | ||
}): { | ||
code: string; | ||
map: import("magic-string").SourceMap; | ||
}; |
import { UnpluginContextMeta } from "unplugin"; | ||
import { ViteResolvedConfig } from "./vite/types"; | ||
export declare function transformProd({ code, id, meta, viteConfig, }: { | ||
export declare function transformProd({ code, id, meta, example, viteConfig, }: { | ||
code: string; | ||
id: string; | ||
meta: UnpluginContextMeta; | ||
example: readonly string[]; | ||
viteConfig?: ViteResolvedConfig; | ||
}): string; | ||
}): { | ||
code: string; | ||
map: import("magic-string").SourceMap; | ||
}; |
@@ -16,18 +16,15 @@ export declare type Env = Record<string, string>; | ||
/** | ||
* Explicitly set whether to inline current environment variables into the code, | ||
* instead of inject environment variables via `import-meta-env` later. | ||
* Compile-time: statically replace `import.meta.env.KEY` with `"value"` | ||
* Runtime: statically replace `import.meta.env` with a global accessor | ||
* | ||
* This is useful if you want to use the plugin in unknown dev server environments | ||
* | ||
* @default | ||
* `true` if following conditions are met, otherwise `false`: | ||
* | ||
* ```text | ||
* vite: if mode is not `"production"` | ||
* webpack: if mode is `"development"` or `"none"` | ||
* rollup: if `NODE_ENV` is not `"production"` | ||
* vite: if mode is not `"production"` then `"compile-time"`, otherwise `"runtime"` | ||
* webpack: if mode is `"development"` or `"none"` then `"compile-time"`, otherwise `"runtime"` | ||
* rollup: if `NODE_ENV` is not `"production"` then `"compile-time"`, otherwise `"runtime"` | ||
* esbuild: (needs to be set explicitly) | ||
* ``` | ||
*/ | ||
shouldInlineEnv?: boolean; | ||
transformMode?: "compile-time" | "runtime"; | ||
} |
@@ -1,4 +0,5 @@ | ||
export declare function preserveViteBuiltInEnv({ code, envPrefix, }: { | ||
code: string; | ||
import { Replacement } from "../replacement"; | ||
export declare const builtInEnvKeys: string[]; | ||
export declare function preserveViteBuiltInEnv({ envPrefix, }: { | ||
envPrefix: undefined | string | string[]; | ||
}): string; | ||
}): Replacement[]; |
{ | ||
"name": "@import-meta-env/unplugin", | ||
"version": "0.2.1", | ||
"description": "Load environment variables into import.meta.env object", | ||
"version": "0.3.0", | ||
"description": "Build once, deploy anywhere. Startup/runtime environment variable solution for JavaScript.", | ||
"license": "MIT", | ||
@@ -42,12 +42,12 @@ "author": "Ernest", | ||
"devDependencies": { | ||
"@types/node": "17.0.45", | ||
"@types/node": "18.11.9", | ||
"@types/object-hash": "2.2.1", | ||
"rollup": "2.79.1", | ||
"rollup": "3.2.5", | ||
"ts-node": "10.9.1", | ||
"typescript": "4.8.4", | ||
"vite": "3.1.7", | ||
"vite": "3.2.2", | ||
"webpack": "5.74.0" | ||
}, | ||
"peerDependencies": { | ||
"@import-meta-env/cli": "^0.2.1", | ||
"@import-meta-env/cli": "^0.3.0", | ||
"dotenv": "^11.0.0 || ^12.0.4 || ^13.0.1 || ^14.3.2 || ^15.0.1 || ^16.0.0" | ||
@@ -61,6 +61,7 @@ }, | ||
"dependencies": { | ||
"magic-string": "^0.26.7", | ||
"object-hash": "^3.0.0", | ||
"picocolors": "^1.0.0", | ||
"unplugin": "^0.9.6" | ||
"unplugin": "^0.10.0" | ||
} | ||
} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
60109
20
1708
6
1
+ Addedmagic-string@^0.26.7
+ Added@import-meta-env/cli@0.3.0(transitive)
+ Addedmagic-string@0.26.7(transitive)
+ Addedsourcemap-codec@1.4.8(transitive)
+ Addedunplugin@0.10.2(transitive)
- Removed@import-meta-env/cli@0.2.2(transitive)
- Removedunplugin@0.9.6(transitive)
Updatedunplugin@^0.10.0