143 lines
4.9 KiB
TypeScript
143 lines
4.9 KiB
TypeScript
|
import path from "path";
|
||
|
import fs from "fs";
|
||
|
import chokidar from "chokidar";
|
||
|
import {logger} from "../Logger";
|
||
|
import {afs, readdirRecursively} from "../Utils";
|
||
|
|
||
|
export default abstract class ViewEngine {
|
||
|
protected readonly viewPaths: string[];
|
||
|
|
||
|
/**
|
||
|
* @param buildDir A temporary directory that will contain any non-final or final non-public asset.
|
||
|
* @param publicDir The output directory that should contain all final and public assets.
|
||
|
* @param devWatchedViewDir The directory that should be watched in dev environment.
|
||
|
* @param additionalViewPaths By order of priority, the directories that contain all the views of the app.
|
||
|
* Swaf provided views and default ./view directory are automatically added (don't add them yourself).
|
||
|
* @protected
|
||
|
*/
|
||
|
protected constructor(
|
||
|
private readonly buildDir: string,
|
||
|
private readonly publicDir: string,
|
||
|
private readonly devWatchedViewDir: string,
|
||
|
...additionalViewPaths: string[]
|
||
|
) {
|
||
|
this.viewPaths = [
|
||
|
...additionalViewPaths.map(p => path.resolve(p)),
|
||
|
path.resolve(__dirname, '../../../views'),
|
||
|
path.resolve(__dirname, '../../views'),
|
||
|
path.resolve(__dirname, '../views'),
|
||
|
].filter(dir => fs.existsSync(dir));
|
||
|
|
||
|
if (!fs.existsSync(this.buildDir)) {
|
||
|
fs.mkdirSync(this.buildDir, {recursive: true});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public abstract getExtension(): string;
|
||
|
|
||
|
public abstract render(
|
||
|
file: string,
|
||
|
locals: Record<string, unknown>,
|
||
|
callback: (err: Error | null, output?: string) => void,
|
||
|
): Promise<void>;
|
||
|
|
||
|
public end?(): Promise<void>;
|
||
|
|
||
|
public getViewPaths(): string[] {
|
||
|
return this.viewPaths;
|
||
|
}
|
||
|
|
||
|
public getBuildDir(): string {
|
||
|
return this.buildDir;
|
||
|
}
|
||
|
|
||
|
public getPublicDir(): string {
|
||
|
return this.publicDir;
|
||
|
}
|
||
|
|
||
|
public getDevWatchedViewDir(): string {
|
||
|
return this.devWatchedViewDir;
|
||
|
}
|
||
|
|
||
|
public preCompile?(canonicalName: string, alsoCompileDependents: boolean): Promise<void>;
|
||
|
|
||
|
public afterPreCompile?(): Promise<void>;
|
||
|
|
||
|
public async preCompileAll(): Promise<void> {
|
||
|
if (this.preCompile) {
|
||
|
logger.info(`Pre-compiling ${this.getExtension()} views...`);
|
||
|
|
||
|
// List all views
|
||
|
const views: string[] = [];
|
||
|
for (const viewPath of this.viewPaths) {
|
||
|
await readdirRecursively(viewPath, async file => {
|
||
|
if (file.endsWith('.' + this.getExtension())) {
|
||
|
views.push(this.toCanonicalName(file));
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// Deduplicate and pre-compile
|
||
|
for (const canonicalName of [...new Set<string>(views)]) {
|
||
|
await this.preCompile(canonicalName, false);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
await this.afterPreCompile?.();
|
||
|
}
|
||
|
|
||
|
public onNewFile?(file: string): Promise<void>;
|
||
|
|
||
|
public onFileChange?(file: string): Promise<void>;
|
||
|
|
||
|
public async watch(): Promise<void> {
|
||
|
const watcher = chokidar.watch(this.devWatchedViewDir, {persistent: true});
|
||
|
watcher.on('ready', () => {
|
||
|
logger.debug(`Watching ${this.getExtension()} assets for changes`);
|
||
|
|
||
|
watcher.on('add', (file) => {
|
||
|
if (file.endsWith('.' + this.getExtension())) {
|
||
|
(this.onNewFile ? this.onNewFile(file) : Promise.resolve())
|
||
|
.then(() => this.preCompile?.(this.toCanonicalName(file), true))
|
||
|
.then(() => this.afterPreCompile?.())
|
||
|
.catch(err => logger.error(err));
|
||
|
}
|
||
|
});
|
||
|
|
||
|
watcher.on('change', (file) => {
|
||
|
if (file.endsWith('.' + this.getExtension())) {
|
||
|
(this.onFileChange ? this.onFileChange(file) : Promise.resolve())
|
||
|
.then(() => this.preCompile?.(this.toCanonicalName(file), true))
|
||
|
.then(() => this.afterPreCompile?.())
|
||
|
.catch(err => logger.error(err));
|
||
|
}
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
|
||
|
protected toCanonicalName(file: string): string {
|
||
|
const resolvedFilePath = path.resolve(file);
|
||
|
|
||
|
let canonicalViewName: string | null = null;
|
||
|
for (const viewPath of this.viewPaths) {
|
||
|
if (resolvedFilePath.startsWith(viewPath)) {
|
||
|
canonicalViewName = resolvedFilePath.substring(viewPath.length + 1);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (!canonicalViewName) throw new Error('view ' + file + ' not found');
|
||
|
return canonicalViewName;
|
||
|
}
|
||
|
|
||
|
protected async resolveFileFromCanonicalName(canonicalName: string): Promise<string> {
|
||
|
for (const viewPath of this.viewPaths) {
|
||
|
const tryPath = path.join(viewPath, canonicalName);
|
||
|
if (await afs.exists(tryPath)) {
|
||
|
return tryPath;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
throw new Error('View not found from canonical name ' + canonicalName);
|
||
|
}
|
||
|
}
|