super-productivity/tools/load-env.js
Johannes Millan 75afe06b69 fix(docker): simplify env handling for Docker builds
- Always read system environment variables first, then override with .env file
- Ensure all required keys are always present in generated types
- Pass environment variables correctly in Docker build
- Update .dockerignore to exclude build artifacts
2025-08-09 12:16:31 +02:00

100 lines
2.6 KiB
JavaScript
Executable file

#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const REQUIRED_ENV_KEYS = [
'UNSPLASH_KEY',
'UNSPLASH_CLIENT_ID',
// 'GOOGLE_DRIVE_TOKEN',
// 'DROPBOX_API_KEY',
// 'WEBDAV_URL',
// 'WEBDAV_USERNAME',
// 'WEBDAV_PASSWORD',
];
// Start with system environment variables for required keys
const env = {};
REQUIRED_ENV_KEYS.forEach((key) => {
if (process.env[key]) {
env[key] = process.env[key];
}
});
// Load and override with .env file values if they exist
const envPath = path.join(process.cwd(), '.env');
const envConfig = dotenv.config({ path: envPath });
if (envConfig.parsed) {
Object.assign(env, envConfig.parsed);
}
// Log what we found
const foundKeys = Object.keys(env).filter((key) => REQUIRED_ENV_KEYS.includes(key));
if (foundKeys.length > 0) {
console.log(
`✅ Found ${foundKeys.length} environment variable(s): ${foundKeys.join(', ')}`,
);
} else {
console.warn(
'⚠️ No environment variables found, generating env.generated.ts with undefined values',
);
}
// Create ENV object with all expected keys (undefined if not set)
const envEntries = REQUIRED_ENV_KEYS.map((key) => {
const value = env[key];
if (value !== undefined) {
// Escape quotes in values
const escapedValue = value.replace(/'/g, "\\'");
return ` ${key}: '${escapedValue}',`;
} else {
return ` ${key}: undefined,`;
}
});
// Generate TypeScript content
const tsContent = `// This file is auto-generated by tools/load-env.js
// Do not modify directly - edit .env file instead
// Generated at: ${new Date().toISOString()}
/**
* Environment variables loaded from .env file
* Access these constants instead of process.env in your Angular app
*/
export const ENV = {
${envEntries.join('\n')}
} as const;
// Type-safe helper to ensure all expected env vars are defined
export type EnvVars = typeof ENV;
`;
// Ensure the config directory exists
const configDir = path.join(process.cwd(), 'src/app/config');
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
// Write the generated file
const outputPath = path.join(configDir, 'env.generated.ts');
fs.writeFileSync(outputPath, tsContent);
console.log(`✅ Generated ${outputPath}`);
// Pass through to the next command
if (process.argv.length > 2) {
// Execute the rest of the command
const { spawn } = require('child_process');
const command = process.argv[2];
const args = process.argv.slice(3);
const child = spawn(command, args, {
stdio: 'inherit',
shell: true,
});
child.on('exit', (code) => {
process.exit(code);
});
}