// Copyright 2023 Blockchain Creative Labs LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var e=require("ethers"),t=require("pino"),n=require("joi"),r=require("date-fns"),i=require("multiformats/cid"),a=require("multiformats/hashes/sha2"),o=require("node-fetch"),s=require("form-data"),u=require("stream"),d=require("@lit-protocol/lit-node-client"),c=require("siwe"),p=require("fast-xml-parser"),l=require("path");function y(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function f(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,t}var m,h,v,g,b,P,T,w=/*#__PURE__*/y(t),x=/*#__PURE__*/y(n),E=/*#__PURE__*/y(o),S=/*#__PURE__*/y(s),A=/*#__PURE__*/f(p),I=/*#__PURE__*/y(l),k="1.0.10",N=(m=!1,{setDebug:function(e){m=e},getDebug:function(){return m}}),O=N.setDebug,j=N.getDebug,C=function(){return w.default({base:{version:"1.0.10"},level:"debug",formatters:{level:function(e){return{level:e.toUpperCase()}},bindings:function(e){return{pid:e.pid,host:e.hostname,node_version:process.version}}},enabled:!(!j()&&"1"!==process.env.DEBUG),redact:["key","pvtKey","rootPvtKey"],timestamp:w.default.stdTimeFunctions.isoTime,msgPrefix:"@verify-media/verify-client@"+k+" ==> "})};function _(e){return e?e.startsWith("http://")||e.startsWith("https://")?e:"https://"+e:e}function B(e){return e?e.startsWith("ipfs://")?e:"ipfs://"+e:e}!function(e){e.PINATA="pinata",e.KUBO="kubo"}(h||(h={})),exports.LocationProtocol=void 0,(v=exports.LocationProtocol||(exports.LocationProtocol={})).IPFS="ipfs",v.HTTPS="https",v.S3="s3",exports.MIME_TYPES=void 0,(g=exports.MIME_TYPES||(exports.MIME_TYPES={})).JPG="image/jpg",g.JPEG="image/jpeg",g.PNG="image/png",g.AVIF="image/avif",g.BMP="image/bmp",g.SVG_XML="image/svg+xml",g.SVG="image/svg",g.WEBP="image/webp",g.TEXT="text/html",g.GIF="image/gif",g.MP4="video/mp4",exports.ContentTypes=void 0,(b=exports.ContentTypes||(exports.ContentTypes={})).HTML="html",b.MARKDOWN="markdown",b.STRING="string",b.TEXT="text",b.IMAGE="image",b.VIDEO="video",exports.STAGE=void 0,(P=exports.STAGE||(exports.STAGE={})).testnet="testnet",P.mainnet="mainnet",P.sandbox="sandbox",exports.LICENSE_TYPES=void 0,(T=exports.LICENSE_TYPES||(exports.LICENSE_TYPES={})).allowlist="allowlist",T.public="public",T.private="private",T.timebased="timebased",T.authorizer="authorizer";var M=function(t){return e.ethers.utils.keccak256(t)};function D(e){if(C().debug("data passed "+!!e),!e)throw new Error("no value passed was passed");var t=M(new Uint8Array(Buffer.from(e,"utf-8")));return C().debug("hash generated"),t}var U,F,R,H=function(e){return void 0===e&&(e=""),e&&e.replace(/\s/g,"").toLowerCase()},q=function(e){switch(e){case"testnet":return"0x27BA7E931906FebA79dED5d32947b12f30379135";case"sandbox":return"0xdCE27c4a76bE1fF9F9C543E13FCC3591E33A0E25";case"mainnet":return"TBD";default:throw new Error("stage can be either sandbox, testnet or mainnet")}},K=function(e){switch(e){case"testnet":return"0xAE8c7c7e6819f425CE750CC7F7e72A13Ef3635E0";case"sandbox":return"0xEe586a3655EB0D017643551e9849ed828Fd7c7FA";case"mainnet":return"TBD";default:throw new Error("stage can be either sandbox, testnet or mainnet")}},G=function(e){switch(e){case"testnet":case"sandbox":return"cayenne";case"mainnet":return"habanero";default:throw new Error("stage can be either sandbox, testnet or mainnet")}},L=function(e,t){var n=H(t);switch(H(e)){case"allowlist":return{sandbox:"0xb98068e0DA0Da5b9a50461F3B99473a3417dFf62",testnet:"0xAa800342cC635FC8D9c394981120CcAf65321b15",mainnet:""}[n];case"public":return{sandbox:"0xB4D05978AfC8a03A1D8e91314186fBd3A9E513b3",testnet:"0x6Cf8374a13b48070b600be33F16370Ab3e557600",mainnet:""}[n];case"private":return{sandbox:"0xEab65FD2aBF9b14C08187aa69bD6A74B7993eAf3",testnet:"0xd4547af11c8296Bc9B3d79Fd9a680b2163D419C",mainnet:""}[n];case"timebased":return{sandbox:"0x55B03c3025901F391bb787FeFB83f23450e7c909",testnet:"",mainnet:""}[n];case"authorizer":return{sandbox:"0x4d18eE1343165E74fe8de53700ee62FDB0810cDb",testnet:"",mainnet:""}[n];default:throw new Error("Invalid license type, only allowed types are "+Object.values(exports.LICENSE_TYPES))}},Y="0xe63231f6",z=(U={stage:"",pvtKey:"",rpcUrl:"",contractAddress:"",identityContractAddress:"",chainId:0,chain:"",maxGasPrice:0,walletExpiryDays:1,rootPvtKey:""},{init:function(e){var t=(null==e?void 0:e.stage)||process.env.STAGE||"",n=Object.values(exports.STAGE);if(!t)throw new Error("stage cannot be empty, either set and env var STAGE or pass a value to this function");if(!n.includes(t))throw new Error("stage can be either sandbox, testnet or mainnet");U.stage=t;var r=(null==e?void 0:e.pvtKey)||process.env.PVT_KEY||"";U.pvtKey=r;var i=(null==e?void 0:e.rpcUrl)||process.env.RPC_URL||"";if(!i)throw new Error("rpcUrl cannot be empty, either set and env var RPC_URL or pass a value to this function");U.rpcUrl=i;var a=(null==e?void 0:e.chainId)||process.env.CHAIN_ID||0;if(!a)throw new Error("chainId cannot be empty, either set and env var CHAIN_ID or pass a value to this function");U.chainId=parseInt(a.toString());var o=(null==e?void 0:e.chain)||process.env.CHAIN||"";if(!o)throw new Error("chain cannot be empty, either set and env var CHAIN or pass a value to this function");U.chain=o;var s=(null==e?void 0:e.walletExpiryDays)||process.env.WALLET_EXPIRY_DAYS||1;U.walletExpiryDays=Number(s);var u=(null==e?void 0:e.maxGasPrice)||process.env.MAX_GAS_PRICE||0;U.maxGasPrice=Number(u);var d=(null==e?void 0:e.rootPvtKey)||process.env.ROOT_PVT_KEY||"";return U.rootPvtKey=d,U.contractAddress=K(t),U.identityContractAddress=q(t),console.log("sdk version "+k+" is ready"),O((null==e?void 0:e.debug)||"1"===process.env.DEBUG),U},getConfig:function(){if(!["stage","rpcUrl","chainId","chain","contractAddress","identityContractAddress"].every(function(e){return Object.prototype.hasOwnProperty.call(U,e)&&Boolean(U[e])}))throw new Error("empty values found in config");return U},clearConfig:function(){U={stage:"",pvtKey:"",rpcUrl:"",contractAddress:"",identityContractAddress:"",chainId:0,chain:"",maxGasPrice:0,walletExpiryDays:1,rootPvtKey:""}},unset:function(e){delete U[e]},set:function(e,t){U[e]=t}}),J=z.init,W=z.getConfig,V=function(e){try{return Promise.resolve(a.sha256.digest(e.body)).then(function(e){return i.CID.create(1,85,e).toString()})}catch(e){return Promise.reject(e)}},X=function(e,t,n){try{if(C().debug(e),!n)throw new Error("IPFS gateway is not provided");var r=n+"/"+B(e).split("ipfs://")[1];return C().debug(r),Promise.resolve(E.default(r)).then(function(e){C().debug(e);var n=null,r="meta"===t?Promise.resolve(e.json()).then(function(e){n=e,C().debug(n)}):Promise.resolve(e.arrayBuffer()).then(function(e){n=new Uint8Array(e),C().debug(n.length)});return r&&r.then?r.then(function(){return n}):n})}catch(e){return Promise.reject(e)}},Q={root:"https://api.pinata.cloud",headers:{pinata_api_key:"",pinata_secret_api_key:""}},Z=function(e){var t=e.data,n=e.config,r=e.type;try{return Promise.resolve(function(e,i){try{var a=function(){C().debug("read pinata config");var e=t.name,i=t.body,a=n.pinataKey,o=n.pinataSecret;C().debug("prep api request"),Q.headers.pinata_api_key=a||process.env.PINATA_KEY||"",Q.headers.pinata_secret_api_key=o||process.env.PINATA_SECRET||"";var s=null,d=function(){if("meta"===r){var t={pinataContent:i,pinataMetadata:{name:e},pinataOptions:{cidVersion:1}},n=Q.root+"/pinning/pinJSONToIPFS";return C().debug("upload asset meta to "+n),Promise.resolve(fetch(n,{method:"POST",headers:{"Content-Type":"application/json",pinata_api_key:Q.headers.pinata_api_key,pinata_secret_api_key:Q.headers.pinata_secret_api_key},body:JSON.stringify(t)})).then(function(e){return Promise.resolve(e.json()).then(function(e){s=e})})}var a=Q.root+"/pinning/pinFileToIPFS",o=new S.default;C().debug("prep formdata to upload asset to "+a);var d=new u.Readable({read:function(){this.push(i),this.push(null)}});return C().debug("append file stream to formdata"),o.append("file",d,{filename:e}),C().debug("append metadata to formdata"),o.append("pinataMetadata",JSON.stringify({name:e})),C().debug("append pinata options to formdata"),o.append("pinataOptions",JSON.stringify({cidVersion:1})),C().debug("upload asset to pinata"),Promise.resolve(fetch(a,{method:"POST",headers:{pinata_api_key:Q.headers.pinata_api_key,pinata_secret_api_key:Q.headers.pinata_secret_api_key,"Content-type":"multipart/form-data; boundary="+o.getBoundary()},body:o})).then(function(e){return Promise.resolve(e.json()).then(function(e){s=e})})}();return d&&d.then?d.then(function(){return s}):s}()}catch(e){return i(e)}return a&&a.then?a.then(void 0,i):a}(0,function(e){throw new Error(e.message)}))}catch(e){return Promise.reject(e)}},$=function(e,t,n){try{var r=e.replace("ipfs://","");C().debug("fetch asset from IPFS via Pinata "+r);var i=n.pinataKey,a=n.pinataSecret,o="https://gateway.pinata.cloud/ipfs/"+r;return C().debug("prep api request"),Q.headers.pinata_api_key=i||process.env.PINATA_KEY||"",Q.headers.pinata_secret_api_key=a||process.env.PINATA_SECRET||"",C().debug("fetch asset from "+o),Promise.resolve(fetch(o,{method:"GET",headers:Q.headers})).then(function(e){return"meta"===t?(C().debug("parse asset meta"),Promise.resolve(e.json())):(C().debug("parse asset binary data"),Promise.resolve(e.arrayBuffer()).then(function(e){return new Uint8Array(e)}))})}catch(e){return Promise.reject(e)}},ee=function(){var e=null,t={promise:null,resolve:null,reject:null},n=new Promise(function(e,n){t.resolve=e,t.reject=n});t.promise=n;var r=function(n){try{if(e)return Promise.resolve(e);var r=W();C().debug("lit client settings, "+{alertWhenUnauthorized:!1,litNetwork:G(r.stage),debug:n||"1"===process.env.LIT_DEBUG||!1}+" ");var i=new d.LitNodeClient({alertWhenUnauthorized:!1,litNetwork:G(r.stage),debug:n||"1"===process.env.LIT_DEBUG||!1});return Promise.resolve(i.connect()).then(function(){return e=i,t.resolve&&t.resolve(e),e})}catch(e){return Promise.reject(e)}};return{init:r,getClient:function(){return Promise.resolve(r()).then(function(){if(!e)throw new Error("lit client not initialized");return e})}}}(),te=ee.getClient,ne=function(e,t,n){return[{conditionType:"evmContract",contractAddress:n,chain:t,functionName:"auth",functionAbi:{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"address",name:"user",type:"address"}],name:"auth",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},functionParams:[e,":userAddress"],returnValueTest:{key:"",comparator:"=",value:"true"}},{operator:"or"},{conditionType:"evmContract",contractAddress:n,chain:t,functionName:"refAuth",functionAbi:{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"address",name:"user",type:"address"}],name:"refAuth",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},functionParams:[e,":userAddress"],returnValueTest:{key:"",comparator:"=",value:"true"}}]},re=function(){var t=W();return new e.Wallet(t.pvtKey||"",new e.ethers.providers.JsonRpcProvider(t.rpcUrl))},ie=function(){try{var e=W().chainId;return Promise.resolve(function(){try{var e=re();return C().debug("using wallet signer"),Promise.resolve(e.address)}catch(e){return Promise.reject(e)}}()).then(function(t){return Promise.resolve(te()).then(function(){return Promise.resolve(function(e){var t=e.address,n=e.chainId,r=e.statement,i=void 0===r?"authsign generated by an identity on verify":r,a=e.uri,o=void 0===a?"http://localhost/login":a,s=e.version,u=void 0===s?"1":s,d=e.domain,p=void 0===d?"localhost":d;try{return Promise.resolve(new c.SiweMessage({domain:p,address:t,statement:i,uri:o,version:u,chainId:n,expirationTime:new Date(Date.now()+42e4).toISOString()}))}catch(e){return Promise.reject(e)}}({address:t,chainId:e})).then(function(e){var n=e.prepareMessage();return Promise.resolve(function(e){try{var t=re();return Promise.resolve(t.signMessage(e))}catch(e){return Promise.reject(e)}}(n)).then(function(e){return{sig:e,derivedVia:"web3.eth.personal.sign",signedMessage:n,address:t}})})})})}catch(e){return Promise.reject(e)}},ae=function(e){var t=e.content,n=e.contentHash;try{C().debug("read sdk config");var r=W(),i=r.contractAddress,a=r.chain;return C().debug("init lit client"),Promise.resolve(te()).then(function(e){if(!e)throw new Error("lit client not initialized");return C().debug("sign auth message"),Promise.resolve(ie()).then(function(r){C().debug("get access control conditions");var o=ne(n,a,i);return C().debug("encrypt file"),Promise.resolve(d.encryptFile({file:t,chain:a,authSig:r,unifiedAccessControlConditions:o},e)).then(function(e){return{ciphertext:e.ciphertext,dataToEncryptHash:e.dataToEncryptHash}})})})}catch(e){return Promise.reject(e)}},oe=function(e){var t=e.ciphertext,n=e.dataToEncryptHash,r=e.contentHash;try{C().debug("read sdk config");var i=W(),a=i.contractAddress,o=i.chain;return C().debug("init lit client"),Promise.resolve(te()).then(function(e){if(!e)throw new Error("lit client not initialized");return C().debug("sign auth message"),Promise.resolve(ie()).then(function(i){C().debug("get access control conditions");var s=ne(r,o,a);return C().debug("decrypt file"),Promise.resolve(d.decryptToFile({unifiedAccessControlConditions:s,ciphertext:t,dataToEncryptHash:n,authSig:i,chain:o},e))})})}catch(e){return Promise.reject(e)}},se=[{inputs:[],name:"AlreadyRegistered",type:"error"},{inputs:[],name:"InvalidParams",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[],name:"NotRegistered",type:"error"},{inputs:[],name:"RegistryExpired",type:"error"},{inputs:[],name:"SignatureExpired",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint8",name:"version",type:"uint8"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"version_",type:"string"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"",type:"string"}],name:"nameToRoot",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"signature",type:"bytes"},{internalType:"address",name:"root",type:"address"},{internalType:"address",name:"intermediate",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"chainID",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"}],name:"register",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"root",type:"address"},{internalType:"string",name:"name",type:"string"}],name:"registerRoot",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"registered",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"rootName",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes",name:"signature",type:"bytes"},{internalType:"address",name:"root",type:"address"},{internalType:"address",name:"intermediate",type:"address"},{internalType:"uint256",name:"chainID",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"}],name:"unregister",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"root",type:"address"}],name:"unregisterRoot",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"used",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"identity",type:"address"}],name:"whoIs",outputs:[{internalType:"address",name:"root",type:"address"}],stateMutability:"view",type:"function"}],ue=function(){try{var t=W(),n=new e.ethers.providers.JsonRpcProvider(t.rpcUrl);return Promise.resolve(n.getBlock("latest")).then(function(e){return new Date(1e3*e.timestamp)})}catch(e){return Promise.reject(e)}};!function(e){e.UserError="UserError",e.EmptyError="EmptyError",e.RevertError="RevertError",e.PanicError="PanicError",e.UnknownError="UnknownError",e.CustomError="CustomError"}(F||(F={})),exports.NODE_TYPE=void 0,(R=exports.NODE_TYPE||(exports.NODE_TYPE={}))[R.ORG=0]="ORG",R[R.REFERENCE=1]="REFERENCE",R[R.ASSET=2]="ASSET";var de=[{inputs:[],name:"InvalidParams",type:"error"},{inputs:[],name:"NodeAlreadyExists",type:"error"},{inputs:[],name:"NodeDoesNotExist",type:"error"},{inputs:[],name:"NotAuthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"_id",type:"bytes32"},{indexed:!0,internalType:"address",name:"_auth",type:"address"}],name:"AccessAuthUpdate",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"approved",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint8",name:"version",type:"uint8"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"minter",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"parentId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Minted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"_id",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"_from",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"_to",type:"bytes32"}],name:"Moved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"_id",type:"bytes32"},{indexed:!0,internalType:"address",name:"_auth",type:"address"}],name:"ReferenceAuthUpdate",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"_id",type:"bytes32"},{indexed:!0,internalType:"string",name:"_uri",type:"string"}],name:"URIUpdate",type:"event"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"address",name:"user",type:"address"}],name:"auth",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"childrenOf",outputs:[{internalType:"uint256[]",name:"childrenIds",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"bytes32",name:"parentId",type:"bytes32"},{internalType:"enum ContentGraph.NodeType",name:"nodeType",type:"uint8"},{internalType:"bytes32",name:"referenceOf",type:"bytes32"}],name:"createNode",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getApproved",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"}],name:"getNode",outputs:[{components:[{internalType:"uint256",name:"token",type:"uint256"},{internalType:"enum ContentGraph.NodeType",name:"nodeType",type:"uint8"},{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"bytes32",name:"referenceOf",type:"bytes32"},{internalType:"string",name:"uri",type:"string"},{internalType:"address",name:"accessAuth",type:"address"},{internalType:"address",name:"referenceAuth",type:"address"}],internalType:"struct ContentGraph.Node",name:"node",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"},{internalType:"address",name:"_identity",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"isLeaf",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"isRoot",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"bytes32",name:"newParentId",type:"bytes32"}],name:"move",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"nodesCreated",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ownerOf",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"parentOf",outputs:[{internalType:"uint256",name:"parentId",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"parentId",type:"bytes32"},{components:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"enum ContentGraph.NodeType",name:"nodeType",type:"uint8"},{internalType:"bytes32",name:"referenceOf",type:"bytes32"},{internalType:"string",name:"uri",type:"string"}],internalType:"struct ContentGraph.ContentNode",name:"content",type:"tuple"}],name:"publish",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"parentId",type:"bytes32"},{components:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"enum ContentGraph.NodeType",name:"nodeType",type:"uint8"},{internalType:"bytes32",name:"referenceOf",type:"bytes32"},{internalType:"string",name:"uri",type:"string"}],internalType:"struct ContentGraph.ContentNode[]",name:"content",type:"tuple[]"}],name:"publishBulk",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"address",name:"user",type:"address"}],name:"refAuth",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"address",name:"accessAuth",type:"address"}],name:"setAccessAuth",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"address",name:"referenceAuth",type:"address"}],name:"setReferenceAuth",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"string",name:"uri",type:"string"}],name:"setURI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"token",type:"uint256"}],name:"tokenToNode",outputs:[{components:[{internalType:"uint256",name:"token",type:"uint256"},{internalType:"enum ContentGraph.NodeType",name:"nodeType",type:"uint8"},{internalType:"bytes32",name:"id",type:"bytes32"},{internalType:"bytes32",name:"referenceOf",type:"bytes32"},{internalType:"string",name:"uri",type:"string"},{internalType:"address",name:"accessAuth",type:"address"},{internalType:"address",name:"referenceAuth",type:"address"}],internalType:"struct ContentGraph.Node",name:"node",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"tokenURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"transferFrom",outputs:[],stateMutability:"nonpayable",type:"function"}];function ce(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var pe="0x08c379a0",le="0x4e487b71";function ye(t,n,r,i,a){var o=t.slice(n.length);try{var s,u=e.utils.defaultAbiCoder.decode([i],"0x"+o)[0];return{type:r,error:"uint256"===i?null!=(s=function(e){switch(e.toNumber()){case 1:return"Assertion error";case 17:return"Arithmetic operation underflowed or overflowed outside of an unchecked block";case 18:return"Division or modulo division by zero";case 33:return"Tried to convert a value into an enum, but the value was too big or negative";case 34:return"Incorrectly encoded storage byte array";case 49:return".pop() was called on an empty array";case 50:return"Array accessed at an out-of-bounds or negative index";case 65:return"Too much memory was allocated, or an array was created that is too large";case 81:return"Called a zero-initialized variable of internal function type";default:return}}(u))?s:a:u,data:t}}catch(e){return{type:F.UnknownError,error:a,data:t}}}var fe=function(t,n){var r,i,a=t;if(!(a instanceof Error))return{type:F.UnknownError,error:null!=(r=a.message)?r:"Unexpected error",data:void 0};try{i=function(e){for(var t,n,r=e;r&&!t;)t=r.data,r=r.error,n=t;if(!t)throw e;if("object"==typeof n&&n.data&&(n=n.data),!n||"string"!=typeof n)throw e;return n}(a)}catch(e){var o,s;return null!=(o=a.message)&&o.includes("user rejected transaction")?{type:F.UserError,error:"User has rejected the transaction",data:i}:{type:F.UnknownError,error:null!=(s=a.message)?s:"Unknown error",data:i}}switch(!0){case"0x"===i:return{type:F.EmptyError,error:"Empty error data returned",data:i};case i.startsWith(pe):return ye(i,pe,F.RevertError,"string","Unknown error returned");case i.startsWith(le):return ye(i,le,F.PanicError,"uint256","Unknown panic code");default:if(!n)return{type:F.CustomError,error:i.slice(0,10),data:i};var u=(n instanceof e.utils.Interface?n:new e.utils.Interface(n)).parseError(i);return{type:F.CustomError,error:u.name,args:u.args,data:i}}};function me(e){return function(){try{var t=arguments;return Promise.resolve(ce(function(){return Promise.resolve(e.apply(void 0,[].slice.call(t)))},function(e){C().error("Error in function:",e);var t=fe(e,de);throw{type:t.type||"native",error:t.error||e.cause,data:t.data||e.message}}))}catch(e){return Promise.reject(e)}}}function he(e){return function(){try{var t=arguments;return Promise.resolve(ce(function(){return Promise.resolve(e.apply(void 0,[].slice.call(t)))},function(e){C().error("Error in function:",e);var t=fe(e,se);throw{type:t.type||"native",error:t.error||e.cause,data:t.data||e.message}}))}catch(e){return Promise.reject(e)}}}var ve=function(){var t=W();return new e.Wallet(t.pvtKey||"",new e.ethers.providers.JsonRpcProvider(t.rpcUrl))},ge=function(){try{var e=ve();return C().debug("using wallet signer"),Promise.resolve(e.address)}catch(e){return Promise.reject(e)}},be=function(){var t=W(),n=t.rootPvtKey,r=t.rpcUrl;if(!n)throw new Error("rootPvtKey cannot be empty, either set and env var ROOT_PVT_KEY or pass a value to this function");var i=new e.Wallet(n,new e.ethers.providers.JsonRpcProvider(r));return C().debug("root wallet address: %s",i.address),i},Pe=function(){var t=ve();return new e.Contract(q(W().stage),se,t)},Te=function(t,n){try{var r=function(){C().debug("structHash: %s",a);var t=e.utils.arrayify(e.utils.keccak256("0x1901"+o.substring(2)+a.substring(2))),n=new e.utils.SigningKey(i).signDigest(t);return e.utils.joinSignature(n)},i=W().rootPvtKey;if(!i)throw new Error("rootPvtKey cannot be empty, either set and env var ROOT_PVT_KEY or pass a value to this function");var a=e.utils.keccak256(t),o="",s=function(){if(!n)return Promise.resolve(function(){try{var t=Pe();return Promise.resolve(t.eip712Domain()).then(function(t){return e.utils.keccak256(e.utils.defaultAbiCoder.encode(["bytes32","bytes32","bytes32","uint256","address"],[e.utils.keccak256(e.utils.toUtf8Bytes("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),e.utils.id(t.name),e.utils.id(t.version),t.chainId,q(W().stage)]))})}catch(e){return Promise.reject(e)}}()).then(function(e){o=e});o=n}();return Promise.resolve(s&&s.then?s.then(r):r())}catch(e){return Promise.reject(e)}},we=he(function(){try{var t=W(),n=t.walletExpiryDays,r=t.chainId,i=be(),a=Pe();return C().debug("walletExpiryDays "+n),C().debug("rootWallet "+i.address),C().debug("identityContract "+a.address),Promise.resolve(ge()).then(function(t){if(C().debug("registering intermediate wallet: %s",t),!t)throw new Error("intermediate wallet not set");return Promise.resolve(ue()).then(function(o){var s=o.getTime();C().debug("block time "+s);var u=s+86400*n,d=s+86400;return C().debug("get signature to register"),Promise.resolve(function(t,n,r){try{var i=be();return Promise.resolve(function(t,n,r,i){try{var a=W().chainId,o=Pe();return Promise.resolve(o.nonces(n)).then(function(o){return C().debug("nonce: %s",o),e.utils.defaultAbiCoder.encode(["bytes32","address","address","uint256","uint256","uint256","uint256"],[e.utils.keccak256(e.utils.toUtf8Bytes("register(address root,address intermediate,uint256 expiry,uint256 nonce,uint256 chainID,uint256 deadline)")),n,t,r,o,a,i])})}catch(e){return Promise.reject(e)}}(t,i.address,n,r)).then(Te)}catch(e){return Promise.reject(e)}}(t,u,d)).then(function(e){return C().debug("signature: %s",e),Promise.resolve(a.register(e,i.address,t,u,r,d)).then(function(e){return C().debug("intermediate wallet registered: %s",e.hash),Promise.resolve(e.wait()).then(function(e){return C().debug("intermediate wallet registered receipt: %s",e.transactionHash),e})})})})})}catch(e){return Promise.reject(e)}}),xe=he(function(){try{var t=W().chainId,n=be(),r=Pe();return C().debug("rootWallet "+n.address),C().debug("identityContract "+r.address),Promise.resolve(ge()).then(function(i){if(!i)throw new Error("intermediate wallet not set");return Promise.resolve(ue()).then(function(a){var o=a.getTime(),s=o+86400;return C().debug("block time "+o),C().debug("get signature to unregister"),Promise.resolve(function(t,n){try{var r=be();return Promise.resolve(function(t,n,r){try{var i=W().chainId,a=Pe();return Promise.resolve(a.nonces(n)).then(function(a){return C().debug("nonce: %s",a),e.utils.defaultAbiCoder.encode(["bytes32","address","address","uint256","uint256","uint256"],[e.utils.keccak256(e.utils.toUtf8Bytes("unregister(address root,address intermediate,uint256 nonce,uint256 chainID,uint256 deadline)")),n,t,a,i,r])})}catch(e){return Promise.reject(e)}}(t,r.address,n)).then(Te)}catch(e){return Promise.reject(e)}}(i,s)).then(function(e){return Promise.resolve(r.unregister(e,n.address,i,t,s)).then(function(e){return Promise.resolve(e.wait())})})})})}catch(e){return Promise.reject(e)}}),Ee=function(e){try{var t=Pe();return Promise.resolve(t.whoIs(e))}catch(e){return Promise.reject(e)}},Se=he(function(e){try{if(!e)throw new Error("orgName cannot be empty");var t=be(),n=Pe();return C().debug("rootWallet "+t.address),C().debug("identityContract "+n.address),C().debug("registering root wallet: %s",t.address),Promise.resolve(n.registerRoot(t.address,e)).then(function(e){return C().debug("root wallet registered: %s",e.hash),Promise.resolve(e.wait())})}catch(e){return Promise.reject(e)}}),Ae=he(function(){try{var e=be(),t=Pe();return C().debug("unregistering root wallet: %s",e.address),Promise.resolve(t.unregisterRoot(e.address)).then(function(e){return C().debug("root wallet unregistered: %s",e.hash),Promise.resolve(e.wait())})}catch(e){return Promise.reject(e)}});function Ie(){return Ie=Object.assign?Object.assign.bind():function(e){for(var t=1;t \n 1.0 \n
\n "+e.metadata.title+"\n "+e.metadata.description+"\n "+e.metadata.datePublished+" \n "+e.metadata.id+"\n "+e.metadata.uri+"\n "+e.metadata.origin+"\n
\n
\n
\n "+t+"\n
\n
\n \n "+n.map(function(e){return"<"+e.type+">\n "+e.title+"\n "+e.contentType+"\n "+e.description+"\n "+e.creditedSource+"\n "+e.hash+"\n "+(e.cid?""+e.cid+"":"")+"\n "+(e.published?""+e.published+"":"")+"\n "}).join("")+" \n \n \n"},wt=function(e){return e.data.access={"lit-protocol":{version:"v3"}},e.data.encrypted=!0,e},xt=function(e,t){if(!t)throw new Error("ipfs hash cannot be empty");return e.data.locations.push({uri:B(t),protocol:exports.LocationProtocol.IPFS}),e},Et=function(e,t){return e.signature=t,e};function St(e,t,n){if(!e.s){if(n instanceof It){if(!n.s)return void(n.o=St.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(St.bind(null,e,t),St.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var At=function(e){return"owned"===e.ownership};const It=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{St(r,1,e(this.v))}catch(e){St(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?St(r,1,t?t(i):i):n?St(r,1,n(i)):St(r,2,i)}catch(e){St(r,2,e)}},r},e}();var kt="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Nt(e){return e instanceof It&&1&e.s}var Ot=function(e,t){if("text"===e.type)return{version:"1.0.0",data:{description:e.description,type:e.contentType,encrypted:!0,access:{"lit-protocol":{version:"v3"}},locations:[],manifest:{uri:_(e.uri),title:e.title,alt:"",description:e.description,caption:"",creditedSource:e.authority.name,signingOrg:{name:e.authority.name,unit:e.authority.name},published:e.published,history:[]},contentBinding:{algo:"keccak256",hash:t}},signature:{curve:"secp256k1",signature:"",message:"",description:""}};if(!e.uri)throw new Error("content.uri is required");var n=new URL(e.uri),r=I.default.basename(n.pathname),i=At(e)?"an image owned by "+e.authority.name:"an image licensed from "+e.licensedFrom;return{version:"1.0.0",data:{description:i,type:e.contentType,encrypted:!0,access:{"lit-protocol":{version:"v3"}},locations:[],manifest:{uri:_(e.uri),title:r,alt:"",description:i,caption:"",creditedSource:(At(e)?e.authority.name:e.licensedFrom)||"",signingOrg:{name:e.authority.name,unit:e.authority.name},published:(new Date).toISOString(),history:[]},contentBinding:{algo:"keccak256",hash:t}},signature:{curve:"secp256k1",signature:"",message:"",description:""}}},jt=function(e){var t=JSON.parse(JSON.stringify(e));return t.data.locations=[],"text/html"!==t.data.type&&(t.data.manifest.published=""),D(JSON.stringify(t.data))};function Ct(e,t,n){if(!e.s){if(n instanceof _t){if(!n.s)return void(n.o=Ct.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(Ct.bind(null,e,t),Ct.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var _t=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var a=1&i?t:n;if(a){try{Ct(r,1,a(this.v))}catch(e){Ct(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?Ct(r,1,t?t(i):i):n?Ct(r,1,n(i)):Ct(r,2,i)}catch(e){Ct(r,2,e)}},r},e}(),Bt="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Mt(e){return e instanceof _t&&1&e.s}var Dt=function(e,t,n){if("text"===e.type)return{version:"1.0.0",data:{description:e.description,type:e.contentType,encrypted:!0,access:{"verify-auth":{license:n}},locations:[{protocol:exports.LocationProtocol.HTTPS,uri:_(e.uri)}],manifest:{uri:_(e.uri),title:e.title,alt:"",description:e.description,caption:"",creditedSource:e.authority.name,signingOrg:{name:e.authority.name,unit:e.authority.name},published:e.published,history:[]},contentBinding:{algo:"keccak256",hash:t}},signature:{curve:"secp256k1",signature:"",message:"",description:""}};if(!e.uri)throw new Error("content.uri is required");var r=new URL(e.uri),i=I.default.basename(r.pathname),a="an image owned by "+e.authority.name;return{version:"1.0.0",data:{description:a,type:e.contentType,encrypted:!0,access:{"verify-auth":{license:n}},locations:[{protocol:exports.LocationProtocol.HTTPS,uri:_(e.uri)}],manifest:{uri:_(e.uri),title:i,alt:"",description:a,caption:"",creditedSource:e.authority.name,signingOrg:{name:e.authority.name,unit:e.authority.name},published:(new Date).toISOString(),history:[]},contentBinding:{algo:"keccak256",hash:t}},signature:{curve:"secp256k1",signature:"",message:"",description:""}}},Ut=function(e){var t=JSON.parse(JSON.stringify(e));return t.data.locations=[],"text/html"!==t.data.type&&(t.data.manifest.published=""),D(JSON.stringify(t.data))};exports.addEncryptionData=wt,exports.addIPFSData=xt,exports.addSignatureData=Et,exports.buildArticleBody=Tt,exports.buildAssetPayload=function(e){return{version:"1.0.0",data:{description:"",type:"",access:{"verify-auth":{license:exports.LICENSE_TYPES.allowlist}},encrypted:!0,locations:[],manifest:{uri:"",title:"",creditedSource:"",signingOrg:{name:"",unit:""},published:"",history:[]},contentBinding:{algo:"keccak256",hash:e}},signature:{curve:"secp256k1",signature:"",message:"",description:""}}},exports.changeParent=ct,exports.checkAllowListAuth=Ce,exports.checkAuth=function(e,t){try{var n=tt();return C().debug("check gas limits"),Promise.resolve($e()).then(function(r){return C().debug("check auth for "+e+" by "+t),Promise.resolve(n.auth(e,t,{gasPrice:r}))})}catch(e){return Promise.reject(e)}},exports.checkAuthorizerAuth=Fe,exports.checkEmbargoAuth=Ye,exports.checkRefAuth=function(e,t){try{var n=tt();return C().debug("check gas limits"),Promise.resolve($e()).then(function(r){return C().debug("check ref auth for "+e+" by "+t),Promise.resolve(n.refAuth(e,t,{gasPrice:r}))})}catch(e){return Promise.reject(e)}},exports.createArticleNode=mt,exports.createHierarchicalNode=vt,exports.createLicenseNode=ft,exports.createNode=dt,exports.createOrgNode=ht,exports.decodeEtherError=fe,exports.decrypt=function(e,t,n){void 0===t&&(t="");try{var r=function(){if("text/html"===i.data.type){C().debug("decrypting html asset");var e=new TextDecoder,t=e.decode(a),n=JSON.parse(t);return C().debug("decoding encrypted asset"),Promise.resolve(oe({ciphertext:n.ciphertext,dataToEncryptHash:n.dataToEncryptHash,contentHash:i.data.contentBinding.hash})).then(function(t){var n=e.decode(t);return{type:i.data.type,content:n}})}C().debug("decrypting non-html asset");var r=(new TextDecoder).decode(a),o=JSON.parse(r);return C().debug("decoding encrypted asset"),Promise.resolve(oe({ciphertext:o.ciphertext,dataToEncryptHash:o.dataToEncryptHash,contentHash:i.data.contentBinding.hash})).then(function(e){var t=Buffer.from(e);return{type:i.data.type,content:t}})};C().debug("decrypting asset "+e.meta.data.contentBinding.hash);var i=e.meta,a=null,o=null!=n&&n.pinataKey&&null!=n&&n.pinataSecret?(C().debug("fetching asset from pinata"),Promise.resolve($(i.data.locations[0].uri,"asset",n)).then(function(e){a=e})):(C().debug("fetching asset from ipfs"),Promise.resolve(X(i.data.locations[0].uri,"asset",t)).then(function(e){a=e}));return Promise.resolve(o&&o.then?o.then(r):r())}catch(e){return Promise.reject(e)}},exports.decryptAsset=oe,exports.encryptAsset=ae,exports.fetchFileFromPinata=$,exports.fetchFromIPFS=X,exports.genCid=V,exports.getArticleProvenance=function(e,t,n){try{return C().debug("get node for "+e),Promise.resolve(it(e)).then(function(e){return C().debug("get children of "+e.token.toString()),Promise.resolve(function(e){try{var t=tt();return Promise.resolve(t.childrenOf(e))}catch(e){return Promise.reject(e)}}(e.token.toString())).then(function(e){var r=e.map(function(e){try{return Promise.resolve(ot(e.toString())).then(function(e){return null!=n&&n.pinataKey&&null!=n&&n.pinataSecret?(C().debug("fetch from pinata "+e.uri),Promise.resolve($(e.uri,"meta",n))):(C().debug("fetch from ipfs "+e.uri),Promise.resolve(X(e.uri,"meta",t)))})}catch(e){return Promise.reject(e)}});return Promise.resolve(Promise.all(r))})})}catch(e){return Promise.reject(e)}},exports.getAssetDetails=Ze,exports.getAssetPrice=Je,exports.getAuthorizerNode=Re,exports.getAuthorizerRoot=He,exports.getChildrenNodes=function(e){try{var t=tt();return C().debug("get node for "+e),Promise.resolve(it(e)).then(function(e){return C().debug("get children for "+e.token.toString()),Promise.resolve(t.childrenOf(e.token.toString())).then(function(e){C().debug("get children nodes for "+e);var t=e.map(function(e){return Promise.resolve(ot(e))});return Promise.resolve(Promise.all(t))})})}catch(e){return Promise.reject(e)}},exports.getConfig=W,exports.getData=function(e,t){try{var n=t.ipfsGateway,r=t.pinataConfig;return Promise.resolve(Ze(e,n,r)).then(function(t){var i;function a(){if("text/html"===t.meta.data.type){var i,a=new TextDecoder,o=a.decode(u);if(!(i=s?{ciphertext:s,dataToEncryptHash:o}:JSON.parse(o)))throw new Error("encryptedAsset is null");return Promise.resolve(oe({ciphertext:i.ciphertext,dataToEncryptHash:i.dataToEncryptHash,contentHash:t.meta.data.contentBinding.hash})).then(function(e){var i=a.decode(e),o=new A.XMLParser({parseTagValue:!1,allowBooleanAttributes:!0}).parse(i),s=JSON.parse(JSON.stringify(o));s.article.orgStruct=t.orgStruct;var u=s.article.contents.image;return Array.isArray(u)||(u=[u]),Promise.resolve(Promise.all(u.map(function(e){return Ze(e.hash,n,r)}))).then(function(e){var t=new Map(e.map(function(e){return[e.meta.data.contentBinding.hash,e]}));return s.article.contents.image=u.map(function(e){return t.get(e.hash)||e}),s})})}return Promise.resolve(Ze(e,n,r))}if("1.0.0"!==t.meta.version)throw new Error("Unsupported schema version, expected 1.0.0");var o=t.meta.data.locations.filter(function(e){return"ipfs"===e.protocol||"https"===e.protocol||"s3"===e.protocol})[0].uri,s=(null==(i=t.meta.data.access)||null==(i=i["lit-protocol"])?void 0:i.ciphertext)||"",u=null,d=null!=r&&r.pinataKey&&null!=r&&r.pinataSecret?Promise.resolve($(o,"asset",r)).then(function(e){u=e}):Promise.resolve(X(o,"asset",n)).then(function(e){u=e});return d&&d.then?d.then(a):a()})}catch(e){return Promise.reject(e)}},exports.getEmbargo=ze,exports.getImageData=function(e){try{if(C().debug("url passed "+e),!e)throw new Error("image url was not passed");return Promise.resolve(fetch(e).then(function(e){return e.blob()})).then(function(e){return C().debug("image data fetched"),Promise.resolve(e.arrayBuffer()).then(function(e){var t=Buffer.from(e);return C().debug("gen buffer from image data blob"),new Uint8Array(Buffer.from(t))})})}catch(e){return Promise.reject(e)}},exports.getLicense=L,exports.getNode=it,exports.getNodesCreated=rt,exports.getParentNode=function(e){try{var t=tt();return C().debug("get parent node for "+e),Promise.resolve(it(e)).then(function(e){return C().debug("get parent token for "+e.token.toString()),Promise.resolve(t.parentOf(e.token.toString())).then(function(e){return C().debug("get token to node for "+e),Promise.resolve(ot(e))})})}catch(e){return Promise.reject(e)}},exports.getSigningWalletNonce=function(){return Promise.resolve(ge()).then(function(e){C().debug("fetching nonce for address: %s",e);var t=Pe();return Promise.resolve(t.nonces(e))})},exports.getTokenToNode=function(e){try{var t=tt();return C().debug("check gas limits"),Promise.resolve($e()).then(function(n){return C().debug("get node for token "+e),Promise.resolve(t.tokenToNode(e,{gasPrice:n}))})}catch(e){return Promise.reject(e)}},exports.getTotalSuppy=function(){try{var e=tt();return Promise.resolve(e.totalSupply())}catch(e){return Promise.reject(e)}},exports.getWalletBalance=function(){try{var e=et();return Promise.resolve(e.provider.getBalance(e.address)).then(function(e){return e})}catch(e){return Promise.reject(e)}},exports.hash=M,exports.hashData=D,exports.hashImage=bt,exports.init=J,exports.nameToRoot=function(e){try{var t=Pe();return C().debug("fetching root address for org name: %s",e),Promise.resolve(t.nameToRoot(e)).then(function(e){return C().debug("root wallet registered: %s",e),e})}catch(e){return Promise.reject(e)}},exports.processAsset=gt,exports.processBlob=function(e){try{if(!e)throw new Error("blob was not passed");var t=e.size/1048576;return C().debug("blob fetched. Size : "+t+" MB"),Promise.resolve(e.arrayBuffer()).then(function(n){var r=Buffer.from(n);C().debug("gen buffer from blob");var i=M(new Uint8Array(Buffer.from(r)));return C().debug("hash generated"),C().debug("gen cid blob"),Promise.resolve(V({body:new Uint8Array(Buffer.from(r)),name:"asset-blob"})).then(function(n){return C().debug("hash generated"),{hash:i,sizeInMb:t,blob:e,cid:n}})})}catch(e){return Promise.reject(e)}},exports.publish=ut,exports.publishArticle=function(e,t,n){try{return C().debug("breaking article to assets"),Promise.resolve(function(e){try{var t=e.contents.filter(function(e){return"image"===e.type}).map(function(t){try{return Promise.resolve(bt(t.uri)).then(function(n){return{title:t.title,description:t.description,uri:t.uri,sourceId:t.id,type:t.type,creditedSource:t.creditedSource,authority:t.authority,contentType:t.contentType,published:t.published,encrypted:!1,origin:e.metadata.origin,ownership:t.ownership,licensedFrom:t.licensedFrom,hash:n}})}catch(e){return Promise.reject(e)}});return Promise.resolve(Promise.all(t)).then(function(t){var n=[].concat(t),r=e.contents.filter(function(e){return"text"===e.type}),i=r[0],a=Tt(e,"body"in i&&i.body||"",t);return n.push({title:e.metadata.title||"",description:e.metadata.description,body:a,uri:e.metadata.uri,sourceId:e.metadata.id,type:"text",creditedSource:"",authority:e.metadata.authority,contentType:"text/html",published:e.metadata.datePublished,encrypted:!1,origin:e.metadata.origin,ownership:"owned",licensedFrom:"",hash:""}),n})}catch(e){return Promise.reject(e)}}(e)).then(function(r){var i=[],a=function(e,t){if("function"==typeof e[kt]){var n,r,i,a=function(e){try{for(;!(n=o.next()).done;)if((e=t(n.value))&&e.then){if(!Nt(e))return void e.then(a,i||(i=St.bind(null,r=new It,2)));e=e.v}r?St(r,1,e):r=e}catch(e){St(r||(r=new It),2,e)}},o=e[kt]();if(a(),o.return){var s=function(e){try{n.done||o.return()}catch(e){}return e};if(r&&r.then)return r.then(s,function(e){throw s(e)});s()}return r}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],d=0;d>> ",c),a=Dt(e,d,r),console.log("add cid to asset node >>> ",c),function(e,t){if(!t)throw new Error("cid cannot be empty");e.data.manifest.cid=t}(a,c),console.log("sign asset node....."),Promise.resolve(Pt(a.data)).then(function(e){return a=Et(a,e),console.log("upload asset meta to ipfs"),Promise.resolve(Z({data:{name:a.data.contentBinding.hash,body:a},config:{pinataKey:t.pinataKey,pinataSecret:t.pinataSecret},type:"meta"})).then(function(e){if(null==e||!e.IpfsHash)throw new Error("failed to upload asset to IPFS");s.id=a.data.contentBinding.hash,s.uri=B(e.IpfsHash),o="PUBLISH"})});if(console.log("existing asset"),!a)throw new Error("failed to construct asset node from onchain metadata");var n=a;console.log("construct new asset node to compare with prev");var i=Dt(e,d,r);return function(){if(Ut(n)!==Ut(i))return i.data.locations=n.data.locations,i.data.access=n.data.access,"text"!==e.type&&(i.data.manifest.published=(new Date).toISOString()),i.data.manifest.history||(i.data.manifest.history=[]),i.data.manifest.history.push(B(l)),console.log("sign asset node"),Promise.resolve(Pt(i.data)).then(function(e){return i=Et(i,e),console.log("upload asset meta to ipfs"),Promise.resolve(Z({data:{name:a.data.contentBinding.hash,body:a},config:{pinataKey:t.pinataKey,pinataSecret:t.pinataSecret},type:"meta"})).then(function(e){if(null==e||!e.IpfsHash)throw new Error("failed to upload asset to IPFS");s.id=a.data.contentBinding.hash,s.uri=B(e.IpfsHash),o="SET_URI",a=i})});console.log("no change"),o="NOOP"}()}();return f&&f.then?f.then(y):y()})})});return Promise.resolve(a&&a.then?a.then(function(e){return i}):i)}catch(e){return Promise.reject(e)}},exports.register=we,exports.registerOrg=yt,exports.registerRoot=Se,exports.registered=function(e){try{var t=Pe();return Promise.resolve(t.registered(e))}catch(e){return Promise.reject(e)}},exports.rootName=function(e){try{var t=Pe();return C().debug("fetching org name for the root address name: %s",e),Promise.resolve(t.rootName(e)).then(function(e){return C().debug("org registered: %s",e),e})}catch(e){return Promise.reject(e)}},exports.setAccessAuth=pt,exports.setAllowList=je,exports.setAuthorizer=Ue,exports.setEmbargo=Le,exports.setPurchaseAccess=Ge,exports.setReferenceAuth=lt,exports.setUri=st,exports.signAssetNode=Pt,exports.unRegisterRoot=Ae,exports.unregister=xe,exports.uploadToIPFS=function(e){var t=e.data,n=e.config,r=e.type;try{var i=function(){if(C().debug(JSON.stringify(l)),!l.ok)throw new Error("failed to upload to IPFS");return Promise.resolve(l.json()).then(function(e){if(C().debug(JSON.stringify(e)),null==e||!e.cid)throw new Error("failed to upload to IPFS");return e})},a=n.rpcUri,s=t.name,d=t.body,c=Buffer.from(n.creds).toString("base64"),p=new o.Headers,l=null;p.set("Authorization","Basic "+c),p.set("Accept","application/json"),C().debug("headers set"),C().debug("uploading to "+a);var y=function(){if("meta"===r){var e=new S.default;return C().debug("uploading meta"),e.append("file-upload",JSON.stringify(d)),C().debug(JSON.stringify(d)),Promise.resolve(E.default(a,{method:"POST",body:e,headers:p})).then(function(e){l=e,C().debug(JSON.stringify(l))})}var t=new S.default;C().debug("uploading file");var n=new u.Readable({read:function(){this.push(d),this.push(null)}});return C().debug("append stream"),t.append("file",n,{filename:s}),C().debug("make fetch request"),Promise.resolve(E.default(a,{method:"POST",body:t,headers:p})).then(function(e){l=e})}();return Promise.resolve(y&&y.then?y.then(i):i())}catch(e){return Promise.reject(e)}},exports.uploadToPinata=Z,exports.verifyAsset=function(t,n){try{C().debug("verify asset "+t);var r={signatureVerified:!1,contentBindingVerified:!1,signer:"",root:""},i=JSON.stringify(n.data);C().debug("hashing metadata");var a=D(i);C().debug("compare asset signature message and calculated message "+a),a===n.signature.message&&(C().debug("message verified"),r.signatureVerified=!0),C().debug("compare assetId and contentBinding hash "+t),t===n.data.contentBinding.hash&&(C().debug("contentBinding verified"),r.contentBindingVerified=!0);var o=e.utils.verifyMessage(a,n.signature.signature);return C().debug("signer address "+o),r.signer=o,Promise.resolve(Ee(o)).then(function(e){return C().debug("root address "+e),r.root=e,r})}catch(e){return Promise.reject(e)}},exports.version=k,exports.whoIs=Ee; //# sourceMappingURL=index.cjs.map