2022-10-19 07:52:29 +00:00
|
|
|
import { base64Decode, base64EncodedDataUrl } from "./base64.ts";
|
2022-10-12 09:47:13 +00:00
|
|
|
import { mime } from "../deps.ts";
|
|
|
|
|
2022-10-13 13:16:18 +00:00
|
|
|
type DataUrl = string;
|
|
|
|
|
|
|
|
// Mapping from path -> `data:mimetype;base64,base64-encoded-data` strings
|
|
|
|
export type AssetJson = Record<string, DataUrl>;
|
2022-10-12 09:47:13 +00:00
|
|
|
|
|
|
|
export class AssetBundle {
|
|
|
|
readonly bundle: AssetJson;
|
|
|
|
|
|
|
|
constructor(bundle: AssetJson = {}) {
|
|
|
|
this.bundle = bundle;
|
|
|
|
}
|
|
|
|
|
|
|
|
has(path: string): boolean {
|
|
|
|
return path in this.bundle;
|
|
|
|
}
|
|
|
|
|
|
|
|
listFiles(): string[] {
|
|
|
|
return Object.keys(this.bundle);
|
|
|
|
}
|
|
|
|
|
|
|
|
readFileSync(
|
|
|
|
path: string,
|
|
|
|
): Uint8Array {
|
|
|
|
const content = this.bundle[path];
|
|
|
|
if (!content) {
|
|
|
|
throw new Error(`No such file ${path}`);
|
|
|
|
}
|
|
|
|
const data = content.split(",", 2)[1];
|
|
|
|
return base64Decode(data);
|
|
|
|
}
|
|
|
|
|
|
|
|
readFileAsDataUrl(path: string): string {
|
|
|
|
const content = this.bundle[path];
|
|
|
|
if (!content) {
|
|
|
|
throw new Error(`No such file ${path}`);
|
|
|
|
}
|
|
|
|
return content;
|
|
|
|
}
|
|
|
|
|
|
|
|
readTextFileSync(
|
|
|
|
path: string,
|
|
|
|
): string {
|
|
|
|
return new TextDecoder().decode(this.readFileSync(path));
|
|
|
|
}
|
|
|
|
|
|
|
|
getMimeType(
|
|
|
|
path: string,
|
|
|
|
): string {
|
|
|
|
const content = this.bundle[path];
|
|
|
|
if (!content) {
|
|
|
|
throw new Error(`No such file ${path}`);
|
|
|
|
}
|
|
|
|
return content.split(";")[0].split(":")[1];
|
|
|
|
}
|
|
|
|
|
|
|
|
writeFileSync(path: string, data: Uint8Array) {
|
2023-01-01 19:28:25 +00:00
|
|
|
// Replace \ with / for windows
|
|
|
|
path = path.replaceAll("\\", "/");
|
2022-10-19 07:52:29 +00:00
|
|
|
const mimeType = mime.getType(path) || "application/octet-stream";
|
|
|
|
this.bundle[path] = base64EncodedDataUrl(mimeType, data);
|
2022-10-12 09:47:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
writeTextFileSync(path: string, s: string) {
|
|
|
|
this.writeFileSync(path, new TextEncoder().encode(s));
|
|
|
|
}
|
|
|
|
|
|
|
|
toJSON(): AssetJson {
|
|
|
|
return this.bundle;
|
|
|
|
}
|
|
|
|
}
|