All files / src/Site SitePagesManager.ts

69.76% Statements 60/86
71.11% Branches 32/45
61.76% Functions 21/34
71.05% Lines 54/76

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 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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334                                                          2x 2x   2x       2x                                                                                                                     17x 17x 17x     17x 17x 17x 17x 17x 17x 17x       5x             10x 10x 10x 10x 10x   10x       10x                                                                                                     10x             2x 2x 3x   2x         26x 26x                             18x 40x     18x 18x 14x 1x 18x 1x   38x 26x 26x                       17x 17x 38x 38x       17x 17x 17x 17x                                                                                                 7x   7x         7x       7x             8x                 9x                        
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import walkSync from 'walk-sync';
import { Template as NunjucksTemplate } from 'nunjucks';
 
import { Page } from '../Page/index.js';
import { PageConfig } from '../Page/PageConfig.js';
import { VariableProcessor } from '../variables/VariableProcessor.js';
import { VariableRenderer } from '../variables/VariableRenderer.js';
import { ExternalManager } from '../External/ExternalManager.js';
import { SiteLinkManager } from '../html/SiteLinkManager.js';
import { PluginManager } from '../plugins/PluginManager.js';
import type { FrontMatter } from '../plugins/Plugin.js';
import {
  TEMPLATE_SITE_ASSET_FOLDER_NAME,
  _,
  CONFIG_FOLDER_NAME,
  SITE_FOLDER_NAME,
  LAYOUT_SITE_FOLDER_NAME,
  FAVICON_DEFAULT_PATH,
  USER_VARIABLES_PATH,
  PAGE_TEMPLATE_NAME,
} from './constants.js';
import * as fsUtil from '../utils/fsUtil.js';
import * as logger from '../utils/logger.js';
import { SiteConfig, SiteConfigPage } from './SiteConfig.js';
import { LayoutManager } from '../Layout/index.js';
 
const __filepath = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filepath);
 
const url = {
  join: path.posix.join,
};
 
const HIGHLIGHT_ASSETS: Record<string, string> = {
  dark: 'codeblock-dark.min.css',
  light: 'codeblock-light.min.css',
};
 
/*
 * A page configuration object.
 */
export type PageCreationConfig = {
  externalScripts: string[],
  frontmatter: FrontMatter,
  layout?: string,
  pageSrc: string,
  searchable: boolean,
  faviconUrl?: string,
  glob?: string,
  globExclude?: string
  title?: string,
  fileExtension?: string,
};
 
export type AddressablePage = {
  frontmatter?: FrontMatter,
  layout?: string,
  searchable?: string | boolean,
  src: string,
  externalScripts?: string[],
  faviconUrl?: string,
  title?: string,
  fileExtension?: string,
};
 
/**
 * Manages the lifecycle and configuration of pages within the site.
 * Handles page creation, collection of addressable pages, and dependency tracking.
 */
export class SitePagesManager {
  rootPath: string;
  outputPath: string;
  pageTemplatePath: string;
  pageTemplate: NunjucksTemplate;
  pages: Page[];
  addressablePages: AddressablePage[];
  addressablePagesSource: string[];
  siteConfig!: SiteConfig;
 
  // Managers
  variableProcessor!: VariableProcessor;
  pluginManager!: PluginManager;
  siteLinkManager!: SiteLinkManager;
  externalManager!: ExternalManager;
  layoutManager!: LayoutManager;
  baseUrlMap: Set<string>;
 
  isDevMode: boolean;
 
  pagefindIndexingSucceeded: boolean;
 
  constructor(rootPath: string, outputPath: string, isDevMode: boolean) {
    this.rootPath = rootPath;
    this.outputPath = outputPath;
    this.isDevMode = isDevMode;
 
    // Page template path
    this.pageTemplatePath = path.join(__dirname, '../Page', PAGE_TEMPLATE_NAME);
    this.pageTemplate = VariableRenderer.compile(fs.readFileSync(this.pageTemplatePath, 'utf8'));
    this.pages = [];
    this.addressablePages = [];
    this.addressablePagesSource = [];
    this.baseUrlMap = new Set();
    this.pagefindIndexingSucceeded = true;
  }
 
  setBaseUrlMap(baseUrlMap: Set<string>) {
    this.baseUrlMap = baseUrlMap;
  }
 
  /**
   * Create a Page object from the site and page creation config.
   */
  createPage(config: PageCreationConfig): Page {
    const sourcePath = path.join(this.rootPath, config.pageSrc);
    const outputExtension = config.fileExtension || '.html';
    const relativePath = fsUtil.ensurePosix(path.relative(this.rootPath, sourcePath));
    const outputPath = fsUtil.setExtension(relativePath, outputExtension);
    const resultPath = path.join(this.outputPath, outputPath);
 
    const baseAssetsPath = path.posix.join(
      this.siteConfig.baseUrl || '/', TEMPLATE_SITE_ASSET_FOLDER_NAME,
    );
 
    const pageConfig = new PageConfig({
      asset: {
        bootstrap: path.posix.join(baseAssetsPath, 'css', 'bootstrap.min.css'),
        externalScripts: _.union(this.siteConfig.externalScripts, config.externalScripts),
        fontAwesome: path.posix.join(baseAssetsPath, 'fontawesome', 'css', 'all.min.css'),
        glyphicons: path.posix.join(baseAssetsPath, 'glyphicons', 'css', 'bootstrap-glyphicons.min.css'),
        octicons: path.posix.join(baseAssetsPath, 'css', 'octicons.css'),
        materialIcons: path.posix.join(baseAssetsPath, 'material-icons', 'material-icons.css'),
        bootstrapIcons: path.posix.join(baseAssetsPath, 'bootstrap-icons', 'font', 'bootstrap-icons.css'),
        highlightLight: path.posix.join(baseAssetsPath, 'css', HIGHLIGHT_ASSETS.light),
        highlightDark: path.posix.join(baseAssetsPath, 'css', HIGHLIGHT_ASSETS.dark),
        markBindCss: path.posix.join(baseAssetsPath, 'css', 'markbind.min.css'),
        markBindJs: path.posix.join(baseAssetsPath, 'js', 'markbind.min.js'),
        pageNavCss: path.posix.join(baseAssetsPath, 'css', 'page-nav.css'),
        siteNavCss: path.posix.join(baseAssetsPath, 'css', 'site-nav.css'),
        bootstrapUtilityJs: path.posix.join(baseAssetsPath, 'js', 'bootstrap-utility.min.js'),
        themeManagerJs: path.posix.join(baseAssetsPath, 'js', 'theme-manager.js'),
        codeThemeJs: path.posix.join(baseAssetsPath, 'js', 'code-theme.js'),
        polyfillJs: path.posix.join(baseAssetsPath, 'js', 'polyfill.min.js'),
        // We use development Vue when MarkBind is served in 'dev' mode so that hydration issues are reported
        vue: this.isDevMode
          ? 'https://cdn.jsdelivr.net/npm/vue@3.3.11/dist/vue.global.min.js'
          : path.posix.join(baseAssetsPath, 'js', 'vue.global.prod.min.js'),
        layoutUserScriptsAndStyles: [],
        pagefindJs: this.siteConfig.enableSearch && this.pagefindIndexingSucceeded
          ? path.posix.join(baseAssetsPath, 'pagefind', 'pagefind.js')
          : undefined,
        pagefindLazyLoaderJs: this.siteConfig.enableSearch && this.pagefindIndexingSucceeded
          ? path.posix.join(baseAssetsPath, 'js', 'pagefind-lazyloader.js')
          : undefined,
      },
      baseUrlMap: this.baseUrlMap,
      dev: this.isDevMode,
      faviconUrl: config.faviconUrl,
      frontmatterOverride: config.frontmatter,
      layout: config.layout,
      layoutsAssetPath: path.posix.join(baseAssetsPath, LAYOUT_SITE_FOLDER_NAME),
      pluginManager: this.pluginManager,
      resultPath,
      rootPath: this.rootPath,
      searchable: this.siteConfig.enableSearch && config.searchable,
      siteLinkManager: this.siteLinkManager,
      siteOutputPath: this.outputPath,
      sourcePath,
      src: config.pageSrc,
      title: config.title,
      template: this.pageTemplate,
      variableProcessor: this.variableProcessor,
      addressablePagesSource: this.addressablePagesSource,
      layoutManager: this.layoutManager,
    });
    return new Page(pageConfig, this.siteConfig);
  }
 
  /**
   * Updates the paths to be traversed as addressable pages and returns a list of filepaths to be deleted
   */
  updateAddressablePages() {
    const oldAddressablePagesSources = this.addressablePages.slice().map(page => page.src);
    this.collectAddressablePages();
    const newAddressablePagesSources = this.addressablePages.map(page => page.src);
 
    return _.difference(oldAddressablePagesSources, newAddressablePagesSources)
      .map(filePath => fsUtil.setExtension(filePath, '.html'));
  }
 
  getPageGlobPaths(page: SiteConfigPage, pagesExclude: string[]) {
    const pageGlobs = page.glob ?? [];
    return walkSync(this.rootPath, {
      directories: false,
      globs: Array.isArray(pageGlobs) ? pageGlobs : [pageGlobs],
      ignore: [
        CONFIG_FOLDER_NAME,
        SITE_FOLDER_NAME,
        ...pagesExclude.concat(page.globExclude || []),
      ],
    });
  }
 
  /**
   * Collects the paths to be traversed as addressable pages
   */
  collectAddressablePages() {
    const { pages, pagesExclude } = this.siteConfig;
    const pagesFromSrc = _.flatMap(pages.filter(page => page.src), page => (Array.isArray(page.src)
      ? page.src.map(pageSrc => ({ ...page, src: pageSrc }))
      : [page])) as unknown as AddressablePage[];
    const set = new Set();
    const duplicatePages = pagesFromSrc
      .filter(page => set.size === set.add(page.src).size)
      .map(page => page.src);
    if (duplicatePages.length > 0) {
      throw new Error(`Duplicate page entries found in site config: ${_.uniq(duplicatePages).join(', ')}`);
    }
    const pagesFromGlobs = _.flatMap(pages.filter(page => page.glob),
                                     page => this.getPageGlobPaths(page, pagesExclude)
                                       .map(filePath => ({
                                         src: filePath,
                                         searchable: page.searchable,
                                         layout: page.layout,
                                         frontmatter: page.frontmatter,
                                         fileExtension: page.fileExtension,
                                       }))) as AddressablePage[];
    /*
     Add pages collected from globs and merge properties for pages
     Page properties collected from src have priority over page properties from globs,
     while page properties from later entries take priority over earlier ones.
     */
    const filteredPages: Record<string, AddressablePage> = {};
    pagesFromGlobs.concat(pagesFromSrc).forEach((page) => {
      const filteredPage = _.omitBy(page, _.isUndefined) as AddressablePage;
      filteredPages[page.src] = page.src in filteredPages
        ? { ...filteredPages[page.src], ...filteredPage }
        : filteredPage;
    });
    this.addressablePages = Object.values(filteredPages);
    this.addressablePagesSource.length = 0;
    this.addressablePages.forEach((page) => {
      this.addressablePagesSource.push(fsUtil.removeExtensionPosix(page.src));
    });
  }
 
  /**
   * Creates new pages and replaces the original pages with the updated version
   */
  updatePages(pagesToUpdate: AddressablePage[]) {
    pagesToUpdate.forEach((pageToUpdate) => {
      this.pages.forEach((page, index) => {
        Iif (page.pageConfig.src === pageToUpdate.src) {
          const newPage = this.createNewPage(pageToUpdate, this.getFavIconUrl());
          newPage.resetState();
          this.pages[index] = newPage;
        }
      });
    });
  }
 
  /**
   * Checks if a specified file path is a dependency of a page
   * @param filePath file path to check
   * @returns whether the file path is a dependency of any of the site's pages
   */
  isDependencyOfPage(filePath: string): boolean {
    return this.pages.some(page => page.isDependency(filePath))
      || fsUtil.ensurePosix(filePath).endsWith(USER_VARIABLES_PATH);
  }
 
  /**
   * Checks if a specified file path satisfies a src or glob in any of the page configurations.
   * @param filePath file path to check
   * @returns whether the file path satisfies any glob
   */
  isFilepathAPage(filePath: string): boolean {
    const { pages, pagesExclude } = this.siteConfig;
    const relativeFilePath = fsUtil.ensurePosix(path.relative(this.rootPath, filePath));
    const srcesFromPages = _.flatMap(pages.filter(page => page.src),
                                     page => (Array.isArray(page.src) ? page.src : [page.src]));
    Iif (srcesFromPages.includes(relativeFilePath)) {
      return true;
    }
 
    const filePathsFromGlobs = _.flatMap(pages.filter(page => page.glob),
                                         page => this.getPageGlobPaths(page, pagesExclude));
    return filePathsFromGlobs.some(fp => fp === relativeFilePath);
  }
 
  getFavIconUrl() {
    const { baseUrl, faviconPath } = this.siteConfig;
 
    Iif (faviconPath) {
      Iif (!fs.existsSync(path.join(this.rootPath, faviconPath))) {
        logger.warn(`${faviconPath} does not exist`);
      }
      return url.join('/', baseUrl, faviconPath);
    } else Iif (fs.existsSync(path.join(this.rootPath, FAVICON_DEFAULT_PATH))) {
      return url.join('/', baseUrl, FAVICON_DEFAULT_PATH);
    }
 
    return undefined;
  }
 
  /**
   * Maps an array of addressable pages to an array of Page object
   */
  mapAddressablePagesToPages(addressablePages: AddressablePage[], faviconUrl: string | undefined) {
    this.pages = addressablePages.map(page => this.createNewPage(page, faviconUrl));
  }
 
  /**
   * Creates and returns a new Page with the given page config details and favicon url
   * @param page config
   * @param faviconUrl of the page
   */
  createNewPage(page: AddressablePage, faviconUrl: string | undefined) {
    return this.createPage({
      faviconUrl,
      pageSrc: page.src,
      title: page.title,
      layout: page.layout,
      frontmatter: page.frontmatter || {},
      searchable: page.searchable !== 'no' && page.searchable !== false,
      externalScripts: page.externalScripts || [],
      fileExtension: page.fileExtension,
    });
  }
}