All files / src resource-injector.ts

100% Statements 79/79
92.31% Branches 48/52
100% Functions 22/22
100% Lines 73/73
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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252    8x   8x 8x 8x     8x                       51x 51x   51x 51x 51x 51x   51x                 48x 28x 19x 19x 1x 1x 1x 1x       19x                     43x                               44x 44x               44x         44x 63x     44x 2x 2x 2x   44x                     61x 11x 50x 49x     1x                       63x 63x 63x 50x 50x   50x 6x 6x 6x 6x       50x 3x 3x 3x                         124x 111x 105x   6x               51x 74x 61x 61x 61x 61x 61x   51x     46x                   61x 46x                                 61x 37x 37x 1x                             61x                         20x 12x                    
import { FragmentStorefront } from "./fragment";
import {ICookieMap, IWrappingJsAsset} from "./types";
import {EVENT, RESOURCE_LOADING_TYPE, RESOURCE_TYPE} from "./lib/enums";
import {IPageFragmentConfig, IPageLibAsset, IPageLibConfiguration, IPageLibDependency} from "./lib/types";
import ResourceFactory from "./resourceFactory";
import {RESOURCE_INJECT_TYPE, RESOURCE_JS_EXECUTE_TYPE} from "./enums";
import CleanCSS from "clean-css";
import {nrSegmentAsync} from "./decorators";
 
export default class ResourceInjector {
 
    private readonly fragments: { [name: string]: FragmentStorefront };
    private readonly pageName: string | undefined;
    private readonly cookies: ICookieMap;
 
    private readonly fragmentFingerPrints: IPageFragmentConfig[];
    private readonly assets: IPageLibAsset[];
    private readonly dependencies: IPageLibDependency[];
    private libraryConfig: IPageLibConfiguration;
 
    constructor(fragments: { [name: string]: FragmentStorefront }, pageName:string | undefined, cookies: ICookieMap) {
        this.fragments = fragments;
        this.cookies = cookies;
 
        this.fragmentFingerPrints = [];
        this.assets = [];
        this.dependencies = [];
        this.pageName = pageName;
 
        this.prepare();
    }
 
    /**
     * Injects prepared assets to dom
     * @param { CheerioStatic } dom
     * @returns {Promise<void>}
     */
    injectAssets(dom: CheerioStatic) {
        this.assets.forEach(asset => {
            if (asset.loadMethod === RESOURCE_LOADING_TYPE.ON_RENDER_START) {
                asset.preLoaded = true;
                if (Array.isArray(asset.dependent) && asset.dependent.length > 0) {
                    this.dependencies.forEach(dependency => {
                        Eif (Array.isArray(asset.dependent) && asset.dependent.indexOf(dependency.name) > -1 && !dependency.preLoaded) {
                            dependency.preLoaded = true;
                            ResourceInjector.injectDefaultJsAsset(dependency, dom);
                        }
                    });
                }
                ResourceInjector.injectDefaultJsAsset(asset, dom);
            }
        });
    }
 
    /**
     * Injects library config to dom
     * @param { CheerioStatic } dom
     * @returns {Promise<void>}
     */
    injectLibraryConfig(dom: CheerioStatic) {
        dom('head').prepend(ResourceInjector.wrapJsAsset({
            content: `{puzzleLibContent}PuzzleJs.emit('${EVENT.ON_RENDER_START}');PuzzleJs.emit('${EVENT.ON_CONFIG}','${JSON.stringify(this.libraryConfig)}');`,
            injectType: RESOURCE_INJECT_TYPE.INLINE,
            name: 'puzzle-lib',
            link: '',
            executeType: RESOURCE_JS_EXECUTE_TYPE.SYNC
        }));
    }
 
    /**
     * Merges, minifies stylesheets and inject them to dom
     * @param { CheerioStatic } dom
     * @param { boolean } precompile
     * @returns {Promise<void>}
     */
    async injectStyleSheets(dom: CheerioStatic, precompile: boolean) {
        return new Promise(async (resolve) => {
            const _CleanCss = new CleanCSS({
                level: {
                    1: {
                        all: true
                    }
                }
            } as any);
 
            const cssData: {[name: string]: string[]} = {
                styleSheets: [],
                dependencyNames: []
            };
 
            for (const fragment of Object.values(this.fragments)) {
                await this.loadCSSData(cssData, fragment, precompile);
            }
 
            if (cssData.styleSheets.length > 0) {
                const output = _CleanCss.minify(cssData.styleSheets.join(''));
                const addEscapeCharacters = output.styles.replace(/content:"/g, 'content:"\\');
                dom('head').append(`<style puzzle-dependency="dynamic-css" dependency-list="${cssData.dependencyNames.join(',')}">${addEscapeCharacters}</style>`);
            }
            resolve();
        });
    }
 
    /**
     * Wraps js asset based on its configuration
     * @param {IWrappingJsAsset} asset
     * @returns {string}
     */
    // @nrSegmentAsync("template.wrapJsAsset", true)
    static wrapJsAsset(asset: IWrappingJsAsset) {
        if (asset.injectType === RESOURCE_INJECT_TYPE.EXTERNAL && asset.link) {
            return `<script puzzle-dependency="${asset.name}" src="${asset.link}" type="text/javascript"${asset.executeType}> </script>`;
        } else if (asset.injectType === RESOURCE_INJECT_TYPE.INLINE && asset.content) {
            return `<script puzzle-dependency="${asset.name}" type="text/javascript">${asset.content}</script>`;
        } else {
            //todo handle error
            return `<!-- Failed to inject asset: ${asset.name} -->`;
        }
    }
 
    /**
     * Load css data(stylesheets and dependency name list) and push to first parameter
     * @param { } cssData
     * @param {FragmentStorefront} fragment
     * @param {boolean} precompile
     * @returns {Promise<>}
     */
    private async loadCSSData(cssData: {[name: string]: string[]}, fragment: FragmentStorefront, precompile: boolean) {
        const targetVersion = fragment.detectVersion(this.cookies, precompile);
        const config = this.getFragmentConfig(fragment, targetVersion);
        if(config) {
            const cssAssets = config.assets.filter(asset => asset.type === RESOURCE_TYPE.CSS);
            const cssDependencies = config.dependencies.filter(dependency => dependency.type === RESOURCE_TYPE.CSS);
 
            for (const asset of cssAssets) {
                const assetContent = await fragment.getAsset(asset.name, targetVersion);
                Eif (assetContent) {
                    cssData.styleSheets.push(assetContent);
                    cssData.dependencyNames.push(asset.name);
                }
            }
 
            for (const dependency of cssDependencies) {
                Eif (!cssData.dependencyNames.includes(dependency.name)) {
                    cssData.dependencyNames.push(dependency.name);
                    cssData.styleSheets.push(await ResourceFactory.instance.getRawContent(dependency.name));
                }
            }
        }
    };
 
    /**
     * Returns fragment config using targeted version
     * @param { FragmentStorefront } fragment
     * @param { string } targetVersion
     * @returns { }
     */
    private getFragmentConfig(fragment: FragmentStorefront, targetVersion: string) {
        if(!fragment.config) return;
        if(fragment.config.version === targetVersion || !fragment.config.passiveVersions || !fragment.config.passiveVersions[targetVersion]) {
            return fragment.config;
        }
        return fragment.config.passiveVersions[targetVersion];
    }
 
    /**
     * Prepare assets, fragmentFingerPrints, dependencies and library config
     * @returns {Promise<void>}
     */
    private prepare() {
        for(let fragment of Object.values(this.fragments)) {
            if (!fragment.config) continue;
            const targetVersion = fragment.detectVersion(this.cookies);
            const config = this.getFragmentConfig(fragment, targetVersion);
            this.prepareFragmentFingerPrint(fragment);
            this.prepareAssets(config);
            this.prepareDependencies(config);
        }
        this.libraryConfig = {
            page: this.pageName,
            fragments: this.fragmentFingerPrints,
            assets: this.assets.filter(asset => asset.type === RESOURCE_TYPE.JS),
            dependencies: this.dependencies
        } as IPageLibConfiguration;
    }
 
    /**
     * Prepare injectable assets from fragment and push to this.assets
     * @param { } config
     */
    private prepareAssets(config) {
        config.assets.forEach((asset) => {
            this.assets.push({
                loadMethod: typeof asset.loadMethod !== 'undefined' ? asset.loadMethod : RESOURCE_LOADING_TYPE.ON_PAGE_RENDER,
                name: asset.name,
                dependent: asset.dependent || [],
                type: asset.type,
                link: asset.link,
                preLoaded: false
            });
        });
    }
 
    /**
     * Prepare injectable dependencies from fragment and push to this.dependencies
     * @param { } config
     * @returns {IPageFragmentConfig}
     */
    private prepareDependencies(config) {
        config.dependencies.forEach(dependency => {
            const dependencyData = ResourceFactory.instance.get(dependency.name);
            if (dependencyData && dependencyData.link && !this.dependencies.find(dependency => dependency.name === dependencyData.name)) {
                this.dependencies.push({
                    name: dependency.name,
                    link: dependencyData.link,
                    type: dependency.type,
                    preLoaded: false
                });
            }
        });
    }
 
    /**
     * Prepare fragment fingerprint from given fragment and push to this.fragmentFingerPrints
     * @param {FragmentStorefront} fragment
     */
    private prepareFragmentFingerPrint(fragment: FragmentStorefront) {
        this.fragmentFingerPrints.push({
            name: fragment.name,
            chunked: fragment.config ? (fragment.shouldWait || (fragment.config.render.static || false)) : false
        });
    }
 
    /**
     * Inject default JS assets
     * @param { } jsAsset
     * @param { CheerioStatic } dom
     * @returns {string}
     */
    private static injectDefaultJsAsset(jsAsset: {type, name, link}, dom: CheerioStatic) {
        if (jsAsset.type === RESOURCE_TYPE.JS) {
            dom('body').append(ResourceInjector.wrapJsAsset({
                content: ``,
                injectType: RESOURCE_INJECT_TYPE.EXTERNAL,
                name: jsAsset.name,
                link: jsAsset.link,
                executeType: RESOURCE_JS_EXECUTE_TYPE.SYNC
            }));
        }
    }
}