-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdotenv.ts
More file actions
192 lines (171 loc) · 6.37 KB
/
Copy pathdotenv.ts
File metadata and controls
192 lines (171 loc) · 6.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/**
* dotenv.ts - Minimal .env loader (zero dependencies)
*
* Why not `dotenv` npm package? We want QMD to stay dependency-light, and
* the subset of dotenv syntax we need is ~30 lines. This loader supports:
*
* - KEY=value simple assignment
* - KEY="value with spaces" double-quoted (escape sequences: \n \t \")
* - KEY='raw value' single-quoted (no escape interpretation)
* - export KEY=value optional `export` prefix
* - # comment lines ignored
* - blank lines ignored
* - trailing # comments on unquoted values are ignored
*
* Lookup order:
* 1. $QMD_ENV_FILE (explicit override)
* 2. ./.env in the current working directory
* 3. ./.env in the repo root (walks up directory tree, capped at 5 levels)
*
* By default, existing process.env values are NOT overwritten — env vars
* exported in the shell take precedence over the .env file. Pass
* { override: true } to change this.
*
* The loader silently no-ops when no .env file is found, so it's safe to
* call unconditionally at CLI startup.
*
* Security: this module NEVER logs values or keys, and callers should not
* either. The .env file must be gitignored.
*/
import { existsSync, readFileSync, statSync } from "node:fs";
import { dirname, resolve as pathResolve } from "node:path";
export type LoadDotenvOptions = {
/** Override existing process.env values. Default: false. */
override?: boolean;
/** Explicit path to the .env file. Skips the search if set. */
path?: string;
/** Start directory for the upward walk. Default: process.cwd(). */
cwd?: string;
/** Max number of parent directories to walk. Default: 5. */
maxDepth?: number;
};
export type LoadDotenvResult = {
/** True if a file was found and parsed. */
loaded: boolean;
/** Absolute path of the file that was loaded, or null. */
path: string | null;
/** Number of keys applied to process.env (excludes skipped ones). */
applied: number;
/** Number of keys skipped because they were already set in process.env. */
skipped: number;
};
// =============================================================================
// Parser
// =============================================================================
/**
* Parse a single .env line into a [key, value] tuple, or null if the line
* is blank / a comment / malformed.
*/
function parseLine(raw: string): [string, string] | null {
// Strip BOM if present at line start.
const line = raw.replace(/^\uFEFF/, "");
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) return null;
// Optional leading `export `.
const body = trimmed.startsWith("export ") ? trimmed.slice(7).trimStart() : trimmed;
const eqIdx = body.indexOf("=");
if (eqIdx <= 0) return null; // no key, or empty key
const key = body.slice(0, eqIdx).trim();
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) return null; // invalid identifier
let value = body.slice(eqIdx + 1);
// Strip surrounding quotes if present and process escapes accordingly.
// Order matters: check quoted first, otherwise a trailing `#` comment is stripped.
const firstChar = value.trimStart()[0];
if (firstChar === '"' || firstChar === "'") {
value = value.trimStart();
const quote = firstChar;
// Find the matching closing quote (last occurrence to allow escapes inside).
const closing = value.lastIndexOf(quote);
if (closing > 0) {
const inner = value.slice(1, closing);
if (quote === '"') {
// Double-quoted: interpret basic escape sequences.
value = inner.replace(/\\(.)/g, (_, ch) => {
if (ch === "n") return "\n";
if (ch === "t") return "\t";
if (ch === "r") return "\r";
if (ch === '"') return '"';
if (ch === "\\") return "\\";
return ch;
});
} else {
// Single-quoted: raw.
value = inner;
}
}
} else {
// Unquoted: strip inline comments (`value # note`) and trailing whitespace.
const hashIdx = value.indexOf(" #");
if (hashIdx >= 0) value = value.slice(0, hashIdx);
value = value.trim();
}
return [key, value];
}
// =============================================================================
// Finder
// =============================================================================
/**
* Walk upward from `startDir` looking for `.env`, up to `maxDepth` levels.
* Returns the absolute path of the first match, or null if none.
*/
function findUpwards(startDir: string, maxDepth: number): string | null {
let dir = pathResolve(startDir);
for (let i = 0; i <= maxDepth; i++) {
const candidate = pathResolve(dir, ".env");
if (existsSync(candidate)) {
try {
// Make sure it's a regular file, not a directory named `.env`.
if (statSync(candidate).isFile()) return candidate;
} catch {
// fall through to parent
}
}
const parent = dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
// =============================================================================
// Loader
// =============================================================================
/**
* Load variables from a .env file into process.env. Silent on failure so
* callers can invoke this unconditionally at startup.
*/
export function loadDotenv(options: LoadDotenvOptions = {}): LoadDotenvResult {
const override = options.override ?? false;
// 1. Resolve the file to load.
let filePath: string | null = null;
const explicit = options.path ?? process.env.QMD_ENV_FILE;
if (explicit) {
const abs = pathResolve(explicit);
if (existsSync(abs)) filePath = abs;
} else {
filePath = findUpwards(options.cwd ?? process.cwd(), options.maxDepth ?? 5);
}
if (!filePath) {
return { loaded: false, path: null, applied: 0, skipped: 0 };
}
// 2. Read + parse.
let content: string;
try {
content = readFileSync(filePath, "utf-8");
} catch {
return { loaded: false, path: null, applied: 0, skipped: 0 };
}
let applied = 0;
let skipped = 0;
for (const rawLine of content.split(/\r?\n/)) {
const parsed = parseLine(rawLine);
if (!parsed) continue;
const [key, value] = parsed;
if (!override && process.env[key] !== undefined) {
skipped++;
continue;
}
process.env[key] = value;
applied++;
}
return { loaded: true, path: filePath, applied, skipped };
}