All files / src/packlets/file-system demo-fs.ts

83.33% Statements 20/24
60% Branches 6/10
80% Functions 4/5
83.33% Lines 20/24

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    1x           1x   1x 2x 2x 2x         3x     1x 1x 2x 1x 1x 1x               1x     3x   1x                   2x 2x 1x   1x        
import type { FileEntry, ProjectFileSystem } from "./types";
 
const demoModules = import.meta.glob("/examples/**/*", {
  query: "?raw",
  import: "default",
  eager: true,
});
 
const demoFiles = new Map<string, string>();
 
for (const [path, content] of Object.entries(demoModules)) {
  const relativePath = path.replace("/examples/", "");
  Eif (typeof content === "string") {
    demoFiles.set(relativePath, content);
  }
}
 
export function createFileSystemFromExample(name: string): ProjectFileSystem {
  const prefix = `${name}/`;
 
  function getEntries(): FileEntry[] {
    const entries: FileEntry[] = [];
    for (const [path] of demoFiles) {
      if (path.startsWith(prefix)) {
        const name = path.replace(prefix, "");
        const content = demoFiles.get(path) ?? "";
        entries.push({
          name,
          path,
          size: new TextEncoder().encode(content).length,
          lastModified: new Date(),
        });
      }
    }
    return entries;
  }
 
  return {
    async listFiles() {
      return getEntries();
    },
    async readFile(path: string) {
      const content = demoFiles.get(path);
      if (content === undefined) {
        throw new Error(`File not found: ${path}`);
      }
      return new TextEncoder().encode(content).buffer;
    },
    async readText(path: string) {
      const content = demoFiles.get(path);
      if (content === undefined) {
        throw new Error(`File not found: ${path}`);
      }
      return content;
    },
  };
}