@storagehub-sdk/msp-client 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,129 @@
1
+ # @storagehub-sdk/msp-client
2
+
3
+ High-level client for interacting with StorageHub MSP (Main Storage Provider) services.
4
+
5
+ ## What is this?
6
+
7
+ The `@storagehub-sdk/msp-client` is a TypeScript client library that provides a simple, high-level interface for:
8
+
9
+ - **File Storage & Retrieval**: Upload and download files to/from StorageHub MSP services
10
+ - **Authentication**: SIWE-style (Sign-In With Ethereum) authentication with MSP providers
11
+ - **Health Monitoring**: Check MSP service availability and status
12
+ - **Bucket Management**: Interact with storage buckets and file keys
13
+
14
+ This package is built on top of `@storagehub-sdk/core` and provides a more convenient API for common MSP operations, abstracting away the lower-level details.
15
+
16
+ ## Prerequisites
17
+
18
+ **⚠️ Important**: This client connects to a StorageHub MSP backend service. You need:
19
+
20
+ 1. **A running MSP backend** - Either:
21
+ - A production MSP service endpoint, or
22
+ - A local MSP backend for development/testing
23
+
24
+ 2. **StorageHub node** - The MSP backend requires connection to a StorageHub blockchain node
25
+
26
+ ### Quick Backend Setup for Development
27
+
28
+ To run a local MSP backend with mocks for testing:
29
+
30
+ ```bash
31
+ # From the StorageHub repository root
32
+ RUST_LOG=info cargo run --bin sh-msp-backend --features mocks -- --host 127.0.0.1 --port 8080
33
+ ```
34
+
35
+ This starts a mock MSP backend on `http://127.0.0.1:8080` that you can use for development.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ # pnpm (recommended)
41
+ pnpm add @storagehub-sdk/msp-client
42
+
43
+ # npm
44
+ npm i @storagehub-sdk/msp-client
45
+
46
+ # yarn
47
+ yarn add @storagehub-sdk/msp-client
48
+ ```
49
+
50
+ ## Quick Start
51
+
52
+ ```ts
53
+ import { MspClient } from '@storagehub-sdk/msp-client';
54
+ import { createReadStream, createWriteStream } from 'node:fs';
55
+ import { Readable } from 'node:stream';
56
+
57
+ // 1. Connect to MSP service
58
+ const client = await MspClient.connect({
59
+ baseUrl: 'http://127.0.0.1:8080' // Your MSP backend URL
60
+ });
61
+
62
+ // 2. Check service health
63
+ const health = await client.getHealth();
64
+ console.log('MSP service health:', health);
65
+
66
+ // 3. Authenticate with wallet (SIWE-style)
67
+ const walletAddress = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';
68
+ const chainId = 1; // Ethereum mainnet
69
+
70
+ // Get authentication message to sign
71
+ const { message } = await client.getNonce(walletAddress, chainId);
72
+ console.log('Sign this message with your wallet:', message);
73
+
74
+ // After signing with your wallet (e.g., MetaMask, WalletConnect, etc.)
75
+ const signature = '0xYourWalletSignature...'; // Replace with actual signature
76
+ const verified = await client.verify(message, signature);
77
+ client.setToken(verified.token); // Set auth token for subsequent requests
78
+
79
+ // 4. Upload a file
80
+ const bucketId = '0xYourBucketId'; // StorageHub bucket identifier
81
+ const fileKey = '0xYourFileKey'; // Unique file identifier
82
+ const filePath = './myfile.txt';
83
+
84
+ const receipt = await client.uploadFile(bucketId, fileKey, createReadStream(filePath));
85
+ console.log('File uploaded successfully:', receipt);
86
+
87
+ // 5. Download the file
88
+ const download = await client.downloadByKey(bucketId, fileKey);
89
+ const outputPath = './downloaded-file.txt';
90
+
91
+ // Stream the download to a file
92
+ const writeStream = createWriteStream(outputPath);
93
+ Readable.fromWeb(download.stream).pipe(writeStream);
94
+
95
+ await new Promise((resolve, reject) => {
96
+ writeStream.on('finish', resolve);
97
+ writeStream.on('error', reject);
98
+ });
99
+
100
+ console.log('File downloaded successfully to:', outputPath);
101
+ console.log('Download status:', download.status);
102
+ ```
103
+
104
+ ## API Reference
105
+
106
+ ### Static Methods
107
+ - **`MspClient.connect(config)`** - Create and connect to MSP service
108
+ - `config.baseUrl: string` - MSP backend URL (e.g., `http://127.0.0.1:8080`)
109
+ - `config.timeoutMs?: number` - Request timeout in milliseconds
110
+ - `config.defaultHeaders?: Record<string, string>` - Default HTTP headers
111
+ - `config.fetchImpl?: typeof fetch` - Custom fetch implementation
112
+
113
+ ### Instance Methods
114
+ - **`getHealth()`** - Check MSP service health and status
115
+ - **`getNonce(address, chainId)`** - Get authentication message for wallet signing
116
+ - `address: string` - Wallet address (0x...)
117
+ - `chainId: number` - Blockchain chain ID (1 for Ethereum mainnet)
118
+ - **`verify(message, signature)`** - Verify wallet signature and get auth token
119
+ - `message: string` - The message that was signed
120
+ - `signature: string` - Wallet signature (0x...)
121
+ - **`setToken(token)`** - Set authentication token for subsequent requests
122
+ - **`uploadFile(bucketId, fileKey, file)`** - Upload file to storage
123
+ - `bucketId: string` - Storage bucket identifier
124
+ - `fileKey: string` - Unique file key/identifier
125
+ - `file: ReadStream | Blob | File` - File data to upload
126
+ - **`downloadByKey(bucketId, fileKey)`** - Download file by bucket and key
127
+ - Returns: `{ stream: ReadableStream, status: string }`
128
+ - **`downloadByLocation(bucketId, filePath)`** - Download file by bucket and path
129
+ - Returns: `{ stream: ReadableStream, status: string }`
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import{TypeRegistry as J}from"@polkadot/types";import{BrowserProvider as G}from"ethers";import{hexlify as X,Transaction as Y,Wallet as Z}from"ethers";var k=Object.defineProperty,F=(e,t)=>()=>(e&&(t=e(e=0)),t),L=(e,t)=>{for(var r in t)k(e,r,{get:t[r],enumerable:!0})},O={};L(O,{FileMetadata:()=>P,FileTrie:()=>S,default:()=>I,initSync:()=>$});function R(){return(y===null||y.byteLength===0)&&(y=new Uint8Array(s.memory.buffer)),y}function U(e,t){return e=e>>>0,v.decode(R().subarray(e,e+t))}function b(e,t){let r=t(e.length*1,1)>>>0;return R().set(e,r/1),g=e.length,r}function T(e,t){return e=e>>>0,R().subarray(e/1,e/1+t)}function W(e){let t=s.__wbindgen_export_0.get(e);return s.__externref_table_dealloc(e),t}async function j(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(n){if(e.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",n);else throw n}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let r=await WebAssembly.instantiate(e,t);return r instanceof WebAssembly.Instance?{instance:r,module:e}:r}}function B(){let e={};return e.wbg={},e.wbg.__wbindgen_init_externref_table=function(){let t=s.__wbindgen_export_0,r=t.grow(4);t.set(0,void 0),t.set(r+0,void 0),t.set(r+1,null),t.set(r+2,!0),t.set(r+3,!1)},e.wbg.__wbindgen_string_new=function(t,r){return U(t,r)},e.wbg.__wbindgen_throw=function(t,r){throw new Error(U(t,r))},e}function H(e,t){return s=e.exports,C.__wbindgen_wasm_module=t,y=null,s.__wbindgen_start(),s}function $(e){if(s!==void 0)return s;typeof e<"u"&&(Object.getPrototypeOf(e)===Object.prototype?{module:e}=e:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let t=B();e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e));let r=new WebAssembly.Instance(e,t);return H(r,e)}async function C(e){if(s!==void 0)return s;typeof e<"u"&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof e>"u"&&(e=new URL("storagehub_wasm_bg.wasm",import.meta.url));let t=B();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:n}=await j(await e,t);return H(r,n)}var s,v,y,g,m,P,_,S,I,D=F(()=>{"use strict";v=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}},typeof TextDecoder<"u"&&v.decode(),y=null,g=0,m=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>s.__wbg_filemetadata_free(e>>>0,1)),P=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,m.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_filemetadata_free(e,0)}constructor(e,t,r,n,d){let l=b(e,s.__wbindgen_malloc),c=g,i=b(t,s.__wbindgen_malloc),o=g,a=b(r,s.__wbindgen_malloc),p=g,f=b(d,s.__wbindgen_malloc),u=g,h=s.filemetadata_new(l,c,i,o,a,p,n,f,u);if(h[2])throw W(h[1]);return this.__wbg_ptr=h[0]>>>0,m.register(this,this.__wbg_ptr,this),this}getFileKey(){let e=s.filemetadata_getFileKey(this.__wbg_ptr);var t=T(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),t}},_=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>s.__wbg_filetrie_free(e>>>0,1)),S=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,_.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_filetrie_free(e,0)}constructor(){let e=s.filetrie_new();return this.__wbg_ptr=e>>>0,_.register(this,this.__wbg_ptr,this),this}push_chunk(e){let t=b(e,s.__wbindgen_malloc),r=g;s.filetrie_push_chunk(this.__wbg_ptr,t,r)}get_root(){let e=s.filetrie_get_root(this.__wbg_ptr);var t=T(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),t}},I=C});D();var E=class extends Error{status;body;constructor(e,t,r){super(e),this.name="HttpError",this.status=t,this.body=r}},N=class extends Error{constructor(e){super(e),this.name="NetworkError"}},q=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},K=3e4,x=class{baseUrl;timeoutMs;defaultHeaders;fetchImpl;constructor(e){if(!e.baseUrl)throw new Error("HttpClient: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeoutMs=e.timeoutMs??K,this.defaultHeaders={Accept:"application/json",...e.defaultHeaders??{}},this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r={}){let n=this.buildUrl(t,r.query),d={...this.defaultHeaders,...r.headers??{}},l=!r.signal&&this.timeoutMs>0?new AbortController:void 0,c=r.signal??l?.signal,i=l?setTimeout(()=>l.abort(),this.timeoutMs):void 0;try{let o=Object.keys(d).some(w=>w.toLowerCase()==="content-type"),a=r.body,p=null;a!=null&&(this.isBodyInit(a)?p=a:(o||(d["Content-Type"]="application/json"),p=JSON.stringify(a)));let f={method:e,headers:d,...c?{signal:c}:{},...p!==null?{body:p}:{}},u=await(typeof globalThis<"u"&&this.fetchImpl===globalThis.fetch?globalThis.fetch.bind(globalThis):this.fetchImpl)(n,f);if(!u.ok){let w=await u.text(),M=this.parseJsonSafely(w);throw new E(`HTTP ${u.status} for ${e} ${n}`,u.status,M??w)}if(r.raw)return u;let h=await u.text();return this.parseJsonSafely(h)??h}catch(o){if(this.isAbortError(o))throw new q(`Request timed out for ${e} ${t}`);if(o instanceof E)throw o;let a=this.getErrorMessage(o);throw new N(a??`Network error for ${e} ${t}`)}finally{i&&clearTimeout(i)}}get(e,t){return this.request("GET",e,t)}post(e,t){return this.request("POST",e,t??{})}put(e,t){return this.request("PUT",e,t??{})}delete(e,t){return this.request("DELETE",e,t??{})}getRaw(e,t){return this.request("GET",e,{...t,raw:!0})}buildUrl(e,t){let r=e.startsWith("/")?e:`/${e}`,n=new URL(this.baseUrl+r);if(t)for(let[d,l]of Object.entries(t))n.searchParams.set(d,String(l));return n.toString()}parseJsonSafely(e){if(e)try{return JSON.parse(e)}catch{return}}isBodyInit(e){return typeof e=="string"||e instanceof Uint8Array||typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||typeof ReadableStream<"u"&&e instanceof ReadableStream}isAbortError(e){return typeof e=="object"&&e!==null&&"name"in e&&typeof e.name=="string"&&e.name==="AbortError"}getErrorMessage(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"message"in e){let t=e.message;if(typeof t=="string")return t}}};var A=class e{config;http;token;constructor(t,r){this.config=t,this.http=r}static async connect(t){if(!t?.baseUrl)throw new Error("MspClient.connect: baseUrl is required");let r=new x({baseUrl:t.baseUrl,...t.timeoutMs!==void 0&&{timeoutMs:t.timeoutMs},...t.defaultHeaders!==void 0&&{defaultHeaders:t.defaultHeaders},...t.fetchImpl!==void 0&&{fetchImpl:t.fetchImpl}});return new e(t,r)}getHealth(t){return this.http.get("/health",{...t?.signal!==void 0&&{signal:t.signal}})}getNonce(t,r,n){return this.http.post("/auth/nonce",{body:{address:t,chainId:r},headers:{"Content-Type":"application/json"},...n?.signal!==void 0&&{signal:n.signal}})}verify(t,r,n){return this.http.post("/auth/verify",{body:{message:t,signature:r},headers:{"Content-Type":"application/json"},...n?.signal!==void 0&&{signal:n.signal}})}setToken(t){this.token=t}withAuth(t){return this.token?{...t??{},Authorization:`Bearer ${this.token}`}:t}async uploadFile(t,r,n,d){let l=`/buckets/${encodeURIComponent(t)}/upload/${encodeURIComponent(r)}`,c=this.withAuth();if(n instanceof ReadableStream)return await this.http.put(l,c?{body:n,headers:{...c,"Content-Type":"application/octet-stream"}}:{body:n,headers:{"Content-Type":"application/octet-stream"}});let i=new FormData,o=await this.coerceToFormPart(n);return i.append("file",o,"file"),await this.http.put(l,c?{body:i,headers:c}:{body:i})}async coerceToFormPart(t){return typeof Blob<"u"&&t instanceof Blob?t:t instanceof Uint8Array?new Blob([t]):typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer?new Blob([t]):new Blob([t])}async downloadByKey(t,r,n){let d=`/buckets/${encodeURIComponent(t)}/download/${encodeURIComponent(r)}`,l={Accept:"*/*"},c=this.withAuth(l),i=await this.http.getRaw(d,c?{headers:c}:{});if(!i.body)throw new Error("Response body is null - unable to create stream");let o=i.headers.get("content-type"),a=i.headers.get("content-range"),p=i.headers.get("content-length"),f=p!==null?Number(p):void 0,u=typeof f=="number"&&Number.isFinite(f)?f:null;return{stream:i.body,status:i.status,contentType:o,contentRange:a,contentLength:u}}async downloadByLocation(t,r,n){let l=r.replace(/^\/+/,"").split("/").map(encodeURIComponent).join("/"),c=`/buckets/${encodeURIComponent(t)}/download/path/${l}`,i={Accept:"*/*"},o=this.withAuth(i),a=await this.http.getRaw(c,o?{headers:o}:{});if(!a.body)throw new Error("Response body is null - unable to create stream");let p=a.headers.get("content-type"),f=a.headers.get("content-range"),u=a.headers.get("content-length"),h=u!==null?Number(u):void 0,w=typeof h=="number"&&Number.isFinite(h)?h:null;return{stream:a.body,status:a.status,contentType:p,contentRange:f,contentLength:w}}};export{A as MspClient};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../core/wasm/pkg/storagehub_wasm.js", "../../core/src/wasm.ts", "../../core/src/file-manager.ts", "../../core/src/http/errors.ts", "../../core/src/http/HttpClient.ts", "../../core/src/init.ts", "../../core/src/wallet/base.ts", "../../core/src/wallet/eip1193.ts", "../../core/src/wallet/errors.ts", "../../core/src/wallet/local.ts", "../src/MspClient.ts"],
4
+ "sourcesContent": ["let wasm;\n\nconst cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );\n\nif (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };\n\nlet cachedUint8ArrayMemory0 = null;\n\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nfunction passArray8ToWasm0(arg, malloc) {\n const ptr = malloc(arg.length * 1, 1) >>> 0;\n getUint8ArrayMemory0().set(arg, ptr / 1);\n WASM_VECTOR_LEN = arg.length;\n return ptr;\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_export_0.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nconst FileMetadataFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_filemetadata_free(ptr >>> 0, 1));\n\nexport class FileMetadata {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n FileMetadataFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_filemetadata_free(ptr, 0);\n }\n /**\n * Constructs a new `FileMetadata`.\n * * `owner`, `bucket_id`, `fingerprint` \u2013 32-byte arrays (passed as slices)\n * * `location` \u2013 arbitrary byte string (file path)\n * * `size` \u2013 file size in bytes\n * @param {Uint8Array} owner\n * @param {Uint8Array} bucket_id\n * @param {Uint8Array} location\n * @param {bigint} size\n * @param {Uint8Array} fingerprint\n */\n constructor(owner, bucket_id, location, size, fingerprint) {\n const ptr0 = passArray8ToWasm0(owner, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n const ptr1 = passArray8ToWasm0(bucket_id, wasm.__wbindgen_malloc);\n const len1 = WASM_VECTOR_LEN;\n const ptr2 = passArray8ToWasm0(location, wasm.__wbindgen_malloc);\n const len2 = WASM_VECTOR_LEN;\n const ptr3 = passArray8ToWasm0(fingerprint, wasm.__wbindgen_malloc);\n const len3 = WASM_VECTOR_LEN;\n const ret = wasm.filemetadata_new(ptr0, len0, ptr1, len1, ptr2, len2, size, ptr3, len3);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n this.__wbg_ptr = ret[0] >>> 0;\n FileMetadataFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * Returns the FileKey (blake2_256 hash of SCALE-encoded metadata) as a\n * 32-byte `Uint8Array`.\n * @returns {Uint8Array}\n */\n getFileKey() {\n const ret = wasm.filemetadata_getFileKey(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\n\nconst FileTrieFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_filetrie_free(ptr >>> 0, 1));\n\nexport class FileTrie {\n\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n FileTrieFinalization.unregister(this);\n return ptr;\n }\n\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_filetrie_free(ptr, 0);\n }\n constructor() {\n const ret = wasm.filetrie_new();\n this.__wbg_ptr = ret >>> 0;\n FileTrieFinalization.register(this, this.__wbg_ptr, this);\n return this;\n }\n /**\n * @param {Uint8Array} bytes\n */\n push_chunk(bytes) {\n const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);\n const len0 = WASM_VECTOR_LEN;\n wasm.filetrie_push_chunk(this.__wbg_ptr, ptr0, len0);\n }\n /**\n * Current Merkle root as a hex string.\n * @returns {Uint8Array}\n */\n get_root() {\n const ret = wasm.filetrie_get_root(this.__wbg_ptr);\n var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();\n wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);\n return v1;\n }\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n\n } catch (e) {\n if (module.headers.get('Content-Type') != 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else {\n throw e;\n }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n\n } else {\n return instance;\n }\n }\n}\n\nfunction __wbg_get_imports() {\n const imports = {};\n imports.wbg = {};\n imports.wbg.__wbindgen_init_externref_table = function() {\n const table = wasm.__wbindgen_export_0;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n ;\n };\n imports.wbg.__wbindgen_string_new = function(arg0, arg1) {\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n };\n imports.wbg.__wbindgen_throw = function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n };\n\n return imports;\n}\n\nfunction __wbg_init_memory(imports, memory) {\n\n}\n\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n __wbg_init.__wbindgen_wasm_module = module;\n cachedUint8ArrayMemory0 = null;\n\n\n wasm.__wbindgen_start();\n return wasm;\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (typeof module !== 'undefined') {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n\n __wbg_init_memory(imports);\n\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n\n const instance = new WebAssembly.Instance(module, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (typeof module_or_path !== 'undefined') {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (typeof module_or_path === 'undefined') {\n module_or_path = new URL('storagehub_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n __wbg_init_memory(imports);\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync };\nexport default __wbg_init;\n", "export { FileMetadata, FileTrie } from '../wasm/pkg/storagehub_wasm.js';\n", "import { CHUNK_SIZE } from './constants';\nimport { FileMetadata, FileTrie } from './wasm.js';\nimport { TypeRegistry } from '@polkadot/types';\nimport type { AccountId, H256 } from '@polkadot/types/interfaces';\n\nexport class FileManager {\n constructor(private readonly file: { size: number; stream: () => ReadableStream<Uint8Array> }) {}\n\n private fingerprint?: H256;\n private fileKey?: H256;\n\n /**\n * Stream the file's contents, feed every 1 kB chunk into a new FileTrie, and\n * return the resulting Merkle root.\n */\n async getFingerprint(): Promise<H256> {\n if (this.fingerprint) {\n return this.fingerprint;\n }\n\n const registry = new TypeRegistry();\n const trie = new FileTrie();\n\n const stream = this.file.stream();\n // ---\n // Streaming fingerprint algorithm\n // We want to feed the MerkleTrie with **fixed-size** `${CHUNK_SIZE}`-byte chunks\n // but a `ReadableStream` gives us arbitrarily-sized `Uint8Array`s (default \u224864 KiB).\n //\n // Strategy\n // 1. Keep an in-memory sliding buffer (`buffer`).\n // 2. `bufferOffset` marks how much of that buffer has already been\n // consumed (pushed to the trie).\n // 3. On each `reader.read()` we append the newly-read bytes after the\n // unconsumed tail. Then, while we still have \u2265 CHUNK_SIZE bytes\n // available, cut a `${CHUNK_SIZE}`-byte window and push it into the trie.\n // 4. Any leftover ( < CHUNK_SIZE ) stays in `buffer` to be prefixed by\n // the next read.\n // ---\n const reader = stream.getReader();\n let buffer = new Uint8Array();\n let bufferOffset = 0;\n\n try {\n while (true) {\n // \u2500\u2500 Step-1: pull next blob fragment (\u224864 KiB) from the stream\n const { done, value } = await reader.read();\n if (done) break; // EOF \u21D2 exit outer loop\n\n if (value && value.length) {\n /*\n * \u2500\u2500 Step-2: concatenate the newly-read bytes **after** any leftover\n * bytes we still haven\u2019t consumed (bufferOffset marks the\n * start of that tail). We create a fresh Uint8Array to\n * avoid costly shifting of the existing buffer.\n */\n const unreadTail = buffer.subarray(bufferOffset);\n const newBuffer = new Uint8Array(unreadTail.length + value.length);\n newBuffer.set(unreadTail, 0);\n newBuffer.set(value, unreadTail.length);\n buffer = newBuffer;\n bufferOffset = 0;\n\n /*\n * \u2500\u2500 Step-3: while the sliding-window holds at least one full\n * CHUNK_SIZE-byte block, slice it out and push it into the\n * trie. We may loop multiple times if the stream chunk was\n * very large.\n */\n while (buffer.length - bufferOffset >= CHUNK_SIZE) {\n const chunk = buffer.subarray(bufferOffset, bufferOffset + CHUNK_SIZE);\n trie.push_chunk(chunk);\n bufferOffset += CHUNK_SIZE;\n }\n }\n }\n\n // \u2500\u2500 Step-4: push the leftover bytes (< CHUNK_SIZE)\n if (buffer.length - bufferOffset > 0) {\n trie.push_chunk(buffer.subarray(bufferOffset));\n }\n } finally {\n reader.releaseLock();\n }\n\n // Retrieve Merkle root from the trie and cache it\n const rootHash = trie.get_root();\n const fingerprint = registry.createType('H256', rootHash) as H256;\n\n this.fingerprint = fingerprint;\n return fingerprint;\n }\n\n /**\n * Compute the FileKey for this file.\n *\n * The caller must provide:\n * \u2022 owner \u2013 32-byte AccountId (Uint8Array or 0x-prefixed hex string)\n * \u2022 bucketId \u2013 32-byte BucketId (Uint8Array or 0x-prefixed hex string)\n * \u2022 location \u2013 path string (encoded to bytes as-is)\n */\n async computeFileKey(owner: AccountId, bucketId: H256, location: string): Promise<H256> {\n if (this.fileKey) {\n return this.fileKey;\n }\n\n const fp = await this.getFingerprint();\n\n const metadata = new FileMetadata(\n owner.toU8a(),\n bucketId.toU8a(),\n new TextEncoder().encode(location),\n BigInt(this.file.size),\n fp.toU8a(),\n );\n\n const fileKey = metadata.getFileKey();\n const registry = new TypeRegistry();\n this.fileKey = registry.createType('H256', fileKey) as H256;\n return this.fileKey;\n }\n}\n", "export class HttpError extends Error {\n public readonly status: number;\n public readonly body?: unknown;\n\n constructor(message: string, status: number, body?: unknown) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n this.body = body;\n }\n}\n\nexport class NetworkError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NetworkError';\n }\n}\n\nexport class TimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TimeoutError';\n }\n}\n", "import { HttpError, NetworkError, TimeoutError } from './errors.js';\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nexport type HttpClientConfig = {\n baseUrl: string;\n timeoutMs?: number;\n defaultHeaders?: Record<string, string>;\n fetchImpl?: typeof fetch;\n};\n\nexport type RequestOptions = {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n query?: Record<string, string | number | boolean>;\n /**\n * Optional request body. If a non-BodyInit object is provided and no\n * explicit Content-Type header is set, it will be JSON-encoded with\n * 'application/json'.\n */\n body?: BodyInit | unknown;\n /**\n * If true, returns the raw Response without consuming the body.\n * Useful for streaming downloads.\n */\n raw?: boolean;\n};\n\nexport class HttpClient {\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly defaultHeaders: Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: HttpClientConfig) {\n if (!options.baseUrl) throw new Error('HttpClient: baseUrl is required');\n this.baseUrl = options.baseUrl.replace(/\\/$/, '');\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.defaultHeaders = { Accept: 'application/json', ...(options.defaultHeaders ?? {}) };\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n async request<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n options: RequestOptions = {},\n ): Promise<T | Response> {\n const url = this.buildUrl(path, options.query);\n const headers = { ...this.defaultHeaders, ...(options.headers ?? {}) };\n\n // Support timeout via AbortController if no external signal provided\n const controller = !options.signal && this.timeoutMs > 0 ? new AbortController() : undefined;\n const signal = options.signal ?? controller?.signal;\n\n const timer: ReturnType<typeof setTimeout> | undefined = controller\n ? setTimeout(() => controller.abort(), this.timeoutMs)\n : undefined;\n\n try {\n // Auto-encode JSON bodies if caller passed a plain object and no Content-Type\n const hasExplicitContentType = Object.keys(headers).some(\n (h) => h.toLowerCase() === 'content-type',\n );\n const candidate = options.body;\n let body: BodyInit | null = null;\n if (candidate !== undefined && candidate !== null) {\n if (this.isBodyInit(candidate)) {\n body = candidate;\n } else {\n // For non-BodyInit payloads, send JSON\n if (!hasExplicitContentType) headers['Content-Type'] = 'application/json';\n body = JSON.stringify(candidate);\n }\n }\n\n const init: RequestInit = {\n method,\n headers,\n ...(signal ? { signal } : {}),\n ...(body !== null ? { body } : {}),\n };\n const fetchFn =\n typeof globalThis !== 'undefined' &&\n this.fetchImpl === (globalThis as unknown as { fetch: typeof fetch }).fetch\n ? (globalThis as unknown as { fetch: typeof fetch }).fetch.bind(globalThis)\n : this.fetchImpl;\n const res = await fetchFn(url, init);\n\n // If the response is not OK, consume body for error details and throw\n if (!res.ok) {\n const text = await res.text();\n const maybeJson = this.parseJsonSafely(text);\n throw new HttpError(\n `HTTP ${res.status} for ${method} ${url}`,\n res.status,\n maybeJson ?? text,\n );\n }\n\n // If raw response requested, return it without consuming the body\n if (options.raw) {\n return res as Response;\n }\n\n // Normal response processing - consume and parse the body\n const text = await res.text();\n const maybeJson = this.parseJsonSafely(text);\n return (maybeJson as T) ?? (text as unknown as T);\n } catch (err: unknown) {\n if (this.isAbortError(err)) {\n throw new TimeoutError(`Request timed out for ${method} ${path}`);\n }\n if (err instanceof HttpError) throw err;\n const msg = this.getErrorMessage(err);\n throw new NetworkError(msg ?? `Network error for ${method} ${path}`);\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, options) as Promise<T>;\n }\n\n post<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, options ?? {}) as Promise<T>;\n }\n\n put<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('PUT', path, options ?? {}) as Promise<T>;\n }\n\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, options ?? {}) as Promise<T>;\n }\n\n getRaw(path: string, options?: RequestOptions): Promise<Response> {\n return this.request('GET', path, { ...options, raw: true }) as Promise<Response>;\n }\n\n private buildUrl(path: string, query?: Record<string, string | number | boolean>): string {\n const normalizedPath = path.startsWith('/') ? path : `/${path}`;\n const url = new URL(this.baseUrl + normalizedPath);\n\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n url.searchParams.set(k, String(v));\n }\n }\n\n return url.toString();\n }\n\n private parseJsonSafely(text: string): unknown | undefined {\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n }\n\n private isBodyInit(value: unknown): value is BodyInit {\n return (\n typeof value === 'string' ||\n value instanceof Uint8Array ||\n (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) ||\n (typeof Blob !== 'undefined' && value instanceof Blob) ||\n (typeof FormData !== 'undefined' && value instanceof FormData) ||\n (typeof ReadableStream !== 'undefined' && value instanceof ReadableStream)\n );\n }\n\n private isAbortError(err: unknown): err is { name: string } {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'name' in err &&\n typeof (err as { name?: unknown }).name === 'string' &&\n (err as { name: string }).name === 'AbortError'\n );\n }\n\n private getErrorMessage(err: unknown): string | undefined {\n if (typeof err === 'string') return err;\n if (typeof err === 'object' && err !== null && 'message' in err) {\n const m = (err as { message?: unknown }).message;\n if (typeof m === 'string') return m;\n }\n return undefined;\n }\n}\n", "let initPromise: Promise<void> | null = null;\n\nexport async function initWasm(): Promise<void> {\n if (initPromise) {\n // If initialization is already in progress, wait for the same Promise\n return initPromise;\n }\n\n // Create the initialization Promise and store it\n initPromise = (async () => {\n // Import the web-style init function\n const wasmInit = (await import('../wasm/pkg/storagehub_wasm.js')).default;\n\n const wasmUrl = new URL('../wasm/pkg/storagehub_wasm_bg.wasm', import.meta.url);\n if (typeof window === 'undefined') {\n // Node.js: read WASM bytes and pass as ArrayBuffer\n const fsMod = 'node:fs/promises';\n const { readFile } = await import(fsMod);\n const buf = await readFile(wasmUrl);\n await wasmInit(buf);\n } else {\n // Browser: pass URL or fetch promise\n await wasmInit(wasmUrl.href);\n }\n })();\n\n return initPromise;\n}\n", "/**\n * Base abstraction for wallet integrations.\n *\n * Any concrete wallet (e.g. a browser extension wallet, a hardware wallet or a\n * mobile-SDK based wallet) must extend this class and implement the methods\n * for retrieving the active account address, sending transactions, and\n * signing arbitrary messages.\n */\nimport type { TransactionRequest } from 'ethers';\n\nexport abstract class WalletBase {\n /**\n * Return the public address for the currently selected account.\n *\n * Implementations may need to prompt the user to unlock the wallet or to\n * choose an account if more than one is available.\n */\n public abstract getAddress(): Promise<string>;\n\n /**\n * Send a transaction through the wallet and return the transaction hash.\n *\n * This is the primary operation for most EIP-1193 compatible wallets which\n * do not support producing detached transaction signatures.\n */\n public abstract sendTransaction(tx: TransactionRequest): Promise<string>;\n\n /**\n * Sign an arbitrary message and return the signature.\n *\n * This is commonly used for off-chain authentication flows (e.g. signing a\n * nonce) or for verifying ownership of an address.\n *\n * @param msg The message to sign, either as raw bytes (`Uint8Array`) or a\n * regular UTF-8 string.\n * @returns A signature string, typically hex-encoded.\n */\n public abstract signMessage(msg: Uint8Array | string): Promise<string>;\n}\n", "import { WalletBase } from './base.js';\nimport { BrowserProvider, type Eip1193Provider, type TransactionRequest } from 'ethers';\n\ndeclare global {\n /**\n * EIP-1193 injected provider placed on the window object by browser wallets.\n * The exact shape is library-specific; we wrap it via ethers' BrowserProvider.\n */\n interface Window {\n ethereum?: unknown;\n }\n}\n\n/**\n * Generic wallet integration for any EIP-1193 compliant injected provider.\n *\n * Implements the minimal `WalletBase` contract (fetching the current address,\n * sending transactions, and signing arbitrary messages) using ethers v6.\n */\nexport class Eip1193Wallet extends WalletBase {\n private constructor(private readonly provider: BrowserProvider) {\n super();\n }\n\n /**\n * Create a wallet from an existing EIP-1193 provider instance.\n */\n public static fromProvider(provider: Eip1193Provider): Eip1193Wallet {\n return new Eip1193Wallet(new BrowserProvider(provider));\n }\n\n /**\n * Request connection to the injected provider at `window.ethereum` and\n * create a new `Eip1193Wallet`.\n *\n * Internally this triggers the extension UI via `eth_requestAccounts` which\n * asks the user to authorise account access.\n *\n * @throws If no injected provider is found.\n */\n public static async connect(): Promise<Eip1193Wallet> {\n if (typeof window.ethereum === 'undefined') {\n throw new Error('EIP-1193 provider not found. Please install a compatible wallet.');\n }\n\n const provider = new BrowserProvider(window.ethereum as Eip1193Provider);\n await provider.send('eth_requestAccounts', []);\n return new Eip1193Wallet(provider);\n }\n\n /** @inheritdoc */\n public async getAddress(): Promise<string> {\n const signer = await this.provider.getSigner();\n return signer.getAddress();\n }\n\n /** @inheritdoc */\n public async sendTransaction(tx: TransactionRequest): Promise<string> {\n const signer = await this.provider.getSigner();\n const txRequest: Partial<TransactionRequest> = {};\n if (tx.to) txRequest.to = tx.to;\n if (tx.data && tx.data !== '0x') txRequest.data = tx.data;\n if (tx.value && tx.value !== 0n) txRequest.value = tx.value;\n if (tx.gasLimit && tx.gasLimit !== 0n) txRequest.gasLimit = tx.gasLimit;\n const response = await signer.sendTransaction(txRequest);\n return response.hash;\n }\n\n /** @inheritdoc */\n public async signMessage(msg: Uint8Array | string): Promise<string> {\n const signer = await this.provider.getSigner();\n return signer.signMessage(msg);\n }\n}\n", "export type WalletErrorCode = 'InvalidPrivateKey' | 'InvalidMnemonic';\n\nexport class WalletError extends Error {\n public readonly name = 'WalletError';\n public readonly code: WalletErrorCode;\n\n public constructor(code: WalletErrorCode, message?: string) {\n super(message ?? code);\n this.code = code;\n }\n}\n", "import { WalletBase } from './base.js';\nimport { WalletError } from './errors.js';\nimport {\n type HDNodeWallet,\n hexlify,\n type Provider,\n Transaction,\n type TransactionRequest,\n Wallet as EthersWallet,\n} from 'ethers';\n\n/**\n * A local, in-memory wallet implementation.\n *\n * @warning This class is intended for development and testing purposes only.\n * It manages private keys in memory and is not suitable for production use\n * where secure key management is required.\n */\nexport class LocalWallet extends WalletBase {\n private constructor(\n private readonly wallet: EthersWallet | HDNodeWallet,\n private readonly provider?: Provider,\n ) {\n super();\n }\n\n /**\n * Create an instance from an existing private key.\n *\n * @param privateKey - A 0x-prefixed hex string containing the private key.\n * @returns A new `LocalWallet` that can sign on behalf of the key\u02BCs address.\n */\n public static fromPrivateKey(privateKey: string, provider?: Provider): LocalWallet {\n // Validate early to provide a stable error type regardless of ethers internals\n const isHex = /^0x[0-9a-fA-F]{64}$/.test(privateKey);\n if (!isHex) throw new WalletError('InvalidPrivateKey');\n\n try {\n return new LocalWallet(new EthersWallet(privateKey, provider), provider);\n } catch {\n throw new WalletError('InvalidPrivateKey');\n }\n }\n\n /**\n * Create an instance from a BIP-39 mnemonic phrase.\n *\n * @param mnemonic - The 12/24-word mnemonic phrase.\n * @returns A new `LocalWallet` bound to the first account derived from the\n * mnemonic.\n */\n public static fromMnemonic(mnemonic: string, provider?: Provider): LocalWallet {\n try {\n const wallet = EthersWallet.fromPhrase(mnemonic);\n const connected = provider ? wallet.connect(provider) : wallet;\n return new LocalWallet(connected, provider);\n } catch {\n throw new WalletError('InvalidMnemonic');\n }\n }\n\n /**\n * Generate a brand-new keypair on the fly.\n *\n * @returns A freshly generated `LocalWallet` with a random private key.\n */\n public static createRandom(provider?: Provider): LocalWallet {\n const wallet = EthersWallet.createRandom();\n const connected = provider ? wallet.connect(provider) : wallet;\n return new LocalWallet(connected, provider);\n }\n\n /** @inheritdoc */\n public getAddress(): Promise<string> {\n return Promise.resolve(this.wallet.address);\n }\n\n public signTransaction(tx: Uint8Array): Promise<string> {\n const hexTx = hexlify(tx);\n return this.wallet.signTransaction(Transaction.from(hexTx));\n }\n\n /** @inheritdoc */\n public async sendTransaction(tx: TransactionRequest): Promise<string> {\n if (!this.provider) {\n throw new Error('No provider configured for LocalWallet; cannot send transaction');\n }\n const connected = this.wallet.connect(this.provider);\n const response = await connected.sendTransaction(tx);\n return response.hash;\n }\n\n /** @inheritdoc */\n public signMessage(msg: Uint8Array | string): Promise<string> {\n return this.wallet.signMessage(msg);\n }\n}\n", "import type {\n DownloadOptions,\n DownloadResult,\n HealthStatus,\n NonceResponse,\n UploadOptions,\n UploadReceipt,\n VerifyResponse,\n} from './types.js';\nimport type { HttpClientConfig } from '@storagehub-sdk/core';\nimport { HttpClient } from '@storagehub-sdk/core';\n\nexport class MspClient {\n public readonly config: HttpClientConfig;\n private readonly http: HttpClient;\n private token?: string;\n\n private constructor(config: HttpClientConfig, http: HttpClient) {\n this.config = config;\n this.http = http;\n }\n\n static async connect(config: HttpClientConfig): Promise<MspClient> {\n if (!config?.baseUrl) throw new Error('MspClient.connect: baseUrl is required');\n\n const http = new HttpClient({\n baseUrl: config.baseUrl,\n ...(config.timeoutMs !== undefined && { timeoutMs: config.timeoutMs }),\n ...(config.defaultHeaders !== undefined && { defaultHeaders: config.defaultHeaders }),\n ...(config.fetchImpl !== undefined && { fetchImpl: config.fetchImpl }),\n });\n\n return new MspClient(config, http);\n }\n\n getHealth(options?: { signal?: AbortSignal }): Promise<HealthStatus> {\n return this.http.get<HealthStatus>('/health', {\n ...(options?.signal !== undefined && { signal: options.signal }),\n });\n }\n\n /** Request a SIWE-style nonce message for the given address and chainId */\n getNonce(\n address: string,\n chainId: number,\n options?: { signal?: AbortSignal },\n ): Promise<NonceResponse> {\n return this.http.post<NonceResponse>('/auth/nonce', {\n body: { address, chainId },\n headers: { 'Content-Type': 'application/json' },\n ...(options?.signal !== undefined && { signal: options.signal }),\n });\n }\n\n /** Verify signed message and receive JWT token */\n verify(\n message: string,\n signature: string,\n options?: { signal?: AbortSignal },\n ): Promise<VerifyResponse> {\n return this.http.post<VerifyResponse>('/auth/verify', {\n body: { message, signature },\n headers: { 'Content-Type': 'application/json' },\n ...(options?.signal !== undefined && { signal: options.signal }),\n });\n }\n\n /** Store token to be sent on subsequent protected requests */\n setToken(token: string): void {\n this.token = token;\n }\n\n /** Merge Authorization header when token is present */\n private withAuth(headers?: Record<string, string>): Record<string, string> | undefined {\n if (!this.token) return headers;\n return { ...(headers ?? {}), Authorization: `Bearer ${this.token}` };\n }\n\n /**\n * Upload a file to a bucket with a specific key.\n *\n * For small files (Blob, ArrayBuffer, Uint8Array), uses multipart/form-data upload.\n * For large files (ReadableStream), uses memory-efficient streaming upload with\n * application/octet-stream to prevent loading entire file into memory.\n *\n */\n async uploadFile(\n bucketId: string,\n fileKey: string,\n file: Blob | ArrayBuffer | Uint8Array | ReadableStream<Uint8Array> | unknown,\n _options?: UploadOptions,\n ): Promise<UploadReceipt> {\n void _options;\n\n const path = `/buckets/${encodeURIComponent(bucketId)}/upload/${encodeURIComponent(fileKey)}`;\n const authHeaders = this.withAuth();\n\n // For ReadableStream, use direct streaming upload (memory efficient)\n if (file instanceof ReadableStream) {\n const res = await this.http.put<UploadReceipt>(\n path,\n authHeaders\n ? {\n body: file,\n headers: {\n ...authHeaders,\n 'Content-Type': 'application/octet-stream',\n },\n }\n : {\n body: file,\n headers: { 'Content-Type': 'application/octet-stream' },\n },\n );\n return res;\n }\n\n // For other types, use FormData (traditional multipart upload)\n const form = new FormData();\n const part = await this.coerceToFormPart(file);\n form.append('file', part as Blob, 'file'); // part is now guaranteed to be Blob\n\n const res = await this.http.put<UploadReceipt>(\n path,\n authHeaders\n ? { body: form as unknown as BodyInit, headers: authHeaders }\n : { body: form as unknown as BodyInit },\n );\n return res;\n }\n\n private async coerceToFormPart(file: Blob | ArrayBuffer | Uint8Array | unknown): Promise<Blob> {\n if (typeof Blob !== 'undefined' && file instanceof Blob) return file;\n if (file instanceof Uint8Array) return new Blob([file]);\n if (typeof ArrayBuffer !== 'undefined' && file instanceof ArrayBuffer) return new Blob([file]);\n\n return new Blob([file as BlobPart]);\n }\n\n /** Download a file by bucket and key. */\n async downloadByKey(\n bucketId: string,\n fileKey: string,\n _options?: DownloadOptions,\n ): Promise<DownloadResult> {\n void _options;\n const path = `/buckets/${encodeURIComponent(bucketId)}/download/${encodeURIComponent(fileKey)}`;\n const baseHeaders: Record<string, string> = { Accept: '*/*' };\n const headers = this.withAuth(baseHeaders);\n const res = await this.http.getRaw(path, headers ? { headers } : {});\n\n if (!res.body) {\n throw new Error('Response body is null - unable to create stream');\n }\n\n const contentType = res.headers.get('content-type');\n const contentRange = res.headers.get('content-range');\n const contentLengthHeader = res.headers.get('content-length');\n const parsedLength = contentLengthHeader !== null ? Number(contentLengthHeader) : undefined;\n const contentLength =\n typeof parsedLength === 'number' && Number.isFinite(parsedLength) ? parsedLength : null;\n\n return {\n stream: res.body,\n status: res.status,\n contentType,\n contentRange,\n contentLength,\n };\n }\n\n /** Download a file by its location path under a bucket. */\n async downloadByLocation(\n bucketId: string,\n filePath: string,\n _options?: DownloadOptions,\n ): Promise<DownloadResult> {\n void _options;\n const normalized = filePath.replace(/^\\/+/, '');\n const encodedPath = normalized.split('/').map(encodeURIComponent).join('/');\n const path = `/buckets/${encodeURIComponent(bucketId)}/download/path/${encodedPath}`;\n const baseHeaders: Record<string, string> = { Accept: '*/*' };\n const headers = this.withAuth(baseHeaders);\n const res = await this.http.getRaw(path, headers ? { headers } : {});\n\n if (!res.body) {\n throw new Error('Response body is null - unable to create stream');\n }\n\n const contentType = res.headers.get('content-type');\n const contentRange = res.headers.get('content-range');\n const contentLengthHeader = res.headers.get('content-length');\n const parsedLength = contentLengthHeader !== null ? Number(contentLengthHeader) : undefined;\n const contentLength =\n typeof parsedLength === 'number' && Number.isFinite(parsedLength) ? parsedLength : null;\n\n return {\n stream: res.body,\n status: res.status,\n contentType,\n contentRange,\n contentLength,\n };\n }\n}\n"],
5
+ "mappings": "AEEA,OAAS,gBAAAA,MAAoB,kBKD7B,OAAS,mBAAAC,MAAsE,SEC/E,OAEE,WAA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IAAI,gBAAgB,EACtDI,EAAeD,IAAwB,KAAO,OAAOA,CAAmB,EAAI,OAC5EE,EACJ,OAAOD,GAAiB,UAAY,OAAO,SAASA,CAAY,EAAIA,EAAe,KAErF,MAAO,CACL,OAAQJ,EAAI,KACZ,OAAQA,EAAI,OACZ,YAAAC,EACA,aAAAC,EACA,cAAAG,CACF,CACF,CACF",
6
+ "names": ["TypeRegistry", "BrowserProvider", "hexlify", "Transaction", "EthersWallet", "storagehub_wasm_exports", "__export", "FileMetadata", "FileTrie", "storagehub_wasm_default", "initSync", "getUint8ArrayMemory0", "cachedUint8ArrayMemory0", "wasm", "getStringFromWasm0", "ptr", "len", "cachedTextDecoder", "passArray8ToWasm0", "arg", "malloc", "WASM_VECTOR_LEN", "getArrayU8FromWasm0", "takeFromExternrefTable0", "idx", "value", "__wbg_load", "module", "imports", "e", "bytes", "instance", "__wbg_get_imports", "table", "offset", "arg0", "arg1", "__wbg_finalize_init", "__wbg_init", "module_or_path", "FileMetadataFinalization", "FileTrieFinalization", "init_storagehub_wasm", "__esmMin", "owner", "bucket_id", "location", "size", "fingerprint", "ptr0", "len0", "ptr1", "len1", "ptr2", "len2", "ptr3", "len3", "ret", "v1", "HttpError", "message", "status", "body", "NetworkError", "TimeoutError", "DEFAULT_TIMEOUT_MS", "HttpClient", "options", "method", "path", "url", "headers", "controller", "signal", "timer", "hasExplicitContentType", "h", "candidate", "init", "res", "text", "maybeJson", "err", "msg", "query", "normalizedPath", "k", "v", "value", "m", "MspClient", "_MspClient", "config", "http", "M", "options", "address", "chainId", "message", "signature", "token", "headers", "bucketId", "fileKey", "file", "_options", "path", "authHeaders", "form", "part", "baseHeaders", "res", "contentType", "contentRange", "contentLengthHeader", "parsedLength", "contentLength", "filePath", "encodedPath"]
7
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@storagehub-sdk/msp-client",
3
+ "version": "0.0.1",
4
+ "description": "High-level façade around @storagehub-sdk/core for easy StorageHub integration",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "publishConfig": {
10
+ "access": "public",
11
+ "registry": "https://registry.npmjs.org/"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md"
16
+ ],
17
+ "dependencies": {
18
+ "@storagehub-sdk/core": "0.0.1"
19
+ },
20
+ "engines": {
21
+ "node": ">=22"
22
+ },
23
+ "scripts": {
24
+ "build": "node ../scripts/build.js",
25
+ "dev": "node ../scripts/build.js --watch",
26
+ "lint": "eslint \"{src/**/*.ts,src/**/*.tsx}\"",
27
+ "format": "prettier --write \"{src/**/*.ts,src/**/*.tsx}\"",
28
+ "format:check": "prettier --check \"{src/**/*.ts,src/**/*.tsx}\"",
29
+ "test": "vitest",
30
+ "typecheck": "tsc --noEmit",
31
+ "coverage": "vitest run --coverage"
32
+ }
33
+ }