@zk-email/sdk 0.0.39 → 0.0.40
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains');var w=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(w||{});var L="Ov23li0KABFCUsxBEQkn";function v(s,e=L){let t=encodeURIComponent(s);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(s){try{let e=await s.getToken();if(e||(await s.onTokenExpired(),e=await s.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var P="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",y,f=new Promise(s=>{y=s;});if(typeof window>"u"||typeof Deno<"u")console.warn("Relayer utils won't work when used server side with bundlers, Next.js etc."),import('@dimidumo/relayer-utils/node').then(s=>{y(s);}).catch(s=>console.log("failed to init WASM on node: ",s));else {console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async s=>{await s.default(),y(s);}).catch(s=>{console.log("Failed to init WASM: ",s);});}catch{}}async function m(s,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":P,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(s,r),n=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${n}`);return n}catch(r){throw console.error("POST Error:",r),r}}async function _(s,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":P,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(s,r),n=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${n}`);return n}catch(r){throw console.error("PATCH Error:",r),r}}async function u(s,e,t){try{let r=s;if(e){let n=new URLSearchParams;Object.entries(e).forEach(([i,a])=>{a&&n.append(i,String(a));}),n.size>0&&(r+=`?${n.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":P,...t?{Authorization:await g(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(s){try{return await(await f).parseEmail(s)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function S(s,e,t=!1){let r=await B(s);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let o=r.canonicalized_body;if(e.shaPrecomputeSelector){let a=o.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);o=a;}let n=r.canonicalized_header;return await T(n,o,e),await Promise.all(e.decomposedRegexes.map(a=>D(o,n,a,t)))}async function T(s,e,t){let r=await f,o=new TextEncoder,n=o.encode(s);if((await r.sha256Pad(n,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let a=o.encode(e),c=(e.length+63+65)/64*64,l=Math.max(c,t.emailBodyMaxLength),d=(await r.sha256Pad(a,l)).get("messageLength");await r.sha256Pad(a,l);if(d>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function D(s,e,t,r=!1){let o={parts:t.parts.map(d=>({is_public:"isPublic"in d?d.isPublic:d.is_public,regex_def:"regexDef"in d?d.regexDef:d.regex_def}))},n;if(t.location==="body")n=s;else if(t.location==="header")n=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length,a=await f,c=a.extractSubstr(n,o,!1);if(c[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return r?a.extractSubstr(n,o,r):c}async function x(s,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},n=await f,i=e.map(c=>({...c,parts:c.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),a=await n.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(s,i,t,o);return JSON.stringify(Object.fromEntries(a))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function E(s,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([s],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var h=class s{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof p))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await s.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){}static async getProofById(e,t){let r;try{r=await u(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let o=this.responseToProofProps(r),n=await p.getBlueprintById(r.blueprint_id,t);return new s(n,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData}}};var b=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof p))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){let t=await this.generateProofRequest(e);for(;![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await x(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let o;try{let i={blueprint_id:t,input:r};o=await m(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let n=h.responseToProofProps(o);return new h(this.blueprint,n)}};var I=(e=>(e.Circom="circom",e))(I||{}),k=(n=>(n[n.None=0]="None",n[n.Draft=1]="Draft",n[n.InProgress=2]="InProgress",n[n.Done=3]="Done",n[n.Failed=4]="Failed",n))(k||{});var F="0x4200000000000000000000000000000000000006",$=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=viem.createPublicClient({chain:chains.baseSepolia,transport:viem.http()});async function R(){try{return await H.readContract({address:F,abi:$,functionName:"totalSupply"})}catch(s){throw console.error("Error fetching WETH total supply:",s),s}}var p=class s{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await u(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let n=this.responseToBlueprintProps(o);return new s(n,t,r)}static async getBlueprintBySlug(e,t,r){let o=e.split("@");if(!o||!(o.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let n=o.pop().replace("v","");if(e=encodeURIComponent(o.join("")),!n)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i;try{let l=`${t}/blueprint/by-slug/${e}/${n}`;i=await u(l);}catch(l){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",l),l}let a=this.responseToBlueprintProps(i);return new s(a,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=s.blueprintPropsToRequest(this.props),t;try{t=await m(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=s.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=s.blueprintPropsToRequest(e),r;try{r=await m(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=s.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},n;try{n=await u(`${e}/blueprint`,o,r);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return n.blueprints?n.blueprints.map(i=>{let a=s.responseToBlueprintProps(i);return new s(a,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,r]of Object.entries(e)){let o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o);}}createProver(){return new b(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=s.blueprintPropsToRequest(e),r;try{r=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=s.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=s.responseToBlueprintProps(t);return new s(r,this.baseUrl,this.auth)})}};var Le=s=>{let e=s?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!s&&!s.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new p(t,e,s.auth)},async getBlueprint(t){return p.getBlueprintBySlug(t,e,s?.auth)},async getBlueprintById(t){return p.getBlueprintById(t,e,s?.auth)},async listBlueprints(t){return p.listBlueprints(e,t,s?.auth)},async getProof(t){return h.getProofById(t,e)}}};
|
2
|
-
exports.Blueprint=
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains');var w=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(w||{});var L="Ov23li0KABFCUsxBEQkn";function v(n,e=L){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var P="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",y,f=new Promise(n=>{y=n;});if(typeof window>"u"||typeof Deno<"u")console.warn("Relayer utils won't work when used server side with bundlers, Next.js etc."),import('@dimidumo/relayer-utils/node').then(n=>{y(n);}).catch(n=>console.log("failed to init WASM on node: ",n));else {console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),y(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}}async function m(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":P,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),i=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${i}`);return i}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":P,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),i=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${i}`);return i}catch(r){throw console.error("PATCH Error:",r),r}}async function c(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let i=new URLSearchParams;Object.entries(e).forEach(([a,p])=>{p&&i.append(a,String(p));}),i.size>0&&(r+=`?${i.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":P,...o?{Authorization:o}:{}}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return await s.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(n){try{return await(await f).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function T(n,e,t=!1){let o=await B(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.canonicalized_body;if(e.shaPrecomputeSelector){let a=r.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=a;}let s=o.canonicalized_header;return await S(s,r,e),await Promise.all(e.decomposedRegexes.map(a=>k(r,s,a,t)))}async function S(n,e,t){let o=await f,r=new TextEncoder,s=r.encode(n);if((await o.sha256Pad(s,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let a=r.encode(e),p=(e.length+63+65)/64*64,l=Math.max(p,t.emailBodyMaxLength),d=(await o.sha256Pad(a,l)).get("messageLength");await o.sha256Pad(a,l);if(d>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function k(n,e,t,o=!1){let r={parts:t.parts.map(d=>({is_public:"isPublic"in d?d.isPublic:d.is_public,regex_def:"regexDef"in d?d.regexDef:d.regex_def}))},s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length,a=await f,p=a.extractSubstr(s,r,!1);if(p[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?a.extractSubstr(s,r,o):p}async function x(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector},s=await f,i=e.map(p=>({...p,parts:p.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),a=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,r);return JSON.stringify(Object.fromEntries(a))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}function E(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}var h=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof u))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await c(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(o){throw console.error("Failed to start download of ZKeys: ",o),o}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}let e;try{e=await c(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await n.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){}static async getProofById(e,t){let o;try{o=await c(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let r=this.responseToProofProps(o),s=await u.getBlueprintById(o.blueprint_id,t);return new n(s,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData}}};var b=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof u))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){let t=await this.generateProofRequest(e);for(;![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let o;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),o=await x(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let r;try{let i={blueprint_id:t,input:o};r=await m(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let s=h.responseToProofProps(r);return new h(this.blueprint,s)}};var I=(e=>(e.Circom="circom",e))(I||{}),D=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(D||{});var F="0x4200000000000000000000000000000000000006",$=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=viem.createPublicClient({chain:chains.baseSepolia,transport:viem.http()});async function R(){try{return await H.readContract({address:F,abi:$,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var u=class n{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await c(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let s=this.responseToBlueprintProps(r);return new n(s,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let s=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!s)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i;try{let l=`${t}/blueprint/by-slug/${e}/${s}`;i=await c(l);}catch(l){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",l),l}let a=this.responseToBlueprintProps(i);return new n(a,t,o)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await m(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),o;try{o=await m(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,o){let r={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await c(`${e}/blueprint`,r,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return s.blueprints?s.blueprints.map(i=>{let a=n.responseToBlueprintProps(i);return new n(a,e,o)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await c(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await c(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(){return new b(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),o;try{o=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await c(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let o=n.responseToBlueprintProps(t);return new n(o,this.baseUrl,this.auth)})}};var Le=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new u(t,e,n.auth)},async getBlueprint(t){return u.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return u.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return u.listBlueprints(e,t,n?.auth)},async getProof(t){return h.getProofById(t,e)}}};
|
2
|
+
exports.Blueprint=u;exports.Proof=h;exports.ProofStatus=w;exports.Status=D;exports.ZkFramework=I;exports.default=Le;exports.generateProofInputs=x;exports.getLoginWithGithubUrl=v;exports.parseEmail=B;exports.startJsonFileDownload=E;exports.testBlueprint=T;exports.testDecomposedRegex=k;//# sourceMappingURL=index.js.map
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","utils","encoder","headerData","bodyData","bodyShaLength","maxShaBytes","bodyLength","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","privateResult","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","r","newProof","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","requestOptions","status","urls","result","cloned","src_default","sdkOptions"],"mappings":"6HAGO,IAAKA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MrB,CAAAA,CAAAA,CAASiC,GAAY,IAAI,CACrE,EACA,MAAM,gBAAA,CAAiBlC,EAAgC,CACrD,OAAOJ,CAAU,CAAA,gBAAA,CAAiBI,EAAIC,CAASiC,CAAAA,CAAAA,EAAY,IAAI,CACjE,CAAA,CACA,MAAM,cAAe7B,CAAAA,CAAAA,CAAuD,CAC1E,OAAOT,EAAU,cAAeK,CAAAA,CAAAA,CAASI,EAAS6B,CAAY,EAAA,IAAI,CACpE,CACA,CAAA,MAAM,SAASlC,CAA4B,CAAA,CACzC,OAAOP,CAAM,CAAA,YAAA,CAAaO,EAAIC,CAAO,CACvC,CACF,CACF","file":"index.js","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// TODO: comment back in\n// @ts-ignore\nif (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\n // if (false) {\n console.warn(\"Relayer utils won't work when used server side with bundlers, Next.js etc.\");\n import(\"@dimidumo/relayer-utils/node\")\n .then((rl) => {\n relayerUtilsResolver(rl);\n })\n .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.canonicalized_body;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalized_header;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n const utils = await relayerUtils;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await utils.sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await utils.sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n const res = await utils.sha256Pad(bodyData, maxShaBytes);\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): { proofData: string; publicData: string } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return { proofData: this.props.proofData!, publicData: this.props.publicData! };\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n const proof = await this.generateProofRequest(eml);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n };\n};\n"]}
|
1
|
+
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","authToken","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","utils","encoder","headerData","bodyData","bodyShaLength","maxShaBytes","bodyLength","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","privateResult","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","newProof","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","requestOptions","status","urls","result","cloned","src_default","sdkOptions"],"mappings":"6HAGO,IAAKA,OACVA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,IAAA,UACAA,CAAAA,CAAAA,CAAAA,CAAAA,YAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,eACAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,QAAA,CAJUA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,ECAZ,IAAMC,CAAmB,CAAA,sBAAA,CAIlB,SAASC,CACdC,CAAAA,CAAAA,CACAC,EAAiBH,CACT,CAAA,CACR,IAAMI,CAAAA,CAAQ,mBAAmBF,C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,CAAgC,CAAA,CACrD,OAAOH,CAAU,CAAA,gBAAA,CAAiBG,EAAIC,CAASiC,CAAAA,CAAAA,EAAY,IAAI,CACjE,CAAA,CACA,MAAM,cAAe7B,CAAAA,CAAAA,CAAuD,CAC1E,OAAOR,EAAU,cAAeI,CAAAA,CAAAA,CAASI,EAAS6B,CAAY,EAAA,IAAI,CACpE,CACA,CAAA,MAAM,SAASlC,CAA4B,CAAA,CACzC,OAAON,CAAM,CAAA,YAAA,CAAaM,EAAIC,CAAO,CACvC,CACF,CACF","file":"index.js","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// TODO: comment back in\n// @ts-ignore\nif (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\n // if (false) {\n console.warn(\"Relayer utils won't work when used server side with bundlers, Next.js etc.\");\n import(\"@dimidumo/relayer-utils/node\")\n .then((rl) => {\n relayerUtilsResolver(rl);\n })\n .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.canonicalized_body;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalized_header;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n const utils = await relayerUtils;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await utils.sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await utils.sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n const res = await utils.sha256Pad(bodyData, maxShaBytes);\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): { proofData: string; publicData: string } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return { proofData: this.props.proofData!, publicData: this.props.publicData! };\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n const proof = await this.generateProofRequest(eml);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitNewVersionDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/ in listBlueprints: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n };\n};\n"]}
|
package/dist/index.mjs
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
import {createPublicClient,http}from'viem';import {baseSepolia}from'viem/chains';var w=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(w||{});var L="Ov23li0KABFCUsxBEQkn";function v(s,e=L){let t=encodeURIComponent(s);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(s){try{let e=await s.getToken();if(e||(await s.onTokenExpired(),e=await s.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var P="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",y,f=new Promise(s=>{y=s;});if(typeof window>"u"||typeof Deno<"u")console.warn("Relayer utils won't work when used server side with bundlers, Next.js etc."),import('@dimidumo/relayer-utils/node').then(s=>{y(s);}).catch(s=>console.log("failed to init WASM on node: ",s));else {console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async s=>{await s.default(),y(s);}).catch(s=>{console.log("Failed to init WASM: ",s);});}catch{}}async function m(s,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":P,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(s,r),n=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${n}`);return n}catch(r){throw console.error("POST Error:",r),r}}async function _(s,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":P,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(s,r),n=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${n}`);return n}catch(r){throw console.error("PATCH Error:",r),r}}async function u(s,e,t){try{let r=s;if(e){let n=new URLSearchParams;Object.entries(e).forEach(([i,a])=>{a&&n.append(i,String(a));}),n.size>0&&(r+=`?${n.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":P,...t?{Authorization:await g(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(s){try{return await(await f).parseEmail(s)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function S(s,e,t=!1){let r=await B(s);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let o=r.canonicalized_body;if(e.shaPrecomputeSelector){let a=o.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);o=a;}let n=r.canonicalized_header;return await T(n,o,e),await Promise.all(e.decomposedRegexes.map(a=>D(o,n,a,t)))}async function T(s,e,t){let r=await f,o=new TextEncoder,n=o.encode(s);if((await r.sha256Pad(n,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let a=o.encode(e),c=(e.length+63+65)/64*64,l=Math.max(c,t.emailBodyMaxLength),d=(await r.sha256Pad(a,l)).get("messageLength");await r.sha256Pad(a,l);if(d>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function D(s,e,t,r=!1){let o={parts:t.parts.map(d=>({is_public:"isPublic"in d?d.isPublic:d.is_public,regex_def:"regexDef"in d?d.regexDef:d.regex_def}))},n;if(t.location==="body")n=s;else if(t.location==="header")n=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length,a=await f,c=a.extractSubstr(n,o,!1);if(c[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return r?a.extractSubstr(n,o,r):c}async function x(s,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},n=await f,i=e.map(c=>({...c,parts:c.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),a=await n.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(s,i,t,o);return JSON.stringify(Object.fromEntries(a))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function E(s,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([s],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var h=class s{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof p))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await s.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){}static async getProofById(e,t){let r;try{r=await u(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let o=this.responseToProofProps(r),n=await p.getBlueprintById(r.blueprint_id,t);return new s(n,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData}}};var b=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof p))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){let t=await this.generateProofRequest(e);for(;![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await x(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let o;try{let i={blueprint_id:t,input:r};o=await m(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let n=h.responseToProofProps(o);return new h(this.blueprint,n)}};var I=(e=>(e.Circom="circom",e))(I||{}),k=(n=>(n[n.None=0]="None",n[n.Draft=1]="Draft",n[n.InProgress=2]="InProgress",n[n.Done=3]="Done",n[n.Failed=4]="Failed",n))(k||{});var F="0x4200000000000000000000000000000000000006",$=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=createPublicClient({chain:baseSepolia,transport:http()});async function R(){try{return await H.readContract({address:F,abi:$,functionName:"totalSupply"})}catch(s){throw console.error("Error fetching WETH total supply:",s),s}}var p=class s{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await u(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let n=this.responseToBlueprintProps(o);return new s(n,t,r)}static async getBlueprintBySlug(e,t,r){let o=e.split("@");if(!o||!(o.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let n=o.pop().replace("v","");if(e=encodeURIComponent(o.join("")),!n)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i;try{let l=`${t}/blueprint/by-slug/${e}/${n}`;i=await u(l);}catch(l){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",l),l}let a=this.responseToBlueprintProps(i);return new s(a,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=s.blueprintPropsToRequest(this.props),t;try{t=await m(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=s.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=s.blueprintPropsToRequest(e),r;try{r=await m(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=s.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},n;try{n=await u(`${e}/blueprint`,o,r);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return n.blueprints?n.blueprints.map(i=>{let a=s.responseToBlueprintProps(i);return new s(a,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,r]of Object.entries(e)){let o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o);}}createProver(){return new b(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=s.blueprintPropsToRequest(e),r;try{r=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=s.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=s.responseToBlueprintProps(t);return new s(r,this.baseUrl,this.auth)})}};var Le=s=>{let e=s?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!s&&!s.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new p(t,e,s.auth)},async getBlueprint(t){return p.getBlueprintBySlug(t,e,s?.auth)},async getBlueprintById(t){return p.getBlueprintById(t,e,s?.auth)},async listBlueprints(t){return p.listBlueprints(e,t,s?.auth)},async getProof(t){return h.getProofById(t,e)}}};
|
2
|
-
export{
|
1
|
+
import {createPublicClient,http}from'viem';import {baseSepolia}from'viem/chains';var w=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(w||{});var L="Ov23li0KABFCUsxBEQkn";function v(n,e=L){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var P="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",y,f=new Promise(n=>{y=n;});if(typeof window>"u"||typeof Deno<"u")console.warn("Relayer utils won't work when used server side with bundlers, Next.js etc."),import('@dimidumo/relayer-utils/node').then(n=>{y(n);}).catch(n=>console.log("failed to init WASM on node: ",n));else {console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),y(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}}async function m(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":P,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),i=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${i}`);return i}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":P,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),i=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${i}`);return i}catch(r){throw console.error("PATCH Error:",r),r}}async function c(n,e,t){let o=null;if(t)try{o=await g(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let i=new URLSearchParams;Object.entries(e).forEach(([a,p])=>{p&&i.append(a,String(p));}),i.size>0&&(r+=`?${i.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":P,...o?{Authorization:o}:{}}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return await s.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(n){try{return await(await f).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function T(n,e,t=!1){let o=await B(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.canonicalized_body;if(e.shaPrecomputeSelector){let a=r.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=a;}let s=o.canonicalized_header;return await S(s,r,e),await Promise.all(e.decomposedRegexes.map(a=>k(r,s,a,t)))}async function S(n,e,t){let o=await f,r=new TextEncoder,s=r.encode(n);if((await o.sha256Pad(s,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let a=r.encode(e),p=(e.length+63+65)/64*64,l=Math.max(p,t.emailBodyMaxLength),d=(await o.sha256Pad(a,l)).get("messageLength");await o.sha256Pad(a,l);if(d>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function k(n,e,t,o=!1){let r={parts:t.parts.map(d=>({is_public:"isPublic"in d?d.isPublic:d.is_public,regex_def:"regexDef"in d?d.regexDef:d.regex_def}))},s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length,a=await f,p=a.extractSubstr(s,r,!1);if(p[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?a.extractSubstr(s,r,o):p}async function x(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector},s=await f,i=e.map(p=>({...p,parts:p.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),a=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,r);return JSON.stringify(Object.fromEntries(a))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}function E(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}var h=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof u))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await c(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(o){throw console.error("Failed to start download of ZKeys: ",o),o}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}let e;try{e=await c(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await n.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){}static async getProofById(e,t){let o;try{o=await c(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let r=this.responseToProofProps(o),s=await u.getBlueprintById(o.blueprint_id,t);return new n(s,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData}}};var b=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof u))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){let t=await this.generateProofRequest(e);for(;![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let o;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),o=await x(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let r;try{let i={blueprint_id:t,input:o};r=await m(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let s=h.responseToProofProps(r);return new h(this.blueprint,s)}};var I=(e=>(e.Circom="circom",e))(I||{}),D=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(D||{});var F="0x4200000000000000000000000000000000000006",$=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=createPublicClient({chain:baseSepolia,transport:http()});async function R(){try{return await H.readContract({address:F,abi:$,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var u=class n{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await c(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let s=this.responseToBlueprintProps(r);return new n(s,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let s=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!s)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i;try{let l=`${t}/blueprint/by-slug/${e}/${s}`;i=await c(l);}catch(l){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",l),l}let a=this.responseToBlueprintProps(i);return new n(a,t,o)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await m(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),o;try{o=await m(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,o){let r={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await c(`${e}/blueprint`,r,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return s.blueprints?s.blueprints.map(i=>{let a=n.responseToBlueprintProps(i);return new n(a,e,o)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await m(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await c(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await c(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(){return new b(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),o;try{o=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await c(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let o=n.responseToBlueprintProps(t);return new n(o,this.baseUrl,this.auth)})}};var Le=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new u(t,e,n.auth)},async getBlueprint(t){return u.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return u.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return u.listBlueprints(e,t,n?.auth)},async getProof(t){return h.getProofById(t,e)}}};
|
2
|
+
export{u as Blueprint,h as Proof,w as ProofStatus,D as Status,I as ZkFramework,Le as default,x as generateProofInputs,v as getLoginWithGithubUrl,B as parseEmail,E as startJsonFileDownload,T as testBlueprint,k as testDecomposedRegex};//# sourceMappingURL=index.mjs.map
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","utils","encoder","headerData","bodyData","bodyShaLength","maxShaBytes","bodyLength","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","privateResult","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","r","newProof","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","requestOptions","status","urls","result","cloned","src_default","sdkOptions"],"mappings":"iFAGO,IAAKA,OACVA,CAAA,CAAA,CAAA,CAAA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,IAAI,CACrE,EACA,MAAM,gBAAA,CAAiBlC,EAAgC,CACrD,OAAOJ,CAAU,CAAA,gBAAA,CAAiBI,EAAIC,CAASiC,CAAAA,CAAAA,EAAY,IAAI,CACjE,CAAA,CACA,MAAM,cAAe7B,CAAAA,CAAAA,CAAuD,CAC1E,OAAOT,EAAU,cAAeK,CAAAA,CAAAA,CAASI,EAAS6B,CAAY,EAAA,IAAI,CACpE,CACA,CAAA,MAAM,SAASlC,CAA4B,CAAA,CACzC,OAAOP,CAAM,CAAA,YAAA,CAAaO,EAAIC,CAAO,CACvC,CACF,CACF","file":"index.mjs","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// TODO: comment back in\n// @ts-ignore\nif (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\n // if (false) {\n console.warn(\"Relayer utils won't work when used server side with bundlers, Next.js etc.\");\n import(\"@dimidumo/relayer-utils/node\")\n .then((rl) => {\n relayerUtilsResolver(rl);\n })\n .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.canonicalized_body;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalized_header;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n const utils = await relayerUtils;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await utils.sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await utils.sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n const res = await utils.sha256Pad(bodyData, maxShaBytes);\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): { proofData: string; publicData: string } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return { proofData: this.props.proofData!, publicData: this.props.publicData! };\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n const proof = await this.generateProofRequest(eml);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n };\n};\n"]}
|
1
|
+
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","authToken","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","utils","encoder","headerData","bodyData","bodyShaLength","maxShaBytes","bodyLength","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","privateResult","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","newProof","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","requestOptions","status","urls","result","cloned","src_default","sdkOptions"],"mappings":"iFAGO,IAAKA,OACVA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,IAAA,UACAA,CAAAA,CAAAA,CAAAA,CAAAA,YAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,eACAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,QAAA,CAJUA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,ECAZ,IAAMC,CAAmB,CAAA,sBAAA,CAIlB,SAASC,CACdC,CAAAA,CAAAA,CACAC,EAAiBH,CACT,CAAA,CACR,IAAMI,CAAAA,CAAQ,mBAAmBF,CAAW,CAAA,CAC5C,OAAO,CAAs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AU,CAAA,gBAAA,CAAiBG,EAAIC,CAASiC,CAAAA,CAAAA,EAAY,IAAI,CACjE,CAAA,CACA,MAAM,cAAe7B,CAAAA,CAAAA,CAAuD,CAC1E,OAAOR,EAAU,cAAeI,CAAAA,CAAAA,CAASI,EAAS6B,CAAY,EAAA,IAAI,CACpE,CACA,CAAA,MAAM,SAASlC,CAA4B,CAAA,CACzC,OAAON,CAAM,CAAA,YAAA,CAAaM,EAAIC,CAAO,CACvC,CACF,CACF","file":"index.mjs","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n} from \"./types\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// TODO: comment back in\n// @ts-ignore\nif (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\n // if (false) {\n console.warn(\"Relayer utils won't work when used server side with bundlers, Next.js etc.\");\n import(\"@dimidumo/relayer-utils/node\")\n .then((rl) => {\n relayerUtilsResolver(rl);\n })\n .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.canonicalized_body;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalized_header;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n const utils = await relayerUtils;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await utils.sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await utils.sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n const res = await utils.sha256Pad(bodyData, maxShaBytes);\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): { proofData: string; publicData: string } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return { proofData: this.props.proofData!, publicData: this.props.publicData! };\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n const proof = await this.generateProofRequest(eml);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitNewVersionDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/ in listBlueprints: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n };\n};\n"]}
|