@zk-email/sdk 0.0.85-4 → 0.0.85-6
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 +80 -5
- package/dist/index.d.ts +80 -5
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -2
package/dist/index.d.mts
CHANGED
@@ -1,3 +1,5 @@
|
|
1
|
+
import * as zod from 'zod';
|
2
|
+
|
1
3
|
type BlueprintProps = {
|
2
4
|
id?: string;
|
3
5
|
title: string;
|
@@ -24,7 +26,6 @@ type BlueprintProps = {
|
|
24
26
|
status?: Status;
|
25
27
|
verifierContract?: VerifierContract;
|
26
28
|
version?: number;
|
27
|
-
stars?: number;
|
28
29
|
};
|
29
30
|
type DecomposedRegex = {
|
30
31
|
parts: DecomposedRegexPart[];
|
@@ -117,7 +118,6 @@ type BlueprintResponse = {
|
|
117
118
|
verifier_contract_address: string;
|
118
119
|
verifier_contract_chain: number;
|
119
120
|
version: number;
|
120
|
-
stars: number;
|
121
121
|
};
|
122
122
|
type ServerDate = {
|
123
123
|
seconds: number;
|
@@ -141,7 +141,6 @@ type ListBlueprintsOptions = {
|
|
141
141
|
skip?: number;
|
142
142
|
limit?: number;
|
143
143
|
sort?: -1 | 1;
|
144
|
-
sortBy?: "updatedAt" | "stars";
|
145
144
|
status?: Status[];
|
146
145
|
isPublic?: boolean;
|
147
146
|
search?: string;
|
@@ -150,7 +149,6 @@ type ListBlueprintsOptionsRequest = {
|
|
150
149
|
skip?: number;
|
151
150
|
limit?: number;
|
152
151
|
sort?: -1 | 1;
|
153
|
-
sortBy?: "updated_at" | "stars";
|
154
152
|
status?: Status[];
|
155
153
|
is_public?: boolean;
|
156
154
|
search?: string;
|
@@ -321,6 +319,83 @@ declare class Blueprint {
|
|
321
319
|
auth?: Auth;
|
322
320
|
baseUrl: string;
|
323
321
|
stars: number;
|
322
|
+
static readonly formSchema: zod.ZodObject<{
|
323
|
+
title: zod.ZodString;
|
324
|
+
circuitName: zod.ZodString;
|
325
|
+
description: zod.ZodString;
|
326
|
+
emailQuery: zod.ZodString;
|
327
|
+
ignoreBodyHashCheck: zod.ZodBoolean;
|
328
|
+
shaPrecomputeSelector: zod.ZodOptional<zod.ZodEffects<zod.ZodString, string, string>>;
|
329
|
+
senderDomain: zod.ZodEffects<zod.ZodString, string, string>;
|
330
|
+
emailBodyMaxLength: zod.ZodEffects<zod.ZodNumber, number, number>;
|
331
|
+
emailHeaderMaxLength: zod.ZodDefault<zod.ZodEffects<zod.ZodNumber, number, number>>;
|
332
|
+
decomposedRegexes: zod.ZodArray<zod.ZodObject<{
|
333
|
+
name: zod.ZodEffects<zod.ZodString, string, string>;
|
334
|
+
maxLength: zod.ZodDefault<zod.ZodNumber>;
|
335
|
+
location: zod.ZodString;
|
336
|
+
parts: zod.ZodUnion<[zod.ZodOptional<zod.ZodEffects<zod.ZodString, any[], string>>, zod.ZodArray<zod.ZodAny, "many">]>;
|
337
|
+
}, "strip", zod.ZodTypeAny, {
|
338
|
+
name: string;
|
339
|
+
maxLength: number;
|
340
|
+
location: string;
|
341
|
+
parts?: any[] | undefined;
|
342
|
+
}, {
|
343
|
+
name: string;
|
344
|
+
location: string;
|
345
|
+
maxLength?: number | undefined;
|
346
|
+
parts?: string | any[] | undefined;
|
347
|
+
}>, "many">;
|
348
|
+
externalInputs: zod.ZodOptional<zod.ZodArray<zod.ZodObject<{
|
349
|
+
name: zod.ZodString;
|
350
|
+
maxLength: zod.ZodDefault<zod.ZodNumber>;
|
351
|
+
}, "strip", zod.ZodTypeAny, {
|
352
|
+
name: string;
|
353
|
+
maxLength: number;
|
354
|
+
}, {
|
355
|
+
name: string;
|
356
|
+
maxLength?: number | undefined;
|
357
|
+
}>, "many">>;
|
358
|
+
}, "strip", zod.ZodTypeAny, {
|
359
|
+
description: string;
|
360
|
+
title: string;
|
361
|
+
circuitName: string;
|
362
|
+
emailQuery: string;
|
363
|
+
ignoreBodyHashCheck: boolean;
|
364
|
+
senderDomain: string;
|
365
|
+
emailBodyMaxLength: number;
|
366
|
+
emailHeaderMaxLength: number;
|
367
|
+
decomposedRegexes: {
|
368
|
+
name: string;
|
369
|
+
maxLength: number;
|
370
|
+
location: string;
|
371
|
+
parts?: any[] | undefined;
|
372
|
+
}[];
|
373
|
+
shaPrecomputeSelector?: string | undefined;
|
374
|
+
externalInputs?: {
|
375
|
+
name: string;
|
376
|
+
maxLength: number;
|
377
|
+
}[] | undefined;
|
378
|
+
}, {
|
379
|
+
description: string;
|
380
|
+
title: string;
|
381
|
+
circuitName: string;
|
382
|
+
emailQuery: string;
|
383
|
+
ignoreBodyHashCheck: boolean;
|
384
|
+
senderDomain: string;
|
385
|
+
emailBodyMaxLength: number;
|
386
|
+
decomposedRegexes: {
|
387
|
+
name: string;
|
388
|
+
location: string;
|
389
|
+
maxLength?: number | undefined;
|
390
|
+
parts?: string | any[] | undefined;
|
391
|
+
}[];
|
392
|
+
shaPrecomputeSelector?: string | undefined;
|
393
|
+
emailHeaderMaxLength?: number | undefined;
|
394
|
+
externalInputs?: {
|
395
|
+
name: string;
|
396
|
+
maxLength?: number | undefined;
|
397
|
+
}[] | undefined;
|
398
|
+
}>;
|
324
399
|
private lastCheckedStatus;
|
325
400
|
constructor(props: BlueprintProps, baseUrl: string, auth?: Auth);
|
326
401
|
addAuth(auth: Auth): void;
|
@@ -365,7 +440,7 @@ declare class Blueprint {
|
|
365
440
|
* @param options - Options to filter the blueprints by.
|
366
441
|
* @returns A promise. Once it resolves, `getId` can be called.
|
367
442
|
*/
|
368
|
-
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
|
443
|
+
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth, fetchStars?: boolean): Promise<Blueprint[]>;
|
369
444
|
/**
|
370
445
|
* Submits a blueprint. This will save the blueprint if it didn't exist before
|
371
446
|
* and start the compilation.
|
package/dist/index.d.ts
CHANGED
@@ -1,3 +1,5 @@
|
|
1
|
+
import * as zod from 'zod';
|
2
|
+
|
1
3
|
type BlueprintProps = {
|
2
4
|
id?: string;
|
3
5
|
title: string;
|
@@ -24,7 +26,6 @@ type BlueprintProps = {
|
|
24
26
|
status?: Status;
|
25
27
|
verifierContract?: VerifierContract;
|
26
28
|
version?: number;
|
27
|
-
stars?: number;
|
28
29
|
};
|
29
30
|
type DecomposedRegex = {
|
30
31
|
parts: DecomposedRegexPart[];
|
@@ -117,7 +118,6 @@ type BlueprintResponse = {
|
|
117
118
|
verifier_contract_address: string;
|
118
119
|
verifier_contract_chain: number;
|
119
120
|
version: number;
|
120
|
-
stars: number;
|
121
121
|
};
|
122
122
|
type ServerDate = {
|
123
123
|
seconds: number;
|
@@ -141,7 +141,6 @@ type ListBlueprintsOptions = {
|
|
141
141
|
skip?: number;
|
142
142
|
limit?: number;
|
143
143
|
sort?: -1 | 1;
|
144
|
-
sortBy?: "updatedAt" | "stars";
|
145
144
|
status?: Status[];
|
146
145
|
isPublic?: boolean;
|
147
146
|
search?: string;
|
@@ -150,7 +149,6 @@ type ListBlueprintsOptionsRequest = {
|
|
150
149
|
skip?: number;
|
151
150
|
limit?: number;
|
152
151
|
sort?: -1 | 1;
|
153
|
-
sortBy?: "updated_at" | "stars";
|
154
152
|
status?: Status[];
|
155
153
|
is_public?: boolean;
|
156
154
|
search?: string;
|
@@ -321,6 +319,83 @@ declare class Blueprint {
|
|
321
319
|
auth?: Auth;
|
322
320
|
baseUrl: string;
|
323
321
|
stars: number;
|
322
|
+
static readonly formSchema: zod.ZodObject<{
|
323
|
+
title: zod.ZodString;
|
324
|
+
circuitName: zod.ZodString;
|
325
|
+
description: zod.ZodString;
|
326
|
+
emailQuery: zod.ZodString;
|
327
|
+
ignoreBodyHashCheck: zod.ZodBoolean;
|
328
|
+
shaPrecomputeSelector: zod.ZodOptional<zod.ZodEffects<zod.ZodString, string, string>>;
|
329
|
+
senderDomain: zod.ZodEffects<zod.ZodString, string, string>;
|
330
|
+
emailBodyMaxLength: zod.ZodEffects<zod.ZodNumber, number, number>;
|
331
|
+
emailHeaderMaxLength: zod.ZodDefault<zod.ZodEffects<zod.ZodNumber, number, number>>;
|
332
|
+
decomposedRegexes: zod.ZodArray<zod.ZodObject<{
|
333
|
+
name: zod.ZodEffects<zod.ZodString, string, string>;
|
334
|
+
maxLength: zod.ZodDefault<zod.ZodNumber>;
|
335
|
+
location: zod.ZodString;
|
336
|
+
parts: zod.ZodUnion<[zod.ZodOptional<zod.ZodEffects<zod.ZodString, any[], string>>, zod.ZodArray<zod.ZodAny, "many">]>;
|
337
|
+
}, "strip", zod.ZodTypeAny, {
|
338
|
+
name: string;
|
339
|
+
maxLength: number;
|
340
|
+
location: string;
|
341
|
+
parts?: any[] | undefined;
|
342
|
+
}, {
|
343
|
+
name: string;
|
344
|
+
location: string;
|
345
|
+
maxLength?: number | undefined;
|
346
|
+
parts?: string | any[] | undefined;
|
347
|
+
}>, "many">;
|
348
|
+
externalInputs: zod.ZodOptional<zod.ZodArray<zod.ZodObject<{
|
349
|
+
name: zod.ZodString;
|
350
|
+
maxLength: zod.ZodDefault<zod.ZodNumber>;
|
351
|
+
}, "strip", zod.ZodTypeAny, {
|
352
|
+
name: string;
|
353
|
+
maxLength: number;
|
354
|
+
}, {
|
355
|
+
name: string;
|
356
|
+
maxLength?: number | undefined;
|
357
|
+
}>, "many">>;
|
358
|
+
}, "strip", zod.ZodTypeAny, {
|
359
|
+
description: string;
|
360
|
+
title: string;
|
361
|
+
circuitName: string;
|
362
|
+
emailQuery: string;
|
363
|
+
ignoreBodyHashCheck: boolean;
|
364
|
+
senderDomain: string;
|
365
|
+
emailBodyMaxLength: number;
|
366
|
+
emailHeaderMaxLength: number;
|
367
|
+
decomposedRegexes: {
|
368
|
+
name: string;
|
369
|
+
maxLength: number;
|
370
|
+
location: string;
|
371
|
+
parts?: any[] | undefined;
|
372
|
+
}[];
|
373
|
+
shaPrecomputeSelector?: string | undefined;
|
374
|
+
externalInputs?: {
|
375
|
+
name: string;
|
376
|
+
maxLength: number;
|
377
|
+
}[] | undefined;
|
378
|
+
}, {
|
379
|
+
description: string;
|
380
|
+
title: string;
|
381
|
+
circuitName: string;
|
382
|
+
emailQuery: string;
|
383
|
+
ignoreBodyHashCheck: boolean;
|
384
|
+
senderDomain: string;
|
385
|
+
emailBodyMaxLength: number;
|
386
|
+
decomposedRegexes: {
|
387
|
+
name: string;
|
388
|
+
location: string;
|
389
|
+
maxLength?: number | undefined;
|
390
|
+
parts?: string | any[] | undefined;
|
391
|
+
}[];
|
392
|
+
shaPrecomputeSelector?: string | undefined;
|
393
|
+
emailHeaderMaxLength?: number | undefined;
|
394
|
+
externalInputs?: {
|
395
|
+
name: string;
|
396
|
+
maxLength?: number | undefined;
|
397
|
+
}[] | undefined;
|
398
|
+
}>;
|
324
399
|
private lastCheckedStatus;
|
325
400
|
constructor(props: BlueprintProps, baseUrl: string, auth?: Auth);
|
326
401
|
addAuth(auth: Auth): void;
|
@@ -365,7 +440,7 @@ declare class Blueprint {
|
|
365
440
|
* @param options - Options to filter the blueprints by.
|
366
441
|
* @returns A promise. Once it resolves, `getId` can be called.
|
367
442
|
*/
|
368
|
-
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
|
443
|
+
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth, fetchStars?: boolean): Promise<Blueprint[]>;
|
369
444
|
/**
|
370
445
|
* Submits a blueprint. This will save the blueprint if it didn't exist before
|
371
446
|
* and start the compilation.
|
package/dist/index.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains'),relayerUtils=require('@zk-email/relayer-utils');function $(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 g(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.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var P=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(P||{});var A="Ov23li0KABFCUsxBEQkn";function U(n,e=A){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function m(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 f="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",_;new Promise(n=>{_=n;});relayerUtils.init().then(()=>{_(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 m(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":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("POST Error:",r),r}}async function B(n,e,t){let o=null;if(t)try{o=await m(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":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("PATCH Error:",r),r}}async function u(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let a=new URLSearchParams;Object.entries(e).forEach(([i,l])=>{l&&a.append(i,String(l));}),a.size>0&&(r+=`?${a.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return await s.json()}catch(r){throw console.error("GET Error:",r),r}}async function b(n,e,t){let o=null;if(t)try{o=await m(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":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("DELETE Error:",r),r}}function O(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 d=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(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 u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await 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 g(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 u(`${t}/proof/${e}`);}catch(a){throw console.error("Failed calling /proof/:id in getProofById: ",a),a}let r=this.responseToProofProps(o),s=await c.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 E,w=new Promise(n=>{E=n;});relayerUtils.init().then(()=>{E(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function I(n){try{return await w,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 I(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 i=r.split(e.shaPrecomputeSelector)[1];if(!i)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=i;}let s=o.canonicalizedHeader;return await N(s,r,e),await Promise.all(e.decomposedRegexes.map(i=>v(r,s,i,t)))}async function N(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 a=o.encode(e),i=(e.length+63+65)/64*64,l=Math.max(i,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(a,l)).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 a="maxLength"in t?t.maxLength:t.max_length;await w;let i=relayerUtils.extractSubstr(s,r,!1);if(i[0].length>a)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?relayerUtils.extractSubstr(s,r,o):i}async function x(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await w;let s=e.map(i=>({...i,parts:i.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),a=await relayerUtils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,s,t,r);return JSON.stringify(Object.fromEntries(a))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var y=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof c))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 i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await x(e,this.blueprint.props.decomposedRegexes,t,i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let s;try{let i={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((l,p)=>({...l,[p.name]:p.value}),{})};s=await h(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let a=d.responseToProofProps(s);return new d(this.blueprint,a)}};var j=(e=>(e.Circom="circom",e))(j||{}),R=(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))(R||{});var c=class n{props;auth;baseUrl;stars=0;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 u(`${t}/blueprint/${e}`);}catch(i){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",i),i}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 a;try{let p=`${t}/blueprint/by-slug/${e}/${s}`;a=await u(p);}catch(p){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",p),p}let i=this.responseToBlueprintProps(a);return new n(i,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){console.log("listing blueprints with options: ",t);let r={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,sortBy:t?.sortBy==="updatedAt"?"updated_at":t?.sortBy,search:t?.search};console.log("requestOptions: ",r);let s;try{s=await u(`${e}/blueprint`,r,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return s.blueprints?(console.log("response: ",s),s.blueprints.map(i=>{let l=n.responseToBlueprintProps(i);return new n(l,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 u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let 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 u(`${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 y(this)}async verifyProofOnChain(e){try{await g(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 B(`${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 u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let 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 b(`${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 u(`${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 b(`${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 b(`${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 T(n,e){let{slugs:t}=await u(`${n}/blueprint/starred`,null,e);return t}var Je=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 c(t,e,n.auth)},async getBlueprint(t){return c.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return c.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return c.listBlueprints(e,t,n?.auth)},async getProof(t){return d.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return T(e,n.auth)}}};
|
2
|
-
exports.Blueprint=
|
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 U(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:U(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 F="Ov23li0KABFCUsxBEQkn";function O(n,e=F){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
|
3
3
|
//# sourceMappingURL=index.js.map
|