11import type { SourceMap } from './source-map'
2- import type { EngineOptions , Filters , Globals , Render , Script , Tag } from './types'
2+ import type { EngineOptions , Filters , Globals , Script , Tag } from './types'
33import { Compiler } from './compiler'
44import { escape } from './escape'
55import * as filters from './filters'
@@ -25,7 +25,11 @@ export const defaultOptions: Required<EngineOptions> = {
2525 cache : false ,
2626}
2727
28- const cache = new Map < string , Render > ( )
28+ const cache = new Map < string , {
29+ template : string
30+ script : Script
31+ sourcemap : SourceMap
32+ } > ( )
2933
3034export class Engine {
3135 protected options : Required < EngineOptions >
@@ -49,46 +53,43 @@ export class Engine {
4953 Object . assign ( this . options . tags , tags )
5054 }
5155
52- async load ( filepath : string ) {
56+ async render (
57+ template : string ,
58+ globals : Globals ,
59+ ) {
60+ const { script, sourcemap } = await this . _compile ( template )
61+ return this . _render ( template , globals , script , sourcemap )
62+ }
63+
64+ async renderFile ( filepath : string , globals : Globals ) {
5365 if ( this . options . cache && cache . has ( filepath ) ) {
54- return cache . get ( filepath )
66+ const { template, script, sourcemap } = cache . get ( filepath ) !
67+ return this . _render ( template , globals , script , sourcemap )
5568 }
5669
5770 const template = await this . options . loader ! ( filepath )
58-
59- return {
60- template,
61- compile : async ( ) => this . compile ( template , filepath ) ,
71+ const { script, sourcemap } = await this . _compile ( template )
72+ if ( this . options . cache ) {
73+ cache . set ( filepath , { template, script, sourcemap } )
6274 }
75+ return this . _render ( template , globals , script , sourcemap )
6376 }
6477
65- async compile ( template : string , filepath ?: string ) {
66- const { value , script , sourcemap } = await new Compiler ( this . options ) . compile (
78+ private async _compile ( template : string , filepath ?: string ) {
79+ return new Compiler ( this . options ) . compile (
6780 await new Tokenizer ( this . options ) . parse ( template ) ,
81+ filepath ,
6882 )
69-
70- const render = async ( globals : Globals ) => this . render ( globals , script , template , sourcemap )
71-
72- if ( this . options . cache && filepath ) {
73- cache . set ( filepath , render )
74- }
75-
76- return {
77- value,
78- script,
79- sourcemap,
80- render,
81- }
8283 }
8384
84- async render (
85- globals : Globals ,
86- func : Script ,
85+ private async _render (
8786 template : string ,
87+ globals : Globals ,
88+ script : Script ,
8889 sourcemap : SourceMap ,
8990 ) {
9091 try {
91- return await func (
92+ return await script (
9293 { ...this . options . globals , ...globals } ,
9394 { ...this . options . filters , ...filters } ,
9495 ( v : unknown ) => {
0 commit comments