1- import { readdir , readFile , stat } from "node:fs/promises" ;
2- import { relative , resolve , sep } from "node:path" ;
3- import { FileSystemTree } from "@webcontainer/api" ;
1+ import { resolve } from "node:path" ;
2+ import { snapshot } from "@webcontainer/snapshot" ;
43import type { BrowserCommand } from "vitest/node" ;
54
65// custom command to read directories from browser context. Used for mounting directories inside webcontainer
76export const readDirectory : BrowserCommand < [ directory : string ] > = async (
87 context ,
98 directory ,
10- ) : Promise < FileSystemTree > => {
9+ ) : Promise < string > => {
1110 const root = context . project . config . root ;
1211 const resolved = resolve ( root , directory ) ;
1312
@@ -21,55 +20,7 @@ export const readDirectory: BrowserCommand<[directory: string]> = async (
2120 ) ;
2221 }
2322
24- const files = await recursiveRead ( directory ) ;
25- const tree : FileSystemTree = { } ;
23+ const tree = await snapshot ( directory ) ;
2624
27- for ( const { filePath, contents } of files ) {
28- const segments = filePath . split ( "/" ) ;
29-
30- let currentTree : FileSystemTree = tree ;
31-
32- for ( let i = 0 ; i < segments . length ; i ++ ) {
33- const name = segments [ i ] ;
34-
35- if ( i === segments . length - 1 ) {
36- currentTree [ name ] = { file : { contents } } ;
37- } else {
38- let folder = currentTree [ name ] ;
39-
40- if ( ! folder || ! ( "directory" in folder ) ) {
41- folder = { directory : { } } ;
42- currentTree [ name ] = folder ;
43- }
44-
45- currentTree = folder . directory ;
46- }
47- }
48- }
49-
50- return tree ;
51-
52- async function recursiveRead (
53- dir : string ,
54- ) : Promise < { filePath : string ; contents : string } [ ] > {
55- const files = await readdir ( dir ) ;
56-
57- const output = await Promise . all (
58- files . map ( async ( file ) => {
59- const filePath = resolve ( dir , file ) ;
60- const fileStat = await stat ( filePath ) ;
61-
62- if ( fileStat . isDirectory ( ) ) {
63- return recursiveRead ( filePath ) ;
64- }
65-
66- return {
67- filePath : relative ( directory , filePath ) . replaceAll ( sep , "/" ) ,
68- contents : await readFile ( filePath , "utf-8" ) ,
69- } ;
70- } ) ,
71- ) ;
72-
73- return output . flat ( ) ;
74- }
25+ return tree . toString ( "base64" ) ;
7526} ;
0 commit comments