# All files / src/Page PageVueServerRenderer.ts

79.24% Statements 42/53
100% Branches 1/1
63.63% Functions 7/11
80.76% Lines 42/52

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
    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

    6x
    6x
    6x
    6x

    6x
    6x
    6x

    6x

    6x

    11x
    8x

    3x
    5x
    1x
    3x

    11x

    11x

    48x

    11x

    11x
    11x

    11x

    11x
    11x

    11x

    11x
    11x
    11x
    11x

    9x
    9x

    9x
    9x

    9x
    9x
    9x
    9x
    9x

    6x

    9x

    9x

    6x

     /* eslint-disable import/no-import-module-exports */
    /*
      Note: the function `requireFromString` causes eslint to detect a false-positive
      due to the usage of `module`. Hence, the use of the above `eslint-disable`.
    */
    import * as Vue from 'vue';
    import { createSSRApp } from 'vue';
    import { renderToString } from 'vue/server-renderer';
    import { compileTemplate } from 'vue/compiler-sfc';
    import type { SFCTemplateCompileOptions, CompilerOptions } from 'vue/compiler-sfc';

    import path from 'path';
    import fs from 'fs-extra';
    import * as logger from '../utils/logger';
    import type { PageConfig, PageAssets } from './PageConfig';
    import type { Page } from '.';
    import { PluginManager } from '../plugins/PluginManager';

    /* eslint-enable import/no-import-module-exports */

    let bundle = require('@markbind/core-web/dist/js/vueCommonAppFactory.min');

    let customElementTagsCache: Set<string> | undefined;

    /**
     * Retrieves the set of tags that should be treated as custom elements by the Vue compiler.
     * These are tags defined in plugins with isCustomElement: true.
     */
    function getCustomElementTags(): Set<string> {
      if (customElementTagsCache) {
        return customElementTagsCache;
      }
      customElementTagsCache = new Set(Object.entries(PluginManager.tagConfig)
        .filter(([, config]) => config.isCustomElement)
        .map(([tagName]) => tagName));
      return customElementTagsCache;
    }

    /**
     * Compiles a Vue page template into a JavaScript function returning render function
     * and saves it as a script file so that the browser can access to
     * generate VDOM during Vue mounting and conduct patching.
     *
     * This is to avoid the overhead of compiling the page into Vue application
     * on the client's browser (alleviates FOUC). It is also the pre-requisite to enable SSR.
     * See https://github.com/vuejs/core/blob/main/packages/compiler-core/src/options.ts for
     * compilerOptionTypes
     *
     * @param content Page content to be compiled into Vue app
     */
    async function compileVuePageCreateAndReturnScript(
      content: string, pageConfig: PageConfig, pageAsset: PageAssets) {
      const customElementTags = getCustomElementTags();

      const compilerOptions: CompilerOptions = {
        runtimeModuleName: 'vue',
        runtimeGlobalName: 'Vue',
        mode: 'function',
        whitespace: 'preserve',
        isCustomElement: tag => customElementTags.has(tag),
      };

      const templateOptions: SFCTemplateCompileOptions = {
        source: content,
        filename: pageConfig.sourcePath,
        id: pageConfig.sourcePath,
        compilerOptions,
      };
      const compiled = compileTemplate(templateOptions);
      const outputContent = compiled.code;

      const scriptContent = `
        const renderFn = new Function(${JSON.stringify(outputContent)});
        var render = renderFn();
      `;

      // Get script file name
      const pageHtmlFileName = path.basename(pageConfig.resultPath, '.html');
      const scriptFileName = `${pageHtmlFileName}.page-vue-render.js`;

      /*
       * Add the script file path for this page's render function to the page's assets (to populate page.njk).
       * The script file path is the same as the page's file path.
       */
      pageAsset.pageVueRenderJs = scriptFileName;

      // Get script's absolute file path to output script file
      const dirName = path.dirname(pageConfig.resultPath);
      const filePath = path.join(dirName, scriptFileName);
      await fs.outputFile(filePath, scriptContent);
      return outputContent;
    }

    /**
     * Referenced from stackOverflow:
     * https://stackoverflow.com/questions/17581830/load-node-js-module-from-string-in-memory
     *
     * Credits to Dominic
     */
    function requireFromString(src: string, filename: string) {
      const m = new (module.constructor as any)();
      m.paths = module.paths; // without this, we won't be able to require Vue in the string module
      m._compile(src, filename);
      return m.exports;
    }

    /**
     * Renders Vue page app into html string (Vue SSR).
     * This function will install the MarkBindVue plugin and render the built Vue page content into html string.
     */
    async function renderVuePage(renderFn: string): Promise<string> {
      const { MarkBindVue, appFactory } = bundle;
      const { plugin } = MarkBindVue;

      // Pass in Vue which is expected to be available globally
      // eslint-disable-next-line @typescript-eslint/no-implied-eval
      const render = new Function('Vue', renderFn)(Vue);
      const app = createSSRApp({
        render,
        ...appFactory(),
      });
      app.use(plugin);
      app.config.compilerOptions.whitespace = 'preserve';
      const html = await renderToString(app);
      const wrappedHtml = `<div id="app">${html}</div>`;
      return wrappedHtml;
    }

    interface PageEntry {
      page: Page;
      renderFn: string;
      pageNav: string;
    }

    // hold the mapping of sourcePath to latest built pages (for hot-reload dev purposes)
    const pageEntries: Record<string, PageEntry> = {};

    function savePageRenderFnForHotReload(page: Page, pageNav: string, renderFn: string) {
      const pageEntry = {
        page,
        pageNav,
        renderFn,
      };
      pageEntries[page.pageConfig.sourcePath] = pageEntry;
    }

    /**
     * Retrieves the latest updated MarkBindVue bundle from webpack compiler watcher,
     * re-render all the built pages, and output the page html files.
     * This function will only be used in development mode (for MarkBindVue bundle hot-reloading purposes).
     */
    async function updateMarkBindVueBundle(newBundle: string): Promise<void> {
      logger.info(`Changes detected in MarkBind Vue Source Files:
    Bundle is regenerated by webpack and built pages are re-rendered with the latest bundle.`);

      // reassign the latest updated MarkBindVue bundle
      bundle = requireFromString(newBundle, '');

      Object.values(pageEntries).forEach(async (pageEntry) => {
        const { page, renderFn } = pageEntry;
        const renderedVuePageContent = await renderVuePage(renderFn);
        page.writeOutputFile(renderedVuePageContent);
      });
    }

    export const pageVueServerRenderer = {
      compileVuePageCreateAndReturnScript,
      renderVuePage,
      updateMarkBindVueBundle,
      savePageRenderFnForHotReload,
    };