59 lines
1.4 KiB
TypeScript
59 lines
1.4 KiB
TypeScript
import fs from 'fs';
|
|
import path from 'path';
|
|
|
|
type PackagedProcess = NodeJS.Process & { pkg?: unknown };
|
|
|
|
function uniquePaths(paths: string[]): string[] {
|
|
return [...new Set(paths.map((candidate) => path.resolve(candidate)))];
|
|
}
|
|
|
|
export function isPackagedRuntime(): boolean {
|
|
return Boolean((process as PackagedProcess).pkg);
|
|
}
|
|
|
|
export function getRuntimeBaseDir(): string {
|
|
return isPackagedRuntime()
|
|
? path.dirname(process.execPath)
|
|
: process.cwd();
|
|
}
|
|
|
|
export function resolveRuntimePath(...segments: string[]): string {
|
|
return path.join(getRuntimeBaseDir(), ...segments);
|
|
}
|
|
|
|
export function resolveProjectRootPath(...segments: string[]): string {
|
|
return path.resolve(__dirname, '..', '..', ...segments);
|
|
}
|
|
|
|
export function findExistingPath(...candidates: string[]): string | null {
|
|
for (const candidate of uniquePaths(candidates)) {
|
|
if (fs.existsSync(candidate)) {
|
|
return candidate;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
export function resolveEnvFilePath(): string {
|
|
if (isPackagedRuntime()) {
|
|
return resolveRuntimePath('.env');
|
|
}
|
|
|
|
return findExistingPath(
|
|
resolveRuntimePath('.env'),
|
|
resolveProjectRootPath('.env')
|
|
) ?? resolveProjectRootPath('.env');
|
|
}
|
|
|
|
export function resolveCertificateDirectory(): string {
|
|
if (isPackagedRuntime()) {
|
|
return resolveRuntimePath('.certs');
|
|
}
|
|
|
|
return findExistingPath(
|
|
resolveRuntimePath('.certs'),
|
|
resolveProjectRootPath('.certs')
|
|
) ?? resolveRuntimePath('.certs');
|
|
}
|