-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine.ts
86 lines (69 loc) · 2.87 KB
/
engine.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { NgModuleFactory, CompilerFactory, Compiler } from 'https://jspm.dev/@angular/core@11';
import { INITIAL_CONFIG, renderModuleFactory } from './platform-server.mjs';
const { readFile } = Deno;
const decoder = new TextDecoder();
export class CommonEngine {
/** Return an instance of the platformServer compiler */
// @ts-ignore
getCompiler(): Compiler {
// @ts-ignore
const compilerFactory: CompilerFactory = this.compilerFactory;//platformCoreDynamic().injector.get(CompilerFactory);
return compilerFactory.createCompiler();
}
private factoryCacheMap = new Map<any, any>();
private readonly templateCache: Map<string, string> = new Map<string, string>()
// @ts-ignore
constructor(private compilerFactory: CompilerFactory, private moduleOrFactory?: any,
private providers: any[] = []) { }
/**
* Render an HTML document for a specific URL with specified
* render options
*/
async render(opts: any): Promise<string> {
// if opts.document dosen't exist then opts.documentFilePath must
const doc = opts.document || await this.getDocument(opts.documentFilePath as string);
const extraProviders = [
...(opts.providers || []),
...(this.providers || []),
{
provide: INITIAL_CONFIG,
useValue: {
document: doc,
url: opts.url
}
}
];
const moduleOrFactory = this.moduleOrFactory || opts.bootstrap;
const factory = await this.getFactory(moduleOrFactory);
return renderModuleFactory(factory, { extraProviders });
}
/** Return the factory for a given engine instance */
async getFactory(moduleOrFactory: any): Promise<any> {
// If module has been compiled AoT
if (moduleOrFactory instanceof NgModuleFactory) {
return moduleOrFactory;
} else {
// we're in JIT mode
const moduleFactory = this.factoryCacheMap.get(moduleOrFactory);
// If module factory is cached
if (moduleFactory) {
return moduleFactory;
}
// Compile the module and cache it
const factory = await this.getCompiler().compileModuleAsync(moduleOrFactory);
this.factoryCacheMap.set(moduleOrFactory, factory);
return factory;
}
}
/** Retrieve the document from the cache or the filesystem */
private getDocument(filePath: string): Promise<string> {
if (this.templateCache.has(filePath)) {
return Promise.resolve(this.templateCache.get(filePath) + '');
}
return readFile(filePath).then(source => {
const template: string = decoder.decode(source)
this.templateCache.set(filePath, template)
return template;
});
}
}