1
0
silverbullet/common/spaces/asset_bundle_space_primitives.ts

84 lines
2.2 KiB
TypeScript
Raw Normal View History

import { FileMeta } from "../types.ts";
import { SpacePrimitives } from "./space_primitives.ts";
2022-10-12 09:47:13 +00:00
import { AssetBundle } from "../../plugos/asset_bundle/bundle.ts";
import { mime } from "../deps.ts";
2022-10-21 14:56:46 +00:00
const bootTime = Date.now();
export class AssetBundlePlugSpacePrimitives implements SpacePrimitives {
constructor(
private wrapped: SpacePrimitives,
private assetBundle: AssetBundle,
) {
}
async fetchFileList(): Promise<FileMeta[]> {
2023-01-13 14:41:29 +00:00
const files = await this.wrapped.fetchFileList();
return this.assetBundle.listFiles()
2022-10-12 09:47:13 +00:00
.map((p) => ({
name: p,
contentType: mime.getType(p) || "application/octet-stream",
2022-10-21 14:56:46 +00:00
lastModified: bootTime,
2022-10-12 09:47:13 +00:00
perm: "ro",
size: -1,
2023-01-13 14:41:29 +00:00
} as FileMeta)).concat(files);
}
readFile(
name: string,
): Promise<{ data: Uint8Array; meta: FileMeta }> {
2022-10-12 09:47:13 +00:00
if (this.assetBundle.has(name)) {
const data = this.assetBundle.readFileSync(name);
// console.log("Requested encoding", encoding);
return Promise.resolve({
data,
meta: {
2022-10-21 14:56:46 +00:00
lastModified: bootTime,
size: data.byteLength,
perm: "ro",
contentType: this.assetBundle.getMimeType(name),
} as FileMeta,
});
}
return this.wrapped.readFile(name);
}
getFileMeta(name: string): Promise<FileMeta> {
2022-10-12 09:47:13 +00:00
if (this.assetBundle.has(name)) {
const data = this.assetBundle.readFileSync(name);
return Promise.resolve({
2022-10-21 14:56:46 +00:00
lastModified: bootTime,
size: data.byteLength,
perm: "ro",
contentType: this.assetBundle.getMimeType(name),
} as FileMeta);
}
return this.wrapped.getFileMeta(name);
}
writeFile(
name: string,
data: Uint8Array,
2023-01-13 14:41:29 +00:00
selfUpdate?: boolean,
lastModified?: number,
): Promise<FileMeta> {
if (this.assetBundle.has(name)) {
console.warn("Attempted to write to read-only asset file", name);
return this.getFileMeta(name);
}
return this.wrapped.writeFile(
name,
data,
selfUpdate,
lastModified,
);
}
deleteFile(name: string): Promise<void> {
2022-10-12 09:47:13 +00:00
if (this.assetBundle.has(name)) {
// Quietly ignore
return Promise.resolve();
}
return this.wrapped.deleteFile(name);
}
}