All files / src/lib/compiler compileAvatars.ts

42.86% Statements 9/21
0% Branches 0/5
33.33% Functions 1/3
42.86% Lines 9/21

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 731x 1x 1x 1x                                     1x   1x         1x                                                                             1x     1x  
import promiseLimit from "lib/helpers/promiseLimit";
import getFileModifiedTime from "lib/helpers/fs/getModifiedTime";
import { assetFilename } from "shared/lib/helpers/assets";
import { readFileToTilesData } from "lib/tiles/readFileToTiles";
import { AvatarData } from "shared/lib/entities/entitiesTypes";
 
type CompileAvatarOptions = {
  warnings: (msg: string) => void;
};
 
export type PrecompiledAvatarData = AvatarData & {
  data: Uint8Array;
  size: number;
  frames: number;
};
 
const avatarBuildCache: Record<
  string,
  {
    timestamp: number;
    data: Uint8Array;
  }
> = {};
 
const compileAvatars = async (
  avatars: AvatarData[],
  projectRoot: string,
  { warnings }: CompileAvatarOptions
) => {
  const avatarData = await promiseLimit(
    10,
    avatars.map((avatar) => {
      return async (): Promise<PrecompiledAvatarData> => {
        const filename = assetFilename(projectRoot, "avatars", avatar);
        const modifiedTime = await getFileModifiedTime(filename);
        let data;
 
        if (
          avatarBuildCache[avatar.id] &&
          avatarBuildCache[avatar.id].timestamp >= modifiedTime
        ) {
          data = avatarBuildCache[avatar.id].data;
        } else {
          data = await readFileToTilesData(filename);
          avatarBuildCache[avatar.id] = {
            data,
            timestamp: modifiedTime,
          };
        }
 
        const size = data.length;
        const frames = Math.ceil(size / 64);
        Iif (Math.ceil(size / 64) !== Math.floor(size / 64)) {
          warnings(
            `Avatar '${avatar.filename}' has invalid dimensions and may not appear correctly. Must be 16px tall and a multiple of 16px wide.`
          );
        }
 
        return {
          ...avatar,
          data,
          size,
          frames,
        };
      };
    })
  );
 
  return avatarData;
};
 
export default compileAvatars;