w3pk 0.8.2 → 0.8.3

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 CHANGED
@@ -333,10 +333,10 @@ import { getCurrentBuildHash, verifyBuildHash } from 'w3pk'
333
333
  // Get IPFS hash of installed w3pk build
334
334
  const hash = await getCurrentBuildHash()
335
335
  console.log('Build hash:', hash)
336
- // => bafybeia3i2dbrloph6lxjlzl6aetkb5tcoelcq4l3d3kqjrkq4x2u4sbvq
336
+ // => bafybeiecegenbzltuaiel3i6z3azesl6y32ugicavyvasfeyddsbnuhzkq
337
337
 
338
338
  // Verify against trusted hash (from GitHub releases)
339
- const trusted = 'bafybeia3i2dbrloph6lxjlzl6aetkb5tcoelcq4l3d3kqjrkq4x2u4sbvq'
339
+ const trusted = 'bafybeiecegenbzltuaiel3i6z3azesl6y32ugicavyvasfeyddsbnuhzkq'
340
340
  const isValid = await verifyBuildHash(trusted)
341
341
  if (isValid) {
342
342
  console.log('✅ Build integrity verified!')
@@ -350,7 +350,7 @@ See [Build Verification Guide](./docs/BUILD_VERIFICATION.md) for complete docume
350
350
  ### Current Build Hash (v0.7.6)
351
351
 
352
352
  ```
353
- bafybeia3i2dbrloph6lxjlzl6aetkb5tcoelcq4l3d3kqjrkq4x2u4sbvq
353
+ bafybeiecegenbzltuaiel3i6z3azesl6y32ugicavyvasfeyddsbnuhzkq
354
354
  ```
355
355
 
356
356
  **Verify package integrity:**
@@ -358,7 +358,7 @@ bafybeia3i2dbrloph6lxjlzl6aetkb5tcoelcq4l3d3kqjrkq4x2u4sbvq
358
358
  ```typescript
359
359
  import { verifyBuildHash } from 'w3pk'
360
360
 
361
- const TRUSTED_HASH = 'bafybeia3i2dbrloph6lxjlzl6aetkb5tcoelcq4l3d3kqjrkq4x2u4sbvq'
361
+ const TRUSTED_HASH = 'bafybeiecegenbzltuaiel3i6z3azesl6y32ugicavyvasfeyddsbnuhzkq'
362
362
  const isValid = await verifyBuildHash(TRUSTED_HASH)
363
363
 
364
364
  if (!isValid) {
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Chainlist types
3
+ */
4
+ interface Chain {
5
+ name: string;
6
+ chain: string;
7
+ icon?: string;
8
+ rpc: string[];
9
+ features?: Array<{
10
+ name: string;
11
+ }>;
12
+ faucets: string[];
13
+ nativeCurrency: {
14
+ name: string;
15
+ symbol: string;
16
+ decimals: number;
17
+ };
18
+ infoURL: string;
19
+ shortName: string;
20
+ chainId: number;
21
+ networkId: number;
22
+ slip44?: number;
23
+ ens?: {
24
+ registry: string;
25
+ };
26
+ explorers?: Array<{
27
+ name: string;
28
+ url: string;
29
+ icon?: string;
30
+ standard: string;
31
+ }>;
32
+ title?: string;
33
+ status?: string;
34
+ redFlags?: string[];
35
+ }
36
+ interface ChainlistOptions {
37
+ /**
38
+ * Custom URL for chains.json data
39
+ * @default 'https://chainid.network/chains.json'
40
+ */
41
+ chainsJsonUrl?: string;
42
+ /**
43
+ * Cache duration in milliseconds
44
+ * @default 3600000 (1 hour)
45
+ */
46
+ cacheDuration?: number;
47
+ }
48
+
49
+ /**
50
+ * Chainlist module for fetching RPC endpoints
51
+ */
52
+
53
+ /**
54
+ * Get RPC endpoints for a specific chain ID, excluding those that require API keys
55
+ *
56
+ * @param chainId - The chain ID to get endpoints for
57
+ * @param options - Optional configuration
58
+ * @returns Array of RPC URLs that don't require API keys
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * import { getEndpoints } from 'w3pk/chainlist'
63
+ *
64
+ * // Get Ethereum mainnet RPCs
65
+ * const endpoints = await getEndpoints(1)
66
+ * console.log(endpoints)
67
+ * // [
68
+ * // "https://api.mycryptoapi.com/eth",
69
+ * // "https://cloudflare-eth.com",
70
+ * // "https://ethereum-rpc.publicnode.com",
71
+ * // ...
72
+ * // ]
73
+ * ```
74
+ */
75
+ declare function getEndpoints(chainId: number, options?: ChainlistOptions): Promise<string[]>;
76
+ /**
77
+ * Get all available chains
78
+ *
79
+ * @param options - Optional configuration
80
+ * @returns Array of all chains
81
+ */
82
+ declare function getAllChains(options?: ChainlistOptions): Promise<Chain[]>;
83
+ /**
84
+ * Get chain information by chain ID
85
+ *
86
+ * @param chainId - The chain ID to get information for
87
+ * @param options - Optional configuration
88
+ * @returns Chain information or undefined if not found
89
+ */
90
+ declare function getChainById(chainId: number, options?: ChainlistOptions): Promise<Chain | undefined>;
91
+ /**
92
+ * Clear the chains data cache
93
+ */
94
+ declare function clearCache(): void;
95
+
96
+ export { type Chain, type ChainlistOptions, clearCache, getAllChains, getChainById, getEndpoints };
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Chainlist types
3
+ */
4
+ interface Chain {
5
+ name: string;
6
+ chain: string;
7
+ icon?: string;
8
+ rpc: string[];
9
+ features?: Array<{
10
+ name: string;
11
+ }>;
12
+ faucets: string[];
13
+ nativeCurrency: {
14
+ name: string;
15
+ symbol: string;
16
+ decimals: number;
17
+ };
18
+ infoURL: string;
19
+ shortName: string;
20
+ chainId: number;
21
+ networkId: number;
22
+ slip44?: number;
23
+ ens?: {
24
+ registry: string;
25
+ };
26
+ explorers?: Array<{
27
+ name: string;
28
+ url: string;
29
+ icon?: string;
30
+ standard: string;
31
+ }>;
32
+ title?: string;
33
+ status?: string;
34
+ redFlags?: string[];
35
+ }
36
+ interface ChainlistOptions {
37
+ /**
38
+ * Custom URL for chains.json data
39
+ * @default 'https://chainid.network/chains.json'
40
+ */
41
+ chainsJsonUrl?: string;
42
+ /**
43
+ * Cache duration in milliseconds
44
+ * @default 3600000 (1 hour)
45
+ */
46
+ cacheDuration?: number;
47
+ }
48
+
49
+ /**
50
+ * Chainlist module for fetching RPC endpoints
51
+ */
52
+
53
+ /**
54
+ * Get RPC endpoints for a specific chain ID, excluding those that require API keys
55
+ *
56
+ * @param chainId - The chain ID to get endpoints for
57
+ * @param options - Optional configuration
58
+ * @returns Array of RPC URLs that don't require API keys
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * import { getEndpoints } from 'w3pk/chainlist'
63
+ *
64
+ * // Get Ethereum mainnet RPCs
65
+ * const endpoints = await getEndpoints(1)
66
+ * console.log(endpoints)
67
+ * // [
68
+ * // "https://api.mycryptoapi.com/eth",
69
+ * // "https://cloudflare-eth.com",
70
+ * // "https://ethereum-rpc.publicnode.com",
71
+ * // ...
72
+ * // ]
73
+ * ```
74
+ */
75
+ declare function getEndpoints(chainId: number, options?: ChainlistOptions): Promise<string[]>;
76
+ /**
77
+ * Get all available chains
78
+ *
79
+ * @param options - Optional configuration
80
+ * @returns Array of all chains
81
+ */
82
+ declare function getAllChains(options?: ChainlistOptions): Promise<Chain[]>;
83
+ /**
84
+ * Get chain information by chain ID
85
+ *
86
+ * @param chainId - The chain ID to get information for
87
+ * @param options - Optional configuration
88
+ * @returns Chain information or undefined if not found
89
+ */
90
+ declare function getChainById(chainId: number, options?: ChainlistOptions): Promise<Chain | undefined>;
91
+ /**
92
+ * Clear the chains data cache
93
+ */
94
+ declare function clearCache(): void;
95
+
96
+ export { type Chain, type ChainlistOptions, clearCache, getAllChains, getChainById, getEndpoints };
package/dist/index.js CHANGED
@@ -678,5 +678,5 @@ ${e}`)}`:n!=null?`${n.split(`
678
678
  ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Tp(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function dl(r,e=""){if(Tp(r)){let t=ul(r,e);return r.errors.length>0?(e=`${e} `,t+=`
679
679
  ${e}${r.errors.map(n=>`${dl(n,`${e}`)}`).join(`
680
680
  ${e}`)}`):t+=`
681
- ${e}[Error list was empty]`,t.trim()}return ul(r,e)}function Rp(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function qi(r,e){let t=Rp(`${r}:trace`);return G.enabled(`${r}:trace`)&&G.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=G(`${r}:trace`,e)),Object.assign(G(r,e),{error:G(`${r}:error`,e),trace:t,newScope:n=>qi(`${r}:${n}`,e)})}function ll(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var hl=m(()=>{"use strict";or();yn();di();cl();G.formatters.b=r=>r==null?"undefined":ie.baseEncode(r);G.formatters.t=r=>r==null?"undefined":W.baseEncode(r);G.formatters.m=r=>r==null?"undefined":ui.baseEncode(r);G.formatters.p=r=>r==null?"undefined":r.toString();G.formatters.c=r=>r==null?"undefined":r.toString();G.formatters.k=r=>r==null?"undefined":r.toString();G.formatters.a=r=>r==null?"undefined":r.toString();G.formatters.e=r=>r==null?"undefined":dl(r)});function Np(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var fl,pl=m(()=>{"use strict";fl=Np});function Mp(r){return r[Symbol.asyncIterator]!=null}function Up(r,e){let t=0;if(Mp(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=fl(r),{value:s,done:i}=n.next();if(i===!0)return(function*(){})();let o=e(s,t++);if(typeof o.then=="function")return(async function*(){await o&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){o===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var ml,gl=m(()=>{"use strict";pl();ml=Up});function _t(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var yl=m(()=>{"use strict"});async function wl(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Kn(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new Kn(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Kn,bl=m(()=>{"use strict";Kn=class extends Error{constructor(t,n,s){super(t??"The operation was aborted");h(this,"type");h(this,"code");this.type="aborted",this.name=s??"AbortError",this.code=n??"ABORT_ERR"}}});function xl(){return new Hi}var Hi,Sl=m(()=>{"use strict";yl();bl();Hi=class{constructor(){h(this,"readNext");h(this,"haveNext");h(this,"ended");h(this,"nextResult");h(this,"error");this.ended=!1,this.readNext=_t(),this.haveNext=_t()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=_t(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=_t(),await wl(this.readNext.promise,t?.signal,t)}}});function Lp(r){return r[Symbol.asyncIterator]!=null}async function _p(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Op(r){let e=new AbortController,t=xl();_p(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Kp(r){for(let e of r)yield*e}function zp(...r){let e=[];for(let t of r)Lp(t)||e.push(t);return e.length===r.length?Kp(e):Op(r)}var Al,vl=m(()=>{"use strict";Sl();Al=zp});var qp,zn,kl=m(()=>{"use strict";hl();Mn();gl();vl();Cr();qp=qi("blockstore:core:tiered"),zn=class extends be{constructor(t){super();h(this,"stores");this.stores=t.slice()}async put(t,n,s){return await Promise.all(this.stores.map(async i=>{await i.put(t,n,s)})),t}async*get(t,n){let s;for(let i of this.stores)try{yield*i.get(t,n);return}catch(o){s=o,qp.error(o)}throw s??new Ue}async has(t,n){for(let s of this.stores)if(await s.has(t,n))return!0;return!1}async delete(t,n){await Promise.all(this.stores.map(async s=>{await s.delete(t,n)}))}async*putMany(t,n={}){for await(let s of t)await this.put(s.cid,s.bytes,n),yield s.cid}async*deleteMany(t,n={}){for await(let s of t)await this.delete(s,n),yield s}async*getAll(t){let n=new Set;yield*ml(Al(...this.stores.map(s=>s.getAll(t))),s=>{let i=s.cid.toString();return n.has(i)?!1:(n.add(i),!0)})}}});var Cl={};T(Cl,{BaseBlockstore:()=>be,BlackHoleBlockstore:()=>Ln,MemoryBlockstore:()=>Un,TieredBlockstore:()=>zn});var El=m(()=>{"use strict";Cr();nl();sl();kl()});var Pl=I((K1,Hp)=>{Hp.exports={name:"w3pk",version:"0.8.2",description:"WebAuthn SDK for passwordless authentication, encrypted wallets, ERC-5564 stealth addresses, and zero-knowledge proofs",author:"Julien B\xE9ranger",license:"GPL-3.0",repository:{type:"git",url:"https://github.com/w3hc/w3pk.git"},bugs:{url:"https://github.com/w3hc/w3pk/issues"},homepage:"https://github.com/w3hc/w3pk#readme",keywords:["webauthn","passkey","authentication","passwordless","fido2","biometric","ethereum","web3","encryption","zero-knowledge","zk-proofs","zk-snarks","privacy","stealth-address","erc-5564","erc-6538","unlinkable","anonymous-transactions","privacy-preserving","ecdh","secp256k1","view-tags","circom","groth16","merkle-tree","commitment-scheme"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./zk":{types:"./dist/zk/index.d.ts",import:"./dist/zk/index.mjs",require:"./dist/zk/index.js"},"./zk/utils":{types:"./dist/zk/utils.d.ts",import:"./dist/zk/utils.mjs",require:"./dist/zk/utils.js"},"./chainlist":{types:"./dist/chainlist/index.d.ts",import:"./dist/chainlist/index.mjs",require:"./dist/chainlist/index.js"}},sideEffects:!1,files:["dist","README.md","LICENSE","docs/","scripts/compute-build-hash.mjs"],scripts:{build:"tsup","build:zk":"npm run build && npm run compile:circuits","compile:circuits":"node scripts/compile-circuits.js",dev:"tsup --watch",test:"tsx test/test.ts && tsx test/comprehensive.test.ts && tsx test/backup.test.ts && tsx test/social-recovery.test.ts && tsx test/recovery-education.test.ts && tsx test/zk/zk.test.ts && tsx test/nft-ownership.test.ts && tsx test/chainlist.test.ts && tsx test/eip7702.test.ts && tsx test/erc5564.test.ts && tsx test/zk/key-stretching.test.ts && tsx test/username-encoding.test.ts && tsx test/username-validation.test.ts && tsx test/origin-derivation.test.ts && tsx test/build-hash.test.ts && tsx test/credential-checking.test.ts && tsx test/webauthn-native.test.ts && tsx test/persistent-session.test.ts && tsx test/sign-message.test.ts && tsx test/requirereauth.test.ts","test:basic":"tsx test/test.ts","test:comprehensive":"tsx test/comprehensive.test.ts","test:backup":"tsx test/backup.test.ts","test:social-recovery":"tsx test/social-recovery.test.ts","test:education":"tsx test/recovery-education.test.ts","test:username":"tsx test/username-encoding.test.ts && tsx test/username-validation.test.ts","test:recovery":"tsx test/backup.test.ts && tsx test/social-recovery.test.ts && tsx test/recovery-education.test.ts","test:zk":"tsx test/zk/zk.test.ts","test:nft":"tsx test/nft-ownership.test.ts","test:chainlist":"tsx test/chainlist.test.ts","test:eip7702":"tsx test/eip7702.test.ts","test:erc5564":"tsx test/erc5564.test.ts",prepublishOnly:"pnpm build","build:hash":"node scripts/compute-build-hash.mjs","release:notes":"node scripts/generate-release-notes.mjs",html:"lsof -ti:3000 | xargs kill -9 2>/dev/null || true && tsup && npx serve . -l 3000 & sleep 5 && open http://localhost:3000/checker.html"},packageManager:"pnpm@10.6.4",dependencies:{},devDependencies:{"@types/node":"^24.9.0","@types/qrcode":"^1.5.5",circomlib:"^2.0.5",tsup:"^8.5.0",tsx:"^4.20.6",typescript:"^5.9.3"},peerDependencies:{ethers:"^6.0.0"},optionalDependencies:{"@ipld/car":"^5.4.2","blockstore-core":"^6.1.1",circomlibjs:"^0.1.7","ipfs-unixfs-importer":"^16.0.1",qrcode:"^1.5.4",snarkjs:"^0.7.5"}}});var Gp={};T(Gp,{ApiError:()=>Br,AuthenticationError:()=>de,CryptoError:()=>N,DEFAULT_TAG:()=>Ce,RecoverySimulator:()=>dt,RegistrationError:()=>et,StealthAddressModule:()=>nt,StorageError:()=>F,WalletError:()=>v,Web3Passkey:()=>ht,Web3PasskeyError:()=>z,assertEthereumAddress:()=>Ir,assertMnemonic:()=>ji,assertUsername:()=>Dr,createWeb3Passkey:()=>Il,default:()=>Vp,getAllTopics:()=>Cs,getCurrentBuildHash:()=>Vi,getCurrentOrigin:()=>Ht,getExplainer:()=>ks,getPackageVersion:()=>Wi,getW3pkBuildHash:()=>$i,isStrongPassword:()=>Yi,normalizeOrigin:()=>Or,searchExplainers:()=>Es,validateEthereumAddress:()=>qn,validateMnemonic:()=>$n,validateUsername:()=>Hn,verifyBuildHash:()=>Bl});module.exports=Ul(Gp);j();function qn(r){return/^0x[a-fA-F0-9]{40}$/.test(r)}function Hn(r){return r.length<3||r.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(r)}function $n(r){let e=r.trim().split(/\s+/);return e.length===12||e.length===24}function Ir(r){if(!qn(r))throw new Error("Invalid Ethereum address format")}function Dr(r){if(!Hn(r))throw new Error("Username must be 3-50 characters long and contain only letters, numbers, underscores, and hyphens. Must start and end with a letter or number.")}function ji(r){if(!$n(r))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function Yi(r){if(r.length<12)return!1;let e=/[A-Z]/.test(r),t=/[a-z]/.test(r),n=/[0-9]/.test(r),s=/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(r);return!(!e||!t||!n||!s||["password","12345678","qwerty","abc123","password123","admin","letmein"].some(o=>r.toLowerCase().includes(o)))}U();Kt();function Ol(){let r=new Uint8Array(32);return crypto.getRandomValues(r),he(r)}async function Kl(r){try{let e=new Uint8Array(r),t=zl(e);if(t===-1)return null;let n=e.slice(t);if(!((n[32]&64)!==0))return null;let o=37;o+=16;let a=n[o]<<8|n[o+1];o+=2,o+=a;let c=n.slice(o),d=await ql(c);return he(d)}catch(e){return console.error("Failed to extract public key:",e),null}}function zl(r){let e=new Uint8Array([104,97,117,116,104,68,97,116,97]);for(let t=0;t<r.length-e.length;t++){let n=!0;for(let s=0;s<e.length;s++)if(r[t+s]!==e[s]){n=!1;break}if(n){let s=r[t+e.length],i=t+e.length+1;if(s>=88&&s<=91){let o=s-87;i+=o}return i}}return-1}async function ql(r){let e=Qi(r,-2),t=Qi(r,-3);if(!e||!t)throw new Error("Failed to extract EC coordinates from COSE key");let n=new Uint8Array(65);n[0]=4,n.set(e,1),n.set(t,33);let s=new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0]),i=new Uint8Array(s.length+n.length);return i.set(s,0),i.set(n,s.length),i.buffer}function Qi(r,e){let t=e<0?32+(-1-e):e;for(let n=0;n<r.length-33;n++)if(r[n]===t&&(r[n+1]===88&&r[n+2]===32||r[n+1]===88&&r[n+2]===32))return r.slice(n+3,n+35);return null}async function Xi(r){try{let{username:e,ethereumAddress:t}=r;Dr(e),Ir(t);let n=new _e;if(await n.userExists(e))throw new Error("Username already registered");let s=Ol(),o=new TextEncoder().encode(e),a=he(o),c=Le(s),d=Le(a),l={challenge:c,rp:{name:"w3pk",id:window.location.hostname},user:{id:d,name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"required",residentKey:"required",requireResidentKey:!0},timeout:6e4,attestation:"none"},f=await navigator.credentials.create({publicKey:l});if(!f)throw new Error("Failed to create credential");let b=await Kl(f.response.attestationObject);if(!b)throw new Error("Public key not returned from authenticator");await n.saveCredential({id:f.id,publicKey:b,username:e,ethereumAddress:t,createdAt:new Date().toISOString(),lastUsed:new Date().toISOString(),signCount:0}),console.log("[register] Credential response:",f.response);let u=f.response.attestationObject;return console.log("[register] Attestation object length:",u.byteLength),{signature:u}}catch(e){throw new et(e instanceof Error?e.message:"Registration failed",e)}}j();U();Kt();function Hl(){let r=new Uint8Array(32);return crypto.getRandomValues(r),he(r)}async function Ur(){try{let r=new _e,e=Hl(),t=[];try{let c=await r.getAllCredentials();c.length>0?(t=c.map(d=>({id:d.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})),console.log(`[login] Found ${t.length} stored credential(s)`)):console.log("[login] No stored credentials found, using discoverable credentials flow")}catch(c){console.warn("[login] Failed to retrieve stored credentials:",c)}let s={challenge:Le(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4};t.length>0&&(s.allowCredentials=t.map(c=>({id:Le(c.id),type:c.type,transports:c.transports})));let i;try{let c=await navigator.credentials.get({publicKey:s});if(!c)throw new Error("Authentication failed - no credential returned");i=c}catch(c){throw c?.name==="NotAllowedError"||c?.message?.toLowerCase().includes("no credentials available")||c?.message?.toLowerCase().includes("no access key")?(await r.getAllCredentials()).length>0?new de("Your passkey is not available on this device. You may need to restore your wallet from a backup, or login on the device where you registered."):new de("No passkey found. Please register first or restore from a backup."):c}let o=await r.getCredentialById(i.id);if(!o)throw new Error("Credential not found in storage. This shouldn't happen - the passkey was authenticated but metadata is missing.");if(!await $l(i,o,r))throw new Error("Signature verification failed");return{verified:!0,user:{username:o.username,ethereumAddress:o.ethereumAddress,credentialId:o.id},signature:i.response.signature}}catch(r){throw new de(r instanceof Error?r.message:"Authentication failed",r)}}async function $l(r,e,t){try{let n=r.response.authenticatorData,s=new DataView(n),o=new Uint8Array(n).slice(0,32),a=window.location.hostname,c=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));if(!Wl(o,c))return console.error("RP ID hash mismatch - possible phishing attack"),!1;let d=s.getUint32(33,!1);if(d>0||e.signCount&&e.signCount>0){let w=e.signCount||0;if(d<=w)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${w}, received=${d}`),!1}let l=Le(e.publicKey),f=await crypto.subtle.importKey("spki",l,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),b=r.response.clientDataJSON,u=await crypto.subtle.digest("SHA-256",b),p=new Uint8Array(n.byteLength+u.byteLength);p.set(new Uint8Array(n),0),p.set(new Uint8Array(u),n.byteLength);let y=r.response.signature,C=Vl(new Uint8Array(y));return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,C,p)?(await t.updateSignatureCounter(e.id,d),!0):!1}catch(n){return console.error("Signature verification error:",n),!1}}function Wl(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function Vl(r){let e=2;e++;let t=r[e++];t>32&&(e++,t--);let n=r.slice(e,e+t);e+=t,e++;let s=r[e++];s>32&&(e++,s--);let i=r.slice(e,e+s),o=new Uint8Array(64);return o.set(n,32-n.length),o.set(i,64-i.length),o.buffer}j();var Gl="Web3PasskeyWallet",jl=1,me="wallets",Lr=class{constructor(){this.db=null}async init(){return new Promise((e,t)=>{let n=indexedDB.open(Gl,jl);n.onerror=()=>t(new F("Failed to open database",n.error)),n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(me)||s.createObjectStore(me,{keyPath:"ethereumAddress"})}})}async store(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([me],"readwrite").objectStore(me).put(e);o.onerror=()=>n(new F("Failed to store wallet data",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([me],"readonly").objectStore(me).get(e);o.onerror=()=>n(new F("Failed to retrieve wallet data",o.error)),o.onsuccess=()=>t(o.result||null)})}async delete(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([me],"readwrite").objectStore(me).delete(e);o.onerror=()=>n(new F("Failed to delete wallet data",o.error)),o.onsuccess=()=>t()})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([me],"readwrite").objectStore(me).clear();i.onerror=()=>t(new F("Failed to clear wallet data",i.error)),i.onsuccess=()=>e()})}};_r();_r();j();var rt="STANDARD",Ce="MAIN",Jl=2147483647;function Or(r){try{let e=new URL(r),t=`${e.protocol}//${e.hostname.toLowerCase()}`,n=e.port;return n&&!(e.protocol==="https:"&&n==="443"||e.protocol==="http:"&&n==="80")&&(t+=`:${n}`),t}catch(e){throw new v(`Invalid origin URL: ${r}`,e)}}async function Ql(r,e=rt,t=Ce){try{let s=`${Or(r)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(s),a=await crypto.subtle.digest("SHA-256",o);return new DataView(a).getUint32(0,!1)%Jl}catch(n){throw new v(`Failed to derive index from origin "${r}", mode "${e}", and tag "${t}"`,n)}}async function jn(r,e,t,n){try{let s=t||rt,i=(n||Ce).toUpperCase(),o=Or(e),a=await Ql(o,s,i),{address:c,privateKey:d}=Gn(r,a),l={address:c,index:a,origin:o,mode:s,tag:i};return s==="YOLO"&&(l.privateKey=d),l}catch(s){throw new v(`Failed to derive origin-specific address for "${e}" with mode "${t||rt}" and tag "${n||Ce}"`,s)}}function Ht(){if(typeof window>"u"||!window.location)throw new v("getCurrentOrigin() only works in browser environments");return window.location.origin}xe();j();var $=require("ethers");j();function Kr(r){try{let e=$.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/0"),t=$.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/1"),n=t.signingKey.compressedPublicKey,s=e.signingKey.compressedPublicKey;return{stealthMetaAddress:n+s.slice(2),spendingPubKey:n,viewingPubKey:s,viewingKey:e.privateKey,spendingKey:t.privateKey}}catch(e){throw new N("Failed to derive stealth keys",e)}}function ro(r){try{let e="0x"+r.slice(2,68),t="0x"+r.slice(68),n=$.ethers.Wallet.createRandom(),s=n.signingKey.compressedPublicKey,i=Yn(n.privateKey,t),o=$.ethers.keccak256(i),a="0x"+o.slice(2,4),c=oo(e,io(o));return{stealthAddress:ao(c),ephemeralPubKey:s,viewTag:a}}catch(e){throw new N("Failed to generate stealth address",e)}}function no(r,e,t,n,s){try{let i=Yn(r,t),o=$.ethers.keccak256(i);if(s&&("0x"+o.slice(2,4)).toLowerCase()!==s.toLowerCase())return{isForUser:!1};let a=oo(e,io(o)),c=ao(a);return c.toLowerCase()!==n.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:c}}catch{return{isForUser:!1}}}function so(r,e,t){try{let n=Yn(r,t),s=$.ethers.keccak256(n);return Xl(e,s)}catch(n){throw new N("Failed to compute stealth private key",n)}}function Yn(r,e){try{return new $.ethers.Wallet(r).signingKey.computeSharedSecret(e)}catch(t){throw new N("Failed to compute shared secret",t)}}function io(r){try{return new $.ethers.Wallet(r).signingKey.compressedPublicKey}catch(e){throw new N("Failed to multiply generator by scalar",e)}}function oo(r,e){try{let t=$.ethers.SigningKey.computePublicKey(r,!1),n=$.ethers.SigningKey.computePublicKey(e,!1),s=BigInt("0x"+t.slice(4,68)),i=BigInt("0x"+t.slice(68)),o=BigInt("0x"+n.slice(4,68)),a=BigInt("0x"+n.slice(68)),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");if(s===o&&i===a){let p=3n*s*s%c,y=2n*i%c,C=p*to(y,c)%c,g=(C*C-2n*s)%c,w=(C*(s-g)-i)%c;return eo((g+c)%c,(w+c)%c)}let d=((a-i)%c+c)%c,l=((o-s)%c+c)%c,f=d*to(l,c)%c,b=(f*f-s-o)%c,u=(f*(s-b)-i)%c;return eo((b+c)%c,(u+c)%c)}catch(t){throw new N("Failed to add public keys",t)}}function Xl(r,e){try{let t=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),n=BigInt(r),s=BigInt(e);return"0x"+((n+s)%t).toString(16).padStart(64,"0")}catch(t){throw new N("Failed to add private keys",t)}}function eo(r,e){return"0x"+(e%2n===0n?"02":"03")+r.toString(16).padStart(64,"0")}function to(r,e){r=(r%e+e)%e;let[t,n]=[r,e],[s,i]=[1n,0n];for(;n!==0n;){let o=t/n;[t,n]=[n,t-o*n],[s,i]=[i,s-o*i]}return(s%e+e)%e}function ao(r){try{let e=$.ethers.SigningKey.computePublicKey(r,!1),t=$.ethers.keccak256("0x"+e.slice(4));return $.ethers.getAddress("0x"+t.slice(-40))}catch(e){throw new N("Failed to derive address from public key",e)}}var nt=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),n=Kr(t),s=ro(n.stealthMetaAddress);return{stealthAddress:s.stealthAddress,ephemeralPublicKey:s.ephemeralPubKey,viewTag:s.viewTag}}catch(t){throw new z("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let n=await this.getMnemonic(t?.requireAuth),s=Kr(n),i=no(s.viewingKey,s.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag);if(!i.isForUser)return{isForUser:!1};let o=so(s.viewingKey,s.spendingKey,e.ephemeralPublicKey);return{isForUser:!0,stealthAddress:i.stealthAddress,stealthPrivateKey:o}}catch(n){throw new z("Failed to parse announcement","ANNOUNCEMENT_PARSE_ERROR",n)}}async scanAnnouncements(e,t){let n=[];for(let s of e){let i=await this.parseAnnouncement(s,t);i.isForUser&&n.push(i)}return n}async getKeys(e){try{let t=await this.getMnemonic(e?.requireAuth);return Kr(t)}catch(t){throw new z("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new z("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};j();xe();var Zl="Web3PasskeyPersistentSessions",ed=1,re="sessions",zr=class{constructor(){this.db=null}async init(){return new Promise((e,t)=>{let n=indexedDB.open(Zl,ed);n.onerror=()=>t(new F("Failed to open persistent session database",n.error)),n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(re)||s.createObjectStore(re,{keyPath:"ethereumAddress"}).createIndex("expiresAt","expiresAt",{unique:!1})}})}async store(e){if(e.securityMode==="STRICT")throw new F("Cannot persist STRICT mode sessions");return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([re],"readwrite").objectStore(re).put(e);o.onerror=()=>n(new F("Failed to store persistent session",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([re],"readonly").objectStore(re).get(e);o.onerror=()=>n(new F("Failed to retrieve persistent session",o.error)),o.onsuccess=()=>{let a=o.result||null;if(a&&Date.now()>a.expiresAt){this.delete(e).catch(console.error),t(null);return}t(a)}})}async delete(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([re],"readwrite").objectStore(re).delete(e);o.onerror=()=>n(new F("Failed to delete persistent session",o.error)),o.onsuccess=()=>t()})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([re],"readwrite").objectStore(re).clear();i.onerror=()=>t(new F("Failed to clear persistent sessions",i.error)),i.onsuccess=()=>e()})}async cleanupExpired(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([re],"readwrite").objectStore(re).index("expiresAt"),o=Date.now(),a=IDBKeyRange.upperBound(o),c=i.openCursor(a);c.onsuccess=d=>{let l=d.target.result;l?(l.delete(),l.continue()):e()},c.onerror=()=>t(new F("Failed to cleanup expired sessions",c.error))})}};async function co(r,e,t){try{let n=await H(e,t);return await fe(r,n)}catch(n){throw new N("Failed to encrypt mnemonic for persistence",n)}}async function Jn(r,e,t){try{let n=await H(e,t);return await pe(r,n)}catch(n){throw new N("Failed to decrypt mnemonic from persistence",n)}}var qr=class{constructor(e=1,t){this.session=null;this.sessionDuration=e*60*60*1e3,this.persistentConfig={enabled:t?.enabled??!1,duration:t?.duration??168,requireReauth:t?.requireReauth??!0},this.persistentStorage=new zr}async startSession(e,t,n,s,i){let o=new Date(Date.now()+this.sessionDuration).toISOString();if(this.session={mnemonic:e,expiresAt:o,credentialId:t},this.persistentConfig.enabled&&i!=="STRICT"&&n&&s)try{let a=await co(e,t,s),c=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:a,expiresAt:c,credentialId:t,ethereumAddress:n,securityMode:i||"STANDARD",createdAt:Date.now()})}catch(a){console.warn("[w3pk] Failed to persist session:",a)}}getMnemonic(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),null):this.session.mnemonic:null}getCredentialId(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),null):this.session.credentialId:null}isActive(){return this.getMnemonic()!==null}getRemainingTime(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),0):Math.floor((new Date(this.session.expiresAt).getTime()-Date.now())/1e3):0}extendSession(){if(!this.session)throw new Error("No active session to extend");if(new Date>new Date(this.session.expiresAt))throw this.clearSession(),new Error("Session expired, cannot extend");this.session.expiresAt=new Date(Date.now()+this.sessionDuration).toISOString()}async restoreFromPersistentStorage(e,t,n){if(!this.persistentConfig.enabled)return null;try{let s=await this.persistentStorage.retrieve(e);if(!s)return null;if(s.credentialId!==t)return console.warn("[w3pk] Credential ID mismatch, clearing persistent session"),await this.persistentStorage.delete(e),null;let i=await Jn(s.encryptedMnemonic,t,n),o=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:i,expiresAt:o,credentialId:t},i}catch(s){console.warn("[w3pk] Failed to restore persistent session:",s);try{await this.persistentStorage.delete(e)}catch{}return null}}async attemptSilentRestore(){if(!this.persistentConfig.enabled||this.persistentConfig.requireReauth)return null;try{let{CredentialStorage:e}=await Promise.resolve().then(()=>(U(),_)),n=await new e().getAllCredentials();if(n.length===0)return null;for(let s of n){let i=await this.persistentStorage.retrieve(s.ethereumAddress);if(!i)continue;if(i.credentialId!==s.id){console.warn("[w3pk] Credential ID mismatch, skipping this session");continue}let o=await Jn(i.encryptedMnemonic,s.id,s.publicKey),a=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:o,expiresAt:a,credentialId:s.id},{mnemonic:o,ethereumAddress:s.ethereumAddress,credentialId:s.id,publicKey:s.publicKey}}return null}catch(e){return console.warn("[w3pk] Failed to attempt silent restore:",e),null}}async clearSession(){if(this.session&&(this.session.mnemonic="0".repeat(this.session.mnemonic.length)),this.session=null,this.persistentConfig.enabled)try{await this.persistentStorage.clear()}catch(e){console.warn("[w3pk] Failed to clear persistent sessions:",e)}}setSessionDuration(e){this.sessionDuration=e*60*60*1e3}};var Hr={debug:!1,sessionDuration:1,persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:r=>{Hr.debug&&console.error("[w3pk]",r)}};j();var uo="https://chainid.network/chains.json";var $r=null,td=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function rd(r){return td.some(e=>e.test(r))}async function nd(r=uo){let e=await fetch(r);if(!e.ok)throw new Error(`Failed to fetch chains data: ${e.status} ${e.statusText}`);return await e.json()}async function sd(r){let e=r?.chainsJsonUrl??uo,t=r?.cacheDuration??36e5,n=Date.now();if($r&&n-$r.timestamp<t)return $r.data;let s=await nd(e);return $r={data:s,timestamp:n},s}async function lo(r,e){let n=(await sd(e)).find(s=>s.chainId===r);return n?n.rpc.filter(s=>!rd(s)&&!s.startsWith("wss://")&&!s.startsWith("ws://")):[]}var id=new Set([1,10,8453,42161,57073,100,42220,137,42,15,40,41,44,46,47,50,51,56,61,71,82,83,95,97,112,123,130,146,151,153,171,180,183,185,195,215,228,247,248,252,261,267,291,293,311,332,336,395,401,416,466,480,488,510,545,634,647,648,747,831,919,938,945,957,964,970,980,995,997,1001,1003,1024,1030,1114,1125,1135,1149,1188,1284,1285,1287,1300,1301,1315,1337,1338,1339,1424,1514,1687,1727,1729,1740,1750,1829,1868,1946,1961,1962,1969,1989,1995,2017,2020,2031,2043,2109,2241,2340,2345,2440,2522,2559,2649,3068,3109,3338,3502,3799,3888,3889,4e3,4048,4078,4162,4201,4202,4460,4488,4661,4689,4690,4888,5e3,5003,5124,5234,5330,5424,5522,6283,6342,6398,6678,6806,6934,6942,6969,7117,7171,7200,7208,7368,7518,7668,7672,7744,7771,7869,7897,8008,8118,8217,8408,8700,8726,8727,8844,8880,8881,8882,8889,9372,9496,9700,9745,9746,9899,9990,9996,10011,10085,10143,10200,11221,11501,11504,11891,13370,14853,16602,16661,17e3,18880,18881,19991,21e3,21816,21912,25327,32323,33401,34443,41923,42170,43111,44787,47805,48898,48900,49049,49088,5e4,50312,53302,53456,53457,55244,56288,59141,60808,60850,62320,62850,64002,71402,72080,73114,73115,75338,78281,80002,80008,80069,80094,80451,80931,84532,88899,91342,92278,94524,96970,97476,97477,98985,100021,100501,101010,102030,102031,102032,112358,120893,121212,121213,121214,121215,129399,161803,175188,192940,193939,198989,212013,222222,240241,325e3,355110,355113,421614,555777,560048,656476,713715,743111,747474,763373,763375,777777,806582,808813,810180,839999,888991,2019775,2222222,4278608,5734951,6666689,6985385,7080969,7777777,9999999,11142220,11155111,11155420,11155931,16969696,19850818,20180427,20250825,28122024,34949059,37084624,52164803,61022448,79479957,96969696,420420421,420420422,888888888,974399131,999999999,1020352220,1273227453,1313161560,1350216234,1380996178,1417429182,1444673419,1482601649,1564830818,2046399126,11297108099,11297108109,88153591557,123420000220,123420001114]);async function od(r,e=1e4){try{let t=new AbortController,n=setTimeout(()=>t.abort(),e),s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},signal:t.signal,body:JSON.stringify({jsonrpc:"2.0",method:"eth_estimateGas",params:[{from:"0xdeadbeef00000000000000000000000000000000",to:"0xdeadbeef00000000000000000000000000000000",data:"0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",value:"0x0"},"latest",{"0xdeadbeef00000000000000000000000000000000":{code:"0xef01000000000000000000000000000000000000000001"}}],id:1})});if(clearTimeout(n),!s.ok)return!1;let i=await s.json();if(i.error){let o=(i.error.message||"").toLowerCase();return!["unsupported","not supported","unknown","invalid","unrecognized","does not support","not implemented"].some(c=>o.includes(c))}return i.result!==void 0}catch{return!1}}async function ho(r,e,t){if(id.has(r))return!0;let n=t?.maxEndpoints||3,s=t?.timeout||1e4;try{let i=await e(r);if(i.length===0)return!1;let o=i.slice(0,n);for(let a of o)if(await od(a,s))return!0;return!1}catch{return!1}}var ht=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.currentSecurityMode="STANDARD";this.config={...Hr,...e},this.walletStorage=new Lr;let t={...Hr.persistentSession,...e.persistentSession};this.sessionManager=new qr(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new nt(e.stealthAddresses,n=>this.getMnemonicFromSession(n)))}async loadZKModule(){if(this.zkModule)return this.zkModule;try{let e=new Function("path","return import(path)"),{ZKProofModule:t}=await e("w3pk/zk"),n=this.config.zkProofs||{};return this.zkModule=new t(n),this.zkModule}catch{throw new Error("ZK module not available. Install dependencies: npm install snarkjs circomlibjs")}}async getMnemonicFromSession(e=!1,t){let n=t||this.currentSecurityMode;if(!e){let f=this.sessionManager.getMnemonic();if(f)return f}if(!this.currentUser)throw new v("Must be authenticated. Call login() first.");let s=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!s)throw new v("No wallet found. Generate a wallet first.");if(!(await Ur()).user)throw new v("Authentication failed");let c=(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(s.credentialId))?.publicKey,d=await H(s.credentialId,c),l=await pe(s.encryptedMnemonic,d);return await this.sessionManager.startSession(l,s.credentialId,this.currentUser.ethereumAddress,c,n),l}async register(e){try{this.currentWallet?.address||await this.generateWallet();let t=this.currentWallet.address,n=this.currentWallet.mnemonic;await Xi({username:e.username,ethereumAddress:t}),this.currentUser={id:t,username:e.username,displayName:e.username,ethereumAddress:t};let i=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialByAddress(t);if(!i)throw new v("Credential not found after registration");let o=i.id,a=i.publicKey,c=await H(o,a),d=await fe(n,c);return await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:d,credentialId:o,createdAt:new Date().toISOString()}),await this.sessionManager.startSession(n,o,t,a,"STANDARD"),this.currentWallet={address:t,mnemonic:n},this.config.onAuthStateChanged?.(!0,this.currentUser),{address:t,username:e.username}}catch(t){throw this.config.onError?.(t),t}}async login(){try{let e=await this.sessionManager.attemptSilentRestore();if(e){if(this.currentUser={id:e.ethereumAddress,username:e.ethereumAddress,displayName:e.ethereumAddress,ethereumAddress:e.ethereumAddress},!await this.walletStorage.retrieve(this.currentUser.ethereumAddress))return await this.sessionManager.clearSession(),this.login();let f=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(e.credentialId);return f&&(this.currentUser.username=f.username,this.currentUser.displayName=f.username),this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser}let t=await Ur();if(!t.verified||!t.user)throw new de("Login failed");this.currentUser={id:t.user.ethereumAddress,username:t.user.username,displayName:t.user.username,ethereumAddress:t.user.ethereumAddress};let n=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!n)throw new v("No wallet found for this user. You may need to register first.");let o=(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(n.credentialId))?.publicKey,a=await this.sessionManager.restoreFromPersistentStorage(this.currentUser.ethereumAddress,n.credentialId,o||""),c;if(a)c=a;else{let d=await H(n.credentialId,o);c=await pe(n.encryptedMnemonic,d),await this.sessionManager.startSession(c,n.credentialId,this.currentUser.ethereumAddress,o,"STANDARD")}return this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser}catch(e){throw this.config.onError?.(e),e}}async logout(){this.currentUser=null,this.currentWallet=null,await this.sessionManager.clearSession(),this.config.onAuthStateChanged?.(!1,void 0)}get isAuthenticated(){return this.currentUser!==null}get user(){return this.currentUser}async hasExistingCredential(){try{return(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getAllCredentials()).length>0}catch{return!1}}async getExistingCredentialCount(){try{return(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getAllCredentials()).length}catch{return 0}}async listExistingCredentials(){try{return(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getAllCredentials()).map(n=>({username:n.username,ethereumAddress:n.ethereumAddress,createdAt:n.createdAt,lastUsed:n.lastUsed}))}catch{return[]}}async generateWallet(){try{let e=Vn();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new v("Failed to generate wallet",e)}}async deriveWallet(e,t,n){try{if(!this.currentUser)throw new v("Must be authenticated to derive wallet");let s=e||rt,i=t||Ce,o=n?.origin||Ht();this.currentSecurityMode=s;let a=s==="STRICT"?!0:n?.requireAuth||!1,c=await this.getMnemonicFromSession(a,s),d=await jn(c,o,s,i);return{address:d.address,privateKey:d.privateKey,index:d.index,origin:d.origin,mode:d.mode,tag:d.tag}}catch(s){throw this.config.onError?.(s),new v("Failed to derive wallet",s)}}async exportMnemonic(){throw new v("exportMnemonic() disabled for security. Use createBackupFile() instead.")}async importMnemonic(e){try{if(!this.currentUser)throw new v("Must be authenticated to import mnemonic");if(!e||e.trim().split(/\s+/).length<12)throw new v("Invalid mnemonic: must be at least 12 words");let t=await Ur();if(!t.user)throw new v("Authentication failed");let n=t.user.credentialId,o=(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(n))?.publicKey,a=await H(n,o),c=await fe(e.trim(),a);await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:c,credentialId:n,createdAt:new Date().toISOString()}),this.currentWallet={address:this.currentUser.ethereumAddress,mnemonic:e.trim()},await this.sessionManager.startSession(e.trim(),n,this.currentUser.ethereumAddress,o,"STANDARD")}catch(t){throw this.config.onError?.(t),new v("Failed to import mnemonic",t)}}async signMessage(e,t){try{if(!this.currentUser)throw new v("Must be authenticated to sign message");let n=t?.mode||rt,s=t?.tag||Ce,i=t?.origin||Ht();this.currentSecurityMode=n;let o=n==="STRICT"?!0:t?.requireAuth||!1,a=await this.getMnemonicFromSession(o,n),c=await jn(a,i,n,s),{Wallet:d}=await import("ethers"),l;if(c.privateKey)l=new d(c.privateKey);else{let{deriveWalletFromMnemonic:b}=await Promise.resolve().then(()=>(_r(),Zi)),{privateKey:u}=b(a,c.index);l=new d(u)}return{signature:await l.signMessage(e),address:c.address,mode:c.mode,tag:c.tag,origin:c.origin}}catch(n){throw this.config.onError?.(n),new v("Failed to sign message",n)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new v("Must be authenticated to sign authorization");let{Wallet:n,keccak256:s,concat:i,toBeHex:o,Signature:a}=await import("ethers"),c,d;if(e.privateKey)c=new n(e.privateKey),d=c.address;else{let C=await this.getMnemonicFromSession(t?.requireAuth);c=n.fromPhrase(C),d=c.address}let l=BigInt(e.chainId||1),f=e.nonce||0n,b=i(["0x05",o(l,32),e.contractAddress.toLowerCase(),o(f,32)]),u=s(b),p=c.signingKey.sign(u),y=a.from(p);return{chainId:l,address:d.toLowerCase(),nonce:f,yParity:y.yParity,r:y.r,s:y.s}}catch(n){throw this.config.onError?.(n),new v("Failed to sign authorization",n)}}async getEndpoints(e){return lo(e)}async supportsEIP7702(e,t){return ho(e,this.getEndpoints.bind(this),t)}get zk(){return new Proxy({},{get:(e,t)=>async(...n)=>(await this.loadZKModule())[t](...n)})}async getBackupStatus(){if(!this.currentUser)throw new v("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(ya(),ga));return new e().getBackupStatus(this.currentUser.ethereumAddress)}async createBackupFile(e="password",t){if(!this.currentUser)throw new v("Must be authenticated to create backup");let n=await this.getMnemonicFromSession(!0),{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),ye)),i=new s,o;if(e==="password"){if(!t)throw new v("Password required for password-based backup");let{backupFile:a}=await i.createPasswordBackup(n,this.currentUser.ethereumAddress,t);o=i.createDownloadableBackup(a)}else if(e==="passkey"){let a=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!a)throw new v("No wallet data found");let d=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(a.credentialId);if(!d)throw new v("Credential not found");let{backupFile:l}=await i.createPasskeyBackup(n,this.currentUser.ethereumAddress,d.id,d.publicKey);o=i.createDownloadableBackup(l)}else if(e==="hybrid"){if(!t)throw new v("Password required for hybrid backup");let a=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!a)throw new v("No wallet data found");let d=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(a.credentialId);if(!d)throw new v("Credential not found");let{backupFile:l}=await i.createHybridBackup(n,this.currentUser.ethereumAddress,t,d.id,d.publicKey);o=i.createDownloadableBackup(l)}else throw new v(`Unknown encryption type: ${e}`);return o}async setupSocialRecovery(e,t,n){if(!this.currentUser)throw new v("Must be authenticated to set up social recovery");let s=await this.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(oe(),ye)),o=new i,{backupFile:a}=n?await o.createPasswordBackup(s,this.currentUser.ethereumAddress,n):await o.createPasskeyBackup(s,this.currentUser.ethereumAddress,(await this.walletStorage.retrieve(this.currentUser.ethereumAddress)).credentialId,(await(await Promise.resolve().then(()=>(U(),_))).CredentialStorage.prototype.getCredentialById.call(new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage,(await this.walletStorage.retrieve(this.currentUser.ethereumAddress)).credentialId)).publicKey),{SocialRecovery:c}=await Promise.resolve().then(()=>(cn(),an));return{guardianShares:(await new c().splitAmongGuardians(a,e,t)).guardianShares,setupComplete:!0}}async generateGuardianInvite(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(cn(),an)),s=new n,i=await s.createGuardianInvitation(e,t),o=s.createShareDownload(e);return{qrCodeDataURL:i.qrCodeDataURL,shareDocument:i.shareDocument,downloadBlob:o.blob,filename:o.filename}}async recoverFromGuardians(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(cn(),an)),{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),ye)),i=new n,o=new s,a=e.map(d=>typeof d=="string"?i.parseGuardianShare(d):d),c=await i.recoverFromShares(a);if(c.encryptionMethod==="password"){if(!t)throw new v("Password required to decrypt password-protected backup");return o.restoreWithPassword(c,t)}else throw new v("Passkey-encrypted backups not supported for guardian recovery. Use password-protected backups.")}async restoreFromBackupFile(e,t){let{BackupFileManager:n}=await Promise.resolve().then(()=>(oe(),ye)),s=new n,i=await s.parseBackupFile(e);if(i.encryptionMethod==="password"){if(!t)throw new v("Password required to restore password-encrypted backup");return s.restoreWithPassword(i,t)}else if(i.encryptionMethod==="passkey"){if(!this.currentUser)throw new v("Must be logged in with passkey to restore passkey-encrypted backup. Call login() first.");let o=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!o)throw new v("No wallet data found for current user");let c=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(o.credentialId);if(!c)throw new v("Credential not found");return s.restoreWithExistingPasskey(i,c.id,c.publicKey)}else if(i.encryptionMethod==="hybrid"){if(!t)throw new v("Password required to restore hybrid backup");if(!this.currentUser)throw new v("Must be logged in with passkey to restore hybrid backup. Call login() first.");let o=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!o)throw new v("No wallet data found for current user");let c=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(o.credentialId);if(!c)throw new v("Credential not found");return s.restoreWithHybrid(i,t,c.id,c.publicKey)}else throw new v(`Unknown encryption method: ${i.encryptionMethod}`)}async registerWithBackupFile(e,t,n){let{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),ye)),i=new s,o=await i.parseBackupFile(e);if(o.encryptionMethod!=="password")throw new v("Can only register with password-encrypted backups. Use restoreFromBackupFile() for passkey-encrypted backups.");let{mnemonic:a,ethereumAddress:c}=await i.restoreWithPassword(o,t),{Wallet:d}=await import("ethers");if(d.fromPhrase(a).address.toLowerCase()!==c.toLowerCase())throw new v("Backup verification failed: address mismatch");return this.currentWallet={address:c,mnemonic:a},this.register({username:n})}async getSyncStatus(){let{DeviceSyncManager:e}=await Promise.resolve().then(()=>(rr(),un));return new e().getSyncInfo()}async exportForSync(){if(!this.currentUser)throw new v("Must be authenticated to export for sync");let e=await this.getMnemonicFromSession(!0),t=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!t)throw new v("No wallet data found");let s=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(t.credentialId);if(!s)throw new v("Credential not found");let{DeviceSyncManager:i}=await Promise.resolve().then(()=>(rr(),un)),o=new i,{backupFile:a,blob:c}=await o.exportForSync(e,this.currentUser.ethereumAddress,s.id,s.publicKey),d=`w3pk-sync-${this.currentUser.ethereumAddress.substring(0,8)}.json`,l;try{l=await o.generateSyncQR(a)}catch(f){console.warn("QR code generation failed:",f)}return{blob:c,filename:d,qrCode:l}}async importFromSync(e){if(!this.currentUser)throw new v("Must be logged in to import from sync. Call login() first.");let{DeviceSyncManager:t}=await Promise.resolve().then(()=>(rr(),un)),{BackupFileManager:n}=await Promise.resolve().then(()=>(oe(),ye)),s=new n,i=new t,o=await s.parseBackupFile(e),a=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!a)throw new v("No wallet data found for current user");let d=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(a.credentialId);if(!d)throw new v("Credential not found");let{mnemonic:l,ethereumAddress:f}=await i.importFromSync(o,d.id,d.publicKey),b=await(await Promise.resolve().then(()=>(xe(),zt))).deriveEncryptionKeyFromWebAuthn(d.id,d.publicKey),u=await(await Promise.resolve().then(()=>(xe(),zt))).encryptData(l,b);return await this.walletStorage.store({ethereumAddress:f,encryptedMnemonic:u,credentialId:d.id,createdAt:new Date().toISOString()}),{ethereumAddress:f,success:!0}}async detectSyncCapabilities(){let{PlatformDetector:e}=await Promise.resolve().then(()=>(Da(),Ia));return new e().detectSyncCapabilities()}async simulateRecoveryScenario(e){if(!this.currentUser)throw new v("Must be authenticated to run recovery simulation");let t=await this.getBackupStatus(),{RecoverySimulator:n}=await Promise.resolve().then(()=>(nr(),pn));return new n().simulateScenario(e,t)}async runRecoveryTest(){if(!this.currentUser)throw new v("Must be authenticated to run recovery test");let e=await this.getBackupStatus(),{RecoverySimulator:t}=await Promise.resolve().then(()=>(nr(),pn));return new t().runInteractiveTest(e)}async getEducation(e){let{getExplainer:t}=await Promise.resolve().then(()=>(nr(),pn)),n=t(e);if(!n)throw new v(`Unknown education topic: ${e}`);return n}hasActiveSession(){return this.sessionManager.isActive()}getSessionRemainingTime(){return this.sessionManager.getRemainingTime()}extendSession(){try{this.sessionManager.extendSession()}catch(e){throw new v("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}};j();nr();async function $p(r,e="build"){let{importer:t}=await Promise.resolve().then(()=>(tl(),el)),{MemoryBlockstore:n}=await Promise.resolve().then(()=>(El(),Cl)),s=new n,o=t(async function*(){yield{path:e,content:r}}(),s,{cidVersion:1,rawLeaves:!0,wrapWithDirectory:!1});for await(let a of o)return a.cid.toString();throw new Error("Failed to generate CID")}async function Wp(r){let e=["index.js","index.mjs","index.d.ts"],t=[],n=0;for(let o of e){let a=`${r}/${o}`,c=await fetch(a);if(!c.ok)throw new Error(`Failed to fetch ${o}: ${c.statusText}`);let d=await c.arrayBuffer(),l=new Uint8Array(d);t.push(l),n+=l.length}let s=new Uint8Array(n),i=0;for(let o of t)s.set(o,i),i+=o.length;return s}async function $i(r){let e=await Wp(r);return $p(e)}function Wi(){try{return Pl().version}catch{throw new Error("Failed to read package version")}}async function Vi(){let r=Wi();return $i(`https://unpkg.com/w3pk@${r}/dist`)}async function Bl(r){return await Vi()===r}function Il(r={}){return new ht(r)}var Vp=Il;
681
+ ${e}[Error list was empty]`,t.trim()}return ul(r,e)}function Rp(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function qi(r,e){let t=Rp(`${r}:trace`);return G.enabled(`${r}:trace`)&&G.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=G(`${r}:trace`,e)),Object.assign(G(r,e),{error:G(`${r}:error`,e),trace:t,newScope:n=>qi(`${r}:${n}`,e)})}function ll(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var hl=m(()=>{"use strict";or();yn();di();cl();G.formatters.b=r=>r==null?"undefined":ie.baseEncode(r);G.formatters.t=r=>r==null?"undefined":W.baseEncode(r);G.formatters.m=r=>r==null?"undefined":ui.baseEncode(r);G.formatters.p=r=>r==null?"undefined":r.toString();G.formatters.c=r=>r==null?"undefined":r.toString();G.formatters.k=r=>r==null?"undefined":r.toString();G.formatters.a=r=>r==null?"undefined":r.toString();G.formatters.e=r=>r==null?"undefined":dl(r)});function Np(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var fl,pl=m(()=>{"use strict";fl=Np});function Mp(r){return r[Symbol.asyncIterator]!=null}function Up(r,e){let t=0;if(Mp(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=fl(r),{value:s,done:i}=n.next();if(i===!0)return(function*(){})();let o=e(s,t++);if(typeof o.then=="function")return(async function*(){await o&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){o===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var ml,gl=m(()=>{"use strict";pl();ml=Up});function _t(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var yl=m(()=>{"use strict"});async function wl(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Kn(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new Kn(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Kn,bl=m(()=>{"use strict";Kn=class extends Error{constructor(t,n,s){super(t??"The operation was aborted");h(this,"type");h(this,"code");this.type="aborted",this.name=s??"AbortError",this.code=n??"ABORT_ERR"}}});function xl(){return new Hi}var Hi,Sl=m(()=>{"use strict";yl();bl();Hi=class{constructor(){h(this,"readNext");h(this,"haveNext");h(this,"ended");h(this,"nextResult");h(this,"error");this.ended=!1,this.readNext=_t(),this.haveNext=_t()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=_t(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=_t(),await wl(this.readNext.promise,t?.signal,t)}}});function Lp(r){return r[Symbol.asyncIterator]!=null}async function _p(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Op(r){let e=new AbortController,t=xl();_p(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Kp(r){for(let e of r)yield*e}function zp(...r){let e=[];for(let t of r)Lp(t)||e.push(t);return e.length===r.length?Kp(e):Op(r)}var Al,vl=m(()=>{"use strict";Sl();Al=zp});var qp,zn,kl=m(()=>{"use strict";hl();Mn();gl();vl();Cr();qp=qi("blockstore:core:tiered"),zn=class extends be{constructor(t){super();h(this,"stores");this.stores=t.slice()}async put(t,n,s){return await Promise.all(this.stores.map(async i=>{await i.put(t,n,s)})),t}async*get(t,n){let s;for(let i of this.stores)try{yield*i.get(t,n);return}catch(o){s=o,qp.error(o)}throw s??new Ue}async has(t,n){for(let s of this.stores)if(await s.has(t,n))return!0;return!1}async delete(t,n){await Promise.all(this.stores.map(async s=>{await s.delete(t,n)}))}async*putMany(t,n={}){for await(let s of t)await this.put(s.cid,s.bytes,n),yield s.cid}async*deleteMany(t,n={}){for await(let s of t)await this.delete(s,n),yield s}async*getAll(t){let n=new Set;yield*ml(Al(...this.stores.map(s=>s.getAll(t))),s=>{let i=s.cid.toString();return n.has(i)?!1:(n.add(i),!0)})}}});var Cl={};T(Cl,{BaseBlockstore:()=>be,BlackHoleBlockstore:()=>Ln,MemoryBlockstore:()=>Un,TieredBlockstore:()=>zn});var El=m(()=>{"use strict";Cr();nl();sl();kl()});var Pl=I((K1,Hp)=>{Hp.exports={name:"w3pk",version:"0.8.3",description:"WebAuthn SDK for passwordless authentication, encrypted wallets, ERC-5564 stealth addresses, and zero-knowledge proofs",author:"Julien B\xE9ranger",license:"GPL-3.0",repository:{type:"git",url:"https://github.com/w3hc/w3pk.git"},bugs:{url:"https://github.com/w3hc/w3pk/issues"},homepage:"https://github.com/w3hc/w3pk#readme",keywords:["webauthn","passkey","authentication","passwordless","fido2","biometric","ethereum","web3","encryption","zero-knowledge","zk-proofs","zk-snarks","privacy","stealth-address","erc-5564","erc-6538","unlinkable","anonymous-transactions","privacy-preserving","ecdh","secp256k1","view-tags","circom","groth16","merkle-tree","commitment-scheme"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./zk":{types:"./dist/zk/index.d.ts",import:"./dist/zk/index.mjs",require:"./dist/zk/index.js"},"./zk/utils":{types:"./dist/zk/utils.d.ts",import:"./dist/zk/utils.mjs",require:"./dist/zk/utils.js"},"./chainlist":{types:"./dist/chainlist/index.d.ts",import:"./dist/chainlist/index.mjs",require:"./dist/chainlist/index.js"}},sideEffects:!1,files:["dist","README.md","LICENSE","docs/","scripts/compute-build-hash.mjs"],scripts:{build:"tsup","build:zk":"npm run build && npm run compile:circuits","compile:circuits":"node scripts/compile-circuits.js",dev:"tsup --watch",test:"tsx test/test.ts && tsx test/comprehensive.test.ts && tsx test/backup.test.ts && tsx test/social-recovery.test.ts && tsx test/recovery-education.test.ts && tsx test/zk/zk.test.ts && tsx test/nft-ownership.test.ts && tsx test/chainlist.test.ts && tsx test/eip7702.test.ts && tsx test/erc5564.test.ts && tsx test/zk/key-stretching.test.ts && tsx test/username-encoding.test.ts && tsx test/username-validation.test.ts && tsx test/origin-derivation.test.ts && tsx test/build-hash.test.ts && tsx test/credential-checking.test.ts && tsx test/webauthn-native.test.ts && tsx test/persistent-session.test.ts && tsx test/sign-message.test.ts && tsx test/requirereauth.test.ts","test:basic":"tsx test/test.ts","test:comprehensive":"tsx test/comprehensive.test.ts","test:backup":"tsx test/backup.test.ts","test:social-recovery":"tsx test/social-recovery.test.ts","test:education":"tsx test/recovery-education.test.ts","test:username":"tsx test/username-encoding.test.ts && tsx test/username-validation.test.ts","test:recovery":"tsx test/backup.test.ts && tsx test/social-recovery.test.ts && tsx test/recovery-education.test.ts","test:zk":"tsx test/zk/zk.test.ts","test:nft":"tsx test/nft-ownership.test.ts","test:chainlist":"tsx test/chainlist.test.ts","test:eip7702":"tsx test/eip7702.test.ts","test:erc5564":"tsx test/erc5564.test.ts",prepublishOnly:"pnpm build","build:hash":"node scripts/compute-build-hash.mjs","release:notes":"node scripts/generate-release-notes.mjs",html:"lsof -ti:3000 | xargs kill -9 2>/dev/null || true && tsup && npx serve . -l 3000 & sleep 5 && open http://localhost:3000/checker.html"},packageManager:"pnpm@10.6.4",dependencies:{},devDependencies:{"@types/node":"^24.9.0","@types/qrcode":"^1.5.5",circomlib:"^2.0.5",tsup:"^8.5.0",tsx:"^4.20.6",typescript:"^5.9.3"},peerDependencies:{ethers:"^6.0.0"},optionalDependencies:{"@ipld/car":"^5.4.2","blockstore-core":"^6.1.1",circomlibjs:"^0.1.7","ipfs-unixfs-importer":"^16.0.1",qrcode:"^1.5.4",snarkjs:"^0.7.5"}}});var Gp={};T(Gp,{ApiError:()=>Br,AuthenticationError:()=>de,CryptoError:()=>N,DEFAULT_TAG:()=>Ce,RecoverySimulator:()=>dt,RegistrationError:()=>et,StealthAddressModule:()=>nt,StorageError:()=>F,WalletError:()=>v,Web3Passkey:()=>ht,Web3PasskeyError:()=>z,assertEthereumAddress:()=>Ir,assertMnemonic:()=>ji,assertUsername:()=>Dr,createWeb3Passkey:()=>Il,default:()=>Vp,getAllTopics:()=>Cs,getCurrentBuildHash:()=>Vi,getCurrentOrigin:()=>Ht,getExplainer:()=>ks,getPackageVersion:()=>Wi,getW3pkBuildHash:()=>$i,isStrongPassword:()=>Yi,normalizeOrigin:()=>Or,searchExplainers:()=>Es,validateEthereumAddress:()=>qn,validateMnemonic:()=>$n,validateUsername:()=>Hn,verifyBuildHash:()=>Bl});module.exports=Ul(Gp);j();function qn(r){return/^0x[a-fA-F0-9]{40}$/.test(r)}function Hn(r){return r.length<3||r.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(r)}function $n(r){let e=r.trim().split(/\s+/);return e.length===12||e.length===24}function Ir(r){if(!qn(r))throw new Error("Invalid Ethereum address format")}function Dr(r){if(!Hn(r))throw new Error("Username must be 3-50 characters long and contain only letters, numbers, underscores, and hyphens. Must start and end with a letter or number.")}function ji(r){if(!$n(r))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function Yi(r){if(r.length<12)return!1;let e=/[A-Z]/.test(r),t=/[a-z]/.test(r),n=/[0-9]/.test(r),s=/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(r);return!(!e||!t||!n||!s||["password","12345678","qwerty","abc123","password123","admin","letmein"].some(o=>r.toLowerCase().includes(o)))}U();Kt();function Ol(){let r=new Uint8Array(32);return crypto.getRandomValues(r),he(r)}async function Kl(r){try{let e=new Uint8Array(r),t=zl(e);if(t===-1)return null;let n=e.slice(t);if(!((n[32]&64)!==0))return null;let o=37;o+=16;let a=n[o]<<8|n[o+1];o+=2,o+=a;let c=n.slice(o),d=await ql(c);return he(d)}catch(e){return console.error("Failed to extract public key:",e),null}}function zl(r){let e=new Uint8Array([104,97,117,116,104,68,97,116,97]);for(let t=0;t<r.length-e.length;t++){let n=!0;for(let s=0;s<e.length;s++)if(r[t+s]!==e[s]){n=!1;break}if(n){let s=r[t+e.length],i=t+e.length+1;if(s>=88&&s<=91){let o=s-87;i+=o}return i}}return-1}async function ql(r){let e=Qi(r,-2),t=Qi(r,-3);if(!e||!t)throw new Error("Failed to extract EC coordinates from COSE key");let n=new Uint8Array(65);n[0]=4,n.set(e,1),n.set(t,33);let s=new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0]),i=new Uint8Array(s.length+n.length);return i.set(s,0),i.set(n,s.length),i.buffer}function Qi(r,e){let t=e<0?32+(-1-e):e;for(let n=0;n<r.length-33;n++)if(r[n]===t&&(r[n+1]===88&&r[n+2]===32||r[n+1]===88&&r[n+2]===32))return r.slice(n+3,n+35);return null}async function Xi(r){try{let{username:e,ethereumAddress:t}=r;Dr(e),Ir(t);let n=new _e;if(await n.userExists(e))throw new Error("Username already registered");let s=Ol(),o=new TextEncoder().encode(e),a=he(o),c=Le(s),d=Le(a),l={challenge:c,rp:{name:"w3pk",id:window.location.hostname},user:{id:d,name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"required",residentKey:"required",requireResidentKey:!0},timeout:6e4,attestation:"none"},f=await navigator.credentials.create({publicKey:l});if(!f)throw new Error("Failed to create credential");let b=await Kl(f.response.attestationObject);if(!b)throw new Error("Public key not returned from authenticator");await n.saveCredential({id:f.id,publicKey:b,username:e,ethereumAddress:t,createdAt:new Date().toISOString(),lastUsed:new Date().toISOString(),signCount:0}),console.log("[register] Credential response:",f.response);let u=f.response.attestationObject;return console.log("[register] Attestation object length:",u.byteLength),{signature:u}}catch(e){throw new et(e instanceof Error?e.message:"Registration failed",e)}}j();U();Kt();function Hl(){let r=new Uint8Array(32);return crypto.getRandomValues(r),he(r)}async function Ur(){try{let r=new _e,e=Hl(),t=[];try{let c=await r.getAllCredentials();c.length>0?(t=c.map(d=>({id:d.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})),console.log(`[login] Found ${t.length} stored credential(s)`)):console.log("[login] No stored credentials found, using discoverable credentials flow")}catch(c){console.warn("[login] Failed to retrieve stored credentials:",c)}let s={challenge:Le(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4};t.length>0&&(s.allowCredentials=t.map(c=>({id:Le(c.id),type:c.type,transports:c.transports})));let i;try{let c=await navigator.credentials.get({publicKey:s});if(!c)throw new Error("Authentication failed - no credential returned");i=c}catch(c){throw c?.name==="NotAllowedError"||c?.message?.toLowerCase().includes("no credentials available")||c?.message?.toLowerCase().includes("no access key")?(await r.getAllCredentials()).length>0?new de("Your passkey is not available on this device. You may need to restore your wallet from a backup, or login on the device where you registered."):new de("No passkey found. Please register first or restore from a backup."):c}let o=await r.getCredentialById(i.id);if(!o)throw new Error("Credential not found in storage. This shouldn't happen - the passkey was authenticated but metadata is missing.");if(!await $l(i,o,r))throw new Error("Signature verification failed");return{verified:!0,user:{username:o.username,ethereumAddress:o.ethereumAddress,credentialId:o.id},signature:i.response.signature}}catch(r){throw new de(r instanceof Error?r.message:"Authentication failed",r)}}async function $l(r,e,t){try{let n=r.response.authenticatorData,s=new DataView(n),o=new Uint8Array(n).slice(0,32),a=window.location.hostname,c=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));if(!Wl(o,c))return console.error("RP ID hash mismatch - possible phishing attack"),!1;let d=s.getUint32(33,!1);if(d>0||e.signCount&&e.signCount>0){let w=e.signCount||0;if(d<=w)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${w}, received=${d}`),!1}let l=Le(e.publicKey),f=await crypto.subtle.importKey("spki",l,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),b=r.response.clientDataJSON,u=await crypto.subtle.digest("SHA-256",b),p=new Uint8Array(n.byteLength+u.byteLength);p.set(new Uint8Array(n),0),p.set(new Uint8Array(u),n.byteLength);let y=r.response.signature,C=Vl(new Uint8Array(y));return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,C,p)?(await t.updateSignatureCounter(e.id,d),!0):!1}catch(n){return console.error("Signature verification error:",n),!1}}function Wl(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function Vl(r){let e=2;e++;let t=r[e++];t>32&&(e++,t--);let n=r.slice(e,e+t);e+=t,e++;let s=r[e++];s>32&&(e++,s--);let i=r.slice(e,e+s),o=new Uint8Array(64);return o.set(n,32-n.length),o.set(i,64-i.length),o.buffer}j();var Gl="Web3PasskeyWallet",jl=1,me="wallets",Lr=class{constructor(){this.db=null}async init(){return new Promise((e,t)=>{let n=indexedDB.open(Gl,jl);n.onerror=()=>t(new F("Failed to open database",n.error)),n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(me)||s.createObjectStore(me,{keyPath:"ethereumAddress"})}})}async store(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([me],"readwrite").objectStore(me).put(e);o.onerror=()=>n(new F("Failed to store wallet data",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([me],"readonly").objectStore(me).get(e);o.onerror=()=>n(new F("Failed to retrieve wallet data",o.error)),o.onsuccess=()=>t(o.result||null)})}async delete(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([me],"readwrite").objectStore(me).delete(e);o.onerror=()=>n(new F("Failed to delete wallet data",o.error)),o.onsuccess=()=>t()})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([me],"readwrite").objectStore(me).clear();i.onerror=()=>t(new F("Failed to clear wallet data",i.error)),i.onsuccess=()=>e()})}};_r();_r();j();var rt="STANDARD",Ce="MAIN",Jl=2147483647;function Or(r){try{let e=new URL(r),t=`${e.protocol}//${e.hostname.toLowerCase()}`,n=e.port;return n&&!(e.protocol==="https:"&&n==="443"||e.protocol==="http:"&&n==="80")&&(t+=`:${n}`),t}catch(e){throw new v(`Invalid origin URL: ${r}`,e)}}async function Ql(r,e=rt,t=Ce){try{let s=`${Or(r)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(s),a=await crypto.subtle.digest("SHA-256",o);return new DataView(a).getUint32(0,!1)%Jl}catch(n){throw new v(`Failed to derive index from origin "${r}", mode "${e}", and tag "${t}"`,n)}}async function jn(r,e,t,n){try{let s=t||rt,i=(n||Ce).toUpperCase(),o=Or(e),a=await Ql(o,s,i),{address:c,privateKey:d}=Gn(r,a),l={address:c,index:a,origin:o,mode:s,tag:i};return s==="YOLO"&&(l.privateKey=d),l}catch(s){throw new v(`Failed to derive origin-specific address for "${e}" with mode "${t||rt}" and tag "${n||Ce}"`,s)}}function Ht(){if(typeof window>"u"||!window.location)throw new v("getCurrentOrigin() only works in browser environments");return window.location.origin}xe();j();var $=require("ethers");j();function Kr(r){try{let e=$.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/0"),t=$.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/1"),n=t.signingKey.compressedPublicKey,s=e.signingKey.compressedPublicKey;return{stealthMetaAddress:n+s.slice(2),spendingPubKey:n,viewingPubKey:s,viewingKey:e.privateKey,spendingKey:t.privateKey}}catch(e){throw new N("Failed to derive stealth keys",e)}}function ro(r){try{let e="0x"+r.slice(2,68),t="0x"+r.slice(68),n=$.ethers.Wallet.createRandom(),s=n.signingKey.compressedPublicKey,i=Yn(n.privateKey,t),o=$.ethers.keccak256(i),a="0x"+o.slice(2,4),c=oo(e,io(o));return{stealthAddress:ao(c),ephemeralPubKey:s,viewTag:a}}catch(e){throw new N("Failed to generate stealth address",e)}}function no(r,e,t,n,s){try{let i=Yn(r,t),o=$.ethers.keccak256(i);if(s&&("0x"+o.slice(2,4)).toLowerCase()!==s.toLowerCase())return{isForUser:!1};let a=oo(e,io(o)),c=ao(a);return c.toLowerCase()!==n.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:c}}catch{return{isForUser:!1}}}function so(r,e,t){try{let n=Yn(r,t),s=$.ethers.keccak256(n);return Xl(e,s)}catch(n){throw new N("Failed to compute stealth private key",n)}}function Yn(r,e){try{return new $.ethers.Wallet(r).signingKey.computeSharedSecret(e)}catch(t){throw new N("Failed to compute shared secret",t)}}function io(r){try{return new $.ethers.Wallet(r).signingKey.compressedPublicKey}catch(e){throw new N("Failed to multiply generator by scalar",e)}}function oo(r,e){try{let t=$.ethers.SigningKey.computePublicKey(r,!1),n=$.ethers.SigningKey.computePublicKey(e,!1),s=BigInt("0x"+t.slice(4,68)),i=BigInt("0x"+t.slice(68)),o=BigInt("0x"+n.slice(4,68)),a=BigInt("0x"+n.slice(68)),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");if(s===o&&i===a){let p=3n*s*s%c,y=2n*i%c,C=p*to(y,c)%c,g=(C*C-2n*s)%c,w=(C*(s-g)-i)%c;return eo((g+c)%c,(w+c)%c)}let d=((a-i)%c+c)%c,l=((o-s)%c+c)%c,f=d*to(l,c)%c,b=(f*f-s-o)%c,u=(f*(s-b)-i)%c;return eo((b+c)%c,(u+c)%c)}catch(t){throw new N("Failed to add public keys",t)}}function Xl(r,e){try{let t=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),n=BigInt(r),s=BigInt(e);return"0x"+((n+s)%t).toString(16).padStart(64,"0")}catch(t){throw new N("Failed to add private keys",t)}}function eo(r,e){return"0x"+(e%2n===0n?"02":"03")+r.toString(16).padStart(64,"0")}function to(r,e){r=(r%e+e)%e;let[t,n]=[r,e],[s,i]=[1n,0n];for(;n!==0n;){let o=t/n;[t,n]=[n,t-o*n],[s,i]=[i,s-o*i]}return(s%e+e)%e}function ao(r){try{let e=$.ethers.SigningKey.computePublicKey(r,!1),t=$.ethers.keccak256("0x"+e.slice(4));return $.ethers.getAddress("0x"+t.slice(-40))}catch(e){throw new N("Failed to derive address from public key",e)}}var nt=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),n=Kr(t),s=ro(n.stealthMetaAddress);return{stealthAddress:s.stealthAddress,ephemeralPublicKey:s.ephemeralPubKey,viewTag:s.viewTag}}catch(t){throw new z("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let n=await this.getMnemonic(t?.requireAuth),s=Kr(n),i=no(s.viewingKey,s.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag);if(!i.isForUser)return{isForUser:!1};let o=so(s.viewingKey,s.spendingKey,e.ephemeralPublicKey);return{isForUser:!0,stealthAddress:i.stealthAddress,stealthPrivateKey:o}}catch(n){throw new z("Failed to parse announcement","ANNOUNCEMENT_PARSE_ERROR",n)}}async scanAnnouncements(e,t){let n=[];for(let s of e){let i=await this.parseAnnouncement(s,t);i.isForUser&&n.push(i)}return n}async getKeys(e){try{let t=await this.getMnemonic(e?.requireAuth);return Kr(t)}catch(t){throw new z("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new z("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};j();xe();var Zl="Web3PasskeyPersistentSessions",ed=1,re="sessions",zr=class{constructor(){this.db=null;this.initPromise=null}async init(){return this.initPromise?this.initPromise:this.db?Promise.resolve():(this.initPromise=new Promise((e,t)=>{let n=indexedDB.open(Zl,ed);n.onerror=()=>{this.initPromise=null,t(new F("Failed to open persistent session database",n.error))},n.onsuccess=()=>{this.db=n.result,this.initPromise=null,e()},n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(re)||s.createObjectStore(re,{keyPath:"ethereumAddress"}).createIndex("expiresAt","expiresAt",{unique:!1})}}),this.initPromise)}async store(e){if(e.securityMode==="STRICT")throw new F("Cannot persist STRICT mode sessions");return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([re],"readwrite").objectStore(re).put(e);o.onerror=()=>n(new F("Failed to store persistent session",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([re],"readonly").objectStore(re).get(e);o.onerror=()=>n(new F("Failed to retrieve persistent session",o.error)),o.onsuccess=()=>{let a=o.result||null;if(a&&Date.now()>a.expiresAt){this.delete(e).catch(console.error),t(null);return}t(a)}})}async delete(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([re],"readwrite").objectStore(re).delete(e);o.onerror=()=>n(new F("Failed to delete persistent session",o.error)),o.onsuccess=()=>t()})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([re],"readwrite").objectStore(re).clear();i.onerror=()=>t(new F("Failed to clear persistent sessions",i.error)),i.onsuccess=()=>e()})}async cleanupExpired(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([re],"readwrite").objectStore(re).index("expiresAt"),o=Date.now(),a=IDBKeyRange.upperBound(o),c=i.openCursor(a);c.onsuccess=d=>{let l=d.target.result;l?(l.delete(),l.continue()):e()},c.onerror=()=>t(new F("Failed to cleanup expired sessions",c.error))})}};async function co(r,e,t){try{let n=await H(e,t);return await fe(r,n)}catch(n){throw new N("Failed to encrypt mnemonic for persistence",n)}}async function Jn(r,e,t){try{let n=await H(e,t);return await pe(r,n)}catch(n){throw new N("Failed to decrypt mnemonic from persistence",n)}}var qr=class{constructor(e=1,t){this.session=null;this.sessionDuration=e*60*60*1e3,this.persistentConfig={enabled:t?.enabled??!1,duration:t?.duration??168,requireReauth:t?.requireReauth??!0},this.persistentStorage=new zr}async startSession(e,t,n,s,i){let o=new Date(Date.now()+this.sessionDuration).toISOString();if(this.session={mnemonic:e,expiresAt:o,credentialId:t},this.persistentConfig.enabled&&i!=="STRICT"&&n&&s)try{let a=await co(e,t,s),c=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:a,expiresAt:c,credentialId:t,ethereumAddress:n,securityMode:i||"STANDARD",createdAt:Date.now()})}catch(a){console.warn("[w3pk] Failed to persist session:",a)}}getMnemonic(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),null):this.session.mnemonic:null}getCredentialId(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),null):this.session.credentialId:null}isActive(){return this.getMnemonic()!==null}getRemainingTime(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),0):Math.floor((new Date(this.session.expiresAt).getTime()-Date.now())/1e3):0}extendSession(){if(!this.session)throw new Error("No active session to extend");if(new Date>new Date(this.session.expiresAt))throw this.clearSession(),new Error("Session expired, cannot extend");this.session.expiresAt=new Date(Date.now()+this.sessionDuration).toISOString()}async restoreFromPersistentStorage(e,t,n){if(!this.persistentConfig.enabled)return null;try{let s=await this.persistentStorage.retrieve(e);if(!s)return null;if(s.credentialId!==t)return console.warn("[w3pk] Credential ID mismatch, clearing persistent session"),await this.persistentStorage.delete(e),null;let i=await Jn(s.encryptedMnemonic,t,n),o=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:i,expiresAt:o,credentialId:t},i}catch(s){console.warn("[w3pk] Failed to restore persistent session:",s);try{await this.persistentStorage.delete(e)}catch{}return null}}async attemptSilentRestore(){if(!this.persistentConfig.enabled||this.persistentConfig.requireReauth)return null;try{let{CredentialStorage:e}=await Promise.resolve().then(()=>(U(),_)),n=await new e().getAllCredentials();if(n.length===0)return null;for(let s of n){let i=await this.persistentStorage.retrieve(s.ethereumAddress);if(!i)continue;if(i.credentialId!==s.id){console.warn("[w3pk] Credential ID mismatch, skipping this session");continue}let o=await Jn(i.encryptedMnemonic,s.id,s.publicKey),a=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:o,expiresAt:a,credentialId:s.id},{mnemonic:o,ethereumAddress:s.ethereumAddress,credentialId:s.id,publicKey:s.publicKey}}return null}catch(e){return console.warn("[w3pk] Failed to attempt silent restore:",e),null}}async clearSession(){if(this.session&&(this.session.mnemonic="0".repeat(this.session.mnemonic.length)),this.session=null,this.persistentConfig.enabled)try{await this.persistentStorage.clear()}catch(e){console.warn("[w3pk] Failed to clear persistent sessions:",e)}}setSessionDuration(e){this.sessionDuration=e*60*60*1e3}};var Hr={debug:!1,sessionDuration:1,persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:r=>{Hr.debug&&console.error("[w3pk]",r)}};j();var uo="https://chainid.network/chains.json";var $r=null,td=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function rd(r){return td.some(e=>e.test(r))}async function nd(r=uo){let e=await fetch(r);if(!e.ok)throw new Error(`Failed to fetch chains data: ${e.status} ${e.statusText}`);return await e.json()}async function sd(r){let e=r?.chainsJsonUrl??uo,t=r?.cacheDuration??36e5,n=Date.now();if($r&&n-$r.timestamp<t)return $r.data;let s=await nd(e);return $r={data:s,timestamp:n},s}async function lo(r,e){let n=(await sd(e)).find(s=>s.chainId===r);return n?n.rpc.filter(s=>!rd(s)&&!s.startsWith("wss://")&&!s.startsWith("ws://")):[]}var id=new Set([1,10,8453,42161,57073,100,42220,137,42,15,40,41,44,46,47,50,51,56,61,71,82,83,95,97,112,123,130,146,151,153,171,180,183,185,195,215,228,247,248,252,261,267,291,293,311,332,336,395,401,416,466,480,488,510,545,634,647,648,747,831,919,938,945,957,964,970,980,995,997,1001,1003,1024,1030,1114,1125,1135,1149,1188,1284,1285,1287,1300,1301,1315,1337,1338,1339,1424,1514,1687,1727,1729,1740,1750,1829,1868,1946,1961,1962,1969,1989,1995,2017,2020,2031,2043,2109,2241,2340,2345,2440,2522,2559,2649,3068,3109,3338,3502,3799,3888,3889,4e3,4048,4078,4162,4201,4202,4460,4488,4661,4689,4690,4888,5e3,5003,5124,5234,5330,5424,5522,6283,6342,6398,6678,6806,6934,6942,6969,7117,7171,7200,7208,7368,7518,7668,7672,7744,7771,7869,7897,8008,8118,8217,8408,8700,8726,8727,8844,8880,8881,8882,8889,9372,9496,9700,9745,9746,9899,9990,9996,10011,10085,10143,10200,11221,11501,11504,11891,13370,14853,16602,16661,17e3,18880,18881,19991,21e3,21816,21912,25327,32323,33401,34443,41923,42170,43111,44787,47805,48898,48900,49049,49088,5e4,50312,53302,53456,53457,55244,56288,59141,60808,60850,62320,62850,64002,71402,72080,73114,73115,75338,78281,80002,80008,80069,80094,80451,80931,84532,88899,91342,92278,94524,96970,97476,97477,98985,100021,100501,101010,102030,102031,102032,112358,120893,121212,121213,121214,121215,129399,161803,175188,192940,193939,198989,212013,222222,240241,325e3,355110,355113,421614,555777,560048,656476,713715,743111,747474,763373,763375,777777,806582,808813,810180,839999,888991,2019775,2222222,4278608,5734951,6666689,6985385,7080969,7777777,9999999,11142220,11155111,11155420,11155931,16969696,19850818,20180427,20250825,28122024,34949059,37084624,52164803,61022448,79479957,96969696,420420421,420420422,888888888,974399131,999999999,1020352220,1273227453,1313161560,1350216234,1380996178,1417429182,1444673419,1482601649,1564830818,2046399126,11297108099,11297108109,88153591557,123420000220,123420001114]);async function od(r,e=1e4){try{let t=new AbortController,n=setTimeout(()=>t.abort(),e),s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},signal:t.signal,body:JSON.stringify({jsonrpc:"2.0",method:"eth_estimateGas",params:[{from:"0xdeadbeef00000000000000000000000000000000",to:"0xdeadbeef00000000000000000000000000000000",data:"0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",value:"0x0"},"latest",{"0xdeadbeef00000000000000000000000000000000":{code:"0xef01000000000000000000000000000000000000000001"}}],id:1})});if(clearTimeout(n),!s.ok)return!1;let i=await s.json();if(i.error){let o=(i.error.message||"").toLowerCase();return!["unsupported","not supported","unknown","invalid","unrecognized","does not support","not implemented"].some(c=>o.includes(c))}return i.result!==void 0}catch{return!1}}async function ho(r,e,t){if(id.has(r))return!0;let n=t?.maxEndpoints||3,s=t?.timeout||1e4;try{let i=await e(r);if(i.length===0)return!1;let o=i.slice(0,n);for(let a of o)if(await od(a,s))return!0;return!1}catch{return!1}}var ht=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.currentSecurityMode="STANDARD";this.config={...Hr,...e},this.walletStorage=new Lr;let t={...Hr.persistentSession,...e.persistentSession};this.sessionManager=new qr(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new nt(e.stealthAddresses,n=>this.getMnemonicFromSession(n)))}async loadZKModule(){if(this.zkModule)return this.zkModule;try{let e=new Function("path","return import(path)"),{ZKProofModule:t}=await e("w3pk/zk"),n=this.config.zkProofs||{};return this.zkModule=new t(n),this.zkModule}catch{throw new Error("ZK module not available. Install dependencies: npm install snarkjs circomlibjs")}}async getMnemonicFromSession(e=!1,t){let n=t||this.currentSecurityMode;if(!e){let f=this.sessionManager.getMnemonic();if(f)return f}if(!this.currentUser)throw new v("Must be authenticated. Call login() first.");let s=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!s)throw new v("No wallet found. Generate a wallet first.");if(!(await Ur()).user)throw new v("Authentication failed");let c=(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(s.credentialId))?.publicKey,d=await H(s.credentialId,c),l=await pe(s.encryptedMnemonic,d);return await this.sessionManager.startSession(l,s.credentialId,this.currentUser.ethereumAddress,c,n),l}async register(e){try{this.currentWallet?.address||await this.generateWallet();let t=this.currentWallet.address,n=this.currentWallet.mnemonic;await Xi({username:e.username,ethereumAddress:t}),this.currentUser={id:t,username:e.username,displayName:e.username,ethereumAddress:t};let i=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialByAddress(t);if(!i)throw new v("Credential not found after registration");let o=i.id,a=i.publicKey,c=await H(o,a),d=await fe(n,c);return await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:d,credentialId:o,createdAt:new Date().toISOString()}),await this.sessionManager.startSession(n,o,t,a,"STANDARD"),this.currentWallet={address:t,mnemonic:n},this.config.onAuthStateChanged?.(!0,this.currentUser),{address:t,username:e.username}}catch(t){throw this.config.onError?.(t),t}}async login(){try{let e=await this.sessionManager.attemptSilentRestore();if(e){if(this.currentUser={id:e.ethereumAddress,username:e.ethereumAddress,displayName:e.ethereumAddress,ethereumAddress:e.ethereumAddress},!await this.walletStorage.retrieve(this.currentUser.ethereumAddress))return await this.sessionManager.clearSession(),this.login();let f=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(e.credentialId);return f&&(this.currentUser.username=f.username,this.currentUser.displayName=f.username),this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser}let t=await Ur();if(!t.verified||!t.user)throw new de("Login failed");this.currentUser={id:t.user.ethereumAddress,username:t.user.username,displayName:t.user.username,ethereumAddress:t.user.ethereumAddress};let n=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!n)throw new v("No wallet found for this user. You may need to register first.");let o=(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(n.credentialId))?.publicKey,a=await this.sessionManager.restoreFromPersistentStorage(this.currentUser.ethereumAddress,n.credentialId,o||""),c;if(a)c=a;else{let d=await H(n.credentialId,o);c=await pe(n.encryptedMnemonic,d),await this.sessionManager.startSession(c,n.credentialId,this.currentUser.ethereumAddress,o,"STANDARD")}return this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser}catch(e){throw this.config.onError?.(e),e}}async logout(){this.currentUser=null,this.currentWallet=null,await this.sessionManager.clearSession(),this.config.onAuthStateChanged?.(!1,void 0)}get isAuthenticated(){return this.currentUser!==null}get user(){return this.currentUser}async hasExistingCredential(){try{return(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getAllCredentials()).length>0}catch{return!1}}async getExistingCredentialCount(){try{return(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getAllCredentials()).length}catch{return 0}}async listExistingCredentials(){try{return(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getAllCredentials()).map(n=>({username:n.username,ethereumAddress:n.ethereumAddress,createdAt:n.createdAt,lastUsed:n.lastUsed}))}catch{return[]}}async generateWallet(){try{let e=Vn();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new v("Failed to generate wallet",e)}}async deriveWallet(e,t,n){try{if(!this.currentUser)throw new v("Must be authenticated to derive wallet");let s=e||rt,i=t||Ce,o=n?.origin||Ht();this.currentSecurityMode=s;let a=s==="STRICT"?!0:n?.requireAuth||!1,c=await this.getMnemonicFromSession(a,s),d=await jn(c,o,s,i);return{address:d.address,privateKey:d.privateKey,index:d.index,origin:d.origin,mode:d.mode,tag:d.tag}}catch(s){throw this.config.onError?.(s),new v("Failed to derive wallet",s)}}async exportMnemonic(){throw new v("exportMnemonic() disabled for security. Use createBackupFile() instead.")}async importMnemonic(e){try{if(!this.currentUser)throw new v("Must be authenticated to import mnemonic");if(!e||e.trim().split(/\s+/).length<12)throw new v("Invalid mnemonic: must be at least 12 words");let t=await Ur();if(!t.user)throw new v("Authentication failed");let n=t.user.credentialId,o=(await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(n))?.publicKey,a=await H(n,o),c=await fe(e.trim(),a);await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:c,credentialId:n,createdAt:new Date().toISOString()}),this.currentWallet={address:this.currentUser.ethereumAddress,mnemonic:e.trim()},await this.sessionManager.startSession(e.trim(),n,this.currentUser.ethereumAddress,o,"STANDARD")}catch(t){throw this.config.onError?.(t),new v("Failed to import mnemonic",t)}}async signMessage(e,t){try{if(!this.currentUser)throw new v("Must be authenticated to sign message");let n=t?.mode||rt,s=t?.tag||Ce,i=t?.origin||Ht();this.currentSecurityMode=n;let o=n==="STRICT"?!0:t?.requireAuth||!1,a=await this.getMnemonicFromSession(o,n),c=await jn(a,i,n,s),{Wallet:d}=await import("ethers"),l;if(c.privateKey)l=new d(c.privateKey);else{let{deriveWalletFromMnemonic:b}=await Promise.resolve().then(()=>(_r(),Zi)),{privateKey:u}=b(a,c.index);l=new d(u)}return{signature:await l.signMessage(e),address:c.address,mode:c.mode,tag:c.tag,origin:c.origin}}catch(n){throw this.config.onError?.(n),new v("Failed to sign message",n)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new v("Must be authenticated to sign authorization");let{Wallet:n,keccak256:s,concat:i,toBeHex:o,Signature:a}=await import("ethers"),c,d;if(e.privateKey)c=new n(e.privateKey),d=c.address;else{let C=await this.getMnemonicFromSession(t?.requireAuth);c=n.fromPhrase(C),d=c.address}let l=BigInt(e.chainId||1),f=e.nonce||0n,b=i(["0x05",o(l,32),e.contractAddress.toLowerCase(),o(f,32)]),u=s(b),p=c.signingKey.sign(u),y=a.from(p);return{chainId:l,address:d.toLowerCase(),nonce:f,yParity:y.yParity,r:y.r,s:y.s}}catch(n){throw this.config.onError?.(n),new v("Failed to sign authorization",n)}}async getEndpoints(e){return lo(e)}async supportsEIP7702(e,t){return ho(e,this.getEndpoints.bind(this),t)}get zk(){return new Proxy({},{get:(e,t)=>async(...n)=>(await this.loadZKModule())[t](...n)})}async getBackupStatus(){if(!this.currentUser)throw new v("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(ya(),ga));return new e().getBackupStatus(this.currentUser.ethereumAddress)}async createBackupFile(e="password",t){if(!this.currentUser)throw new v("Must be authenticated to create backup");let n=await this.getMnemonicFromSession(!0),{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),ye)),i=new s,o;if(e==="password"){if(!t)throw new v("Password required for password-based backup");let{backupFile:a}=await i.createPasswordBackup(n,this.currentUser.ethereumAddress,t);o=i.createDownloadableBackup(a)}else if(e==="passkey"){let a=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!a)throw new v("No wallet data found");let d=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(a.credentialId);if(!d)throw new v("Credential not found");let{backupFile:l}=await i.createPasskeyBackup(n,this.currentUser.ethereumAddress,d.id,d.publicKey);o=i.createDownloadableBackup(l)}else if(e==="hybrid"){if(!t)throw new v("Password required for hybrid backup");let a=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!a)throw new v("No wallet data found");let d=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(a.credentialId);if(!d)throw new v("Credential not found");let{backupFile:l}=await i.createHybridBackup(n,this.currentUser.ethereumAddress,t,d.id,d.publicKey);o=i.createDownloadableBackup(l)}else throw new v(`Unknown encryption type: ${e}`);return o}async setupSocialRecovery(e,t,n){if(!this.currentUser)throw new v("Must be authenticated to set up social recovery");let s=await this.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(oe(),ye)),o=new i,{backupFile:a}=n?await o.createPasswordBackup(s,this.currentUser.ethereumAddress,n):await o.createPasskeyBackup(s,this.currentUser.ethereumAddress,(await this.walletStorage.retrieve(this.currentUser.ethereumAddress)).credentialId,(await(await Promise.resolve().then(()=>(U(),_))).CredentialStorage.prototype.getCredentialById.call(new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage,(await this.walletStorage.retrieve(this.currentUser.ethereumAddress)).credentialId)).publicKey),{SocialRecovery:c}=await Promise.resolve().then(()=>(cn(),an));return{guardianShares:(await new c().splitAmongGuardians(a,e,t)).guardianShares,setupComplete:!0}}async generateGuardianInvite(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(cn(),an)),s=new n,i=await s.createGuardianInvitation(e,t),o=s.createShareDownload(e);return{qrCodeDataURL:i.qrCodeDataURL,shareDocument:i.shareDocument,downloadBlob:o.blob,filename:o.filename}}async recoverFromGuardians(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(cn(),an)),{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),ye)),i=new n,o=new s,a=e.map(d=>typeof d=="string"?i.parseGuardianShare(d):d),c=await i.recoverFromShares(a);if(c.encryptionMethod==="password"){if(!t)throw new v("Password required to decrypt password-protected backup");return o.restoreWithPassword(c,t)}else throw new v("Passkey-encrypted backups not supported for guardian recovery. Use password-protected backups.")}async restoreFromBackupFile(e,t){let{BackupFileManager:n}=await Promise.resolve().then(()=>(oe(),ye)),s=new n,i=await s.parseBackupFile(e);if(i.encryptionMethod==="password"){if(!t)throw new v("Password required to restore password-encrypted backup");return s.restoreWithPassword(i,t)}else if(i.encryptionMethod==="passkey"){if(!this.currentUser)throw new v("Must be logged in with passkey to restore passkey-encrypted backup. Call login() first.");let o=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!o)throw new v("No wallet data found for current user");let c=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(o.credentialId);if(!c)throw new v("Credential not found");return s.restoreWithExistingPasskey(i,c.id,c.publicKey)}else if(i.encryptionMethod==="hybrid"){if(!t)throw new v("Password required to restore hybrid backup");if(!this.currentUser)throw new v("Must be logged in with passkey to restore hybrid backup. Call login() first.");let o=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!o)throw new v("No wallet data found for current user");let c=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(o.credentialId);if(!c)throw new v("Credential not found");return s.restoreWithHybrid(i,t,c.id,c.publicKey)}else throw new v(`Unknown encryption method: ${i.encryptionMethod}`)}async registerWithBackupFile(e,t,n){let{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),ye)),i=new s,o=await i.parseBackupFile(e);if(o.encryptionMethod!=="password")throw new v("Can only register with password-encrypted backups. Use restoreFromBackupFile() for passkey-encrypted backups.");let{mnemonic:a,ethereumAddress:c}=await i.restoreWithPassword(o,t),{Wallet:d}=await import("ethers");if(d.fromPhrase(a).address.toLowerCase()!==c.toLowerCase())throw new v("Backup verification failed: address mismatch");return this.currentWallet={address:c,mnemonic:a},this.register({username:n})}async getSyncStatus(){let{DeviceSyncManager:e}=await Promise.resolve().then(()=>(rr(),un));return new e().getSyncInfo()}async exportForSync(){if(!this.currentUser)throw new v("Must be authenticated to export for sync");let e=await this.getMnemonicFromSession(!0),t=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!t)throw new v("No wallet data found");let s=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(t.credentialId);if(!s)throw new v("Credential not found");let{DeviceSyncManager:i}=await Promise.resolve().then(()=>(rr(),un)),o=new i,{backupFile:a,blob:c}=await o.exportForSync(e,this.currentUser.ethereumAddress,s.id,s.publicKey),d=`w3pk-sync-${this.currentUser.ethereumAddress.substring(0,8)}.json`,l;try{l=await o.generateSyncQR(a)}catch(f){console.warn("QR code generation failed:",f)}return{blob:c,filename:d,qrCode:l}}async importFromSync(e){if(!this.currentUser)throw new v("Must be logged in to import from sync. Call login() first.");let{DeviceSyncManager:t}=await Promise.resolve().then(()=>(rr(),un)),{BackupFileManager:n}=await Promise.resolve().then(()=>(oe(),ye)),s=new n,i=new t,o=await s.parseBackupFile(e),a=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!a)throw new v("No wallet data found for current user");let d=await new(await Promise.resolve().then(()=>(U(),_))).CredentialStorage().getCredentialById(a.credentialId);if(!d)throw new v("Credential not found");let{mnemonic:l,ethereumAddress:f}=await i.importFromSync(o,d.id,d.publicKey),b=await(await Promise.resolve().then(()=>(xe(),zt))).deriveEncryptionKeyFromWebAuthn(d.id,d.publicKey),u=await(await Promise.resolve().then(()=>(xe(),zt))).encryptData(l,b);return await this.walletStorage.store({ethereumAddress:f,encryptedMnemonic:u,credentialId:d.id,createdAt:new Date().toISOString()}),{ethereumAddress:f,success:!0}}async detectSyncCapabilities(){let{PlatformDetector:e}=await Promise.resolve().then(()=>(Da(),Ia));return new e().detectSyncCapabilities()}async simulateRecoveryScenario(e){if(!this.currentUser)throw new v("Must be authenticated to run recovery simulation");let t=await this.getBackupStatus(),{RecoverySimulator:n}=await Promise.resolve().then(()=>(nr(),pn));return new n().simulateScenario(e,t)}async runRecoveryTest(){if(!this.currentUser)throw new v("Must be authenticated to run recovery test");let e=await this.getBackupStatus(),{RecoverySimulator:t}=await Promise.resolve().then(()=>(nr(),pn));return new t().runInteractiveTest(e)}async getEducation(e){let{getExplainer:t}=await Promise.resolve().then(()=>(nr(),pn)),n=t(e);if(!n)throw new v(`Unknown education topic: ${e}`);return n}hasActiveSession(){return this.sessionManager.isActive()}getSessionRemainingTime(){return this.sessionManager.getRemainingTime()}extendSession(){try{this.sessionManager.extendSession()}catch(e){throw new v("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}};j();nr();async function $p(r,e="build"){let{importer:t}=await Promise.resolve().then(()=>(tl(),el)),{MemoryBlockstore:n}=await Promise.resolve().then(()=>(El(),Cl)),s=new n,o=t(async function*(){yield{path:e,content:r}}(),s,{cidVersion:1,rawLeaves:!0,wrapWithDirectory:!1});for await(let a of o)return a.cid.toString();throw new Error("Failed to generate CID")}async function Wp(r){let e=["index.js","index.mjs","index.d.ts"],t=[],n=0;for(let o of e){let a=`${r}/${o}`,c=await fetch(a);if(!c.ok)throw new Error(`Failed to fetch ${o}: ${c.statusText}`);let d=await c.arrayBuffer(),l=new Uint8Array(d);t.push(l),n+=l.length}let s=new Uint8Array(n),i=0;for(let o of t)s.set(o,i),i+=o.length;return s}async function $i(r){let e=await Wp(r);return $p(e)}function Wi(){try{return Pl().version}catch{throw new Error("Failed to read package version")}}async function Vi(){let r=Wi();return $i(`https://unpkg.com/w3pk@${r}/dist`)}async function Bl(r){return await Vi()===r}function Il(r={}){return new ht(r)}var Vp=Il;
682
682
  //# sourceMappingURL=index.js.map