@zk-email/sdk 0.0.85-7 → 0.0.86-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +18 -10
- package/dist/index.d.ts +18 -10
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -1
- package/dist/localProverWorker.d.mts +4 -0
- package/dist/localProverWorker.d.ts +4 -0
- package/dist/localProverWorker.js +2 -0
- package/dist/localProverWorker.js.map +1 -0
- package/dist/localProverWorker.mjs +2 -0
- package/dist/localProverWorker.mjs.map +1 -0
- package/package.json +13 -5
package/dist/index.d.mts
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
import { z } from 'zod';
|
2
|
+
export { ZodError } from 'zod';
|
2
3
|
|
3
4
|
type BlueprintProps = {
|
4
5
|
id?: string;
|
@@ -26,6 +27,7 @@ type BlueprintProps = {
|
|
26
27
|
status?: Status;
|
27
28
|
verifierContract?: VerifierContract;
|
28
29
|
version?: number;
|
30
|
+
stars?: number;
|
29
31
|
};
|
30
32
|
type DecomposedRegex = {
|
31
33
|
parts: DecomposedRegexPart[];
|
@@ -118,6 +120,7 @@ type BlueprintResponse = {
|
|
118
120
|
verifier_contract_address: string;
|
119
121
|
verifier_contract_chain: number;
|
120
122
|
version: number;
|
123
|
+
stars: number;
|
121
124
|
};
|
122
125
|
type ServerDate = {
|
123
126
|
seconds: number;
|
@@ -141,19 +144,16 @@ type ListBlueprintsOptions = {
|
|
141
144
|
skip?: number;
|
142
145
|
limit?: number;
|
143
146
|
sort?: -1 | 1;
|
147
|
+
sortBy?: "updatedAt" | "stars";
|
144
148
|
status?: Status[];
|
145
149
|
isPublic?: boolean;
|
146
150
|
search?: string;
|
147
151
|
};
|
148
|
-
type ListBlueprintsOptionsRequest = {
|
149
|
-
skip?: number;
|
150
|
-
limit?: number;
|
151
|
-
sort?: -1 | 1;
|
152
|
-
status?: Status[];
|
153
|
-
is_public?: boolean;
|
154
|
-
search?: string;
|
155
|
-
};
|
156
152
|
type DownloadUrls = Record<string, string>;
|
153
|
+
type ChunkedZkeyUrl = {
|
154
|
+
url: string;
|
155
|
+
suffix: "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k";
|
156
|
+
};
|
157
157
|
|
158
158
|
declare enum ProofStatus {
|
159
159
|
None = 0,
|
@@ -285,6 +285,8 @@ declare class Prover {
|
|
285
285
|
* Done or Failed.
|
286
286
|
*/
|
287
287
|
generateProof(eml: string, externalInputs?: ExternalInputInput[]): Promise<Proof>;
|
288
|
+
generateLocalProof(eml: string, externalInputs?: ExternalInputInput[]): Promise<Proof>;
|
289
|
+
generateProofInputs(eml: string, externalInputs?: ExternalInputInput[]): Promise<string>;
|
288
290
|
/**
|
289
291
|
* Starts proving for a given email.
|
290
292
|
* @param eml - Email to prove agains the blueprint of this Prover.
|
@@ -388,6 +390,9 @@ declare const blueprintFormSchema: z.ZodObject<{
|
|
388
390
|
maxLength?: number | undefined;
|
389
391
|
}[] | undefined;
|
390
392
|
}>;
|
393
|
+
type ValidationErrors = {
|
394
|
+
[K in keyof z.infer<typeof blueprintFormSchema>]?: string;
|
395
|
+
};
|
391
396
|
|
392
397
|
/**
|
393
398
|
* Represents a Regex Blueprint including the decomposed regex access to the circuit.
|
@@ -442,7 +447,7 @@ declare class Blueprint {
|
|
442
447
|
* @param options - Options to filter the blueprints by.
|
443
448
|
* @returns A promise. Once it resolves, `getId` can be called.
|
444
449
|
*/
|
445
|
-
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth
|
450
|
+
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
|
446
451
|
/**
|
447
452
|
* Submits a blueprint. This will save the blueprint if it didn't exist before
|
448
453
|
* and start the compilation.
|
@@ -508,6 +513,8 @@ declare class Blueprint {
|
|
508
513
|
getStars(): Promise<number>;
|
509
514
|
cancelCompilation(): Promise<void>;
|
510
515
|
delete(): Promise<void>;
|
516
|
+
getChunkedZkeyUrls(): Promise<ChunkedZkeyUrl[]>;
|
517
|
+
getWasmUrl(): Promise<string>;
|
511
518
|
}
|
512
519
|
|
513
520
|
type SdkOptions = {
|
@@ -525,6 +532,7 @@ type ParsedEmail = {
|
|
525
532
|
};
|
526
533
|
|
527
534
|
declare function startJsonFileDownload(json: string, name?: string): void;
|
535
|
+
declare function getDKIMSelector(emlContent: string): string | null;
|
528
536
|
|
529
537
|
declare function parseEmail(eml: string): Promise<ParsedEmail>;
|
530
538
|
declare function testBlueprint(eml: string, blueprint: BlueprintProps, revealPrivate?: boolean): Promise<string[][]>;
|
@@ -542,4 +550,4 @@ declare const _default: (sdkOptions?: SdkOptions) => {
|
|
542
550
|
getStarredBlueprints(): Promise<string[]>;
|
543
551
|
};
|
544
552
|
|
545
|
-
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
|
553
|
+
export { type Auth, Blueprint, type BlueprintProps, type BlueprintRequest, type BlueprintResponse, type ChunkedZkeyUrl, 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 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, getDKIMSelector, getLoginWithGithubUrl, parseEmail, startJsonFileDownload, testBlueprint, testDecomposedRegex };
|
package/dist/index.d.ts
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
import { z } from 'zod';
|
2
|
+
export { ZodError } from 'zod';
|
2
3
|
|
3
4
|
type BlueprintProps = {
|
4
5
|
id?: string;
|
@@ -26,6 +27,7 @@ type BlueprintProps = {
|
|
26
27
|
status?: Status;
|
27
28
|
verifierContract?: VerifierContract;
|
28
29
|
version?: number;
|
30
|
+
stars?: number;
|
29
31
|
};
|
30
32
|
type DecomposedRegex = {
|
31
33
|
parts: DecomposedRegexPart[];
|
@@ -118,6 +120,7 @@ type BlueprintResponse = {
|
|
118
120
|
verifier_contract_address: string;
|
119
121
|
verifier_contract_chain: number;
|
120
122
|
version: number;
|
123
|
+
stars: number;
|
121
124
|
};
|
122
125
|
type ServerDate = {
|
123
126
|
seconds: number;
|
@@ -141,19 +144,16 @@ type ListBlueprintsOptions = {
|
|
141
144
|
skip?: number;
|
142
145
|
limit?: number;
|
143
146
|
sort?: -1 | 1;
|
147
|
+
sortBy?: "updatedAt" | "stars";
|
144
148
|
status?: Status[];
|
145
149
|
isPublic?: boolean;
|
146
150
|
search?: string;
|
147
151
|
};
|
148
|
-
type ListBlueprintsOptionsRequest = {
|
149
|
-
skip?: number;
|
150
|
-
limit?: number;
|
151
|
-
sort?: -1 | 1;
|
152
|
-
status?: Status[];
|
153
|
-
is_public?: boolean;
|
154
|
-
search?: string;
|
155
|
-
};
|
156
152
|
type DownloadUrls = Record<string, string>;
|
153
|
+
type ChunkedZkeyUrl = {
|
154
|
+
url: string;
|
155
|
+
suffix: "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k";
|
156
|
+
};
|
157
157
|
|
158
158
|
declare enum ProofStatus {
|
159
159
|
None = 0,
|
@@ -285,6 +285,8 @@ declare class Prover {
|
|
285
285
|
* Done or Failed.
|
286
286
|
*/
|
287
287
|
generateProof(eml: string, externalInputs?: ExternalInputInput[]): Promise<Proof>;
|
288
|
+
generateLocalProof(eml: string, externalInputs?: ExternalInputInput[]): Promise<Proof>;
|
289
|
+
generateProofInputs(eml: string, externalInputs?: ExternalInputInput[]): Promise<string>;
|
288
290
|
/**
|
289
291
|
* Starts proving for a given email.
|
290
292
|
* @param eml - Email to prove agains the blueprint of this Prover.
|
@@ -388,6 +390,9 @@ declare const blueprintFormSchema: z.ZodObject<{
|
|
388
390
|
maxLength?: number | undefined;
|
389
391
|
}[] | undefined;
|
390
392
|
}>;
|
393
|
+
type ValidationErrors = {
|
394
|
+
[K in keyof z.infer<typeof blueprintFormSchema>]?: string;
|
395
|
+
};
|
391
396
|
|
392
397
|
/**
|
393
398
|
* Represents a Regex Blueprint including the decomposed regex access to the circuit.
|
@@ -442,7 +447,7 @@ declare class Blueprint {
|
|
442
447
|
* @param options - Options to filter the blueprints by.
|
443
448
|
* @returns A promise. Once it resolves, `getId` can be called.
|
444
449
|
*/
|
445
|
-
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth
|
450
|
+
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
|
446
451
|
/**
|
447
452
|
* Submits a blueprint. This will save the blueprint if it didn't exist before
|
448
453
|
* and start the compilation.
|
@@ -508,6 +513,8 @@ declare class Blueprint {
|
|
508
513
|
getStars(): Promise<number>;
|
509
514
|
cancelCompilation(): Promise<void>;
|
510
515
|
delete(): Promise<void>;
|
516
|
+
getChunkedZkeyUrls(): Promise<ChunkedZkeyUrl[]>;
|
517
|
+
getWasmUrl(): Promise<string>;
|
511
518
|
}
|
512
519
|
|
513
520
|
type SdkOptions = {
|
@@ -525,6 +532,7 @@ type ParsedEmail = {
|
|
525
532
|
};
|
526
533
|
|
527
534
|
declare function startJsonFileDownload(json: string, name?: string): void;
|
535
|
+
declare function getDKIMSelector(emlContent: string): string | null;
|
528
536
|
|
529
537
|
declare function parseEmail(eml: string): Promise<ParsedEmail>;
|
530
538
|
declare function testBlueprint(eml: string, blueprint: BlueprintProps, revealPrivate?: boolean): Promise<string[][]>;
|
@@ -542,4 +550,4 @@ declare const _default: (sdkOptions?: SdkOptions) => {
|
|
542
550
|
getStarredBlueprints(): Promise<string[]>;
|
543
551
|
};
|
544
552
|
|
545
|
-
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
|
553
|
+
export { type Auth, Blueprint, type BlueprintProps, type BlueprintRequest, type BlueprintResponse, type ChunkedZkeyUrl, 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 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, getDKIMSelector, getLoginWithGithubUrl, parseEmail, startJsonFileDownload, testBlueprint, testDecomposedRegex };
|
package/dist/index.js
CHANGED
@@ -1,3 +1,4 @@
|
|
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 Ye=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
|
-
exports.Blueprint=d;exports.Proof=m;exports.ProofStatus=x;exports.Status=S;exports.ZkFramework=J;exports.default=Ye;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');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function N(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:N(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 j="Ov23li0KABFCUsxBEQkn";function z(n,e=j){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";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 E(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 p(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,c])=>{c&&i.append(a,String(c));}),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 y(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 Z(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 G(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 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 p(`${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 p(`${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 p(`${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 R,w=new Promise(n=>{R=n;});relayerUtils.init().then(()=>{R(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function L(n){try{return await w,await relayerUtils.parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function W(n,e,t=!1){let o=await L(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 Q(s,r,e),await Promise.all(e.decomposedRegexes.map(a=>T(r,s,a,t)))}async function Q(n,e,t){await w;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,c=Math.max(a,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(i,c)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function T(n,e,t,o=!1){let r={parts:t.parts.map(u=>({is_public:"isPublic"in u?u.isPublic:u.is_public,regex_def:"regexDef"in u?u.regexDef:u.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;console.log("maxLength: ",i),await w;let a=relayerUtils.extractSubstr(s,r,!1);if(console.log("privateResult : ",a),a[0].length>i)throw new Error(`Max length of ${i} 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 w;let s=e.map(a=>({...a,parts:a.parts.map(c=>({is_public:c.isPublic||!!c.is_public,regex_def:c.regexDef||!!c.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(!(e instanceof d))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={...t||{isLocal:!1}};}async generateProof(e,t=[]){if(this.options.isLocal)return await this.generateLocalProof(e,t);{let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}}async generateLocalProof(e,t=[]){let o=await this.generateProofInputs(e,t);console.log("got inputs");let r=await this.blueprint.getChunkedZkeyUrls(),s=await this.blueprint.getWasmUrl();console.log("got urls, wasmUrl: ",s);let i=await new Promise((a,c)=>{console.log("meta url: ",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)));let u=new URL("../dist/localProverWorker.js",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))),B=new Worker(u,{type:"module"});B.onmessage=U=>{let{type:A,message:F,progress:M,result:k,error:D}=U.data;switch(A){case"progress":console.log(`Download progress: ${M}`);break;case"message":console.log(F);break;case"result":console.log("Proof result:",k),a(k);break;case"error":console.error("Error in worker:",D),c(D);break}},B.postMessage({chunkedZkeyUrls:r,inputs:o,wasmUrl:s});});return console.log("result: ",i),i}async generateProofInputs(e,t=[]){if(!this.blueprint.getId())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 s={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,s);}catch(s){throw console.error("Failed to generate inputs for proof"),s}return r}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");let r=await this.generateProofInputs(e,t);console.log("got proof input");let s;try{let a={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((c,u)=>({...c,[u.name]:u.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 Y=(e=>(e.Circom="circom",e))(Y||{}),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 C=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 X(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 X(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=C;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 p(`${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 u=`${t}/blueprint/by-slug/${e}/${s}`;i=await p(u);}catch(u){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",u),u}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,stars:e.stars}}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){t?.sortBy&&(t.sortBy=t.sortBy==="updatedAt"?"updated_at":t.sortBy);let r;try{r=await p(`${e}/blueprint`,t,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return r.blueprints?r.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 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 p(`${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 p(`${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 E(`${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 p(`${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 y(`${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 p(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.props.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 y(`${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 y(`${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 getChunkedZkeyUrls(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await p(`${this.baseUrl}/blueprint/chunked-zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/chunked-zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async getWasmUrl(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await p(`${this.baseUrl}/blueprint/wasm/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/wasm/:id in getWasmUrl: ",t),t}return e.url}};async function $(n,e){let{slugs:t}=await p(`${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 $(e,n.auth)}}};
|
3
|
+
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=Y;exports.default=et;exports.generateProofInputs=_;exports.getDKIMSelector=G;exports.getLoginWithGithubUrl=z;exports.parseEmail=L;exports.startJsonFileDownload=Z;exports.testBlueprint=W;exports.testDecomposedRegex=T;//# sourceMappingURL=index.js.map
|
3
4
|
//# sourceMappingURL=index.js.map
|