@zk-email/sdk 0.0.85-9 → 0.0.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -529,11 +529,19 @@ type ParsedEmail = {
529
529
  };
530
530
 
531
531
  declare function startJsonFileDownload(json: string, name?: string): void;
532
+ declare function getDKIMSelector(emlContent: string): string | null;
532
533
 
533
534
  declare function parseEmail(eml: string): Promise<ParsedEmail>;
534
535
  declare function testBlueprint(eml: string, blueprint: BlueprintProps, revealPrivate?: boolean): Promise<string[][]>;
535
536
  declare function testDecomposedRegex(body: string, header: string, decomposedRegex: DecomposedRegex | DecomposedRegexJson, revealPrivate?: boolean): Promise<string[]>;
536
537
  declare function generateProofInputs(eml: string, decomposedRegexes: DecomposedRegex[], externalInputs: ExternalInputInput[], params: GenerateProofInputsParams): Promise<string>;
538
+ declare function getMaxEmailBodyLength(emlContent: string, shaPrecomputeSelector: string): Promise<number>;
539
+ declare function extractEMLDetails(emlContent: string): Promise<{
540
+ senderDomain: string | null;
541
+ headerLength: number;
542
+ emailQuery: string;
543
+ emailBodyMaxLength: number;
544
+ }>;
537
545
 
538
546
  declare function getLoginWithGithubUrl(callbackUrl: string, githubClientId?: string): string;
539
547
 
@@ -546,4 +554,4 @@ declare const _default: (sdkOptions?: SdkOptions) => {
546
554
  getStarredBlueprints(): Promise<string[]>;
547
555
  };
548
556
 
549
- export { type Auth, Blueprint, type BlueprintProps, type BlueprintRequest, type BlueprintResponse, type DecomposedRegex, type DecomposedRegexJson, type DecomposedRegexPart, type DecomposedRegexPartJson, type DecomposedRegexPartResponse, type DecomposedRegexResponse, type DownloadUrls, type ExternalInput, type ExternalInputInput, type ExternalInputResponse, type GenerateProofInputsParams, type GenerateProofInputsParamsInternal, type ListBlueprintsOptions, type ListBlueprintsOptionsRequest, type ParsedEmail, Proof, type ProofData, type ProofProps, type ProofRequest, type ProofResponse, ProofStatus, type ProverOptions, type ServerDate, Status, type ValidationErrors, type VerifierContract, ZkFramework, _default as default, generateProofInputs, getLoginWithGithubUrl, parseEmail, startJsonFileDownload, testBlueprint, testDecomposedRegex };
557
+ export { type Auth, Blueprint, type BlueprintProps, type BlueprintRequest, type BlueprintResponse, type DecomposedRegex, type DecomposedRegexJson, type DecomposedRegexPart, type DecomposedRegexPartJson, type DecomposedRegexPartResponse, type DecomposedRegexResponse, type DownloadUrls, type ExternalInput, type ExternalInputInput, type ExternalInputResponse, type GenerateProofInputsParams, type GenerateProofInputsParamsInternal, type ListBlueprintsOptions, type ListBlueprintsOptionsRequest, type ParsedEmail, Proof, type ProofData, type ProofProps, type ProofRequest, type ProofResponse, ProofStatus, type ProverOptions, type ServerDate, Status, type ValidationErrors, type VerifierContract, ZkFramework, _default as default, extractEMLDetails, generateProofInputs, getDKIMSelector, getLoginWithGithubUrl, getMaxEmailBodyLength, parseEmail, startJsonFileDownload, testBlueprint, testDecomposedRegex };
package/dist/index.d.ts CHANGED
@@ -529,11 +529,19 @@ type ParsedEmail = {
529
529
  };
530
530
 
531
531
  declare function startJsonFileDownload(json: string, name?: string): void;
532
+ declare function getDKIMSelector(emlContent: string): string | null;
532
533
 
533
534
  declare function parseEmail(eml: string): Promise<ParsedEmail>;
534
535
  declare function testBlueprint(eml: string, blueprint: BlueprintProps, revealPrivate?: boolean): Promise<string[][]>;
535
536
  declare function testDecomposedRegex(body: string, header: string, decomposedRegex: DecomposedRegex | DecomposedRegexJson, revealPrivate?: boolean): Promise<string[]>;
536
537
  declare function generateProofInputs(eml: string, decomposedRegexes: DecomposedRegex[], externalInputs: ExternalInputInput[], params: GenerateProofInputsParams): Promise<string>;
538
+ declare function getMaxEmailBodyLength(emlContent: string, shaPrecomputeSelector: string): Promise<number>;
539
+ declare function extractEMLDetails(emlContent: string): Promise<{
540
+ senderDomain: string | null;
541
+ headerLength: number;
542
+ emailQuery: string;
543
+ emailBodyMaxLength: number;
544
+ }>;
537
545
 
538
546
  declare function getLoginWithGithubUrl(callbackUrl: string, githubClientId?: string): string;
539
547
 
@@ -546,4 +554,4 @@ declare const _default: (sdkOptions?: SdkOptions) => {
546
554
  getStarredBlueprints(): Promise<string[]>;
547
555
  };
548
556
 
549
- export { type Auth, Blueprint, type BlueprintProps, type BlueprintRequest, type BlueprintResponse, type DecomposedRegex, type DecomposedRegexJson, type DecomposedRegexPart, type DecomposedRegexPartJson, type DecomposedRegexPartResponse, type DecomposedRegexResponse, type DownloadUrls, type ExternalInput, type ExternalInputInput, type ExternalInputResponse, type GenerateProofInputsParams, type GenerateProofInputsParamsInternal, type ListBlueprintsOptions, type ListBlueprintsOptionsRequest, type ParsedEmail, Proof, type ProofData, type ProofProps, type ProofRequest, type ProofResponse, ProofStatus, type ProverOptions, type ServerDate, Status, type ValidationErrors, type VerifierContract, ZkFramework, _default as default, generateProofInputs, getLoginWithGithubUrl, parseEmail, startJsonFileDownload, testBlueprint, testDecomposedRegex };
557
+ export { type Auth, Blueprint, type BlueprintProps, type BlueprintRequest, type BlueprintResponse, type DecomposedRegex, type DecomposedRegexJson, type DecomposedRegexPart, type DecomposedRegexPartJson, type DecomposedRegexPartResponse, type DecomposedRegexResponse, type DownloadUrls, type ExternalInput, type ExternalInputInput, type ExternalInputResponse, type GenerateProofInputsParams, type GenerateProofInputsParamsInternal, type ListBlueprintsOptions, type ListBlueprintsOptionsRequest, type ParsedEmail, Proof, type ProofData, type ProofProps, type ProofRequest, type ProofResponse, ProofStatus, type ProverOptions, type ServerDate, Status, type ValidationErrors, type VerifierContract, ZkFramework, _default as default, extractEMLDetails, generateProofInputs, getDKIMSelector, getLoginWithGithubUrl, getMaxEmailBodyLength, parseEmail, startJsonFileDownload, testBlueprint, testDecomposedRegex };
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains'),relayerUtils=require('@zk-email/relayer-utils'),zod=require('zod');function F(n){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${n}]`,internalType:`uint256[${n}]`}],outputs:[],stateMutability:"view"}]}async function f(n){if(!n.blueprint.props.verifierContract?.chain||!n.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!n.props.proofData||!n.props.publicOutputs)throw new Error("No proof data generated yet");let e=viem.createPublicClient({chain:chains.base,transport:viem.http("https://sepolia.base.org")}),t=n.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],n.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",n.blueprint.props.verifierContract.address);try{await e.readContract({address:n.blueprint.props.verifierContract.address,abi:F(n.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var x=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(x||{});var U="Ov23li0KABFCUsxBEQkn";function O(n,e=U){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 b="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",B;new Promise(n=>{B=n;});relayerUtils.init().then(()=>{B(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function h(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":b,...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 D(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":b,...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,u])=>{u&&i.append(a,String(u));}),i.size>0&&(r+=`?${i.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":b,...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 w(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:"DELETE",headers:{"Content-Type":"application/json","x-api-key":b,...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("DELETE Error:",r),r}}function H(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 m=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof d))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(){await f(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}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 d.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,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,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,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var I,y=new Promise(n=>{I=n;});relayerUtils.init().then(()=>{I(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function R(n){try{return await y,await relayerUtils.parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function z(n,e,t=!1){let o=await R(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;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.canonicalizedHeader;return await G(s,r,e),await Promise.all(e.decomposedRegexes.map(a=>v(r,s,a,t)))}async function G(n,e,t){await y;let o=new TextEncoder,r=o.encode(n);if((await relayerUtils.sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let i=o.encode(e),a=(e.length+63+65)/64*64,u=Math.max(a,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(i,u)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function v(n,e,t,o=!1){let r={parts:t.parts.map(p=>({is_public:"isPublic"in p?p.isPublic:p.is_public,regex_def:"regexDef"in p?p.regexDef:p.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;await y;let a=relayerUtils.extractSubstr(s,r,!1);if(a[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?relayerUtils.extractSubstr(s,r,o):a}async function _(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await y;let s=e.map(a=>({...a,parts:a.parts.map(u=>({is_public:u.isPublic||!!u.is_public,regex_def:u.regexDef||!!u.regex_def}))})),i=await relayerUtils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,s,t,r);return JSON.stringify(Object.fromEntries(i))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var P=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof d))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e,t=[]){let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);let r;try{let a={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 _(e,this.blueprint.props.decomposedRegexes,t,a);}catch(a){throw console.error("Failed to generate inputs for proof"),a}console.log("got proof input");let s;try{let a={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((u,p)=>({...u,[p.name]:p.value}),{})};s=await h(`${this.blueprint.baseUrl}/proof`,a);}catch(a){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",a),a}let i=m.responseToProofProps(s);return new m(this.blueprint,i)}};var J=(e=>(e.Circom="circom",e))(J||{}),S=(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))(S||{});var T=zod.z.object({title:zod.z.string().min(1,{message:"Title must be at least 1 characters."}),circuitName:zod.z.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/,"Invalid name, must start with a letter, digit, or underscore, and can only contain letters, digits or underscores."),description:zod.z.string().min(1),emailQuery:zod.z.string(),ignoreBodyHashCheck:zod.z.boolean(),shaPrecomputeSelector:zod.z.string().transform(n=>n.replace(/(?<!\\)"/g,'\\"')).optional(),senderDomain:zod.z.string().refine(n=>!n.includes("@"),{message:"Sender domain should not contain '@' symbol, only the domain"}),emailBodyMaxLength:zod.z.coerce.number().transform((n,e)=>(n%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),n>1e4&&e.addIssue({code:"custom",message:"Must be less than or equal to 10000"}),n)),emailHeaderMaxLength:zod.z.coerce.number().transform((n,e)=>(n%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),n)).default(1024),decomposedRegexes:zod.z.array(zod.z.object({name:zod.z.string().min(1).transform((n,e)=>n.includes(" ")?(e.addIssue({code:"custom",message:"Warning: Name contains spaces or dashes. They will be replaced with underscores."}),n.replace(/[ -]/g,"_")):n),maxLength:zod.z.coerce.number().positive().default(64),location:zod.z.string().regex(/(body)|(header)/),parts:zod.z.string().transform((n,e)=>{if(!n.includes("isPublic"))return e.addIssue({code:"custom",message:'Each parts config must include at least one "isPublic" field, and at least one thats true and one thats false. Please add it for now until we fix this requirement.'}),zod.z.NEVER;let t;try{t=JSON.parse(n);}catch{return e.addIssue({code:"custom",message:"Invalid JSON"}),zod.z.NEVER}if(!Array.isArray(t))return e.addIssue({code:"custom",message:"Parts must be an array"}),zod.z.NEVER;for(let o=0;o<t.length;o++){let r=t[o];if(typeof r!="object"||r===null)return e.addIssue({code:"custom",message:`Part ${o} must be an object`}),zod.z.NEVER;if(!("isPublic"in r)||typeof r.isPublic!="boolean")return e.addIssue({code:"custom",message:`Part ${o} must have a boolean 'isPublic' field`}),zod.z.NEVER;if(!("regexDef"in r)||typeof r.regexDef!="string")return e.addIssue({code:"custom",message:`Part ${o} must have a string 'regexDef' field`}),zod.z.NEVER}try{return V(t),t}catch(o){return e.addIssue({code:"custom",message:o.message}),zod.z.NEVER}}).optional().or(zod.z.array(zod.z.any()))})),externalInputs:zod.z.array(zod.z.object({name:zod.z.string().min(1),maxLength:zod.z.coerce.number().positive().default(64)})).optional()});function V(n){let e="";for(let t of n){if(t.isPublic||(e=e+t.regexDef),!t.isPublic&&!t.regexDef)throw new Error("Part has to have a nonempty regex with isPublic = false");break}if(!e)throw new Error("Part has to have a regex with isPublic = false in order to find it later");return JSON.stringify(e)}var d=class n{props;auth;baseUrl;stars=0;static formSchema=T;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 p=`${t}/blueprint/by-slug/${e}/${s}`;i=await c(p);}catch(p){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",p),p}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 h(`${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 h(`${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 h(`${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,r=!0){let s={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},i;try{i=await c(`${e}/blueprint`,s,o);}catch(u){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",u),u}if(!i.blueprints)return [];let a=i.blueprints.map(u=>{let p=n.responseToBlueprintProps(u);return new n(p,e,o)});return r&&await Promise.all(a.map(u=>u.getStars())),a}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 h(`${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}`);}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 P(this)}async verifyProofOnChain(e){try{await f(e);}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 D(`${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)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await h(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await w(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await c(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await w(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await w(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}};async function L(n,e){let{slugs:t}=await c(`${n}/blueprint/starred`,null,e);return t}var et=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 d(t,e,n.auth)},async getBlueprint(t){return d.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return d.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return d.listBlueprints(e,t,n?.auth)},async getProof(t){return m.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return L(e,n.auth)}}};
2
- Object.defineProperty(exports,"ZodError",{enumerable:true,get:function(){return zod.ZodError}});exports.Blueprint=d;exports.Proof=m;exports.ProofStatus=x;exports.Status=S;exports.ZkFramework=J;exports.default=et;exports.generateProofInputs=_;exports.getLoginWithGithubUrl=O;exports.parseEmail=R;exports.startJsonFileDownload=H;exports.testBlueprint=z;exports.testDecomposedRegex=v;//# sourceMappingURL=index.js.map
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains'),relayerUtils=require('@zk-email/relayer-utils'),zod=require('zod');function O(n){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${n}]`,internalType:`uint256[${n}]`}],outputs:[],stateMutability:"view"}]}async function b(n){if(!n.blueprint.props.verifierContract?.chain||!n.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!n.props.proofData||!n.props.publicOutputs)throw new Error("No proof data generated yet");let e=viem.createPublicClient({chain:chains.base,transport:viem.http("https://sepolia.base.org")}),t=n.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],n.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",n.blueprint.props.verifierContract.address);try{await e.readContract({address:n.blueprint.props.verifierContract.address,abi:O(n.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var B=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(B||{});var H="Ov23li0KABFCUsxBEQkn";function q(n,e=H){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function f(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 y="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F";async function m(n,e,t){let o=null;if(t)try{o=await f(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":y,...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 k(n,e,t){let o=null;if(t)try{o=await f(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":y,...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 f(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,u])=>{u&&i.append(a,String(u));}),i.size>0&&(r+=`?${i.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":y,...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 w(n,e,t){let o=null;if(t)try{o=await f(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"DELETE",headers:{"Content-Type":"application/json","x-api-key":y,...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("DELETE Error:",r),r}}function N(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);}function j(n){let e=[],t=n.split(`
2
+ `);for(let o of t){if(o.trim()==="")break;o.startsWith(" ")||o.startsWith(" ")?e[e.length-1]+=o.trim():e.push(o);}for(let o of e)if(o.includes("DKIM-Signature")){let r=o.match(/s=([^;]+)/);if(r&&r[1])return r[1].trim()}return null}var g=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof d))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(){await b(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}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 d.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,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,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,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var v,P=new Promise(n=>{v=n;});relayerUtils.init().then(()=>{v(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function x(n){try{return await P,await relayerUtils.parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function V(n,e,t=!1){let o=await x(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;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.canonicalizedHeader;return await K(s,r,e),await Promise.all(e.decomposedRegexes.map(a=>L(r,s,a,t)))}async function K(n,e,t){await P;let o=new TextEncoder,r=o.encode(n);if((await relayerUtils.sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let i=o.encode(e),a=(e.length+63+65)/64*64,u=Math.max(a,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(i,u)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function L(n,e,t,o=!1){let r={parts:t.parts.map(p=>({is_public:"isPublic"in p?p.isPublic:p.is_public,regex_def:"regexDef"in p?p.regexDef:p.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;await P;let a=relayerUtils.extractSubstr(s,r,!1);if(a[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?relayerUtils.extractSubstr(s,r,o):a}async function D(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await P;let s=e.map(a=>({...a,parts:a.parts.map(u=>({is_public:u.isPublic||!!u.is_public,regex_def:u.regexDef||!!u.regex_def}))})),i=await relayerUtils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,s,t,r);return JSON.stringify(Object.fromEntries(i))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}async function Z(n,e){let o=(await x(n)).cleanedBody,r=o.indexOf(e);return r===-1?o.length:o.length-r-e.length}async function W(n){let e={},t=n.split(`
3
+ `),o=!0,r=[];for(let h of t)o&&(h.trim()===""?o=!1:r.push(h));r.map(h=>h.startsWith(" ")||h.startsWith(" ")?h.trim():`
4
+ ${h.trim()}`).join("").split(`
5
+ `).forEach(h=>{let[E,...A]=h.split(":");E&&(e[E.trim()]=A.join(":").trim());});let i=e["Return-Path"]?.match(/@([^\s>]+)/)?.[1]?.split(".").slice(-2).join(".")||null,a=`from:${i}`,u=await x(n);console.log(u.canonicalizedBody,"parsedEmail");let p=u.cleanedBody.length,$=u.canonicalizedHeader.length;return {senderDomain:i,headerLength:$,emailQuery:a,emailBodyMaxLength:p}}var _=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof d))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e,t=[]){let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);let r;try{let a={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 D(e,this.blueprint.props.decomposedRegexes,t,a);}catch(a){throw console.error("Failed to generate inputs for proof"),a}console.log("got proof input");let s;try{let a={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((u,p)=>({...u,[p.name]:p.value}),{})};s=await m(`${this.blueprint.baseUrl}/proof`,a);}catch(a){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",a),a}let i=g.responseToProofProps(s);return new g(this.blueprint,i)}};var Q=(e=>(e.Circom="circom",e))(Q||{}),S=(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))(S||{});var T=zod.z.object({title:zod.z.string().min(1,{message:"Title must be at least 1 characters."}),circuitName:zod.z.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/,"Invalid name, must start with a letter, digit, or underscore, and can only contain letters, digits or underscores."),description:zod.z.string().min(1),emailQuery:zod.z.string(),ignoreBodyHashCheck:zod.z.boolean(),shaPrecomputeSelector:zod.z.string().transform(n=>n.replace(/(?<!\\)"/g,'\\"')).optional(),senderDomain:zod.z.string().refine(n=>!n.includes("@"),{message:"Sender domain should not contain '@' symbol, only the domain"}),emailBodyMaxLength:zod.z.coerce.number().transform((n,e)=>(n%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),n>1e4&&e.addIssue({code:"custom",message:"Must be less than or equal to 10000"}),n)),emailHeaderMaxLength:zod.z.coerce.number().transform((n,e)=>(n%64!==0&&e.addIssue({code:"custom",message:"Must be a multiple of 64"}),n)).default(1024),decomposedRegexes:zod.z.array(zod.z.object({name:zod.z.string().min(1).transform((n,e)=>n.includes(" ")?(e.addIssue({code:"custom",message:"Warning: Name contains spaces or dashes. They will be replaced with underscores."}),n.replace(/[ -]/g,"_")):n),maxLength:zod.z.coerce.number().positive().default(64),location:zod.z.string().regex(/(body)|(header)/),parts:zod.z.string().transform((n,e)=>{if(!n.includes("isPublic"))return e.addIssue({code:"custom",message:'Each parts config must include at least one "isPublic" field, and at least one thats true and one thats false. Please add it for now until we fix this requirement.'}),zod.z.NEVER;let t;try{t=JSON.parse(n);}catch{return e.addIssue({code:"custom",message:"Invalid JSON"}),zod.z.NEVER}if(!Array.isArray(t))return e.addIssue({code:"custom",message:"Parts must be an array"}),zod.z.NEVER;for(let o=0;o<t.length;o++){let r=t[o];if(typeof r!="object"||r===null)return e.addIssue({code:"custom",message:`Part ${o} must be an object`}),zod.z.NEVER;if(!("isPublic"in r)||typeof r.isPublic!="boolean")return e.addIssue({code:"custom",message:`Part ${o} must have a boolean 'isPublic' field`}),zod.z.NEVER;if(!("regexDef"in r)||typeof r.regexDef!="string")return e.addIssue({code:"custom",message:`Part ${o} must have a string 'regexDef' field`}),zod.z.NEVER}try{return Y(t),t}catch(o){return e.addIssue({code:"custom",message:o.message}),zod.z.NEVER}}).optional().or(zod.z.array(zod.z.any()))})),externalInputs:zod.z.array(zod.z.object({name:zod.z.string().min(1),maxLength:zod.z.coerce.number().positive().default(64)})).optional()});function Y(n){let e="";for(let t of n){if(t.isPublic||(e=e+t.regexDef),!t.isPublic&&!t.regexDef)throw new Error("Part has to have a nonempty regex with isPublic = false");break}if(!e)throw new Error("Part has to have a regex with isPublic = false in order to find it later");return JSON.stringify(e)}var d=class n{props;auth;baseUrl;stars=0;static formSchema=T;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 p=`${t}/blueprint/by-slug/${e}/${s}`;i=await c(p);}catch(p){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",p),p}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,r=!0){let s={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},i;try{i=await c(`${e}/blueprint`,s,o);}catch(u){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",u),u}if(!i.blueprints)return [];let a=i.blueprints.map(u=>{let p=n.responseToBlueprintProps(u);return new n(p,e,o)});return r&&await Promise.all(a.map(u=>u.getStars())),a}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}`);}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 _(this)}async verifyProofOnChain(e){try{await b(e);}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 k(`${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)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await m(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await w(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await c(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await w(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await w(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}};async function C(n,e){let{slugs:t}=await c(`${n}/blueprint/starred`,null,e);return t}var Xe=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 d(t,e,n.auth)},async getBlueprint(t){return d.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return d.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return d.listBlueprints(e,t,n?.auth)},async getProof(t){return g.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return C(e,n.auth)}}};
6
+ Object.defineProperty(exports,"ZodError",{enumerable:true,get:function(){return zod.ZodError}});exports.Blueprint=d;exports.Proof=g;exports.ProofStatus=B;exports.Status=S;exports.ZkFramework=Q;exports.default=Xe;exports.extractEMLDetails=W;exports.generateProofInputs=D;exports.getDKIMSelector=j;exports.getLoginWithGithubUrl=q;exports.getMaxEmailBodyLength=Z;exports.parseEmail=x;exports.startJsonFileDownload=N;exports.testBlueprint=V;exports.testDecomposedRegex=L;//# sourceMappingURL=index.js.map
3
7
  //# sourceMappingURL=index.js.map