All files / src/vite css-asset.ts

97.87% Statements 46/47
96% Branches 24/25
100% Functions 7/7
100% Lines 41/41

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  2x 2x                       2x     21x 21x 21x     4x 4x 3x 3x   4x     21x       5x 5x 5x 6x 3x   3x 1x   2x       11x 11x 1x             5x 4x 4x   3x 3x 3x   2x 2x         2x       3x   2x 2x 2x   2x   1x 1x 1x   1x          
import type { Plugin } from "vite";
import MagicString from "magic-string";
import mime from "mime-types";
import type { RegisterExplicitIdFunction } from "../servicenow/types";
 
export interface ViteMetadata {
  importedCss: Set<string>;
  importedCssUrls?: Map<string, string>;
}
 
interface CssAssetPluginOptions {
  registerExplicitId?: RegisterExplicitIdFunction;
}
 
export function servicenowCssAssetPlugin(
  options: CssAssetPluginOptions = {},
): Plugin {
  const { registerExplicitId } = options;
  let serve = false;
  const idCache: Record<string, string> = {};
 
  function resolveId(diskPath: string): string {
    let id = idCache[diskPath];
    if (!id) {
      id = registerExplicitId!("sys_ux_theme_asset", diskPath);
      idCache[diskPath] = id;
    }
    return id;
  }
 
  return {
    name: "servicenow-css-asset",
    enforce: "post",
    config(config) {
      config.experimental ??= {};
      const existingRenderBuiltUrl = config.experimental.renderBuiltUrl;
      config.experimental.renderBuiltUrl = (filename, info) => {
        if (info.hostType === "js" && mime.lookup(filename) === "text/css") {
          return `/uxta/${resolveId(filename)}.assetx`;
        }
        if (existingRenderBuiltUrl) {
          return existingRenderBuiltUrl(filename, info);
        }
        return { relative: true };
      };
    },
    configResolved(config) {
      serve = config.command === "serve";
      if (!serve && !registerExplicitId) {
        throw new Error("registerExplicitId is required for build mode");
      }
    },
    // Vite's __vitePreload uses dep.endsWith(".css") to decide whether to load
    // a dependency as a stylesheet or a JS module. Our uxta URLs end with .assetx,
    // so we patch the check to also recognize .assetx as CSS.
    renderChunk(code, chunk) {
      if (serve) return null;
      const preloadHelperId = "\0vite/preload-helper.js";
      if (!chunk.moduleIds.includes(preloadHelperId)) return null;
 
      const target = 'let isCss=dep.endsWith(".css")';
      const idx = code.indexOf(target);
      if (idx === -1) return null;
 
      const s = new MagicString(code);
      s.overwrite(
        idx,
        idx + target.length,
        'let isCss=dep.endsWith(".css")||dep.endsWith(".assetx")',
      );
      return { code: s.toString(), map: s.generateMap({ hires: "boundary" }) };
    },
    // Capture the output urls in a meta object for later use in the HTML plugin
    generateBundle(_, bundle) {
      if (serve) return;
 
      for (const chunk of Object.values(bundle)) {
        Iif (chunk.type !== "chunk") continue;
        const meta = (chunk as unknown as { viteMetadata?: ViteMetadata })
          .viteMetadata;
        if (!meta?.importedCss?.size) continue;
 
        const urls = new Map<string, string>();
        for (const cssFile of meta.importedCss) {
          urls.set(cssFile, `/uxta/${resolveId(cssFile)}.assetx`);
        }
        meta.importedCssUrls = urls;
      }
    },
  };
}