import { importFile, type DotNestedKeys, type DotNestedValue } from '@h3ravel/shared' import { safeDot, setNested } from '@h3ravel/support' import * as supportModule from '@h3ravel/support' import { IApplication } from '@h3ravel/contracts' import { Registerer } from '@h3ravel/core' import path from 'node:path' import { readdir } from 'node:fs/promises' export class ConfigRepository { private loaded: boolean = false private configs: Record> = {} constructor(protected app: IApplication) { } // get> (): X // get, T extends Extract> (key: T): X[T] /** * Get the defined configurations */ get> (): X get, K extends DotNestedKeys> (key: K, def?: any): DotNestedValue get, K extends DotNestedKeys> (key?: K, def?: any): any { return safeDot(this.configs, key) ?? def } /** * Modify the defined configurations */ set (key: T, value: any): void { setNested(this.configs, key, value) } async load () { if (!this.loaded) { const configPath = this.app.getPath('config') globalThis.env ??= this.app.make('env') Registerer.register(this.app as never) const files = (await readdir(configPath)).filter((e) => { return /\.(c|m)?(j|t)sx?$/.test(e) && !e.includes('.d.') }) for (let i = 0; i < files.length; i++) { const configModule = await importFile<{ default?: (app: IApplication) => Record }>( path.join(configPath, files[i]), { virtualModules: { '@h3ravel/support': supportModule, }, }, ) const name = files[i].replaceAll(/\.ts|\.js/g, '') if (typeof configModule.default === 'function') { this.configs[name] = configModule.default(this.app) } } this.loaded = true } return this } }