All files / lib/pipeline/module/compiler scriptModule.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 4/4
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  26x 26x   26x   1669x   7x   1662x   8x           7x       8x   8x 8x 8x         15x     15x     14x 14x  
import { HtmlCompilerModule, HtmlCompilerContext } from '../htmlCompiler';
import { InternalScriptNode, ExternalScriptNode, MimeType } from '../../..';
import {resolveResPath} from '../../../fs/pathUtils';
 
export class ScriptModule implements HtmlCompilerModule {
    async enterNode(htmlContext: HtmlCompilerContext): Promise<void> {
        if (InternalScriptNode.isInternalScriptNode(htmlContext.node)) {
            // compile internal <script>
            await compileInternalScript(htmlContext.node, htmlContext);
 
        } else if (ExternalScriptNode.isExternalScriptNode(htmlContext.node)) {
            // compile external <script>
            await compileExternalScript(htmlContext.node, htmlContext);
        }
    }
}
 
async function compileInternalScript(node: InternalScriptNode, htmlContext: HtmlCompilerContext): Promise<void> {
    await compileScript(htmlContext, node.scriptContent);
}
 
async function compileExternalScript(node: ExternalScriptNode, htmlContext: HtmlCompilerContext): Promise<void> {
    const pipelineContext = htmlContext.pipelineContext;
 
    const resPath = resolveResPath(node.src, pipelineContext.fragment.path);
    const scriptContent = await pipelineContext.pipeline.getRawText(resPath, MimeType.JAVASCRIPT);
    await compileScript(htmlContext, scriptContent);
}
 
async function compileScript(htmlContext: HtmlCompilerContext, scriptText: string): Promise<void> {
    // create eval context. This will use parent scope if it exists, or else will fall back to current scope.
    const evalContext = htmlContext.createParentScopeEvalContext();
 
    // compile and execute
    await htmlContext.pipelineContext.pipeline.compileScript(scriptText, evalContext);
 
    // remove when done
    htmlContext.node.removeSelf();
    htmlContext.setDeleted();
}