示例工程 15-tailwind-css-and-design-tokens

15-tailwind-css-and-design-tokens/demo-03-csp-style/check.mjs

javascript · 1.1 KB

import fs from "node:fs";
import path from "node:path";
import { gzipSync } from "node:zlib";

const dist = path.resolve("dist");
const html = fs.readFileSync(path.join(dist, "index.html"), "utf8");
const cssFile = fs
  .readdirSync(path.join(dist, "assets"))
  .find((name) => name.endsWith(".css"));
if (!cssFile) throw new Error("missing css asset");
const css = fs.readFileSync(path.join(dist, "assets", cssFile), "utf8");
const hand = fs.readFileSync("hand.css", "utf8");

const csp =
  html.match(
    /<meta[^>]+http-equiv="Content-Security-Policy"[^>]+content="([^"]+)"/,
  )?.[1] ?? "";
const hasLink = /<link[^>]+rel="stylesheet"/.test(html);
const hasInlineStyle = /<style[\s>]/.test(html);
const gzip = gzipSync(css).length;
const handGzip = gzipSync(hand).length;

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      hasLink &&
      !hasInlineStyle &&
      csp.includes("style-src 'self'") &&
      !csp.includes("unsafe-inline") &&
      css.includes("--color-primary") &&
      gzip > 0,
    cssFile,
    cssBytes: css.length,
    gzipBytes: gzip,
    handGzipBytes: handGzip,
    hasLink,
    hasInlineStyle,
    csp,
  }),
);