UNPKG

sindri

Version:

The Sindri Labs JavaScript SDK and CLI tool.

5 lines 64.2 kB
#! /usr/bin/env node "use strict";var sr=Object.create;var pe=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var cr=Object.getOwnPropertyNames;var lr=Object.getPrototypeOf,pr=Object.prototype.hasOwnProperty;var ur=(t,e)=>{for(var o in e)pe(t,o,{get:e[o],enumerable:!0})},Qe=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of cr(e))!pr.call(t,i)&&i!==o&&pe(t,i,{get:()=>e[i],enumerable:!(n=ar(e,i))||n.enumerable});return t};var y=(t,e,o)=>(o=t!=null?sr(lr(t)):{},Qe(e||!t||!t.__esModule?pe(o,"default",{value:t,enumerable:!0}):o,t)),mr=t=>Qe(pe({},"__esModule",{value:!0}),t);var zr={};ur(zr,{program:()=>nr});module.exports=mr(zr);var dr=()=>typeof document>"u"?new URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,R=dr();var ke=require("process"),ir=require("@commander-js/extra-typings");var dt=y(require("assert")),Le=y(require("fs")),ft=y(require("path")),L=y(require("process")),gt=require("@commander-js/extra-typings"),ht=y(require("tar"));var ae=require("fs/promises"),ye=y(require("path")),lt=y(require("gzip-js")),pt=y(require("ignore-walk")),ut=y(require("tar")),mt=y(require("tar-js"));var Z=class{constructor(e){this.config=e}};var de=y(require("axios")),Ne=require("axios"),rt=y(require("@fullstax/p-retry"));var Xe=require("buffer"),et=require("formdata-node");var Q=process.env.BROWSER_BUILD?window.File:Xe.File,K=process.env.BROWSER_BUILD?window.FormData:et.FormData;var P=class extends Error{url;status;statusText;body;request;constructor(e,o,n){super(n),this.name="ApiError",this.url=o.url,this.status=o.status,this.statusText=o.statusText,this.body=o.body,this.request=e}};var ue=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},X=class{#t;#r;#e;#o;#i;#s;#n;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#i=new Promise((o,n)=>{this.#s=o,this.#n=n;let i=a=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#s?.(a))},s=a=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#n?.(a))},c=a=>{this.#t||this.#r||this.#e||this.#o.push(a)};return Object.defineProperty(c,"isResolved",{get:()=>this.#t}),Object.defineProperty(c,"isRejected",{get:()=>this.#r}),Object.defineProperty(c,"isCancelled",{get:()=>this.#e}),e(i,s,c)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,o){return this.#i.then(e,o)}catch(e){return this.#i.catch(e)}finally(e){return this.#i.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#n?.(new ue("Request aborted"))}}get isCancelled(){return this.#e}};var _e=t=>t!=null,fe=t=>typeof t=="string",Oe=t=>fe(t)&&t!=="",ot=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),fr=t=>t instanceof K,gr=t=>t>=200&&t<300,hr=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},yr=t=>{let e=[],o=(i,s)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},n=(i,s)=>{_e(s)&&(Array.isArray(s)?s.forEach(c=>{n(i,c)}):typeof s=="object"?Object.entries(s).forEach(([c,a])=>{n(`${i}[${c}]`,a)}):o(i,s))};return Object.entries(t).forEach(([i,s])=>{n(i,s)}),e.length>0?`?${e.join("&")}`:""},br=(t,e)=>{let o=t.ENCODE_PATH||encodeURI,n=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(s,c)=>e.path?.hasOwnProperty(c)?o(String(e.path[c])):s),i=`${t.BASE}${n}`;return e.query?`${i}${yr(e.query)}`:i},Rr=t=>{if(t.formData){if(t.formData instanceof K)return t.formData;let e=new K,o=(n,i)=>{fe(i)||ot(i)?e.append(n,i):e.append(n,JSON.stringify(i))};return Object.entries(t.formData).filter(([n,i])=>_e(i)).forEach(([n,i])=>{Array.isArray(i)?i.forEach(s=>o(n,s)):o(n,i)}),e}},me=async(t,e)=>typeof e=="function"?e(t):e,Cr=async(t,e,o)=>{let n=await me(e,t.TOKEN),i=await me(e,t.USERNAME),s=await me(e,t.PASSWORD),c=await me(e,t.HEADERS),a=o&&"getHeaders"in o&&typeof o?.getHeaders=="function"&&o?.getHeaders()||{},u=Object.entries({Accept:"application/json",...c,...e.headers,...a}).filter(([p,d])=>_e(d)).reduce((p,[d,m])=>({...p,[d]:String(m)}),{});if(Oe(n)&&(u.Authorization=`Bearer ${n}`),Oe(i)&&Oe(s)){let p=hr(`${i}:${s}`);u.Authorization=`Basic ${p}`}return e.body&&(e.mediaType?u["Content-Type"]=e.mediaType:ot(e.body)?u["Content-Type"]=e.body.type||"application/octet-stream":fe(e.body)?u["Content-Type"]="text/plain":fr(e.body)||(u["Content-Type"]="application/json")),u},wr=t=>{if(t.body)return t.body},tt=t=>!!(de.default.isAxiosError(t)&&(t.response?.status&&[502,503,504].includes(t.response.status)||t.code&&["ECONNREFUSED","ECONNRESET","ENOTFOUND","ENETUNREACH",Ne.AxiosError.ECONNABORTED,Ne.AxiosError.ERR_NETWORK].includes(t.code))),Sr=async(t,e,o,n,i,s,c,a)=>{let u=de.default.CancelToken.source(),p={url:o,headers:s,data:n??i,method:e.method,withCredentials:t.WITH_CREDENTIALS,cancelToken:u.token,responseType:e.responseType};c(()=>u.cancel("The user aborted a request."));try{return t.sindri?await(0,rt.default)(()=>a.request(p),{...t.sindri.retryOptions,onFailedAttempt:d=>{tt(d)&&t.sindri.logger.debug({attemptNumber:d.attemptNumber,error:d.message,retriesLeft:d.retriesLeft},`${e.method} ${o} - Request failed, ${d.retriesLeft>0?"retrying":"aborting..."}...`)},shouldRetry:tt}):await a.request(p)}catch(d){let m=d;if(m.response)return m.response;throw d}},Pr=(t,e)=>{if(e){let o=t.headers[e];if(fe(o))return o}},Ir=t=>{if(t.status!==204)return t.data},vr=(t,e)=>{let n={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(n)throw new P(t,e,n);if(!e.ok){let i=e.status??"unknown",s=e.statusText??"unknown",c=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new P(t,e,`Generic Error: status: ${i}; status text: ${s}; body: ${c}`)}},it=(t,e,o=de.default)=>new X(async(n,i,s)=>{let c=Date.now(),a=()=>{let d=Date.now()-c;if(d<1e3)return`${d} ms`;let m=d/1e3;if(m<60)return`${m.toFixed(2)} s`;let f=m/60;return f<60?`${f.toFixed(2)} m`:`${(f/60).toFixed(2)} h`},u=br(t,e),p=`${e.method} ${u}`;try{let d=Rr(e),m=wr(e),f=await Cr(t,e,d);if(!s.isCancelled){t.sindri?.logger.debug(`${p} requested`);let l=await Sr(t,e,u,m,d,f,s,o),h=Ir(l),g=Pr(l,e.responseHeader),b={url:u,ok:gr(l.status),status:l.status,statusText:l.statusText,body:g??h},C=`${p} ${l.status} ${l.statusText} (${a()})`;!b.body||typeof b.body=="string"?t.sindri?.logger.debug(`${C} - ${b.body||"<empty-body>"}`):e.responseType==="stream"?t.sindri?.logger.debug(`${C} - <streaming-response>`):e.responseType==="blob"?t.sindri?.logger.debug(`${C} - <blob-response>`):t.sindri?.logger.debug(b.body,C),vr(e,b),n(b.body)}}catch(d){let m=d instanceof Error?d.message:"Unknown error";t.sindri?.logger.debug(`${p} ERROR (${a()}) - ${m}`),i(d)}});var ge=class extends Z{constructor(e){super(e)}request(e){return it(this.config,e)}};var ee=class{constructor(e){this.httpRequest=e}apikeyGenerate(e,o){return this.httpRequest.request({method:"POST",url:"/api/apikey/generate",headers:{"Sindri-Team-Id":o},body:e,mediaType:"application/json",errors:{400:"Bad Request",401:"Unauthorized",403:"Forbidden"}})}apikeyDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/apikey/{apikey_id}/delete",path:{apikey_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}apikeyGenerateWithAuth(e){return this.httpRequest.request({method:"POST",url:"/api/v1/apikey/generate",query:{name:e},errors:{400:"Bad Request"}})}apikeyList(){return this.httpRequest.request({method:"GET",url:"/api/v1/apikey/list",errors:{500:"Internal Server Error"}})}};var te=class{constructor(e){this.httpRequest=e}circuitCreate(e){return this.httpRequest.request({method:"POST",url:"/api/v1/circuit/create",formData:e,mediaType:"multipart/form-data",errors:{400:"Bad Request",422:"Unprocessable Entity",500:"Internal Server Error",501:"Not Implemented"}})}circuitDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/circuit/{circuit_id}/delete",path:{circuit_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}circuitDetail(e,o=!0){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/detail",path:{circuit_id:e},query:{include_verification_key:o},errors:{404:"Not Found",500:"Internal Server Error"}})}circuitList(){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/list",errors:{500:"Internal Server Error"}})}circuitProofs(e){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/proofs",path:{circuit_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}proofCreate(e,o){return this.httpRequest.request({method:"POST",url:"/api/v1/circuit/{circuit_id}/prove",path:{circuit_id:e},body:o,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",501:"Not Implemented"}})}};var re=class{constructor(e){this.httpRequest=e}passwordChangeWithJwtAuth(e){return this.httpRequest.request({method:"POST",url:"/api/v1/password/change",body:e,mediaType:"application/json",errors:{422:"Unprocessable Entity"}})}sindriManifestSchema(){return this.httpRequest.request({method:"GET",url:"/api/v1/sindri-manifest-schema.json"})}circuitDownload(e,o){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/download",path:{circuit_id:e},query:{path:o},errors:{404:"Not Found",422:"Unprocessable Entity",500:"Internal Server Error"}})}circuitProofsPaginated(e,o=100,n){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/proofs/paginated",path:{circuit_id:e},query:{limit:o,offset:n},errors:{404:"Not Found",500:"Internal Server Error"},responseType:process.env.BROWSER_BUILD?"blob":"stream"})}circuitSmartContractVerifier(e){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/smart_contract_verifier",path:{circuit_id:e},errors:{404:"Not Found",409:"Conflict",500:"Internal Server Error",501:"Not Implemented"}})}circuitStatus(e){return this.httpRequest.request({method:"GET",url:"/api/v1/circuit/{circuit_id}/status",path:{circuit_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectList(e){return this.httpRequest.request({method:"POST",url:"/api/v1/project/list",body:e,mediaType:"application/json",errors:{404:"Not Found",500:"Internal Server Error"}})}projectListPaginated(e,o=100,n){return this.httpRequest.request({method:"POST",url:"/api/v1/project/list/paginated",query:{limit:o,offset:n},body:e,mediaType:"application/json",errors:{404:"Not Found",500:"Internal Server Error"}})}projectProofs(e){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/proofs",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectCircuits(e){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/circuits",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectCircuitsPaginated(e,o=100,n){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/circuits/paginated",path:{project_id:e},query:{limit:o,offset:n},errors:{404:"Not Found",500:"Internal Server Error"}})}projectDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/project/{project_id}/delete",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectDetail(e){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/detail",path:{project_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}projectProofsPaginated(e,o=100,n){return this.httpRequest.request({method:"GET",url:"/api/v1/project/{project_id}/proofs/paginated",path:{project_id:e},query:{limit:o,offset:n},errors:{404:"Not Found",500:"Internal Server Error"}})}projectSettings(e,o){return this.httpRequest.request({method:"POST",url:"/api/v1/project/{project_name}/settings",path:{project_name:e},body:o,mediaType:"application/json",errors:{404:"Not Found",422:"Unprocessable Entity",500:"Internal Server Error"}})}proofHistogram(e){return this.httpRequest.request({method:"POST",url:"/api/v1/proof/histogram",body:e,mediaType:"application/json",errors:{500:"Internal Server Error"}})}proofList(e){return this.httpRequest.request({method:"POST",url:"/api/v1/proof/list",body:e,mediaType:"application/json",errors:{500:"Internal Server Error"}})}proofListPaginated(e,o=100,n){return this.httpRequest.request({method:"POST",url:"/api/v1/proof/list/paginated",query:{limit:o,offset:n},body:e,mediaType:"application/json",errors:{500:"Internal Server Error"}})}proofStatus(e){return this.httpRequest.request({method:"GET",url:"/api/v1/proof/{proof_id}/status",path:{proof_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}teamAvatarUpload(e){return this.httpRequest.request({method:"POST",url:"/api/v1/team/avatar/upload",formData:e,mediaType:"multipart/form-data",errors:{400:"Bad Request",500:"Internal Server Error"}})}teamCreate(e,o){return this.httpRequest.request({method:"POST",url:"/api/v1/team/create",headers:{"Sindri-Team-Id":o},body:e,mediaType:"application/json",errors:{400:"Bad Request",409:"Conflict",500:"Internal Server Error"}})}teamDetail(e){return this.httpRequest.request({method:"GET",url:"/api/v1/team/{team_slug}/detail",path:{team_slug:e},errors:{404:"Not Found"}})}teamInvite(e,o){return this.httpRequest.request({method:"POST",url:"/api/v1/team/invite",headers:{"Sindri-Team-Id":o},body:e,mediaType:"application/json"})}teamMe(){return this.httpRequest.request({method:"GET",url:"/api/v1/team/me"})}teamMembers(e,o){return this.httpRequest.request({method:"GET",url:"/api/v1/team/{team_slug}/members",path:{team_slug:e},headers:{"Sindri-Team-Id":o},errors:{404:"Not Found"}})}teamRemoveMember(e,o){return this.httpRequest.request({method:"POST",url:"/api/v1/team/remove-member",headers:{"Sindri-Team-Id":o},body:e,mediaType:"application/json",errors:{403:"Forbidden",404:"Not Found"}})}teamSettings(e){return this.httpRequest.request({method:"POST",url:"/api/v1/team/settings",body:e,mediaType:"application/json",errors:{404:"Not Found",422:"Unprocessable Entity",500:"Internal Server Error"}})}userLogin(e){return this.httpRequest.request({method:"POST",url:"/api/v1/user/login",body:e,mediaType:"application/json",errors:{401:"Unauthorized",403:"Forbidden"}})}userLogout(){return this.httpRequest.request({method:"POST",url:"/api/v1/user/logout"})}userMe(){return this.httpRequest.request({method:"GET",url:"/api/v1/user/me"})}userPassword(e){return this.httpRequest.request({method:"POST",url:"/api/v1/user/password",body:e,mediaType:"application/json",errors:{422:"Unprocessable Entity"}})}};var oe=class{constructor(e){this.httpRequest=e}proofDetail(e,o=!0,n=!0,i=!0,s=!0){return this.httpRequest.request({method:"GET",url:"/api/v1/proof/{proof_id}/detail",path:{proof_id:e},query:{include_proof:o,include_public:n,include_smart_contract_calldata:i,include_verification_key:s},errors:{404:"Not Found",500:"Internal Server Error",501:"Not Implemented"}})}proofDelete(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/proof/{proof_id}/delete",path:{proof_id:e},errors:{404:"Not Found",500:"Internal Server Error"}})}};var ie=class{constructor(e){this.httpRequest=e}jwtTokenVerify(e){return this.httpRequest.request({method:"POST",url:"/api/token/verify",body:e,mediaType:"application/json"})}jwtTokenGenerate(e){return this.httpRequest.request({method:"POST",url:"/api/token/pair",body:e,mediaType:"application/json",errors:{403:"Forbidden"}})}jwtTokenRefresh(e){return this.httpRequest.request({method:"POST",url:"/api/token/refresh",body:e,mediaType:"application/json"})}};var ne=class{authorization;circuits;internal;proofs;token;request;constructor(e,o=ge){this.request=new o({BASE:e?.BASE??"https://sindri.app",VERSION:e?.VERSION??"1.17.30",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.authorization=new ee(this.request),this.circuits=new te(this.request),this.internal=new re(this.request),this.proofs=new oe(this.request),this.token=new ie(this.request)}};var W=y(require("fs")),$e=y(require("path")),nt=y(require("env-paths")),V=y(require("lodash")),N=require("zod"),st=()=>{let t=(0,nt.default)("sindri",{suffix:""});return $e.default.join(t.config,"sindri.conf.json")},je=N.z.object({auth:N.z.nullable(N.z.object({apiKey:N.z.string(),apiKeyId:N.z.string(),apiKeyName:N.z.string(),baseUrl:N.z.string().url(),teamId:N.z.number(),teamSlug:N.z.string()})).default(null)}),Tr=je.parse({}),xr=t=>{let e=st();if(W.default.existsSync(e)){t?.debug(`Loading config from "${e}".`);try{let o=W.default.readFileSync(e,{encoding:"utf-8"}),n=je.parse(JSON.parse(o));return t?.debug("Config loaded successfully."),n}catch(o){t?.warn(`The config schema in "${e}" is invalid and will not be used. To remove it and start fresh, run: rm ${e}`),t?.debug(o)}}return t?.debug(`Config file "${e}" does not exist, initializing default config.`),V.default.cloneDeep(Tr)},D=class{_config;logger;constructor(e){this.logger=e,this.reload()}get auth(){return V.default.cloneDeep(this._config.auth)}get config(){return V.default.cloneDeep(this._config)}reload(){this._config=xr(this.logger)}update(e){this.logger?.debug("Merging in config update:"),this.logger?.debug(e);let o=V.default.cloneDeep(this._config);V.default.merge(o,e),this._config=je.parse(o);let n=st(),i=$e.default.dirname(n);W.default.existsSync(i)||W.default.mkdirSync(i,{recursive:!0}),this.logger?.debug(`Writing merged config to "${n}":`,this._config),W.default.writeFileSync(n,JSON.stringify(this._config,null,2),{encoding:"utf-8"})}};var at=y(require("pino")),ct=y(require("pino-pretty")),De=t=>{let e=(0,at.default)(process.env.BROWSER_BUILD?{browser:{asObject:!0}}:(0,ct.default)({colorize:!0,destination:2,ignore:"hostname,pid",levelFirst:!1,sync:!0}));return e.level=t??!0?"silent":"info",e},Ko=De(),q=console.log;var M=null;function se({cache:t=!0,logger:e,raiseExceptions:o=!1}={}){if(t&&M)return M;if(process.env.BROWSER_BUILD)return M={};let{SINDRI_META:n}=process.env;if(!n)return M={};let i=([c,a])=>{if(typeof a!="string"){let p=`Invalid metadata entry for '${c}' (value must be a string).`;if(o)throw new Error(p);return e?.warn({key:c,value:a,SINDRI_META:n},p+" Ignoring."),!1}let u=he(c,a);if(u){if(o)throw new Error(u);return e?.warn({key:c,value:a,SINDRI_META:n},u+" Ignoring."),!1}return!0};if(n.startsWith("{"))try{return M=Object.fromEntries(Object.entries(JSON.parse(n)).filter(i))}catch(c){let a="Failed to parse 'SINDRI_META' as JSON.";if(o)throw new Error(a);return e?.warn({SINDRI_META:n,error:c.toString()},a+" Using '{}' as the default."),M={}}let s="\0";return M=Object.fromEntries(n.replace(/::/g,s).split(":").map(c=>c.replace(new RegExp(s,"g"),":")).filter(c=>{if(!c.includes("=")){let a=`Invalid 'SINDRI_META' metadata segment '${c}' (missing '=', try 'key=value').`;if(o)throw new Error(a);return e?.warn({segment:c,SINDRI_META:n},a+" Ignoring."),!1}return!0}).map(c=>{let a=c.indexOf("=");return[c.slice(0,a),c.slice(a+1)]}).filter(i))}function qe(t){let e=se({raiseExceptions:!0});return Object.entries(t).forEach(([o,n])=>{let i=he(o,n);if(i)throw new Error(i)}),{...e,...t}}function he(t,e){let c=/^[a-zA-Z][a-zA-Z0-9_-]*$/;return t.length<1||t.length>64?`Invalid metadata key length for '${t}' (must be 1-64 characters).`:c.test(t)?e.length<0||e.length>4096?`Invalid metadata value length for '${t}' (must be 0-4096 characters).`:null:`Invalid metadata key for '${t}' (must start with an alphabet character and only include alphanumeric characters, underscores, and hyphens).`}var be=class t{_client;_clientConfig;_config;logger;pollingInterval=1e3;retryOptions={minTimeout:1e3,retries:6};constructor(e={},{retryOptions:o}={}){this._client=new ne,this._clientConfig=this._client.request.config;let n="v0.0.1-alpha.73";this._clientConfig.HEADERS={...this._clientConfig.HEADERS,"Sindri-Client":`sindri-js-sdk/${n}`},this.logger=De(),process.env.BROWSER_BUILD||(this._config=new D(this.logger)),this._clientConfig.sindri=this,this.authorize(e),o&&(this.retryOptions=structuredClone(o))}get apiKey(){return this._clientConfig.TOKEN&&typeof this._clientConfig.TOKEN!="string"?null:this._clientConfig.TOKEN||null}get baseUrl(){return this._clientConfig.BASE}get logLevel(){return this.logger.level}set logLevel(e){this.logger.level=e,this.logger.debug(`Set log level to "${this.logger.level}".`)}authorize(e){return process.env.BROWSER_BUILD?(this._clientConfig.BASE=e.baseUrl||"https://sindri.app",this._clientConfig.TOKEN=e.apiKey):(this._config.reload(),this._clientConfig.BASE=e.baseUrl||process.env.SINDRI_BASE_URL||this._config.auth?.baseUrl||this._clientConfig.BASE||"https://sindri.app",this._clientConfig.TOKEN=e.apiKey||process.env.SINDRI_API_KEY||this._config.auth?.apiKey),!!(this._clientConfig.BASE&&this._clientConfig.TOKEN)}create(e,o){return new t(e,o)}async createCircuit(e,o=["latest"],n={}){let i=new K;o=typeof o=="string"?[o]:o??[];for(let a of o){if(!/^[-a-zA-Z0-9_.]+$/.test(a))throw new Error(`"${a}" is not a valid tag. Tags may only contain alphanumeric characters, underscores, hyphens, and periods.`);i.append("tags",a)}if(o.length===0&&i.append("tags",""),i.append("meta",JSON.stringify(qe(n))),typeof e=="string"){if(process.env.BROWSER_BUILD)throw new Error("Specifying `project` as a path is not allowed in the browser build.");let a;try{a=await(0,ae.stat)(e)}catch{throw new Error(`The "${e}" path does not exist or you do not have permission to access it.`)}if(a.isFile()){if(!/\.(zip|tar|tar\.gz|tgz)$/i.test(e))throw new Error("Only gzipped tarballs or zip files are supported.");let u=ye.default.basename(e),p=await(0,ae.readFile)(e);i.append("files",new Q([p],u))}else if(a.isDirectory()){let u=ye.default.join(e,"sindri.json"),p;try{p=await(0,ae.readFile)(u,{encoding:"utf-8"})}catch{throw new Error(`Expected Sindri manifest file at "${u}" does not exist.`)}let d;try{d=JSON.parse(p)}catch{throw new Error(`Could not parse "${u}", is it valid JSON?`)}let m=d?.name;if(!m)throw new Error(`No circuit "name" field was found in "${u}", the manifest is invalid.`);let f=pt.default.sync({follow:!0,ignoreFiles:[".sindriignore"],path:e}).filter(b=>!/(^|\/)\.git(\/|$)/.test(b)),l=ye.default.basename(u);f.includes(l)||f.push(l);let h=`${m}.tar.gz`;f.sort((b,C)=>b.localeCompare(C));let g=ut.default.c({cwd:e,gzip:!0,onwarn:(b,C)=>{this.logger.warn(`While creating tarball: ${b} - ${C}`)},prefix:`${m}/`,sync:!0},f);i.append("files",new Q([g.read()],h))}else throw new Error(`The "${e}" path is not a file or directory.`)}else if(Array.isArray(e)){if(!e.every(l=>l instanceof Q))throw new Error("All entries in `project` must be `File` instances.");let a=e.find(l=>l.name==="sindri.json");if(!a)throw new Error("The `project` array must include a `sindri.json` file.");let u;try{u=JSON.parse(await a.text())}catch{throw new Error('Could not parse "sindri.json", is it valid JSON?')}let p=u?.name;if(!p)throw new Error('No circuit "name" field was found in "sindri.json", the manifest is invalid.');let d=new mt.default;e.sort((l,h)=>l.name.localeCompare(h.name));for(let l of e){let h=new Uint8Array(await l.arrayBuffer());await new Promise(g=>d.append(`${p}/${l.name}`,h,g))}let m=new Uint8Array(lt.default.zip(d.out)),f=new Q([m],`${p}.tar.gz`);process.env.BROWSER_BUILD,i.append("files",f)}let c=(await this._client.circuits.circuitCreate(i)).circuit_id;for(;;){let a=await this._client.internal.circuitStatus(c);if(a.status==="Ready"||a.status==="Failed")break;await new Promise(u=>setTimeout(u,this.pollingInterval))}return this._client.circuits.circuitDetail(c,!1)}async getAllCircuitProofs(e){return await this._client.circuits.circuitProofs(e)}async getAllCircuits(){return await this._client.circuits.circuitList()}async getCircuit(e){return await this._client.circuits.circuitDetail(e)}async getProof(e){return await this._client.proofs.proofDetail(e)}async proveCircuit(e,o,n=!1,i=!1,s={}){let a=(await this._client.circuits.proofCreate(e,{meta:qe(s),perform_verify:n,proof_input:o})).proof_id;for(;;){let u=await this._client.internal.proofStatus(a);if(u.status==="Ready"||u.status==="Failed")break;await new Promise(p=>setTimeout(p,this.pollingInterval))}return this._client.proofs.proofDetail(a,!0,!0,i,!0)}};var r=new be;var yt=new gt.Command().name("clone").description("Clone a circuit into a local directory.").argument("<circuit>","The circuit to clone.").argument("[directory]","The directory to clone the circuit into.").action(async(t,e)=>{let n=/^(?:([-a-zA-Z0-9_]+)\/)?([-a-zA-Z0-9_]+)(?::([-a-zA-Z0-9_.]+))?$/.exec(t);if(!n)return r.logger.error(`"${t}" is not a valid circuit identifier.`),L.default.exit(1);(0,dt.default)(n[2],"The circuit name must be provided.");let i=n[2],s=ft.default.resolve(e??i);if(Le.default.existsSync(s))return r.logger.error(`The directory "${s}" already exists. Aborting.`),L.default.exit(1);if(!r.apiKey||!r.baseUrl)return r.logger.warn("You must login first with `sindri login`."),L.default.exit(1);let c;r.logger.info(`Cloning the circuit "${t}" into "${s}".`);try{c=await r._client.internal.circuitDownload(t)}catch(a){return a instanceof P&&a.status===401?(r.logger.error("Your credentials are invalid. Please log in again with `sindri login`."),L.default.exit(1)):a instanceof P&&a.status===404?(r.logger.error(`The circuit "${t}" does not exist or you lack permission to access it.`),L.default.exit(1)):(r.logger.fatal("An unknown error occurred."),r.logger.error(a),L.default.exit(1))}try{Le.default.mkdirSync(s,{recursive:!0})}catch(a){return r.logger.fatal(`Failed to create the directory "${s}". Aborting.`),r.logger.error(a),L.default.exit(1)}await new Promise((a,u)=>{c.on("end",a),c.on("error",u),c.pipe(ht.default.x({cwd:s,noChmod:!0,noMtime:!0,onwarn:(p,d)=>{r.logger.warn(`While extracting tarball: ${p} - ${d}`)},preserveOwner:!1,preservePaths:!1,strip:1}))}),r.logger.info("Circuit cloned successfully.")});var Fe=require("@commander-js/extra-typings");var Er=new Fe.Command().name("list").description("Show the current config.").action(async()=>{r._config.reload(),q(r._config.config)}),bt=new Fe.Command().name("config").description("Commands related to configuration and config files.").addCommand(Er);var Et=y(require("assert")),Se=y(require("path")),$=y(require("process")),Ie=require("@commander-js/extra-typings");var Rt=y(require("assert")),Me=require("child_process"),G=require("fs"),T=require("fs/promises"),Ct=y(require("os")),x=y(require("path")),I=y(require("process")),wt=require("stream"),St=require("url"),Pt=y(require("axios")),It=require("compare-versions"),Re=y(require("dockerode")),vt=y(require("nunjucks"));var Ar=(0,St.fileURLToPath)(R),kr=x.default.dirname(Ar);function Or(t){return new Promise(e=>{let o=(0,Me.spawn)(t,["--version"]);o.on("error",()=>{e(!1)}),o.on("exit",n=>{e(n!==127&&n!==null)})})}async function He(t){let e=new Re.default;try{await e.ping()}catch(o){return t?.debug("Failed to connect to the Docker daemon."),t?.debug(o),!1}return t?.debug("Docker daemon is accessible."),!0}function Nr(t,e,o){let n=t.indexOf("=");n===-1&&(o.fatal(`Invalid metadata segment '${t}' (missing '=', try 'key=value'). Aborting.`),I.default.exit(1));let[i,s]=[t.slice(0,n),t.slice(n+1)],c=he(i,s);return c&&(o.fatal({key:i,value:s},`Invalid metadata entry '${t}'. ${c} Aborting.`),I.default.exit(1)),{...e,[i]:s}}var Ce=t=>(e,o)=>Nr(e,o,t),_r=new wt.Writable({write(t,e,o){o()}});async function Je(t,e=[],{cwd:o=I.default.cwd(),docker:n=new Re.default,logger:i,rootDirectory:s,tag:c="auto",tty:a=!1}){if(ze(I.default.env.SINDRI_FORCE_DOCKER??"false"))i?.debug(`Forcing docker usage for command "${t}" because "SINDRI_FORCE_DOCKER" is set to "${I.default.env.SINDRI_FORCE_DOCKER}".`);else{if(await Or(t))return i?.debug({args:e,command:t},`Executing the "${t}" command locally.`),{code:await $r(t,e,{cwd:o,logger:i,tty:a}),method:"local"};i?.debug(`The "${t}" command was not found locally, trying Docker instead.`)}return await He(i)?(i?.debug({args:e,command:t},`Executing the "${t}" command in a Docker container.`),{code:await we(t,e,{cwd:o,docker:n,logger:i,rootDirectory:s,tag:c,tty:a}),method:"docker"}):(i?.debug(`The "${t}" command is not available locally or in Docker.`),{code:null,method:null})}async function we(t,e=[],{cwd:o=I.default.cwd(),docker:n=new Re.default,logger:i,rootDirectory:s,tag:c="auto",tty:a=!1}){let u=E(/^sindri.json$/i,o);s||(u?s=x.default.dirname(u):(s=o,i?.warn(`No "sindri.json" file was found in or above "${o}", using the current directory as the project root.`))),s=x.default.normalize(x.default.resolve(s));let p;if(t==="nargo"&&c==="auto"){let h="latest";if(u)try{let g=await(0,T.readFile)(u,{encoding:"utf-8"}),b=JSON.parse(g);b.noirVersion&&(h=b.noirVersion,h&&!h.startsWith("v")&&(h=`v${h}`))}catch(g){i?.error(`Failed to parse the "${u}" file, using the "latest" tag for the "nargo" command.`),i?.debug(g)}else i?.warn(`No "sindri.json" file was found in or above "${o}", using the "latest" tag for the "nargo" command.`);p=`sindrilabs/${t}:${h}`}else if(["circomspect","nargo"].includes(t))p=`sindrilabs/${t}:${c==="auto"?"latest":c}`;else throw new Error(`The command "${t}" is not supported.`);i?.debug(`Pulling the "${p}" image.`);try{await new Promise((h,g)=>{n.pull(p,(b,C)=>{b?g(b):n.modem.followProgress(C,(w,v)=>w?g(w):h(v))})})}catch(h){return i?.error(`Failed to pull the "${p}" image.`),i?.error(h),I.default.exit(1)}let d=s;if(I.default.env.SINDRI_DEVELOPMENT_HOST_ROOT)if(s==="/sindri"||s.startsWith("/sindri/"))d=s.replace("/sindri",I.default.env.SINDRI_DEVELOPMENT_HOST_ROOT),i?.debug(`Remapped "${s}" to "${d}" for bind mount on the Docker host.`);else return i?.fatal(`The root directory path "${s}" must be under "/sindri/"when using "SINDRI_DEVELOPMENT_HOST_ROOT".`),I.default.exit(1);let m=x.default.relative(s,o),f;return m.startsWith("..")?(f="/sindri/",i?.warn(`The current working directory ("${o}") is not under the project root ("${s}"), will use the project root as the current working directory.`)):f=x.default.join("/sindri/",m),i?.debug(`Remapped the "${o}" working directory to "${f}" in the Docker container.`),(await new Promise((h,g)=>{n.run(p,e,a?[I.default.stdout,I.default.stderr]:_r,{AttachStderr:a,AttachStdin:a,AttachStdout:a,HostConfig:{Binds:[`${d}:/sindri`,"/tmp/sindri/:/tmp/sindri/"]},OpenStdin:a,StdinOnce:!1,Tty:a,WorkingDir:f},(b,C)=>{b?g(b):h(C)}).on("container",b=>{if(!a)return;let C=b.attach({stream:!0,stdin:!0,stdout:!0,stderr:!0},function(w,v){w&&g(w),v.pipe(I.default.stdout)});C&&C.resume()})})).StatusCode}async function $r(t,e=[],{cwd:o=I.default.cwd(),logger:n,tty:i=!1}){let s=(0,Me.spawn)(t,e,{cwd:o,stdio:i?"inherit":"ignore"});try{return await new Promise((a,u)=>{s.on("error",p=>{u(p)}),s.on("close",(p,d)=>{p==null&&d!=null&&(p=128+Ct.default.constants.signals[d]),(0,Rt.default)(p!=null),a(p)})})}catch(c){return n?.error(`Failed to execute the "${t}" command.`),n?.error(c),I.default.exit(1)}}async function Be(t){try{return await(0,T.access)(t,G.constants.F_OK),!0}catch{return!1}}function E(t,e=kr){let o=(0,G.readdirSync)(e);for(let i of o)if(typeof t=="string"?i===t:t.test(i))return x.default.join(e,i);let n=x.default.dirname(e);return n===e?null:E(t,n)}async function Tt(t,e="sindrilabs"){let o=`https://hub.docker.com/v2/repositories/${e}/${t}/tags/?page_size=1`,n=[];for(;o;){let i=await Pt.default.get(o);n=n.concat(i.data.results),o=i.data.next}return n.filter(({tag_status:i})=>i==="active").filter(({name:i})=>i!=="dev").sort((i,s)=>i.last_updated.localeCompare(s.last_updated)).map(({name:i})=>i).sort((i,s)=>i==="latest"?1:s==="latest"?-1:(0,It.compareVersions)(i,s))}function ze(t){return["1","true","t","yes","y","on"].includes(t.toLowerCase())}function xt(){let t=E("sindri-manifest.json");if(!t)throw new Error("A `sindri-manifest.json` file was unexpectedly not found.");let e=(0,G.readFileSync)(t,{encoding:"utf-8"});return JSON.parse(e)}async function Ue(t,e,o,n){let i=x.default.resolve(e);await Be(i)||await(0,T.mkdir)(i,{recursive:!0});let s=E("templates");if(!s)throw new Error("Root template directory not found.");let c=x.default.isAbsolute(t)?t:x.default.resolve(s,t);if(!await Be(c))throw new Error(`The "${c}" directory does not exist.`);let a=(p,d)=>{let m=p;return Object.entries(d).forEach(([f,l])=>{typeof l=="string"&&(m=m.replace(new RegExp(`template${f.toUpperCase()}`,"gi"),l))}),vt.default.renderString(m,d)},u=async(p,d)=>{if((await(0,T.stat)(p)).isDirectory()){if(await Be(d)||(await(0,T.mkdir)(d,{recursive:!0}),n?.debug(`Created directory: "${d}"`)),!(await(0,T.stat)(d)).isDirectory())throw new Error(`"File ${d} exists and is not a directory.`);let l=await(0,T.readdir)(p);await Promise.all(l.map(async h=>{let g=a(h,o);await u(x.default.join(p,h),x.default.join(d,g))}));return}let m=await(0,T.readFile)(p,{encoding:"utf-8"}),f=a(m,o);await(0,T.writeFile)(d,f,{encoding:"utf-8"}),n?.debug(`Rendered "${p}" template to "${d}".`)};await u(c,i)}var Pe,Y,Ke,jr=new Ie.Command().name("circomspect").description("Trail of Bit's Circomspect static analysis tool for Circom circuits.").helpOption(!1).addHelpCommand(!1).allowUnknownOption().passThroughOptions().argument("[args...]","Arguments to pass to the tool.").action(async t=>{if(!Pe)try{let e=await we("circomspect",t,{logger:r.logger,rootDirectory:Y,tag:Ke,tty:!0});$.default.exit(e)}catch(e){return r.logger.error("Failed to run the circomspect command."),r.logger.debug(e),$.default.exit(1)}}),Dr=new Ie.Command().name("nargo").description("Aztec Lab's Noir compiler and package manager.").helpOption(!1).addHelpCommand(!1).allowUnknownOption().passThroughOptions().argument("[args...]","Arguments to pass to the tool.").action(async t=>{if(!Pe)try{let e=await we("nargo",t,{logger:r.logger,rootDirectory:Y,tag:Ke,tty:!0});$.default.exit(e)}catch(e){return r.logger.error("Failed to run the nargo command."),r.logger.debug(e),$.default.exit(1)}}),At=new Ie.Command().name("exec").alias("x").description("Run a ZKP tool in your project root inside of an optimized docker container.").passThroughOptions().option("-l, --list-tags","List the available docker image tags for a given tool.").option("-t, --tag <tag>","The version tag of the docker image to use.","auto").addCommand(jr).addCommand(Dr).hook("preAction",async t=>{let e=t.opts();if(Pe=!!e.listTags,Ke=e.tag,Pe){let i=t.args[0];(0,Et.default)(i,"The preAction hook should only run if there's a subcommand.");try{(await Tt(i)).forEach(c=>q(c))}catch(s){return r.logger.fatal("Error listing available docker image tags."),r.logger.error(s),$.default.exit(1)}return $.default.exit(0)}let o=$.default.cwd(),n=E(/^sindri.json$/i,o);n?Y=Se.default.dirname(n):(Y=o,r.logger.warn(`No "sindri.json" file was found in or above "${o}", using the current directory as the project root.`)),Y=Se.default.normalize(Se.default.resolve(Y)),await He(r.logger)||(r.logger.fatal(`Docker is either not installed or the daemon isn't currently running, but it is required by "sindri exec". Please install Docker by following the instructions at: https://docs.docker.com/get-docker/`),$.default.exit(1))});var H=require("child_process"),O=require("fs"),ce=y(require("path")),ve=y(require("process")),kt=require("@commander-js/extra-typings"),S=require("@inquirer/prompts");var Ot=new kt.Command().name("init").description("Initialize a new Sindri project.").argument("[directory]","The directory where the new project should be initialized.",".").action(async t=>{let e=ce.default.resolve(t),o=ce.default.basename(e);if(!(0,O.existsSync)(e))(0,O.mkdirSync)(e,{recursive:!0});else if(!(0,O.statSync)(e).isDirectory())return r.logger.warn(`File "${e}" exists and is not a directory, aborting.`),ve.default.exit(1);if((0,O.readdirSync)(e).length>0&&!await(0,S.confirm)({message:`The "${e}" directory already exists and contains files. Continuing will overwrite your existing files. Are you *SURE* you would like to proceed?`,default:!1}))return r.logger.info("Aborting."),ve.default.exit(1);let i=await(0,S.input)({message:"Circuit Name:",default:o.replace(/[^-a-zA-Z0-9_]/g,"-"),validate:m=>m.length===0?"You must specify a circuit name.":/^[-a-zA-Z0-9_]+$/.test(m)?!0:"Only alphanumeric characters, hyphens, and underscores are allowed."}),s=await(0,S.select)({message:"Proving Framework:",default:"circom",choices:[{name:"Circom",value:"circom"},{name:"Gnark",value:"gnark"},{name:"Halo2",value:"halo2"},{name:"Jolt",value:"jolt"},{name:"Noir",value:"noir"},{name:"Plonky2",value:"plonky2"},{name:"SP1",value:"sp1"}]}),c={circuitName:i,circuitType:s},a=s;if(s==="circom"){let m=await(0,S.select)({message:"Proving Scheme:",default:"groth16",choices:[{name:"Groth16",value:"groth16"}]}),f=await(0,S.select)({message:"Curve Name:",default:"bn254",choices:[{name:"BN254",value:"bn254"}]}),l=await(0,S.select)({message:"Witness Compiler:",default:"c++",choices:[{name:"C++",value:"c++"},{name:"Wasm",value:"wasm"}]});Object.assign(c,{curveName:f,provingScheme:m,witnessCompiler:l})}else if(s==="gnark"){let m=await(0,S.input)({message:"Go Package Name:",default:i.replace(/[^a-zA-Z0-9]/g,"").replace(/^[^a-z]*/g,""),validate:g=>g.length===0?"You must specify a package name.":/^[a-z][a-z0-9]*$/.test(g)?!0:"Package names must begin with a lowercase letter and only be followed by alphanumeric characters."}),f=await(0,S.select)({message:"Proving Scheme:",default:"groth16",choices:[{name:"Groth16",value:"groth16"},{name:"PlonK",value:"plonk"}]}),l=await(0,S.select)({message:"Curve Name:",default:"bn254",choices:[{name:"BN254",value:"bn254"},{name:"BLS12-377",value:"bls12-377"},{name:"BLS12-381",value:"bls12-381"},{name:"BLS24-315",value:"bls24-315"},{name:"BW6-633",value:"bw6-633"},{name:"BW6-761",value:"bw6-761"}]}),h=l.toUpperCase().replace("-","_");Object.assign(c,{curveName:l,gnarkCurveName:h,packageName:m,provingScheme:f})}else if(s==="halo2"){let m=await(0,S.select)({message:"Halo2 Base Version:",default:"axiom-v0.3.0",choices:[{name:"Axiom v0.3.0",value:"axiom-v0.3.0"},{name:"PSE v0.3.0",value:"pse-v0.3.0"}]}),f=await(0,S.input)({message:"Halo2 Package Name:",default:i.toLowerCase().replace(/[^a-z0-9_]+/,"_").replace(/_+/g,"_").replace(/-+/g,"-"),validate:C=>C.length===0?"You must specify a package name.":/^[a-z0-9_]+(?:-[a-z0-9_]+)*$/.test(C)?!0:"Package names must begin with a lowercase letter, number, or underscore, and only be followed by lowercase or numeric characters and underscores (optionally separated by hyphens)."}),l=parseInt(await(0,S.input)({message:"Degree:",default:"13",validate:C=>C.length===0?"You must specify a degree.":/^[1-9]\d*$/.test(C)?!0:"Degree must be a positive integer."}),10),h=m==="axiom-v0.3.0"?await(0,S.select)({message:"Halo2 Base Version:",default:"GateThreadBuilder",choices:[{name:"Gate Thread Builder",value:"GateThreadBuilder"}]}):void 0,g=m!=="axiom-v0.3.0"?"::circuit::EqualCircuit":"::circuit_def::CircuitInput",b=`${f.replace(/-/g,"_")}${g}`;a=`${a}/${m}`,Object.assign(c,{className:b,halo2Version:m,degree:l,packageName:f,threadBuilder:h})}else if(s==="jolt"){let m=await(0,S.input)({message:"Jolt Package Name:",default:i.toLowerCase().replace(/[^a-z0-9_]+/,"_").replace(/_+/g,"_").replace(/-+/g,"-"),validate:h=>h.length===0?"You must specify a package name.":/^[a-z0-9_]+(?:-[a-z0-9_]+)*$/.test(h)?!0:"Package names must begin with a lowercase letter, number, or underscore, and only be followed by lowercase or numeric characters and underscores (optionally separated by hyphens)."}),f=await(0,S.select)({message:"Commitment Scheme:",default:"hyperkzg",choices:[{name:"HyperKZG",value:"hyperkzg"},{name:"Zeromorph",value:"zeromorph"}]}),l=await(0,S.confirm)({message:"Use Rust standard library:",default:!0});Object.assign(c,{commitmentScheme:f,packageName:m,stdEnabled:l})}else if(s==="noir"){let m=await(0,S.input)({message:"Noir Package Name:",default:i.toLowerCase().replace(/[- ]/g,"_").replace(/[^a-zA-Z0-9_]+/,"").replace(/_+/g,"_"),validate:h=>h.length===0?"You must specify a package name.":/^[a-zA-Z0-9_]+$/.test(h)?!0:"Package names must only contain alphanumeric characters and underscores."}),f=await(0,S.select)({message:"Noir Version:",default:"0.23.0",choices:[{name:"0.17.0",value:"0.17.0"},{name:"0.18.0",value:"0.18.0"},{name:"0.19.4",value:"0.19.4"},{name:"0.22.0",value:"0.22.0"},{name:"0.23.0",value:"0.23.0"}]}),l=await(0,S.select)({message:"Proving Scheme:",default:"barretenberg",choices:[{name:"Barretenberg",value:"barretenberg"}]});Object.assign(c,{packageName:m,noirVersion:f,provingScheme:l})}else if(s==="plonky2"){let m=await(0,S.input)({message:"Plonky2 Package Name:",default:i.toLowerCase().replace(/[^a-z0-9_]+/,"_").replace(/_+/g,"_").replace(/-+/g,"-"),validate:h=>h.length===0?"You must specify a package name.":/^[a-z0-9_]+(?:-[a-z0-9_]+)*$/.test(h)?!0:"Package names must begin with a lowercase letter, number, or underscore, and only be followed by lowercase or numeric characters and underscores (optionally separated by hyphens)."}),f=await(0,S.input)({message:"Full path to circuit struct:",default:"Circuit",validate:h=>/^[A-Z][A-Za-z0-9_]*$/.test(h)?!0:"Struct name must begin with an uppercase letter and contain only alphanumeric characters and underscores."}),l=await(0,S.select)({message:"Plonky2 Version:",default:"0.2.2",choices:[{name:"0.2.0",value:"0.2.0"},{name:"0.2.1",value:"0.2.1"},{name:"0.2.2",value:"0.2.2"}]});Object.assign(c,{packageName:m,plonky2Version:l,structName:f})}else if(s==="sp1"){let m=await(0,S.select)({message:"Proving Scheme:",default:"groth16",choices:[{name:"Compressed",value:"compressed"},{name:"Core",value:"core"},{name:"Groth16",value:"groth16"},{name:"Plonk",value:"plonk"}]});Object.assign(c,{provingScheme:m})}else return r.logger.fatal(`Sorry, ${s} is not yet supported.`),ve.default.exit(1);r.logger.info(`Proceeding to generate scaffolded project in "${e}".`),await Ue("common",e,c,r.logger),await Ue(a,e,c,r.logger);let u=ce.default.join(e,".gitkeep");if((0,O.existsSync)(u)&&(0,O.rmSync)(u),r.logger.info("Project scaffolding successful."),s==="circom"){let m=!1;try{(0,H.execSync)("npm --version"),m=!0}catch{r.logger.warn("NPM is not installed, cannot install circomlib as a dependency. You will need to install NPM and run `npm install` yourself.")}m&&(r.logger.info("Installing circomlib."),(0,H.execSync)("npm install",{cwd:e}))}let p=!1;try{(0,H.execSync)("git --version"),p=!0}catch{r.logger.debug("Git is not installed, skipping git initialization questions.")}let d=(0,O.existsSync)(ce.default.join(e,".git"));if(p&&!d&&await(0,S.confirm)({message:`Would you like to initialize a git repository in "${e}"?`,default:!0})){r.logger.info(`Initializing git repository in "${e}".`);try{(0,H.execSync)("git init .",{cwd:e}),(0,H.execSync)("git add .",{cwd:e}),(0,H.execSync)("git commit -m 'Initial commit.'",{cwd:e}),r.logger.info("Successfully initialized git repository.")}catch(f){r.logger.error("Error occurred while initializing the git repository.");let l=f;["output","stderr","stdout"].forEach(g=>{g in l&&(l[g]="<truncated>")}),r.logger.error(l)}}});var Nt=y(require("assert")),_t=require("buffer"),xe=require("fs"),Te=y(require("path")),k=y(require("process")),$t=require("@commander-js/extra-typings"),jt=require("formdata-node"),Dt=y(require("ignore-walk")),qt=y(require("tar"));function qr(t,e){let o=e.isNotDefault?e.concat([t]):[t];return o.isNotDefault=!0,o}var Lt=new $t.Command().name("deploy").description("Deploy the current Sindri project.").option("-m, --meta <key=value>","Metadata key/value to attach to the circuit build.",Ce(r.logger),se({logger:r.logger,raiseExceptions:!1})).option("-t, --tag <tag>","Tag to apply to the circuit.",qr,["latest"]).option("-u, --untagged","Discard the current circuit after compiling.").argument("[directory]","The location of the Sindri project to deploy.",".").action(async(t,{meta:e,tag:o,untagged:n})=>{if(n){if(o.length!==1||o[0]!=="latest"||o.isNotDefault)return r.logger.error("You cannot use both the `--tag` and `--untagged` options together."),k.default.exit(1)}else for(let g of o)if(!/^[-a-zA-Z0-9_.]+$/.test(g))return r.logger.error(`"${g}" is not a valid tag. Tags may only contain alphanumeric characters, underscores, hyphens, and periods.`),k.default.exit(1);let i=Te.default.resolve(t);if(!(0,xe.existsSync)(i))return r.logger.error(`The "${i}" directory does not exist. Aborting.`),k.default.exit(1);let s=E(/^sindri.json$/i,i);if(!s)return r.logger.error(`No "sindri.json" file was found in or above "${i}". Aborting.`),k.default.exit(1);r.logger.debug(`Found "sindri.json" at "${s}".`);let c=Te.default.dirname(s);r.logger.debug(`Changing current directory to "${c}".`),k.default.chdir(c);let a={};try{let g=(0,xe.readFileSync)(s,{encoding:"utf-8"});a=JSON.parse(g),r.logger.debug(`Successfully loaded "sindri.json" from "${s}":`),r.logger.debug(a)}catch(g){return r.logger.fatal(`Error loading "${s}", perhaps it is not valid JSON?`),r.logger.error(g),k.default.exit(1)}if(!("name"in a))return r.logger.error('No "name" field found in "sindri.json". Aborting.'),k.default.exit(1);let u=a.name;if(!r.apiKey||!r.baseUrl)return r.logger.warn("You must login first with `sindri login`."),k.default.exit(1);let p=Dt.default.sync({follow:!0,ignoreFiles:[".sindriignore"],path:"."}).filter(g=>!/(^|\/)\.git(\/|$)/.test(g)),d=Te.default.basename(s);p.includes(d)||p.push(d);let m=new jt.FormData,f=`${u}.tar.gz`;if(r.logger.info(`Creating "${f}" package with ${p.length} files.`),m.append("files",new _t.Blob([qt.default.c({gzip:!0,onwarn:(g,b)=>{r.logger.warn(`While creating tarball: ${g} - ${b}`)},prefix:`${u}/`,sync:!0},p).read()]),f),m.append("meta",JSON.stringify(e)),n)m.append("tags","");else for(let g of o)m.append("tags",g);let l;try{r.logger.info("Circuit compilation initiated."),l=(await r._client.circuits.circuitCreate(m)).circuit_id}catch(g){if(g instanceof P&&g.status===401)r.logger.error("Your credentials are invalid. Please log in again with `sindri login`.");else return r.logger.fatal("An unknown error occurred."),r.logger.error(g),k.default.exit(1)}if(!l)return r.logger.error("No circuit ID was returned from the API. Aborting."),k.default.exit(1);let h=Date.now();for(;;){try{r.logger.debug("Polling for circuit compilation status.");let g=await r._client.internal.circuitStatus(l),b=["Failed","Ready"].includes(g.status)?await r._client.circuits.circuitDetail(l,!1):null,C=((Date.now()-h)/1e3).toFixed(1);if(g.status==="Ready"){r.logger.info(`Circuit compiled successfully after ${C} seconds.`);break}else{if(g.status==="Failed")return(0,Nt.default)(b!=null),r.logger.error(`Circuit compilation failed after ${C} seconds: `+(b.error??"Unknown error.")),k.default.exit(1);g.status==="Queued"?r.logger.debug("Circuit compilation is queued."):g.status==="In Progress"&&r.logger.debug("Circuit compilation is in progress.")}}catch(g){return r.logger.fatal("An unknown error occurred while polling for compilation to finish."),r.logger.error(g),k.default.exit(1)}await new Promise(g=>setTimeout(g,1e3))}});var Ft=y(require("assert")),Bt=require("crypto"),F=require("fs"),J=y(require("path")),_=y(require("process")),Mt=require("@commander-js/extra-typings"),Ht=require("jsonschema");var Jt=new Mt.Command().name("lint").description("Lint the current Sindri project for potential issues.").argument("[directory]","The directory, or subdirectory, of the project to lint.",".").action(async t=>{let e=0,o=0,n;try{if(n=xt(),!n)throw new Error('No "sindri-manifest.json" file found.');r.logger.debug('Successfully loaded "sindri-manifest.json".')}catch{return r.logger.error('No "sindri-manifest.json" JSON Schema file found. Aborting.'),_.default.exit(1)}let i=J.default.resolve(t);if(!(0,F.existsSync)(i))return r.logger.error(`The "${i}" directory does not exist. Aborting.`),_.default.exit(1);let s=E(/^sindri.json$/i,i);if(!s)return r.logger.error(`No "sindri.json" file was found in or above "${i}". Aborting.`),_.default.exit(1);r.logger.debug(`Found "sindri.json" at "${s}".`);let c=J.default.dirname(s);r.logger.debug(`Changing current directory to "${c}".`),_.default.chdir(i);let a={};try{let l=(0,F.readFileSync)(s,{encoding:"utf-8"});a=JSON.parse(l),r.logger.debug(`Successfully loaded "sindri.json" from "${s}":`),r.logger.debug(a)}catch(l){return r.logger.fatal(`Error loading "${s}", perhaps it is not valid JSON?`),r.logger.error(l),_.default.exit(1)}(0,Ft.default)(Array.isArray(n.anyOf));let u;!("circuitType"in a)||!a.circuitType?u=void 0:a.circuitType==="circom"?u=n.anyOf.find(l=>/circom/i.test(l.$ref??"")):a.circuitType==="gnark"?u=n.anyOf.find(l=>/gnark/i.test(l.$ref??"")):a.circuitType==="halo2"?"halo2Version"in a&&a.halo2Version==="axiom-v0.2.2"?u=n.anyOf.find(l=>/halo2axiomv022/i.test(l.$ref??"")):"halo2Version"in a&&a.halo2Version==="axiom-v0.3.0"?u=n.anyOf.find(l=>/halo2axiomv030/i.test(l.$ref??"")):u={anyOf:n.anyOf.filter(l=>/halo2/i.test(l.$ref??""))}:a.circuitType==="noir"&&(u=n.anyOf.find(l=>/noir/i.test(l.$ref??""))),u?(delete n.anyOf,n={...n,...u}):(r.logger.warn(`Circuit type is not configured in "${s}" so some linting steps will be skipped and the manifest linting output will be very noisy. Please correct "circuitType" in "sindri.json" and rerun "sindri lint" to get better linting.`),o+=1);let p="circuitType"in a&&typeof a.circuitType=="string"&&["circom","gnark","halo2","noir"].includes(a.circuitType)?a.circuitType:null;p?r.logger.debug(`Detected circuit type "${p}".`):r.logger.debug("No circuit type detected!");let m=new Ht.Validator().validate(a,n,{nestedErrors:!0});if(m.valid)r.logger.info(`Sindri manifest file "${s}" is valid.`);else{r.logger.warn(`Sindri manifest file "${s}" contains errors:`);for(let l of m.errors){let h=l.property.replace(/^instance/,"sindri.json").