2020-07-06 14:53:03 +00:00
|
|
|
import LifecycleUnit from '../lifecycle/Unit.ts'
|
|
|
|
import {fs, path} from '../external/std.ts'
|
|
|
|
import {Canon} from './Canon.ts'
|
|
|
|
|
|
|
|
export interface CanonicalDefinition {
|
|
|
|
canonical_name: string,
|
|
|
|
original_name: string,
|
|
|
|
imported: any,
|
|
|
|
}
|
|
|
|
|
2020-07-21 03:54:25 +00:00
|
|
|
export class Canonical<T> extends LifecycleUnit {
|
2020-07-06 14:53:03 +00:00
|
|
|
protected base_path: string = '.'
|
|
|
|
protected suffix: string = '.ts'
|
|
|
|
protected canonical_item: string = ''
|
2020-07-21 03:54:25 +00:00
|
|
|
protected _items: { [key: string]: T } = {}
|
2020-07-06 14:53:03 +00:00
|
|
|
|
|
|
|
public get path(): string {
|
|
|
|
return path.resolve(this.base_path)
|
|
|
|
}
|
|
|
|
|
|
|
|
public get canonical_items() {
|
|
|
|
return `${this.canonical_item}s`
|
|
|
|
}
|
|
|
|
|
|
|
|
public async up() {
|
|
|
|
for await ( const entry of fs.walk(this.path) ) {
|
|
|
|
if ( !entry.isFile || !entry.path.endsWith(this.suffix) ) continue
|
|
|
|
const def = await this._get_canonical_definition(entry.path)
|
|
|
|
this._items[def.canonical_name] = await this.init_canonical_item(def)
|
|
|
|
}
|
|
|
|
|
|
|
|
this.make(Canon).register_resource(this.canonical_items, (key: string) => this.get(key))
|
|
|
|
}
|
|
|
|
|
2020-07-21 03:54:25 +00:00
|
|
|
public async init_canonical_item(definition: CanonicalDefinition): Promise<T> {
|
2020-07-06 14:53:03 +00:00
|
|
|
return definition.imported.default
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _get_canonical_definition(file_path: string): Promise<CanonicalDefinition> {
|
|
|
|
const original_name = file_path.replace(this.path, '').substr(1)
|
|
|
|
const path_regex = new RegExp(path.SEP, 'g')
|
|
|
|
const canonical_name = original_name.replace(path_regex, ':')
|
|
|
|
.split('').reverse().join('')
|
|
|
|
.substr(this.suffix.length)
|
|
|
|
.split('').reverse().join('')
|
|
|
|
const imported = await import(file_path)
|
|
|
|
return { canonical_name, original_name, imported }
|
|
|
|
}
|
|
|
|
|
2020-07-21 03:54:25 +00:00
|
|
|
public get(key: string): T | undefined {
|
|
|
|
return this._items[key]
|
2020-07-06 14:53:03 +00:00
|
|
|
}
|
|
|
|
}
|