filecoin 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +1 -1
  2. package/dist/chunks/{chunk-IAJFQYLN.js → chunk-5CKSVYCY.js} +2 -2
  3. package/dist/chunks/{chunk-K63EJUGU.js → chunk-AHVL5QFR.js} +2 -2
  4. package/dist/chunks/{chunk-CIVQHT3F.js → chunk-CC75NTEJ.js} +2 -2
  5. package/dist/chunks/{chunk-YVRWI5E3.js → chunk-D63BUPKY.js} +2 -2
  6. package/dist/chunks/{chunk-GCPUMM4E.js → chunk-I5AWWJGL.js} +2 -2
  7. package/dist/chunks/{chunk-63JLHZEK.js → chunk-IFG72OQD.js} +2 -2
  8. package/dist/chunks/{chunk-JFBUOLJ3.js → chunk-P2G2GV6U.js} +2 -2
  9. package/dist/chunks/{chunk-QRFSFJOZ.js → chunk-PSXNKYPA.js} +2 -2
  10. package/dist/chunks/{chunk-DHTPICN4.js → chunk-QAYTK26Z.js} +2 -2
  11. package/dist/chunks/{chunk-ASZ5KTWE.js → chunk-QLZRQUR6.js} +2 -2
  12. package/dist/chunks/{chunk-BFBNDHQG.js → chunk-S2DTA2FM.js} +2 -2
  13. package/dist/chunks/chunk-SVWQJYA5.js +3 -0
  14. package/dist/chunks/chunk-SVWQJYA5.js.map +7 -0
  15. package/dist/chunks/{chunk-MWVOEA6K.js → chunk-TCUXKQ65.js} +2 -2
  16. package/dist/chunks/{chunk-72RYXITT.js → chunk-UW35AN2V.js} +2 -2
  17. package/dist/chunks/{chunk-72RYXITT.js.map → chunk-UW35AN2V.js.map} +2 -2
  18. package/dist/chunks/{chunk-BZITZ3BI.js → chunk-VGOSQFKJ.js} +2 -2
  19. package/dist/chunks/{chunk-Z6O5SHUU.js → chunk-ZAMDBJVN.js} +2 -2
  20. package/dist/chunks/{delete-BO7K4456.js → delete-SPJVG4ZK.js} +2 -2
  21. package/dist/chunks/{doctor-NF75MDBO.js → doctor-AQGSDILX.js} +2 -2
  22. package/dist/chunks/{get-3EC2XCFH.js → get-C4RUQWRS.js} +2 -2
  23. package/dist/chunks/{inspect-FDI442BE.js → inspect-NXI72CUH.js} +2 -2
  24. package/dist/chunks/{inspect-RJCGSGKG.js → inspect-SBGOKBEP.js} +2 -2
  25. package/dist/chunks/{login-NNTYQ37I.js → login-3LYCAAPW.js} +2 -2
  26. package/dist/chunks/{logout-3RWZFH2E.js → logout-JLRMENQI.js} +2 -2
  27. package/dist/chunks/{ls-GNEVBKRP.js → ls-N5D6HCA4.js} +2 -2
  28. package/dist/chunks/{ls-F546AXRG.js → ls-O5RNPZCH.js} +2 -2
  29. package/dist/chunks/{put-FXMGPSU6.js → put-GTJP7IFM.js} +2 -2
  30. package/dist/chunks/{resume-G5PS246S.js → resume-BCEYVRX7.js} +2 -2
  31. package/dist/chunks/{status-HOLDXKMR.js → status-IWMRFMPV.js} +2 -2
  32. package/dist/main.js +1 -1
  33. package/dist/main.js.map +1 -1
  34. package/dist/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +2 -2
  36. package/dist/chunks/chunk-AKXAQJ6H.js +0 -3
  37. package/dist/chunks/chunk-AKXAQJ6H.js.map +0 -7
  38. /package/dist/chunks/{chunk-IAJFQYLN.js.map → chunk-5CKSVYCY.js.map} +0 -0
  39. /package/dist/chunks/{chunk-K63EJUGU.js.map → chunk-AHVL5QFR.js.map} +0 -0
  40. /package/dist/chunks/{chunk-CIVQHT3F.js.map → chunk-CC75NTEJ.js.map} +0 -0
  41. /package/dist/chunks/{chunk-YVRWI5E3.js.map → chunk-D63BUPKY.js.map} +0 -0
  42. /package/dist/chunks/{chunk-GCPUMM4E.js.map → chunk-I5AWWJGL.js.map} +0 -0
  43. /package/dist/chunks/{chunk-63JLHZEK.js.map → chunk-IFG72OQD.js.map} +0 -0
  44. /package/dist/chunks/{chunk-JFBUOLJ3.js.map → chunk-P2G2GV6U.js.map} +0 -0
  45. /package/dist/chunks/{chunk-QRFSFJOZ.js.map → chunk-PSXNKYPA.js.map} +0 -0
  46. /package/dist/chunks/{chunk-DHTPICN4.js.map → chunk-QAYTK26Z.js.map} +0 -0
  47. /package/dist/chunks/{chunk-ASZ5KTWE.js.map → chunk-QLZRQUR6.js.map} +0 -0
  48. /package/dist/chunks/{chunk-BFBNDHQG.js.map → chunk-S2DTA2FM.js.map} +0 -0
  49. /package/dist/chunks/{chunk-MWVOEA6K.js.map → chunk-TCUXKQ65.js.map} +0 -0
  50. /package/dist/chunks/{chunk-BZITZ3BI.js.map → chunk-VGOSQFKJ.js.map} +0 -0
  51. /package/dist/chunks/{chunk-Z6O5SHUU.js.map → chunk-ZAMDBJVN.js.map} +0 -0
  52. /package/dist/chunks/{delete-BO7K4456.js.map → delete-SPJVG4ZK.js.map} +0 -0
  53. /package/dist/chunks/{doctor-NF75MDBO.js.map → doctor-AQGSDILX.js.map} +0 -0
  54. /package/dist/chunks/{get-3EC2XCFH.js.map → get-C4RUQWRS.js.map} +0 -0
  55. /package/dist/chunks/{inspect-FDI442BE.js.map → inspect-NXI72CUH.js.map} +0 -0
  56. /package/dist/chunks/{inspect-RJCGSGKG.js.map → inspect-SBGOKBEP.js.map} +0 -0
  57. /package/dist/chunks/{login-NNTYQ37I.js.map → login-3LYCAAPW.js.map} +0 -0
  58. /package/dist/chunks/{logout-3RWZFH2E.js.map → logout-JLRMENQI.js.map} +0 -0
  59. /package/dist/chunks/{ls-GNEVBKRP.js.map → ls-N5D6HCA4.js.map} +0 -0
  60. /package/dist/chunks/{ls-F546AXRG.js.map → ls-O5RNPZCH.js.map} +0 -0
  61. /package/dist/chunks/{put-FXMGPSU6.js.map → put-GTJP7IFM.js.map} +0 -0
  62. /package/dist/chunks/{resume-G5PS246S.js.map → resume-BCEYVRX7.js.map} +0 -0
  63. /package/dist/chunks/{status-HOLDXKMR.js.map → status-IWMRFMPV.js.map} +0 -0
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
2
  import{a as o,c as i,e as l,f as r,g as u,i as t,u as m,v as p}from"./chunk-JUFFOBKU.js";import{d as c}from"./chunk-3TJUKWFC.js";var n=r({value:o(),source:t(["input","env","config","default"]).describe("input means --network or FILECOIN_NETWORK")}),z=c({name:"doctor",description:"Show resolved settings and check the state database and RPC",examples:["filecoin doctor","filecoin doctor --network mainnet"],input:u(m),env:p,secrets:["sessionKey"],output:r({network:n,rpcUrl:n,consoleUrl:n,apiUrl:n,configFile:o(),stateDir:n,credentials:t(["env","config","pending","none"]),checks:l(r({name:o(),ok:i(),message:o()}))}),readOnly:!0,human:e=>[`network: ${e.network.value} (${e.network.source})`,`rpc: ${e.rpcUrl.value} (${e.rpcUrl.source})`,`console: ${e.consoleUrl.value} (${e.consoleUrl.source})`,`api: ${e.apiUrl.value} (${e.apiUrl.source})`,`config: ${e.configFile}`,`state: ${e.stateDir.value} (${e.stateDir.source})`,`credentials: ${e.credentials}`,...e.checks.map(s=>`${s.ok?"ok":"FAIL"} ${s.name}: ${s.message}`)].join(`
3
- `),handler:()=>import("./doctor-NF75MDBO.js")});export{z as a};
4
- //# sourceMappingURL=chunk-MWVOEA6K.js.map
3
+ `),handler:()=>import("./doctor-AQGSDILX.js")});export{z as a};
4
+ //# sourceMappingURL=chunk-TCUXKQ65.js.map
@@ -182,5 +182,5 @@ ${e}`}function Ev(e){let t=e.abiItem?Yr(e.abiItem,{includeName:!0}):void 0,n=e.a
182
182
  WHERE chain_id = ? AND payer = ? ${t.all?"":"AND status = 'active'"}
183
183
  ${n?"AND (created_at, ref) < (?, ?)":""}
184
184
  ORDER BY created_at DESC, ref DESC
185
- LIMIT ?`).all(t.chainId,t.payer,...n??[],t.limit+1);return Rl(i.map(Nv),t.limit,r=>[r.createdAt,r.ref])}var KD=18;function WP(e){return Ia(e,KD)}import{setTimeout as WD}from"node:timers/promises";var XP="/dashboard/setup";function YP(e){let t=new URL(XP,e.consoleUrl);return t.searchParams.set("network",e.network),t.searchParams.set("signer",e.address.toLowerCase()),e.name&&t.searchParams.set("name",e.name),t.searchParams.set("scopes",e.scopes.join(",")),e.days!=null&&t.searchParams.set("days",String(e.days)),t.toString()}function QP(e){let t=new URL(XP,e.consoleUrl);return t.searchParams.set("network",e.network),e.deposit!=null&&e.deposit>0n&&t.searchParams.set("deposit",WP(e.deposit)),t.toString()}var Ov=2000n;async function JD(e){let{client:t,signer:n}=e,i=rn({abi:vt,name:"AuthorizationsUpdated"}),r=await $e(t,{cacheTime:0}),o;for(let a=e.fromBlock;a<=r;a+=Ov+1n){let s=a+Ov>r?r:a+Ov,c=await ir(t,{address:t.chain.contracts.sessionKeyRegistry.address,event:i,fromBlock:a,toBlock:s,strict:!0});for(let u of c)_e(u.args.signer,n)&&(o=u.args.identity)}return o}function XD(e,t,n=BigInt(Math.floor(Date.now()/1e3))){let i=[],r=[],o;for(let a of e){let s=t[Po[a]]??0n;s>n?(i.push(a),(o===void 0||s<o)&&(o=s)):r.push(a)}return o===void 0?{granted:i,missing:r}:{granted:i,missing:r,expiresAt:o}}async function YD(e){let t=await Xd(e.client,{address:e.root,sessionKeyAddress:e.signer,permissions:Qd(e.scopes)});return XD(e.scopes,t)}async function QD(e){let t=await JD(e);if(!t)return{status:"pending"};let n=await YD({...e,root:t});return{status:n.missing.length===0?"granted":n.granted.length>0?"partial":"none",root:t,...n}}var JP=3e3;async function Dae(e){let t=Date.now();for(;;){try{let n=await QD(e);if(n.status!=="pending")return n}catch(n){if(e.signal?.aborted)throw n}if(Date.now()-t+JP>e.timeoutMs)return{status:"pending"};await WD(JP,void 0,{signal:e.signal})}}function Uv(e){let{sessionKey:t,rootAddress:n}=e.credentials;if(t||n){if(!t)throw qo("FILECOIN_SESSION_KEY must be a 32-byte hex private key.","sessionKey");if(!(n&&pe(n)))throw qo("FILECOIN_ROOT_ADDRESS must be the wallet that authorized FILECOIN_SESSION_KEY.","rootAddress");return{privateKey:t,rootAddress:tt(n),source:"env"}}let i=e.config.get(`sessions.${e.network}`);if(i){if(!i.rootAddress)throw eC(YP({consoleUrl:e.consoleUrl,address:i.address,scopes:i.scopes.filter(Yb),network:e.network,name:i.name,days:i.days}));return{privateKey:i.privateKey,rootAddress:tt(i.rootAddress),source:"config"}}}function eC(e){return new Kt({code:Tr.loginPending,message:"The session key is waiting for approval in filecoin-app.",details:{url:e},next:[{by:"user",description:`Open ${e} and approve the session key with your wallet`},{by:"agent",command:"filecoin login --check",description:"Confirm the saved key after the user approves"}]})}function tC(e={}){let t=["filecoin login"];e.fresh&&t.push("--fresh");for(let n of e.scopes??[])t.push(`--scopes ${n}`);return t.join(" ")}function Lv(){return new Kt({code:Tr.authRequired,message:"No session key for this network.",next:[{by:"user",command:"filecoin login",description:"Authorize a session key in the filecoin-app dashboard, then retry"}]})}function rC(e){let t=Uv(e);if(!t)throw Lv();return Xb({privateKey:t.privateKey,root:t.rootAddress,chain:e.chain,transport:e.transport})}async function nC(e,t){let n=Qd(t);return await e.syncExpirations(n),t.filter(i=>!e.hasPermission(Po[i]))}async function e_(e,t){let n=rC(e),i=await nC(n,t);if(i.length>0){let r=e.config.get(`sessions.${e.network}`)?.scopes.filter(Yb),o=r?.length?r:zm,a=i.filter(s=>!o.includes(s));throw new Kt({code:Tr.sessionExpired,message:`The session key is missing or expired for: ${i.join(", ")}.`,details:{missing:i},next:[{by:"user",command:tC({fresh:!0,scopes:a.length>0?[...o,...a]:void 0}),description:"Authorize a new session key with the needed scopes"}]})}return n}function t_(e){let{funds:t,lockupCurrent:n,lockupRate:i,lockupLastSettledAt:r,currentEpoch:o}=e,a=o-r,s=n+i*a;return s>t?s-t:0n}async function r_(e,t){let n=t.blockNumber??await $e(e,{cacheTime:0}),i=await O(e,iC({chain:e.chain,token:t.token,address:t.address,contractAddress:t.contractAddress}));return oC(i,n)}function iC(e){let t=F(e.chain),n=e.token??t.contracts.usdfc.address;return{abi:t.contracts.filecoinPay.abi,address:e.contractAddress??t.contracts.filecoinPay.address,functionName:"accounts",args:[n,e.address]}}function oC(e,t){let[n,i,r,o]=e,a=t-o,s=i+a*r,c=n-s;return{funds:e[0],lockupCurrent:e[1],lockupRate:e[2],lockupLastSettledAt:e[3],availableFunds:c<0n?0n:c}}async function Ol(e,t={}){let n=await O(e,aC({chain:e.chain,contractAddress:t.contractAddress}));return{token:n.token,rates:{storagePerTibPerMonth:n.rates.storagePerTibPerMonth,datasetFeePerMonth:n.rates.datasetFeePerMonth,cdnEgressPerTib:n.rates.cdnEgressPerTib,cacheMissEgressPerTib:n.rates.cacheMissEgressPerTib},fees:{createDataSetFee:n.fees.createDataSetFee,addPiecesBaseFee:n.fees.addPiecesBaseFee,addPiecesPerPieceFee:n.fees.addPiecesPerPieceFee,schedulePieceRemovalsFee:n.fees.schedulePieceRemovalsFee,terminateFee:n.fees.terminateFee},lockups:{lifecycleReserveTarget:n.lockups.lifecycleReserveTarget,replenishThreshold:n.lockups.replenishThreshold,defaultLockupPeriod:n.lockups.defaultLockupPeriod,cdnLockupAmount:n.lockups.cdnLockupAmount,cacheMissLockupAmount:n.lockups.cacheMissLockupAmount,cdnLockupPeriod:n.lockups.cdnLockupPeriod}}}function aC(e){let t=F(e.chain);return{abi:t.contracts.fwssView.abi,address:e.contractAddress??t.contracts.fwssView.address,functionName:"getPriceList",args:[]}}async function n_(e,t){let n=await O(e,sC({chain:e.chain,token:t.token,address:t.address,operator:t.operator,contractAddress:t.contractAddress}));return cC(n)}function sC(e){let t=F(e.chain),n=e.token??t.contracts.usdfc.address,i=e.operator??t.contracts.fwss.address;return{abi:t.contracts.filecoinPay.abi,address:e.contractAddress??t.contracts.filecoinPay.address,functionName:"operatorApprovals",args:[n,e.address,i]}}function cC(e){return{isApproved:e[0],rateAllowance:e[1],lockupAllowance:e[2],rateUsage:e[3],lockupUsage:e[4],maxLockupPeriod:e[5]}}async function i_(e,t){let n=t.requiredMaxLockupPeriod??(await Ol(e)).lockups.defaultLockupPeriod,i=await n_(e,{address:t.clientAddress});return i.isApproved&&i.rateAllowance===rt&&i.lockupAllowance>=rt/2n&&i.maxLockupPeriod>=n}function o_(e){let{funds:t,lockupCurrent:n,lockupRate:i,lockupLastSettledAt:r,currentEpoch:o}=e,a=i===0n?rt:r+(t-n)/i,s=a<o?a:o,c=n+i*(s-r),u=t-c,p=u>0n?u:0n,d=a===rt?rt:a>o?a-o:0n,l=i===0n?rt:t/i;return{availableFunds:p,runwayInEpochs:d,grossCoverageInEpochs:l}}function jo(e){return e*Be.BYTES_PER_LEAF*127n/128n}function uC(e){return(e*4n+126n)/127n}function Bs(e){if(e.length===0)throw new ue("pieceSizes must contain at least one piece");for(let t of e)if(t<=0n)throw new ue("pieceSizes must contain only positive byte sizes")}function Ul(e){return Bs(e),e.reduce((t,n)=>t+uC(n),0n)}function Mo(e){let{sizeInBytes:t,storagePerTibPerMonth:n,datasetFeePerMonth:i,epochsPerMonth:r}=e;if(t===0n)return{ratePerEpoch:0n,ratePerMonth:0n};let o=n*t/Be.TiB,a=n*t/(Be.TiB*r),s=o+i;return{ratePerEpoch:a+i/r,ratePerMonth:s}}function a_(e){let{pieceSizes:t,dataSetLeafCount:n,priceList:i,epochsPerMonth:r=xl.EPOCHS_PER_MONTH,lockupEpochs:o,isNewDataSet:a,withCDN:s}=e;if(n<0n)throw new ue("dataSetLeafCount cannot be negative");let c=a?0n:n,u=Ul(t),p=c+u,d=o??i.lockups.defaultLockupPeriod,l={storagePerTibPerMonth:i.rates.storagePerTibPerMonth,datasetFeePerMonth:i.rates.datasetFeePerMonth,epochsPerMonth:r},m;if(c>0n){let T=Mo({...l,sizeInBytes:jo(p)}),w=Mo({...l,sizeInBytes:jo(c)});m=T.ratePerEpoch-w.ratePerEpoch,m<0n&&(m=0n)}else m=Mo({...l,sizeInBytes:jo(p)}).ratePerEpoch;let f=m*d,y=a?i.lockups.lifecycleReserveTarget:0n,x=a&&s?i.lockups.cdnLockupAmount:0n,g=a&&s?i.lockups.cacheMissLockupAmount:0n;return{rateDeltaPerEpoch:m,streamingLockup:f,lifecycleLockup:y,cdnLockup:x,cacheMissLockup:g,total:f+y+x+g}}function s_(e){Bs(e.pieceSizes);let t=e.pendingOneTimePayments??0n;if(t<0n)throw new ue("pendingOneTimePayments cannot be negative");let n=e.priceList.lockups.lifecycleReserveTarget,i=e.priceList.lockups.replenishThreshold,r=e.isNewDataSet?n:0n,o;if(e.isNewDataSet)o=n;else{if(e.currentReserveBalance==null)throw new ue("currentReserveBalance is required for an existing data set");if(e.currentReserveBalance<0n)throw new ue("currentReserveBalance cannot be negative");o=e.currentReserveBalance}let a=t+(e.isNewDataSet?e.priceList.fees.createDataSetFee:0n),s=0n,c=e.priceList.fees.addPiecesBaseFee+e.priceList.fees.addPiecesPerPieceFee;for(let u=0;u<e.pieceSizes.length;u++){if(a+=c,o<a+i){let p=n+a;s+=p-o,o=p}o-=a,a=0n}return{initialLockup:r,replenishmentLockup:s,total:r+s,finalReserveBalance:o}}function c_(e){Bs(e.pieceSizes);let t=BigInt(e.pieceSizes.length),n=e.isNewDataSet?e.priceList.fees.createDataSetFee:0n,i=(e.priceList.fees.addPiecesBaseFee+e.priceList.fees.addPiecesPerPieceFee)*t;return{createDataSetFee:n,addPiecesFee:i,total:n+i}}function Bv(e){if(e.pdpEndEpoch!==0n)throw new Dl(e.pdpEndEpoch)}function u_(e){if(e.isNewDataSet)return null;if(e.dataSetLeafCount==null)throw new ue("dataSetLeafCount is required for an existing data set");if(e.currentLifecycleReserveBalance==null)throw new ue("currentLifecycleReserveBalance is required for an existing data set");if(e.pdpEndEpoch==null)throw new ue("pdpEndEpoch is required for an existing data set");let t={leafCount:e.dataSetLeafCount,lifecycleReserveBalance:e.currentLifecycleReserveBalance,pendingOneTimePayments:e.pendingOneTimePayments??0n,pdpEndEpoch:e.pdpEndEpoch};return Bv(t),t}function pC(e){return e.netRateAfterUpload*e.extraRunwayEpochs}function dC(e){let{rawDepositNeeded:t,netRateAfterUpload:n,runwayInEpochs:i,availableFunds:r,bufferEpochs:o}=e;if(t>0n)return n*o;if(i<=o){let a=n*o-r;return a>0n?a:0n}return 0n}function p_(e){if(e.contexts.length===0)throw new ue("contexts must contain at least one storage context");let t=e.epochsPerMonth??xl.EPOCHS_PER_MONTH,n=e.extraRunwayEpochs??$P,i=e.bufferEpochs??_P,r=0n,o=0n,a=0n,s=0n,c=0n,u=0n,p=0n,d=0n,l=0n,m=0n,f=0n;for(let P of e.contexts){P.dataSet!=null&&Bv(P.dataSet);let C=P.dataSet==null,_=P.dataSet?.leafCount??0n,U=Ul(P.pieceSizes),M=a_({pieceSizes:P.pieceSizes,dataSetLeafCount:_,priceList:e.priceList,epochsPerMonth:t,lockupEpochs:e.lockupEpochs,isNewDataSet:C,withCDN:P.withCDN}),fe=c_({priceList:e.priceList,isNewDataSet:C,pieceSizes:P.pieceSizes}),q=s_({priceList:e.priceList,isNewDataSet:C,pieceSizes:P.pieceSizes,currentReserveBalance:P.dataSet?.lifecycleReserveBalance,pendingOneTimePayments:P.dataSet?.pendingOneTimePayments}),ye=Mo({sizeInBytes:jo(_+U),storagePerTibPerMonth:e.priceList.rates.storagePerTibPerMonth,datasetFeePerMonth:e.priceList.rates.datasetFeePerMonth,epochsPerMonth:t});r+=M.rateDeltaPerEpoch,o+=M.total+q.replenishmentLockup,a+=M.lifecycleLockup,s+=q.replenishmentLockup,c+=M.streamingLockup,u+=M.cdnLockup,p+=M.cacheMissLockup,d+=ye.ratePerEpoch,l+=ye.ratePerMonth,m+=fe.createDataSetFee,f+=fe.addPiecesFee}let y=e.account.currentLockupRate+r,x=pC({netRateAfterUpload:y,extraRunwayEpochs:n}),g=o+x+e.account.debt-e.account.availableFunds,w=e.account.currentLockupRate===0n&&e.contexts.every(P=>P.dataSet==null)?0n:dC({rawDepositNeeded:g,netRateAfterUpload:y,runwayInEpochs:e.account.runwayInEpochs,availableFunds:e.account.availableFunds,bufferEpochs:i}),b=(g>0n?g:0n)+w,I=!e.account.fwssMaxApproved,$=m,S=f;return{rates:{perEpoch:d,perMonth:l},fees:{createDataSetFee:$,addPiecesFee:S,total:$+S},lockups:{rateDeltaPerEpoch:r,lifecycleLockup:a,reserveReplenishment:s,streamingLockup:c,cdnLockup:u,cacheMissLockup:p,total:o},depositNeeded:b,needsFwssMaxApproval:I,ready:b===0n&&!I}}async function d_(e,t){let n=t.isNewDataSet??!0,i=t.withCDN??!1,r=u_({isNewDataSet:n,dataSetLeafCount:t.dataSetLeafCount,currentLifecycleReserveBalance:t.currentLifecycleReserveBalance,pendingOneTimePayments:t.pendingOneTimePayments,pdpEndEpoch:t.pdpEndEpoch}),[o,a,s]=await Promise.all([r_(e,{address:t.clientAddress}),Ol(e),$e(e,{cacheTime:0})]),c=await i_(e,{clientAddress:t.clientAddress,requiredMaxLockupPeriod:a.lockups.defaultLockupPeriod}),u={funds:o.funds,lockupCurrent:o.lockupCurrent,lockupRate:o.lockupRate,lockupLastSettledAt:o.lockupLastSettledAt,currentEpoch:s},p=t_(u),{availableFunds:d,runwayInEpochs:l}=o_(u);return p_({contexts:[{pieceSizes:t.pieceSizes,withCDN:i,dataSet:r}],priceList:a,account:{currentLockupRate:o.lockupRate,debt:p,availableFunds:d,runwayInEpochs:l,fwssMaxApproved:c},extraRunwayEpochs:t.extraRunwayEpochs,bufferEpochs:t.bufferEpochs})}import{createReadStream as ZC}from"node:fs";import{Readable as HC}from"node:stream";var Zo=class extends le{name="AtLeastOnePieceRequiredError";constructor(){super("At least one piece must be provided")}static is(t){return he(t)&&t.name==="AtLeastOnePieceRequiredError"}};function Ll(e){return e.some(t=>t.length>0)?e:[]}var l_=globalThis.crypto;function lC(){let e=0n;for(let t=0;t<32;t++)e<<=8n,e|=BigInt(mC(256));return e}function br(){if(l_?.getRandomValues==null)return lC();{let e=new BigUint64Array(4);l_.getRandomValues(e);let t=0n;return e.forEach(n=>{t<<=64n,t|=n}),t}}function mC(e){return Math.floor(Math.random()*e)}var Fv=[{type:"uint256"},{type:"string[][]"},{type:"string[][]"},{type:"bytes"}];async function Ho(e,t){let n=F(e.chain),{clientDataSetId:i,nonce:r,pieces:o,verifyingContract:a}=t,s=r??br(),c=Ll(Array.from(o,m=>m.metadata??[])),u=await xn(e,{account:e.account,domain:So({chain:n,verifyingContract:a}),types:St,primaryType:"AddPieces",message:{clientDataSetId:i,nonce:s,pieceData:o.map(m=>({data:re(m.pieceCid.bytes)})),pieceMetadata:c.map((m,f)=>({pieceIndex:BigInt(f),metadata:m}))}}),p=c.map(m=>m.map(f=>f.key)),d=c.map(m=>m.map(f=>f.value));return ze(Fv,[s,p,d,u])}function Vo(e){if(e?.aborted)throw new As(e)}var jv=[{type:"address"},{type:"uint256"},{type:"string[]"},{type:"string[]"},{type:"bytes"}];async function m_(e,t){let n=F(e.chain),i=t.metadata??[],r=t.clientDataSetId??br(),o=await xn(e,{account:e.account,domain:So({chain:n}),types:St,primaryType:"CreateDataSet",message:{clientDataSetId:r,payee:t.payee,metadata:i}}),a=i.map(p=>p.key),s=i.map(p=>p.value),c=t.payer??e.account.address;return ze(jv,[c,r,a,s,o])}var Mv=[{type:"bytes"},{type:"bytes"}];async function Bl(e,t){let n=t.clientDataSetId??br(),i=await m_(e,{...t,clientDataSetId:n}),r=await Ho(e,{...t,clientDataSetId:n});return ze(Mv,[i,r])}var f_=`0x${"00".repeat(65)}`;function fC(e){if(e.kind!=="addPieces")return!1;let t=e.dataSetId??e.dataSet?.dataSetId;return t!=null&&e.legacyPieceStorageIdLimit!=null&&t<e.legacyPieceStorageIdLimit}function yC(e){return e.pieces.length<1||fC(e)&&e.pieces.length>Be.MAX_LEGACY_ADD_PIECES_BATCH_SIZE?!1:hC(e)<=Be.MAX_ADD_PIECES_MESSAGE_SIZE}function gC(e){let t=e.size;if(t<Be.MIN_UPLOAD_SIZE||t>Be.MAX_UPLOAD_SIZE)throw new Mn(t)}function Fl(e){if(e.pieces.length<1)throw new Zo;for(let t of e.pieces)gC(t.pieceCid);if(!yC(e))throw new kl(e.pieces.length)}function hC(e){let t=xC(e),n=e.pieces.map(r=>({data:re(r.pieceCid.bytes)})),i=se({abi:bt,functionName:"addPieces",args:[0n,Nr,n,t]});return ve(i)}function xC(e){let t=bC(e.pieces);if(e.kind==="addPieces")return t;let n=No(e.metadata,{cdn:e.cdn??!1}),i=ze(jv,[Nr,0n,n.map(r=>r.key),n.map(r=>r.value),f_]);return ze(Mv,[i,t])}function bC(e){let t=Ll(e.map(r=>Wr(r.metadata))),n=t.map(r=>r.map(o=>o.key)),i=t.map(r=>r.map(o=>o.value));return ze(Fv,[0n,n,i,f_])}async function vC(e){let{serviceURL:t,dataSetId:n,pieces:i,extraData:r}=e,o=await L.post(new URL(`pdp/data-sets/${n}/pieces`,t),{json:{pieces:i.map(c=>({pieceCid:c.toString(),subPieces:[{subPieceCid:c.toString()}]})),extraData:r},signal:e.signal,timeout:ee.TIMEOUT,retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY,shouldRetry:c=>ne.is(c.error)&&c.error.code===429}});if(o.error)throw ne.is(o.error)?new El(await o.error.response.text()):o.error;let a=o.result.headers.get("Location"),s=a?.split("/").pop();if(!a||!s||!xe(s))throw new xr(a);return{txHash:s,statusUrl:new URL(a,t).toString()}}async function y_(e,t){Vo(t.signal),Fl({kind:"addPieces",dataSetId:t.dataSetId,legacyPieceStorageIdLimit:F(e.chain).legacyPieceStorageIdLimit,pieces:t.pieces});let n=t.extraData??await Ho(e,{clientDataSetId:t.clientDataSetId,nonce:t.nonce,pieces:t.pieces.map(i=>({pieceCid:i.pieceCid,metadata:Wr(i.metadata)}))});return vC({serviceURL:t.serviceURL,dataSetId:t.dataSetId,pieces:t.pieces.map(i=>i.pieceCid),extraData:n,retryCount:t.retryCount,retryDelay:t.retryDelay,signal:t.signal})}var zce=Ft({txHash:ie,txStatus:Ie("pending"),dataSetId:Bn,pieceCount:En(),addMessageOk:qr(),piecesAdded:Ie(!1),confirmedTxHash:ie.optional()}),TC=Ft({txHash:ie,txStatus:Ie("rejected"),dataSetId:Bn,pieceCount:En(),addMessageOk:qr(),piecesAdded:Ie(!1),confirmedTxHash:ie.optional()}),wC=Ft({txHash:ie,txStatus:Ie("confirmed"),dataSetId:Bn,pieceCount:En(),addMessageOk:Ie(!0),piecesAdded:Ie(!0),confirmedPieceIds:An(Bn),confirmedTxHash:ie.optional()}),IC=go("txStatus",[TC,wC]);async function jl(e){let t=await L.json.get(e.statusUrl,{retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},poll:{limit:ee.POLL_LIMIT,interval:e.pollInterval??ee.POLL_INTERVAL,statusCodes:[202,200],shouldPoll:async n=>(await n.response.clone().json()).piecesAdded===!1},signal:e.signal,timeout:e.timeout??ee.TIMEOUT,schema:IC});if(t.error)throw ne.is(t.error)?new Al(await t.error.response.text()):t.error;if(t.result.txStatus==="rejected")throw new Lo(t.result);return t.result}var Uce=Ft({createMessageHash:ie,dataSetCreated:Ie(!1),service:mr(),txStatus:yo([Ie("pending"),Ie("confirmed")]),ok:qr(),confirmedTxHash:ie.optional()}),SC=Ft({createMessageHash:ie,dataSetCreated:Ie(!1),service:mr(),txStatus:Ie("rejected"),ok:Ie(!1),confirmedTxHash:ie.optional()}),PC=Ft({createMessageHash:ie,dataSetCreated:Ie(!0),service:mr(),txStatus:Ie("confirmed"),ok:Ie(!0),dataSetId:Bn,confirmedTxHash:ie.optional()}),_C=go("txStatus",[SC,PC]);async function g_(e){let t=await L.json.get(e.statusUrl,{retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},poll:{limit:ee.POLL_LIMIT,interval:e.pollInterval??ee.POLL_INTERVAL,statusCodes:[202,200],shouldPoll:async n=>(await n.response.clone().json()).dataSetCreated===!1},signal:e.signal,timeout:e.timeout??ee.TIMEOUT,schema:_C});if(t.error)throw ne.is(t.error)?new $l(await t.error.response.text()):t.error;if(t.result.txStatus==="rejected")throw new Uo(t.result);return t.result}async function $C(e){let t=await L.post(new URL("pdp/data-sets/create-and-add",e.serviceURL),{json:{recordKeeper:e.recordKeeper,extraData:e.extraData,pieces:e.pieces.map(r=>({pieceCid:r.toString(),subPieces:[{subPieceCid:r.toString()}]}))},signal:e.signal,timeout:ee.TIMEOUT,retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY,shouldRetry:r=>ne.is(r.error)&&r.error.code===429}});if(t.error)throw ne.is(t.error)?new _l(await t.error.response.text()):t.error;let n=t.result.headers.get("Location"),i=n?.split("/").pop();if(!n||!i||!xe(i))throw new xr(n);return{txHash:i,statusUrl:new URL(n,e.serviceURL).toString()}}async function h_(e,t){Vo(t.signal),Fl({kind:"createDataSetAndAddPieces",metadata:t.metadata,cdn:t.cdn,pieces:t.pieces});let n=F(e.chain),i=t.extraData??await Bl(e,{clientDataSetId:t.clientDataSetId,payee:t.payee,payer:t.payer,metadata:No(t.metadata,{cdn:t.cdn??!1}),pieces:t.pieces.map(r=>({pieceCid:r.pieceCid,metadata:Wr(r.metadata)}))});return $C({serviceURL:t.serviceURL,recordKeeper:t.recordKeeper??n.contracts.fwss.address,extraData:i,pieces:t.pieces.map(r=>r.pieceCid),retryCount:t.retryCount,retryDelay:t.retryDelay,signal:t.signal})}async function x_(e){let t=new URL(e.statusUrl).origin,n=await g_({statusUrl:e.statusUrl,timeout:e.timeout,signal:e.signal,retryCount:e.retryCount,retryDelay:e.retryDelay,pollInterval:e.pollInterval}),i=await jl({statusUrl:new URL(`/pdp/data-sets/${n.dataSetId}/pieces/added/${n.createMessageHash}`,t).toString(),timeout:e.timeout,signal:e.signal,retryCount:e.retryCount,retryDelay:e.retryDelay,pollInterval:e.pollInterval});return{hash:n.createMessageHash,confirmedTxHash:n.confirmedTxHash??i.confirmedTxHash,dataSetId:n.dataSetId,piecesIds:i.confirmedPieceIds}}async function b_(e,t){let n=await O(e,kC({chain:e.chain,dataSetId:t.dataSetId,contractAddress:t.contractAddress}));return EC(n)}function EC(e){return e.pdpRailId===0n?null:e}function kC(e){let t=F(e.chain);return{abi:t.contracts.fwssView.abi,address:e.contractAddress??t.contracts.fwssView.address,functionName:"getDataSet",args:[e.dataSetId]}}async function v_(e,t){let n=await b_(e,t);if(!n)return null;let i=await AC(e,{dataSetInfo:n,providerId:n.providerId});return{...n,...i}}async function AC(e,t){let n=F(e.chain),[i,r,o,a,s]=await Nt(e,{allowFailure:!1,contracts:[fl({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId}),hl({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId}),bl({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId}),Rs({chain:e.chain,providerId:t.providerId}),Ds({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId})]}),c=Co(a)?Fn(a):null,u=vl(o);return{live:i,managed:_e(r,n.contracts.fwss.address),cdn:t.dataSetInfo.cdnRailId>0n&&"withCDN"in u,metadata:u,provider:c,hasActivePieces:s>0n}}async function Zv(e){let{pieceCid:t,serviceURL:n}=e,i=new URLSearchParams({pieceCid:t.toString()}),r=e.retryCount??(e.poll?ee.POLL_LIMIT:void 0),o=e.retryDelay??(e.poll?e.pollInterval??1e3:ee.RETRY_DELAY),a=await L.json.get(new URL(`pdp/piece?${i.toString()}`,n),{signal:e.signal,timeout:e.timeout??ee.TIMEOUT,retry:{retries:r,factor:e.poll?1:void 0,minTimeout:o,shouldRetry:c=>ne.is(c.error)&&c.error.code===404},poll:e.poll?{limit:ee.POLL_LIMIT,interval:e.pollInterval??1e3,statusCodes:[202]}:!1});if(a.error)throw ne.is(a.error)?new Us(await a.error.response.text()):ks.is(a.error)?new Us("Timeout waiting for piece to be found"):a.error;let s=a.result;return ft(s.pieceCid)}async function T_(e){let t=await L.post(new URL("pdp/piece/uploads",e.serviceURL),{timeout:ee.TIMEOUT,retry:{methods:["post"],retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},signal:e.signal});if(t.error)throw ne.is(t.error)?new jn(`Failed to create upload session: ${await t.error.response.text()}`):t.error;if(t.result.status!==201)throw new jn(`Expected 201 Created, got ${t.result.status}`);let n=t.result.headers.get("Location");if(!n)throw new xr("Upload session created but Location header missing");let i=n.match(/\/pdp\/piece\/uploads\/([a-fA-F0-9-]+)/);if(!i)throw new xr(`Invalid Location header format: ${n}`);let r=i[1],o=Promise.resolve(e.pieceCid),a=null;if(e.pieceCid==null){let{transform:T,result:w}=$v();a=T,o=w}let s=wl(e.data)?new Blob([e.data]).stream():e.data,c=wl(e.data)?e.data.length:e.size,u=0,p=new TransformStream({transform(T,w){let b;if(wl(T))b=T;else if(ArrayBuffer.isView(T))b=new Uint8Array(T.buffer,T.byteOffset,T.byteLength);else{w.error("Invalid chunk type only Uint8Array and TypedArray are supported");return}if(u+=b.length,u>Be.MAX_UPLOAD_SIZE){w.error(new Mn(u));return}e.onProgress&&e.onProgress(u),w.enqueue(b)},flush(T){if(u<Be.MIN_UPLOAD_SIZE){T.error(new Mn(u));return}}}),d=a?s.pipeThrough(p).pipeThrough(a):s.pipeThrough(p),l,m={},f={"Content-Type":"application/octet-stream"};if(UP())l=d,m={duplex:"half"};else{let T=[],w=0,b=d.getReader();for(;;){let{done:I,value:$}=await b.read();if(I)break;T.push($),w+=$.length}l=new Blob(T),f["Content-Length"]=(c??w).toString()}let y=await L.put(new URL(`pdp/piece/uploads/${r}`,e.serviceURL),{body:l,headers:f,timeout:!1,signal:e.signal,...m});if(y.error)throw ne.is(y.error)?new Os(`Failed to upload piece: ${await y.error.response.text()}`):y.error;if(y.result.status!==204)throw new Os(`Expected 204 No Content, got ${y.result.status}`);let x=await o,g=await L.post(new URL(`pdp/piece/uploads/${r}`,e.serviceURL),{json:{pieceCid:x.toString()},timeout:ee.TIMEOUT,retry:{methods:["post"],retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},signal:e.signal});if(g.error)throw ne.is(g.error)?new jn(`Failed to finalize upload: ${await g.error.response.text()}`):g.error;if(g.result.status!==200)throw new jn(`Expected 200 OK for finalization, got ${g.result.status}`);return{pieceCid:x,size:u}}var zC=8e3,DC=2,CC=500;async function w_(e,t={}){let n=await L.get(new URL("pdp/ping",e),{retry:{retries:DC,minTimeout:CC},signal:t.signal,timeout:t.timeout??zC});if(n.error)throw n.error;return n.result}async function I_(e,t){let n=F(e.chain),i=await xn(e,{account:e.account,domain:So({chain:n}),types:St,primaryType:"SchedulePieceRemovals",message:{clientDataSetId:t.clientDataSetId,pieceIds:t.pieceIds}});return ze([{type:"bytes"}],[i])}var S_=(1n<<63n)-1n;async function RC(e){let{serviceURL:t,dataSetId:n,extraData:i}=e,r=P_(e.pieceIds),o=`{"extraData":${JSON.stringify(i)},"pieceIds":[${r.join(",")}]}`,a=await L.delete(new URL(`pdp/data-sets/${n}/pieces/${r[0]}`,t),{body:o,headers:{"content-type":"application/json"},signal:e.signal,timeout:ee.TIMEOUT,retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY}});if(a.error)throw ne.is(a.error)?new zl(await a.error.response.text()):a.error;return{hash:(await a.result.json()).txHash}}function NC(e){if(!Number.isInteger(e)||e<1)throw new Zo}function P_(e){let t=[...new Set(e)];NC(t.length);for(let n of t)if(n<0n||n>S_)throw new RangeError(`Piece ID ${n} is outside Curio's supported range of 0 to ${S_}`);return t}async function __(e,t){Vo(t.signal);let n=P_(t.pieceIds);return RC({serviceURL:t.serviceURL,dataSetId:t.dataSetId,pieceIds:n,extraData:await I_(e,{clientDataSetId:t.clientDataSetId,pieceIds:n}),retryCount:t.retryCount,retryDelay:t.retryDelay,signal:t.signal})}async function $_(e,t={}){let{cursor:n,limit:i}=Do(t,100n),r=await O(e,OC({chain:e.chain,offset:n,limit:i+1n,contractAddress:t.contractAddress}));return ml(r,i,()=>n+i)}function OC(e){let t=F(e.chain);return{abi:t.contracts.fwssView.abi,address:e.contractAddress??t.contracts.fwssView.address,functionName:"getApprovedProviders",args:[e.offset,e.limit]}}async function UC(e,t={}){let{cursor:n,limit:i}=Do(t,50n),r=await O(e,LC({chain:e.chain,onlyActive:t.onlyActive,offset:n,limit:i,contractAddress:t.contractAddress}));return BC(r,n)}function LC(e){let t=F(e.chain);return{abi:t.contracts.serviceProviderRegistry.abi,address:e.contractAddress??t.contracts.serviceProviderRegistry.address,functionName:"getProvidersByProductType",args:[Cs.PDP,e.onlyActive??!0,e.offset,e.limit]}}function BC(e,t=0n){return{items:e.providers.map(Fn),...e.hasMore?{nextCursor:t+BigInt(e.providers.length)}:{}}}async function E_(e,t={}){let[n,i]=await Promise.all([Array.fromAsync(Ln(({cursor:r})=>UC(e,{onlyActive:!0,cursor:r,contractAddress:t.contractAddress}))),Array.fromAsync(Ln(({cursor:r})=>$_(e,{cursor:r})))]);return n.filter(r=>i.includes(r.id))}async function k_(e,t={}){let n=await O(e,FC({chain:e.chain,contractAddress:t.contractAddress}));return jC(n)}function FC(e){let t=F(e.chain);return{abi:t.contracts.endorsements.abi,address:e.contractAddress??t.contracts.endorsements.address,functionName:"getProviderIds",args:[]}}function jC(e){return Array.from(new Set(e))}async function A_(e,t){let[n,i,r]=await Promise.all([E_(e),k_(e),Array.fromAsync(Ln(({cursor:o})=>Tl(e,{address:t.address,cursor:o})))]);return{providers:n,endorsedIds:i,clientDataSets:r,legacyPieceStorageIdLimit:F(e.chain).legacyPieceStorageIdLimit}}function MC(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;if(i.length===0)return!0;for(let r of i)if(e[r]!==t[r])return!1;return!0}function Ml(e,t,n=0n){return e.filter(r=>r.live&&r.managed&&r.pdpEndEpoch===0n&&MC(r.metadata,t)).sort((r,o)=>{let a=r.dataSetId>=n,s=o.dataSetId>=n;return a!==s?a?-1:1:r.hasActivePieces&&!o.hasActivePieces?-1:o.hasActivePieces&&!r.hasActivePieces?1:r.dataSetId<o.dataSetId?-1:r.dataSetId>o.dataSetId?1:0})}function z_(e){let t=e.count??1,n=e.excludeProviderIds??[],i=e.metadata??{},r=e.endorsedIds.length>0,o=e.providers.filter(d=>!n.includes(d.id)&&(!r||e.endorsedIds.includes(d.id)));if(o.length===0)return[];let a=new Map(o.map(d=>[d.id,d])),s=e.clientDataSets.filter(d=>a.has(d.providerId)),c=Ml(s,i,e.legacyPieceStorageIdLimit),u=[],p=[];for(let d=0;d<t;d++){let l=!1;for(let m of c){if(p.includes(m.providerId))continue;let f=a.get(m.providerId);if(f!=null){u.push({provider:f,dataSetId:m.dataSetId,endorsed:e.endorsedIds.includes(m.providerId),dataSetMetadata:m.metadata}),p.push(m.providerId),l=!0;break}}if(!l){for(let m of o)if(!p.includes(m.id)){u.push({provider:m,dataSetId:null,endorsed:e.endorsedIds.includes(m.id),dataSetMetadata:i}),p.push(m.id),l=!0;break}}if(!l)break}return u}var VC=(1n<<128n)-1n;function C_(e,t){let n=e.client,i=t.client,r=t.rootAddress,o=e.signal,a=new Map;function s(d){let l=a.get(d);return l||(l=v_(n,{dataSetId:d}),l.catch(()=>a.delete(d)),a.set(d,l)),l}async function c(d){try{return await w_(d,{signal:o}),!0}catch(l){if(o?.aborted)throw l;return!1}}return{async selectPlacement({metadata:d,providerId:l}){let[m,f]=await Promise.all([A_(n,{address:r}),l==null?void 0:zP(n,{providerId:l})]);if(l!=null){if(!f)throw Jt(`Provider ${l} has no active PDP offering.`);let x=Ml(m.clientDataSets.filter(g=>g.providerId===l),d,m.legacyPieceStorageIdLimit);return u({providerId:l,serviceURL:f.pdp.serviceURL,payee:f.payee,dataSetId:x[0]?.dataSetId})}let y=[];for(;;){let[x]=z_({...m,count:1,metadata:d,excludeProviderIds:y});if(!x)throw new Kt({code:"service_unavailable",message:"No reachable storage provider is available."});let g=x.provider;if(await c(g.pdp.serviceURL))return u({providerId:g.id,serviceURL:g.pdp.serviceURL,payee:g.payee,dataSetId:x.dataSetId??void 0});y.push(g.id)}},async quote({size:d,placement:l}){let m=l.dataSetId==null?void 0:await p(l.dataSetId),f=await d_(n,{clientAddress:r,pieceSizes:[BigInt(d)],isNewDataSet:m==null,...m});return{ready:f.ready,depositNeeded:f.depositNeeded,needsApproval:f.needsFwssMaxApproval,ratePerMonth:f.rates.perMonth,lockup:f.lockups.total,fundingUrl:QP({consoleUrl:e.consoleUrl,network:e.network,deposit:f.depositNeeded})}},async hasPiece({serviceURL:d,pieceCid:l}){try{return await Zv({serviceURL:d,pieceCid:ft(l),signal:o}),!0}catch(m){if(o?.aborted)throw m;return!1}},async upload({serviceURL:d,path:l,size:m,pieceCid:f}){let y=ft(f);await T_({serviceURL:d,data:HC.toWeb(ZC(l)),size:m,pieceCid:y,signal:o}),await Zv({serviceURL:d,pieceCid:y,poll:!0,signal:o})},async signCommit({placement:d,pieceCid:l,metadata:m,pieceMetadata:f}){let y=br(),x=[{pieceCid:ft(l),metadata:Wr(f)}];if(d.dataSetId==null){let T=br(),w=await Bl(i,{clientDataSetId:T,nonce:y,payee:d.payee,payer:r,metadata:No(m,{cdn:!1}),pieces:x});return{created:!0,nonce:y.toString(),clientDataSetId:T.toString(),extraData:w}}if(d.clientDataSetId==null)throw new Error("Adding to a data set requires its client data set ID.");let g=await Ho(i,{clientDataSetId:d.clientDataSetId,nonce:y,pieces:x});return{created:!1,nonce:y.toString(),extraData:g}},async submitCommit({placement:d,pieceCid:l,commit:m,pieceMetadata:f}){let y=[{pieceCid:ft(l),metadata:f}];if(m.created){let g=await h_(i,{serviceURL:d.serviceURL,payee:d.payee,payer:r,pieces:y,extraData:m.extraData,signal:o});return{transactionHash:g.txHash,statusUrl:g.statusUrl}}if(d.dataSetId==null||d.clientDataSetId==null)throw new Error("Adding to a data set requires its IDs.");let x=await y_(i,{serviceURL:d.serviceURL,dataSetId:d.dataSetId,clientDataSetId:d.clientDataSetId,pieces:y,extraData:m.extraData,signal:o});return{transactionHash:x.txHash,statusUrl:x.statusUrl}},async findCommit({nonce:d}){let l=await O(n,{address:n.chain.contracts.fwssView.address,abi:n.chain.contracts.fwssView.abi,functionName:"clientNonces",args:[r,d]});if(l!==0n)return{dataSetId:l&VC,pieceId:(l>>128n)-1n}},async waitForCommit({statusUrl:d,created:l}){try{if(l){let f=await x_({statusUrl:d,signal:o});return{dataSetId:f.dataSetId,pieceId:D_(f.piecesIds)}}let m=await jl({statusUrl:d,signal:o});return{dataSetId:m.dataSetId,pieceId:D_(m.confirmedPieceIds)}}catch(m){throw Lo.is(m)||Uo.is(m)?new Kt({code:Tr.commitRejected,message:"The provider reported the commit transaction as failed.",cause:m}):m}},async schedulePieceRemoval({serviceURL:d,dataSetId:l,pieceId:m}){let f=await s(l);if(!f)throw Jt(`Data set ${l} not found.`);return{transactionHash:(await __(i,{serviceURL:d,dataSetId:l,clientDataSetId:f.clientDataSetId,pieceIds:[m],signal:o})).hash}},async waitForTransaction(d){return{status:(await Hs(Ea(n,{hash:d}),o)).status}}};async function u(d){if(d.dataSetId==null)return d;let l=await s(d.dataSetId);return l?{...d,clientDataSetId:l.clientDataSetId}:{...d,dataSetId:void 0}}async function p(d){let[l,m]=await Promise.all([s(d),IP(n,{dataSetId:d})]);if(l)return{dataSetLeafCount:m,currentLifecycleReserveBalance:l.lifecycleReserveBalance,pendingOneTimePayments:l.pendingOneTimePayments,pdpEndEpoch:l.pdpEndEpoch}}}function D_(e){let[t]=e;if(t==null)throw new Error("Provider confirmed no piece IDs.");return t}import{join as xR}from"node:path";var GC=Uu([it(jt.rpcUrls.default.http[0]),it(jt.rpcUrls.ankr.http[0]),it(jt.rpcUrls.drpc.http[0])],{rank:!1}),qC=Uu([it(Mt.rpcUrls.default.http[0]),it(Mt.rpcUrls.ankr.http[0]),it(Mt.rpcUrls.drpc.http[0])],{rank:!1}),KC=it(xo.rpcUrls.default.http[0]);function R_(e){if(e.id===jt.id)return GC;if(e.id===Mt.id)return qC;if(e.id===xo.id)return KC;throw new ho(e.id)}import Hn from"node:fs";import ql from"node:path";import Kl from"node:process";import{isDeepStrictEqual as q_}from"node:util";function N_(e){if(e.path?.length){let t="";for(let n of e.path){let i=typeof n=="object"?n.key:n;if(typeof i=="string"||typeof i=="number")t?t+=`.${i}`:t+=i;else return null}return t}return null}var O_=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}};var Zn=e=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")},Zl=new Set(["__proto__","prototype","constructor"]),WC=Math.max(...[...Zl].map(e=>e.length)),U_=1e6,JC=e=>e>="0"&&e<="9";function L_(e){if(e==="0")return!0;if(/^[1-9]\d*$/.test(e)){let t=Number.parseInt(e,10);return t<=Number.MAX_SAFE_INTEGER&&t<=U_}return!1}function Hv(e,t){return Zl.has(e)?!1:(e&&L_(e)?t.push(Number.parseInt(e,10)):t.push(e),!0)}function XC(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);let t=[],n="",i="",r=!1,o="start",a=!1,s=0;for(let c of e){if(s++,a){n+=c,a=!1;continue}if(c==="\\"){if(o==="index")throw new Error(`Invalid character '${c}' in an index at position ${s}`);if(o==="indexEnd")throw new Error(`Invalid character '${c}' after an index at position ${s}`);a=!0,o=o==="start"?"property":o;continue}switch(c){case".":{if(o==="index")throw new Error(`Invalid character '${c}' in an index at position ${s}`);if(o==="indexEnd"){o="property";break}if(!Hv(n,t))return[];n="",o="property";break}case"[":{if(o==="index")throw new Error(`Invalid character '${c}' in an index at position ${s}`);if(o==="indexEnd"){o="index";break}if(o==="property"&&n.length<=WC&&Zl.has(n))return[];r=o==="property",o="index";break}case"]":{if(o==="indexEnd")throw new Error(`Invalid character '${c}' after an index at position ${s}`);if(o!=="index"){o==="start"&&(o="property"),n+=c;break}if(i===""){n+="[]",o="property";break}if((n!==""||r)&&!Hv(n,t))return[];n="",r=!1;let u=Number.parseInt(i,10),p=u<=U_&&i===String(u);t.push(p?u:i),i="",o="indexEnd";break}default:{if(o==="index"){if(!JC(c))throw new Error(`Invalid character '${c}' in an index at position ${s}`);i+=c;break}if(o==="indexEnd")throw new Error(`Invalid character '${c}' after an index at position ${s}`);o==="start"&&(o="property"),n+=c}}}switch(a&&(n+="\\"),o){case"property":{if(!Hv(n,t))return[];break}case"index":throw new Error("Index was not closed");case"start":{t.push("");break}}return t}function Hl(e){if(typeof e=="string")return XC(e);if(Array.isArray(e)){let t=[];for(let[n,i]of e.entries()){if(typeof i!="string"&&typeof i!="number")throw new TypeError(`Expected a string or number for path segment at index ${n}, got ${typeof i}`);if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`Path segment at index ${n} must be a finite number, got ${i}`);if(Zl.has(i))return[];typeof i=="string"&&L_(i)?t.push(Number.parseInt(i,10)):t.push(i)}return t}return[]}function B_(e,t,n){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return n===void 0?e:n;let i=Hl(t);if(i.length===0)return n;for(let r=0;r<i.length;r++){let o=i[r];if(e=e[o],e==null){if(r!==i.length-1)return n;break}}return e===void 0?n:e}function F_(e,t,n){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return e;let i=e,r=Hl(t);if(r.length===0)return e;for(let o=0;o<r.length;o++){let a=r[o];if(o===r.length-1){e[a]=n;continue}let s=e[a];if(Zn(s)){e=s;continue}let u=typeof r[o+1]=="number";e[a]=u?[]:{},e=e[a]}return i}function Vv(e,t){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return!1;let n=Hl(t);if(n.length===0)return!1;for(let i=0;i<n.length;i++){let r=n[i];if(i===n.length-1)return Object.hasOwn(e,r)?(delete e[r],!0):!1;let o=e[r];if(!Zn(o))return!1;e=o}}function j_(e,t){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return!1;let n=Hl(t);if(n.length===0)return!1;for(let i of n){if(!Zn(e)||!(i in e))return!1;e=e[i]}return!0}var Go=e=>e instanceof URL?{$url:e.toString()}:e instanceof Map?{$map:[...e.entries()].map(([t,n])=>[Go(t),Go(n)])}:e instanceof Uint8Array?{$bytes:[...e.values()]}:e instanceof ArrayBuffer?{$bytes:[...new Uint8Array(e).values()]}:e?.type==="Buffer"&&Array.isArray(e.data)?{$bytes:e.data}:typeof e=="bigint"?{$bigint:e.toString()}:e instanceof Set?{$set:[...e.values()].map(t=>Go(t))}:e instanceof RegExp?{$regex:[e.source,e.flags]}:Array.isArray(e)?e.map(t=>Go(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Go(n)])):e,YC=(e,t)=>t instanceof URL?{$url:t.toString()}:t instanceof Map?{$map:[...t.entries()]}:t instanceof Uint8Array?{$bytes:[...t.values()]}:t instanceof ArrayBuffer?{$bytes:[...new Uint8Array(t).values()]}:t?.type==="Buffer"&&Array.isArray(t.data)?{$bytes:t.data}:typeof t=="bigint"?{$bigint:t.toString()}:t instanceof Set?{$set:[...t.values()]}:t instanceof RegExp?{$regex:[t.source,t.flags]}:t,QC=(e,t)=>t&&(t.$url?new URL(t.$url):t.$map?new Map(t.$map):t.$bytes?new Uint8Array(t.$bytes):t.$bigint?BigInt(t.$bigint):t.$set?new Set(t.$set):t.$regex?new RegExp(t.$regex[0],t.$regex[1]):t),M_=(e,t)=>JSON.stringify(Go(e),YC,t),Z_=e=>JSON.parse(e,QC);import{randomBytes as eR}from"node:crypto";import et from"node:fs";import js from"node:path";import vr from"node:process";var tR=new Set(["EAGAIN","EBUSY","EMFILE","ENFILE"]),rR=new Set(["EACCES","EPERM"]),nR=1e3,iR=200,oR=6e4,H_=new Set,Gl=e=>e?.code??"",Vl=e=>{let t=Date.now()+nR;for(let n=10;;n=Math.min(n*2,100))try{return e()}catch(i){let r=Gl(i);if(!(tR.has(r)||vr.platform==="win32"&&rR.has(r))||Date.now()+n>t)throw i;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n)}},Fs=e=>{try{e()}catch{}},aR=e=>{let t=Gl(e),n=vr.geteuid?.()===0;return t==="ENOSYS"||!n&&(t==="EINVAL"||t==="EPERM")},sR=(e,t)=>{let n=0;for(;n<t.length;)n+=et.writeSync(e,t,n,t.length-n,n)},V_=e=>{let t=[...js.basename(e)];for(;Buffer.byteLength(t.join(""))>iR;)t.pop();return`${t.join("")}.`},cR=e=>{try{return vr.kill(e,0),!0}catch(t){return Gl(t)==="EPERM"}},uR=e=>{if(H_.has(e))return;H_.add(e);let t=js.dirname(e),n=V_(e),i=[];Fs(()=>{i=et.readdirSync(t)});for(let r of i){if(!r.startsWith(n))continue;let o=/^(\d+)\.[0-9a-f]{8}\.tmp$/.exec(r.slice(n.length));if(!o)continue;let a=Number(o[1]);if(a===vr.pid||cR(a))continue;let s=js.join(t,r);Fs(()=>{Date.now()-et.statSync(s).mtimeMs>oR&&et.rmSync(s,{force:!0})})}},G_=(e,t,n)=>{let i=e,r;try{i=et.realpathSync(e),r=et.statSync(i)}catch(c){if(Gl(c)!=="ENOENT")throw c}let o=n??(r?r.mode&4095:438),a=js.join(js.dirname(i),`${V_(i)}${vr.pid}.${eR(4).toString("hex")}.tmp`),s;try{s=Vl(()=>et.openSync(a,"wx",o));let c=s,u=Buffer.from(t);Vl(()=>sR(c,u));try{et.fchmodSync(c,o)}catch(p){if(!aR(p))throw p}r&&vr.geteuid&&vr.getegid&&(r.uid!==vr.geteuid()||r.gid!==vr.getegid())&&Fs(()=>et.fchownSync(c,r.uid,r.gid)),Vl(()=>et.fsyncSync(c)),s=void 0,et.closeSync(c),Vl(()=>et.renameSync(a,i))}catch(c){let u=s;throw u!==void 0&&Fs(()=>et.closeSync(u)),Fs(()=>et.rmSync(a,{force:!0})),c}uR(i)};var Xr=()=>Object.create(null),pR=/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~]+/,dR=/[A-ZÀ-Ý\u00C0-\u00D6\u00D9-\u00DD][a-zà-ÿ]/g,lR=/[A-ZÀ-Ý\u00C0-\u00D6\u00D9-\u00DD]+/g,mR=e=>(e=e.replace(dR,t=>` ${t[0].toLowerCase()||t[0]}${t[1]}`),e=e.replace(lR,t=>` ${t.toLowerCase()}`),e.trim().split(pR).join("-").replace(/^-/,"").replace(/-\s*$/,"")),fR=e=>e===null?"null":Array.isArray(e)?"array":typeof e,K_=(e,t)=>{let n=new Set(["undefined","symbol","function"]),i=typeof t;if(n.has(i))throw new TypeError(`Setting a value of type \`${i}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},yR=(e,t)=>{let n=e["~standard"].validate(t);if(n instanceof Promise)throw new TypeError("Async schemas are not supported. The schema `validate` function must return synchronously.");if(n.issues){let i=n.issues.map(o=>{let a=N_(o);return a?`\`${a}\` ${o.message}`:o.message}).join("; "),r=new O_(n.issues);throw r.message=`Config schema violation: ${i}`,r}return n.value},Wl=class{path;events;#e;#t;#r;#n;#p;#i;#y=new WeakMap;constructor(t={}){let n=this.#I(t);this.#t=n,this.#e=n.schema,n.defaults!==void 0&&(this.#r=this.#u(n.defaults)),this.events=new EventTarget,this.path=this.#S(n),this.#P(),n.watch&&this.#_()}get(t,n){return this.#o(this.store,t,n)}set(t,n){let i=fR(t);if(i!=="string"&&i!=="object")throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${i}`);if(typeof t!="object"&&n===void 0)throw new TypeError("Use `delete()` to clear values");let r=this.store;if(typeof t=="object")for(let[o,a]of Object.entries(t))this.#s(r,o,a);else this.#s(r,t,n);this.store=r}has(t){let n=String(t);return this.#t.accessPropertiesByDotNotation?j_(this.store,n):n in this.store}appendToArray(t,n){let i=String(t);K_(i,n);let r=this.store,o=this.#o(r,i,[]);if(!Array.isArray(o))throw new TypeError(`The key \`${i}\` is already set to a non-array value`);this.#s(r,i,[...o,n]),this.store=r}reset(...t){let n=this.store,i=!1;for(let r of t){let o=String(r),a=this.#T(n,o);a!==void 0&&(this.#s(n,o,a),i=!0)}i&&(this.store=n)}delete(t){let n=String(t),i=this.store;this.#t.accessPropertiesByDotNotation?Vv(i,n):delete i[n],this.store=i}clear(){this.store=Xr()}onDidChange(t,n){if(typeof t!="string")throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof t}`);if(typeof n!="function")throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof n}`);return this.#v(i=>this.#o(i,t),n)}onDidAnyChange(t){if(typeof t!="function")throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this.#v(n=>n,t)}get size(){return Object.keys(this.store).length}get store(){return this.#l(this.#d())}set store(t){this.#x(this.#a(t)),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[t,n]of Object.entries(this.store))yield[t,n]}_closeWatcher(){this.#n&&(this.#n.close(),this.#n=void 0),this.#p&&(Hn.unwatchFile(this.path),this.#p=!1),this.#i?.cancel(),this.#i=void 0}#d(){try{return Hn.readFileSync(this.path,"utf8")}catch(t){if(t.code==="ENOENT"){this.#f();return}throw t}}#l(t){return this.#g(t).value}#g(t){if(t!==void 0)try{let i=Object.assign(Xr(),this.#c(t));return{raw:i,value:this.#a(i)}}catch(i){if(!this.#t.clearInvalidConfig)throw i}let n=Xr();return{raw:n,value:this.#a(n),cleared:t!==void 0}}#h(){return this.#r===void 0?Xr():Object.assign(Xr(),this.#c(this.#r))}#T(t,n){let i=this.#o(this.#h(),n);if(i!==void 0)return i;let r=Object.assign(Xr(),this.#c(this.#u(t)));this.#t.accessPropertiesByDotNotation?Vv(r,n):delete r[n];try{return this.#o(this.#a(r),n)}catch{return}}#o(t,n,i){return this.#t.accessPropertiesByDotNotation?B_(t,n,i):n in t?t[n]:i}#s(t,n,i){K_(n,i),this.#t.accessPropertiesByDotNotation?F_(t,n,i):n!=="__proto__"&&n!=="constructor"&&n!=="prototype"&&(t[n]=i)}#w(t){let n=this.#y.get(t);if(n===void 0){try{let i=this.#d();n={data:i,store:this.#l(i)}}catch(i){n=null,this.#m(i)}this.#y.set(t,n)}return n}#m(t){this.events.dispatchEvent(new CustomEvent("error",{detail:t}))}#a(t){let n=Object.assign(this.#h(),t);return this.#e?yR(this.#e,n):n}#x(t){if(this.#e)try{this.#a(t)}catch(n){throw new TypeError(`Schema output must be valid schema input to be stored. ${n.message}`,{cause:n})}this.#f(),this.#b(t)}#f(){Hn.mkdirSync(ql.dirname(this.path),{recursive:!0})}#b(t){let n=this.#u(t);if(Kl.env.SNAP){Hn.writeFileSync(this.path,n,{mode:this.#t.configFileMode});return}G_(this.path,n,this.#t.configFileMode)}#v(t,n){let i=t(this.store),r=o=>{try{let a=this.#w(o);if(a===null||q_(t(a.store),i))return;let s=i,c=t(this.#l(a.data));i=c,n.call(this,c,s)}catch(a){this.#m(a)}};return this.events.addEventListener("change",r),()=>{this.events.removeEventListener("change",r)}}#c=t=>Z_(t);#u=t=>M_(t," ");#I(t){let n={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:384,...t};if(!n.cwd){if(!n.projectName)throw new Error("Please specify the `projectName` option.");n.cwd=Ls(mR(n.projectName),{suffix:n.projectSuffix??"nodejs"}).config}return typeof n.fileExtension=="string"&&(n.fileExtension=n.fileExtension.replace(/^\.+/,"")),n.serialize&&(this.#u=n.serialize),n.deserialize&&(this.#c=n.deserialize),n}#S(t){let n=t.fileExtension?`.${t.fileExtension}`:"";return ql.resolve(t.cwd??Kl.cwd(),`${t.configName??"config"}${n}`)}#P(){let{raw:t,value:n,cleared:i}=this.#g(this.#d());(i||!q_(t,Object.assign(Xr(),n)))&&this.#x(n)}#_(){if(this.#f(),Hn.existsSync(this.path)||this.#b(Xr()),Kl.platform==="win32"||Kl.platform==="darwin"){this.#i??=W_(()=>{this.events.dispatchEvent(new Event("change"))},100);let t=ql.dirname(this.path),n=ql.basename(this.path);this.#n=Hn.watch(t,{persistent:!1,encoding:"utf8"},(i,r)=>{r&&r!==n||this.#i?.()}),this.#n.on("error",i=>{this._closeWatcher(),this.#m(i)})}else this.#i??=W_(()=>{this.events.dispatchEvent(new Event("change"))},1e3),Hn.watchFile(this.path,{persistent:!1},()=>{this.#i?.()}),this.#p=!0}};function W_(e,t){let n,i=()=>{clearTimeout(n),n=void 0};return Object.assign(()=>{i(),n=setTimeout(()=>{n=void 0,e()},t)},{cancel:i})}var gR=Yv(e0),J_=Zs({privateKey:Wt(),address:Wt(),rootAddress:Wt().optional(),scopes:Xv(Wt()),name:Wt().optional(),days:Jv().int().optional(),fromBlock:Wt(),expiresAt:Wt().optional(),createdAt:Wt()}),hR=Zs({network:gR.optional(),sessions:Zs({mainnet:J_.optional(),calibration:J_.optional()}).default({})});function X_(e=process.env){return new Wl({projectName:"filecoin",projectSuffix:"",cwd:e.FILECOIN_CONFIG_DIR,schema:hR})}function Y_(e,t){return e??t.get("network")??t0}var bR="https://poc.filecoin.cloud",vR="https://api.filecoin.cloud";function TR(e,t){return n=>{let i=e(n);return{...i,request:(r,o)=>t.aborted?Promise.reject(t.reason):Hs(i.request(r,o),t)}}}function Q_(e={}){let t=e.env??process.env,n=X_(t),i=Y_(e.network,n),r=i==="mainnet"?jt:Mt,o=t.FILECOIN_RPC_URL?it(t.FILECOIN_RPC_URL):R_(r),a=e.signal?TR(o,e.signal):o,s=HP(t),c;return{network:i,chain:r,env:t,config:n,credentials:{sessionKey:e.sessionKey,rootAddress:e.rootAddress},consoleUrl:t.FILECOIN_CONSOLE_URL??bR,apiUrl:t.FILECOIN_API_URL??vR,signal:e.signal,transport:a,client:Af({chain:r,transport:a}),db:()=>(c??=VP(s),c),stagingDir:u=>xR(s,"staging",u)}}function nde(e){let{network:t,sessionKey:n,rootAddress:i}=e.input;return Q_({network:t,sessionKey:n,rootAddress:i,signal:e.signal})}function e$(e){let t=Uv(e);if(!t)throw Lv();return{chainId:e.chain.id.toString(),payer:t.rootAddress}}async function ide(e,t,n){let i=await e_(e,t);return{db:e.db(),backend:C_(e,i),chainId:e.chain.id.toString(),payer:i.rootAddress,apiUrl:e.apiUrl,stagingDir:e.stagingDir,signal:n.signal,progress:r=>n.progress(r),onOperation:r=>n.checkpoint({id:r.id,next:[Qv(r.id)]})}}function ode(e,t){let n=KP(e.db(),t,e$(e));if(!n)throw Jt(`No managed resource ${t}.`,{by:"agent",command:"filecoin ls",description:"List managed resources"});return n}function ade(e,t){let n=Fo(e.db(),t,e$(e));if(!n)throw Jt(`No operation ${t}.`,{by:"agent",command:"filecoin operations ls",description:"List operations"});return n}export{O as a,$e as b,Nt as c,jt as d,Mt as e,F as f,Xd as g,ZA as h,Wb as i,Po as j,Fre as k,jre as l,Yb as m,vP as n,jS as o,_o as p,Vre as q,Gre as r,HS as s,$o as t,Gt as u,az as v,cz as w,pz as x,el as y,KS as z,Pt as A,pne as B,CD as C,RD as D,xl as E,Be as F,Vz as G,Do as H,Ln as I,loe as J,HP as K,HD as L,qP as M,lae as N,Fo as O,mae as P,fae as Q,yae as R,gae as S,bae as T,KP as U,vae as V,Tae as W,WP as X,YP as Y,QP as Z,YD as _,QD as $,Dae as aa,Uv as ba,eC as ca,tC as da,Lv as ea,rC as fa,nC as ga,t_ as ha,r_ as ia,o_ as ja,d_ as ka,C_ as la,nde as ma,e$ as na,ide as oa,ode as pa,ade as qa};
186
- //# sourceMappingURL=chunk-72RYXITT.js.map
185
+ LIMIT ?`).all(t.chainId,t.payer,...n??[],t.limit+1);return Rl(i.map(Nv),t.limit,r=>[r.createdAt,r.ref])}var KD=18;function WP(e){return Ia(e,KD)}import{setTimeout as WD}from"node:timers/promises";var XP="/dashboard/setup";function YP(e){let t=new URL(XP,e.consoleUrl);return t.searchParams.set("network",e.network),t.searchParams.set("signer",e.address.toLowerCase()),e.name&&t.searchParams.set("name",e.name),t.searchParams.set("scopes",e.scopes.join(",")),e.days!=null&&t.searchParams.set("days",String(e.days)),t.toString()}function QP(e){let t=new URL(XP,e.consoleUrl);return t.searchParams.set("network",e.network),e.deposit!=null&&e.deposit>0n&&t.searchParams.set("deposit",WP(e.deposit)),t.toString()}var Ov=2000n;async function JD(e){let{client:t,signer:n}=e,i=rn({abi:vt,name:"AuthorizationsUpdated"}),r=await $e(t,{cacheTime:0}),o;for(let a=e.fromBlock;a<=r;a+=Ov+1n){let s=a+Ov>r?r:a+Ov,c=await ir(t,{address:t.chain.contracts.sessionKeyRegistry.address,event:i,fromBlock:a,toBlock:s,strict:!0});for(let u of c)_e(u.args.signer,n)&&(o=u.args.identity)}return o}function XD(e,t,n=BigInt(Math.floor(Date.now()/1e3))){let i=[],r=[],o;for(let a of e){let s=t[Po[a]]??0n;s>n?(i.push(a),(o===void 0||s<o)&&(o=s)):r.push(a)}return o===void 0?{granted:i,missing:r}:{granted:i,missing:r,expiresAt:o}}async function YD(e){let t=await Xd(e.client,{address:e.root,sessionKeyAddress:e.signer,permissions:Qd(e.scopes)});return XD(e.scopes,t)}async function QD(e){let t=await JD(e);if(!t)return{status:"pending"};let n=await YD({...e,root:t});return{status:n.missing.length===0?"granted":n.granted.length>0?"partial":"none",root:t,...n}}var JP=3e3;async function Dae(e){let t=Date.now();for(;;){try{let n=await QD(e);if(n.status!=="pending")return n}catch(n){if(e.signal?.aborted)throw n}if(Date.now()-t+JP>e.timeoutMs)return{status:"pending"};await WD(JP,void 0,{signal:e.signal})}}function Uv(e){let{sessionKey:t,rootAddress:n}=e.credentials;if(t||n){if(!t)throw qo("FILECOIN_SESSION_KEY must be a 32-byte hex private key.","sessionKey");if(!(n&&pe(n)))throw qo("FILECOIN_ROOT_ADDRESS must be the wallet that authorized FILECOIN_SESSION_KEY.","rootAddress");return{privateKey:t,rootAddress:tt(n),source:"env"}}let i=e.config.get(`sessions.${e.network}`);if(i){if(!i.rootAddress)throw eC(YP({consoleUrl:e.consoleUrl,address:i.address,scopes:i.scopes.filter(Yb),network:e.network,name:i.name,days:i.days}));return{privateKey:i.privateKey,rootAddress:tt(i.rootAddress),source:"config"}}}function eC(e){return new Kt({code:Tr.loginPending,message:"The session key is waiting for approval in filecoin-app.",details:{url:e},next:[{by:"user",description:`Open ${e} and approve the session key with your wallet`},{by:"agent",command:"filecoin login --check",description:"Confirm the saved key after the user approves"}]})}function tC(e={}){let t=["filecoin login"];e.fresh&&t.push("--fresh");for(let n of e.scopes??[])t.push(`--scopes ${n}`);return t.join(" ")}function Lv(){return new Kt({code:Tr.authRequired,message:"No session key for this network.",next:[{by:"user",command:"filecoin login",description:"Authorize a session key in the filecoin-app dashboard, then retry"}]})}function rC(e){let t=Uv(e);if(!t)throw Lv();return Xb({privateKey:t.privateKey,root:t.rootAddress,chain:e.chain,transport:e.transport})}async function nC(e,t){let n=Qd(t);return await e.syncExpirations(n),t.filter(i=>!e.hasPermission(Po[i]))}async function e_(e,t){let n=rC(e),i=await nC(n,t);if(i.length>0){let r=e.config.get(`sessions.${e.network}`)?.scopes.filter(Yb),o=r?.length?r:zm,a=i.filter(s=>!o.includes(s));throw new Kt({code:Tr.sessionExpired,message:`The session key is missing or expired for: ${i.join(", ")}.`,details:{missing:i},next:[{by:"user",command:tC({fresh:!0,scopes:a.length>0?[...o,...a]:void 0}),description:"Authorize a new session key with the needed scopes"}]})}return n}function t_(e){let{funds:t,lockupCurrent:n,lockupRate:i,lockupLastSettledAt:r,currentEpoch:o}=e,a=o-r,s=n+i*a;return s>t?s-t:0n}async function r_(e,t){let n=t.blockNumber??await $e(e,{cacheTime:0}),i=await O(e,iC({chain:e.chain,token:t.token,address:t.address,contractAddress:t.contractAddress}));return oC(i,n)}function iC(e){let t=F(e.chain),n=e.token??t.contracts.usdfc.address;return{abi:t.contracts.filecoinPay.abi,address:e.contractAddress??t.contracts.filecoinPay.address,functionName:"accounts",args:[n,e.address]}}function oC(e,t){let[n,i,r,o]=e,a=t-o,s=i+a*r,c=n-s;return{funds:e[0],lockupCurrent:e[1],lockupRate:e[2],lockupLastSettledAt:e[3],availableFunds:c<0n?0n:c}}async function Ol(e,t={}){let n=await O(e,aC({chain:e.chain,contractAddress:t.contractAddress}));return{token:n.token,rates:{storagePerTibPerMonth:n.rates.storagePerTibPerMonth,datasetFeePerMonth:n.rates.datasetFeePerMonth,cdnEgressPerTib:n.rates.cdnEgressPerTib,cacheMissEgressPerTib:n.rates.cacheMissEgressPerTib},fees:{createDataSetFee:n.fees.createDataSetFee,addPiecesBaseFee:n.fees.addPiecesBaseFee,addPiecesPerPieceFee:n.fees.addPiecesPerPieceFee,schedulePieceRemovalsFee:n.fees.schedulePieceRemovalsFee,terminateFee:n.fees.terminateFee},lockups:{lifecycleReserveTarget:n.lockups.lifecycleReserveTarget,replenishThreshold:n.lockups.replenishThreshold,defaultLockupPeriod:n.lockups.defaultLockupPeriod,cdnLockupAmount:n.lockups.cdnLockupAmount,cacheMissLockupAmount:n.lockups.cacheMissLockupAmount,cdnLockupPeriod:n.lockups.cdnLockupPeriod}}}function aC(e){let t=F(e.chain);return{abi:t.contracts.fwssView.abi,address:e.contractAddress??t.contracts.fwssView.address,functionName:"getPriceList",args:[]}}async function n_(e,t){let n=await O(e,sC({chain:e.chain,token:t.token,address:t.address,operator:t.operator,contractAddress:t.contractAddress}));return cC(n)}function sC(e){let t=F(e.chain),n=e.token??t.contracts.usdfc.address,i=e.operator??t.contracts.fwss.address;return{abi:t.contracts.filecoinPay.abi,address:e.contractAddress??t.contracts.filecoinPay.address,functionName:"operatorApprovals",args:[n,e.address,i]}}function cC(e){return{isApproved:e[0],rateAllowance:e[1],lockupAllowance:e[2],rateUsage:e[3],lockupUsage:e[4],maxLockupPeriod:e[5]}}async function i_(e,t){let n=t.requiredMaxLockupPeriod??(await Ol(e)).lockups.defaultLockupPeriod,i=await n_(e,{address:t.clientAddress});return i.isApproved&&i.rateAllowance===rt&&i.lockupAllowance>=rt/2n&&i.maxLockupPeriod>=n}function o_(e){let{funds:t,lockupCurrent:n,lockupRate:i,lockupLastSettledAt:r,currentEpoch:o}=e,a=i===0n?rt:r+(t-n)/i,s=a<o?a:o,c=n+i*(s-r),u=t-c,p=u>0n?u:0n,d=a===rt?rt:a>o?a-o:0n,l=i===0n?rt:t/i;return{availableFunds:p,runwayInEpochs:d,grossCoverageInEpochs:l}}function jo(e){return e*Be.BYTES_PER_LEAF*127n/128n}function uC(e){return(e*4n+126n)/127n}function Bs(e){if(e.length===0)throw new ue("pieceSizes must contain at least one piece");for(let t of e)if(t<=0n)throw new ue("pieceSizes must contain only positive byte sizes")}function Ul(e){return Bs(e),e.reduce((t,n)=>t+uC(n),0n)}function Mo(e){let{sizeInBytes:t,storagePerTibPerMonth:n,datasetFeePerMonth:i,epochsPerMonth:r}=e;if(t===0n)return{ratePerEpoch:0n,ratePerMonth:0n};let o=n*t/Be.TiB,a=n*t/(Be.TiB*r),s=o+i;return{ratePerEpoch:a+i/r,ratePerMonth:s}}function a_(e){let{pieceSizes:t,dataSetLeafCount:n,priceList:i,epochsPerMonth:r=xl.EPOCHS_PER_MONTH,lockupEpochs:o,isNewDataSet:a,withCDN:s}=e;if(n<0n)throw new ue("dataSetLeafCount cannot be negative");let c=a?0n:n,u=Ul(t),p=c+u,d=o??i.lockups.defaultLockupPeriod,l={storagePerTibPerMonth:i.rates.storagePerTibPerMonth,datasetFeePerMonth:i.rates.datasetFeePerMonth,epochsPerMonth:r},m;if(c>0n){let T=Mo({...l,sizeInBytes:jo(p)}),w=Mo({...l,sizeInBytes:jo(c)});m=T.ratePerEpoch-w.ratePerEpoch,m<0n&&(m=0n)}else m=Mo({...l,sizeInBytes:jo(p)}).ratePerEpoch;let f=m*d,y=a?i.lockups.lifecycleReserveTarget:0n,x=a&&s?i.lockups.cdnLockupAmount:0n,g=a&&s?i.lockups.cacheMissLockupAmount:0n;return{rateDeltaPerEpoch:m,streamingLockup:f,lifecycleLockup:y,cdnLockup:x,cacheMissLockup:g,total:f+y+x+g}}function s_(e){Bs(e.pieceSizes);let t=e.pendingOneTimePayments??0n;if(t<0n)throw new ue("pendingOneTimePayments cannot be negative");let n=e.priceList.lockups.lifecycleReserveTarget,i=e.priceList.lockups.replenishThreshold,r=e.isNewDataSet?n:0n,o;if(e.isNewDataSet)o=n;else{if(e.currentReserveBalance==null)throw new ue("currentReserveBalance is required for an existing data set");if(e.currentReserveBalance<0n)throw new ue("currentReserveBalance cannot be negative");o=e.currentReserveBalance}let a=t+(e.isNewDataSet?e.priceList.fees.createDataSetFee:0n),s=0n,c=e.priceList.fees.addPiecesBaseFee+e.priceList.fees.addPiecesPerPieceFee;for(let u=0;u<e.pieceSizes.length;u++){if(a+=c,o<a+i){let p=n+a;s+=p-o,o=p}o-=a,a=0n}return{initialLockup:r,replenishmentLockup:s,total:r+s,finalReserveBalance:o}}function c_(e){Bs(e.pieceSizes);let t=BigInt(e.pieceSizes.length),n=e.isNewDataSet?e.priceList.fees.createDataSetFee:0n,i=(e.priceList.fees.addPiecesBaseFee+e.priceList.fees.addPiecesPerPieceFee)*t;return{createDataSetFee:n,addPiecesFee:i,total:n+i}}function Bv(e){if(e.pdpEndEpoch!==0n)throw new Dl(e.pdpEndEpoch)}function u_(e){if(e.isNewDataSet)return null;if(e.dataSetLeafCount==null)throw new ue("dataSetLeafCount is required for an existing data set");if(e.currentLifecycleReserveBalance==null)throw new ue("currentLifecycleReserveBalance is required for an existing data set");if(e.pdpEndEpoch==null)throw new ue("pdpEndEpoch is required for an existing data set");let t={leafCount:e.dataSetLeafCount,lifecycleReserveBalance:e.currentLifecycleReserveBalance,pendingOneTimePayments:e.pendingOneTimePayments??0n,pdpEndEpoch:e.pdpEndEpoch};return Bv(t),t}function pC(e){return e.netRateAfterUpload*e.extraRunwayEpochs}function dC(e){let{rawDepositNeeded:t,netRateAfterUpload:n,runwayInEpochs:i,availableFunds:r,bufferEpochs:o}=e;if(t>0n)return n*o;if(i<=o){let a=n*o-r;return a>0n?a:0n}return 0n}function p_(e){if(e.contexts.length===0)throw new ue("contexts must contain at least one storage context");let t=e.epochsPerMonth??xl.EPOCHS_PER_MONTH,n=e.extraRunwayEpochs??$P,i=e.bufferEpochs??_P,r=0n,o=0n,a=0n,s=0n,c=0n,u=0n,p=0n,d=0n,l=0n,m=0n,f=0n;for(let P of e.contexts){P.dataSet!=null&&Bv(P.dataSet);let C=P.dataSet==null,_=P.dataSet?.leafCount??0n,U=Ul(P.pieceSizes),M=a_({pieceSizes:P.pieceSizes,dataSetLeafCount:_,priceList:e.priceList,epochsPerMonth:t,lockupEpochs:e.lockupEpochs,isNewDataSet:C,withCDN:P.withCDN}),fe=c_({priceList:e.priceList,isNewDataSet:C,pieceSizes:P.pieceSizes}),q=s_({priceList:e.priceList,isNewDataSet:C,pieceSizes:P.pieceSizes,currentReserveBalance:P.dataSet?.lifecycleReserveBalance,pendingOneTimePayments:P.dataSet?.pendingOneTimePayments}),ye=Mo({sizeInBytes:jo(_+U),storagePerTibPerMonth:e.priceList.rates.storagePerTibPerMonth,datasetFeePerMonth:e.priceList.rates.datasetFeePerMonth,epochsPerMonth:t});r+=M.rateDeltaPerEpoch,o+=M.total+q.replenishmentLockup,a+=M.lifecycleLockup,s+=q.replenishmentLockup,c+=M.streamingLockup,u+=M.cdnLockup,p+=M.cacheMissLockup,d+=ye.ratePerEpoch,l+=ye.ratePerMonth,m+=fe.createDataSetFee,f+=fe.addPiecesFee}let y=e.account.currentLockupRate+r,x=pC({netRateAfterUpload:y,extraRunwayEpochs:n}),g=o+x+e.account.debt-e.account.availableFunds,w=e.account.currentLockupRate===0n&&e.contexts.every(P=>P.dataSet==null)?0n:dC({rawDepositNeeded:g,netRateAfterUpload:y,runwayInEpochs:e.account.runwayInEpochs,availableFunds:e.account.availableFunds,bufferEpochs:i}),b=(g>0n?g:0n)+w,I=!e.account.fwssMaxApproved,$=m,S=f;return{rates:{perEpoch:d,perMonth:l},fees:{createDataSetFee:$,addPiecesFee:S,total:$+S},lockups:{rateDeltaPerEpoch:r,lifecycleLockup:a,reserveReplenishment:s,streamingLockup:c,cdnLockup:u,cacheMissLockup:p,total:o},depositNeeded:b,needsFwssMaxApproval:I,ready:b===0n&&!I}}async function d_(e,t){let n=t.isNewDataSet??!0,i=t.withCDN??!1,r=u_({isNewDataSet:n,dataSetLeafCount:t.dataSetLeafCount,currentLifecycleReserveBalance:t.currentLifecycleReserveBalance,pendingOneTimePayments:t.pendingOneTimePayments,pdpEndEpoch:t.pdpEndEpoch}),[o,a,s]=await Promise.all([r_(e,{address:t.clientAddress}),Ol(e),$e(e,{cacheTime:0})]),c=await i_(e,{clientAddress:t.clientAddress,requiredMaxLockupPeriod:a.lockups.defaultLockupPeriod}),u={funds:o.funds,lockupCurrent:o.lockupCurrent,lockupRate:o.lockupRate,lockupLastSettledAt:o.lockupLastSettledAt,currentEpoch:s},p=t_(u),{availableFunds:d,runwayInEpochs:l}=o_(u);return p_({contexts:[{pieceSizes:t.pieceSizes,withCDN:i,dataSet:r}],priceList:a,account:{currentLockupRate:o.lockupRate,debt:p,availableFunds:d,runwayInEpochs:l,fwssMaxApproved:c},extraRunwayEpochs:t.extraRunwayEpochs,bufferEpochs:t.bufferEpochs})}import{createReadStream as ZC}from"node:fs";import{Readable as HC}from"node:stream";var Zo=class extends le{name="AtLeastOnePieceRequiredError";constructor(){super("At least one piece must be provided")}static is(t){return he(t)&&t.name==="AtLeastOnePieceRequiredError"}};function Ll(e){return e.some(t=>t.length>0)?e:[]}var l_=globalThis.crypto;function lC(){let e=0n;for(let t=0;t<32;t++)e<<=8n,e|=BigInt(mC(256));return e}function br(){if(l_?.getRandomValues==null)return lC();{let e=new BigUint64Array(4);l_.getRandomValues(e);let t=0n;return e.forEach(n=>{t<<=64n,t|=n}),t}}function mC(e){return Math.floor(Math.random()*e)}var Fv=[{type:"uint256"},{type:"string[][]"},{type:"string[][]"},{type:"bytes"}];async function Ho(e,t){let n=F(e.chain),{clientDataSetId:i,nonce:r,pieces:o,verifyingContract:a}=t,s=r??br(),c=Ll(Array.from(o,m=>m.metadata??[])),u=await xn(e,{account:e.account,domain:So({chain:n,verifyingContract:a}),types:St,primaryType:"AddPieces",message:{clientDataSetId:i,nonce:s,pieceData:o.map(m=>({data:re(m.pieceCid.bytes)})),pieceMetadata:c.map((m,f)=>({pieceIndex:BigInt(f),metadata:m}))}}),p=c.map(m=>m.map(f=>f.key)),d=c.map(m=>m.map(f=>f.value));return ze(Fv,[s,p,d,u])}function Vo(e){if(e?.aborted)throw new As(e)}var jv=[{type:"address"},{type:"uint256"},{type:"string[]"},{type:"string[]"},{type:"bytes"}];async function m_(e,t){let n=F(e.chain),i=t.metadata??[],r=t.clientDataSetId??br(),o=await xn(e,{account:e.account,domain:So({chain:n}),types:St,primaryType:"CreateDataSet",message:{clientDataSetId:r,payee:t.payee,metadata:i}}),a=i.map(p=>p.key),s=i.map(p=>p.value),c=t.payer??e.account.address;return ze(jv,[c,r,a,s,o])}var Mv=[{type:"bytes"},{type:"bytes"}];async function Bl(e,t){let n=t.clientDataSetId??br(),i=await m_(e,{...t,clientDataSetId:n}),r=await Ho(e,{...t,clientDataSetId:n});return ze(Mv,[i,r])}var f_=`0x${"00".repeat(65)}`;function fC(e){if(e.kind!=="addPieces")return!1;let t=e.dataSetId??e.dataSet?.dataSetId;return t!=null&&e.legacyPieceStorageIdLimit!=null&&t<e.legacyPieceStorageIdLimit}function yC(e){return e.pieces.length<1||fC(e)&&e.pieces.length>Be.MAX_LEGACY_ADD_PIECES_BATCH_SIZE?!1:hC(e)<=Be.MAX_ADD_PIECES_MESSAGE_SIZE}function gC(e){let t=e.size;if(t<Be.MIN_UPLOAD_SIZE||t>Be.MAX_UPLOAD_SIZE)throw new Mn(t)}function Fl(e){if(e.pieces.length<1)throw new Zo;for(let t of e.pieces)gC(t.pieceCid);if(!yC(e))throw new kl(e.pieces.length)}function hC(e){let t=xC(e),n=e.pieces.map(r=>({data:re(r.pieceCid.bytes)})),i=se({abi:bt,functionName:"addPieces",args:[0n,Nr,n,t]});return ve(i)}function xC(e){let t=bC(e.pieces);if(e.kind==="addPieces")return t;let n=No(e.metadata,{cdn:e.cdn??!1}),i=ze(jv,[Nr,0n,n.map(r=>r.key),n.map(r=>r.value),f_]);return ze(Mv,[i,t])}function bC(e){let t=Ll(e.map(r=>Wr(r.metadata))),n=t.map(r=>r.map(o=>o.key)),i=t.map(r=>r.map(o=>o.value));return ze(Fv,[0n,n,i,f_])}async function vC(e){let{serviceURL:t,dataSetId:n,pieces:i,extraData:r}=e,o=await L.post(new URL(`pdp/data-sets/${n}/pieces`,t),{json:{pieces:i.map(c=>({pieceCid:c.toString(),subPieces:[{subPieceCid:c.toString()}]})),extraData:r},signal:e.signal,timeout:ee.TIMEOUT,retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY,shouldRetry:c=>ne.is(c.error)&&c.error.code===429}});if(o.error)throw ne.is(o.error)?new El(await o.error.response.text()):o.error;let a=o.result.headers.get("Location"),s=a?.split("/").pop();if(!a||!s||!xe(s))throw new xr(a);return{txHash:s,statusUrl:new URL(a,t).toString()}}async function y_(e,t){Vo(t.signal),Fl({kind:"addPieces",dataSetId:t.dataSetId,legacyPieceStorageIdLimit:F(e.chain).legacyPieceStorageIdLimit,pieces:t.pieces});let n=t.extraData??await Ho(e,{clientDataSetId:t.clientDataSetId,nonce:t.nonce,pieces:t.pieces.map(i=>({pieceCid:i.pieceCid,metadata:Wr(i.metadata)}))});return vC({serviceURL:t.serviceURL,dataSetId:t.dataSetId,pieces:t.pieces.map(i=>i.pieceCid),extraData:n,retryCount:t.retryCount,retryDelay:t.retryDelay,signal:t.signal})}var zce=Ft({txHash:ie,txStatus:Ie("pending"),dataSetId:Bn,pieceCount:En(),addMessageOk:qr(),piecesAdded:Ie(!1),confirmedTxHash:ie.optional()}),TC=Ft({txHash:ie,txStatus:Ie("rejected"),dataSetId:Bn,pieceCount:En(),addMessageOk:qr(),piecesAdded:Ie(!1),confirmedTxHash:ie.optional()}),wC=Ft({txHash:ie,txStatus:Ie("confirmed"),dataSetId:Bn,pieceCount:En(),addMessageOk:Ie(!0),piecesAdded:Ie(!0),confirmedPieceIds:An(Bn),confirmedTxHash:ie.optional()}),IC=go("txStatus",[TC,wC]);async function jl(e){let t=await L.json.get(e.statusUrl,{retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},poll:{limit:ee.POLL_LIMIT,interval:e.pollInterval??ee.POLL_INTERVAL,statusCodes:[202,200],shouldPoll:async n=>(await n.response.clone().json()).piecesAdded===!1},signal:e.signal,timeout:e.timeout??ee.TIMEOUT,schema:IC});if(t.error)throw ne.is(t.error)?new Al(await t.error.response.text()):t.error;if(t.result.txStatus==="rejected")throw new Lo(t.result);return t.result}var Uce=Ft({createMessageHash:ie,dataSetCreated:Ie(!1),service:mr(),txStatus:yo([Ie("pending"),Ie("confirmed")]),ok:qr(),confirmedTxHash:ie.optional()}),SC=Ft({createMessageHash:ie,dataSetCreated:Ie(!1),service:mr(),txStatus:Ie("rejected"),ok:Ie(!1),confirmedTxHash:ie.optional()}),PC=Ft({createMessageHash:ie,dataSetCreated:Ie(!0),service:mr(),txStatus:Ie("confirmed"),ok:Ie(!0),dataSetId:Bn,confirmedTxHash:ie.optional()}),_C=go("txStatus",[SC,PC]);async function g_(e){let t=await L.json.get(e.statusUrl,{retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},poll:{limit:ee.POLL_LIMIT,interval:e.pollInterval??ee.POLL_INTERVAL,statusCodes:[202,200],shouldPoll:async n=>(await n.response.clone().json()).dataSetCreated===!1},signal:e.signal,timeout:e.timeout??ee.TIMEOUT,schema:_C});if(t.error)throw ne.is(t.error)?new $l(await t.error.response.text()):t.error;if(t.result.txStatus==="rejected")throw new Uo(t.result);return t.result}async function $C(e){let t=await L.post(new URL("pdp/data-sets/create-and-add",e.serviceURL),{json:{recordKeeper:e.recordKeeper,extraData:e.extraData,pieces:e.pieces.map(r=>({pieceCid:r.toString(),subPieces:[{subPieceCid:r.toString()}]}))},signal:e.signal,timeout:ee.TIMEOUT,retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY,shouldRetry:r=>ne.is(r.error)&&r.error.code===429}});if(t.error)throw ne.is(t.error)?new _l(await t.error.response.text()):t.error;let n=t.result.headers.get("Location"),i=n?.split("/").pop();if(!n||!i||!xe(i))throw new xr(n);return{txHash:i,statusUrl:new URL(n,e.serviceURL).toString()}}async function h_(e,t){Vo(t.signal),Fl({kind:"createDataSetAndAddPieces",metadata:t.metadata,cdn:t.cdn,pieces:t.pieces});let n=F(e.chain),i=t.extraData??await Bl(e,{clientDataSetId:t.clientDataSetId,payee:t.payee,payer:t.payer,metadata:No(t.metadata,{cdn:t.cdn??!1}),pieces:t.pieces.map(r=>({pieceCid:r.pieceCid,metadata:Wr(r.metadata)}))});return $C({serviceURL:t.serviceURL,recordKeeper:t.recordKeeper??n.contracts.fwss.address,extraData:i,pieces:t.pieces.map(r=>r.pieceCid),retryCount:t.retryCount,retryDelay:t.retryDelay,signal:t.signal})}async function x_(e){let t=new URL(e.statusUrl).origin,n=await g_({statusUrl:e.statusUrl,timeout:e.timeout,signal:e.signal,retryCount:e.retryCount,retryDelay:e.retryDelay,pollInterval:e.pollInterval}),i=await jl({statusUrl:new URL(`/pdp/data-sets/${n.dataSetId}/pieces/added/${n.createMessageHash}`,t).toString(),timeout:e.timeout,signal:e.signal,retryCount:e.retryCount,retryDelay:e.retryDelay,pollInterval:e.pollInterval});return{hash:n.createMessageHash,confirmedTxHash:n.confirmedTxHash??i.confirmedTxHash,dataSetId:n.dataSetId,piecesIds:i.confirmedPieceIds}}async function b_(e,t){let n=await O(e,kC({chain:e.chain,dataSetId:t.dataSetId,contractAddress:t.contractAddress}));return EC(n)}function EC(e){return e.pdpRailId===0n?null:e}function kC(e){let t=F(e.chain);return{abi:t.contracts.fwssView.abi,address:e.contractAddress??t.contracts.fwssView.address,functionName:"getDataSet",args:[e.dataSetId]}}async function v_(e,t){let n=await b_(e,t);if(!n)return null;let i=await AC(e,{dataSetInfo:n,providerId:n.providerId});return{...n,...i}}async function AC(e,t){let n=F(e.chain),[i,r,o,a,s]=await Nt(e,{allowFailure:!1,contracts:[fl({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId}),hl({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId}),bl({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId}),Rs({chain:e.chain,providerId:t.providerId}),Ds({chain:e.chain,dataSetId:t.dataSetInfo.dataSetId})]}),c=Co(a)?Fn(a):null,u=vl(o);return{live:i,managed:_e(r,n.contracts.fwss.address),cdn:t.dataSetInfo.cdnRailId>0n&&"withCDN"in u,metadata:u,provider:c,hasActivePieces:s>0n}}async function Zv(e){let{pieceCid:t,serviceURL:n}=e,i=new URLSearchParams({pieceCid:t.toString()}),r=e.retryCount??(e.poll?ee.POLL_LIMIT:void 0),o=e.retryDelay??(e.poll?e.pollInterval??1e3:ee.RETRY_DELAY),a=await L.json.get(new URL(`pdp/piece?${i.toString()}`,n),{signal:e.signal,timeout:e.timeout??ee.TIMEOUT,retry:{retries:r,factor:e.poll?1:void 0,minTimeout:o,shouldRetry:c=>ne.is(c.error)&&c.error.code===404},poll:e.poll?{limit:ee.POLL_LIMIT,interval:e.pollInterval??1e3,statusCodes:[202]}:!1});if(a.error)throw ne.is(a.error)?new Us(await a.error.response.text()):ks.is(a.error)?new Us("Timeout waiting for piece to be found"):a.error;let s=a.result;return ft(s.pieceCid)}async function T_(e){let t=await L.post(new URL("pdp/piece/uploads",e.serviceURL),{timeout:ee.TIMEOUT,retry:{methods:["post"],retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},signal:e.signal});if(t.error)throw ne.is(t.error)?new jn(`Failed to create upload session: ${await t.error.response.text()}`):t.error;if(t.result.status!==201)throw new jn(`Expected 201 Created, got ${t.result.status}`);let n=t.result.headers.get("Location");if(!n)throw new xr("Upload session created but Location header missing");let i=n.match(/\/pdp\/piece\/uploads\/([a-fA-F0-9-]+)/);if(!i)throw new xr(`Invalid Location header format: ${n}`);let r=i[1],o=Promise.resolve(e.pieceCid),a=null;if(e.pieceCid==null){let{transform:T,result:w}=$v();a=T,o=w}let s=wl(e.data)?new Blob([e.data]).stream():e.data,c=wl(e.data)?e.data.length:e.size,u=0,p=new TransformStream({transform(T,w){let b;if(wl(T))b=T;else if(ArrayBuffer.isView(T))b=new Uint8Array(T.buffer,T.byteOffset,T.byteLength);else{w.error("Invalid chunk type only Uint8Array and TypedArray are supported");return}if(u+=b.length,u>Be.MAX_UPLOAD_SIZE){w.error(new Mn(u));return}e.onProgress&&e.onProgress(u),w.enqueue(b)},flush(T){if(u<Be.MIN_UPLOAD_SIZE){T.error(new Mn(u));return}}}),d=a?s.pipeThrough(p).pipeThrough(a):s.pipeThrough(p),l,m={},f={"Content-Type":"application/octet-stream"};if(UP())l=d,m={duplex:"half"};else{let T=[],w=0,b=d.getReader();for(;;){let{done:I,value:$}=await b.read();if(I)break;T.push($),w+=$.length}l=new Blob(T),f["Content-Length"]=(c??w).toString()}let y=await L.put(new URL(`pdp/piece/uploads/${r}`,e.serviceURL),{body:l,headers:f,timeout:!1,signal:e.signal,...m});if(y.error)throw ne.is(y.error)?new Os(`Failed to upload piece: ${await y.error.response.text()}`):y.error;if(y.result.status!==204)throw new Os(`Expected 204 No Content, got ${y.result.status}`);let x=await o,g=await L.post(new URL(`pdp/piece/uploads/${r}`,e.serviceURL),{json:{pieceCid:x.toString()},timeout:ee.TIMEOUT,retry:{methods:["post"],retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY},signal:e.signal});if(g.error)throw ne.is(g.error)?new jn(`Failed to finalize upload: ${await g.error.response.text()}`):g.error;if(g.result.status!==200)throw new jn(`Expected 200 OK for finalization, got ${g.result.status}`);return{pieceCid:x,size:u}}var zC=8e3,DC=2,CC=500;async function w_(e,t={}){let n=await L.get(new URL("pdp/ping",e),{retry:{retries:DC,minTimeout:CC},signal:t.signal,timeout:t.timeout??zC});if(n.error)throw n.error;return n.result}async function I_(e,t){let n=F(e.chain),i=await xn(e,{account:e.account,domain:So({chain:n}),types:St,primaryType:"SchedulePieceRemovals",message:{clientDataSetId:t.clientDataSetId,pieceIds:t.pieceIds}});return ze([{type:"bytes"}],[i])}var S_=(1n<<63n)-1n;async function RC(e){let{serviceURL:t,dataSetId:n,extraData:i}=e,r=P_(e.pieceIds),o=`{"extraData":${JSON.stringify(i)},"pieceIds":[${r.join(",")}]}`,a=await L.delete(new URL(`pdp/data-sets/${n}/pieces/${r[0]}`,t),{body:o,headers:{"content-type":"application/json"},signal:e.signal,timeout:ee.TIMEOUT,retry:{retries:e.retryCount,minTimeout:e.retryDelay??ee.RETRY_DELAY}});if(a.error)throw ne.is(a.error)?new zl(await a.error.response.text()):a.error;return{hash:(await a.result.json()).txHash}}function NC(e){if(!Number.isInteger(e)||e<1)throw new Zo}function P_(e){let t=[...new Set(e)];NC(t.length);for(let n of t)if(n<0n||n>S_)throw new RangeError(`Piece ID ${n} is outside Curio's supported range of 0 to ${S_}`);return t}async function __(e,t){Vo(t.signal);let n=P_(t.pieceIds);return RC({serviceURL:t.serviceURL,dataSetId:t.dataSetId,pieceIds:n,extraData:await I_(e,{clientDataSetId:t.clientDataSetId,pieceIds:n}),retryCount:t.retryCount,retryDelay:t.retryDelay,signal:t.signal})}async function $_(e,t={}){let{cursor:n,limit:i}=Do(t,100n),r=await O(e,OC({chain:e.chain,offset:n,limit:i+1n,contractAddress:t.contractAddress}));return ml(r,i,()=>n+i)}function OC(e){let t=F(e.chain);return{abi:t.contracts.fwssView.abi,address:e.contractAddress??t.contracts.fwssView.address,functionName:"getApprovedProviders",args:[e.offset,e.limit]}}async function UC(e,t={}){let{cursor:n,limit:i}=Do(t,50n),r=await O(e,LC({chain:e.chain,onlyActive:t.onlyActive,offset:n,limit:i,contractAddress:t.contractAddress}));return BC(r,n)}function LC(e){let t=F(e.chain);return{abi:t.contracts.serviceProviderRegistry.abi,address:e.contractAddress??t.contracts.serviceProviderRegistry.address,functionName:"getProvidersByProductType",args:[Cs.PDP,e.onlyActive??!0,e.offset,e.limit]}}function BC(e,t=0n){return{items:e.providers.map(Fn),...e.hasMore?{nextCursor:t+BigInt(e.providers.length)}:{}}}async function E_(e,t={}){let[n,i]=await Promise.all([Array.fromAsync(Ln(({cursor:r})=>UC(e,{onlyActive:!0,cursor:r,contractAddress:t.contractAddress}))),Array.fromAsync(Ln(({cursor:r})=>$_(e,{cursor:r})))]);return n.filter(r=>i.includes(r.id))}async function k_(e,t={}){let n=await O(e,FC({chain:e.chain,contractAddress:t.contractAddress}));return jC(n)}function FC(e){let t=F(e.chain);return{abi:t.contracts.endorsements.abi,address:e.contractAddress??t.contracts.endorsements.address,functionName:"getProviderIds",args:[]}}function jC(e){return Array.from(new Set(e))}async function A_(e,t){let[n,i,r]=await Promise.all([E_(e),k_(e),Array.fromAsync(Ln(({cursor:o})=>Tl(e,{address:t.address,cursor:o})))]);return{providers:n,endorsedIds:i,clientDataSets:r,legacyPieceStorageIdLimit:F(e.chain).legacyPieceStorageIdLimit}}function MC(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;if(i.length===0)return!0;for(let r of i)if(e[r]!==t[r])return!1;return!0}function Ml(e,t,n=0n){return e.filter(r=>r.live&&r.managed&&r.pdpEndEpoch===0n&&MC(r.metadata,t)).sort((r,o)=>{let a=r.dataSetId>=n,s=o.dataSetId>=n;return a!==s?a?-1:1:r.hasActivePieces&&!o.hasActivePieces?-1:o.hasActivePieces&&!r.hasActivePieces?1:r.dataSetId<o.dataSetId?-1:r.dataSetId>o.dataSetId?1:0})}function z_(e){let t=e.count??1,n=e.excludeProviderIds??[],i=e.metadata??{},r=e.endorsedIds.length>0,o=e.providers.filter(d=>!n.includes(d.id)&&(!r||e.endorsedIds.includes(d.id)));if(o.length===0)return[];let a=new Map(o.map(d=>[d.id,d])),s=e.clientDataSets.filter(d=>a.has(d.providerId)),c=Ml(s,i,e.legacyPieceStorageIdLimit),u=[],p=[];for(let d=0;d<t;d++){let l=!1;for(let m of c){if(p.includes(m.providerId))continue;let f=a.get(m.providerId);if(f!=null){u.push({provider:f,dataSetId:m.dataSetId,endorsed:e.endorsedIds.includes(m.providerId),dataSetMetadata:m.metadata}),p.push(m.providerId),l=!0;break}}if(!l){for(let m of o)if(!p.includes(m.id)){u.push({provider:m,dataSetId:null,endorsed:e.endorsedIds.includes(m.id),dataSetMetadata:i}),p.push(m.id),l=!0;break}}if(!l)break}return u}var VC=(1n<<128n)-1n;function C_(e,t){let n=e.client,i=t.client,r=t.rootAddress,o=e.signal,a=new Map;function s(d){let l=a.get(d);return l||(l=v_(n,{dataSetId:d}),l.catch(()=>a.delete(d)),a.set(d,l)),l}async function c(d){try{return await w_(d,{signal:o}),!0}catch(l){if(o?.aborted)throw l;return!1}}return{async selectPlacement({metadata:d,providerId:l}){let[m,f]=await Promise.all([A_(n,{address:r}),l==null?void 0:zP(n,{providerId:l})]);if(l!=null){if(!f)throw Jt(`Provider ${l} has no active PDP offering.`);let x=Ml(m.clientDataSets.filter(g=>g.providerId===l),d,m.legacyPieceStorageIdLimit);return u({providerId:l,serviceURL:f.pdp.serviceURL,payee:f.payee,dataSetId:x[0]?.dataSetId})}let y=[];for(;;){let[x]=z_({...m,count:1,metadata:d,excludeProviderIds:y});if(!x)throw new Kt({code:"service_unavailable",message:"No reachable storage provider is available."});let g=x.provider;if(await c(g.pdp.serviceURL))return u({providerId:g.id,serviceURL:g.pdp.serviceURL,payee:g.payee,dataSetId:x.dataSetId??void 0});y.push(g.id)}},async quote({size:d,placement:l}){let m=l.dataSetId==null?void 0:await p(l.dataSetId),f=await d_(n,{clientAddress:r,pieceSizes:[BigInt(d)],isNewDataSet:m==null,...m});return{ready:f.ready,depositNeeded:f.depositNeeded,needsApproval:f.needsFwssMaxApproval,ratePerMonth:f.rates.perMonth,lockup:f.lockups.total,fundingUrl:QP({consoleUrl:e.consoleUrl,network:e.network,deposit:f.depositNeeded})}},async hasPiece({serviceURL:d,pieceCid:l}){try{return await Zv({serviceURL:d,pieceCid:ft(l),signal:o}),!0}catch(m){if(o?.aborted)throw m;return!1}},async upload({serviceURL:d,path:l,size:m,pieceCid:f}){let y=ft(f);await T_({serviceURL:d,data:HC.toWeb(ZC(l)),size:m,pieceCid:y,signal:o}),await Zv({serviceURL:d,pieceCid:y,poll:!0,signal:o})},async signCommit({placement:d,pieceCid:l,metadata:m,pieceMetadata:f}){let y=br(),x=[{pieceCid:ft(l),metadata:Wr(f)}];if(d.dataSetId==null){let T=br(),w=await Bl(i,{clientDataSetId:T,nonce:y,payee:d.payee,payer:r,metadata:No(m,{cdn:!1}),pieces:x});return{created:!0,nonce:y.toString(),clientDataSetId:T.toString(),extraData:w}}if(d.clientDataSetId==null)throw new Error("Adding to a data set requires its client data set ID.");let g=await Ho(i,{clientDataSetId:d.clientDataSetId,nonce:y,pieces:x});return{created:!1,nonce:y.toString(),extraData:g}},async submitCommit({placement:d,pieceCid:l,commit:m,pieceMetadata:f}){let y=[{pieceCid:ft(l),metadata:f}];if(m.created){let g=await h_(i,{serviceURL:d.serviceURL,payee:d.payee,payer:r,pieces:y,extraData:m.extraData,signal:o});return{transactionHash:g.txHash,statusUrl:g.statusUrl}}if(d.dataSetId==null||d.clientDataSetId==null)throw new Error("Adding to a data set requires its IDs.");let x=await y_(i,{serviceURL:d.serviceURL,dataSetId:d.dataSetId,clientDataSetId:d.clientDataSetId,pieces:y,extraData:m.extraData,signal:o});return{transactionHash:x.txHash,statusUrl:x.statusUrl}},async findCommit({nonce:d}){let l=await O(n,{address:n.chain.contracts.fwssView.address,abi:n.chain.contracts.fwssView.abi,functionName:"clientNonces",args:[r,d]});if(l!==0n)return{dataSetId:l&VC,pieceId:(l>>128n)-1n}},async waitForCommit({statusUrl:d,created:l}){try{if(l){let f=await x_({statusUrl:d,signal:o});return{dataSetId:f.dataSetId,pieceId:D_(f.piecesIds)}}let m=await jl({statusUrl:d,signal:o});return{dataSetId:m.dataSetId,pieceId:D_(m.confirmedPieceIds)}}catch(m){throw Lo.is(m)||Uo.is(m)?new Kt({code:Tr.commitRejected,message:"The provider reported the commit transaction as failed.",cause:m}):m}},async schedulePieceRemoval({serviceURL:d,dataSetId:l,pieceId:m}){let f=await s(l);if(!f)throw Jt(`Data set ${l} not found.`);return{transactionHash:(await __(i,{serviceURL:d,dataSetId:l,clientDataSetId:f.clientDataSetId,pieceIds:[m],signal:o})).hash}},async waitForTransaction(d){return{status:(await Hs(Ea(n,{hash:d}),o)).status}}};async function u(d){if(d.dataSetId==null)return d;let l=await s(d.dataSetId);return l?{...d,clientDataSetId:l.clientDataSetId}:{...d,dataSetId:void 0}}async function p(d){let[l,m]=await Promise.all([s(d),IP(n,{dataSetId:d})]);if(l)return{dataSetLeafCount:m,currentLifecycleReserveBalance:l.lifecycleReserveBalance,pendingOneTimePayments:l.pendingOneTimePayments,pdpEndEpoch:l.pdpEndEpoch}}}function D_(e){let[t]=e;if(t==null)throw new Error("Provider confirmed no piece IDs.");return t}import{join as xR}from"node:path";var GC=Uu([it(jt.rpcUrls.default.http[0]),it(jt.rpcUrls.ankr.http[0]),it(jt.rpcUrls.drpc.http[0])],{rank:!1}),qC=Uu([it(Mt.rpcUrls.default.http[0]),it(Mt.rpcUrls.ankr.http[0]),it(Mt.rpcUrls.drpc.http[0])],{rank:!1}),KC=it(xo.rpcUrls.default.http[0]);function R_(e){if(e.id===jt.id)return GC;if(e.id===Mt.id)return qC;if(e.id===xo.id)return KC;throw new ho(e.id)}import Hn from"node:fs";import ql from"node:path";import Kl from"node:process";import{isDeepStrictEqual as q_}from"node:util";function N_(e){if(e.path?.length){let t="";for(let n of e.path){let i=typeof n=="object"?n.key:n;if(typeof i=="string"||typeof i=="number")t?t+=`.${i}`:t+=i;else return null}return t}return null}var O_=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}};var Zn=e=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")},Zl=new Set(["__proto__","prototype","constructor"]),WC=Math.max(...[...Zl].map(e=>e.length)),U_=1e6,JC=e=>e>="0"&&e<="9";function L_(e){if(e==="0")return!0;if(/^[1-9]\d*$/.test(e)){let t=Number.parseInt(e,10);return t<=Number.MAX_SAFE_INTEGER&&t<=U_}return!1}function Hv(e,t){return Zl.has(e)?!1:(e&&L_(e)?t.push(Number.parseInt(e,10)):t.push(e),!0)}function XC(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);let t=[],n="",i="",r=!1,o="start",a=!1,s=0;for(let c of e){if(s++,a){n+=c,a=!1;continue}if(c==="\\"){if(o==="index")throw new Error(`Invalid character '${c}' in an index at position ${s}`);if(o==="indexEnd")throw new Error(`Invalid character '${c}' after an index at position ${s}`);a=!0,o=o==="start"?"property":o;continue}switch(c){case".":{if(o==="index")throw new Error(`Invalid character '${c}' in an index at position ${s}`);if(o==="indexEnd"){o="property";break}if(!Hv(n,t))return[];n="",o="property";break}case"[":{if(o==="index")throw new Error(`Invalid character '${c}' in an index at position ${s}`);if(o==="indexEnd"){o="index";break}if(o==="property"&&n.length<=WC&&Zl.has(n))return[];r=o==="property",o="index";break}case"]":{if(o==="indexEnd")throw new Error(`Invalid character '${c}' after an index at position ${s}`);if(o!=="index"){o==="start"&&(o="property"),n+=c;break}if(i===""){n+="[]",o="property";break}if((n!==""||r)&&!Hv(n,t))return[];n="",r=!1;let u=Number.parseInt(i,10),p=u<=U_&&i===String(u);t.push(p?u:i),i="",o="indexEnd";break}default:{if(o==="index"){if(!JC(c))throw new Error(`Invalid character '${c}' in an index at position ${s}`);i+=c;break}if(o==="indexEnd")throw new Error(`Invalid character '${c}' after an index at position ${s}`);o==="start"&&(o="property"),n+=c}}}switch(a&&(n+="\\"),o){case"property":{if(!Hv(n,t))return[];break}case"index":throw new Error("Index was not closed");case"start":{t.push("");break}}return t}function Hl(e){if(typeof e=="string")return XC(e);if(Array.isArray(e)){let t=[];for(let[n,i]of e.entries()){if(typeof i!="string"&&typeof i!="number")throw new TypeError(`Expected a string or number for path segment at index ${n}, got ${typeof i}`);if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`Path segment at index ${n} must be a finite number, got ${i}`);if(Zl.has(i))return[];typeof i=="string"&&L_(i)?t.push(Number.parseInt(i,10)):t.push(i)}return t}return[]}function B_(e,t,n){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return n===void 0?e:n;let i=Hl(t);if(i.length===0)return n;for(let r=0;r<i.length;r++){let o=i[r];if(e=e[o],e==null){if(r!==i.length-1)return n;break}}return e===void 0?n:e}function F_(e,t,n){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return e;let i=e,r=Hl(t);if(r.length===0)return e;for(let o=0;o<r.length;o++){let a=r[o];if(o===r.length-1){e[a]=n;continue}let s=e[a];if(Zn(s)){e=s;continue}let u=typeof r[o+1]=="number";e[a]=u?[]:{},e=e[a]}return i}function Vv(e,t){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return!1;let n=Hl(t);if(n.length===0)return!1;for(let i=0;i<n.length;i++){let r=n[i];if(i===n.length-1)return Object.hasOwn(e,r)?(delete e[r],!0):!1;let o=e[r];if(!Zn(o))return!1;e=o}}function j_(e,t){if(!Zn(e)||typeof t!="string"&&!Array.isArray(t))return!1;let n=Hl(t);if(n.length===0)return!1;for(let i of n){if(!Zn(e)||!(i in e))return!1;e=e[i]}return!0}var Go=e=>e instanceof URL?{$url:e.toString()}:e instanceof Map?{$map:[...e.entries()].map(([t,n])=>[Go(t),Go(n)])}:e instanceof Uint8Array?{$bytes:[...e.values()]}:e instanceof ArrayBuffer?{$bytes:[...new Uint8Array(e).values()]}:e?.type==="Buffer"&&Array.isArray(e.data)?{$bytes:e.data}:typeof e=="bigint"?{$bigint:e.toString()}:e instanceof Set?{$set:[...e.values()].map(t=>Go(t))}:e instanceof RegExp?{$regex:[e.source,e.flags]}:Array.isArray(e)?e.map(t=>Go(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Go(n)])):e,YC=(e,t)=>t instanceof URL?{$url:t.toString()}:t instanceof Map?{$map:[...t.entries()]}:t instanceof Uint8Array?{$bytes:[...t.values()]}:t instanceof ArrayBuffer?{$bytes:[...new Uint8Array(t).values()]}:t?.type==="Buffer"&&Array.isArray(t.data)?{$bytes:t.data}:typeof t=="bigint"?{$bigint:t.toString()}:t instanceof Set?{$set:[...t.values()]}:t instanceof RegExp?{$regex:[t.source,t.flags]}:t,QC=(e,t)=>t&&(t.$url?new URL(t.$url):t.$map?new Map(t.$map):t.$bytes?new Uint8Array(t.$bytes):t.$bigint?BigInt(t.$bigint):t.$set?new Set(t.$set):t.$regex?new RegExp(t.$regex[0],t.$regex[1]):t),M_=(e,t)=>JSON.stringify(Go(e),YC,t),Z_=e=>JSON.parse(e,QC);import{randomBytes as eR}from"node:crypto";import et from"node:fs";import js from"node:path";import vr from"node:process";var tR=new Set(["EAGAIN","EBUSY","EMFILE","ENFILE"]),rR=new Set(["EACCES","EPERM"]),nR=1e3,iR=200,oR=6e4,H_=new Set,Gl=e=>e?.code??"",Vl=e=>{let t=Date.now()+nR;for(let n=10;;n=Math.min(n*2,100))try{return e()}catch(i){let r=Gl(i);if(!(tR.has(r)||vr.platform==="win32"&&rR.has(r))||Date.now()+n>t)throw i;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,n)}},Fs=e=>{try{e()}catch{}},aR=e=>{let t=Gl(e),n=vr.geteuid?.()===0;return t==="ENOSYS"||!n&&(t==="EINVAL"||t==="EPERM")},sR=(e,t)=>{let n=0;for(;n<t.length;)n+=et.writeSync(e,t,n,t.length-n,n)},V_=e=>{let t=[...js.basename(e)];for(;Buffer.byteLength(t.join(""))>iR;)t.pop();return`${t.join("")}.`},cR=e=>{try{return vr.kill(e,0),!0}catch(t){return Gl(t)==="EPERM"}},uR=e=>{if(H_.has(e))return;H_.add(e);let t=js.dirname(e),n=V_(e),i=[];Fs(()=>{i=et.readdirSync(t)});for(let r of i){if(!r.startsWith(n))continue;let o=/^(\d+)\.[0-9a-f]{8}\.tmp$/.exec(r.slice(n.length));if(!o)continue;let a=Number(o[1]);if(a===vr.pid||cR(a))continue;let s=js.join(t,r);Fs(()=>{Date.now()-et.statSync(s).mtimeMs>oR&&et.rmSync(s,{force:!0})})}},G_=(e,t,n)=>{let i=e,r;try{i=et.realpathSync(e),r=et.statSync(i)}catch(c){if(Gl(c)!=="ENOENT")throw c}let o=n??(r?r.mode&4095:438),a=js.join(js.dirname(i),`${V_(i)}${vr.pid}.${eR(4).toString("hex")}.tmp`),s;try{s=Vl(()=>et.openSync(a,"wx",o));let c=s,u=Buffer.from(t);Vl(()=>sR(c,u));try{et.fchmodSync(c,o)}catch(p){if(!aR(p))throw p}r&&vr.geteuid&&vr.getegid&&(r.uid!==vr.geteuid()||r.gid!==vr.getegid())&&Fs(()=>et.fchownSync(c,r.uid,r.gid)),Vl(()=>et.fsyncSync(c)),s=void 0,et.closeSync(c),Vl(()=>et.renameSync(a,i))}catch(c){let u=s;throw u!==void 0&&Fs(()=>et.closeSync(u)),Fs(()=>et.rmSync(a,{force:!0})),c}uR(i)};var Xr=()=>Object.create(null),pR=/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~]+/,dR=/[A-ZÀ-Ý\u00C0-\u00D6\u00D9-\u00DD][a-zà-ÿ]/g,lR=/[A-ZÀ-Ý\u00C0-\u00D6\u00D9-\u00DD]+/g,mR=e=>(e=e.replace(dR,t=>` ${t[0].toLowerCase()||t[0]}${t[1]}`),e=e.replace(lR,t=>` ${t.toLowerCase()}`),e.trim().split(pR).join("-").replace(/^-/,"").replace(/-\s*$/,"")),fR=e=>e===null?"null":Array.isArray(e)?"array":typeof e,K_=(e,t)=>{let n=new Set(["undefined","symbol","function"]),i=typeof t;if(n.has(i))throw new TypeError(`Setting a value of type \`${i}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},yR=(e,t)=>{let n=e["~standard"].validate(t);if(n instanceof Promise)throw new TypeError("Async schemas are not supported. The schema `validate` function must return synchronously.");if(n.issues){let i=n.issues.map(o=>{let a=N_(o);return a?`\`${a}\` ${o.message}`:o.message}).join("; "),r=new O_(n.issues);throw r.message=`Config schema violation: ${i}`,r}return n.value},Wl=class{path;events;#e;#t;#r;#n;#p;#i;#y=new WeakMap;constructor(t={}){let n=this.#I(t);this.#t=n,this.#e=n.schema,n.defaults!==void 0&&(this.#r=this.#u(n.defaults)),this.events=new EventTarget,this.path=this.#S(n),this.#P(),n.watch&&this.#_()}get(t,n){return this.#o(this.store,t,n)}set(t,n){let i=fR(t);if(i!=="string"&&i!=="object")throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${i}`);if(typeof t!="object"&&n===void 0)throw new TypeError("Use `delete()` to clear values");let r=this.store;if(typeof t=="object")for(let[o,a]of Object.entries(t))this.#s(r,o,a);else this.#s(r,t,n);this.store=r}has(t){let n=String(t);return this.#t.accessPropertiesByDotNotation?j_(this.store,n):n in this.store}appendToArray(t,n){let i=String(t);K_(i,n);let r=this.store,o=this.#o(r,i,[]);if(!Array.isArray(o))throw new TypeError(`The key \`${i}\` is already set to a non-array value`);this.#s(r,i,[...o,n]),this.store=r}reset(...t){let n=this.store,i=!1;for(let r of t){let o=String(r),a=this.#T(n,o);a!==void 0&&(this.#s(n,o,a),i=!0)}i&&(this.store=n)}delete(t){let n=String(t),i=this.store;this.#t.accessPropertiesByDotNotation?Vv(i,n):delete i[n],this.store=i}clear(){this.store=Xr()}onDidChange(t,n){if(typeof t!="string")throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof t}`);if(typeof n!="function")throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof n}`);return this.#v(i=>this.#o(i,t),n)}onDidAnyChange(t){if(typeof t!="function")throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this.#v(n=>n,t)}get size(){return Object.keys(this.store).length}get store(){return this.#l(this.#d())}set store(t){this.#x(this.#a(t)),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[t,n]of Object.entries(this.store))yield[t,n]}_closeWatcher(){this.#n&&(this.#n.close(),this.#n=void 0),this.#p&&(Hn.unwatchFile(this.path),this.#p=!1),this.#i?.cancel(),this.#i=void 0}#d(){try{return Hn.readFileSync(this.path,"utf8")}catch(t){if(t.code==="ENOENT"){this.#f();return}throw t}}#l(t){return this.#g(t).value}#g(t){if(t!==void 0)try{let i=Object.assign(Xr(),this.#c(t));return{raw:i,value:this.#a(i)}}catch(i){if(!this.#t.clearInvalidConfig)throw i}let n=Xr();return{raw:n,value:this.#a(n),cleared:t!==void 0}}#h(){return this.#r===void 0?Xr():Object.assign(Xr(),this.#c(this.#r))}#T(t,n){let i=this.#o(this.#h(),n);if(i!==void 0)return i;let r=Object.assign(Xr(),this.#c(this.#u(t)));this.#t.accessPropertiesByDotNotation?Vv(r,n):delete r[n];try{return this.#o(this.#a(r),n)}catch{return}}#o(t,n,i){return this.#t.accessPropertiesByDotNotation?B_(t,n,i):n in t?t[n]:i}#s(t,n,i){K_(n,i),this.#t.accessPropertiesByDotNotation?F_(t,n,i):n!=="__proto__"&&n!=="constructor"&&n!=="prototype"&&(t[n]=i)}#w(t){let n=this.#y.get(t);if(n===void 0){try{let i=this.#d();n={data:i,store:this.#l(i)}}catch(i){n=null,this.#m(i)}this.#y.set(t,n)}return n}#m(t){this.events.dispatchEvent(new CustomEvent("error",{detail:t}))}#a(t){let n=Object.assign(this.#h(),t);return this.#e?yR(this.#e,n):n}#x(t){if(this.#e)try{this.#a(t)}catch(n){throw new TypeError(`Schema output must be valid schema input to be stored. ${n.message}`,{cause:n})}this.#f(),this.#b(t)}#f(){Hn.mkdirSync(ql.dirname(this.path),{recursive:!0})}#b(t){let n=this.#u(t);if(Kl.env.SNAP){Hn.writeFileSync(this.path,n,{mode:this.#t.configFileMode});return}G_(this.path,n,this.#t.configFileMode)}#v(t,n){let i=t(this.store),r=o=>{try{let a=this.#w(o);if(a===null||q_(t(a.store),i))return;let s=i,c=t(this.#l(a.data));i=c,n.call(this,c,s)}catch(a){this.#m(a)}};return this.events.addEventListener("change",r),()=>{this.events.removeEventListener("change",r)}}#c=t=>Z_(t);#u=t=>M_(t," ");#I(t){let n={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:384,...t};if(!n.cwd){if(!n.projectName)throw new Error("Please specify the `projectName` option.");n.cwd=Ls(mR(n.projectName),{suffix:n.projectSuffix??"nodejs"}).config}return typeof n.fileExtension=="string"&&(n.fileExtension=n.fileExtension.replace(/^\.+/,"")),n.serialize&&(this.#u=n.serialize),n.deserialize&&(this.#c=n.deserialize),n}#S(t){let n=t.fileExtension?`.${t.fileExtension}`:"";return ql.resolve(t.cwd??Kl.cwd(),`${t.configName??"config"}${n}`)}#P(){let{raw:t,value:n,cleared:i}=this.#g(this.#d());(i||!q_(t,Object.assign(Xr(),n)))&&this.#x(n)}#_(){if(this.#f(),Hn.existsSync(this.path)||this.#b(Xr()),Kl.platform==="win32"||Kl.platform==="darwin"){this.#i??=W_(()=>{this.events.dispatchEvent(new Event("change"))},100);let t=ql.dirname(this.path),n=ql.basename(this.path);this.#n=Hn.watch(t,{persistent:!1,encoding:"utf8"},(i,r)=>{r&&r!==n||this.#i?.()}),this.#n.on("error",i=>{this._closeWatcher(),this.#m(i)})}else this.#i??=W_(()=>{this.events.dispatchEvent(new Event("change"))},1e3),Hn.watchFile(this.path,{persistent:!1},()=>{this.#i?.()}),this.#p=!0}};function W_(e,t){let n,i=()=>{clearTimeout(n),n=void 0};return Object.assign(()=>{i(),n=setTimeout(()=>{n=void 0,e()},t)},{cancel:i})}var gR=Yv(e0),J_=Zs({privateKey:Wt(),address:Wt(),rootAddress:Wt().optional(),scopes:Xv(Wt()),name:Wt().optional(),days:Jv().int().optional(),fromBlock:Wt(),expiresAt:Wt().optional(),createdAt:Wt()}),hR=Zs({network:gR.optional(),sessions:Zs({mainnet:J_.optional(),calibration:J_.optional()}).default({})});function X_(e=process.env){return new Wl({projectName:"filecoin",projectSuffix:"",cwd:e.FILECOIN_CONFIG_DIR,schema:hR})}function Y_(e,t){return e??t.get("network")??t0}var bR="https://poc.filecoin.cloud",vR="https://api.filecoin.io";function TR(e,t){return n=>{let i=e(n);return{...i,request:(r,o)=>t.aborted?Promise.reject(t.reason):Hs(i.request(r,o),t)}}}function Q_(e={}){let t=e.env??process.env,n=X_(t),i=Y_(e.network,n),r=i==="mainnet"?jt:Mt,o=t.FILECOIN_RPC_URL?it(t.FILECOIN_RPC_URL):R_(r),a=e.signal?TR(o,e.signal):o,s=HP(t),c;return{network:i,chain:r,env:t,config:n,credentials:{sessionKey:e.sessionKey,rootAddress:e.rootAddress},consoleUrl:t.FILECOIN_CONSOLE_URL??bR,apiUrl:t.FILECOIN_API_URL??vR,signal:e.signal,transport:a,client:Af({chain:r,transport:a}),db:()=>(c??=VP(s),c),stagingDir:u=>xR(s,"staging",u)}}function nde(e){let{network:t,sessionKey:n,rootAddress:i}=e.input;return Q_({network:t,sessionKey:n,rootAddress:i,signal:e.signal})}function e$(e){let t=Uv(e);if(!t)throw Lv();return{chainId:e.chain.id.toString(),payer:t.rootAddress}}async function ide(e,t,n){let i=await e_(e,t);return{db:e.db(),backend:C_(e,i),chainId:e.chain.id.toString(),payer:i.rootAddress,apiUrl:e.apiUrl,stagingDir:e.stagingDir,signal:n.signal,progress:r=>n.progress(r),onOperation:r=>n.checkpoint({id:r.id,next:[Qv(r.id)]})}}function ode(e,t){let n=KP(e.db(),t,e$(e));if(!n)throw Jt(`No managed resource ${t}.`,{by:"agent",command:"filecoin ls",description:"List managed resources"});return n}function ade(e,t){let n=Fo(e.db(),t,e$(e));if(!n)throw Jt(`No operation ${t}.`,{by:"agent",command:"filecoin operations ls",description:"List operations"});return n}export{O as a,$e as b,Nt as c,jt as d,Mt as e,F as f,Xd as g,ZA as h,Wb as i,Po as j,Fre as k,jre as l,Yb as m,vP as n,jS as o,_o as p,Vre as q,Gre as r,HS as s,$o as t,Gt as u,az as v,cz as w,pz as x,el as y,KS as z,Pt as A,pne as B,CD as C,RD as D,xl as E,Be as F,Vz as G,Do as H,Ln as I,loe as J,HP as K,HD as L,qP as M,lae as N,Fo as O,mae as P,fae as Q,yae as R,gae as S,bae as T,KP as U,vae as V,Tae as W,WP as X,YP as Y,QP as Z,YD as _,QD as $,Dae as aa,Uv as ba,eC as ca,tC as da,Lv as ea,rC as fa,nC as ga,t_ as ha,r_ as ia,o_ as ja,d_ as ka,C_ as la,nde as ma,e$ as na,ide as oa,ode as pa,ade as qa};
186
+ //# sourceMappingURL=chunk-UW35AN2V.js.map