1- import { KuboRPCClient } from "kubo-rpc-client" ;
1+ import { KuboRPCClient , ImportCandidate , AwaitIterable } from "kubo-rpc-client" ;
22import fs from "fs" ;
33import path from "path" ;
44
@@ -14,6 +14,26 @@ export async function ipfsAddFromFs(
1414 kuboClient : KuboRPCClient ,
1515 onProgress ?: ( percent : number ) => void
1616) : Promise < string > {
17+ // Calculate total size of all files before upload
18+ function * getStatFiles ( dir : string ) : Generator < string > {
19+ const stat = fs . statSync ( dir ) ;
20+ if ( stat . isDirectory ( ) ) {
21+ for ( const entry of fs . readdirSync ( dir ) ) {
22+ yield * getStatFiles ( path . join ( dir , entry ) ) ;
23+ }
24+ } else {
25+ yield dir ;
26+ }
27+ }
28+
29+ let totalSize = 0 ;
30+ if ( fs . statSync ( dirOrFilePath ) . isDirectory ( ) ) {
31+ for ( const filePath of getStatFiles ( dirOrFilePath ) ) {
32+ totalSize += fs . statSync ( filePath ) . size ;
33+ }
34+ } else {
35+ totalSize = fs . statSync ( dirOrFilePath ) . size ;
36+ }
1737 // Helper to recursively collect files from a directory
1838 function * getFiles (
1939 dir : string
@@ -31,26 +51,31 @@ export async function ipfsAddFromFs(
3151 }
3252 }
3353
34- let files : any ;
54+ let files : AwaitIterable < ImportCandidate > ;
3555 if ( fs . statSync ( dirOrFilePath ) . isDirectory ( ) ) {
36- files = Array . from ( getFiles ( dirOrFilePath ) ) ;
56+ files = getFiles ( dirOrFilePath ) ;
3757 } else {
38- files = [
39- {
58+ files = ( function * ( ) {
59+ yield {
4060 path : path . basename ( dirOrFilePath ) ,
4161 content : fs . createReadStream ( dirOrFilePath )
42- }
43- ] ;
62+ } ;
63+ } ) ( ) ;
4464 }
4565
4666 // Add files to IPFS
4767 let lastCid = "" ;
68+ let uploaded = 0 ;
4869 for await ( const result of kuboClient . addAll ( files , {
4970 wrapWithDirectory : true ,
50- progress : onProgress
71+ progress : ( bytes : number ) => {
72+ uploaded = bytes ;
73+ if ( onProgress && totalSize > 0 ) {
74+ onProgress ( Math . min ( uploaded / totalSize , 1 ) ) ;
75+ }
76+ }
5177 } ) ) {
5278 lastCid = result . cid . toString ( ) ;
53- // Progress is now handled by kuboClient.addAll's progress callback
5479 }
5580 if ( ! lastCid ) throw Error ( "No CID returned from IPFS add" ) ;
5681 return `/ipfs/${ lastCid } ` ;
0 commit comments