@env-lane/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +17 -0
- package/dist/index.cjs +942 -0
- package/dist/index.d.cts +221 -0
- package/dist/index.d.ts +221 -0
- package/dist/index.js +884 -0
- package/package.json +62 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
// src/check.ts
|
|
2
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
|
|
3
|
+
import path4 from "path";
|
|
4
|
+
import { parse as parse2 } from "dotenv";
|
|
5
|
+
import fg2 from "fast-glob";
|
|
6
|
+
|
|
7
|
+
// src/config.ts
|
|
8
|
+
import { existsSync, readFileSync } from "fs";
|
|
9
|
+
import path from "path";
|
|
10
|
+
import { loadConfig as c12LoadConfig } from "c12";
|
|
11
|
+
import { findUp } from "find-up";
|
|
12
|
+
import YAML from "yaml";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
var sortTargetSchema = z.object({
|
|
15
|
+
baseDir: z.string().min(1).optional(),
|
|
16
|
+
file: z.string().min(1).optional(),
|
|
17
|
+
template: z.string().min(1).optional(),
|
|
18
|
+
files: z.record(z.string(), z.string().min(1)).optional()
|
|
19
|
+
});
|
|
20
|
+
var schema = z.object({
|
|
21
|
+
selector: z.object({
|
|
22
|
+
envKey: z.string().min(1).optional(),
|
|
23
|
+
defaultBuild: z.string().min(1).optional(),
|
|
24
|
+
builds: z.array(z.string().min(1)).optional(),
|
|
25
|
+
forbidInDotenv: z.boolean().optional()
|
|
26
|
+
}).optional(),
|
|
27
|
+
workspace: z.object({
|
|
28
|
+
packageGlobs: z.array(z.string().min(1)).optional(),
|
|
29
|
+
aliases: z.record(z.string(), z.string().min(1)).optional(),
|
|
30
|
+
defaultTarget: z.string().min(1).optional(),
|
|
31
|
+
includeRoot: z.boolean().optional()
|
|
32
|
+
}).optional(),
|
|
33
|
+
dotenv: z.object({
|
|
34
|
+
order: z.array(z.string().min(1)).optional(),
|
|
35
|
+
localBuildName: z.string().min(1).optional(),
|
|
36
|
+
localOverrideFile: z.string().min(1).optional(),
|
|
37
|
+
requireOverride: z.boolean().optional(),
|
|
38
|
+
includeProcessEnv: z.boolean().optional()
|
|
39
|
+
}).optional(),
|
|
40
|
+
vault: z.object({
|
|
41
|
+
enabled: z.boolean().optional(),
|
|
42
|
+
disableUnsafeWarning: z.boolean().optional(),
|
|
43
|
+
configFile: z.string().min(1).optional()
|
|
44
|
+
}).optional(),
|
|
45
|
+
output: z.object({
|
|
46
|
+
format: z.enum(["text", "json", "dotenv"]).optional()
|
|
47
|
+
}).optional(),
|
|
48
|
+
sort: z.record(z.string(), sortTargetSchema).optional()
|
|
49
|
+
}).passthrough();
|
|
50
|
+
function defineConfig(config) {
|
|
51
|
+
return config;
|
|
52
|
+
}
|
|
53
|
+
async function findWorkspaceRoot(cwd = process.cwd()) {
|
|
54
|
+
const marker = await findUp(["pnpm-workspace.yaml", "package.json", ".git"], {
|
|
55
|
+
cwd,
|
|
56
|
+
type: "file"
|
|
57
|
+
});
|
|
58
|
+
if (!marker) return path.resolve(cwd);
|
|
59
|
+
if (path.basename(marker) === ".git") return path.dirname(marker);
|
|
60
|
+
if (path.basename(marker) === "package.json") {
|
|
61
|
+
const pnpm = await findUp("pnpm-workspace.yaml", { cwd: path.dirname(marker), type: "file" });
|
|
62
|
+
return pnpm ? path.dirname(pnpm) : path.dirname(marker);
|
|
63
|
+
}
|
|
64
|
+
return path.dirname(marker);
|
|
65
|
+
}
|
|
66
|
+
function readPnpmWorkspaceGlobs(rootDir) {
|
|
67
|
+
const workspaceFile = path.join(rootDir, "pnpm-workspace.yaml");
|
|
68
|
+
if (!existsSync(workspaceFile)) return [];
|
|
69
|
+
const doc = YAML.parse(readFileSync(workspaceFile, "utf8"));
|
|
70
|
+
return Array.isArray(doc?.packages) ? doc.packages.filter((item) => typeof item === "string") : [];
|
|
71
|
+
}
|
|
72
|
+
async function loadEnvLaneConfig(options = {}) {
|
|
73
|
+
const rootDir = await findWorkspaceRoot(options.cwd);
|
|
74
|
+
const configFileName = options.configFile ? path.relative(rootDir, path.resolve(rootDir, options.configFile)) : void 0;
|
|
75
|
+
const loaded = await c12LoadConfig({
|
|
76
|
+
name: "env-lane",
|
|
77
|
+
cwd: rootDir,
|
|
78
|
+
configFile: configFileName,
|
|
79
|
+
packageJson: false,
|
|
80
|
+
dotenv: false,
|
|
81
|
+
rcFile: false,
|
|
82
|
+
globalRc: false
|
|
83
|
+
});
|
|
84
|
+
const parsed = schema.parse(loaded.config ?? {});
|
|
85
|
+
const workspaceGlobs = parsed.workspace?.packageGlobs ?? readPnpmWorkspaceGlobs(rootDir) ?? [];
|
|
86
|
+
return {
|
|
87
|
+
rootDir,
|
|
88
|
+
selector: {
|
|
89
|
+
envKey: parsed.selector?.envKey ?? "ENV_BUILD",
|
|
90
|
+
defaultBuild: parsed.selector?.defaultBuild ?? "local",
|
|
91
|
+
builds: parsed.selector?.builds ?? [],
|
|
92
|
+
forbidInDotenv: parsed.selector?.forbidInDotenv ?? true
|
|
93
|
+
},
|
|
94
|
+
workspace: {
|
|
95
|
+
packageGlobs: workspaceGlobs.length ? workspaceGlobs : ["packages/*", "apps/*"],
|
|
96
|
+
aliases: parsed.workspace?.aliases ?? {},
|
|
97
|
+
defaultTarget: parsed.workspace?.defaultTarget ?? "",
|
|
98
|
+
includeRoot: parsed.workspace?.includeRoot ?? true
|
|
99
|
+
},
|
|
100
|
+
dotenv: {
|
|
101
|
+
order: parsed.dotenv?.order ?? [".env", ".env.{build}"],
|
|
102
|
+
localBuildName: parsed.dotenv?.localBuildName ?? "local",
|
|
103
|
+
localOverrideFile: parsed.dotenv?.localOverrideFile ?? ".env.local",
|
|
104
|
+
requireOverride: parsed.dotenv?.requireOverride ?? false,
|
|
105
|
+
includeProcessEnv: parsed.dotenv?.includeProcessEnv ?? true
|
|
106
|
+
},
|
|
107
|
+
vault: {
|
|
108
|
+
enabled: parsed.vault?.enabled ?? false,
|
|
109
|
+
disableUnsafeWarning: parsed.vault?.disableUnsafeWarning ?? false,
|
|
110
|
+
configFile: parsed.vault?.configFile ?? "env-lane.vault.json"
|
|
111
|
+
},
|
|
112
|
+
output: {
|
|
113
|
+
format: parsed.output?.format ?? "text"
|
|
114
|
+
},
|
|
115
|
+
sort: parsed.sort
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/dotenv.ts
|
|
120
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
|
|
121
|
+
import path3 from "path";
|
|
122
|
+
import { parse } from "dotenv";
|
|
123
|
+
|
|
124
|
+
// src/workspace.ts
|
|
125
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
126
|
+
import path2 from "path";
|
|
127
|
+
import fg from "fast-glob";
|
|
128
|
+
function readPackageName(dir) {
|
|
129
|
+
const file = path2.join(dir, "package.json");
|
|
130
|
+
if (!existsSync2(file)) return void 0;
|
|
131
|
+
try {
|
|
132
|
+
const json = JSON.parse(readFileSync2(file, "utf8"));
|
|
133
|
+
return typeof json.name === "string" ? json.name : void 0;
|
|
134
|
+
} catch {
|
|
135
|
+
return void 0;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function unique(values) {
|
|
139
|
+
return [...new Set(values)];
|
|
140
|
+
}
|
|
141
|
+
async function listWorkspacePackages(options = {}) {
|
|
142
|
+
const config = options.config ?? await loadEnvLaneConfig(options);
|
|
143
|
+
return listWorkspacePackagesForConfig(config);
|
|
144
|
+
}
|
|
145
|
+
async function listWorkspacePackagesForConfig(config) {
|
|
146
|
+
const entries = await fg(config.workspace.packageGlobs, {
|
|
147
|
+
cwd: config.rootDir,
|
|
148
|
+
onlyDirectories: true,
|
|
149
|
+
absolute: true,
|
|
150
|
+
ignore: ["**/node_modules/**", "**/dist/**"]
|
|
151
|
+
});
|
|
152
|
+
const packages = [];
|
|
153
|
+
if (config.workspace.includeRoot) {
|
|
154
|
+
const rootName = readPackageName(config.rootDir);
|
|
155
|
+
packages.push({
|
|
156
|
+
name: rootName,
|
|
157
|
+
dir: config.rootDir,
|
|
158
|
+
relativeDir: ".",
|
|
159
|
+
aliases: unique(["root", ".", rootName].filter(Boolean)),
|
|
160
|
+
isRoot: true
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
for (const dir of entries.sort()) {
|
|
164
|
+
const packageJson = path2.join(dir, "package.json");
|
|
165
|
+
if (!existsSync2(packageJson)) continue;
|
|
166
|
+
const name = readPackageName(dir);
|
|
167
|
+
const relativeDir = path2.relative(config.rootDir, dir).replaceAll(path2.sep, "/");
|
|
168
|
+
packages.push({
|
|
169
|
+
name,
|
|
170
|
+
dir,
|
|
171
|
+
relativeDir,
|
|
172
|
+
aliases: unique([name, path2.basename(dir), relativeDir].filter(Boolean)),
|
|
173
|
+
isRoot: false
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
for (const [alias, target] of Object.entries(config.workspace.aliases)) {
|
|
177
|
+
const matched = packages.find(
|
|
178
|
+
(pkg) => pkg.name === target || pkg.relativeDir === target || path2.basename(pkg.dir) === target
|
|
179
|
+
);
|
|
180
|
+
if (matched && !matched.aliases.includes(alias)) matched.aliases.push(alias);
|
|
181
|
+
}
|
|
182
|
+
const byDir = /* @__PURE__ */ new Map();
|
|
183
|
+
for (const pkg of packages) byDir.set(pkg.dir, pkg);
|
|
184
|
+
return [...byDir.values()];
|
|
185
|
+
}
|
|
186
|
+
function targetMatchesPackage(pkg, value) {
|
|
187
|
+
return pkg.aliases.includes(value) || pkg.name === value || pkg.relativeDir === value;
|
|
188
|
+
}
|
|
189
|
+
function formatAvailableTargets(packages) {
|
|
190
|
+
return unique(packages.flatMap((pkg) => pkg.aliases)).join(", ");
|
|
191
|
+
}
|
|
192
|
+
function resolveTargetPackageFromList(target, config, packages) {
|
|
193
|
+
const value = (target || config.workspace.defaultTarget || "").trim();
|
|
194
|
+
if (!value) {
|
|
195
|
+
const nonRoot = packages.filter((pkg) => !pkg.isRoot);
|
|
196
|
+
if (nonRoot.length === 0) return packages.find((pkg) => pkg.isRoot) ?? packages[0];
|
|
197
|
+
throw new Error(`Missing target. Available targets: ${formatAvailableTargets(packages)}`);
|
|
198
|
+
}
|
|
199
|
+
const matches = packages.filter((pkg) => targetMatchesPackage(pkg, value));
|
|
200
|
+
if (matches.length > 1) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`Ambiguous target '${value}'. Matches: ${matches.map((pkg) => pkg.name ?? pkg.relativeDir).join(", ")}. Use a package name, relative directory, or configure a unique alias.`
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
const matched = matches[0];
|
|
206
|
+
if (!matched) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
`Unknown target '${value}'. Available targets: ${formatAvailableTargets(packages)}`
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
return matched;
|
|
212
|
+
}
|
|
213
|
+
async function resolveTargetPackage(target, options = {}) {
|
|
214
|
+
const config = options.config ?? await loadEnvLaneConfig(options);
|
|
215
|
+
const packages = options.packages ?? await listWorkspacePackagesForConfig(config);
|
|
216
|
+
return resolveTargetPackageFromList(target, config, packages);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/dotenv.ts
|
|
220
|
+
function resolveBuildName(options, envKey, defaultBuild) {
|
|
221
|
+
const raw = String(options.build ?? process.env[envKey] ?? defaultBuild).trim();
|
|
222
|
+
if (!raw) throw new Error("Build name is empty.");
|
|
223
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(raw)) throw new Error(`Invalid build name '${raw}'.`);
|
|
224
|
+
return raw;
|
|
225
|
+
}
|
|
226
|
+
function patternToFile(pattern, build, localBuildName, localOverrideFile) {
|
|
227
|
+
if (pattern === ".env.{build}" && build === localBuildName) return localOverrideFile;
|
|
228
|
+
return pattern.replaceAll("{build}", build);
|
|
229
|
+
}
|
|
230
|
+
async function listEnvFiles(options = {}) {
|
|
231
|
+
const config = await loadEnvLaneConfig(options);
|
|
232
|
+
const target = await resolveTargetPackage(options.target, { ...options, config });
|
|
233
|
+
return listEnvFilesForTarget(config, target, options);
|
|
234
|
+
}
|
|
235
|
+
function listEnvFilesForTarget(config, target, options = {}) {
|
|
236
|
+
const build = resolveBuildName(options, config.selector.envKey, config.selector.defaultBuild);
|
|
237
|
+
return config.dotenv.order.map((pattern, index) => {
|
|
238
|
+
const fileName = patternToFile(
|
|
239
|
+
pattern,
|
|
240
|
+
build,
|
|
241
|
+
config.dotenv.localBuildName,
|
|
242
|
+
config.dotenv.localOverrideFile
|
|
243
|
+
);
|
|
244
|
+
const filePath = path3.resolve(target.dir, fileName);
|
|
245
|
+
return {
|
|
246
|
+
kind: index === 0 ? "base" : index === 1 ? "override" : "custom",
|
|
247
|
+
path: filePath,
|
|
248
|
+
relativePath: path3.relative(config.rootDir, filePath).replaceAll(path3.sep, "/"),
|
|
249
|
+
exists: existsSync3(filePath),
|
|
250
|
+
required: index > 0 && Boolean(options.requireOverride ?? config.dotenv.requireOverride),
|
|
251
|
+
order: index
|
|
252
|
+
};
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
function lineForKey(content, key) {
|
|
256
|
+
const lines = content.split(/\r?\n/);
|
|
257
|
+
const re = new RegExp(`^\\s*(?:export\\s+)?${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=`);
|
|
258
|
+
const idx = lines.findIndex((line) => re.test(line));
|
|
259
|
+
return idx >= 0 ? idx + 1 : void 0;
|
|
260
|
+
}
|
|
261
|
+
async function resolveInjectedEnv(options = {}) {
|
|
262
|
+
const config = await loadEnvLaneConfig(options);
|
|
263
|
+
const target = await resolveTargetPackage(options.target, { ...options, config });
|
|
264
|
+
const build = resolveBuildName(options, config.selector.envKey, config.selector.defaultBuild);
|
|
265
|
+
const files = listEnvFilesForTarget(config, target, options);
|
|
266
|
+
const values = {};
|
|
267
|
+
const sources = {};
|
|
268
|
+
const missingRequired = files.filter((file) => file.required && !file.exists);
|
|
269
|
+
if (missingRequired.length)
|
|
270
|
+
throw new Error(
|
|
271
|
+
`Missing required env file(s): ${missingRequired.map((file) => file.relativePath).join(", ")}`
|
|
272
|
+
);
|
|
273
|
+
for (const file of files) {
|
|
274
|
+
if (!file.exists) continue;
|
|
275
|
+
const content = readFileSync3(file.path, "utf8");
|
|
276
|
+
const parsed = parse(content);
|
|
277
|
+
if (config.selector.forbidInDotenv && Object.prototype.hasOwnProperty.call(parsed, config.selector.envKey)) {
|
|
278
|
+
throw new Error(
|
|
279
|
+
`${config.selector.envKey} is a selector and must not be stored in dotenv files (${file.relativePath}).`
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
283
|
+
values[key] = value;
|
|
284
|
+
sources[key] = {
|
|
285
|
+
source: "dotenv",
|
|
286
|
+
file: file.path,
|
|
287
|
+
relativeFile: file.relativePath,
|
|
288
|
+
line: lineForKey(content, key)
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (options.includeProcessEnv ?? config.dotenv.includeProcessEnv) {
|
|
293
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
294
|
+
if (value === void 0) continue;
|
|
295
|
+
if (Object.prototype.hasOwnProperty.call(values, key)) {
|
|
296
|
+
sources[key] = { source: "process", shellOverride: true };
|
|
297
|
+
} else {
|
|
298
|
+
sources[key] = { source: "process" };
|
|
299
|
+
}
|
|
300
|
+
values[key] = value;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
values[config.selector.envKey] = build;
|
|
304
|
+
sources[config.selector.envKey] = {
|
|
305
|
+
source: "selector",
|
|
306
|
+
shellOverride: Object.prototype.hasOwnProperty.call(process.env, config.selector.envKey)
|
|
307
|
+
};
|
|
308
|
+
return {
|
|
309
|
+
rootDir: config.rootDir,
|
|
310
|
+
target,
|
|
311
|
+
build,
|
|
312
|
+
selectorKey: config.selector.envKey,
|
|
313
|
+
files,
|
|
314
|
+
values,
|
|
315
|
+
sources
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/check.ts
|
|
320
|
+
function lineForKey2(content, key) {
|
|
321
|
+
const lines = content.split(/\r?\n/);
|
|
322
|
+
const re = new RegExp(`^\\s*(?:export\\s+)?${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=`);
|
|
323
|
+
const idx = lines.findIndex((line) => re.test(line));
|
|
324
|
+
return idx >= 0 ? idx + 1 : void 0;
|
|
325
|
+
}
|
|
326
|
+
async function checkDotenvSelector(options = {}) {
|
|
327
|
+
const config = await loadEnvLaneConfig(options);
|
|
328
|
+
const target = options.target && options.target !== "all" ? await resolveTargetPackage(options.target, { ...options, config }) : void 0;
|
|
329
|
+
const scanDir = target?.dir ?? config.rootDir;
|
|
330
|
+
const files = await fg2(["**/.env", "**/.env.*", "**/*.env", "**/*.env.*"], {
|
|
331
|
+
cwd: scanDir,
|
|
332
|
+
absolute: true,
|
|
333
|
+
onlyFiles: true,
|
|
334
|
+
ignore: [
|
|
335
|
+
"**/node_modules/**",
|
|
336
|
+
"**/dist/**",
|
|
337
|
+
"**/coverage/**",
|
|
338
|
+
"**/tmp/**",
|
|
339
|
+
"**/.git/**",
|
|
340
|
+
"**/.turbo/**"
|
|
341
|
+
]
|
|
342
|
+
});
|
|
343
|
+
const violations = [];
|
|
344
|
+
for (const file of files) {
|
|
345
|
+
if (!existsSync4(file)) continue;
|
|
346
|
+
const content = readFileSync4(file, "utf8");
|
|
347
|
+
const parsed = parse2(content);
|
|
348
|
+
if (Object.prototype.hasOwnProperty.call(parsed, config.selector.envKey)) {
|
|
349
|
+
violations.push({
|
|
350
|
+
file,
|
|
351
|
+
relativeFile: path4.relative(config.rootDir, file).replaceAll(path4.sep, "/"),
|
|
352
|
+
line: lineForKey2(content, config.selector.envKey)
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const missingRequired = [];
|
|
357
|
+
if (options.requireOverride ?? config.dotenv.requireOverride) {
|
|
358
|
+
const targets = options.target && options.target !== "all" ? [target ?? await resolveTargetPackage(options.target, { ...options, config })] : await listWorkspacePackagesForConfig(config);
|
|
359
|
+
for (const pkg of targets) {
|
|
360
|
+
const envFiles = listEnvFilesForTarget(config, pkg, {
|
|
361
|
+
target: pkg.relativeDir,
|
|
362
|
+
build: options.build,
|
|
363
|
+
requireOverride: true
|
|
364
|
+
});
|
|
365
|
+
for (const file of envFiles.filter((item) => item.required && !item.exists)) {
|
|
366
|
+
missingRequired.push({
|
|
367
|
+
file: file.path,
|
|
368
|
+
relativeFile: file.relativePath,
|
|
369
|
+
target: pkg.name ?? pkg.relativeDir
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return {
|
|
375
|
+
ok: violations.length === 0 && missingRequired.length === 0,
|
|
376
|
+
selectorKey: config.selector.envKey,
|
|
377
|
+
violations,
|
|
378
|
+
missingRequired
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// src/logger.ts
|
|
383
|
+
var currentLogger = {
|
|
384
|
+
log: (...args) => console.log(...args),
|
|
385
|
+
info: (...args) => console.info(...args),
|
|
386
|
+
warn: (...args) => console.warn(...args),
|
|
387
|
+
error: (...args) => console.error(...args),
|
|
388
|
+
success: (...args) => console.log(...args),
|
|
389
|
+
debug: (...args) => console.debug(...args),
|
|
390
|
+
write: (msg) => process.stdout.write(msg)
|
|
391
|
+
};
|
|
392
|
+
function setLogger(logger) {
|
|
393
|
+
currentLogger = logger;
|
|
394
|
+
}
|
|
395
|
+
function getLogger() {
|
|
396
|
+
return currentLogger;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// src/redaction.ts
|
|
400
|
+
var SECRET_KEY_RE = /(SECRET|PRIVATE|PASSWORD|PASS|TOKEN|API_KEY|ACCESS_KEY|CREDENTIAL|DATABASE_URL|DB_URL|REDIS_URL|REDIS_URI|RPC_URL|(^|_)KEY($|_))/i;
|
|
401
|
+
function isSecretLikeKey(key) {
|
|
402
|
+
return SECRET_KEY_RE.test(key);
|
|
403
|
+
}
|
|
404
|
+
function redactValue(key, value, showSecrets = false) {
|
|
405
|
+
if (showSecrets) return value;
|
|
406
|
+
return isSecretLikeKey(key) ? value ? "<redacted>" : "" : value;
|
|
407
|
+
}
|
|
408
|
+
function redactRecord(values, showSecrets = false) {
|
|
409
|
+
return Object.fromEntries(
|
|
410
|
+
Object.entries(values).map(([key, value]) => [key, redactValue(key, value, showSecrets)])
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// src/run.ts
|
|
415
|
+
import { execa } from "execa";
|
|
416
|
+
async function runWithInjectedEnv(options) {
|
|
417
|
+
if (!options.command.length) throw new Error("Missing command.");
|
|
418
|
+
const resolved = await resolveInjectedEnv(options);
|
|
419
|
+
const cwd = options.runCwd === "root" ? resolved.rootDir : !options.runCwd || options.runCwd === "target" ? resolved.target.dir : options.runCwd;
|
|
420
|
+
if (!options.quiet) {
|
|
421
|
+
const loaded = resolved.files.filter((file) => file.exists).map((file) => file.relativePath).join(", ") || "<none>";
|
|
422
|
+
const missing = resolved.files.filter((file) => !file.exists).map((file) => file.relativePath).join(", ");
|
|
423
|
+
const logger = getLogger();
|
|
424
|
+
logger.info(
|
|
425
|
+
`[env-lane] target=${resolved.target.name ?? resolved.target.relativeDir} build=${resolved.build}`
|
|
426
|
+
);
|
|
427
|
+
logger.info(`[env-lane] loaded=${loaded}`);
|
|
428
|
+
if (missing) logger.info(`[env-lane] missing=${missing}`);
|
|
429
|
+
}
|
|
430
|
+
const subprocess = execa(options.command[0], options.command.slice(1), {
|
|
431
|
+
cwd,
|
|
432
|
+
env: resolved.values,
|
|
433
|
+
stdio: "inherit",
|
|
434
|
+
reject: false,
|
|
435
|
+
shell: process.platform === "win32"
|
|
436
|
+
});
|
|
437
|
+
const result = await subprocess;
|
|
438
|
+
return result.exitCode ?? 1;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// src/sort.ts
|
|
442
|
+
import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync5, writeFileSync } from "fs";
|
|
443
|
+
import path5 from "path";
|
|
444
|
+
var ENV_ENTRY_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
|
|
445
|
+
var COMMENTED_ENV_ENTRY_RE = /^\s*#\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
|
|
446
|
+
function portable(file) {
|
|
447
|
+
return file.replace(/\\/g, "/").replaceAll(path5.sep, "/");
|
|
448
|
+
}
|
|
449
|
+
async function loadSortConfig(configPath) {
|
|
450
|
+
const abs = path5.resolve(configPath);
|
|
451
|
+
if (!existsSync5(abs)) throw new Error(`Sort config does not exist: ${abs}`);
|
|
452
|
+
const config = await loadEnvLaneConfig({ cwd: path5.dirname(abs), configFile: abs });
|
|
453
|
+
const packages = await listWorkspacePackagesForConfig(config);
|
|
454
|
+
const sort = { ...config.sort };
|
|
455
|
+
const handledAliases = /* @__PURE__ */ new Set();
|
|
456
|
+
for (const pkg of packages) {
|
|
457
|
+
for (const alias of pkg.aliases) {
|
|
458
|
+
handledAliases.add(alias);
|
|
459
|
+
const target = sort[alias] ?? {};
|
|
460
|
+
sort[alias] = {
|
|
461
|
+
...target,
|
|
462
|
+
baseDir: target.baseDir ?? pkg.dir,
|
|
463
|
+
file: target.file ?? ".env",
|
|
464
|
+
template: target.template ?? ".env.example"
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
for (const [key, target] of Object.entries(sort)) {
|
|
469
|
+
if (handledAliases.has(key)) continue;
|
|
470
|
+
sort[key] = {
|
|
471
|
+
...target,
|
|
472
|
+
baseDir: target.baseDir ?? config.rootDir,
|
|
473
|
+
file: target.file ?? ".env",
|
|
474
|
+
template: target.template ?? ".env.example"
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
return {
|
|
478
|
+
baseDir: config.rootDir,
|
|
479
|
+
envFiles: [],
|
|
480
|
+
sort,
|
|
481
|
+
dotenv: config.dotenv,
|
|
482
|
+
selector: config.selector,
|
|
483
|
+
packages
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
function emitCommandChange(command, payload) {
|
|
487
|
+
getLogger().info(`[env-store-change] ${JSON.stringify({ command, ...payload })}`);
|
|
488
|
+
}
|
|
489
|
+
function createEmptyDocument() {
|
|
490
|
+
return { hasBom: false, eol: "\n", hasFinalNewline: true, lines: [] };
|
|
491
|
+
}
|
|
492
|
+
function createTextDocument(content) {
|
|
493
|
+
const hasBom = content.startsWith("\uFEFF");
|
|
494
|
+
const raw = hasBom ? content.slice(1) : content;
|
|
495
|
+
const eol = raw.includes("\r\n") ? "\r\n" : "\n";
|
|
496
|
+
const hasFinalNewline = raw.length > 0 && /\r?\n$/.test(raw);
|
|
497
|
+
let lines = raw.length > 0 ? raw.split(/\r\n|\n/) : [];
|
|
498
|
+
if (hasFinalNewline && lines.at(-1) === "") lines = lines.slice(0, -1);
|
|
499
|
+
return { hasBom, eol, hasFinalNewline, lines };
|
|
500
|
+
}
|
|
501
|
+
function renderTextDocument(document, lines) {
|
|
502
|
+
const body = lines.join(document.eol);
|
|
503
|
+
const withNewline = lines.length > 0 && document.hasFinalNewline ? `${body}${document.eol}` : body;
|
|
504
|
+
return document.hasBom ? `\uFEFF${withNewline}` : withNewline;
|
|
505
|
+
}
|
|
506
|
+
function parseEnvLine(line) {
|
|
507
|
+
const trimmed = line.trim();
|
|
508
|
+
if (!trimmed) return { kind: "empty", rawLine: line };
|
|
509
|
+
if (trimmed.startsWith("#")) {
|
|
510
|
+
const commentedEntryMatch = line.match(COMMENTED_ENV_ENTRY_RE);
|
|
511
|
+
if (commentedEntryMatch) {
|
|
512
|
+
const eqIdx2 = line.indexOf("=");
|
|
513
|
+
return {
|
|
514
|
+
kind: "commented-entry",
|
|
515
|
+
rawLine: line,
|
|
516
|
+
key: commentedEntryMatch[1],
|
|
517
|
+
prefix: line.slice(0, eqIdx2 + 1),
|
|
518
|
+
rawValue: line.slice(eqIdx2 + 1)
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
return { kind: "comment", rawLine: line };
|
|
522
|
+
}
|
|
523
|
+
const eqIdx = line.indexOf("=");
|
|
524
|
+
if (eqIdx < 0) return { kind: "invalid", rawLine: line, reason: "missing equals sign" };
|
|
525
|
+
const match = line.match(ENV_ENTRY_RE);
|
|
526
|
+
if (!match) return { kind: "invalid", rawLine: line, reason: "invalid env key" };
|
|
527
|
+
return {
|
|
528
|
+
kind: "entry",
|
|
529
|
+
rawLine: line,
|
|
530
|
+
key: match[1],
|
|
531
|
+
prefix: line.slice(0, eqIdx + 1),
|
|
532
|
+
rawValue: line.slice(eqIdx + 1)
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function loadEnvDocument(filePath) {
|
|
536
|
+
const fileExists = existsSync5(filePath);
|
|
537
|
+
const document = fileExists ? createTextDocument(readFileSync5(filePath, "utf8")) : createEmptyDocument();
|
|
538
|
+
const parsedLines = document.lines.map((line, index) => ({
|
|
539
|
+
lineNumber: index + 1,
|
|
540
|
+
...parseEnvLine(line)
|
|
541
|
+
}));
|
|
542
|
+
return { exists: fileExists, document, parsedLines };
|
|
543
|
+
}
|
|
544
|
+
function isEnvEntryLikeLine(line) {
|
|
545
|
+
return line.kind === "entry" || line.kind === "commented-entry";
|
|
546
|
+
}
|
|
547
|
+
function buildEnvSortLayout(envDoc) {
|
|
548
|
+
const blocks = [];
|
|
549
|
+
let preambleLines = [];
|
|
550
|
+
let pendingLines = [];
|
|
551
|
+
let sawEntry = false;
|
|
552
|
+
for (const line of envDoc.parsedLines) {
|
|
553
|
+
if (isEnvEntryLikeLine(line)) {
|
|
554
|
+
if (!sawEntry) {
|
|
555
|
+
preambleLines = pendingLines;
|
|
556
|
+
pendingLines = [];
|
|
557
|
+
sawEntry = true;
|
|
558
|
+
}
|
|
559
|
+
blocks.push({
|
|
560
|
+
key: line.key,
|
|
561
|
+
kind: line.kind,
|
|
562
|
+
rawLine: line.rawLine,
|
|
563
|
+
rawValue: line.rawValue,
|
|
564
|
+
leadingLines: pendingLines,
|
|
565
|
+
lineNumber: line.lineNumber,
|
|
566
|
+
order: blocks.length
|
|
567
|
+
});
|
|
568
|
+
pendingLines = [];
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
pendingLines.push(line.rawLine);
|
|
572
|
+
}
|
|
573
|
+
if (!sawEntry) {
|
|
574
|
+
preambleLines = pendingLines;
|
|
575
|
+
pendingLines = [];
|
|
576
|
+
}
|
|
577
|
+
return { preambleLines, blocks, suffixLines: pendingLines };
|
|
578
|
+
}
|
|
579
|
+
function hasCommentedEnvValue(block) {
|
|
580
|
+
const trimmed = block.rawValue.trim();
|
|
581
|
+
return trimmed !== "" && !trimmed.startsWith("#");
|
|
582
|
+
}
|
|
583
|
+
function shouldIgnoreEmptyCommentedEnvBlock(block, groupBlocks) {
|
|
584
|
+
if (block.kind !== "commented-entry" || hasCommentedEnvValue(block)) return false;
|
|
585
|
+
return groupBlocks.some(
|
|
586
|
+
(candidate) => candidate !== block && (candidate.kind === "entry" || hasCommentedEnvValue(candidate))
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
function isBlankLine(line) {
|
|
590
|
+
return line.trim() === "";
|
|
591
|
+
}
|
|
592
|
+
function normalizeBlankLineRuns(lines) {
|
|
593
|
+
const normalizedLines = [];
|
|
594
|
+
for (const line of lines) {
|
|
595
|
+
if (isBlankLine(line) && normalizedLines.length > 0 && isBlankLine(normalizedLines.at(-1) ?? ""))
|
|
596
|
+
continue;
|
|
597
|
+
normalizedLines.push(line);
|
|
598
|
+
}
|
|
599
|
+
return normalizedLines;
|
|
600
|
+
}
|
|
601
|
+
function buildEnvSortGroups(blocks) {
|
|
602
|
+
const groupedBlocks = /* @__PURE__ */ new Map();
|
|
603
|
+
for (const block of blocks) {
|
|
604
|
+
const groupBlocks = groupedBlocks.get(block.key) ?? [];
|
|
605
|
+
groupBlocks.push(block);
|
|
606
|
+
groupedBlocks.set(block.key, groupBlocks);
|
|
607
|
+
}
|
|
608
|
+
const groups = [];
|
|
609
|
+
for (const [key, groupBlocks] of groupedBlocks) {
|
|
610
|
+
const keptBlocks = groupBlocks.filter(
|
|
611
|
+
(block) => !shouldIgnoreEmptyCommentedEnvBlock(block, groupBlocks)
|
|
612
|
+
);
|
|
613
|
+
if (keptBlocks.length === 0) continue;
|
|
614
|
+
groups.push({
|
|
615
|
+
key,
|
|
616
|
+
order: Math.min(...keptBlocks.map((block) => block.order)),
|
|
617
|
+
blocks: keptBlocks,
|
|
618
|
+
leadingLines: normalizeBlankLineRuns(groupBlocks.flatMap((block) => block.leadingLines)),
|
|
619
|
+
rawLines: keptBlocks.map((block) => block.rawLine)
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
groups.sort((left, right) => left.order - right.order);
|
|
623
|
+
return groups;
|
|
624
|
+
}
|
|
625
|
+
function buildCommentLineSet(lines) {
|
|
626
|
+
const normalizedComments = /* @__PURE__ */ new Set();
|
|
627
|
+
for (const line of lines) {
|
|
628
|
+
const parsed = parseEnvLine(line);
|
|
629
|
+
if (parsed.kind === "comment") normalizedComments.add(line.trim());
|
|
630
|
+
}
|
|
631
|
+
return normalizedComments;
|
|
632
|
+
}
|
|
633
|
+
function partitionPreambleLines(templateLines, envLines) {
|
|
634
|
+
const normalizedTemplateLines = normalizeBlankLineRuns(templateLines);
|
|
635
|
+
const normalizedEnvLines = normalizeBlankLineRuns(envLines);
|
|
636
|
+
if (normalizedEnvLines.length === 0) return { matchedTemplateLines: [], extraLines: [] };
|
|
637
|
+
if (normalizedTemplateLines.length === 0) {
|
|
638
|
+
return {
|
|
639
|
+
matchedTemplateLines: [],
|
|
640
|
+
extraLines: normalizedEnvLines.filter((line) => !isBlankLine(line))
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
const templateComments = buildCommentLineSet(normalizedTemplateLines);
|
|
644
|
+
const matchedTemplateLines = [];
|
|
645
|
+
const extraLines = [];
|
|
646
|
+
for (const line of normalizedEnvLines) {
|
|
647
|
+
const parsed = parseEnvLine(line);
|
|
648
|
+
if (parsed.kind === "comment" && templateComments.has(line.trim())) {
|
|
649
|
+
matchedTemplateLines.push(line);
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
if (parsed.kind === "empty") continue;
|
|
653
|
+
extraLines.push(line);
|
|
654
|
+
}
|
|
655
|
+
return {
|
|
656
|
+
matchedTemplateLines: normalizeBlankLineRuns(matchedTemplateLines),
|
|
657
|
+
extraLines: normalizeBlankLineRuns(extraLines)
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
function mergeLeadingLines(templateLines, envLines) {
|
|
661
|
+
const normalizedTemplateLines = normalizeBlankLineRuns(templateLines);
|
|
662
|
+
if (normalizedTemplateLines.length === 0) return normalizeBlankLineRuns(envLines);
|
|
663
|
+
const templateComments = buildCommentLineSet(normalizedTemplateLines);
|
|
664
|
+
const unmatchedEnvLines = normalizeBlankLineRuns(
|
|
665
|
+
envLines.filter((line) => {
|
|
666
|
+
const parsed = parseEnvLine(line);
|
|
667
|
+
if (parsed.kind === "empty") return false;
|
|
668
|
+
return parsed.kind !== "comment" || !templateComments.has(line.trim());
|
|
669
|
+
})
|
|
670
|
+
);
|
|
671
|
+
if (unmatchedEnvLines.length === 0) return normalizedTemplateLines;
|
|
672
|
+
const mergedLines = [...normalizedTemplateLines];
|
|
673
|
+
if (!isBlankLine(mergedLines.at(-1) ?? "") && !isBlankLine(unmatchedEnvLines[0]))
|
|
674
|
+
mergedLines.push("");
|
|
675
|
+
mergedLines.push(...unmatchedEnvLines);
|
|
676
|
+
return normalizeBlankLineRuns(mergedLines);
|
|
677
|
+
}
|
|
678
|
+
function commentOutEnvEntryLine(line) {
|
|
679
|
+
const parsed = parseEnvLine(line);
|
|
680
|
+
if (parsed.kind === "commented-entry") return parsed.rawLine;
|
|
681
|
+
if (parsed.kind !== "entry") return `# ${line.trimStart()}`;
|
|
682
|
+
const indent = line.match(/^\s*/)?.[0] ?? "";
|
|
683
|
+
return `${indent}# ${line.slice(indent.length)}`;
|
|
684
|
+
}
|
|
685
|
+
function buildEnvSortPlan(envFilePath, templateFilePath) {
|
|
686
|
+
const resolvedEnvFilePath = path5.resolve(envFilePath);
|
|
687
|
+
const resolvedTemplateFilePath = path5.resolve(templateFilePath);
|
|
688
|
+
if (!existsSync5(resolvedTemplateFilePath)) {
|
|
689
|
+
throw new Error(`Template env file does not exist: ${resolvedTemplateFilePath}`);
|
|
690
|
+
}
|
|
691
|
+
const envDoc = loadEnvDocument(resolvedEnvFilePath);
|
|
692
|
+
const templateDoc = loadEnvDocument(resolvedTemplateFilePath);
|
|
693
|
+
const envLayout = buildEnvSortLayout(envDoc);
|
|
694
|
+
const templateLayout = buildEnvSortLayout(templateDoc);
|
|
695
|
+
if (envLayout.blocks.length > 0) {
|
|
696
|
+
const { matchedTemplateLines, extraLines } = partitionPreambleLines(
|
|
697
|
+
templateLayout.preambleLines,
|
|
698
|
+
envLayout.preambleLines
|
|
699
|
+
);
|
|
700
|
+
envLayout.preambleLines = matchedTemplateLines;
|
|
701
|
+
if (extraLines.length > 0) {
|
|
702
|
+
envLayout.blocks[0] = {
|
|
703
|
+
...envLayout.blocks[0],
|
|
704
|
+
leadingLines: normalizeBlankLineRuns([...extraLines, ...envLayout.blocks[0].leadingLines])
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const envGroups = new Map(buildEnvSortGroups(envLayout.blocks).map((group) => [group.key, group]));
|
|
709
|
+
const templateKeys = new Set(templateLayout.blocks.map((block) => block.key));
|
|
710
|
+
const templateBlocksByKey = [];
|
|
711
|
+
const seenTemplateKeys = /* @__PURE__ */ new Set();
|
|
712
|
+
for (const block of templateLayout.blocks) {
|
|
713
|
+
if (seenTemplateKeys.has(block.key)) continue;
|
|
714
|
+
seenTemplateKeys.add(block.key);
|
|
715
|
+
templateBlocksByKey.push(block);
|
|
716
|
+
}
|
|
717
|
+
const renderedLines = mergeLeadingLines(templateLayout.preambleLines, envLayout.preambleLines);
|
|
718
|
+
const consumedKeys = /* @__PURE__ */ new Set();
|
|
719
|
+
const operations = [];
|
|
720
|
+
let renderedOrder = 0;
|
|
721
|
+
for (const templateBlock of templateBlocksByKey) {
|
|
722
|
+
const envGroup = envGroups.get(templateBlock.key);
|
|
723
|
+
if (envGroup) {
|
|
724
|
+
consumedKeys.add(envGroup.key);
|
|
725
|
+
renderedLines.push(
|
|
726
|
+
...mergeLeadingLines(templateBlock.leadingLines, envGroup.leadingLines),
|
|
727
|
+
...envGroup.rawLines
|
|
728
|
+
);
|
|
729
|
+
if (envGroup.order !== renderedOrder) operations.push({ action: "move", key: envGroup.key });
|
|
730
|
+
if (envGroup.blocks.length > 1)
|
|
731
|
+
operations.push({ action: "group-duplicate", key: envGroup.key });
|
|
732
|
+
renderedOrder++;
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
renderedLines.push(...templateBlock.leadingLines, commentOutEnvEntryLine(templateBlock.rawLine));
|
|
736
|
+
operations.push({ action: "insert-commented", key: templateBlock.key });
|
|
737
|
+
renderedOrder++;
|
|
738
|
+
}
|
|
739
|
+
const leftoverGroups = [...envGroups.values()].filter((group) => !consumedKeys.has(group.key));
|
|
740
|
+
for (const group of leftoverGroups) {
|
|
741
|
+
renderedLines.push(...group.leadingLines, ...group.rawLines);
|
|
742
|
+
operations.push({
|
|
743
|
+
action: templateKeys.has(group.key) ? "append-duplicate" : "append-extra",
|
|
744
|
+
key: group.key
|
|
745
|
+
});
|
|
746
|
+
renderedOrder++;
|
|
747
|
+
}
|
|
748
|
+
renderedLines.push(...mergeLeadingLines(templateLayout.suffixLines, envLayout.suffixLines));
|
|
749
|
+
const renderDocument = envDoc.exists ? envDoc.document : templateDoc.document;
|
|
750
|
+
const currentContent = envDoc.exists ? renderTextDocument(envDoc.document, envDoc.document.lines) : "";
|
|
751
|
+
const nextContent = renderTextDocument(renderDocument, renderedLines);
|
|
752
|
+
const summary = operations.reduce(
|
|
753
|
+
(acc, operation) => {
|
|
754
|
+
if (operation.action === "move") acc.movedCount++;
|
|
755
|
+
else if (operation.action === "insert-commented") acc.insertedCommentedCount++;
|
|
756
|
+
else if (operation.action === "append-extra") acc.appendedExtraCount++;
|
|
757
|
+
else if (operation.action === "append-duplicate") acc.appendedDuplicateCount++;
|
|
758
|
+
else if (operation.action === "group-duplicate") acc.groupedDuplicateCount++;
|
|
759
|
+
return acc;
|
|
760
|
+
},
|
|
761
|
+
{
|
|
762
|
+
movedCount: 0,
|
|
763
|
+
insertedCommentedCount: 0,
|
|
764
|
+
appendedExtraCount: 0,
|
|
765
|
+
appendedDuplicateCount: 0,
|
|
766
|
+
groupedDuplicateCount: 0
|
|
767
|
+
}
|
|
768
|
+
);
|
|
769
|
+
return {
|
|
770
|
+
filePath: resolvedEnvFilePath,
|
|
771
|
+
templateFilePath: resolvedTemplateFilePath,
|
|
772
|
+
changed: currentContent !== nextContent,
|
|
773
|
+
currentContent,
|
|
774
|
+
nextContent,
|
|
775
|
+
operations,
|
|
776
|
+
summary
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
async function sortEnvFile(envFilePath, templateFilePath) {
|
|
780
|
+
const plan = buildEnvSortPlan(envFilePath, templateFilePath);
|
|
781
|
+
if (!plan.changed) {
|
|
782
|
+
return {
|
|
783
|
+
applied: false,
|
|
784
|
+
filePath: plan.filePath,
|
|
785
|
+
templateFilePath: plan.templateFilePath,
|
|
786
|
+
...plan.summary
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
mkdirSync(path5.dirname(plan.filePath), { recursive: true });
|
|
790
|
+
writeFileSync(plan.filePath, plan.nextContent, "utf8");
|
|
791
|
+
for (const operation of plan.operations) {
|
|
792
|
+
emitCommandChange("sort", {
|
|
793
|
+
action: operation.action,
|
|
794
|
+
filePath: portable(plan.filePath),
|
|
795
|
+
templateFilePath: portable(plan.templateFilePath),
|
|
796
|
+
key: operation.key
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
emitCommandChange("sort", {
|
|
800
|
+
action: "write-file",
|
|
801
|
+
filePath: portable(plan.filePath),
|
|
802
|
+
templateFilePath: portable(plan.templateFilePath)
|
|
803
|
+
});
|
|
804
|
+
return {
|
|
805
|
+
applied: true,
|
|
806
|
+
filePath: plan.filePath,
|
|
807
|
+
templateFilePath: plan.templateFilePath,
|
|
808
|
+
...plan.summary
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
function normalizeSortSelector(value, fallback, fieldName) {
|
|
812
|
+
const normalized = value === void 0 || value === null || value === "" ? fallback : String(value).trim();
|
|
813
|
+
if (!normalized) return fallback;
|
|
814
|
+
if (fieldName === "env-suffix" && normalized === "default") return "";
|
|
815
|
+
return normalized;
|
|
816
|
+
}
|
|
817
|
+
function interpolateSortFilePattern(pattern, envSuffix) {
|
|
818
|
+
return pattern.replaceAll("{env}", envSuffix).replaceAll("{suffix}", envSuffix);
|
|
819
|
+
}
|
|
820
|
+
async function sortEnvFilesFromConfig(configPath, keyArg = "all", envSuffixArg = "all") {
|
|
821
|
+
const config = await loadSortConfig(configPath);
|
|
822
|
+
const keySelector = normalizeSortSelector(keyArg, "all", "key");
|
|
823
|
+
const envSuffixSelector = normalizeSortSelector(envSuffixArg, "all", "env-suffix");
|
|
824
|
+
const selectedTargets = Object.entries(config.sort).filter(
|
|
825
|
+
([key]) => keySelector === "all" || key === keySelector
|
|
826
|
+
);
|
|
827
|
+
if (selectedTargets.length === 0) throw new Error(`Unknown sort key: ${keySelector}`);
|
|
828
|
+
const results = [];
|
|
829
|
+
for (const [key, target] of selectedTargets) {
|
|
830
|
+
const baseDir = target.baseDir ?? config.baseDir;
|
|
831
|
+
const file = target.file ?? ".env";
|
|
832
|
+
const template = target.template ?? ".env.example";
|
|
833
|
+
const defaultFilePath = path5.resolve(baseDir, file);
|
|
834
|
+
const templateFilePath = path5.resolve(baseDir, template);
|
|
835
|
+
const targetDir = path5.dirname(defaultFilePath);
|
|
836
|
+
const files = /* @__PURE__ */ new Map([["", defaultFilePath]]);
|
|
837
|
+
for (const pattern of config.dotenv.order) {
|
|
838
|
+
if (pattern.includes("{build}")) {
|
|
839
|
+
for (const build of config.selector.builds) {
|
|
840
|
+
files.set(build, path5.resolve(targetDir, pattern.replace("{build}", build)));
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
if (target.files) {
|
|
845
|
+
for (const [suffix, file2] of Object.entries(target.files)) {
|
|
846
|
+
if (suffix === "default")
|
|
847
|
+
throw new Error(`config.sort.${key}.files must not use reserved suffix "default".`);
|
|
848
|
+
files.set(suffix, path5.resolve(baseDir, interpolateSortFilePattern(file2, suffix)));
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
const jobs = envSuffixSelector === "all" ? [...files.entries()] : [
|
|
852
|
+
[
|
|
853
|
+
envSuffixSelector,
|
|
854
|
+
files.get(envSuffixSelector) ?? path5.resolve(targetDir, `${path5.basename(defaultFilePath)}.${envSuffixSelector}`)
|
|
855
|
+
]
|
|
856
|
+
];
|
|
857
|
+
for (const [, file2] of jobs) results.push(await sortEnvFile(file2, templateFilePath));
|
|
858
|
+
}
|
|
859
|
+
return { applied: results.some((result) => result.applied), count: results.length, results };
|
|
860
|
+
}
|
|
861
|
+
export {
|
|
862
|
+
buildEnvSortPlan,
|
|
863
|
+
checkDotenvSelector,
|
|
864
|
+
defineConfig,
|
|
865
|
+
findWorkspaceRoot,
|
|
866
|
+
getLogger,
|
|
867
|
+
isSecretLikeKey,
|
|
868
|
+
listEnvFiles,
|
|
869
|
+
listEnvFilesForTarget,
|
|
870
|
+
listWorkspacePackages,
|
|
871
|
+
listWorkspacePackagesForConfig,
|
|
872
|
+
loadEnvLaneConfig,
|
|
873
|
+
readPnpmWorkspaceGlobs,
|
|
874
|
+
redactRecord,
|
|
875
|
+
redactValue,
|
|
876
|
+
resolveBuildName,
|
|
877
|
+
resolveInjectedEnv,
|
|
878
|
+
resolveTargetPackage,
|
|
879
|
+
resolveTargetPackageFromList,
|
|
880
|
+
runWithInjectedEnv,
|
|
881
|
+
setLogger,
|
|
882
|
+
sortEnvFile,
|
|
883
|
+
sortEnvFilesFromConfig
|
|
884
|
+
};
|