@snow-tzu/type-config
Version:
Core configuration management system with Spring Boot-like features
167 lines (166 loc) • 5.89 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncryptionHelper = exports.InMemoryConfigSource = exports.EnvConfigSource = exports.FileConfigSource = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const yaml = __importStar(require("js-yaml"));
const crypto = __importStar(require("crypto"));
class FileConfigSource {
constructor(filePath, priority = 100, name) {
this.filePath = filePath;
this.priority = priority;
this.name = name;
this.name = name || `file:${filePath}`;
}
async load() {
if (!fs.existsSync(this.filePath)) {
return {};
}
const ext = path.extname(this.filePath);
const content = fs.readFileSync(this.filePath, 'utf-8');
switch (ext) {
case '.json':
return JSON.parse(content);
case '.yml':
case '.yaml':
return yaml.load(content);
case '.env':
return this.parseEnvFile(content);
default:
throw new Error(`Unsupported file type: ${ext}`);
}
}
parseEnvFile(content) {
const result = {};
content.split('\n').forEach(line => {
const match = line.match(/^\s*([^#][^=]+)=(.*)$/);
if (match) {
result[match[1].trim()] = match[2].trim();
}
});
return result;
}
}
exports.FileConfigSource = FileConfigSource;
class EnvConfigSource {
constructor(prefix = '', priority = 200, name = 'env') {
this.prefix = prefix;
this.priority = priority;
this.name = name;
}
async load() {
const result = {};
Object.keys(process.env).forEach(key => {
if (!this.prefix || key.startsWith(this.prefix)) {
const cleanKey = this.prefix ? key.slice(this.prefix.length) : key;
const nestedKey = cleanKey.toLowerCase().replace(/_/g, '.');
this.setNestedValue(result, nestedKey, process.env[key]);
}
});
return result;
}
setNestedValue(obj, path, value) {
const keys = path.split('.');
let current = obj;
for (let i = 0; i < keys.length - 1; i++) {
if (!current[keys[i]] || typeof current[keys[i]] !== 'object') {
current[keys[i]] = {};
}
current = current[keys[i]];
}
current[keys[keys.length - 1]] = value;
}
}
exports.EnvConfigSource = EnvConfigSource;
class InMemoryConfigSource {
constructor(config, priority = 50, name = 'memory') {
this.config = config;
this.priority = priority;
this.name = name;
}
async load() {
return { ...this.config };
}
}
exports.InMemoryConfigSource = InMemoryConfigSource;
class EncryptionHelper {
constructor(secretKey) {
this.secretKey = secretKey;
this.algorithm = 'aes-256-cbc';
if (secretKey.length !== 32) {
throw new Error('Secret key must be 32 characters long');
}
}
encrypt(value) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(this.algorithm, Buffer.from(this.secretKey), iv);
let encrypted = cipher.update(value, 'utf8', 'hex');
encrypted += cipher.final('hex');
return `ENC(${iv.toString('hex')}:${encrypted})`;
}
decrypt(value) {
const match = value.match(/^ENC\(([^:]+):(.+)\)$/);
if (!match) {
return value;
}
const iv = Buffer.from(match[1], 'hex');
const encrypted = match[2];
const decipher = crypto.createDecipheriv(this.algorithm, Buffer.from(this.secretKey), iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
isEncrypted(value) {
return /^ENC\([^:]+:.+\)$/.test(value);
}
decryptObject(obj) {
if (typeof obj === 'string') {
return this.decrypt(obj);
}
if (Array.isArray(obj)) {
return obj.map(item => this.decryptObject(item));
}
if (obj && typeof obj === 'object') {
const result = {};
for (const key in obj) {
result[key] = this.decryptObject(obj[key]);
}
return result;
}
return obj;
}
}
exports.EncryptionHelper = EncryptionHelper;