All files / src/lib/compiler compileTilesets.ts

52.63% Statements 10/19
0% Branches 0/4
33.33% Functions 1/3
52.63% Lines 10/19

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 641x 1x 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 { TilesetData } from "shared/lib/entities/entitiesTypes";
import { readFileToTilesDataArray } from "lib/tiles/readFileToTiles";
import { tileArrayToTileData } from "shared/lib/tiles/tileData";
 
type CompileTilesetOptions = {
  warnings: (msg: string) => void;
};
 
export type PrecompiledTilesetData = TilesetData & {
  id: string;
  data: Uint8Array;
};
 
const tilesetBuildCache: Record<
  string,
  {
    timestamp: number;
    data: Uint8Array;
  }
> = {};
 
const compileTilesets = async (
  tilesets: TilesetData[],
  projectRoot: string,
  { warnings: _ }: CompileTilesetOptions
): Promise<PrecompiledTilesetData[]> => {
  const tilesetData = await promiseLimit(
    10,
    tilesets.map((tileset) => {
      return async (): Promise<PrecompiledTilesetData> => {
        const filename = assetFilename(projectRoot, "tilesets", tileset);
        const modifiedTime = await getFileModifiedTime(filename);
        let data;
 
        if (
          tilesetBuildCache[tileset.id] &&
          tilesetBuildCache[tileset.id].timestamp >= modifiedTime
        ) {
          data = tilesetBuildCache[tileset.id].data;
        } else {
          const tileData = await readFileToTilesDataArray(filename);
          data = tileArrayToTileData(tileData);
          tilesetBuildCache[tileset.id] = {
            data,
            timestamp: modifiedTime,
          };
        }
 
        return {
          ...tileset,
          data,
        };
      };
    })
  );
 
  return tilesetData;
};
 
export default compileTilesets;