@dereekb/zoho 13.11.9 → 13.11.11
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/cli/index.js +2 -2
- package/cli/package.json +7 -7
- package/index.cjs.js +5 -7
- package/index.esm.js +5 -7
- package/nestjs/package.json +5 -5
- package/package.json +8 -8
package/cli/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __createRequire } from 'node:module';
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
|
-
var dc=Object.defineProperty;var lc=Object.getOwnPropertyDescriptor;var Z=(e,t,o,r)=>{for(var n=r>1?void 0:r?lc(t,o):t,i=e.length-1,a;i>=0;i--)(a=e[i])&&(n=(r?a(t,o,n):a(n))||n);return r&&n&&dc(t,o,n),n},b=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as hc,mkdirSync as mc,writeFileSync as yc}from"node:fs";import{join as gc}from"node:path";var to=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],nt={},Cr=[...to],eo;function oo(e){nt=e}function At(){return nt}function ro(e){Cr=e}function xr(e){eo=e}function ue(e){let t=e;for(let o of Cr)t=t.replace(o,"[REDACTED]");return t}function Fr(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function at(e,t){let{dumpDir:o,commandPath:r}=nt;if(!o)return;hc(o)||mc(o,{recursive:!0});let n=r?.length?r.join("_"):"response",i=Fr(),a=t?`${n}_${i}_${t}`:`${n}_${i}`;return gc(o,`${a}.${e}`)}function fc(e,t){let o=at("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};yc(o,JSON.stringify(r,null,2))}function Ze(e,t){let o=t.split(",").map(r=>r.trim());return Array.isArray(e)?e.map(r=>Tr(r,o)):e!=null&&typeof e=="object"?Tr(e,o):e}function Tr(e,t){if(e==null||typeof e!="object")return e;let o={};for(let r of t)r in e&&(o[r]=e[r]);return o}function h(e,t){fc(e,t);let r={ok:!0,data:nt.pick?Ze(e,nt.pick):e,...t?{meta:t}:{}};console.log(JSON.stringify(r))}function Zr(e){console.log(JSON.stringify(no(e)))}var it=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function no(e){if(eo){let t=eo(e);if(t)return t}return e instanceof it?{ok:!1,error:ue(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?{ok:!1,error:ue(e.message),code:"ERROR"}:{ok:!1,error:ue(String(e)),code:"UNKNOWN_ERROR"}}function ve(e,t=!1){return typeof e=="string"?t:e!=null&&typeof e=="object"&&Symbol.iterator in e}function st(e){for(let t of e)return!1;return!0}function io(e,t){for(let o of e)t(o)}function B(e,t,o=!1){e!=null&&(ve(e,o)?io(e,t):t(e))}function Sr(e){if(!Array.isArray(e))throw new Error("Input is not an array/tuple...");let t;if(e.length>0){let o=e[0],r=!1;if(Array.isArray(o)){let n=o.length;r=e.findIndex(a=>Array.isArray(a)?a.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function Rc(e){return e!=null?Tc(e):[]}var C=Rc;function Tc(e){return Array.isArray(e)?e:[e]}function Ar(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function ao(e){return Object.keys(e).length===0}function kr(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function br(e){return{...e}}function Ir(e){return e!=null}function kt(e){return ve(e,!1)?!st(e):Pr(e)}function so(e){let t;return ve(e,!0)?t=!st(e):Pr(e)?t=typeof e=="object"?!ao(e):!0:t=!1,t}function Pr(e){return e!=null&&e!==""}function Cc(e){return(t=>{let o;return t!=null?o=t.filter((r,n,i)=>e(r,n,i)):o=[],o})}var he=Cc(Ir);function Er({base:e,build:t}){let o=e??{};return t(o),o}var xc=(e=>e);function Or(){return xc}function we(e,t){let o=Fc(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Fc(e,t){return kr(Zc(e,t))}function Zc(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),i=o.get(n);i!=null?i.push(r):o.set(n,[r])}),o}function Dr(e,t,o){return C(t).forEach(r=>e.set(r,o)),e}function co(e){return Array.from(e.entries())}function Mr(e){return Sc(co(e))}function Sc(e){let t=[];return e.forEach(([o,r])=>{B(r,n=>{t.push([o,n])})}),t}function _r(){let e=new Map,t=(n,i)=>{let a=e.get(n);a==null&&(a=[],e.set(n,a)),B(i,s=>a.push(s))},o=(n,i)=>t(n,Sr(i));return{map:()=>e,entries:()=>co(e),tuples:()=>Mr(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,i)=>B(n,a=>t(a,i)),addTuplesToKeys:(n,i)=>B(n,a=>o(a,i)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function Ac(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function vr(e){let t=Ac(e);return t!=null&&t!=="class"}function wr(e){return vr(e)?e:()=>e}function Nr(e,t){return Math.log(t)/Math.log(e)}var Ur=",",kc=" ";function bc(e,t=Ur,o=!1){if(e==null)return e;let r=C(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function uo(e,t,o){let r=e.split(t),n=[];if(r.length>1){let i=r.length>o,a=i?o-1:r.length;for(let s=0;s<a;s+=1)n.push(r[s]);i&&n.push(r.slice(a).join(t))}else n.push(r[0]);return n}function Ic(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return bc(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function Lr(e){let{joiner:t}=e,o=Ic(e),r=(n,i=a=>a)=>n.split(t).map(s=>i(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,i){return uo(n,t,i)}}}var po=Lr({joiner:Ur}),Pc=Lr({joiner:kc,trimByDefault:!0});var P=po.joinStrings,bh=po.splitStrings,Ih=po.splitStringsToSet,Ph=Pc.joinStrings;var Gr=Ar;function Vr(e,{forEach:t,filter:o}){Ec(e,o).forEach((n,i)=>t(n,i))}function Ec(e,t){return lo(t)(e)}function lo(e){let t;if(e!=null){let o=Oc(e);t=r=>Kr(r).filter((n,i)=>o(n,i))}else t=Kr;return t}function Kr(e){return Object.entries(e)}function ho(e){return typeof e=="object"?e:{valueFilter:e}}function Oc(e){let t=ho(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,i;switch(o){case 1:i=([,a])=>a!==void 0;break;case 2:i=([,a])=>a!=null;break;case 3:i=([,a])=>!!a;break;case 4:i=([,a])=>kt(a);break;case 5:i=([,a])=>so(a);break;case 6:i=([,a])=>!!a&&kt(a);break;case 7:i=([,a])=>!!a&&so(a);break;default:i=()=>!0;break}if(n){let a=i,s=new Set(n.map(c=>c.toString()));i=(c,u)=>a(c,u)&&s.has(c[0])}return Gr(i,r)}function ct(e){let t,o=n=>{t={value:e(n)}},r=(n=>(t||o(n),t.value));return r.set=n=>t={value:n},r.reset=()=>t=void 0,r.init=o,r.used=()=>!!t,r}function Dc({filter:e,copy:t,dynamic:o=!1}){let r=e!=null?Ne({filter:e,copy:!1}):_c;return n=>{let i=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},a=o?i:ct(i);return s=>{let c=a();return t&&(s=br(s)),Object.assign(s,c),s}}}function zr(e,t){return Mc(t)(e)}function Mc(e){let t=Dc({filter:e,copy:!1,dynamic:!0});return o=>t(he(o))({})}var Vh=Ne({copy:!0,filter:{valueFilter:1}}),zh=Ne({copy:!0,filter:{valueFilter:2}}),Hr=Ne({copy:!0,filter:{valueFilter:4}}),Hh=Ne({copy:!0,filter:{valueFilter:6}}),jh=mo({valueFilter:1}),Wh=mo({valueFilter:6}),Bh=mo({valueFilter:2});function mo(e){let t=jr({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ne({copy:e=!1,filter:t={valueFilter:1}}={}){let o=ho(t);o.invertFilter=!o.invertFilter;let r=jr({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var _c=Ne({copy:!1});function jr({forEach:e,filter:t}){let o=lo(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function Wr(e){let t=Object.assign(Object.create(null),e??{});return{load:async()=>Object.assign(Object.create(null),t),get:async o=>Object.hasOwn(t,o)?t[o]:void 0,set:async(o,r)=>{let n=Object.assign(Object.create(null),t);n[o]=r,t=n},remove:async o=>{let r=Object.assign(Object.create(null),t);delete r[o],t=r},clear:async()=>{t=Object.create(null)}}}function Br(e){let t,o,r=0;function n(){if(t!=null)return Promise.resolve(t.entries);if(o==null){let i=r;o=e.load().then(a=>(r===i&&(t={entries:a},o=void 0),a),a=>{throw r===i&&(o=void 0),a})}return o}return{load:async()=>({...await n()}),get:async i=>(await n())[i],set:async(i,a)=>{let s=await n();r+=1,o=void 0,await e.set(i,a),t={entries:{...s,[i]:a}}},remove:async i=>{let a=await n();r+=1,o=void 0,await e.remove(i);let s={...a};delete s[i],t={entries:s}},clear:async()=>{r+=1,o=void 0,await e.clear(),t={entries:{}}}}}function qr(e){return{load:async()=>{let t;for(let o of e){let r=await o.load();if(r!=null){t=r;break}}return t},update:async t=>{for(let o=e.length-1;o>=0;o-=1)await e[o].update(t)},clear:async()=>{for(let t=e.length-1;t>=0;t-=1)await e[t].clear()}}}function bt(e,t,o){let[r,n]=yo(e,t,!1);return r+o+n}function yo(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var vc=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],em=new Set(vc);function Jr(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=It(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=bt(n,i[0],o(s));break}default:{let s=[],c=i.length,u=0,p=0;for(let d=0;d<c;d+=1){p=i[d];let g=n[p],m=n.substring(u,p)+o(g);s.push(m),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function wc(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[i,a]of[...t].entries())if(e.has(a)&&(n.push(i),n.length>=r))break;return n}}function It(e,t,o){return wc(e)(t,o)}function Nc(e,t){return It(e,t,1)[0]}function Uc(e){return t=>{let r=Nc(typeof e=="string"?new Set([e]):e,t),n;return r!=null?n=yo(t,r,!1):n=[t,void 0],n}}function $r(e,t){return Uc(t)(e)}var Ue="/",Lc=".";function Gc(e){let t=e.split(Lc,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Ue?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function Xr(e){return Gc(e)!=="invalid"}var Kc=/^\/+/,Vc=/\/+$/;var zc=/\/{2,}/g;function Yr(e){return e.startsWith(Ue)?e.replace(Kc,Ue):`${Ue}${e}`}function Qr(e){return e.replaceAll(zc,Ue)}function en(e){return e.replace(Vc,"")}function Hc(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var tn=/:(\d+)/;function jc(e){return tn.test(e)}function Wc(e){let t=tn.exec(e);return t?Number(t[1]):void 0}function Bc(e){let t=an(e),o=qc(t),{domain:r,path:n}=o,i=Hc(r),a=jc(e),s=a?Wc(e)??void 0:void 0,[c,u]=$r(o.path,"?"),p=i&&(c===""||Xr(c+"/")),d=$c(e);return{input:e,isWebsiteUrl:p,hasWebsiteDomain:i,hasHttpPrefix:d,hasPortNumber:a,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function on(e){let t=Bc(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function rn(e,t=!1){let o=It(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(i=>n=bt(n,i,"&")),n}function qc(e){let t=an(e);return Jc(t)}function Jc(e){let t=uo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:Yr(r??"/")}}var nn=/^https:\/\/|http:\/\//;function an(e){return e.replace(nn,"")}function $c(e){return nn.test(e)}function F(){}function sn(e){let t;return e==null||ru(e)?t=e:t=Xc(e),t}function Xc(e){return e==null?e:new Date(e)}var cn=24,Yc=60;var Qc=60,eu=Qc*Yc,L=1e3,Se=L*60,go=Se*60,tu=go*cn,hm=eu*cn,ou=7,mm=tu*ou;function ru(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function un(e){return e.getTime()<Date.now()}function pn(e,t){return e!=null?new Date(e.getTime()+(t??0)):e}function nu(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:sn(n);function c(g){return g??r??new Date}function u(g,l=!1){let m=c(g),f=d(m),R;return f==null?R=l:R=f<=m,R}function p(g){let l=c(g);return d(l)}function d(g){let l=null;return o!=null?l=o.expiresAt??null:t!=null?l=t:a!=null&&(l=pn(s??(i!==!1?g:null),a)),l}return{input:e,hasExpired:u,getExpirationDate:p}}function dn(e,t){let o=!0;return e!=null&&(o=nu(e).hasExpired(t,!0)),o}function ln(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function fo(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function iu(e){let n=go,i={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},a=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;l(e??i);function p(){return{...i}}function d(){return u}function g(I){u=I}function l(I,K=!1){let Y=Math.max(0,I.startLimitAt??1),A=I.cooldownRate??1,w=I.maxWaitTime??n,U=I.exponentRate??2;i={startLimitAt:Y,cooldownRate:A,maxWaitTime:w,exponentRate:U},s=Nr(U,w/L+1),K&&m()}function m(){a=0,c=new Date}function f(I){if(!u)return 0;let{cooldownRate:K}=i,A=(Date.now()-c.getTime())*K/L,w=Math.max(a-A,0),U=Math.max(0,w-i.startLimitAt);return I&&(a=w+I,c=new Date),U>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(U,0))-1)*L}function R(I){return f(I??0)}function S(){let I=f(1);return fo(I)}return{waitForRateLimit:S,getNextWaitTime:R,getConfig:p,setConfig:l,getEnabled:d,setEnabled:g,reset:m}}function hn(e){let o=iu({exponentRate:1.5,maxWaitTime:L*8,...e}),r=Se,n=new Date,i=0,a=0,s=!0;S(e,!0);function c(){un(n)&&d()}function u(){return s}function p(A){s=A}function d(){a=i,n=new Date(Date.now()+r)}function g(){return n}function l(){return Math.max(0,n.getTime()-Date.now())}function m(A){n=A}function f(){return c(),a}function R(A){a=A}function S(A,w=!1){i=A.limit??i,r=A.resetPeriod??r;let U={cooldownRate:A.cooldownRate??Math.max(.1,r/L),exponentRate:A.exponentRate??1.5,maxWaitTime:A.maxWaitTime??L*8};o.setConfig(U,w),w&&d(),n=A.resetAt??n}function I(A){if(!s)return 0;function w(){return a-=A,o.getNextWaitTime(A)}let U=0;return a>0?U=w():(c(),a>0?U=w():U=l()),U}function K(A){return I(A??0)}function Y(){let A=I(1);return fo(A)}return{getRemainingLimit:f,setRemainingLimit:R,getTimeUntilNextReset:l,getResetAt:g,setNextResetAt:m,setConfig:S,reset:d,getNextWaitTime:K,waitForRateLimit:Y,getEnabled:u,setEnabled:p}}var au="__CATCH_ALL_HANDLE_RESULT_KEY__";function mn(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,i=new Map,a=u=>{n=u},s=(u,p)=>{u===au?a(p):Dr(i,u,p)},c=(u,p,d)=>{let g=d.bind(u);s(p,g)};return Er({base:(u=>{let p=e(u),d=(p!=null?i.get(p):void 0)??n,g;return d?g=Promise.resolve(d(u)).then(l=>l??o):g=Promise.resolve(r),g}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=a}})}}function su(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function cu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function uu(e,t,o){let r=cu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function yn(e,t){return o=>uu(e,o,t)}function gn(e){return t=>(o,r)=>{let n=su(o,t),i=e.configurerForAccessor(n);r(i)}}var pu=-1,fn=0;function du(e){return e?.page??pu}function Rn(e){return du(e)+1}import{BaseError as Tn}from"make-error";var q=class extends Tn{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function Cn(e){return(t,o)=>lu(e(t,o))}var Le=class extends Tn{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function lu(e){return e.then(t=>{if(!t.ok)throw new Le(t);return t})}import{BaseError as Dm}from"make-error";function xn(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let a=new AbortController;r=a,o={...o,signal:a.signal}}let i=e(t,o);if(n){let a=setTimeout(()=>{r?.abort()},n);i=i.finally(()=>{clearTimeout(a)})}return i}}function Zn(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>Sn({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>mu({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var hu=(e,t)=>t(e);function mu(e){let{makeFetch:t=fetch,fetchHandler:o=hu,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=xn(a)),n&&(a=Cn(a));let s=Sn(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var yu=(e,t)=>new Request(e,t);function Sn(e){let{makeRequest:t=yu,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(en(o)):void 0,u=c?l=>{let m,f=l.toString();if(!s&&on(f))m=new URL(f);else{let R=c.origin+Qr("/"+c.pathname+"/"+l);m=new URL(R,c)}return m}:void 0;async function p(l){let m=ln(l)?await l:l;return Fn(m)?m:t(m)}let d=u?async l=>{let m,f,R;if(typeof l=="string"?m=l:Fn(l)?a?(m=l.url,f=l):R=l:R=await t(l),!R){let S=u(m);R=await t(S.href,f)}return R}:p,g;if(r!=null||n!=null){let l=wr(r);async function m(){let R=await l();return n?{...R,timeout:n}:R}async function f(R,S){let I=await m(),K=gu(I,await S),Y=K.timeout===void 0?R.timeout:K.timeout;return{...K,timeout:Y}}i?g=(R,S)=>i(R,f(R,S)):g=(R,S)=>f(R,S)}else i?g=i:g=(l,m)=>m;return async(l,m)=>{try{let f=await d(l);m=await g(f,m);let R=await t(f,m);return R.timeout=n,R}catch(f){throw f instanceof q?f:new q(f)}}}function gu(e,t){let o;if(t){let r=fu([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function fu(e){let t=_r();return he(e).forEach(o=>{let r=Ru(o),n=new Set;r.forEach(([i,a])=>{n.has(i)||(t.delete(i),n.add(i)),a&&t.add(i,a)})}),t.tuples()}function Ru(e){let t=[];return Array.isArray(e)?t=e:typeof e.forEach=="function"?e.forEach((o,r)=>{t.push([r,o])}):typeof e=="object"&&(t=Object.entries(e)),t}function Fn(e){return!!e.url}import{safeParse as Tu}from"fast-content-type-parse";function Pt(e){let t=e.headers.get("content-type"),o=Tu(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function An(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,i=async(a,s)=>{async function c(u){await n.waitForRateLimit();let p,d;try{p=await s(a.clone())}catch(l){d=l,p=d.response}if(await t(p,d)&&u<r)p=await c(u+1);else if(d!=null)throw d;return p}return c(0)};return i._rateLimiter=n,i}var Ro=class extends q{constructor(o){super("There was no next page for this.");this.page=o}},To=class extends q{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},Cu=100;function Ge(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:i}=e;return(a,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},p=u??i,d=c===null?Number.MAX_SAFE_INTEGER:c??Cu;function g(m,f=void 0){return async()=>{let R=await t(m),{cursor:S,nextPageCursor:I,hasNext:K}=await o(R),Y=S??f?.cursor,A=K!==!1,w=f?f.page+1:fn,U=w>=d,rt={input:m,result:R,page:w,previous:f,hasNext:A,isAtMaxPage:U,cursor:Y,nextPageCursor:I,fetchNext:ct(async()=>{if(U)throw new To(rt,d);let Rr=A?await r(rt,m,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Rr)throw new Ro(rt);return g({...m,...Rr},rt)()})};return rt}}return{input:a,fetchNext:ct(()=>g(a)())}}}function T(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?zr(e):e,i=r??!0?Hr(n??{}):n,a=new URLSearchParams(i);return o!=null&&B(o,s=>a.delete(s),!1),a}function Co(e){let t;if(typeof e=="string")t=e;else if(xu(e))t=e.href;else{let o=Co(e.url);if(e.queryParams){let r=Su(e.queryParams);st(r)?t=o:t=rn(o+`?${r.toString()}`)}else t=o}return t}function xu(e){return typeof e=="object"&&e instanceof URL}function Fu(e){return typeof e=="object"&&e instanceof URLSearchParams}function Zu(e){let t=[];return io(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let i=String(r);B(n,a=>{a!=null&&t.push([i,String(a)])})}}),t}function Su(e){let t;return Fu(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):ve(e)?t=new URLSearchParams(Zu(e)):t=Au(e),t}function Au(e){let t=[];return Vr(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&B(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var xo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function ku(e){return e!=null?typeof e=="string"?e:JSON.stringify(e):void 0}var bu=e=>{throw new xo(e)},Q=e=>null;function ee(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??bu};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=kn(o);return(a,s,c)=>{let u=Co(a),p=i(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(l=>{let m=l.json().catch(r),f=n?m.then(R=>n(R,l)):m;return d?f.then(R=>d(R,l)):f})}}function kn(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Or()}=e;return(r=t,n)=>{let i;return typeof r=="string"?i={method:r,body:n}:i=r,i=o(i),{...i,method:i.method,body:ku(i.body)}}}var Xm=kn();var te=Zn({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function bn(e){let t,o=e?.notInitializedMessage??"Context slot has not been initialized.";return{set:r=>{t=r},get:()=>t,require:()=>{if(t==null)throw new Error(o);return t}}}var Iu=["raw","page_by_line","data_by_line"],Pu=["replace","concat"],Eu=["meta","pages","merged_page"];function Fo(e){return e.option("multiple-pages",{type:"number",default:1,describe:"Pages to fetch in this invocation (>=1). Continues from the per-API page/offset flag."}).option("multiple-pages-output",{type:"string",choices:Eu,default:"meta",describe:"Stdout shape when multiple-pages > 1: meta (summary, low memory), pages (array of page responses, WARNING: holds all pages in memory), merged_page (concat all records into one array, WARNING: holds all records in memory)."}).option("dump-output",{type:"string",choices:Iu,default:"raw",describe:"Dump file format when --dump-dir is set. raw: one full JSON page response (concatenated JSON when --dump-merge=concat, not standard JSON). page_by_line: NDJSON of page responses. data_by_line: NDJSON of records."}).option("dump-merge",{type:"string",choices:Pu,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as Ou}from"@nestjs/common";var ky=Ou((e,t)=>Du(t));function Du(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Zo,BadRequestException as Mu,InternalServerErrorException as _u,Logger as vu}from"@nestjs/common";import wu from"raw-body";import{parse as Nu}from"querystring";var In=new vu("RawBody"),Oy=Zo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw In.error("RawBody request was not readable. This is generally due to bad configuration."),new Mu("Invalid body");return await wu(o)}),Pn=Zo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw In.error("RawBody expected a buffer set to req.body."),new _u("failed parsing body");return r}),Dy=Zo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=Uu(o.body),o.body});function Uu(e){let t=Lu(e);return Nu(t)}function Lu(e){return e.toString("utf8").trim()}import{Injectable as Gu}from"@nestjs/common";import Ku from"body-parser";var Ke=class{use(t,o,r){Ku.json()(t,o,r)}};Ke=Z([Gu()],Ke);import{Injectable as Vu}from"@nestjs/common";import zu from"body-parser";var Ve=class{use(t,o,r){zu.raw({type:"*/*"})(t,o,r)}};Ve=Z([Vu()],Ve);import{Logger as Hu,Module as ju,RequestMethod as Wu}from"@nestjs/common";var Bu="/webhook",qu={path:`${Bu}/{*path}`,method:Wu.POST},So=class{configure(t){Ju(t)}},Et=class extends So{logger=new Hu("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Et=Z([ju({})],Et);function Ju(e){e.apply(Ve).forRoutes(qu).apply(Ke).forRoutes("{*path}")}var En="CLIENT_WEB_APP_URL";var Ae=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as $u,Injectable as Xu}from"@nestjs/common";var ke=class{_config;constructor(t){this._config=t}get config(){return this._config}get webAppUrl(){return this.config.client.clientWebAppUrl}get webAppHost(){return this.webAppUrl.split("://",2)[1]}};ke=Z([Xu(),b(0,$u(Ae))],ke);import{Module as Yu}from"@nestjs/common";import{ConfigModule as Qu,ConfigService as ep}from"@nestjs/config";function tp(e){let t={client:{clientWebAppUrl:e.get(En)}};return Ae.assertValidConfig(t),t}var Ot=class{};Ot=Z([Yu({imports:[Qu],providers:[{provide:Ae,inject:[ep],useFactory:tp},ke],exports:[ke]})],Ot);var On="SERVER_ENV_TOKEN";import{Inject as op,Injectable as rp}from"@nestjs/common";function Dn(){return process.env.NODE_ENV==="test"}var Dt=class{constructor(t){this.env=t}get isTestingEnv(){return Dn()}get isProduction(){return this.env.production}get isStaging(){return!!this.env.staging}get developerToolsEnabled(){return!!(!this.isProduction&&this.env.developerToolsEnabled)}get appUrl(){return this.env.appUrl}get appApiUrl(){return this.env.appApiUrl}};Dt=Z([rp(),b(0,op(On))],Dt);import{dirname as up}from"node:path";import{chmod as np,mkdirSync as ip,readFile as ap,writeFile as sp}from"node:fs";import{rm as cp}from"node:fs/promises";function me(e){return new Promise((t,o)=>{ap(e,{encoding:"utf-8"},(r,n)=>{if(r){r.code==="ENOENT"?t(void 0):o(r);return}try{t(JSON.parse(n))}catch{t(void 0)}})})}function Mt(e){return ip(e.dirPath,{recursive:!0}),new Promise((t,o)=>{sp(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{if(r){o(r);return}if(e.mode==null){t();return}np(e.filePath,e.mode,n=>{n?o(n):t()})})})}function ut(e){return cp(e,{force:!0})}var pp=384;function Mn(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??pp;async function a(){let p=await me(t);if(p==null)return{};if(r==null)return p;let d={};for(let g of Object.keys(p)){let l=r(p[g]);l!=null&&(d[g]=l)}return d}async function s(p){let d=n==null?p:Object.fromEntries(Object.entries(p).map(([g,l])=>[g,n(l)]));await Mt({filePath:t,dirPath:up(t),data:d,mode:i})}let c=Promise.resolve();function u(p){let d=c.then(p,p);return c=d.catch(()=>{}),d}return{load:a,get:async p=>(await a())[p],set:(p,d)=>u(async()=>{let g=await a();await s({...g,[p]:d})}),remove:p=>u(async()=>{let g={...await a()};delete g[p],await s(g)}),clear:()=>u(async()=>{await ut(t)})}}var Jg=Buffer.from([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function pt(e){return me(e.configFilePath)}function dp(e){return Mt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function dt(e){let t=await pt({configFilePath:e.configFilePath})??{},o={activeEnv:e.updates.activeEnv??t.activeEnv,envs:e.updates.envs?{...t.envs,...e.updates.envs}:t.envs,output:e.updates.output===void 0?t.output:Ao(t.output,e.updates.output)};return await dp({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Ao(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:lp(e?.commands,t)}}function lp(e,t){if(!("commands"in t))return e;if(!t.commands)return;let o={...e};for(let r of Object.keys(t.commands))o[r]={...e?.[r],...t.commands[r]};return o}function _n(e){let t=e.commandPath.join("."),o=t?e.outputConfig?.commands?.[t]:void 0;return{dumpDir:e.cliFlags.dumpDir??o?.dumpDir??e.outputConfig?.dumpDir,pick:e.cliFlags.pick??o?.pick??e.outputConfig?.pick}}function pe(e){return e==null?e:e.length<=4?"***":e.substring(0,4)+"***"}import{homedir as hp}from"node:os";import{join as ko}from"node:path";function _t(e){let t=e.configDirOverride??ko(hp(),`.${e.cliName}`);return{configDir:t,configFilePath:ko(t,"config.json"),tokenCachePath:ko(t,".tokens.json")}}function vn(e){let t=_t({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await pt({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{let i=n._?n._.map(String):[],a=i[0],s=n.setDumpDir,c=n.setPick;if((s!==void 0||c!==void 0)&&a&&!e.skipCommands.has(a)){let l=i.join("."),m={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(l,m)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,g=p?_n({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};oo({dumpDir:g.dumpDir,pick:n.pickAll?void 0:g.pick,commandPath:i})}}function vt(e){return async t=>{try{await e(t)}catch(o){Zr(o),process.exit(1)}}}function mp(e){let t=_t({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await pt({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{dumpDir:void 0,pick:void 0,commands:void 0}}}));return{loadOutputConfig:o,mergeOutputConfig:r,clearOutputConfig:n}}function wn(e){let t=mp(e),o={command:"set",describe:"Configure output settings (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. recruit.list)"}).check(a=>{if(a.setDumpDir==null&&a.setPick==null)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:vt(async i=>{let a=i.command,s=i.setDumpDir,c=i.setPick,u;if(a){let d={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};u={commands:{[a]:d}}}else u={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await t.mergeOutputConfig(u);let p=await t.loadOutputConfig();h({saved:!0,output:p??{}})})},r={command:"show",describe:"Show current output configuration",builder:i=>i,handler:vt(async()=>{let i=await t.loadOutputConfig();h({output:i??{}})})},n={command:"clear",describe:"Clear output configuration (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:vt(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new it({message:`No per-command output config for "${a}".`,code:"OUTPUT_COMMAND_NOT_FOUND"});let c={...s.commands};delete c[a],await t.mergeOutputConfig({...s,commands:c}),h({cleared:!0,command:a})}else await t.clearOutputConfig(),h({cleared:!0})})};return{command:"output",describe:"Configure output settings (dump, field filtering)",builder:i=>i.command(o).command(r).command(n).demandCommand(1,"Specify an output subcommand."),handler:F}}import{writeFileSync as yp,appendFileSync as gp}from"node:fs";function Nn(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=At(),n=t==="raw"?"json":"ndjson",i=at(n),a=r?at(n,"pick"):void 0;if(!i)return{mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};let s=0;function c(m){if(!r)return m;let f=Ze(m.data,r);return{...m,data:f}}function u(m){let f=m.append?gp:yp;i&&f(i,m.mainContent),a&&m.pickContent!==void 0&&f(a,m.pickContent)}function p(m,f){let R=JSON.stringify(m,null,2),S=a?JSON.stringify(c(m),null,2):void 0;u({mainContent:R,pickContent:S,append:f})}function d(m,f){let R=JSON.stringify(m)+`
|
|
4
|
+
var dc=Object.defineProperty;var lc=Object.getOwnPropertyDescriptor;var Z=(e,t,o,r)=>{for(var n=r>1?void 0:r?lc(t,o):t,i=e.length-1,a;i>=0;i--)(a=e[i])&&(n=(r?a(t,o,n):a(n))||n);return r&&n&&dc(t,o,n),n},b=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as hc,mkdirSync as mc,writeFileSync as yc}from"node:fs";import{join as gc}from"node:path";var to=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/id_token[=:]\s*\S+/gi],nt={},Cr=[...to],eo;function oo(e){nt=e}function At(){return nt}function ro(e){Cr=e}function xr(e){eo=e}function ue(e){let t=e;for(let o of Cr)t=t.replace(o,"[REDACTED]");return t}function Fr(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function at(e,t){let{dumpDir:o,commandPath:r}=nt;if(!o)return;hc(o)||mc(o,{recursive:!0});let n=r?.length?r.join("_"):"response",i=Fr(),a=t?`${n}_${i}_${t}`:`${n}_${i}`;return gc(o,`${a}.${e}`)}function fc(e,t){let o=at("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};yc(o,JSON.stringify(r,null,2))}function Ze(e,t){let o=t.split(",").map(r=>r.trim());return Array.isArray(e)?e.map(r=>Tr(r,o)):e!=null&&typeof e=="object"?Tr(e,o):e}function Tr(e,t){if(e==null||typeof e!="object")return e;let o={};for(let r of t)r in e&&(o[r]=e[r]);return o}function h(e,t){fc(e,t);let r={ok:!0,data:nt.pick?Ze(e,nt.pick):e,...t?{meta:t}:{}};console.log(JSON.stringify(r))}function Zr(e){console.log(JSON.stringify(no(e)))}var it=class extends Error{code;suggestion;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.suggestion=t.suggestion}};function no(e){if(eo){let t=eo(e);if(t)return t}return e instanceof it?{ok:!1,error:ue(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?{ok:!1,error:ue(e.message),code:"ERROR"}:{ok:!1,error:ue(String(e)),code:"UNKNOWN_ERROR"}}function ve(e,t=!1){return typeof e=="string"?t:e!=null&&typeof e=="object"&&Symbol.iterator in e}function st(e){for(let t of e)return!1;return!0}function io(e,t){for(let o of e)t(o)}function B(e,t,o=!1){e!=null&&(ve(e,o)?io(e,t):t(e))}function Sr(e){if(!Array.isArray(e))throw new Error("Input is not an array/tuple...");let t;if(e.length>0){let o=e[0],r=!1;if(Array.isArray(o)){let n=o.length;r=e.findIndex(a=>Array.isArray(a)?a.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function Rc(e){return e!=null?Tc(e):[]}var C=Rc;function Tc(e){return Array.isArray(e)?e:[e]}function Ar(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function ao(e){return Object.keys(e).length===0}function kr(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function br(e){return{...e}}function Ir(e){return e!=null}function kt(e){return ve(e,!1)?!st(e):Pr(e)}function so(e){let t;return ve(e,!0)?t=!st(e):Pr(e)?t=typeof e=="object"?!ao(e):!0:t=!1,t}function Pr(e){return e!=null&&e!==""}function Cc(e){return t=>{let o;return t!=null?o=t.filter((r,n,i)=>e(r,n,i)):o=[],o}}var he=Cc(Ir);function Er({base:e,build:t}){let o=e??{};return t(o),o}var xc=(e=>e);function Or(){return xc}function we(e,t){let o=Fc(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Fc(e,t){return kr(Zc(e,t))}function Zc(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),i=o.get(n);i!=null?i.push(r):o.set(n,[r])}),o}function Dr(e,t,o){return C(t).forEach(r=>e.set(r,o)),e}function co(e){return Array.from(e.entries())}function Mr(e){return Sc(co(e))}function Sc(e){let t=[];return e.forEach(([o,r])=>{B(r,n=>{t.push([o,n])})}),t}function _r(){let e=new Map,t=(n,i)=>{let a=e.get(n);a==null&&(a=[],e.set(n,a)),B(i,s=>a.push(s))},o=(n,i)=>t(n,Sr(i));return{map:()=>e,entries:()=>co(e),tuples:()=>Mr(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,i)=>B(n,a=>t(a,i)),addTuplesToKeys:(n,i)=>B(n,a=>o(a,i)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function Ac(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function vr(e){let t=Ac(e);return t!=null&&t!=="class"}function wr(e){return vr(e)?e:()=>e}function Nr(e,t){return Math.log(t)/Math.log(e)}var Ur=",",kc=" ";function bc(e,t=Ur,o=!1){if(e==null)return e;let r=C(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function uo(e,t,o){let r=e.split(t),n=[];if(r.length>1){let i=r.length>o,a=i?o-1:r.length;for(let s=0;s<a;s+=1)n.push(r[s]);i&&n.push(r.slice(a).join(t))}else n.push(r[0]);return n}function Ic(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return bc(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function Lr(e){let{joiner:t}=e,o=Ic(e),r=(n,i=a=>a)=>n.split(t).map(s=>i(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,i){return uo(n,t,i)}}}var po=Lr({joiner:Ur}),Pc=Lr({joiner:kc,trimByDefault:!0});var P=po.joinStrings,bh=po.splitStrings,Ih=po.splitStringsToSet,Ph=Pc.joinStrings;var Gr=Ar;function Vr(e,{forEach:t,filter:o}){Ec(e,o).forEach((n,i)=>t(n,i))}function Ec(e,t){return lo(t)(e)}function lo(e){let t;if(e!=null){let o=Oc(e);t=r=>Kr(r).filter((n,i)=>o(n,i))}else t=Kr;return t}function Kr(e){return Object.entries(e)}function ho(e){return typeof e=="object"?e:{valueFilter:e}}function Oc(e){let t=ho(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,i;switch(o){case 1:i=([,a])=>a!==void 0;break;case 2:i=([,a])=>a!=null;break;case 3:i=([,a])=>!!a;break;case 4:i=([,a])=>kt(a);break;case 5:i=([,a])=>so(a);break;case 6:i=([,a])=>!!a&&kt(a);break;case 7:i=([,a])=>!!a&&so(a);break;default:i=()=>!0;break}if(n){let a=i,s=new Set(n.map(c=>c.toString()));i=(c,u)=>a(c,u)&&s.has(c[0])}return Gr(i,r)}function ct(e){let t,o=n=>{t={value:e(n)}},r=(n=>(t||o(n),t.value));return r.set=n=>t={value:n},r.reset=()=>t=void 0,r.init=o,r.used=()=>!!t,r}function Dc({filter:e,copy:t,dynamic:o=!1}){let r=e!=null?Ne({filter:e,copy:!1}):_c;return n=>{let i=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},a=o?i:ct(i);return s=>{let c=a();return t&&(s=br(s)),Object.assign(s,c),s}}}function zr(e,t){return Mc(t)(e)}function Mc(e){let t=Dc({filter:e,copy:!1,dynamic:!0});return o=>t(he(o))({})}var Vh=Ne({copy:!0,filter:{valueFilter:1}}),zh=Ne({copy:!0,filter:{valueFilter:2}}),Hr=Ne({copy:!0,filter:{valueFilter:4}}),Hh=Ne({copy:!0,filter:{valueFilter:6}}),jh=mo({valueFilter:1}),Wh=mo({valueFilter:6}),Bh=mo({valueFilter:2});function mo(e){let t=jr({filter:e,forEach:([o],r,n,i)=>{i.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ne({copy:e=!1,filter:t={valueFilter:1}}={}){let o=ho(t);o.invertFilter=!o.invertFilter;let r=jr({filter:o,forEach:([n],i,a)=>{delete a[n]}});return(n,i)=>((typeof i=="boolean"?i:e)&&(n={...n}),r(n),n)}var _c=Ne({copy:!1});function jr({forEach:e,filter:t}){let o=lo(t);return((r,n)=>{o(r).forEach((a,s)=>e(a,s,r,n))})}function Wr(e){let t=Object.assign(Object.create(null),e??{});return{load:async()=>Object.assign(Object.create(null),t),get:async o=>Object.hasOwn(t,o)?t[o]:void 0,set:async(o,r)=>{let n=Object.assign(Object.create(null),t);n[o]=r,t=n},remove:async o=>{let r=Object.assign(Object.create(null),t);delete r[o],t=r},clear:async()=>{t=Object.create(null)}}}function Br(e){let t,o,r=0;function n(){if(t!=null)return Promise.resolve(t.entries);if(o==null){let i=r;o=e.load().then(a=>(r===i&&(t={entries:a},o=void 0),a),a=>{throw r===i&&(o=void 0),a})}return o}return{load:async()=>({...await n()}),get:async i=>(await n())[i],set:async(i,a)=>{let s=await n();r+=1,o=void 0,await e.set(i,a),t={entries:{...s,[i]:a}}},remove:async i=>{let a=await n();r+=1,o=void 0,await e.remove(i);let s={...a};delete s[i],t={entries:s}},clear:async()=>{r+=1,o=void 0,await e.clear(),t={entries:{}}}}}function qr(e){return{load:async()=>{let t;for(let o of e){let r=await o.load();if(r!=null){t=r;break}}return t},update:async t=>{for(let o=e.length-1;o>=0;o-=1)await e[o].update(t)},clear:async()=>{for(let t=e.length-1;t>=0;t-=1)await e[t].clear()}}}function bt(e,t,o){let[r,n]=yo(e,t,!1);return r+o+n}function yo(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}var vc=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],em=new Set(vc);function Jr(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let i=It(r,n),a;switch(i.length){case 0:a=n;break;case 1:{let s=n[i[0]];a=bt(n,i[0],o(s));break}default:{let s=[],c=i.length,u=0,p=0;for(let d=0;d<c;d+=1){p=i[d];let g=n[p],m=n.substring(u,p)+o(g);s.push(m),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function wc(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[i,a]of[...t].entries())if(e.has(a)&&(n.push(i),n.length>=r))break;return n}}function It(e,t,o){return wc(e)(t,o)}function Nc(e,t){return It(e,t,1)[0]}function Uc(e){return t=>{let r=Nc(typeof e=="string"?new Set([e]):e,t),n;return r!=null?n=yo(t,r,!1):n=[t,void 0],n}}function $r(e,t){return Uc(t)(e)}var Ue="/",Lc=".";function Gc(e){let t=e.split(Lc,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Ue?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function Xr(e){return Gc(e)!=="invalid"}var Kc=/^\/+/,Vc=/\/+$/;var zc=/\/{2,}/g;function Yr(e){return e.startsWith(Ue)?e.replace(Kc,Ue):`${Ue}${e}`}function Qr(e){return e.replaceAll(zc,Ue)}function en(e){return e.replace(Vc,"")}function Hc(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var tn=/:(\d+)/;function jc(e){return tn.test(e)}function Wc(e){let t=tn.exec(e);return t?Number(t[1]):void 0}function Bc(e){let t=an(e),o=qc(t),{domain:r,path:n}=o,i=Hc(r),a=jc(e),s=a?Wc(e)??void 0:void 0,[c,u]=$r(o.path,"?"),p=i&&(c===""||Xr(c+"/")),d=$c(e);return{input:e,isWebsiteUrl:p,hasWebsiteDomain:i,hasHttpPrefix:d,hasPortNumber:a,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function on(e){let t=Bc(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function rn(e,t=!1){let o=It(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(i=>n=bt(n,i,"&")),n}function qc(e){let t=an(e);return Jc(t)}function Jc(e){let t=uo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:Yr(r??"/")}}var nn=/^https:\/\/|http:\/\//;function an(e){return e.replace(nn,"")}function $c(e){return nn.test(e)}function F(){}function sn(e){let t;return e==null||ru(e)?t=e:t=Xc(e),t}function Xc(e){return e==null?e:new Date(e)}var cn=24,Yc=60;var Qc=60,eu=Qc*Yc,L=1e3,Se=L*60,go=Se*60,tu=go*cn,hm=eu*cn,ou=7,mm=tu*ou;function ru(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function un(e){return e.getTime()<Date.now()}function pn(e,t){return e!=null?new Date(e.getTime()+(t??0)):e}function nu(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:sn(n);function c(g){return g??r??new Date}function u(g,l=!1){let m=c(g),f=d(m),R;return f==null?R=l:R=f<=m,R}function p(g){let l=c(g);return d(l)}function d(g){let l=null;return o!=null?l=o.expiresAt??null:t!=null?l=t:a!=null&&(l=pn(s??(i!==!1?g:null),a)),l}return{input:e,hasExpired:u,getExpirationDate:p}}function dn(e,t){let o=!0;return e!=null&&(o=nu(e).hasExpired(t,!0)),o}function ln(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function fo(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function iu(e){let n=go,i={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},a=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;l(e??i);function p(){return{...i}}function d(){return u}function g(I){u=I}function l(I,K=!1){let Y=Math.max(0,I.startLimitAt??1),A=I.cooldownRate??1,w=I.maxWaitTime??n,U=I.exponentRate??2;i={startLimitAt:Y,cooldownRate:A,maxWaitTime:w,exponentRate:U},s=Nr(U,w/L+1),K&&m()}function m(){a=0,c=new Date}function f(I){if(!u)return 0;let{cooldownRate:K}=i,A=(Date.now()-c.getTime())*K/L,w=Math.max(a-A,0),U=Math.max(0,w-i.startLimitAt);return I&&(a=w+I,c=new Date),U>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(U,0))-1)*L}function R(I){return f(I??0)}function S(){let I=f(1);return fo(I)}return{waitForRateLimit:S,getNextWaitTime:R,getConfig:p,setConfig:l,getEnabled:d,setEnabled:g,reset:m}}function hn(e){let o=iu({exponentRate:1.5,maxWaitTime:L*8,...e}),r=Se,n=new Date,i=0,a=0,s=!0;S(e,!0);function c(){un(n)&&d()}function u(){return s}function p(A){s=A}function d(){a=i,n=new Date(Date.now()+r)}function g(){return n}function l(){return Math.max(0,n.getTime()-Date.now())}function m(A){n=A}function f(){return c(),a}function R(A){a=A}function S(A,w=!1){i=A.limit??i,r=A.resetPeriod??r;let U={cooldownRate:A.cooldownRate??Math.max(.1,r/L),exponentRate:A.exponentRate??1.5,maxWaitTime:A.maxWaitTime??L*8};o.setConfig(U,w),w&&d(),n=A.resetAt??n}function I(A){if(!s)return 0;function w(){return a-=A,o.getNextWaitTime(A)}let U=0;return a>0?U=w():(c(),a>0?U=w():U=l()),U}function K(A){return I(A??0)}function Y(){let A=I(1);return fo(A)}return{getRemainingLimit:f,setRemainingLimit:R,getTimeUntilNextReset:l,getResetAt:g,setNextResetAt:m,setConfig:S,reset:d,getNextWaitTime:K,waitForRateLimit:Y,getEnabled:u,setEnabled:p}}var au="__CATCH_ALL_HANDLE_RESULT_KEY__";function mn(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,i=new Map,a=u=>{n=u},s=(u,p)=>{u===au?a(p):Dr(i,u,p)},c=(u,p,d)=>{let g=d.bind(u);s(p,g)};return Er({base:(u=>{let p=e(u),d=(p!=null?i.get(p):void 0)??n,g;return d?g=Promise.resolve(d(u)).then(l=>l??o):g=Promise.resolve(r),g}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=a}})}}function su(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function cu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function uu(e,t,o){let r=cu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function yn(e,t){return o=>uu(e,o,t)}function gn(e){return t=>(o,r)=>{let n=su(o,t),i=e.configurerForAccessor(n);r(i)}}var pu=-1,fn=0;function du(e){return e?.page??pu}function Rn(e){return du(e)+1}import{BaseError as Tn}from"make-error";var q=class extends Tn{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function Cn(e){return(t,o)=>lu(e(t,o))}var Le=class extends Tn{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function lu(e){return e.then(t=>{if(!t.ok)throw new Le(t);return t})}import{BaseError as Dm}from"make-error";function xn(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let a=new AbortController;r=a,o={...o,signal:a.signal}}let i=e(t,o);if(n){let a=setTimeout(()=>{r?.abort()},n);i=i.finally(()=>{clearTimeout(a)})}return i}}function Zn(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>Sn({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>mu({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var hu=(e,t)=>t(e);function mu(e){let{makeFetch:t=fetch,fetchHandler:o=hu,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=xn(a)),n&&(a=Cn(a));let s=Sn(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var yu=(e,t)=>new Request(e,t);function Sn(e){let{makeRequest:t=yu,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(en(o)):void 0,u=c?l=>{let m,f=l.toString();if(!s&&on(f))m=new URL(f);else{let R=c.origin+Qr("/"+c.pathname+"/"+l);m=new URL(R,c)}return m}:void 0;async function p(l){let m=ln(l)?await l:l;return Fn(m)?m:t(m)}let d=u?async l=>{let m,f,R;if(typeof l=="string"?m=l:Fn(l)?a?(m=l.url,f=l):R=l:R=await t(l),!R){let S=u(m);R=await t(S.href,f)}return R}:p,g;if(r!=null||n!=null){let l=wr(r);async function m(){let R=await l();return n?{...R,timeout:n}:R}async function f(R,S){let I=await m(),K=gu(I,await S),Y=K.timeout===void 0?R.timeout:K.timeout;return{...K,timeout:Y}}i?g=(R,S)=>i(R,f(R,S)):g=(R,S)=>f(R,S)}else i?g=i:g=(l,m)=>m;return async(l,m)=>{try{let f=await d(l);m=await g(f,m);let R=await t(f,m);return R.timeout=n,R}catch(f){throw f instanceof q?f:new q(f)}}}function gu(e,t){let o;if(t){let r=fu([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function fu(e){let t=_r();return he(e).forEach(o=>{let r=Ru(o),n=new Set;r.forEach(([i,a])=>{n.has(i)||(t.delete(i),n.add(i)),a&&t.add(i,a)})}),t.tuples()}function Ru(e){let t=[];return Array.isArray(e)?t=e:typeof e.forEach=="function"?e.forEach((o,r)=>{t.push([r,o])}):typeof e=="object"&&(t=Object.entries(e)),t}function Fn(e){return!!e.url}import{safeParse as Tu}from"fast-content-type-parse";function Pt(e){let t=e.headers.get("content-type"),o=Tu(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function An(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,i=async(a,s)=>{async function c(u){await n.waitForRateLimit();let p,d;try{p=await s(a.clone())}catch(l){d=l,p=d.response}if(await t(p,d)&&u<r)p=await c(u+1);else if(d!=null)throw d;return p}return c(0)};return i._rateLimiter=n,i}var Ro=class extends q{constructor(o){super("There was no next page for this.");this.page=o}},To=class extends q{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},Cu=100;function Ge(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:i}=e;return(a,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},p=u??i,d=c===null?Number.MAX_SAFE_INTEGER:c??Cu;function g(m,f=void 0){return async()=>{let R=await t(m),{cursor:S,nextPageCursor:I,hasNext:K}=await o(R),Y=S??f?.cursor,A=K!==!1,w=f?f.page+1:fn,U=w>=d,rt={input:m,result:R,page:w,previous:f,hasNext:A,isAtMaxPage:U,cursor:Y,nextPageCursor:I,fetchNext:ct(async()=>{if(U)throw new To(rt,d);let Rr=A?await r(rt,m,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Rr)throw new Ro(rt);return g({...m,...Rr},rt)()})};return rt}}return{input:a,fetchNext:ct(()=>g(a)())}}}function T(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?zr(e):e,i=r??!0?Hr(n??{}):n,a=new URLSearchParams(i);return o!=null&&B(o,s=>a.delete(s),!1),a}function Co(e){let t;if(typeof e=="string")t=e;else if(xu(e))t=e.href;else{let o=Co(e.url);if(e.queryParams){let r=Su(e.queryParams);st(r)?t=o:t=rn(o+`?${r.toString()}`)}else t=o}return t}function xu(e){return typeof e=="object"&&e instanceof URL}function Fu(e){return typeof e=="object"&&e instanceof URLSearchParams}function Zu(e){let t=[];return io(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let i=String(r);B(n,a=>{a!=null&&t.push([i,String(a)])})}}),t}function Su(e){let t;return Fu(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):ve(e)?t=new URLSearchParams(Zu(e)):t=Au(e),t}function Au(e){let t=[];return Vr(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&B(n,a=>{t.push([i,String(a)])})}}),new URLSearchParams(t)}var xo=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function ku(e){return e!=null?typeof e=="string"?e:JSON.stringify(e):void 0}var bu=e=>{throw new xo(e)},Q=e=>null;function ee(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??bu};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=kn(o);return(a,s,c)=>{let u=Co(a),p=i(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(l=>{let m=l.json().catch(r),f=n?m.then(R=>n(R,l)):m;return d?f.then(R=>d(R,l)):f})}}function kn(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Or()}=e;return(r=t,n)=>{let i;return typeof r=="string"?i={method:r,body:n}:i=r,i=o(i),{...i,method:i.method,body:ku(i.body)}}}var Xm=kn();var te=Zn({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function bn(e){let t,o=e?.notInitializedMessage??"Context slot has not been initialized.";return{set:r=>{t=r},get:()=>t,require:()=>{if(t==null)throw new Error(o);return t}}}var Iu=["raw","page_by_line","data_by_line"],Pu=["replace","concat"],Eu=["meta","pages","merged_page"];function Fo(e){return e.option("multiple-pages",{type:"number",default:1,describe:"Pages to fetch in this invocation (>=1). Continues from the per-API page/offset flag."}).option("multiple-pages-output",{type:"string",choices:Eu,default:"meta",describe:"Stdout shape when multiple-pages > 1: meta (summary, low memory), pages (array of page responses, WARNING: holds all pages in memory), merged_page (concat all records into one array, WARNING: holds all records in memory)."}).option("dump-output",{type:"string",choices:Iu,default:"raw",describe:"Dump file format when --dump-dir is set. raw: one full JSON page response (concatenated JSON when --dump-merge=concat, not standard JSON). page_by_line: NDJSON of page responses. data_by_line: NDJSON of records."}).option("dump-merge",{type:"string",choices:Pu,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as Ou}from"@nestjs/common";var ky=Ou((e,t)=>Du(t));function Du(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Zo,BadRequestException as Mu,InternalServerErrorException as _u,Logger as vu}from"@nestjs/common";import wu from"raw-body";import{parse as Nu}from"querystring";var In=new vu("RawBody"),Oy=Zo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw In.error("RawBody request was not readable. This is generally due to bad configuration."),new Mu("Invalid body");return await wu(o)}),Pn=Zo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw In.error("RawBody expected a buffer set to req.body."),new _u("failed parsing body");return r}),Dy=Zo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=Uu(o.body),o.body});function Uu(e){let t=Lu(e);return Nu(t)}function Lu(e){return e.toString("utf8").trim()}import{Injectable as Gu}from"@nestjs/common";import Ku from"body-parser";var Ke=class{use(t,o,r){Ku.json()(t,o,r)}};Ke=Z([Gu()],Ke);import{Injectable as Vu}from"@nestjs/common";import zu from"body-parser";var Ve=class{use(t,o,r){zu.raw({type:"*/*"})(t,o,r)}};Ve=Z([Vu()],Ve);import{Logger as Hu,Module as ju,RequestMethod as Wu}from"@nestjs/common";var Bu="/webhook",qu={path:`${Bu}/{*path}`,method:Wu.POST},So=class{configure(t){Ju(t)}},Et=class extends So{logger=new Hu("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Et=Z([ju({})],Et);function Ju(e){e.apply(Ve).forRoutes(qu).apply(Ke).forRoutes("{*path}")}var En="CLIENT_WEB_APP_URL";var Ae=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as $u,Injectable as Xu}from"@nestjs/common";var ke=class{_config;constructor(t){this._config=t}get config(){return this._config}get webAppUrl(){return this.config.client.clientWebAppUrl}get webAppHost(){return this.webAppUrl.split("://",2)[1]}};ke=Z([Xu(),b(0,$u(Ae))],ke);import{Module as Yu}from"@nestjs/common";import{ConfigModule as Qu,ConfigService as ep}from"@nestjs/config";function tp(e){let t={client:{clientWebAppUrl:e.get(En)}};return Ae.assertValidConfig(t),t}var Ot=class{};Ot=Z([Yu({imports:[Qu],providers:[{provide:Ae,inject:[ep],useFactory:tp},ke],exports:[ke]})],Ot);var On="SERVER_ENV_TOKEN";import{Inject as op,Injectable as rp}from"@nestjs/common";function Dn(){return process.env.NODE_ENV==="test"}var Dt=class{constructor(t){this.env=t}get isTestingEnv(){return Dn()}get isProduction(){return this.env.production}get isStaging(){return!!this.env.staging}get developerToolsEnabled(){return!!(!this.isProduction&&this.env.developerToolsEnabled)}get appUrl(){return this.env.appUrl}get appApiUrl(){return this.env.appApiUrl}};Dt=Z([rp(),b(0,op(On))],Dt);import{dirname as up}from"node:path";import{chmod as np,mkdirSync as ip,readFile as ap,writeFile as sp}from"node:fs";import{rm as cp}from"node:fs/promises";function me(e){return new Promise((t,o)=>{ap(e,{encoding:"utf-8"},(r,n)=>{if(r){r.code==="ENOENT"?t(void 0):o(r);return}try{t(JSON.parse(n))}catch{t(void 0)}})})}function Mt(e){return ip(e.dirPath,{recursive:!0}),new Promise((t,o)=>{sp(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{if(r){o(r);return}if(e.mode==null){t();return}np(e.filePath,e.mode,n=>{n?o(n):t()})})})}function ut(e){return cp(e,{force:!0})}var pp=384;function Mn(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??pp;async function a(){let p=await me(t);if(p==null)return{};if(r==null)return p;let d={};for(let g of Object.keys(p)){let l=r(p[g]);l!=null&&(d[g]=l)}return d}async function s(p){let d=n==null?p:Object.fromEntries(Object.entries(p).map(([g,l])=>[g,n(l)]));await Mt({filePath:t,dirPath:up(t),data:d,mode:i})}let c=Promise.resolve();function u(p){let d=c.then(p,p);return c=d.catch(()=>{}),d}return{load:a,get:async p=>(await a())[p],set:(p,d)=>u(async()=>{let g=await a();await s({...g,[p]:d})}),remove:p=>u(async()=>{let g={...await a()};delete g[p],await s(g)}),clear:()=>u(async()=>{await ut(t)})}}var Jg=Buffer.from([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function pt(e){return me(e.configFilePath)}function dp(e){return Mt({filePath:e.configFilePath,dirPath:e.configDir,data:e.config})}async function dt(e){let t=await pt({configFilePath:e.configFilePath})??{},o={activeEnv:e.updates.activeEnv??t.activeEnv,envs:e.updates.envs?{...t.envs,...e.updates.envs}:t.envs,output:e.updates.output===void 0?t.output:Ao(t.output,e.updates.output)};return await dp({configFilePath:e.configFilePath,configDir:e.configDir,config:o}),o}function Ao(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:lp(e?.commands,t)}}function lp(e,t){if(!("commands"in t))return e;if(!t.commands)return;let o={...e};for(let r of Object.keys(t.commands))o[r]={...e?.[r],...t.commands[r]};return o}function _n(e){let t=e.commandPath.join("."),o=t?e.outputConfig?.commands?.[t]:void 0;return{dumpDir:e.cliFlags.dumpDir??o?.dumpDir??e.outputConfig?.dumpDir,pick:e.cliFlags.pick??o?.pick??e.outputConfig?.pick}}function pe(e){return e==null?e:e.length<=4?"***":e.substring(0,4)+"***"}import{homedir as hp}from"node:os";import{join as ko}from"node:path";function _t(e){let t=e.configDirOverride??ko(hp(),`.${e.cliName}`);return{configDir:t,configFilePath:ko(t,"config.json"),tokenCachePath:ko(t,".tokens.json")}}function vn(e){let t=_t({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await pt({configFilePath:t.configFilePath}))?.output),r=e.saveCommandOutputConfig??(async(n,i)=>{await dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{commands:{[n]:i}}}})});return async n=>{let i=n._?n._.map(String):[],a=i[0],s=n.setDumpDir,c=n.setPick;if((s!==void 0||c!==void 0)&&a&&!e.skipCommands.has(a)){let l=i.join("."),m={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(l,m)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,g=p?_n({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};oo({dumpDir:g.dumpDir,pick:n.pickAll?void 0:g.pick,commandPath:i})}}function vt(e){return async t=>{try{await e(t)}catch(o){Zr(o),process.exit(1)}}}function mp(e){let t=_t({cliName:e.cliName}),o=e.loadOutputConfig??(async()=>(await pt({configFilePath:t.configFilePath}))?.output),r=e.mergeOutputConfig??(i=>dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:i}})),n=e.clearOutputConfig??(()=>dt({configFilePath:t.configFilePath,configDir:t.configDir,updates:{output:{dumpDir:void 0,pick:void 0,commands:void 0}}}));return{loadOutputConfig:o,mergeOutputConfig:r,clearOutputConfig:n}}function wn(e){let t=mp(e),o={command:"set",describe:"Configure output settings (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. recruit.list)"}).check(a=>{if(a.setDumpDir==null&&a.setPick==null)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:vt(async i=>{let a=i.command,s=i.setDumpDir,c=i.setPick,u;if(a){let d={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};u={commands:{[a]:d}}}else u={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await t.mergeOutputConfig(u);let p=await t.loadOutputConfig();h({saved:!0,output:p??{}})})},r={command:"show",describe:"Show current output configuration",builder:i=>i,handler:vt(async()=>{let i=await t.loadOutputConfig();h({output:i??{}})})},n={command:"clear",describe:"Clear output configuration (global or per-command)",builder:i=>i.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:vt(async i=>{let a=i.command;if(a){let s=await t.loadOutputConfig();if(!s?.commands?.[a])throw new it({message:`No per-command output config for "${a}".`,code:"OUTPUT_COMMAND_NOT_FOUND"});let c={...s.commands};delete c[a],await t.mergeOutputConfig({...s,commands:c}),h({cleared:!0,command:a})}else await t.clearOutputConfig(),h({cleared:!0})})};return{command:"output",describe:"Configure output settings (dump, field filtering)",builder:i=>i.command(o).command(r).command(n).demandCommand(1,"Specify an output subcommand."),handler:F}}import{writeFileSync as yp,appendFileSync as gp}from"node:fs";function Nn(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=At(),n=t==="raw"?"json":"ndjson",i=at(n),a=r?at(n,"pick"):void 0;if(!i)return{mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};let s=0;function c(m){if(!r)return m;let f=Ze(m.data,r);return{...m,data:f}}function u(m){let f=m.append?gp:yp;i&&f(i,m.mainContent),a&&m.pickContent!==void 0&&f(a,m.pickContent)}function p(m,f){let R=JSON.stringify(m,null,2),S=a?JSON.stringify(c(m),null,2):void 0;u({mainContent:R,pickContent:S,append:f})}function d(m,f){let R=JSON.stringify(m)+`
|
|
5
5
|
`,S=a?JSON.stringify(c(m))+`
|
|
6
6
|
`:void 0;u({mainContent:R,pickContent:S,append:f})}function g(m,f){let R=m.data??[],S=a?Ze(R,r):void 0;R.length===0?f||u({mainContent:"",pickContent:a?"":void 0,append:!1}):R.forEach((I,K)=>{let Y=f||K>0,A=JSON.stringify(I)+`
|
|
7
7
|
`,w=a&&S?JSON.stringify(S[K])+`
|
|
8
|
-
`:void 0;u({mainContent:A,pickContent:w,append:Y})})}function l(m){let R=o==="concat"&&!(s===0);t==="raw"?p(m,R):t==="page_by_line"?d(m,R):g(m,R),s+=1}return{mainPath:i,pickPath:a,writePage:l,close:()=>{}}}async function fp(e){let{initialInput:t,requestedPages:o,fetchPage:r,adapter:n,stream:i,shouldCollectPages:a,shouldCollectRecords:s}=e,c={pagesFetched:0,totalRecords:0,hasMorePagesAvailable:!1,lastResult:void 0,lastInput:t,collectedPages:[],collectedRecords:[]},u=t;for(let p=0;p<o;p++){let d=await r(u);if(c.pagesFetched+=1,c.totalRecords+=n.countOf(d),c.lastResult=d,c.lastInput=u,i.writePage(d),a)c.collectedPages.push(d);else if(s)for(let l of d.data??[])c.collectedRecords.push(l);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,d);let g=n.nextInput(u,d);if(!g)break;u=g}return c}function Rp(e){let{multiplePagesOutput:t,summaryMeta:o,state:r,adapter:n,pickFilter:i}=e;if(t==="meta")console.log(JSON.stringify({ok:!0,meta:o}));else if(t==="pages"){let a=i?r.collectedPages.map(s=>({...s,data:Ze(s.data,i)})):r.collectedPages;console.log(JSON.stringify({ok:!0,data:a,meta:o}))}else{let a=r.lastResult?n.metaOf(r.lastInput,r.lastResult):{},s=i?Ze(r.collectedRecords,i):r.collectedRecords;console.log(JSON.stringify({ok:!0,data:s,meta:{...a,...o}}))}}async function k(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:i,dumpMerge:a}=e,s=Math.max(1,Math.floor(e.multiplePages||1));if(s<=1)return{handled:!1,result:await o(t)};let c=At();c.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let u=Nn({dumpOutput:i,dumpMerge:a}),p;try{p=await fp({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:u,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{u.close()}let d={pagesFetched:p.pagesFetched,totalRecords:p.totalRecords,hasMorePagesAvailable:p.hasMorePagesAvailable,dumpFile:u.mainPath??null};return u.pickPath&&(d.dumpFilePick=u.pickPath),Rp({multiplePagesOutput:n,summaryMeta:d,state:p,adapter:r,pickFilter:c.pick}),{handled:!0}}import Wl from"yargs";import{hideBin as Bl}from"yargs/helpers";import{writeFile as Tp,mkdirSync as Cp}from"node:fs";import{join as bo}from"node:path";import{homedir as xp}from"node:os";var wt=["recruit","crm","desk"];function Io(){return bo(xp(),".zoho-cli")}function lt(){return bo(Io(),"config.json")}function ht(){return bo(Io(),".tokens.json")}function be(e,t){if(t){let o=process.env[`ZOHO_${t}_${e}`];if(o)return o}return process.env[`ZOHO_${e}`]}async function z(){let e=lt(),t=await me(e),o=be("ACCOUNTS_CLIENT_ID"),r=be("ACCOUNTS_CLIENT_SECRET"),n=be("ACCOUNTS_REFRESH_TOKEN");if(!t&&!(o&&r&&n))return;let a={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:be("ACCOUNTS_URL")??t?.shared?.region,apiMode:be("API_URL")??t?.shared?.apiMode};function s(u){let p=u.toUpperCase(),d=be("API_URL",p),g=u==="desk"?be("DESK_ORG_ID"):void 0,l=t?.[u],m=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],f=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],R=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`];if(!(!l&&!(m||f||R)&&!g))return{clientId:m??l?.clientId,clientSecret:f??l?.clientSecret,refreshToken:R??l?.refreshToken,apiUrl:d??l?.apiUrl,orgId:g??l?.orgId}}return{shared:a,recruit:s("recruit")??t?.recruit,crm:s("crm")??t?.crm,desk:s("desk")??t?.desk,output:t?.output}}function mt(e,t){let o=e[t],r=e.shared,n=o?.clientId??r.clientId,i=o?.clientSecret??r.clientSecret,a=o?.refreshToken??r.refreshToken;if(!(!n||!i||!a))return{clientId:n,clientSecret:i,refreshToken:a,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId}}async function Fp(e){let t=lt();return Cp(Io(),{recursive:!0}),new Promise((o,r)=>{Tp(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function H(e){let t=await z(),o={shared:{...t?.shared,...e.shared},recruit:e.recruit!==void 0?{...t?.recruit,...e.recruit}:t?.recruit,crm:e.crm!==void 0?{...t?.crm,...e.crm}:t?.crm,desk:e.desk!==void 0?{...t?.desk,...e.desk}:t?.desk,output:e.output===void 0?t?.output:Ao(t?.output,e.output)};return await Fp(o),o}async function Un(){await H({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Ln(){let e=lt(),t=ht();await ut(e),await ut(t)}function J(e){return wt.filter(t=>{let o=mt(e,t);return!(!o||t==="desk"&&!o.orgId)})}import{Inject as Os,Injectable as fd}from"@nestjs/common";function ze(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function v(e,t){return Ge({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:Rn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function Nt(e){switch(e){case"sandbox":return"https://recruitsandbox.zoho.com/recruit";case"production":return"https://recruit.zoho.com/recruit";default:return e}}var He="Candidates",Gn="Job_Openings",Ut="Notes",Kn="Emails",yt="Attachments";function Lt(e){let t;if(e!=null)switch(typeof e){case"string":t=e;break;case"object":{let o;Array.isArray(e)?o={and:[e]}:o=e,t=Gt(o);break}default:break}return t}function Gt(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(Po):a&&(s=Gt(a)):s=a,s}function o(a,s){return a.length>1?`(${a.join(s)})`:a[0]}function r(a,s){let c=he(a.map(t)).flatMap(C);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,i=n;return e.and&&(i=r([r(e.and,"and"),n],"and")),i}var Vn=Jr({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function Po(e){let t=Vn(e.value);return`(${e.field}:${e.filter}:${t})`}var zn=Lt;import{BaseError as vp}from"make-error";import{BaseError as Sp}from"make-error";var Ap="__internal_data_array_blank_error";function kp(e){return Array.isArray(e?.data)}var qe="success";function $(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var ye=class extends Sp{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},G=class extends ye{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},je=class extends G{constructor(t,o){super({code:Ap,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function oe(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof je&&!o||(r instanceof G?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof ye?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function re(e,t){return(o,r=t,n)=>async(i,a)=>{try{return await o(i,a)}catch(s){if(s instanceof Le){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function ne(e){return(t,o)=>{if(t?.error!=null){let n=new Le(o),i=e(t,n);if(i)throw i}return t}}var bp="INTERNAL_ERROR",Ip="INVALID_TOKEN",V=class extends G{},Hn="FAILURE",Eo=class extends G{},Pp="4834",We=class extends G{},Ep="INVALID_QUERY",Oo=class extends G{get details(){return this.error.details}},Kt="MANDATORY_NOT_FOUND",ge="DUPLICATE_DATA",Vt="INVALID_DATA",Op="TOO_MANY_REQUESTS",jn=429,Dp="X-RATELIMIT-LIMIT",Mp="X-RATELIMIT-REMAINING",_p="X-RATELIMIT-RESET",Wn=100,Bn=Se;function Do(e){let t=e.get(Dp),o=e.get(Mp),r=e.get(_p),n=null;if(t!=null&&o!=null&&r!=null){let i=Number(t),a=Number(o),s=Number(r),c=new Date(s);n={limit:i,remaining:a,reset:s,resetAt:c}}return n}var Be=class extends G{get headerDetails(){return Do(this.responseError.response.headers)}};function ie(e,t){let o;if(kp(e))o=new je(e,t);else{let r=de(e,t);if(r){let n=$(r);switch(n.code){case bp:o=new Eo(n,e,t);break;case Ip:o=new V(n,e,t);break;case Pp:o=new We(n,e,t);break;case Ep:o=new Oo(n,e,t);break;case Op:o=new Be(n,e,t);break;default:o=new G(n,e,t);break}}}return o}function de(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var qn="ALREADY_ASSOCIATED",Mo=class extends vp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},Je=class extends ye{},_o=class extends Je{},vo=class extends Je{},zt=class extends Je{get invalidFieldDetails(){return this.error.details}},wo=class extends zt{};function Jn(e){let t;switch(e.code){case Vt:{let o=new zt(e);o.invalidFieldDetails.id?t=new wo(e):t=o;break}case Kt:t=new _o(e);break;case ge:t=new vo(e);break;default:t=new Je(e);break}return t}function $n(e,t){return o=>{if(o?.data?.length)return o;throw new Mo(e,t)}}var wp=oe("ZohoRecruit");async function Np(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Xn(t,e)),o}function Xn(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var Yn=ne(Xn),Qn=re(Np,wp);import{BaseError as Up}from"make-error";function Uo(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,M(o,{data:C(r)})).then(i=>{let a=Array.isArray(r),s=ae(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Jn(p[0].result);c=u[0].result.details}return c}))}function ei(e){return Uo(e,"","POST")}function ti(e){return Uo(e,"/upsert","POST")}function oi(e){return Uo(e,"","PUT")}function ri(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,M("DELETE")).then(Lp)}function ni(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,M("GET")).then($n(t.module)).then(o=>o.data[0])}function ii(e){return(t=>e.fetchJson(`/v2/${t.module}?${hi(t).toString()}`,M("GET")))}function Lo(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=zn(o.criteria);r.criteria=n}if(!r.word&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, criteria, email, or phone must be provided");return hi(r)}return(o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,M("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function ai(e){return v(Lo(e))}function $e(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${Vo(n,n.filter).toString()}`,M("GET")).then(i=>i??(r!==!1?ze():i))}}function Go(e){return $e(e)({targetModule:Kn})}function si(e){return v(Go(e))}function Ko(e){return $e(e)({targetModule:yt})}function ci(e){return v(Ko(e))}var dR=20*1024*1024;function ui(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:i}=t,a={attachments_category_id:P(o),attachments_category:P(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${yt}?${T(a).toString()}`,c;if(n!=null){let u=new FormData;u.append("file",n),c=e.fetch(s,{method:"POST",headers:{"Content-Type":""},body:u})}else if(i){let u=`${s}&${T({attachment_url:i}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function pi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function di(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"DELETE"})}var No=class extends Up{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function li(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v2/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?Nt(t.apiUrl):""}${a}`;return e.fetchJson(c,M("POST")).then(u=>{if(u.code!=="success")throw new No(u);return u.details})}}function hi(...e){return T(e,{omitKeys:"module"})}function Vo(...e){return T(e,{omitKeys:["id","module"]})}function M(e,t){return{method:e,body:t??void 0}}function Lp(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===qe?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function ae(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===qe?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function mi(e){return t=>e.fetchJson(`/v2/${He}/actions/associate`,M("PUT",{data:C(t)})).then(o=>{let r=o.data.map(()=>t),n=ae(r,o.data),{included:i,excluded:a}=we(n.errorItems,s=>s.result.code===Hn&&s.result.details.error[0].code===qn);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function yi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${Vo(t).toString()}`,M("GET")).then(o=>o??ze())}function zo(e){let t=yi(e);return o=>t({...o,module:He})}function gi(e){return v(zo(e))}function Ho(e,t=Gn){let o=yi(e);return r=>o({...r,module:t})}function fi(e){return v(Ho(e))}function jo(e){return t=>e.fetchJson(`/v2/${Ut}`,M("POST",{data:t.data})).then(o=>ae(C(t.data),o.data))}function Ri(e){return t=>e.fetchJson(`/v2/${Ut}?${T({ids:t.ids})}`,M("DELETE")).then(o=>ae(C(t.ids),o.data))}function Wo(e){return $e(e)({targetModule:Ut})}function Ti(e){return v(Wo(e))}function Ci(e){let t=jo(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Zi(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module})}`,M("POST",{tags:C(t.tags)})).then(o=>{let r=ae(C(t.tags),o.tags),{included:n,excluded:i}=we(r.errorItems,a=>a.result.code===ge);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Si(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,M("GET")).then(o=>({...o,data:o.tags}))}var xi=100;function Ai(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>xi)throw new Error(`Cannot add tags to more than ${xi} records at once.`);return e.fetchJson(`/v2/${He}/actions/add_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return ae(r,o.data)})}}var Fi=100;function ki(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Fi)throw new Error(`Cannot remove tags from more than ${Fi} records at once.`);return e.fetchJson(`/v2/${He}/actions/remove_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return ae(r,o.data)})}}var Gp="invalid_code",Kp="invalid_client",Bo=class extends q{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},Xe=class extends q{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},Vp=oe("ZohoAccounts");async function zp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=bi(t,e)),o}function bi(e,t){let o,r=e.error;if(r){let n=$(r);switch(n.code){case Gp:case Kp:o=new Bo(n.code);break;default:o=ie(e,t);break}}return o}var Ii=ne(bi),Pi=re(zp,Vp);function fe(e){return async()=>{let t=await e();if(!t.accessToken)throw new Xe;return t.accessToken}}var Hp=e=>{let t="limit"in e?e.limit:void 0,o="resetAt"in e?e.resetAt:void 0,r=t!=null?" The limit is "+String(t)+" requests per reset period.":"",n=o!=null?" Will be reset at "+String(o)+".":"";console.warn("zohoRateLimitedFetchHandler(): Too many requests made."+r+n)};function qo(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests!==!1?e.onTooManyRequests??Hp:void 0,r=e.maxRateLimit??Wn,n=e.resetPeriod??Bn;function i(c,u){return{limit:c,startLimitAt:Math.ceil(c/10),cooldownRate:1.2*(c/(n/L)),exponentRate:1.08,maxWaitTime:L*10,resetPeriod:n,resetAt:u}}let a=i(r),s=hn(a);return An({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,g=!1;if(p){let{remaining:l,limit:m,resetAt:f}=p;if(m!=null&&m!==r){let R=i(m,f??void 0);s.setConfig(R,!1)}if(s.setRemainingLimit(l),f&&s.setNextResetAt(f),g=!0,c.status===jn){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(g),d}})}function Re(e){return qo({...e,readRateLimitDetails:jp})}function jp(e){let t=Do(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Ei(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Re(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=Nt(a.apiUrl),c=i({apiUrl:s}),u=Qn(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:Yn,handleFetchJsonParseErrorFunction:Q});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Ht(e){switch(e){case"sandbox":return"https://crmsandbox.zoho.com/crm";case"production":return"https://www.zohoapis.com/crm";default:return e}}var jt="Notes",Oi="Emails",gt="Attachments";var Di=Lt;import{BaseError as Wp}from"make-error";var Jo=class extends Wp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},Ye=class extends ye{},$o=class extends Ye{},Xo=class extends Ye{},Wt=class extends Ye{get invalidFieldDetails(){return this.error.details}},Yo=class extends Wt{};function Mi(e){let t;switch(e.code){case Vt:{let o=new Wt(e);o.invalidFieldDetails.api_name==="id"?t=new Yo(e):t=o;break}case Kt:t=new $o(e);break;case ge:t=new Xo(e);break;default:t=new Ye(e);break}return t}function _i(e,t){return o=>{if(o?.data?.length)return o;throw new Jo(e,t)}}var Bp=oe("ZohoCrm",{logDataArrayErrors:!1});async function qp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=vi(t,e)),o}function vi(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var wi=ne(vi),Ni=re(qp,Bp);import{BaseError as Jp}from"make-error";function er(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,N(o,{data:C(r)})).catch(Yi).then(i=>{let a=Array.isArray(r),s=Te(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Mi(p[0].result);c=u[0].result.details}return c}))}function Ui(e){return er(e,"","POST")}function Li(e){return er(e,"/upsert","POST")}function Gi(e){return er(e,"","PUT")}function Ki(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,N("DELETE")).catch(Yi).then(Xp)}function Vi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,N("GET")).then(_i(t.module)).then(o=>o.data[0])}function zi(e){return(t=>e.fetchJson(`/v8/${t.module}?${Xi(t).toString()}`,N("GET")))}function tr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Di(o.criteria);r.criteria=n}if(!r.word&&!o.cvid&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, cvid, criteria, email, or phone must be provided");return Xi(r)}return(o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,N("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function Hi(e){return v(tr(e))}function Qe(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${$p(n,n.filter).toString()}`,N("GET")).then(i=>i??(r!==!1?ze():i))}}function or(e){let t=Qe(e)({targetModule:Oi});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function ji(e){return v(or(e))}function rr(e){return Qe(e)({targetModule:gt})}function Wi(e){return v(rr(e))}var ST=20*1024*1024;function Bi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,i={attachments_category_id:P(o),attachments_category:P(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let a=`/v8/${t.module}/${t.id}/${gt}?${T(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function qi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function Ji(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"DELETE"})}var Qo=class extends Jp{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function $i(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v8/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?Ht(t.apiUrl):""}${a}`;return e.fetchJson(c,N("POST")).then(u=>{if(u.code!=="success")throw new Qo(u);return u.details})}}function Xi(...e){return T(e,{omitKeys:"module"})}function $p(...e){return T(e,{omitKeys:["id","module"]})}function N(e,t){return{method:e,body:t??void 0}}function Yi(e){let t;if(e instanceof je)t={data:e.errorDataArray};else throw e;return t}function Xp(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===qe?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function Te(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===qe?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function nr(e){return t=>e.fetchJson(`/v2/${jt}`,N("POST",{data:t.data})).then(o=>Te(C(t.data),o.data))}function Qi(e){return t=>e.fetchJson(`/v2/${jt}?${T({ids:t.ids})}`,N("DELETE")).then(o=>Te(C(t.ids),o.data))}function ir(e){return Qe(e)({targetModule:jt})}function ea(e){return v(ir(e))}function ta(e){let t=nr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function ra(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module})}`,N("POST",{tags:C(t.tags)})).catch(o=>{let r;if(o instanceof G){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Te(C(t.tags),o.tags),{included:n,excluded:i}=we(r.errorItems,a=>a.result.code===ge);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function na(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,N("DELETE")).then(o=>o.tags)}function ia(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,N("GET")).then(o=>({...o,data:o.tags}))}var oa=100;function aa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,N("POST",sa(t))).then(o=>{let r=o.data.map(()=>t);return Te(r,o.data)})}function sa(e){if(Array.isArray(e.ids)&&e.ids.length>oa)throw new Error(`Cannot add/remove tags from more than ${oa} records at once.`);let t=[...C(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&C(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:C(e.ids)}}function ca(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,N("POST",sa(t))).then(o=>{let r=o.data.map(()=>t);return Te(r,o.data)})}function ua(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Re(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=Ht(a.apiUrl),c=i({apiUrl:s}),u=Ni(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:wi,handleFetchJsonParseErrorFunction:Q});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function pa(e,t){return Ge({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.page_context?.has_more_rows??!1}},buildInputForNextPage:function(o,r,n){let a=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??a?.row_count??20,c=(a?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function Ie(e,t){return{method:e,body:t??void 0}}function da(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,Ie("GET"))}function ar(e){return t=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/requests",queryParams:{data:JSON.stringify(n)}},Ie("GET"))}}function la(e){let t=ar(e);return pa(t)}function ha(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,Ie("GET"))}function ma(e){return()=>e.fetchJson("/fieldtypes",Ie("GET"))}function ya(e){return({requestId:t,...o})=>{let n=T(o).toString(),i=n?`?${n}`:"",a=`/requests/${t}/pdf${i}`;return e.fetch(a,{method:"GET"})}}function ga(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function fa(e){return({requestData:t,file:o})=>{let r=new FormData;return r.append("data",JSON.stringify({requests:t})),r.append("file",o),e.fetch("/requests",{method:"POST",headers:{"Content-Type":""},body:r}).then(n=>n.json())}}function Ra(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,Ie("PUT",{requests:o}))}function Ta(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,Ie("POST",r))}}function Ca(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,Ie("PUT",{expire_by:o}))}function xa(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let i=T(n),a=i.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...a?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()}:{}})}}function Fa(e){switch(e){case"sandbox":return"https://signsandbox.zoho.com/api/v1";case"production":return"https://sign.zoho.com/api/v1";default:return e}}var Yp=oe("ZohoSign",{logDataArrayErrors:!1});async function Qp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Za(t,e)),o}function Za(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var Sa=ne(Za),Aa=re(Qp,Yp);function ka(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Re(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=Fa(a.apiUrl),c=i({apiUrl:s}),u=Aa(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:Sa,handleFetchJsonParseErrorFunction:Q});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function ba(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var ed=oe("ZohoDesk",{logDataArrayErrors:!1});async function td(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ia(t,e)),o}function Ia(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var Pa=ne(Ia),Ea=re(td,ed);var od="X-Rate-Limit-Remaining-v3",rd="Retry-After",nd=200;function id(e){let t=e.get(od),o;if(t!=null){let r=Number(t),n,i=e.get(rd);if(i!=null){let a=Number(i);Number.isNaN(a)||(n=new Date(Date.now()+a*L))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function Oa(e){return qo({maxRateLimit:nd,...e,readRateLimitDetails:id})}function Da(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Oa(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:a.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!a.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=ba(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=Ea(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:Pa,handleFetchJsonParseErrorFunction:Q});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Ma=25;function X(e,t){return Ge({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Ma}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??Ma,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Pe(e,t){return{method:e,body:t??void 0}}function et(e,t){return T(e,{omitKeys:t})}function Bt(e){let t;return e&&(t=P(C(e))),t}function sr(e){return t=>{let{include:o,...r}=t,n=et([{...r,include:Bt(o)}]);return e.fetchJson(`/tickets?${n}`,Pe("GET")).then(i=>i??{data:[]})}}function _a(e){return t=>{let{ticketId:o,include:r}=t,i=et([{include:Bt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Pe("GET"))}}function cr(e){return t=>{let o=et([t]);return e.fetchJson(`/tickets/search?${o}`,Pe("GET")).then(r=>r??{data:[]})}}function va(e){return t=>{let{contactId:o,include:r,...n}=t,i=et([{...n,include:Bt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Pe("GET")).then(a=>a??{data:[]})}}function wa(e){return t=>{let{productId:o,include:r,...n}=t,i=et([{...n,include:Bt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Pe("GET")).then(a=>a??{data:[]})}}function Na(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Pe("GET"))}function Ua(e){return t=>{let o=et([{agentIds:P(C(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Pe("GET"))}}function La(e){return X(sr(e))}function Ga(e){return X(cr(e))}function Ka(e){return{method:e}}function Va(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,Ka("GET")).then(r=>r??{data:[]})}}function za(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ka("GET"))}function ur(e){return{method:e}}function Ha(e){let t;return e&&(t=P(C(e))),t}function pr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Ha(o)}]);return e.fetchJson(`/contacts?${n}`,ur("GET")).then(i=>i??{data:[]})}}function ja(e){return t=>{let{contactId:o,include:r}=t,i=T([{include:Ha(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,ur("GET"))}}function Wa(e){return t=>{let o=T([{contactIds:P(C(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,ur("GET")).then(r=>r??[])}}function Ba(e){return X(pr(e))}function ft(e,t){return{method:e,body:t??void 0}}function qa(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("GET")).then(o=>o??[])}function Ja(e){return t=>{let o={tags:C(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("POST",o)).then(r=>r??[])}}function $a(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,ft("DELETE"))}function Xa(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,ft("GET")).then(r=>r??{data:[]})}}function Ya(e){return t=>{let o=T([t]);return e.fetchJson(`/ticketTags?${o}`,ft("GET")).then(r=>r??{data:[]})}}function dr(e,t){return{method:e,body:t??void 0}}function Qa(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("GET")).then(o=>o??[])}function es(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("POST",o))}}function ts(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("DELETE",o))}}function os(e,t){return{method:e,body:t??void 0}}function ad(e){let t;return e&&(t=P(C(e))),t}function rs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:ad(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,os("GET")).then(a=>a??{data:[]})}}function ns(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,os("DELETE"))}function qt(e,t){return{method:e,body:t??void 0}}function is(e){let t;return e&&(t=P(C(e))),t}function as(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:is(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,qt("GET")).then(a=>a??{data:[]})}}function ss(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=T([{include:is(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,qt("GET"))}}function cs(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,qt("POST",r))}}function us(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,qt("DELETE"))}function Rt(e,t){return{method:e,body:t??void 0}}function ps(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Rt("GET"))}function ds(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Rt("POST",r))}}function ls(e){return t=>{let{ticketId:o,...r}=t,n=T([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Rt("GET")).then(i=>i??{data:[]})}}function hs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Rt("GET"))}function ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Rt("GET"))}function ys(e){return{method:e}}function gs(e){let t;return e&&(t=P(C(e))),t}function lr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:gs(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,ys("GET")).then(a=>a??{data:[]})}}function fs(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=T([{include:gs(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,ys("GET"))}}function Rs(e){return X(lr(e))}function sd(e){return{method:e}}function cd(e){let t;return e&&(t=P(C(e))),t}function hr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:cd(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,sd("GET")).then(a=>a??{data:[]})}}function Ts(e){return X(hr(e))}function Jt(e){return{method:e}}function Cs(e){let t;return e&&(t=P(C(e))),t}function mr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Cs(o)}]);return e.fetchJson(`/agents?${n}`,Jt("GET")).then(i=>i??{data:[]})}}function xs(e){return t=>{let{agentId:o,include:r}=t,i=T([{include:Cs(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,Jt("GET"))}}function Fs(e){return t=>{let o=T([{agentIds:P(C(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,Jt("GET")).then(r=>r?.data??[])}}function Zs(e){return()=>e.fetchJson("/myinfo",Jt("GET"))}function Ss(e){return X(mr(e))}function $t(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:i,refreshToken:a}=t??{},s=i?.clientId??o,c=i?.clientSecret??r,p=T({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:a??n});return e.fetchJson(`/oauth/v2/token?${p}`,ud("POST"))}}function ud(e,t){return{method:e,body:t}}var pd="https://accounts.zoho.com";function As(e){return e==="us"?pd:e}function ks(e){let t=Re(),{logZohoServerErrorFunction:o,fetchFactory:r=n=>te.makeFetch({baseUrl:n.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:t,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return n=>{if(n.refreshToken)if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsConfig missing clientSecret.")}else throw new Error("ZohoAccountsConfig missing clientId.");else throw new Error("ZohoAccountsConfig missing refreshToken.");let i=As(n.apiUrl??"us"),a=r({apiUrl:i}),s=Pi(a,o),c=ee(s,{interceptJsonResponse:Ii,handleFetchJsonParseErrorFunction:Q}),u=async()=>{let l=Date.now(),{access_token:m,api_domain:f,scope:R,expires_in:S}=await $t(d)();return{accessToken:m,apiDomain:f,expiresIn:S,expiresAt:new Date(l+S*L),scope:R}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=dd({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function dd(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Se,i=null,a=async()=>{i=null},s=async()=>{if(!i){let c=await o?.loadCachedToken();c&&(i=c)}if(i!=null&&Date.now()+n>=i.expiresAt.getTime()&&(i=null),!i){try{i=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new Xe("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function Ce(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var xe=class{zohoAccounts;factoryConfig;static assertValidConfig(t){let{zohoAccounts:o}=t;if(o)if(o.serviceAccessTokenKey)if(o.refreshToken)if(o.apiUrl){if(!o.clientId)throw new Error("ZohoAccountsServiceConfig.zohoAccounts.clientId is required")}else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.apiUrl is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.refreshToken is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.serviceAccessTokenKey is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts is required")}};import{Injectable as ld}from"@nestjs/common";var tt=class{};tt=Z([ld()],tt);function hd(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!dn(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function md(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function yd(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Is(e,t){let o=[...e],r=typeof t=="function"?t:t!==!1?yd:void 0;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");function n(i){let a=o.map(u=>u.loadZohoAccessTokenCache(i)),s=a.map(hd),c=qr(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>md(d,u)));if(r!=null){let d=he(p.map(g=>g.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function Ps(e,t){let o={};if(e!=null)for(let i of Object.keys(e)){let a=e[i];a!=null&&(o[i]=a)}let r=Wr(o);function n(i){return{loadCachedToken:async()=>{let a=await r.get(i);return t&&console.log("retrieving access token from memory: ",{service:i,hit:a!=null,expiresAt:a?.expiresAt}),a},updateCachedToken:async a=>{await r.set(i,a),t&&console.log("updating access token in memory: ",{service:i,expiresAt:a?.expiresAt})},clearCachedToken:async()=>{await r.remove(i),t&&console.log("clearing access token in memory: ",{service:i})}}}return{loadZohoAccessTokenCache:n}}var gd=".tmp/zoho-access-tokens.json";function bs(e){if(e==null||typeof e!="object")return;let t=e,o=t.expiresAt,r=o!=null&&!(o instanceof Date)?new Date(o):o;return{...t,expiresAt:r}}function Es(e=gd,t=!0){let o=Mn({filePath:e,reviver:bs}),r=t?Br(o):o;function n(c){return{loadCachedToken:()=>r.get(c),updateCachedToken:async u=>{try{await r.set(c,u)}catch(p){console.error("Failed updating access token in file: ",p)}},clearCachedToken:async()=>{try{await r.remove(c)}catch(u){console.error("Failed clearing access token in file: ",u)}}}}async function i(){let c=await me(e);if(c==null)return;let u={};for(let p of Object.keys(c))u[p]=bs(c[p]);return u}async function a(c){await r.clear();for(let[u,p]of Object.entries(c))p!=null&&await r.set(u,p)}async function s(){await r.clear()}return{loadZohoAccessTokenCache:n,readTokenFile:i,writeTokenFile:a,deleteTokenFile:s}}var _=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=ks(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return $t(this.accountsContext)}};_=Z([fd(),b(0,Os(xe)),b(1,Os(tt))],_);import{Inject as Ds,Injectable as Rd}from"@nestjs/common";var Tt=class{zohoCrm;factoryConfig;static assertValidConfig(t){Ce(t.zohoCrm)}};var Ee=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=ua({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Ui(this.crmContext)}get upsertRecord(){return Li(this.crmContext)}get updateRecord(){return Gi(this.crmContext)}get deleteRecord(){return Ki(this.crmContext)}get getRecordById(){return Vi(this.crmContext)}get getRecords(){return zi(this.crmContext)}get searchRecords(){return tr(this.crmContext)}get searchRecordsPageFactory(){return Hi(this.crmContext)}get getRelatedRecordsFunctionFactory(){return Qe(this.crmContext)}get getEmailsForRecord(){return or(this.crmContext)}get getEmailsForRecordPageFactory(){return ji(this.crmContext)}get getAttachmentsForRecord(){return rr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Wi(this.crmContext)}get uploadAttachmentForRecord(){return Bi(this.crmContext)}get downloadAttachmentForRecord(){return qi(this.crmContext)}get deleteAttachmentFromRecord(){return Ji(this.crmContext)}get createNotes(){return nr(this.crmContext)}get deleteNotes(){return Qi(this.crmContext)}get createNotesForRecord(){return ta(this.crmContext)}get getNotesForRecord(){return ir(this.crmContext)}get getNotesForRecordPageFactory(){return ea(this.crmContext)}get executeRestApiFunction(){return $i(this.crmContext)}get createTagsForModule(){return ra(this.crmContext)}get deleteTag(){return na(this.crmContext)}get getTagsForModule(){return ia(this.crmContext)}get addTagsToRecords(){return aa(this.crmContext)}get removeTagsFromRecords(){return ca(this.crmContext)}};Ee=Z([Rd(),b(0,Ds(Tt)),b(1,Ds(_))],Ee);import{ConfigModule as BF,ConfigService as qF}from"@nestjs/config";import{Inject as Ms,Injectable as Td}from"@nestjs/common";var Ct=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Ce(t.zohoRecruit)}};var Oe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Ei({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return ei(this.recruitContext)}get upsertRecord(){return ti(this.recruitContext)}get updateRecord(){return oi(this.recruitContext)}get deleteRecord(){return ri(this.recruitContext)}get getRecordById(){return ni(this.recruitContext)}get getRecords(){return ii(this.recruitContext)}get searchRecords(){return Lo(this.recruitContext)}get searchRecordsPageFactory(){return ai(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return $e(this.recruitContext)}get getEmailsForRecord(){return Go(this.recruitContext)}get getEmailsForRecordPageFactory(){return si(this.recruitContext)}get getAttachmentsForRecord(){return Ko(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return ci(this.recruitContext)}get uploadAttachmentForRecord(){return ui(this.recruitContext)}get downloadAttachmentForRecord(){return pi(this.recruitContext)}get deleteAttachmentFromRecord(){return di(this.recruitContext)}get createNotes(){return jo(this.recruitContext)}get deleteNotes(){return Ri(this.recruitContext)}get createNotesForRecord(){return Ci(this.recruitContext)}get getNotesForRecord(){return Wo(this.recruitContext)}get getNotesForRecordPageFactory(){return Ti(this.recruitContext)}get executeRestApiFunction(){return li(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return mi(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return zo(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return gi(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Ho(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return fi(this.recruitContext)}get createTagsForModule(){return Zi(this.recruitContext)}get getTagsForModule(){return Si(this.recruitContext)}get addTagsToRecords(){return Ai(this.recruitContext)}get removeTagsFromRecords(){return ki(this.recruitContext)}};Oe=Z([Td(),b(0,Ms(Ct)),b(1,Ms(_))],Oe);import{ConfigModule as gZ,ConfigService as fZ}from"@nestjs/config";import{Inject as _s,Injectable as Cd}from"@nestjs/common";var xt=class{zohoSign;factoryConfig;static assertValidConfig(t){Ce(t.zohoSign)}};var Ft=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=ka({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return da(this.signContext)}get getDocuments(){return ar(this.signContext)}get getDocumentsPageFactory(){return la(this.signContext)}get getDocumentFormData(){return ha(this.signContext)}get retrieveFieldTypes(){return ma(this.signContext)}get downloadPdf(){return ya(this.signContext)}get downloadCompletionCertificate(){return ga(this.signContext)}get createDocument(){return fa(this.signContext)}get updateDocument(){return Ra(this.signContext)}get sendDocumentForSignature(){return Ta(this.signContext)}get extendDocument(){return Ca(this.signContext)}get deleteDocument(){return xa(this.signContext)}};Ft=Z([Cd(),b(0,_s(xt)),b(1,_s(_))],Ft);import{ConfigModule as LZ,ConfigService as GZ}from"@nestjs/config";function vs(e){return{...e,operationType:e.notifications.operation_type}}var ws=mn(e=>e.operationType),Ns=gn({configurerForAccessor:e=>{let t=yn(e,r=>r);return{...e,handleRequestSubmitted:t("RequestSubmitted"),handleRequestViewed:t("RequestViewed"),handleRequestSigningSuccess:t("RequestSigningSuccess"),handleRequestCompleted:t("RequestCompleted"),handleRequestRejected:t("RequestRejected"),handleRequestRecalled:t("RequestRecalled"),handleRequestForwarded:t("RequestForwarded"),handleRequestExpired:t("RequestExpired")}}});var Us="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",De=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as bd,Inject as Id,Post as Pd,Req as Ed}from"@nestjs/common";import{Inject as Sd,Injectable as Ad,Logger as kd}from"@nestjs/common";import{createHmac as xd,timingSafeEqual as Fd}from"node:crypto";var Zd="x-zs-webhook-signature";function Ls(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Zd];if(!n)return{valid:!1};let i=r.toString("utf-8"),a=xd("sha256",t).update(i,"utf-8").digest("base64"),s=!1;try{let u=Buffer.from(n,"base64"),p=Buffer.from(a,"base64");u.length===p.length&&(s=Fd(u,p))}catch{s=!1}let c;if(s)try{let u=JSON.parse(i);c=vs(u)}catch{s=!1}return s&&c?{valid:!0,event:c}:{valid:!1}}}var le=class{logger=new kd("ZohoSignWebhookService");_verifier;handler=ws();configure=Ns(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Ls({secret:o})}async updateForWebhook(t,o){let r=await this._verifier(t,o);r.valid?await this.updateForZohoSignEvent(r.event):this.logger.warn("Received invalid Zoho Sign webhook event.",t)}async updateForZohoSignEvent(t){await this.handler(t)||this.logger.warn("Received unexpected/unhandled Zoho Sign webhook event.",t)}};le=Z([Ad(),b(0,Sd(De))],le);var Me=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};Z([Pd(),b(0,Ed()),b(1,Pn())],Me.prototype,"handleZohoSignWebhook",1),Me=Z([bd("/webhook/zoho/sign"),b(0,Id(le))],Me);import{Module as Od}from"@nestjs/common";import{ConfigModule as Dd,ConfigService as Md}from"@nestjs/config";function _d(e){let t={zohoSignWebhook:{webhookSecret:e.get(Us)}};return De.assertValidConfig(t),t}var Yt=class{};Yt=Z([Od({imports:[Dd],controllers:[Me],providers:[{provide:De,inject:[Md],useFactory:_d},le],exports:[le]})],Yt);import{Inject as Gs,Injectable as vd}from"@nestjs/common";var Zt=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Ce(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var _e=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Da({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return sr(this.deskContext)}get getTicketById(){return _a(this.deskContext)}get searchTickets(){return cr(this.deskContext)}get getTicketsForContact(){return va(this.deskContext)}get getTicketsForProduct(){return wa(this.deskContext)}get getTicketMetrics(){return Na(this.deskContext)}get getAgentsTicketsCount(){return Ua(this.deskContext)}get getTicketsPageFactory(){return La(this.deskContext)}get searchTicketsPageFactory(){return Ga(this.deskContext)}get getDepartments(){return Va(this.deskContext)}get getDepartmentById(){return za(this.deskContext)}get getContacts(){return pr(this.deskContext)}get getContactById(){return ja(this.deskContext)}get getContactsByIds(){return Wa(this.deskContext)}get getContactsPageFactory(){return Ba(this.deskContext)}get getTicketTags(){return qa(this.deskContext)}get associateTicketTags(){return Ja(this.deskContext)}get dissociateTicketTag(){return $a(this.deskContext)}get searchTags(){return Xa(this.deskContext)}get getAllTags(){return Ya(this.deskContext)}get getTicketFollowers(){return Qa(this.deskContext)}get addTicketFollowers(){return es(this.deskContext)}get removeTicketFollowers(){return ts(this.deskContext)}get getTicketAttachments(){return rs(this.deskContext)}get deleteTicketAttachment(){return ns(this.deskContext)}get getTicketComments(){return as(this.deskContext)}get getTicketCommentById(){return ss(this.deskContext)}get createTicketComment(){return cs(this.deskContext)}get deleteTicketComment(){return us(this.deskContext)}get getTicketTimer(){return ps(this.deskContext)}get performTicketTimerAction(){return ds(this.deskContext)}get getTicketTimeEntries(){return ls(this.deskContext)}get getTicketTimeEntryById(){return hs(this.deskContext)}get getTicketTimeEntrySummation(){return ms(this.deskContext)}get getTicketThreads(){return lr(this.deskContext)}get getTicketThreadById(){return fs(this.deskContext)}get getTicketThreadsPageFactory(){return Rs(this.deskContext)}get getTicketActivities(){return hr(this.deskContext)}get getTicketActivitiesPageFactory(){return Ts(this.deskContext)}get getAgents(){return mr(this.deskContext)}get getAgentById(){return xs(this.deskContext)}get getAgentsByIds(){return Fs(this.deskContext)}get getMyInfo(){return Zs(this.deskContext)}get getAgentsPageFactory(){return Ss(this.deskContext)}};_e=Z([vd(),b(0,Gs(Zt)),b(1,Gs(_))],_e);import{ConfigModule as GS,ConfigService as KS}from"@nestjs/config";function wd(e){return`${e.clientId}:${e.refreshToken}`}function ot(e){let t=Is([Ps(),Es(ht())]),o=new Map;function r(p,d){let g=wd(p),l=o.get(g);if(l)return l;let m={zohoAccounts:{serviceAccessTokenKey:d,refreshToken:p.refreshToken,clientId:p.clientId,clientSecret:p.clientSecret,apiUrl:p.region??"us"}},f=new _(m,t);return o.set(g,f),f}let n,i=mt(e,"recruit");if(i){let p=r(i,"recruit"),d={zohoRecruit:{apiUrl:i.apiMode}};n=new Oe(d,p)}let a,s=mt(e,"crm");if(s){let p=r(s,"crm"),d={zohoCrm:{apiUrl:s.apiMode}};a=new Ee(d,p)}let c,u=mt(e,"desk");if(u?.orgId){let p=r(u,"desk"),d={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new _e(d,p)}return{recruitApi:n,crmApi:a,deskApi:c}}ro([...to,/1000\.\w{20,}/g]);function Ks(e){return e instanceof V?{ok:!1,error:ue(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof We?{ok:!1,error:ue(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Be?{ok:!1,error:ue(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof G?{ok:!1,error:ue(e.message),code:"API_ERROR"}:no(e)}xr(e=>{if(e instanceof V||e instanceof We||e instanceof Be||e instanceof G)return Ks(e)});function y(e){console.log(JSON.stringify(Ks(e)))}var Vs={us:"https://accounts.zoho.com",eu:"https://accounts.zoho.eu",in:"https://accounts.zoho.in",au:"https://accounts.zoho.com.au",jp:"https://accounts.zoho.jp"},zs={recruit:["ZohoRecruit.modules.ALL","ZohoRecruit.settings.all","ZohoRecruit.functions.execute.READ","ZohoRecruit.functions.execute.CREATE"],crm:["ZohoCRM.modules.ALL","ZohoCRM.settings.ALL","ZohoCRM.functions.execute.READ","ZohoCRM.functions.execute.CREATE"],desk:["Desk.tickets.ALL","Desk.tasks.ALL","Desk.contacts.ALL","Desk.settings.ALL","Desk.events.ALL","Desk.search.READ","Desk.articles.READ","Desk.basic.READ"],sign:["ZohoSign.documents.ALL","ZohoSign.templates.ALL"]};function Nd(e){if(e){if(e.startsWith("http://")||e.startsWith("https://"))try{let o=new URL(e).searchParams.get("code");if(!o)throw new Error('No "code" parameter found in the provided URL.');return o}catch(t){throw t instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`):t}return e}}var Ud={command:"setup",describe:"Generate OAuth authorization URL, exchange code, or set refresh token directly",builder:e=>e.option("client-id",{type:"string",describe:"OAuth client ID (from https://api-console.zoho.com/)"}).option("client-secret",{type:"string",describe:"OAuth client secret"}).option("redirect-uri",{type:"string",default:"http://localhost/oauth",describe:"Redirect URI (must match API console config)"}).option("region",{type:"string",default:"us",choices:["us","eu","in","au","jp"],describe:"Zoho region"}).option("scopes",{type:"string",default:"recruit,crm,desk",describe:"Comma-separated products for OAuth scopes (recruit,crm,desk,sign)"}).option("code",{type:"string",describe:"Authorization code or the full redirect URL (code is extracted automatically)"}).option("token",{type:"string",describe:"Set a refresh token directly (skips OAuth code exchange)"}).option("product",{type:"string",choices:[...wt],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth setup --client-id 1000.ABC --client-secret xyz","Step 1: Get OAuth URL (saves shared credentials)"],["$0 auth setup --code 1000.AUTH.CODE","Step 2: Exchange code for refresh token"],['$0 auth setup --code "http://localhost/oauth?code=1000.AUTH.CODE&location=us"',"Step 2: Paste the full redirect URL"],["$0 auth setup --client-id 1000.ABC --client-secret xyz --token 1000.REFRESH.TOKEN","Set shared refresh token directly"],["$0 auth setup --product crm --client-id 1000.CRM --client-secret xyz --token 1000.CRM.TOKEN","Set CRM-specific credentials"]]),handler:async e=>{try{let t=await z(),o=e.product,r=e.clientId??t?.shared?.clientId,n=e.clientSecret??t?.shared?.clientSecret,i=e.redirectUri,a=e.region??t?.shared?.region??"us",s=e.scopes.split(",").map(d=>d.trim()),c=Nd(e.code),u=e.token,p=Vs[a]??Vs.us;if(!r||!n)throw new Error("--client-id and --client-secret are required. Get them from https://api-console.zoho.com/");if(u){let d={clientId:r,clientSecret:n,refreshToken:u};if(o){let g={...d,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0},l=await H({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:g});h({success:!0,product:o,refreshToken:pe(u),configSaved:!0,configuredProducts:J(l)})}else{let g=await H({shared:{...d,region:a,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0});h({success:!0,refreshToken:pe(u),configSaved:!0,configuredProducts:J(g)})}}else if(c){let d=`${p}/oauth/v2/token`,g=new URLSearchParams({grant_type:"authorization_code",client_id:r,client_secret:n,redirect_uri:i,code:c}),m=await(await fetch(d,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:g.toString()})).json();if(m.error)throw new Error(`Token exchange failed: ${m.error}`);let f=m.refresh_token;if(!f)throw new Error("No refresh_token in response. The authorization code may have expired (valid for 2 minutes). Generate a new one.");let R={clientId:r,clientSecret:n,refreshToken:f},S;o?S=await H({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:{...R,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0}}):S=await H({shared:{...R,region:a,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({step:2,success:!0,product:o??"shared",refreshToken:pe(f),accessToken:m.access_token?pe(m.access_token):null,scope:m.scope,configSaved:!0,configuredProducts:J(S)})}else{let d=s.flatMap(l=>zs[l]??[]);if(d.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(zs).join(", ")}`);let g=`${p}/oauth/v2/auth?scope=${d.join(",")}&client_id=${encodeURIComponent(r)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(i)}`;await H({shared:{clientId:r,clientSecret:n,refreshToken:t?.shared?.refreshToken??"",region:a,apiMode:e.apiMode??t?.shared?.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({step:1,instructions:'Open the authorization URL in a browser. Authorize the application. Copy the "code" parameter from the redirect URL.',authorizationUrl:g,redirectUri:i,scopes:d,credentialsSaved:!0,nextStep:'zoho-cli auth setup --code "PASTE_REDIRECT_URL_OR_AUTH_CODE"'})}}catch(t){y(t),process.exit(1)}}},Ld={command:"set",describe:"Save Zoho API credentials directly",builder:e=>e.option("client-id",{type:"string",demandOption:!0,describe:"OAuth client ID"}).option("client-secret",{type:"string",demandOption:!0,describe:"OAuth client secret"}).option("refresh-token",{type:"string",demandOption:!0,describe:"OAuth refresh token"}).option("product",{type:"string",choices:[...wt],describe:"Store for a specific product instead of shared"}).option("region",{type:"string",default:"us",describe:"Zoho region (us, eu, in, au, jp)"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth set --client-id abc --client-secret xyz --refresh-token 1000.abc.xyz","Set shared credentials"],["$0 auth set --product crm --client-id abc --client-secret xyz --refresh-token 1000.crm.xyz","Set CRM-specific credentials"]]),handler:async e=>{try{let t=e.product,o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken},r;t?r=await H({shared:(await z())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await H({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({saved:!0,product:t??"shared",configuredProducts:J(r)})}catch(t){y(t),process.exit(1)}}},Gd={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){if(r)return{clientId:r.clientId?pe(r.clientId):void 0,clientSecret:r.clientSecret?pe(r.clientSecret):void 0,refreshToken:r.refreshToken?pe(r.refreshToken):void 0}};var e=o;let t=await z();if(!t){h({configured:!1});return}h({configured:!0,shared:{...o(t.shared),region:t.shared?.region??"us",apiMode:t.shared?.apiMode??"production"},recruit:t.recruit?{...o(t.recruit),apiUrl:t.recruit.apiUrl}:null,crm:t.crm?{...o(t.crm),apiUrl:t.crm.apiUrl}:null,desk:t.desk?{...o(t.desk),apiUrl:t.desk.apiUrl,orgId:t.desk.orgId}:null,configuredProducts:J(t)})}catch(t){y(t),process.exit(1)}}},Kd={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await z();if(!e){h({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"});return}let t=J(e);if(t.length===0){h({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});return}let o=ot(e),r={};for(let n of t)try{let i;if(n==="recruit"?i=o.recruitApi:n==="crm"?i=o.crmApi:i=o.deskApi,!i){r[n]={authenticated:!1,error:"Not configured"};continue}let s=await i.zohoAccountsApi.accessToken();r[n]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(i){let a=i instanceof Error?i.message:String(i);r[n]={authenticated:!1,error:a}}h({products:r})}catch(e){y(e),process.exit(1)}}},Vd={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Ln(),h({cleared:!0})}catch(e){y(e),process.exit(1)}}},Hs={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(Ud).command(Ld).command(Gd).command(Kd).command(Vd).demandCommand(1,"Please specify an auth subcommand."),handler:F};import{access as zd,constants as Hd}from"node:fs";import{dirname as jd}from"node:path";var js={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=[],t=await z();t?e.push({name:"config",status:"pass",message:`Config loaded from ${lt()}`}):e.push({name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}),t?.shared?.clientId&&t?.shared?.clientSecret&&t?.shared?.refreshToken?e.push({name:"shared-credentials",status:"pass",message:"Shared credentials present"}):t&&e.push({name:"shared-credentials",status:"warn",message:"Missing shared credentials. Per-product credentials may still work."});let o=jd(ht());if(await Wd(o)?e.push({name:"token-cache",status:"pass",message:`Token cache directory writable: ${o}`}):e.push({name:"token-cache",status:"warn",message:`Token cache directory not writable: ${o}`}),t){let i=J(t);i.length>0?e.push({name:"products",status:"pass",message:`Configured products: ${i.join(", ")}`}):e.push({name:"products",status:"fail",message:"No products have complete credentials"});let a=ot(t);for(let s of i)try{let c;if(s==="recruit"?c=a.recruitApi:s==="crm"?c=a.crmApi:c=a.deskApi,c){let p=await c.zohoAccountsApi.accessToken();e.push({name:`${s}-token`,status:"pass",message:`${s}: Token exchange successful. Scope: ${p.scope}`})}}catch(c){let u=c instanceof Error?c.message:String(c);e.push({name:`${s}-token`,status:"fail",message:`${s}: Token exchange failed: ${u}`})}t.desk?.orgId?e.push({name:"desk-org-id",status:"pass",message:`Desk org ID configured: ${t.desk.orgId}`}):i.includes("desk")||e.push({name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."})}let n=e.every(i=>i.status==="pass");h({checks:e,healthy:n}),n||process.exit(e.some(i=>i.status==="fail")?1:0)}};function Wd(e){return new Promise(t=>{zd(e,Hd.W_OK,o=>{t(!o)})})}var Ws=bn({notInitializedMessage:"CLI context not initialized. This is a bug."});function Bs(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await z();r||(y(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),J(r).length===0&&(y(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),Ws.set(ot(r))}catch(r){y(r),process.exit(4)}}}function fr(e){return Ws.require()}function j(e){let{recruitApi:t}=fr(e);if(!t)throw new Error("Recruit not configured. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z");return t}function W(e){let{crmApi:t}=fr(e);if(!t)throw new Error("CRM not configured. Run: zoho-cli auth setup --product crm --client-id X --client-secret Y --token Z");return t}function x(e){let{deskApi:t}=fr(e);if(!t)throw new Error("Desk not configured. Run: zoho-cli auth setup --product desk --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function se(e){return Fo(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function E(e){return Fo(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function D(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function Fe(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function St(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function Qt(e){return e.option("sort-by",{type:"string",describe:"Field to sort by"}).option("sort-order",{type:"string",choices:["asc","desc"],describe:"Sort direction"})}var Bd={nextInput:(e,t)=>{if(!t.info?.more_records)return;let o=e.page??1;return{...e,page:o+1}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({page:t.info?.page??e.page,per_page:t.info?.per_page??e.per_page,more_records:t.info?.more_records??!1}),hasMorePagesAvailable:(e,t)=>t.info?.more_records??!1},O={nextInput:(e,t)=>{let o=e.limit??25;if(o<=0||(t.data?.length??0)<o)return;let n=e.from??1;return{...e,from:n+o}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({from:e.from,limit:e.limit,count:t.data?.length??0}),hasMorePagesAvailable:(e,t)=>{let o=e.limit??25;return o<=0?!1:(t.data?.length??0)>=o}};async function ce(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:r,adapter:Bd,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;h(i.data,{page:i.info?.page,per_page:i.info?.per_page,more_records:i.info?.more_records})}}var qd={command:"list",describe:"List records from a module",builder:e=>Qt(St(se(D(e)))),handler:async e=>{try{let t=j(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await ce({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){y(t),process.exit(1)}}},Jd={command:"get",describe:"Get a record by ID",builder:e=>Fe(D(e)),handler:async e=>{try{let o=await j(e).getRecordById({module:e.module,id:e.id});h(o)}catch(t){y(t),process.exit(1)}}},$d={command:"search",describe:"Search records in a module",builder:e=>se(D(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=j(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){y(t),process.exit(1)}}},Xd={command:"insert",describe:"Insert a record into a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=j(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},Yd={command:"upsert",describe:"Upsert a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=j(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},Qd={command:"update",describe:"Update a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=j(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},el={command:"delete",describe:"Delete records from a module",builder:e=>D(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=j(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});h(r)}catch(t){y(t),process.exit(1)}}},tl={command:"emails",describe:"Get emails for a record",builder:e=>se(Fe(D(e))),handler:async e=>{try{let t=j(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){y(t),process.exit(1)}}},ol={command:"attachments",describe:"Get attachments for a record",builder:e=>se(Fe(D(e))),handler:async e=>{try{let t=j(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){y(t),process.exit(1)}}},qs={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(qd).command(Jd).command($d).command(Xd).command(Yd).command(Qd).command(el).command(tl).command(ol).demandCommand(1,"Please specify a recruit subcommand.").example([["$0 recruit list -m Candidates --per-page 10","List first 10 candidates"],["$0 recruit get -m Candidates --id 12345","Get a candidate by ID"],['$0 recruit search -m Candidates --word "John"',"Search candidates by keyword"],[`$0 recruit insert -m Candidates --data '{"First_Name":"John","Last_Name":"Doe"}'`,"Insert a candidate"]]),handler:F};var rl={command:"list",describe:"List records from a module",builder:e=>Qt(St(se(D(e)),!0)),handler:async e=>{try{let t=W(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await ce({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){y(t),process.exit(1)}}},nl={command:"get",describe:"Get a record by ID",builder:e=>Fe(D(e)),handler:async e=>{try{let o=await W(e).getRecordById({module:e.module,id:e.id});h(o)}catch(t){y(t),process.exit(1)}}},il={command:"search",describe:"Search records in a module",builder:e=>se(D(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=W(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){y(t),process.exit(1)}}},al={command:"insert",describe:"Insert a record into a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},sl={command:"upsert",describe:"Upsert a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},cl={command:"update",describe:"Update a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},ul={command:"delete",describe:"Delete records from a module",builder:e=>D(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=W(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});h(r)}catch(t){y(t),process.exit(1)}}},pl={command:"emails",describe:"Get emails for a record",builder:e=>se(Fe(D(e))),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){y(t),process.exit(1)}}},dl={command:"attachments",describe:"Get attachments for a record",builder:e=>St(se(Fe(D(e))),!0),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){y(t),process.exit(1)}}},Js={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(rl).command(nl).command(il).command(al).command(sl).command(cl).command(ul).command(pl).command(dl).demandCommand(1,"Please specify a CRM subcommand.").example([['$0 crm list -m Contacts --fields "First_Name,Last_Name,Email" --per-page 10',"List contacts"],["$0 crm get -m Contacts --id 12345","Get a contact by ID"],['$0 crm search -m Leads --word "Acme"',"Search leads by keyword"],[`$0 crm insert -m Contacts --data '{"First_Name":"Jane","Last_Name":"Doe"}'`,"Insert a contact"]]),handler:F};var ll={command:"list",describe:"List tickets",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status"}).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},hl={command:"get <ticketId>",describe:"Get a ticket by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let o=await x(e).getTicketById({ticketId:e.ticketId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},ml={command:"search",describe:"Search tickets",builder:e=>E(e).option("subject",{type:"string",describe:"Search by subject"}).option("status",{type:"string",describe:"Filter by status"}).option("email",{type:"string",describe:"Filter by email"}).option("department-id",{type:"string",describe:"Filter by department ID"}).option("channel",{type:"string",describe:"Filter by channel"}).option("priority",{type:"string",describe:"Filter by priority"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,subject:e.subject,status:e.status,email:e.email,departmentId:e.departmentId,channel:e.channel,priority:e.priority},r=await k({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},yl={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>E(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=x(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},gl={command:"metrics <ticketId>",describe:"Get ticket metrics",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketMetrics({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},fl={command:"agent-counts",describe:"Get ticket counts per agent",builder:e=>e.option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}).option("department-id",{type:"string",describe:"Filter by department ID"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});h(r)}catch(t){y(t),process.exit(1)}}},$s={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(ll).command(hl).command(ml).command(yl).command(gl).command(fl).demandCommand(1),handler:F};var Rl={command:"list",describe:"List departments",builder:e=>E(e).option("search",{type:"string",describe:"Search by name"}).option("is-enabled",{type:"boolean",describe:"Filter by enabled status"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await k({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Tl={command:"get <departmentId>",describe:"Get a department by ID",builder:e=>e.positional("departmentId",{type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let o=await x(e).getDepartmentById({departmentId:e.departmentId});h(o)}catch(t){y(t),process.exit(1)}}},Xs={command:"departments",describe:"Desk department operations",builder:e=>e.command(Rl).command(Tl).demandCommand(1),handler:F};var Cl={command:"list",describe:"List contacts",builder:e=>E(e).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},xl={command:"get <contactId>",describe:"Get a contact by ID",builder:e=>e.positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getContactById({contactId:e.contactId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},Ys={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Cl).command(xl).demandCommand(1),handler:F};var Fl={command:"list",describe:"List agents",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status (active, disabled)"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. role,profile,departments)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Zl={command:"get <agentId>",describe:"Get an agent by ID",builder:e=>e.positional("agentId",{type:"string",demandOption:!0,describe:"Agent ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getAgentById({agentId:e.agentId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},Sl={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await x(e).getMyInfo();h(o)}catch(t){y(t),process.exit(1)}}},Qs={command:"agents",describe:"Desk agent operations",builder:e=>e.command(Fl).command(Zl).command(Sl).demandCommand(1),handler:F};var Al={command:"list",describe:"List all tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await k({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},kl={command:"search",describe:"Search tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",describe:"Department ID"}).option("query",{alias:"q",type:"string",demandOption:!0,describe:"Search string"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await k({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},bl={command:"for-ticket <ticketId>",describe:"Get tags on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTags({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},Il={command:"associate <ticketId>",describe:"Add tags to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tags",{type:"string",demandOption:!0,describe:"Comma-separated tag names"}),handler:async e=>{try{let t=x(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});h(r)}catch(t){y(t),process.exit(1)}}},Pl={command:"dissociate <ticketId>",describe:"Remove a tag from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tag-id",{type:"string",demandOption:!0,describe:"Tag ID to remove"}),handler:async e=>{try{await x(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),h({removed:!0})}catch(t){y(t),process.exit(1)}}},ec={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Al).command(kl).command(bl).command(Il).command(Pl).demandCommand(1),handler:F};var El={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await k({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Ol={command:"get <ticketId> <commentId>",describe:"Get a comment by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{let o=await x(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});h(o)}catch(t){y(t),process.exit(1)}}},Dl={command:"create <ticketId>",describe:"Create a comment on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("content",{type:"string",demandOption:!0,describe:"Comment content"}).option("public",{type:"boolean",default:!1,describe:"Make comment public"}).option("content-type",{type:"string",default:"plainText",choices:["plainText","html"],describe:"Content type"}),handler:async e=>{try{let o=await x(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});h(o)}catch(t){y(t),process.exit(1)}}},Ml={command:"delete <ticketId> <commentId>",describe:"Delete a comment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{await x(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),h({deleted:!0})}catch(t){y(t),process.exit(1)}}},tc={command:"comments",describe:"Desk comment operations",builder:e=>e.command(El).command(Ol).command(Dl).command(Ml).demandCommand(1),handler:F};var _l={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},vl={command:"delete <ticketId> <attachmentId>",describe:"Delete an attachment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("attachmentId",{type:"string",demandOption:!0,describe:"Attachment ID"}),handler:async e=>{try{await x(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),h({deleted:!0})}catch(t){y(t),process.exit(1)}}},oc={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(_l).command(vl).demandCommand(1),handler:F};var wl={command:"list <ticketId>",describe:"List followers of a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketFollowers({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},Nl={command:"add <ticketId>",describe:"Add followers to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),h({added:!0})}catch(t){y(t),process.exit(1)}}},Ul={command:"remove <ticketId>",describe:"Remove followers from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),h({removed:!0})}catch(t){y(t),process.exit(1)}}},rc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(wl).command(Nl).command(Ul).demandCommand(1),handler:F};var Ll={command:"timer <ticketId>",describe:"Get current timer state for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimer({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},Gl={command:"timer-action <ticketId>",describe:"Start, pause, resume, or stop a timer",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("action",{type:"string",demandOption:!0,choices:["start","pause","resume","stop"],describe:"Timer action"}),handler:async e=>{try{let o=await x(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});h(o)}catch(t){y(t),process.exit(1)}}},Kl={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Vl={command:"summation <ticketId>",describe:"Get time entry summation for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimeEntrySummation({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},nc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(Ll).command(Gl).command(Kl).command(Vl).demandCommand(1),handler:F};var zl={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Hl={command:"get <ticketId> <threadId>",describe:"Get a thread by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("threadId",{type:"string",demandOption:!0,describe:"Thread ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},ic={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(zl).command(Hl).demandCommand(1),handler:F};var jl={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},ac={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(jl).demandCommand(1),handler:F};var sc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command($s).command(Xs).command(Ys).command(Qs).command(ec).command(tc).command(oc).command(rc).command(nc).command(ic).command(ac).demandCommand(1,"Please specify a desk subcommand.").example([["$0 desk tickets list --limit 10","List first 10 tickets"],["$0 desk tickets get 12345","Get a ticket by ID"],["$0 desk agents my-info","Get current agent info"],['$0 desk comments create 12345 --content "Looking into this"',"Add a comment"]]),handler:F};var cc={command:"request <product> <method> <path>",describe:"Make a raw API request through the authenticated context",builder:e=>e.positional("product",{type:"string",demandOption:!0,choices:["recruit","crm","desk"],describe:"Zoho product"}).positional("method",{type:"string",demandOption:!0,choices:["GET","POST","PUT","PATCH","DELETE"],describe:"HTTP method"}).positional("path",{type:"string",demandOption:!0,describe:"API path (relative to product base URL)"}).option("body",{type:"string",describe:"JSON request body"}).option("query",{type:"string",describe:"JSON query parameters"}).example([["$0 request recruit GET /v2/Candidates","List candidates via raw API"],[`$0 request desk GET /tickets --query '{"limit":5}'`,"List 5 desk tickets via raw API"],[`$0 request crm POST /v8/Contacts --body '{"data":[{"Last_Name":"Test"}]}'`,"Create a CRM contact via raw API"]]),handler:async e=>{try{let t=e.product,o=e.method,r=e.path,n;switch(t){case"recruit":n=j(e).recruitContext;break;case"crm":n=W(e).crmContext;break;case"desk":n=x(e).deskContext;break;default:throw new Error(`Unknown product: ${t}`)}let i=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),p=i.includes("?")?"&":"?";i=`${i}${p}${u.toString()}`}let a={method:o};e.body&&(a.body=e.body,a.headers={"Content-Type":"application/json"});let s=await n.fetchJson(i,a);h(s)}catch(t){y(t),process.exit(1)}}};var ql=wn({cliName:"zoho-cli",loadOutputConfig:async()=>(await z())?.output,mergeOutputConfig:e=>H({output:e}),clearOutputConfig:Un}),Jl=[qs,Js,sc,cc],uc=[Hs,ql,js];function $l(e){return e.command.split(" ")[0]}var pc=new Set(uc.map($l)),Xl=vn({cliName:"zoho-cli",skipCommands:pc,loadOutputConfig:async()=>(await z())?.output,saveCommandOutputConfig:async(e,t)=>{await H({output:{commands:{[e]:t}}})}});async function Yl(){try{await Wl(Bl(process.argv)).scriptName("zoho-cli").usage("$0 <command> [options]").option("verbose",{alias:"v",type:"boolean",default:!1,global:!0,describe:"Verbose output"}).option("dump-dir",{type:"string",global:!0,describe:"Directory to save full API responses as JSON files (overrides config)"}).option("pick",{type:"string",global:!0,describe:"Comma-separated top-level fields to include in output (overrides config)"}).option("set-dump-dir",{type:"string",global:!0,describe:"Save dump directory to config for this command and apply now"}).option("set-pick",{type:"string",global:!0,describe:"Save pick fields to config for this command and apply now"}).option("pick-all",{type:"boolean",global:!0,describe:"Ignore any configured pick filters and return full response data"}).middleware([Bs(pc),Xl],!0).command(uc).command(Jl).demandCommand(1,"Please specify a command. Use --help for available commands.").strict().fail(!1).help().alias("help","h").version(!1).wrap(Math.min(120,process.stdout.columns||80)).parse()}catch(e){y(e),process.exit(1)}}Yl();
|
|
8
|
+
`:void 0;u({mainContent:A,pickContent:w,append:Y})})}function l(m){let R=o==="concat"&&!(s===0);t==="raw"?p(m,R):t==="page_by_line"?d(m,R):g(m,R),s+=1}return{mainPath:i,pickPath:a,writePage:l,close:()=>{}}}async function fp(e){let{initialInput:t,requestedPages:o,fetchPage:r,adapter:n,stream:i,shouldCollectPages:a,shouldCollectRecords:s}=e,c={pagesFetched:0,totalRecords:0,hasMorePagesAvailable:!1,lastResult:void 0,lastInput:t,collectedPages:[],collectedRecords:[]},u=t;for(let p=0;p<o;p++){let d=await r(u);if(c.pagesFetched+=1,c.totalRecords+=n.countOf(d),c.lastResult=d,c.lastInput=u,i.writePage(d),a)c.collectedPages.push(d);else if(s)for(let l of d.data??[])c.collectedRecords.push(l);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,d);let g=n.nextInput(u,d);if(!g)break;u=g}return c}function Rp(e){let{multiplePagesOutput:t,summaryMeta:o,state:r,adapter:n,pickFilter:i}=e;if(t==="meta")console.log(JSON.stringify({ok:!0,meta:o}));else if(t==="pages"){let a=i?r.collectedPages.map(s=>({...s,data:Ze(s.data,i)})):r.collectedPages;console.log(JSON.stringify({ok:!0,data:a,meta:o}))}else{let a=r.lastResult?n.metaOf(r.lastInput,r.lastResult):{},s=i?Ze(r.collectedRecords,i):r.collectedRecords;console.log(JSON.stringify({ok:!0,data:s,meta:{...a,...o}}))}}async function k(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:i,dumpMerge:a}=e,s=Math.max(1,Math.floor(e.multiplePages||1));if(s<=1)return{handled:!1,result:await o(t)};let c=At();c.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let u=Nn({dumpOutput:i,dumpMerge:a}),p;try{p=await fp({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:u,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{u.close()}let d={pagesFetched:p.pagesFetched,totalRecords:p.totalRecords,hasMorePagesAvailable:p.hasMorePagesAvailable,dumpFile:u.mainPath??null};return u.pickPath&&(d.dumpFilePick=u.pickPath),Rp({multiplePagesOutput:n,summaryMeta:d,state:p,adapter:r,pickFilter:c.pick}),{handled:!0}}import Wl from"yargs";import{hideBin as Bl}from"yargs/helpers";import{writeFile as Tp,mkdirSync as Cp}from"node:fs";import{join as bo}from"node:path";import{homedir as xp}from"node:os";var wt=["recruit","crm","desk"];function Io(){return bo(xp(),".zoho-cli")}function lt(){return bo(Io(),"config.json")}function ht(){return bo(Io(),".tokens.json")}function be(e,t){if(t){let o=process.env[`ZOHO_${t}_${e}`];if(o)return o}return process.env[`ZOHO_${e}`]}async function z(){let e=lt(),t=await me(e),o=be("ACCOUNTS_CLIENT_ID"),r=be("ACCOUNTS_CLIENT_SECRET"),n=be("ACCOUNTS_REFRESH_TOKEN");if(!t&&!(o&&r&&n))return;let a={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:be("ACCOUNTS_URL")??t?.shared?.region,apiMode:be("API_URL")??t?.shared?.apiMode};function s(u){let p=u.toUpperCase(),d=be("API_URL",p),g=u==="desk"?be("DESK_ORG_ID"):void 0,l=t?.[u],m=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],f=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],R=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`];if(!(!l&&!(m||f||R)&&!g))return{clientId:m??l?.clientId,clientSecret:f??l?.clientSecret,refreshToken:R??l?.refreshToken,apiUrl:d??l?.apiUrl,orgId:g??l?.orgId}}return{shared:a,recruit:s("recruit")??t?.recruit,crm:s("crm")??t?.crm,desk:s("desk")??t?.desk,output:t?.output}}function mt(e,t){let o=e[t],r=e.shared,n=o?.clientId??r.clientId,i=o?.clientSecret??r.clientSecret,a=o?.refreshToken??r.refreshToken;if(!(!n||!i||!a))return{clientId:n,clientSecret:i,refreshToken:a,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId}}async function Fp(e){let t=lt();return Cp(Io(),{recursive:!0}),new Promise((o,r)=>{Tp(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function H(e){let t=await z(),o={shared:{...t?.shared,...e.shared},recruit:e.recruit===void 0?t?.recruit:{...t?.recruit,...e.recruit},crm:e.crm===void 0?t?.crm:{...t?.crm,...e.crm},desk:e.desk===void 0?t?.desk:{...t?.desk,...e.desk},output:e.output===void 0?t?.output:Ao(t?.output,e.output)};return await Fp(o),o}async function Un(){await H({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Ln(){let e=lt(),t=ht();await ut(e),await ut(t)}function J(e){return wt.filter(t=>{let o=mt(e,t);return!(!o||t==="desk"&&!o.orgId)})}import{Inject as Os,Injectable as fd}from"@nestjs/common";function ze(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function v(e,t){return Ge({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:Rn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function Nt(e){switch(e){case"sandbox":return"https://recruitsandbox.zoho.com/recruit";case"production":return"https://recruit.zoho.com/recruit";default:return e}}var He="Candidates",Gn="Job_Openings",Ut="Notes",Kn="Emails",yt="Attachments";function Lt(e){let t;if(e!=null)switch(typeof e){case"string":t=e;break;case"object":{let o;Array.isArray(e)?o={and:[e]}:o=e,t=Gt(o);break}default:break}return t}function Gt(e){function t(a){let s;return typeof a=="object"?Array.isArray(a)?s=a.map(Po):a&&(s=Gt(a)):s=a,s}function o(a,s){return a.length>1?`(${a.join(s)})`:a[0]}function r(a,s){let c=he(a.map(t)).flatMap(C);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,i=n;return e.and&&(i=r([r(e.and,"and"),n],"and")),i}var Vn=Jr({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function Po(e){let t=Vn(e.value);return`(${e.field}:${e.filter}:${t})`}var zn=Lt;import{BaseError as vp}from"make-error";import{BaseError as Sp}from"make-error";var Ap="__internal_data_array_blank_error";function kp(e){return Array.isArray(e?.data)}var qe="success";function $(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var ye=class extends Sp{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},G=class extends ye{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},je=class extends G{constructor(t,o){super({code:Ap,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function oe(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof je&&!o||(r instanceof G?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof ye?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function re(e,t){return(o,r=t,n)=>async(i,a)=>{try{return await o(i,a)}catch(s){if(s instanceof Le){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function ne(e){return(t,o)=>{if(t?.error!=null){let n=new Le(o),i=e(t,n);if(i)throw i}return t}}var bp="INTERNAL_ERROR",Ip="INVALID_TOKEN",V=class extends G{},Hn="FAILURE",Eo=class extends G{},Pp="4834",We=class extends G{},Ep="INVALID_QUERY",Oo=class extends G{get details(){return this.error.details}},Kt="MANDATORY_NOT_FOUND",ge="DUPLICATE_DATA",Vt="INVALID_DATA",Op="TOO_MANY_REQUESTS",jn=429,Dp="X-RATELIMIT-LIMIT",Mp="X-RATELIMIT-REMAINING",_p="X-RATELIMIT-RESET",Wn=100,Bn=Se;function Do(e){let t=e.get(Dp),o=e.get(Mp),r=e.get(_p),n=null;if(t!=null&&o!=null&&r!=null){let i=Number(t),a=Number(o),s=Number(r),c=new Date(s);n={limit:i,remaining:a,reset:s,resetAt:c}}return n}var Be=class extends G{get headerDetails(){return Do(this.responseError.response.headers)}};function ie(e,t){let o;if(kp(e))o=new je(e,t);else{let r=de(e,t);if(r){let n=$(r);switch(n.code){case bp:o=new Eo(n,e,t);break;case Ip:o=new V(n,e,t);break;case Pp:o=new We(n,e,t);break;case Ep:o=new Oo(n,e,t);break;case Op:o=new Be(n,e,t);break;default:o=new G(n,e,t);break}}}return o}function de(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var qn="ALREADY_ASSOCIATED",Mo=class extends vp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},Je=class extends ye{},_o=class extends Je{},vo=class extends Je{},zt=class extends Je{get invalidFieldDetails(){return this.error.details}},wo=class extends zt{};function Jn(e){let t;switch(e.code){case Vt:{let o=new zt(e);o.invalidFieldDetails.id?t=new wo(e):t=o;break}case Kt:t=new _o(e);break;case ge:t=new vo(e);break;default:t=new Je(e);break}return t}function $n(e,t){return o=>{if(!o?.data?.length)throw new Mo(e,t);return o}}var wp=oe("ZohoRecruit");async function Np(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Xn(t,e)),o}function Xn(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var Yn=ne(Xn),Qn=re(Np,wp);import{BaseError as Up}from"make-error";function Uo(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,M(o,{data:C(r)})).then(i=>{let a=Array.isArray(r),s=ae(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Jn(p[0].result);c=u[0].result.details}return c}))}function ei(e){return Uo(e,"","POST")}function ti(e){return Uo(e,"/upsert","POST")}function oi(e){return Uo(e,"","PUT")}function ri(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,M("DELETE")).then(Lp)}function ni(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,M("GET")).then($n(t.module)).then(o=>o.data[0])}function ii(e){return(t=>e.fetchJson(`/v2/${t.module}?${hi(t).toString()}`,M("GET")))}function Lo(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=zn(o.criteria);r.criteria=n}if(!r.word&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, criteria, email, or phone must be provided");return hi(r)}return(o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,M("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function ai(e){return v(Lo(e))}function $e(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${Vo(n,n.filter).toString()}`,M("GET")).then(i=>i??(r!==!1?ze():i))}}function Go(e){return $e(e)({targetModule:Kn})}function si(e){return v(Go(e))}function Ko(e){return $e(e)({targetModule:yt})}function ci(e){return v(Ko(e))}var dR=20*1024*1024;function ui(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:i}=t,a={attachments_category_id:P(o),attachments_category:P(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${yt}?${T(a).toString()}`,c;if(n!=null){let u=new FormData;u.append("file",n),c=e.fetch(s,{method:"POST",headers:{"Content-Type":""},body:u})}else if(i){let u=`${s}&${T({attachment_url:i}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function pi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function di(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"DELETE"})}var No=class extends Up{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function li(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v2/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?Nt(t.apiUrl):""}${a}`;return e.fetchJson(c,M("POST")).then(u=>{if(u.code!=="success")throw new No(u);return u.details})}}function hi(...e){return T(e,{omitKeys:"module"})}function Vo(...e){return T(e,{omitKeys:["id","module"]})}function M(e,t){return{method:e,body:t??void 0}}function Lp(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===qe?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function ae(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===qe?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function mi(e){return t=>e.fetchJson(`/v2/${He}/actions/associate`,M("PUT",{data:C(t)})).then(o=>{let r=o.data.map(()=>t),n=ae(r,o.data),{included:i,excluded:a}=we(n.errorItems,s=>s.result.code===Hn&&s.result.details.error[0].code===qn);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function yi(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${Vo(t).toString()}`,M("GET")).then(o=>o??ze())}function zo(e){let t=yi(e);return o=>t({...o,module:He})}function gi(e){return v(zo(e))}function Ho(e,t=Gn){let o=yi(e);return r=>o({...r,module:t})}function fi(e){return v(Ho(e))}function jo(e){return t=>e.fetchJson(`/v2/${Ut}`,M("POST",{data:t.data})).then(o=>ae(C(t.data),o.data))}function Ri(e){return t=>e.fetchJson(`/v2/${Ut}?${T({ids:t.ids})}`,M("DELETE")).then(o=>ae(C(t.ids),o.data))}function Wo(e){return $e(e)({targetModule:Ut})}function Ti(e){return v(Wo(e))}function Ci(e){let t=jo(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function Zi(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module})}`,M("POST",{tags:C(t.tags)})).then(o=>{let r=ae(C(t.tags),o.tags),{included:n,excluded:i}=we(r.errorItems,a=>a.result.code===ge);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Si(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,M("GET")).then(o=>({...o,data:o.tags}))}var xi=100;function Ai(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>xi)throw new Error(`Cannot add tags to more than ${xi} records at once.`);return e.fetchJson(`/v2/${He}/actions/add_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return ae(r,o.data)})}}var Fi=100;function ki(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Fi)throw new Error(`Cannot remove tags from more than ${Fi} records at once.`);return e.fetchJson(`/v2/${He}/actions/remove_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return ae(r,o.data)})}}var Gp="invalid_code",Kp="invalid_client",Bo=class extends q{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},Xe=class extends q{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},Vp=oe("ZohoAccounts");async function zp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=bi(t,e)),o}function bi(e,t){let o,r=e.error;if(r){let n=$(r);switch(n.code){case Gp:case Kp:o=new Bo(n.code);break;default:o=ie(e,t);break}}return o}var Ii=ne(bi),Pi=re(zp,Vp);function fe(e){return async()=>{let t=await e();if(!t.accessToken)throw new Xe;return t.accessToken}}var Hp=e=>{let t="limit"in e?e.limit:void 0,o="resetAt"in e?e.resetAt:void 0,r=t==null?"":" The limit is "+String(t)+" requests per reset period.",n=o==null?"":" Will be reset at "+String(o)+".";console.warn("zohoRateLimitedFetchHandler(): Too many requests made."+r+n)};function qo(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests===!1?void 0:e.onTooManyRequests??Hp,r=e.maxRateLimit??Wn,n=e.resetPeriod??Bn;function i(c,u){return{limit:c,startLimitAt:Math.ceil(c/10),cooldownRate:1.2*(c/(n/L)),exponentRate:1.08,maxWaitTime:L*10,resetPeriod:n,resetAt:u}}let a=i(r),s=hn(a);return An({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,g=!1;if(p){let{remaining:l,limit:m,resetAt:f}=p;if(m!=null&&m!==r){let R=i(m,f??void 0);s.setConfig(R,!1)}if(s.setRemainingLimit(l),f&&s.setNextResetAt(f),g=!0,c.status===jn){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(g),d}})}function Re(e){return qo({...e,readRateLimitDetails:jp})}function jp(e){let t=Do(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function Ei(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Re(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=Nt(a.apiUrl),c=i({apiUrl:s}),u=Qn(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:Yn,handleFetchJsonParseErrorFunction:Q});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Ht(e){switch(e){case"sandbox":return"https://crmsandbox.zoho.com/crm";case"production":return"https://www.zohoapis.com/crm";default:return e}}var jt="Notes",Oi="Emails",gt="Attachments";var Di=Lt;import{BaseError as Wp}from"make-error";var Jo=class extends Wp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},Ye=class extends ye{},$o=class extends Ye{},Xo=class extends Ye{},Wt=class extends Ye{get invalidFieldDetails(){return this.error.details}},Yo=class extends Wt{};function Mi(e){let t;switch(e.code){case Vt:{let o=new Wt(e);o.invalidFieldDetails.api_name==="id"?t=new Yo(e):t=o;break}case Kt:t=new $o(e);break;case ge:t=new Xo(e);break;default:t=new Ye(e);break}return t}function _i(e,t){return o=>{if(!o?.data?.length)throw new Jo(e,t);return o}}var Bp=oe("ZohoCrm",{logDataArrayErrors:!1});async function qp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=vi(t,e)),o}function vi(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var wi=ne(vi),Ni=re(qp,Bp);import{BaseError as Jp}from"make-error";function er(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,N(o,{data:C(r)})).catch(Yi).then(i=>{let a=Array.isArray(r),s=Te(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Mi(p[0].result);c=u[0].result.details}return c}))}function Ui(e){return er(e,"","POST")}function Li(e){return er(e,"/upsert","POST")}function Gi(e){return er(e,"","PUT")}function Ki(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,N("DELETE")).catch(Yi).then(Xp)}function Vi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,N("GET")).then(_i(t.module)).then(o=>o.data[0])}function zi(e){return(t=>e.fetchJson(`/v8/${t.module}?${Xi(t).toString()}`,N("GET")))}function tr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Di(o.criteria);r.criteria=n}if(!r.word&&!o.cvid&&!o.criteria&&!o.email&&!o.phone)throw new Error("At least one of word, cvid, criteria, email, or phone must be provided");return Xi(r)}return(o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,N("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function Hi(e){return v(tr(e))}function Qe(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${$p(n,n.filter).toString()}`,N("GET")).then(i=>i??(r!==!1?ze():i))}}function or(e){let t=Qe(e)({targetModule:Oi});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function ji(e){return v(or(e))}function rr(e){return Qe(e)({targetModule:gt})}function Wi(e){return v(rr(e))}var ST=20*1024*1024;function Bi(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,i={attachments_category_id:P(o),attachments_category:P(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let a=`/v8/${t.module}/${t.id}/${gt}?${T(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function qi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function Ji(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"DELETE"})}var Qo=class extends Jp{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function $i(e){return t=>{let r=T(t.params).toString(),n=!!t.apiKey,i=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),a=`/v8/functions/${t.functionName}/actions/execute?${i}`,c=`${n&&t.apiUrl!=null?Ht(t.apiUrl):""}${a}`;return e.fetchJson(c,N("POST")).then(u=>{if(u.code!=="success")throw new Qo(u);return u.details})}}function Xi(...e){return T(e,{omitKeys:"module"})}function $p(...e){return T(e,{omitKeys:["id","module"]})}function N(e,t){return{method:e,body:t??void 0}}function Yi(e){let t;if(e instanceof je)t={data:e.errorDataArray};else throw e;return t}function Xp(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===qe?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function Te(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===qe?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function nr(e){return t=>e.fetchJson(`/v2/${jt}`,N("POST",{data:t.data})).then(o=>Te(C(t.data),o.data))}function Qi(e){return t=>e.fetchJson(`/v2/${jt}?${T({ids:t.ids})}`,N("DELETE")).then(o=>Te(C(t.ids),o.data))}function ir(e){return Qe(e)({targetModule:jt})}function ea(e){return v(ir(e))}function ta(e){let t=nr(e);return o=>{let{module:r,id:n,notes:i}=o,a={data:C(i).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(a)}}function ra(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module})}`,N("POST",{tags:C(t.tags)})).catch(o=>{let r;if(o instanceof G){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Te(C(t.tags),o.tags),{included:n,excluded:i}=we(r.errorItems,a=>a.result.code===ge);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function na(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,N("DELETE")).then(o=>o.tags)}function ia(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,N("GET")).then(o=>({...o,data:o.tags}))}var oa=100;function aa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,N("POST",sa(t))).then(o=>{let r=o.data.map(()=>t);return Te(r,o.data)})}function sa(e){if(Array.isArray(e.ids)&&e.ids.length>oa)throw new Error(`Cannot add/remove tags from more than ${oa} records at once.`);let t=[...C(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&C(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:C(e.ids)}}function ca(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,N("POST",sa(t))).then(o=>{let r=o.data.map(()=>t);return Te(r,o.data)})}function ua(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Re(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=Ht(a.apiUrl),c=i({apiUrl:s}),u=Ni(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:wi,handleFetchJsonParseErrorFunction:Q});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function pa(e,t){return Ge({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.page_context?.has_more_rows??!1}},buildInputForNextPage:function(o,r,n){let a=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??a?.row_count??20,c=(a?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function Ie(e,t){return{method:e,body:t??void 0}}function da(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,Ie("GET"))}function ar(e){return t=>{let{search_columns:o,...r}=t,n={page_context:{...r,...o?{search_columns:o}:{}}};return e.fetchJson({url:"/requests",queryParams:{data:JSON.stringify(n)}},Ie("GET"))}}function la(e){let t=ar(e);return pa(t)}function ha(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,Ie("GET"))}function ma(e){return()=>e.fetchJson("/fieldtypes",Ie("GET"))}function ya(e){return({requestId:t,...o})=>{let n=T(o).toString(),i=n?`?${n}`:"",a=`/requests/${t}/pdf${i}`;return e.fetch(a,{method:"GET"})}}function ga(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function fa(e){return({requestData:t,file:o})=>{let r=new FormData;return r.append("data",JSON.stringify({requests:t})),r.append("file",o),e.fetch("/requests",{method:"POST",headers:{"Content-Type":""},body:r}).then(n=>n.json())}}function Ra(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,Ie("PUT",{requests:o}))}function Ta(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,Ie("POST",r))}}function Ca(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,Ie("PUT",{expire_by:o}))}function xa(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let i=T(n),a=i.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...a?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()}:{}})}}function Fa(e){switch(e){case"sandbox":return"https://signsandbox.zoho.com/api/v1";case"production":return"https://sign.zoho.com/api/v1";default:return e}}var Yp=oe("ZohoSign",{logDataArrayErrors:!1});async function Qp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Za(t,e)),o}function Za(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var Sa=ne(Za),Aa=re(Qp,Yp);function ka(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Re(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoConfig missing api url.");let s=Fa(a.apiUrl),c=i({apiUrl:s}),u=Aa(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:Sa,handleFetchJsonParseErrorFunction:Q});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function ba(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var ed=oe("ZohoDesk",{logDataArrayErrors:!1});async function td(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Ia(t,e)),o}function Ia(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ie(e,t);break}return o}var Pa=ne(Ia),Ea=re(td,ed);var od="X-Rate-Limit-Remaining-v3",rd="Retry-After",nd=200;function id(e){let t=e.get(od),o;if(t!=null){let r=Number(t),n,i=e.get(rd);if(i!=null){let a=Number(i);Number.isNaN(a)||(n=new Date(Date.now()+a*L))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function Oa(e){return qo({maxRateLimit:nd,...e,readRateLimitDetails:id})}function Da(e){let{accountsContext:t}=e,o=fe(t.loadAccessToken),r=Oa(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>te.makeFetch({baseUrl:a.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:a.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return a=>{if(!a.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!a.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=ba(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=Ea(c,n,l=>{l instanceof V&&t.loadAccessToken.resetAccessToken()}),p=ee(u,{interceptJsonResponse:Pa,handleFetchJsonParseErrorFunction:Q});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var Ma=25;function X(e,t){return Ge({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=Ma}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??Ma,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Pe(e,t){return{method:e,body:t??void 0}}function et(e,t){return T(e,{omitKeys:t})}function Bt(e){let t;return e&&(t=P(C(e))),t}function sr(e){return t=>{let{include:o,...r}=t,n=et([{...r,include:Bt(o)}]);return e.fetchJson(`/tickets?${n}`,Pe("GET")).then(i=>i??{data:[]})}}function _a(e){return t=>{let{ticketId:o,include:r}=t,i=et([{include:Bt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Pe("GET"))}}function cr(e){return t=>{let o=et([t]);return e.fetchJson(`/tickets/search?${o}`,Pe("GET")).then(r=>r??{data:[]})}}function va(e){return t=>{let{contactId:o,include:r,...n}=t,i=et([{...n,include:Bt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Pe("GET")).then(a=>a??{data:[]})}}function wa(e){return t=>{let{productId:o,include:r,...n}=t,i=et([{...n,include:Bt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Pe("GET")).then(a=>a??{data:[]})}}function Na(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Pe("GET"))}function Ua(e){return t=>{let o=et([{agentIds:P(C(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Pe("GET"))}}function La(e){return X(sr(e))}function Ga(e){return X(cr(e))}function Ka(e){return{method:e}}function Va(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,Ka("GET")).then(r=>r??{data:[]})}}function za(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ka("GET"))}function ur(e){return{method:e}}function Ha(e){let t;return e&&(t=P(C(e))),t}function pr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Ha(o)}]);return e.fetchJson(`/contacts?${n}`,ur("GET")).then(i=>i??{data:[]})}}function ja(e){return t=>{let{contactId:o,include:r}=t,i=T([{include:Ha(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,ur("GET"))}}function Wa(e){return t=>{let o=T([{contactIds:P(C(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,ur("GET")).then(r=>r??[])}}function Ba(e){return X(pr(e))}function ft(e,t){return{method:e,body:t??void 0}}function qa(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("GET")).then(o=>o??[])}function Ja(e){return t=>{let o={tags:C(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("POST",o)).then(r=>r??[])}}function $a(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,ft("DELETE"))}function Xa(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,ft("GET")).then(r=>r??{data:[]})}}function Ya(e){return t=>{let o=T([t]);return e.fetchJson(`/ticketTags?${o}`,ft("GET")).then(r=>r??{data:[]})}}function dr(e,t){return{method:e,body:t??void 0}}function Qa(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("GET")).then(o=>o??[])}function es(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("POST",o))}}function ts(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("DELETE",o))}}function os(e,t){return{method:e,body:t??void 0}}function ad(e){let t;return e&&(t=P(C(e))),t}function rs(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:ad(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,os("GET")).then(a=>a??{data:[]})}}function ns(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,os("DELETE"))}function qt(e,t){return{method:e,body:t??void 0}}function is(e){let t;return e&&(t=P(C(e))),t}function as(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:is(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,qt("GET")).then(a=>a??{data:[]})}}function ss(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=T([{include:is(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,qt("GET"))}}function cs(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,qt("POST",r))}}function us(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,qt("DELETE"))}function Rt(e,t){return{method:e,body:t??void 0}}function ps(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Rt("GET"))}function ds(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Rt("POST",r))}}function ls(e){return t=>{let{ticketId:o,...r}=t,n=T([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Rt("GET")).then(i=>i??{data:[]})}}function hs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Rt("GET"))}function ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Rt("GET"))}function ys(e){return{method:e}}function gs(e){let t;return e&&(t=P(C(e))),t}function lr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:gs(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,ys("GET")).then(a=>a??{data:[]})}}function fs(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=T([{include:gs(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,ys("GET"))}}function Rs(e){return X(lr(e))}function sd(e){return{method:e}}function cd(e){let t;return e&&(t=P(C(e))),t}function hr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:cd(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,sd("GET")).then(a=>a??{data:[]})}}function Ts(e){return X(hr(e))}function Jt(e){return{method:e}}function Cs(e){let t;return e&&(t=P(C(e))),t}function mr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Cs(o)}]);return e.fetchJson(`/agents?${n}`,Jt("GET")).then(i=>i??{data:[]})}}function xs(e){return t=>{let{agentId:o,include:r}=t,i=T([{include:Cs(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,Jt("GET"))}}function Fs(e){return t=>{let o=T([{agentIds:P(C(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,Jt("GET")).then(r=>r?.data??[])}}function Zs(e){return()=>e.fetchJson("/myinfo",Jt("GET"))}function Ss(e){return X(mr(e))}function $t(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:i,refreshToken:a}=t??{},s=i?.clientId??o,c=i?.clientSecret??r,p=T({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:a??n});return e.fetchJson(`/oauth/v2/token?${p}`,ud("POST"))}}function ud(e,t){return{method:e,body:t}}var pd="https://accounts.zoho.com";function As(e){return e==="us"?pd:e}function ks(e){let t=Re(),{logZohoServerErrorFunction:o,fetchFactory:r=n=>te.makeFetch({baseUrl:n.apiUrl,baseRequest:{headers:{"Content-Type":"application/json"}},fetchHandler:t,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return n=>{if(n.refreshToken)if(n.clientId){if(!n.clientSecret)throw new Error("ZohoAccountsConfig missing clientSecret.")}else throw new Error("ZohoAccountsConfig missing clientId.");else throw new Error("ZohoAccountsConfig missing refreshToken.");let i=As(n.apiUrl??"us"),a=r({apiUrl:i}),s=Pi(a,o),c=ee(s,{interceptJsonResponse:Ii,handleFetchJsonParseErrorFunction:Q}),u=async()=>{let l=Date.now(),{access_token:m,api_domain:f,scope:R,expires_in:S}=await $t(d)();return{accessToken:m,apiDomain:f,expiresIn:S,expiresAt:new Date(l+S*L),scope:R}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=dd({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function dd(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Se,i=null,a=async()=>{i=null},s=async()=>{if(!i){let c=await o?.loadCachedToken();c&&(i=c)}if(i!=null&&Date.now()+n>=i.expiresAt.getTime()&&(i=null),!i){try{i=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new Xe("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function Ce(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var xe=class{zohoAccounts;factoryConfig;static assertValidConfig(t){let{zohoAccounts:o}=t;if(o)if(o.serviceAccessTokenKey)if(o.refreshToken)if(o.apiUrl){if(!o.clientId)throw new Error("ZohoAccountsServiceConfig.zohoAccounts.clientId is required")}else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.apiUrl is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.refreshToken is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts.serviceAccessTokenKey is required");else throw new Error("ZohoAccountsServiceConfig.zohoAccounts is required")}};import{Injectable as ld}from"@nestjs/common";var tt=class{};tt=Z([ld()],tt);function hd(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!dn(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function md(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function yd(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Is(e,t){let o=[...e],r=typeof t=="function"?t:t!==!1?yd:void 0;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");function n(i){let a=o.map(u=>u.loadZohoAccessTokenCache(i)),s=a.map(hd),c=qr(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>md(d,u)));if(r!=null){let d=he(p.map(g=>g.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function Ps(e,t){let o={};if(e!=null)for(let i of Object.keys(e)){let a=e[i];a!=null&&(o[i]=a)}let r=Wr(o);function n(i){return{loadCachedToken:async()=>{let a=await r.get(i);return t&&console.log("retrieving access token from memory: ",{service:i,hit:a!=null,expiresAt:a?.expiresAt}),a},updateCachedToken:async a=>{await r.set(i,a),t&&console.log("updating access token in memory: ",{service:i,expiresAt:a?.expiresAt})},clearCachedToken:async()=>{await r.remove(i),t&&console.log("clearing access token in memory: ",{service:i})}}}return{loadZohoAccessTokenCache:n}}var gd=".tmp/zoho-access-tokens.json";function bs(e){if(e==null||typeof e!="object")return;let t=e,o=t.expiresAt,r=o!=null&&!(o instanceof Date)?new Date(o):o;return{...t,expiresAt:r}}function Es(e=gd,t=!0){let o=Mn({filePath:e,reviver:bs}),r=t?Br(o):o;function n(c){return{loadCachedToken:()=>r.get(c),updateCachedToken:async u=>{try{await r.set(c,u)}catch(p){console.error("Failed updating access token in file: ",p)}},clearCachedToken:async()=>{try{await r.remove(c)}catch(u){console.error("Failed clearing access token in file: ",u)}}}}async function i(){let c=await me(e);if(c==null)return;let u={};for(let p of Object.keys(c))u[p]=bs(c[p]);return u}async function a(c){await r.clear();for(let[u,p]of Object.entries(c))p!=null&&await r.set(u,p)}async function s(){await r.clear()}return{loadZohoAccessTokenCache:n,readTokenFile:i,writeTokenFile:a,deleteTokenFile:s}}var _=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=ks(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return $t(this.accountsContext)}};_=Z([fd(),b(0,Os(xe)),b(1,Os(tt))],_);import{Inject as Ds,Injectable as Rd}from"@nestjs/common";var Tt=class{zohoCrm;factoryConfig;static assertValidConfig(t){Ce(t.zohoCrm)}};var Ee=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=ua({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Ui(this.crmContext)}get upsertRecord(){return Li(this.crmContext)}get updateRecord(){return Gi(this.crmContext)}get deleteRecord(){return Ki(this.crmContext)}get getRecordById(){return Vi(this.crmContext)}get getRecords(){return zi(this.crmContext)}get searchRecords(){return tr(this.crmContext)}get searchRecordsPageFactory(){return Hi(this.crmContext)}get getRelatedRecordsFunctionFactory(){return Qe(this.crmContext)}get getEmailsForRecord(){return or(this.crmContext)}get getEmailsForRecordPageFactory(){return ji(this.crmContext)}get getAttachmentsForRecord(){return rr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Wi(this.crmContext)}get uploadAttachmentForRecord(){return Bi(this.crmContext)}get downloadAttachmentForRecord(){return qi(this.crmContext)}get deleteAttachmentFromRecord(){return Ji(this.crmContext)}get createNotes(){return nr(this.crmContext)}get deleteNotes(){return Qi(this.crmContext)}get createNotesForRecord(){return ta(this.crmContext)}get getNotesForRecord(){return ir(this.crmContext)}get getNotesForRecordPageFactory(){return ea(this.crmContext)}get executeRestApiFunction(){return $i(this.crmContext)}get createTagsForModule(){return ra(this.crmContext)}get deleteTag(){return na(this.crmContext)}get getTagsForModule(){return ia(this.crmContext)}get addTagsToRecords(){return aa(this.crmContext)}get removeTagsFromRecords(){return ca(this.crmContext)}};Ee=Z([Rd(),b(0,Ds(Tt)),b(1,Ds(_))],Ee);import{ConfigModule as BF,ConfigService as qF}from"@nestjs/config";import{Inject as Ms,Injectable as Td}from"@nestjs/common";var Ct=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Ce(t.zohoRecruit)}};var Oe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=Ei({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return ei(this.recruitContext)}get upsertRecord(){return ti(this.recruitContext)}get updateRecord(){return oi(this.recruitContext)}get deleteRecord(){return ri(this.recruitContext)}get getRecordById(){return ni(this.recruitContext)}get getRecords(){return ii(this.recruitContext)}get searchRecords(){return Lo(this.recruitContext)}get searchRecordsPageFactory(){return ai(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return $e(this.recruitContext)}get getEmailsForRecord(){return Go(this.recruitContext)}get getEmailsForRecordPageFactory(){return si(this.recruitContext)}get getAttachmentsForRecord(){return Ko(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return ci(this.recruitContext)}get uploadAttachmentForRecord(){return ui(this.recruitContext)}get downloadAttachmentForRecord(){return pi(this.recruitContext)}get deleteAttachmentFromRecord(){return di(this.recruitContext)}get createNotes(){return jo(this.recruitContext)}get deleteNotes(){return Ri(this.recruitContext)}get createNotesForRecord(){return Ci(this.recruitContext)}get getNotesForRecord(){return Wo(this.recruitContext)}get getNotesForRecordPageFactory(){return Ti(this.recruitContext)}get executeRestApiFunction(){return li(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return mi(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return zo(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return gi(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Ho(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return fi(this.recruitContext)}get createTagsForModule(){return Zi(this.recruitContext)}get getTagsForModule(){return Si(this.recruitContext)}get addTagsToRecords(){return Ai(this.recruitContext)}get removeTagsFromRecords(){return ki(this.recruitContext)}};Oe=Z([Td(),b(0,Ms(Ct)),b(1,Ms(_))],Oe);import{ConfigModule as gZ,ConfigService as fZ}from"@nestjs/config";import{Inject as _s,Injectable as Cd}from"@nestjs/common";var xt=class{zohoSign;factoryConfig;static assertValidConfig(t){Ce(t.zohoSign)}};var Ft=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=ka({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return da(this.signContext)}get getDocuments(){return ar(this.signContext)}get getDocumentsPageFactory(){return la(this.signContext)}get getDocumentFormData(){return ha(this.signContext)}get retrieveFieldTypes(){return ma(this.signContext)}get downloadPdf(){return ya(this.signContext)}get downloadCompletionCertificate(){return ga(this.signContext)}get createDocument(){return fa(this.signContext)}get updateDocument(){return Ra(this.signContext)}get sendDocumentForSignature(){return Ta(this.signContext)}get extendDocument(){return Ca(this.signContext)}get deleteDocument(){return xa(this.signContext)}};Ft=Z([Cd(),b(0,_s(xt)),b(1,_s(_))],Ft);import{ConfigModule as LZ,ConfigService as GZ}from"@nestjs/config";function vs(e){return{...e,operationType:e.notifications.operation_type}}var ws=mn(e=>e.operationType),Ns=gn({configurerForAccessor:e=>{let t=yn(e,r=>r);return{...e,handleRequestSubmitted:t("RequestSubmitted"),handleRequestViewed:t("RequestViewed"),handleRequestSigningSuccess:t("RequestSigningSuccess"),handleRequestCompleted:t("RequestCompleted"),handleRequestRejected:t("RequestRejected"),handleRequestRecalled:t("RequestRecalled"),handleRequestForwarded:t("RequestForwarded"),handleRequestExpired:t("RequestExpired")}}});var Us="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",De=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as bd,Inject as Id,Post as Pd,Req as Ed}from"@nestjs/common";import{Inject as Sd,Injectable as Ad,Logger as kd}from"@nestjs/common";import{createHmac as xd,timingSafeEqual as Fd}from"node:crypto";var Zd="x-zs-webhook-signature";function Ls(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Zd];if(!n)return{valid:!1};let i=r.toString("utf-8"),a=xd("sha256",t).update(i,"utf-8").digest("base64"),s=!1;try{let u=Buffer.from(n,"base64"),p=Buffer.from(a,"base64");u.length===p.length&&(s=Fd(u,p))}catch{s=!1}let c;if(s)try{let u=JSON.parse(i);c=vs(u)}catch{s=!1}return s&&c?{valid:!0,event:c}:{valid:!1}}}var le=class{logger=new kd("ZohoSignWebhookService");_verifier;handler=ws();configure=Ns(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Ls({secret:o})}async updateForWebhook(t,o){let r=await this._verifier(t,o);r.valid?await this.updateForZohoSignEvent(r.event):this.logger.warn("Received invalid Zoho Sign webhook event.",t)}async updateForZohoSignEvent(t){await this.handler(t)||this.logger.warn("Received unexpected/unhandled Zoho Sign webhook event.",t)}};le=Z([Ad(),b(0,Sd(De))],le);var Me=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};Z([Pd(),b(0,Ed()),b(1,Pn())],Me.prototype,"handleZohoSignWebhook",1),Me=Z([bd("/webhook/zoho/sign"),b(0,Id(le))],Me);import{Module as Od}from"@nestjs/common";import{ConfigModule as Dd,ConfigService as Md}from"@nestjs/config";function _d(e){let t={zohoSignWebhook:{webhookSecret:e.get(Us)}};return De.assertValidConfig(t),t}var Yt=class{};Yt=Z([Od({imports:[Dd],controllers:[Me],providers:[{provide:De,inject:[Md],useFactory:_d},le],exports:[le]})],Yt);import{Inject as Gs,Injectable as vd}from"@nestjs/common";var Zt=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Ce(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var _e=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Da({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return sr(this.deskContext)}get getTicketById(){return _a(this.deskContext)}get searchTickets(){return cr(this.deskContext)}get getTicketsForContact(){return va(this.deskContext)}get getTicketsForProduct(){return wa(this.deskContext)}get getTicketMetrics(){return Na(this.deskContext)}get getAgentsTicketsCount(){return Ua(this.deskContext)}get getTicketsPageFactory(){return La(this.deskContext)}get searchTicketsPageFactory(){return Ga(this.deskContext)}get getDepartments(){return Va(this.deskContext)}get getDepartmentById(){return za(this.deskContext)}get getContacts(){return pr(this.deskContext)}get getContactById(){return ja(this.deskContext)}get getContactsByIds(){return Wa(this.deskContext)}get getContactsPageFactory(){return Ba(this.deskContext)}get getTicketTags(){return qa(this.deskContext)}get associateTicketTags(){return Ja(this.deskContext)}get dissociateTicketTag(){return $a(this.deskContext)}get searchTags(){return Xa(this.deskContext)}get getAllTags(){return Ya(this.deskContext)}get getTicketFollowers(){return Qa(this.deskContext)}get addTicketFollowers(){return es(this.deskContext)}get removeTicketFollowers(){return ts(this.deskContext)}get getTicketAttachments(){return rs(this.deskContext)}get deleteTicketAttachment(){return ns(this.deskContext)}get getTicketComments(){return as(this.deskContext)}get getTicketCommentById(){return ss(this.deskContext)}get createTicketComment(){return cs(this.deskContext)}get deleteTicketComment(){return us(this.deskContext)}get getTicketTimer(){return ps(this.deskContext)}get performTicketTimerAction(){return ds(this.deskContext)}get getTicketTimeEntries(){return ls(this.deskContext)}get getTicketTimeEntryById(){return hs(this.deskContext)}get getTicketTimeEntrySummation(){return ms(this.deskContext)}get getTicketThreads(){return lr(this.deskContext)}get getTicketThreadById(){return fs(this.deskContext)}get getTicketThreadsPageFactory(){return Rs(this.deskContext)}get getTicketActivities(){return hr(this.deskContext)}get getTicketActivitiesPageFactory(){return Ts(this.deskContext)}get getAgents(){return mr(this.deskContext)}get getAgentById(){return xs(this.deskContext)}get getAgentsByIds(){return Fs(this.deskContext)}get getMyInfo(){return Zs(this.deskContext)}get getAgentsPageFactory(){return Ss(this.deskContext)}};_e=Z([vd(),b(0,Gs(Zt)),b(1,Gs(_))],_e);import{ConfigModule as GS,ConfigService as KS}from"@nestjs/config";function wd(e){return`${e.clientId}:${e.refreshToken}`}function ot(e){let t=Is([Ps(),Es(ht())]),o=new Map;function r(p,d){let g=wd(p),l=o.get(g);if(l)return l;let m={zohoAccounts:{serviceAccessTokenKey:d,refreshToken:p.refreshToken,clientId:p.clientId,clientSecret:p.clientSecret,apiUrl:p.region??"us"}},f=new _(m,t);return o.set(g,f),f}let n,i=mt(e,"recruit");if(i){let p=r(i,"recruit"),d={zohoRecruit:{apiUrl:i.apiMode}};n=new Oe(d,p)}let a,s=mt(e,"crm");if(s){let p=r(s,"crm"),d={zohoCrm:{apiUrl:s.apiMode}};a=new Ee(d,p)}let c,u=mt(e,"desk");if(u?.orgId){let p=r(u,"desk"),d={zohoDesk:{apiUrl:u.apiMode,orgId:u.orgId}};c=new _e(d,p)}return{recruitApi:n,crmApi:a,deskApi:c}}ro([...to,/1000\.\w{20,}/g]);function Ks(e){return e instanceof V?{ok:!1,error:ue(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof We?{ok:!1,error:ue(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Be?{ok:!1,error:ue(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof G?{ok:!1,error:ue(e.message),code:"API_ERROR"}:no(e)}xr(e=>{if(e instanceof V||e instanceof We||e instanceof Be||e instanceof G)return Ks(e)});function y(e){console.log(JSON.stringify(Ks(e)))}var Vs={us:"https://accounts.zoho.com",eu:"https://accounts.zoho.eu",in:"https://accounts.zoho.in",au:"https://accounts.zoho.com.au",jp:"https://accounts.zoho.jp"},zs={recruit:["ZohoRecruit.modules.ALL","ZohoRecruit.settings.all","ZohoRecruit.functions.execute.READ","ZohoRecruit.functions.execute.CREATE"],crm:["ZohoCRM.modules.ALL","ZohoCRM.settings.ALL","ZohoCRM.functions.execute.READ","ZohoCRM.functions.execute.CREATE"],desk:["Desk.tickets.ALL","Desk.tasks.ALL","Desk.contacts.ALL","Desk.settings.ALL","Desk.events.ALL","Desk.search.READ","Desk.articles.READ","Desk.basic.READ"],sign:["ZohoSign.documents.ALL","ZohoSign.templates.ALL"]};function Nd(e){if(e){if(e.startsWith("http://")||e.startsWith("https://"))try{let o=new URL(e).searchParams.get("code");if(!o)throw new Error('No "code" parameter found in the provided URL.');return o}catch(t){throw t instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`):t}return e}}var Ud={command:"setup",describe:"Generate OAuth authorization URL, exchange code, or set refresh token directly",builder:e=>e.option("client-id",{type:"string",describe:"OAuth client ID (from https://api-console.zoho.com/)"}).option("client-secret",{type:"string",describe:"OAuth client secret"}).option("redirect-uri",{type:"string",default:"http://localhost/oauth",describe:"Redirect URI (must match API console config)"}).option("region",{type:"string",default:"us",choices:["us","eu","in","au","jp"],describe:"Zoho region"}).option("scopes",{type:"string",default:"recruit,crm,desk",describe:"Comma-separated products for OAuth scopes (recruit,crm,desk,sign)"}).option("code",{type:"string",describe:"Authorization code or the full redirect URL (code is extracted automatically)"}).option("token",{type:"string",describe:"Set a refresh token directly (skips OAuth code exchange)"}).option("product",{type:"string",choices:[...wt],describe:"Store credentials for a specific product instead of shared"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth setup --client-id 1000.ABC --client-secret xyz","Step 1: Get OAuth URL (saves shared credentials)"],["$0 auth setup --code 1000.AUTH.CODE","Step 2: Exchange code for refresh token"],['$0 auth setup --code "http://localhost/oauth?code=1000.AUTH.CODE&location=us"',"Step 2: Paste the full redirect URL"],["$0 auth setup --client-id 1000.ABC --client-secret xyz --token 1000.REFRESH.TOKEN","Set shared refresh token directly"],["$0 auth setup --product crm --client-id 1000.CRM --client-secret xyz --token 1000.CRM.TOKEN","Set CRM-specific credentials"]]),handler:async e=>{try{let t=await z(),o=e.product,r=e.clientId??t?.shared?.clientId,n=e.clientSecret??t?.shared?.clientSecret,i=e.redirectUri,a=e.region??t?.shared?.region??"us",s=e.scopes.split(",").map(d=>d.trim()),c=Nd(e.code),u=e.token,p=Vs[a]??Vs.us;if(!r||!n)throw new Error("--client-id and --client-secret are required. Get them from https://api-console.zoho.com/");if(u){let d={clientId:r,clientSecret:n,refreshToken:u};if(o){let g={...d,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0},l=await H({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:g});h({success:!0,product:o,refreshToken:pe(u),configSaved:!0,configuredProducts:J(l)})}else{let g=await H({shared:{...d,region:a,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0});h({success:!0,refreshToken:pe(u),configSaved:!0,configuredProducts:J(g)})}}else if(c){let d=`${p}/oauth/v2/token`,g=new URLSearchParams({grant_type:"authorization_code",client_id:r,client_secret:n,redirect_uri:i,code:c}),m=await(await fetch(d,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:g.toString()})).json();if(m.error)throw new Error(`Token exchange failed: ${m.error}`);let f=m.refresh_token;if(!f)throw new Error("No refresh_token in response. The authorization code may have expired (valid for 2 minutes). Generate a new one.");let R={clientId:r,clientSecret:n,refreshToken:f},S;o?S=await H({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:{...R,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0}}):S=await H({shared:{...R,region:a,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({step:2,success:!0,product:o??"shared",refreshToken:pe(f),accessToken:m.access_token?pe(m.access_token):null,scope:m.scope,configSaved:!0,configuredProducts:J(S)})}else{let d=s.flatMap(l=>zs[l]??[]);if(d.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(zs).join(", ")}`);let g=`${p}/oauth/v2/auth?scope=${d.join(",")}&client_id=${encodeURIComponent(r)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(i)}`;await H({shared:{clientId:r,clientSecret:n,refreshToken:t?.shared?.refreshToken??"",region:a,apiMode:e.apiMode??t?.shared?.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({step:1,instructions:'Open the authorization URL in a browser. Authorize the application. Copy the "code" parameter from the redirect URL.',authorizationUrl:g,redirectUri:i,scopes:d,credentialsSaved:!0,nextStep:'zoho-cli auth setup --code "PASTE_REDIRECT_URL_OR_AUTH_CODE"'})}}catch(t){y(t),process.exit(1)}}},Ld={command:"set",describe:"Save Zoho API credentials directly",builder:e=>e.option("client-id",{type:"string",demandOption:!0,describe:"OAuth client ID"}).option("client-secret",{type:"string",demandOption:!0,describe:"OAuth client secret"}).option("refresh-token",{type:"string",demandOption:!0,describe:"OAuth refresh token"}).option("product",{type:"string",choices:[...wt],describe:"Store for a specific product instead of shared"}).option("region",{type:"string",default:"us",describe:"Zoho region (us, eu, in, au, jp)"}).option("org-id",{type:"string",describe:"Zoho Desk organization ID"}).option("api-mode",{type:"string",default:"production",choices:["production","sandbox"],describe:"API mode"}).example([["$0 auth set --client-id abc --client-secret xyz --refresh-token 1000.abc.xyz","Set shared credentials"],["$0 auth set --product crm --client-id abc --client-secret xyz --refresh-token 1000.crm.xyz","Set CRM-specific credentials"]]),handler:async e=>{try{let t=e.product,o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken},r;t?r=await H({shared:(await z())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await H({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({saved:!0,product:t??"shared",configuredProducts:J(r)})}catch(t){y(t),process.exit(1)}}},Gd={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){if(r)return{clientId:r.clientId?pe(r.clientId):void 0,clientSecret:r.clientSecret?pe(r.clientSecret):void 0,refreshToken:r.refreshToken?pe(r.refreshToken):void 0}};var e=o;let t=await z();if(!t){h({configured:!1});return}h({configured:!0,shared:{...o(t.shared),region:t.shared?.region??"us",apiMode:t.shared?.apiMode??"production"},recruit:t.recruit?{...o(t.recruit),apiUrl:t.recruit.apiUrl}:null,crm:t.crm?{...o(t.crm),apiUrl:t.crm.apiUrl}:null,desk:t.desk?{...o(t.desk),apiUrl:t.desk.apiUrl,orgId:t.desk.orgId}:null,configuredProducts:J(t)})}catch(t){y(t),process.exit(1)}}},Kd={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await z();if(!e){h({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"});return}let t=J(e);if(t.length===0){h({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});return}let o=ot(e),r={};for(let n of t)try{let i;if(n==="recruit"?i=o.recruitApi:n==="crm"?i=o.crmApi:i=o.deskApi,!i){r[n]={authenticated:!1,error:"Not configured"};continue}let s=await i.zohoAccountsApi.accessToken();r[n]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(i){let a=i instanceof Error?i.message:String(i);r[n]={authenticated:!1,error:a}}h({products:r})}catch(e){y(e),process.exit(1)}}},Vd={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Ln(),h({cleared:!0})}catch(e){y(e),process.exit(1)}}},Hs={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(Ud).command(Ld).command(Gd).command(Kd).command(Vd).demandCommand(1,"Please specify an auth subcommand."),handler:F};import{access as zd,constants as Hd}from"node:fs";import{dirname as jd}from"node:path";var js={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=[],t=await z();t?e.push({name:"config",status:"pass",message:`Config loaded from ${lt()}`}):e.push({name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}),t?.shared?.clientId&&t?.shared?.clientSecret&&t?.shared?.refreshToken?e.push({name:"shared-credentials",status:"pass",message:"Shared credentials present"}):t&&e.push({name:"shared-credentials",status:"warn",message:"Missing shared credentials. Per-product credentials may still work."});let o=jd(ht());if(await Wd(o)?e.push({name:"token-cache",status:"pass",message:`Token cache directory writable: ${o}`}):e.push({name:"token-cache",status:"warn",message:`Token cache directory not writable: ${o}`}),t){let i=J(t);i.length>0?e.push({name:"products",status:"pass",message:`Configured products: ${i.join(", ")}`}):e.push({name:"products",status:"fail",message:"No products have complete credentials"});let a=ot(t);for(let s of i)try{let c;if(s==="recruit"?c=a.recruitApi:s==="crm"?c=a.crmApi:c=a.deskApi,c){let p=await c.zohoAccountsApi.accessToken();e.push({name:`${s}-token`,status:"pass",message:`${s}: Token exchange successful. Scope: ${p.scope}`})}}catch(c){let u=c instanceof Error?c.message:String(c);e.push({name:`${s}-token`,status:"fail",message:`${s}: Token exchange failed: ${u}`})}t.desk?.orgId?e.push({name:"desk-org-id",status:"pass",message:`Desk org ID configured: ${t.desk.orgId}`}):i.includes("desk")||e.push({name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."})}let n=e.every(i=>i.status==="pass");h({checks:e,healthy:n}),n||process.exit(e.some(i=>i.status==="fail")?1:0)}};function Wd(e){return new Promise(t=>{zd(e,Hd.W_OK,o=>{t(!o)})})}var Ws=bn({notInitializedMessage:"CLI context not initialized. This is a bug."});function Bs(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await z();r||(y(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),J(r).length===0&&(y(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),Ws.set(ot(r))}catch(r){y(r),process.exit(4)}}}function fr(e){return Ws.require()}function j(e){let{recruitApi:t}=fr(e);if(!t)throw new Error("Recruit not configured. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z");return t}function W(e){let{crmApi:t}=fr(e);if(!t)throw new Error("CRM not configured. Run: zoho-cli auth setup --product crm --client-id X --client-secret Y --token Z");return t}function x(e){let{deskApi:t}=fr(e);if(!t)throw new Error("Desk not configured. Run: zoho-cli auth setup --product desk --client-id X --client-secret Y --token Z --org-id YOUR_ORG_ID");return t}function se(e){return Fo(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function E(e){return Fo(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function D(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function Fe(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function St(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function Qt(e){return e.option("sort-by",{type:"string",describe:"Field to sort by"}).option("sort-order",{type:"string",choices:["asc","desc"],describe:"Sort direction"})}var Bd={nextInput:(e,t)=>{if(!t.info?.more_records)return;let o=e.page??1;return{...e,page:o+1}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({page:t.info?.page??e.page,per_page:t.info?.per_page??e.per_page,more_records:t.info?.more_records??!1}),hasMorePagesAvailable:(e,t)=>t.info?.more_records??!1},O={nextInput:(e,t)=>{let o=e.limit??25;if(o<=0||(t.data?.length??0)<o)return;let n=e.from??1;return{...e,from:n+o}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({from:e.from,limit:e.limit,count:t.data?.length??0}),hasMorePagesAvailable:(e,t)=>{let o=e.limit??25;return o<=0?!1:(t.data?.length??0)>=o}};async function ce(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:r,adapter:Bd,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;h(i.data,{page:i.info?.page,per_page:i.info?.per_page,more_records:i.info?.more_records})}}var qd={command:"list",describe:"List records from a module",builder:e=>Qt(St(se(D(e)))),handler:async e=>{try{let t=j(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await ce({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){y(t),process.exit(1)}}},Jd={command:"get",describe:"Get a record by ID",builder:e=>Fe(D(e)),handler:async e=>{try{let o=await j(e).getRecordById({module:e.module,id:e.id});h(o)}catch(t){y(t),process.exit(1)}}},$d={command:"search",describe:"Search records in a module",builder:e=>se(D(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=j(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){y(t),process.exit(1)}}},Xd={command:"insert",describe:"Insert a record into a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=j(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},Yd={command:"upsert",describe:"Upsert a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=j(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},Qd={command:"update",describe:"Update a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=j(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},el={command:"delete",describe:"Delete records from a module",builder:e=>D(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=j(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});h(r)}catch(t){y(t),process.exit(1)}}},tl={command:"emails",describe:"Get emails for a record",builder:e=>se(Fe(D(e))),handler:async e=>{try{let t=j(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){y(t),process.exit(1)}}},ol={command:"attachments",describe:"Get attachments for a record",builder:e=>se(Fe(D(e))),handler:async e=>{try{let t=j(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){y(t),process.exit(1)}}},qs={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(qd).command(Jd).command($d).command(Xd).command(Yd).command(Qd).command(el).command(tl).command(ol).demandCommand(1,"Please specify a recruit subcommand.").example([["$0 recruit list -m Candidates --per-page 10","List first 10 candidates"],["$0 recruit get -m Candidates --id 12345","Get a candidate by ID"],['$0 recruit search -m Candidates --word "John"',"Search candidates by keyword"],[`$0 recruit insert -m Candidates --data '{"First_Name":"John","Last_Name":"Doe"}'`,"Insert a candidate"]]),handler:F};var rl={command:"list",describe:"List records from a module",builder:e=>Qt(St(se(D(e)),!0)),handler:async e=>{try{let t=W(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await ce({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){y(t),process.exit(1)}}},nl={command:"get",describe:"Get a record by ID",builder:e=>Fe(D(e)),handler:async e=>{try{let o=await W(e).getRecordById({module:e.module,id:e.id});h(o)}catch(t){y(t),process.exit(1)}}},il={command:"search",describe:"Search records in a module",builder:e=>se(D(e)).option("criteria",{type:"string",describe:"Search criteria string, e.g. (First_Name:equals:John)"}).option("word",{type:"string",describe:"Keyword search"}).option("email",{type:"string",describe:"Search by email"}).option("phone",{type:"string",describe:"Search by phone"}),handler:async e=>{try{let t=W(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){y(t),process.exit(1)}}},al={command:"insert",describe:"Insert a record into a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},sl={command:"upsert",describe:"Upsert a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},cl={command:"update",describe:"Update a record in a module",builder:e=>D(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=W(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});h(r)}catch(t){y(t),process.exit(1)}}},ul={command:"delete",describe:"Delete records from a module",builder:e=>D(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=W(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});h(r)}catch(t){y(t),process.exit(1)}}},pl={command:"emails",describe:"Get emails for a record",builder:e=>se(Fe(D(e))),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){y(t),process.exit(1)}}},dl={command:"attachments",describe:"Get attachments for a record",builder:e=>St(se(Fe(D(e))),!0),handler:async e=>{try{let t=W(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await ce({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){y(t),process.exit(1)}}},Js={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(rl).command(nl).command(il).command(al).command(sl).command(cl).command(ul).command(pl).command(dl).demandCommand(1,"Please specify a CRM subcommand.").example([['$0 crm list -m Contacts --fields "First_Name,Last_Name,Email" --per-page 10',"List contacts"],["$0 crm get -m Contacts --id 12345","Get a contact by ID"],['$0 crm search -m Leads --word "Acme"',"Search leads by keyword"],[`$0 crm insert -m Contacts --data '{"First_Name":"Jane","Last_Name":"Doe"}'`,"Insert a contact"]]),handler:F};var ll={command:"list",describe:"List tickets",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status"}).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},hl={command:"get <ticketId>",describe:"Get a ticket by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. contacts,assignee,departments,team,isRead)"}),handler:async e=>{try{let o=await x(e).getTicketById({ticketId:e.ticketId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},ml={command:"search",describe:"Search tickets",builder:e=>E(e).option("subject",{type:"string",describe:"Search by subject"}).option("status",{type:"string",describe:"Filter by status"}).option("email",{type:"string",describe:"Filter by email"}).option("department-id",{type:"string",describe:"Filter by department ID"}).option("channel",{type:"string",describe:"Filter by channel"}).option("priority",{type:"string",describe:"Filter by priority"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,subject:e.subject,status:e.status,email:e.email,departmentId:e.departmentId,channel:e.channel,priority:e.priority},r=await k({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},yl={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>E(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=x(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},gl={command:"metrics <ticketId>",describe:"Get ticket metrics",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketMetrics({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},fl={command:"agent-counts",describe:"Get ticket counts per agent",builder:e=>e.option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}).option("department-id",{type:"string",describe:"Filter by department ID"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});h(r)}catch(t){y(t),process.exit(1)}}},$s={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(ll).command(hl).command(ml).command(yl).command(gl).command(fl).demandCommand(1),handler:F};var Rl={command:"list",describe:"List departments",builder:e=>E(e).option("search",{type:"string",describe:"Search by name"}).option("is-enabled",{type:"boolean",describe:"Filter by enabled status"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await k({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Tl={command:"get <departmentId>",describe:"Get a department by ID",builder:e=>e.positional("departmentId",{type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let o=await x(e).getDepartmentById({departmentId:e.departmentId});h(o)}catch(t){y(t),process.exit(1)}}},Xs={command:"departments",describe:"Desk department operations",builder:e=>e.command(Rl).command(Tl).demandCommand(1),handler:F};var Cl={command:"list",describe:"List contacts",builder:e=>E(e).option("sort-by",{type:"string",describe:"Field to sort by"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},xl={command:"get <contactId>",describe:"Get a contact by ID",builder:e=>e.positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getContactById({contactId:e.contactId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},Ys={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Cl).command(xl).demandCommand(1),handler:F};var Fl={command:"list",describe:"List agents",builder:e=>E(e).option("department-id",{type:"string",describe:"Filter by department ID"}).option("status",{type:"string",describe:"Filter by status (active, disabled)"}).option("include",{type:"string",describe:"Comma-separated includes (e.g. role,profile,departments)"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Zl={command:"get <agentId>",describe:"Get an agent by ID",builder:e=>e.positional("agentId",{type:"string",demandOption:!0,describe:"Agent ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getAgentById({agentId:e.agentId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},Sl={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await x(e).getMyInfo();h(o)}catch(t){y(t),process.exit(1)}}},Qs={command:"agents",describe:"Desk agent operations",builder:e=>e.command(Fl).command(Zl).command(Sl).demandCommand(1),handler:F};var Al={command:"list",describe:"List all tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await k({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},kl={command:"search",describe:"Search tags",builder:e=>E(e).option("department-id",{alias:"d",type:"string",describe:"Department ID"}).option("query",{alias:"q",type:"string",demandOption:!0,describe:"Search string"}),handler:async e=>{try{let t=x(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await k({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},bl={command:"for-ticket <ticketId>",describe:"Get tags on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTags({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},Il={command:"associate <ticketId>",describe:"Add tags to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tags",{type:"string",demandOption:!0,describe:"Comma-separated tag names"}),handler:async e=>{try{let t=x(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});h(r)}catch(t){y(t),process.exit(1)}}},Pl={command:"dissociate <ticketId>",describe:"Remove a tag from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("tag-id",{type:"string",demandOption:!0,describe:"Tag ID to remove"}),handler:async e=>{try{await x(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),h({removed:!0})}catch(t){y(t),process.exit(1)}}},ec={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Al).command(kl).command(bl).command(Il).command(Pl).demandCommand(1),handler:F};var El={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await k({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Ol={command:"get <ticketId> <commentId>",describe:"Get a comment by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{let o=await x(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});h(o)}catch(t){y(t),process.exit(1)}}},Dl={command:"create <ticketId>",describe:"Create a comment on a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("content",{type:"string",demandOption:!0,describe:"Comment content"}).option("public",{type:"boolean",default:!1,describe:"Make comment public"}).option("content-type",{type:"string",default:"plainText",choices:["plainText","html"],describe:"Content type"}),handler:async e=>{try{let o=await x(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});h(o)}catch(t){y(t),process.exit(1)}}},Ml={command:"delete <ticketId> <commentId>",describe:"Delete a comment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("commentId",{type:"string",demandOption:!0,describe:"Comment ID"}),handler:async e=>{try{await x(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),h({deleted:!0})}catch(t){y(t),process.exit(1)}}},tc={command:"comments",describe:"Desk comment operations",builder:e=>e.command(El).command(Ol).command(Dl).command(Ml).demandCommand(1),handler:F};var _l={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},vl={command:"delete <ticketId> <attachmentId>",describe:"Delete an attachment",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("attachmentId",{type:"string",demandOption:!0,describe:"Attachment ID"}),handler:async e=>{try{await x(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),h({deleted:!0})}catch(t){y(t),process.exit(1)}}},oc={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(_l).command(vl).demandCommand(1),handler:F};var wl={command:"list <ticketId>",describe:"List followers of a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketFollowers({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},Nl={command:"add <ticketId>",describe:"Add followers to a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),h({added:!0})}catch(t){y(t),process.exit(1)}}},Ul={command:"remove <ticketId>",describe:"Remove followers from a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("agent-ids",{type:"string",demandOption:!0,describe:"Comma-separated agent IDs"}),handler:async e=>{try{let t=x(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),h({removed:!0})}catch(t){y(t),process.exit(1)}}},rc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(wl).command(Nl).command(Ul).demandCommand(1),handler:F};var Ll={command:"timer <ticketId>",describe:"Get current timer state for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimer({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},Gl={command:"timer-action <ticketId>",describe:"Start, pause, resume, or stop a timer",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("action",{type:"string",demandOption:!0,choices:["start","pause","resume","stop"],describe:"Timer action"}),handler:async e=>{try{let o=await x(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});h(o)}catch(t){y(t),process.exit(1)}}},Kl={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Vl={command:"summation <ticketId>",describe:"Get time entry summation for a ticket",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let o=await x(e).getTicketTimeEntrySummation({ticketId:e.ticketId});h(o)}catch(t){y(t),process.exit(1)}}},nc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(Ll).command(Gl).command(Kl).command(Vl).demandCommand(1),handler:F};var zl={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await k({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},Hl={command:"get <ticketId> <threadId>",describe:"Get a thread by ID",builder:e=>e.positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).positional("threadId",{type:"string",demandOption:!0,describe:"Thread ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let o=await x(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});h(o)}catch(t){y(t),process.exit(1)}}},ic={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(zl).command(Hl).demandCommand(1),handler:F};var jl={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>E(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=x(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await k({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:O,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;h(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){y(t),process.exit(1)}}},ac={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(jl).demandCommand(1),handler:F};var sc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command($s).command(Xs).command(Ys).command(Qs).command(ec).command(tc).command(oc).command(rc).command(nc).command(ic).command(ac).demandCommand(1,"Please specify a desk subcommand.").example([["$0 desk tickets list --limit 10","List first 10 tickets"],["$0 desk tickets get 12345","Get a ticket by ID"],["$0 desk agents my-info","Get current agent info"],['$0 desk comments create 12345 --content "Looking into this"',"Add a comment"]]),handler:F};var cc={command:"request <product> <method> <path>",describe:"Make a raw API request through the authenticated context",builder:e=>e.positional("product",{type:"string",demandOption:!0,choices:["recruit","crm","desk"],describe:"Zoho product"}).positional("method",{type:"string",demandOption:!0,choices:["GET","POST","PUT","PATCH","DELETE"],describe:"HTTP method"}).positional("path",{type:"string",demandOption:!0,describe:"API path (relative to product base URL)"}).option("body",{type:"string",describe:"JSON request body"}).option("query",{type:"string",describe:"JSON query parameters"}).example([["$0 request recruit GET /v2/Candidates","List candidates via raw API"],[`$0 request desk GET /tickets --query '{"limit":5}'`,"List 5 desk tickets via raw API"],[`$0 request crm POST /v8/Contacts --body '{"data":[{"Last_Name":"Test"}]}'`,"Create a CRM contact via raw API"]]),handler:async e=>{try{let t=e.product,o=e.method,r=e.path,n;switch(t){case"recruit":n=j(e).recruitContext;break;case"crm":n=W(e).crmContext;break;case"desk":n=x(e).deskContext;break;default:throw new Error(`Unknown product: ${t}`)}let i=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),p=i.includes("?")?"&":"?";i=`${i}${p}${u.toString()}`}let a={method:o};e.body&&(a.body=e.body,a.headers={"Content-Type":"application/json"});let s=await n.fetchJson(i,a);h(s)}catch(t){y(t),process.exit(1)}}};var ql=wn({cliName:"zoho-cli",loadOutputConfig:async()=>(await z())?.output,mergeOutputConfig:e=>H({output:e}),clearOutputConfig:Un}),Jl=[qs,Js,sc,cc],uc=[Hs,ql,js];function $l(e){return e.command.split(" ")[0]}var pc=new Set(uc.map($l)),Xl=vn({cliName:"zoho-cli",skipCommands:pc,loadOutputConfig:async()=>(await z())?.output,saveCommandOutputConfig:async(e,t)=>{await H({output:{commands:{[e]:t}}})}});async function Yl(){try{await Wl(Bl(process.argv)).scriptName("zoho-cli").usage("$0 <command> [options]").option("verbose",{alias:"v",type:"boolean",default:!1,global:!0,describe:"Verbose output"}).option("dump-dir",{type:"string",global:!0,describe:"Directory to save full API responses as JSON files (overrides config)"}).option("pick",{type:"string",global:!0,describe:"Comma-separated top-level fields to include in output (overrides config)"}).option("set-dump-dir",{type:"string",global:!0,describe:"Save dump directory to config for this command and apply now"}).option("set-pick",{type:"string",global:!0,describe:"Save pick fields to config for this command and apply now"}).option("pick-all",{type:"boolean",global:!0,describe:"Ignore any configured pick filters and return full response data"}).middleware([Bs(pc),Xl],!0).command(uc).command(Jl).demandCommand(1,"Please specify a command. Use --help for available commands.").strict().fail(!1).help().alias("help","h").version(!1).wrap(Math.min(120,process.stdout.columns||80)).parse()}catch(e){y(e),process.exit(1)}}await Yl();
|
package/cli/package.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/cli",
|
|
3
|
-
"version": "13.11.
|
|
3
|
+
"version": "13.11.11",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"zoho-cli": "index.js"
|
|
7
7
|
},
|
|
8
8
|
"peerDependencies": {
|
|
9
|
-
"@dereekb/dbx-cli": "13.11.
|
|
10
|
-
"@dereekb/nestjs": "13.11.
|
|
11
|
-
"@dereekb/rxjs": "13.11.
|
|
12
|
-
"@dereekb/util": "13.11.
|
|
13
|
-
"@dereekb/zoho": "13.11.
|
|
14
|
-
"@dereekb/zoho/nestjs": "13.11.
|
|
9
|
+
"@dereekb/dbx-cli": "13.11.11",
|
|
10
|
+
"@dereekb/nestjs": "13.11.11",
|
|
11
|
+
"@dereekb/rxjs": "13.11.11",
|
|
12
|
+
"@dereekb/util": "13.11.11",
|
|
13
|
+
"@dereekb/zoho": "13.11.11",
|
|
14
|
+
"@dereekb/zoho/nestjs": "13.11.11",
|
|
15
15
|
"yargs": "^18.0.0"
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
package/index.cjs.js
CHANGED
|
@@ -1263,9 +1263,8 @@ function _ts_generator$a(thisArg, body) {
|
|
|
1263
1263
|
var _x_data;
|
|
1264
1264
|
if (!(x === null || x === void 0 ? void 0 : (_x_data = x.data) === null || _x_data === void 0 ? void 0 : _x_data.length)) {
|
|
1265
1265
|
throw new ZohoRecruitRecordNoContentError(moduleName, recordId);
|
|
1266
|
-
} else {
|
|
1267
|
-
return x;
|
|
1268
1266
|
}
|
|
1267
|
+
return x;
|
|
1269
1268
|
};
|
|
1270
1269
|
}
|
|
1271
1270
|
/**
|
|
@@ -3367,8 +3366,8 @@ function _object_spread_props$i(target, source) {
|
|
|
3367
3366
|
*/ var DEFAULT_ZOHO_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION = function DEFAULT_ZOHO_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION(details) {
|
|
3368
3367
|
var limit = 'limit' in details ? details.limit : undefined;
|
|
3369
3368
|
var resetAt = 'resetAt' in details ? details.resetAt : undefined;
|
|
3370
|
-
var limitMessage = limit
|
|
3371
|
-
var resetMessage = resetAt
|
|
3369
|
+
var limitMessage = limit == null ? '' : ' The limit is ' + String(limit) + ' requests per reset period.';
|
|
3370
|
+
var resetMessage = resetAt == null ? '' : ' Will be reset at ' + String(resetAt) + '.';
|
|
3372
3371
|
console.warn('zohoRateLimitedFetchHandler(): Too many requests made.' + limitMessage + resetMessage);
|
|
3373
3372
|
};
|
|
3374
3373
|
/**
|
|
@@ -3389,7 +3388,7 @@ function _object_spread_props$i(target, source) {
|
|
|
3389
3388
|
*/ function makeZohoRateLimitedFetchHandler(config) {
|
|
3390
3389
|
var _config_onTooManyRequests, _config_maxRateLimit, _config_resetPeriod;
|
|
3391
3390
|
var readRateLimitDetails = config.readRateLimitDetails;
|
|
3392
|
-
var onTooManyRequests = config.onTooManyRequests
|
|
3391
|
+
var onTooManyRequests = config.onTooManyRequests === false ? undefined : (_config_onTooManyRequests = config.onTooManyRequests) !== null && _config_onTooManyRequests !== void 0 ? _config_onTooManyRequests : DEFAULT_ZOHO_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION;
|
|
3393
3392
|
var defaultLimit = (_config_maxRateLimit = config.maxRateLimit) !== null && _config_maxRateLimit !== void 0 ? _config_maxRateLimit : DEFAULT_ZOHO_API_RATE_LIMIT;
|
|
3394
3393
|
var defaultResetPeriod = (_config_resetPeriod = config.resetPeriod) !== null && _config_resetPeriod !== void 0 ? _config_resetPeriod : DEFAULT_ZOHO_API_RATE_LIMIT_RESET_PERIOD;
|
|
3395
3394
|
/**
|
|
@@ -4181,9 +4180,8 @@ function _ts_generator$6(thisArg, body) {
|
|
|
4181
4180
|
var _x_data;
|
|
4182
4181
|
if (!(x === null || x === void 0 ? void 0 : (_x_data = x.data) === null || _x_data === void 0 ? void 0 : _x_data.length)) {
|
|
4183
4182
|
throw new ZohoCrmRecordNoContentError(moduleName, recordId);
|
|
4184
|
-
} else {
|
|
4185
|
-
return x;
|
|
4186
4183
|
}
|
|
4184
|
+
return x;
|
|
4187
4185
|
};
|
|
4188
4186
|
}
|
|
4189
4187
|
/**
|
package/index.esm.js
CHANGED
|
@@ -1261,9 +1261,8 @@ function _ts_generator$a(thisArg, body) {
|
|
|
1261
1261
|
var _x_data;
|
|
1262
1262
|
if (!(x === null || x === void 0 ? void 0 : (_x_data = x.data) === null || _x_data === void 0 ? void 0 : _x_data.length)) {
|
|
1263
1263
|
throw new ZohoRecruitRecordNoContentError(moduleName, recordId);
|
|
1264
|
-
} else {
|
|
1265
|
-
return x;
|
|
1266
1264
|
}
|
|
1265
|
+
return x;
|
|
1267
1266
|
};
|
|
1268
1267
|
}
|
|
1269
1268
|
/**
|
|
@@ -3365,8 +3364,8 @@ function _object_spread_props$i(target, source) {
|
|
|
3365
3364
|
*/ var DEFAULT_ZOHO_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION = function DEFAULT_ZOHO_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION(details) {
|
|
3366
3365
|
var limit = 'limit' in details ? details.limit : undefined;
|
|
3367
3366
|
var resetAt = 'resetAt' in details ? details.resetAt : undefined;
|
|
3368
|
-
var limitMessage = limit
|
|
3369
|
-
var resetMessage = resetAt
|
|
3367
|
+
var limitMessage = limit == null ? '' : ' The limit is ' + String(limit) + ' requests per reset period.';
|
|
3368
|
+
var resetMessage = resetAt == null ? '' : ' Will be reset at ' + String(resetAt) + '.';
|
|
3370
3369
|
console.warn('zohoRateLimitedFetchHandler(): Too many requests made.' + limitMessage + resetMessage);
|
|
3371
3370
|
};
|
|
3372
3371
|
/**
|
|
@@ -3387,7 +3386,7 @@ function _object_spread_props$i(target, source) {
|
|
|
3387
3386
|
*/ function makeZohoRateLimitedFetchHandler(config) {
|
|
3388
3387
|
var _config_onTooManyRequests, _config_maxRateLimit, _config_resetPeriod;
|
|
3389
3388
|
var readRateLimitDetails = config.readRateLimitDetails;
|
|
3390
|
-
var onTooManyRequests = config.onTooManyRequests
|
|
3389
|
+
var onTooManyRequests = config.onTooManyRequests === false ? undefined : (_config_onTooManyRequests = config.onTooManyRequests) !== null && _config_onTooManyRequests !== void 0 ? _config_onTooManyRequests : DEFAULT_ZOHO_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION;
|
|
3391
3390
|
var defaultLimit = (_config_maxRateLimit = config.maxRateLimit) !== null && _config_maxRateLimit !== void 0 ? _config_maxRateLimit : DEFAULT_ZOHO_API_RATE_LIMIT;
|
|
3392
3391
|
var defaultResetPeriod = (_config_resetPeriod = config.resetPeriod) !== null && _config_resetPeriod !== void 0 ? _config_resetPeriod : DEFAULT_ZOHO_API_RATE_LIMIT_RESET_PERIOD;
|
|
3393
3392
|
/**
|
|
@@ -4179,9 +4178,8 @@ function _ts_generator$6(thisArg, body) {
|
|
|
4179
4178
|
var _x_data;
|
|
4180
4179
|
if (!(x === null || x === void 0 ? void 0 : (_x_data = x.data) === null || _x_data === void 0 ? void 0 : _x_data.length)) {
|
|
4181
4180
|
throw new ZohoCrmRecordNoContentError(moduleName, recordId);
|
|
4182
|
-
} else {
|
|
4183
|
-
return x;
|
|
4184
4181
|
}
|
|
4182
|
+
return x;
|
|
4185
4183
|
};
|
|
4186
4184
|
}
|
|
4187
4185
|
/**
|
package/nestjs/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/nestjs",
|
|
3
|
-
"version": "13.11.
|
|
3
|
+
"version": "13.11.11",
|
|
4
4
|
"peerDependencies": {
|
|
5
|
-
"@dereekb/nestjs": "13.11.
|
|
6
|
-
"@dereekb/rxjs": "13.11.
|
|
7
|
-
"@dereekb/util": "13.11.
|
|
8
|
-
"@dereekb/zoho": "13.11.
|
|
5
|
+
"@dereekb/nestjs": "13.11.11",
|
|
6
|
+
"@dereekb/rxjs": "13.11.11",
|
|
7
|
+
"@dereekb/util": "13.11.11",
|
|
8
|
+
"@dereekb/zoho": "13.11.11",
|
|
9
9
|
"@nestjs/common": "^11.1.19",
|
|
10
10
|
"@nestjs/config": "^4.0.4",
|
|
11
11
|
"express": "^5.2.1"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho",
|
|
3
|
-
"version": "13.11.
|
|
3
|
+
"version": "13.11.11",
|
|
4
4
|
"bin": {
|
|
5
5
|
"zoho-cli": "cli/index.js"
|
|
6
6
|
},
|
|
@@ -23,13 +23,13 @@
|
|
|
23
23
|
}
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
|
-
"@dereekb/date": "13.11.
|
|
27
|
-
"@dereekb/dbx-cli": "13.11.
|
|
28
|
-
"@dereekb/firebase": "13.11.
|
|
29
|
-
"@dereekb/model": "13.11.
|
|
30
|
-
"@dereekb/nestjs": "13.11.
|
|
31
|
-
"@dereekb/rxjs": "13.11.
|
|
32
|
-
"@dereekb/util": "13.11.
|
|
26
|
+
"@dereekb/date": "13.11.11",
|
|
27
|
+
"@dereekb/dbx-cli": "13.11.11",
|
|
28
|
+
"@dereekb/firebase": "13.11.11",
|
|
29
|
+
"@dereekb/model": "13.11.11",
|
|
30
|
+
"@dereekb/nestjs": "13.11.11",
|
|
31
|
+
"@dereekb/rxjs": "13.11.11",
|
|
32
|
+
"@dereekb/util": "13.11.11",
|
|
33
33
|
"@nestjs/common": "^11.1.19",
|
|
34
34
|
"@nestjs/config": "^4.0.4",
|
|
35
35
|
"express": "^5.2.1",
|