All files index.ts

90.91% Statements 20/22
75% Branches 12/16
100% Functions 4/4
94.74% Lines 18/19
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 491x 1x 1x         1x     4x 4x     4x 2x   4x   4x   4x 4x             1x           4x     4x         1x 4x     1x  
import axios from "axios";
import SHA384 from "crypto-js/sha384";
import Base64 from "crypto-js/enc-base64";
 
export type cdnType = "css" | "js";
export type algoType = "sha384";
 
const intergrityGen = async (url: string, type?: cdnType, algo?: algoType) => {
  // TODO: support more hashing algorithm
 
  Eif (!algo) {
    algo = "sha384";
  }
 
  if (!type) {
    type = url.endsWith("css") ? "css" : url.endsWith("js") ? "js" : undefined;
  }
  Iif (type === undefined) throw new Error("must specify type for cdn (css/js)");
 
  const { hash, data } = await axios
    .get(url)
    .then(d => ({ hash: Base64.stringify(SHA384(d.data)), data: d.data }));
  return {
    hash: hash,
    html: template(type, url, hash, algo),
    byte: byteSize(data)
  };
};
 
export const template = (
  type: cdnType,
  url: string,
  hash: string,
  algo: algoType
) => {
  Iif (type !== "css" && type !== "js")
    throw new Error("must specify type for cdn (css/js)");
 
  return type === "css"
    ? `<link rel="stylesheet" href="${url}" integrity="${algo}-${hash}" crossorigin="anonymous">`
    : `<script src="${url}" integrity="${algo}-${hash}" crossorigin="anonymous"></script>`;
};
 
export const byteSize: (data: string) => number = (data: string) => {
  return Buffer.byteLength(data, "utf8");
};
 
export default intergrityGen;