@dereekb/zoho 13.11.18 → 13.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 yc=Object.defineProperty;var gc=Object.getOwnPropertyDescriptor;var A=(e,t,o,r)=>{for(var n=r>1?void 0:r?gc(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&&yc(t,o,n),n},I=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as fc,mkdirSync as Rc,writeFileSync as Tc}from"node:fs";import{join as Cc}from"node:path";var Cr=1;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],Ne={},xr=[...to],eo,xc=!1,Zc;function oo(e){Ne=e}function At(){return Ne}function Zr(e){xc=e}function Fr(e){Zc=e}function ro(e){xr=e}function Sr(e){eo=e}function pe(e){let t=e;for(let o of xr)t=t.replace(o,"[REDACTED]");return t}function Ar(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function at(e,t){let{dumpDir:o,commandPath:r}=Ne,n;if(o){fc(o)||Rc(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=Ar(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=Cc(o,`${s}.${e}`)}else n=void 0;return n}function Fc(e,t){let o=at("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};Tc(o,JSON.stringify(r,null,2))}function Se(e,t){let o=t.split(",").map(n=>n.trim()),r;return Array.isArray(e)?r=e.map(n=>Tr(n,o)):e!=null&&typeof e=="object"?r=Tr(e,o):r=e,r}function Tr(e,t){let o;if(e==null||typeof e!="object")o=e;else{let r={};for(let n of t)n in e&&(r[n]=e[n]);o=r}return o}function br(e){return Ne.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function h(e,t){Fc(e,t);let r={ok:!0,data:Ne.pick?Se(e,Ne.pick):e,...t?{meta:t}:{}};console.log(br(r))}function kr(e){console.log(br(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){let t=eo?eo(e):void 0,o;return t?o=t:e instanceof it?o={ok:!1,error:pe(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?o={ok:!1,error:pe(e.message),code:"ERROR"}:o={ok:!1,error:pe(String(e)),code:"UNKNOWN_ERROR"},o}function we(e,t=!1){let o;return typeof e=="string"?o=t:e!=null&&typeof e=="object"&&Symbol.iterator in e?o=!0:o=!1,o}function st(e){let t=!0;for(let o of e){t=!1;break}return t}function io(e,t){for(let o of e)t(o)}function J(e,t,o=!1){e!=null&&(we(e,o)?io(e,t):t(e))}function Ir(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 Sc(e){return e!=null?Ac(e):[]}var C=Sc;function Ac(e){return Array.isArray(e)?e:[e]}function Pr(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function ao(e){return Object.keys(e).length===0}function Er(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Or(e){return{...e}}function Dr(e){return e!=null}function bt(e){return we(e,!1)?!st(e):Mr(e)}function so(e){let t;return we(e,!0)?t=!st(e):Mr(e)?t=typeof e=="object"?!ao(e):!0:t=!1,t}function Mr(e){return e!=null&&e!==""}function bc(e){return t=>{let o;return t!=null?o=t.filter((r,n,i)=>e(r,n,i)):o=[],o}}var me=bc(Dr);function _r({base:e,build:t}){let o=e??{};return t(o),o}var kc=(e=>e);function vr(){return kc}function Ue(e,t){let o=Ic(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Ic(e,t){return Er(Pc(e,t))}function Pc(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 Nr(e,t,o){return C(t).forEach(r=>e.set(r,o)),e}function co(e){return Array.from(e.entries())}function wr(e){return Ec(co(e))}function Ec(e){let t=[];return e.forEach(([o,r])=>{J(r,n=>{t.push([o,n])})}),t}function Ur(){let e=new Map,t=(n,i)=>{let a=e.get(n);a==null&&(a=[],e.set(n,a)),J(i,s=>a.push(s))},o=(n,i)=>t(n,Ir(i));return{map:()=>e,entries:()=>co(e),tuples:()=>wr(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,i)=>J(n,a=>t(a,i)),addTuplesToKeys:(n,i)=>J(n,a=>o(a,i)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function Oc(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function Lr(e){let t=Oc(e);return t!=null&&t!=="class"}function Gr(e){return Lr(e)?e:()=>e}function Kr(e,t){return Math.log(t)/Math.log(e)}var Vr=",",Dc=" ";function Mc(e,t=Vr,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;switch(o){case 1:r=[e];break;case 2:{let n=e.indexOf(t);r=n<0?[e]:[e.slice(0,n),e.slice(n+t.length)];break}default:{let n=e.split(t),i=[];if(n.length>1){let a=n.length>o,s=a?o-1:n.length;for(let c=0;c<s;c+=1)i.push(n[c]);a&&i.push(n.slice(s).join(t))}else i.push(n[0]);r=i;break}}return r}function _c(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return Mc(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function Hr(e){let{joiner:t}=e,o=_c(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=Hr({joiner:Vr}),vc=Hr({joiner:Dc,trimByDefault:!0});var P=po.joinStrings,Mh=po.splitStrings,_h=po.splitStringsToSet,vh=vc.joinStrings;var zr=Pr;function Wr(e,{forEach:t,filter:o}){Nc(e,o).forEach((n,i)=>t(n,i))}function Nc(e,t){return lo(t)(e)}function lo(e){let t;if(e!=null){let o=wc(e);t=r=>jr(r).filter((n,i)=>o(n,i))}else t=jr;return t}function jr(e){return Object.entries(e)}function ho(e){return typeof e=="object"?e:{valueFilter:e}}function wc(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])=>bt(a);break;case 5:i=([,a])=>so(a);break;case 6:i=([,a])=>!!a&&bt(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 zr(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 Uc({filter:e,copy:t,dynamic:o=!1}){let r=e!=null?Le({filter:e,copy:!1}):Gc;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=Or(s)),Object.assign(s,c),s}}}function Br(e,t){return Lc(t)(e)}function Lc(e){let t=Uc({filter:e,copy:!1,dynamic:!0});return o=>t(me(o))({})}var qh=Le({copy:!0,filter:{valueFilter:1}}),Jh=Le({copy:!0,filter:{valueFilter:2}}),qr=Le({copy:!0,filter:{valueFilter:4}}),$h=Le({copy:!0,filter:{valueFilter:6}}),Xh=mo({valueFilter:1}),Yh=mo({valueFilter:6}),Qh=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 Le({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 Gc=Le({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 $r(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 Xr(e){let t,o,r=0;function n(){let i;if(t==null){if(o==null){let a=r;o=e.load().then(s=>(r===a&&(t={entries:s},o=void 0),s),s=>{throw r===a&&(o=void 0),s})}i=o}else i=Promise.resolve(t.entries);return i}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 Yr(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 kt(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 Kc=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],am=new Set(Kc);function Qr(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=kt(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 y=n[p],f=n.substring(u,p)+o(y);s.push(f),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function Vc(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 Vc(e)(t,o)}function Hc(e,t){return It(e,t,1)[0]}function zc(e){return t=>{let r=Hc(typeof e=="string"?new Set([e]):e,t),n;return r!=null?n=yo(t,r,!1):n=[t,void 0],n}}function en(e,t){return zc(t)(e)}var Ge="/",jc=".";function Wc(e){let t=e.split(jc,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Ge?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function tn(e){return Wc(e)!=="invalid"}var Bc=/^\/+/,qc=/\/+$/;var Jc=/\/{2,}/g;function on(e){return e.startsWith(Ge)?e.replace(Bc,Ge):`${Ge}${e}`}function rn(e){return e.replaceAll(Jc,Ge)}function nn(e){return e.replace(qc,"")}function $c(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var an=/:(\d+)/;function Xc(e){return an.test(e)}function Yc(e){let t=an.exec(e);return t?Number(t[1]):void 0}function Qc(e){let t=pn(e),o=eu(t),{domain:r,path:n}=o,i=$c(r),a=Xc(e),s=a?Yc(e)??void 0:void 0,[c,u]=en(o.path,"?"),p=i&&(c===""||tn(c+"/")),d=ou(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 sn(e){let t=Qc(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function cn(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=kt(n,i,"&")),n}function eu(e){let t=pn(e);return tu(t)}function tu(e){let t=uo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:on(r??"/")}}var un=/^https:\/\/|http:\/\//;function pn(e){return e.replace(un,"")}function ou(e){return un.test(e)}function S(){}function dn(e){let t;return e==null||uu(e)?t=e:t=ru(e),t}function ru(e){return e==null?e:new Date(e)}var ln=24,nu=60;var iu=60,au=iu*nu,L=1e3,Ae=L*60,go=Ae*60,su=go*ln,Tm=au*ln,cu=7,Cm=su*cu;function uu(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function hn(e){return e.getTime()<Date.now()}function mn(e,t){return e!=null?new Date(e.getTime()+(t??0)):e}function pu(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:dn(n);function c(y){return y??r??new Date}function u(y,l=!1){let f=c(y),g=d(f),R;return g==null?R=l:R=g<=f,R}function p(y){let l=c(y);return d(l)}function d(y){let l=null;return o!=null?l=o.expiresAt??null:t!=null?l=t:a!=null&&(l=mn(s??(i!==!1?y:null),a)),l}return{input:e,hasExpired:u,getExpirationDate:p}}function yn(e,t){let o=!0;return e!=null&&(o=pu(e).hasExpired(t,!0)),o}function gn(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 du(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 y(F){u=F}function l(F,U=!1){let z=Math.max(0,F.startLimitAt??1),b=F.cooldownRate??1,v=F.maxWaitTime??n,V=F.exponentRate??2;i={startLimitAt:z,cooldownRate:b,maxWaitTime:v,exponentRate:V},s=Kr(V,v/L+1),U&&f()}function f(){a=0,c=new Date}function g(F){let U;if(u){let{cooldownRate:z}=i,v=(Date.now()-c.getTime())*z/L,V=Math.max(a-v,0),j=Math.max(0,V-i.startLimitAt);F&&(a=V+F,c=new Date),U=j>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(j,0))-1)*L}else U=0;return U}function R(F){return g(F??0)}function Z(){let F=g(1);return fo(F)}return{waitForRateLimit:Z,getNextWaitTime:R,getConfig:p,setConfig:l,getEnabled:d,setEnabled:y,reset:f}}function fn(e){let o=du({exponentRate:1.5,maxWaitTime:L*8,...e}),r=Ae,n=new Date,i=0,a=0,s=!0;Z(e,!0);function c(){hn(n)&&d()}function u(){return s}function p(b){s=b}function d(){a=i,n=new Date(Date.now()+r)}function y(){return n}function l(){return Math.max(0,n.getTime()-Date.now())}function f(b){n=b}function g(){return c(),a}function R(b){a=b}function Z(b,v=!1){i=b.limit??i,r=b.resetPeriod??r;let V={cooldownRate:b.cooldownRate??Math.max(.1,r/L),exponentRate:b.exponentRate??1.5,maxWaitTime:b.maxWaitTime??L*8};o.setConfig(V,v),v&&d(),n=b.resetAt??n}function F(b){let v=0;if(s){let j=function(){return a-=b,o.getNextWaitTime(b)};var V=j;a>0?v=j():(c(),a>0?v=j():v=l())}return v}function U(b){return F(b??0)}function z(){let b=F(1);return fo(b)}return{getRemainingLimit:g,setRemainingLimit:R,getTimeUntilNextReset:l,getResetAt:y,setNextResetAt:f,setConfig:Z,reset:d,getNextWaitTime:U,waitForRateLimit:z,getEnabled:u,setEnabled:p}}var lu="__CATCH_ALL_HANDLE_RESULT_KEY__";function Rn(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===lu?a(p):Nr(i,u,p)},c=(u,p,d)=>{let y=d.bind(u);s(p,y)};return _r({base:(u=>{let p=e(u),d=(p!=null?i.get(p):void 0)??n,y;return d?y=Promise.resolve(d(u)).then(l=>l??o):y=Promise.resolve(r),y}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=a}})}}function hu(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function mu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function yu(e,t,o){let r=mu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function Tn(e,t){return o=>yu(e,o,t)}function Cn(e){return t=>(o,r)=>{let n=hu(o,t),i=e.configurerForAccessor(n);r(i)}}var gu=-1,xn=0;function fu(e){return e?.page??gu}function Zn(e){return fu(e)+1}import{BaseError as Fn}from"make-error";var $=class extends Fn{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function Sn(e){return(t,o)=>Ru(e(t,o))}var Ke=class extends Fn{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function Ru(e){return e.then(t=>{if(!t.ok)throw new Ke(t);return t})}import{BaseError as Um}from"make-error";function An(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??void 0);if(n){let a=setTimeout(()=>{r?.abort()},n);i=i.finally(()=>{clearTimeout(a)})}return i}}function kn(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>In({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>Cu({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var Tu=(e,t)=>t(e);function Cu(e){let{makeFetch:t=fetch,fetchHandler:o=Tu,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=An(a)),n&&(a=Sn(a));let s=In(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var xu=(e,t)=>new Request(e,t??void 0);function In(e){let{makeRequest:t=xu,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(nn(o)):void 0,u=c?l=>{let f,g=l.toString();if(!s&&sn(g))f=new URL(g);else{let R=c.origin+rn("/"+c.pathname+"/"+l);f=new URL(R,c)}return f}:void 0;async function p(l){let f=gn(l)?await l:l;return bn(f)?f:t(f)}let d=u?async l=>{let f,g,R;if(typeof l=="string"?f=l:bn(l)?a?(f=l.url,g=l):R=l:R=await t(l),!R){let Z=u(f);R=await t(Z.href,g)}return R}:p,y;if(r!=null||n!=null){let l=Gr(r);async function f(){let R=await l();return n?{...R,timeout:n}:R}async function g(R,Z){let F=await f(),U=Zu(F,await Z),z=U.timeout===void 0?R.timeout:U.timeout;return{...U,timeout:z}}i?y=(R,Z)=>i(R,g(R,Z)):y=(R,Z)=>g(R,Z)}else i?y=i:y=(l,f)=>f;return async(l,f)=>{try{let g=await d(l);f=await y(g,f??void 0);let R=await t(g,f);return R.timeout=n,R}catch(g){throw g instanceof $?g:new $(g)}}}function Zu(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=Ur();return me(e).forEach(o=>{let r=Su(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 Su(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 bn(e){return!!e.url}import{safeParse as Au}from"fast-content-type-parse";function Pt(e){let t=e.headers.get("content-type"),o=Au(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Pn(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 ${constructor(o){super("There was no next page for this.");this.page=o}},To=class extends ${constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},bu=100;function Ve(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??bu;function y(f,g=void 0){return async()=>{let R=await t(f),{cursor:Z,nextPageCursor:F,hasNext:U}=await o(R),z=Z??g?.cursor,b=U!==!1,v=g?g.page+1:xn,V=v>=d,j={input:f,result:R,page:v,previous:g,hasNext:b,isAtMaxPage:V,cursor:z,nextPageCursor:F,fetchNext:ct(async()=>{if(V)throw new To(j,d);let Rr=b?await r(j,f,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Rr)throw new Ro(j);return y({...f,...Rr},j)()})};return j}}return{input:a,fetchNext:ct(()=>y(a)())}}}function T(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?Br(e):e,i=r??!0?qr(n??{}):n,a=new URLSearchParams(i);return o!=null&&J(o,s=>a.delete(s),!1),a}function Co(e){let t;if(typeof e=="string")t=e;else if(ku(e))t=e.href;else{let o=Co(e.url);if(e.queryParams){let r=Eu(e.queryParams);st(r)?t=o:t=cn(o+`?${r.toString()}`)}else t=o}return t}function ku(e){return typeof e=="object"&&e instanceof URL}function Iu(e){return typeof e=="object"&&e instanceof URLSearchParams}function Pu(e){let t=[];return io(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let i=String(r);J(n,a=>{a!=null&&t.push([i,String(a)])})}}),t}function Eu(e){let t;return Iu(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):we(e)?t=new URLSearchParams(Pu(e)):t=Ou(e),t}function Ou(e){let t=[];return Wr(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&J(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 Du(e){return e!=null?typeof e=="string"?e:JSON.stringify(e):void 0}var Mu=e=>{throw new xo(e)},ee=e=>null;function te(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Mu};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=En(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 f=l.json().catch(r),g=n?f.then(R=>n(R,l)):f;return d?g.then(R=>d(R,l)):g})}}function En(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=vr()}=e;return(r=t,n)=>{let i;return typeof r=="string"?i={method:r,body:n}:i=r??{method:t,body:n},i=o(i),{...i,method:i.method,body:Du(i.body)}}}var ry=En();var oe=kn({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function On(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}}}function Et(e,t=Cr){return async o=>{try{await e(o)}catch(r){kr(r),process.exit(t)}}}var _u=["raw","page_by_line","data_by_line"],vu=["replace","concat"],Nu=["meta","pages","merged_page"];function Zo(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:Nu,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:_u,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:vu,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as wu}from"@nestjs/common";var _y=wu((e,t)=>Uu(t));function Uu(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Fo,BadRequestException as Lu,InternalServerErrorException as Gu,Logger as Ku}from"@nestjs/common";import Vu from"raw-body";import{parse as Hu}from"querystring";var Dn=new Ku("RawBody"),Ly=Fo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Dn.error("RawBody request was not readable. This is generally due to bad configuration."),new Lu("Invalid body");return Vu(o)}),Mn=Fo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Dn.error("RawBody expected a buffer set to req.body."),new Gu("failed parsing body");return r}),Gy=Fo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=zu(o.body),o.body});function zu(e){let t=ju(e);return Hu(t)}function ju(e){return e.toString("utf8").trim()}import{Injectable as Wu}from"@nestjs/common";import Bu from"body-parser";var He=class{use(t,o,r){Bu.json()(t,o,r)}};He=A([Wu()],He);import{Injectable as qu}from"@nestjs/common";import Ju from"body-parser";var ze=class{use(t,o,r){Ju.raw({type:"*/*"})(t,o,r)}};ze=A([qu()],ze);import{Logger as $u,Module as Xu,RequestMethod as Yu}from"@nestjs/common";var Qu="/webhook",ep={path:`${Qu}/{*path}`,method:Yu.POST},So=class{configure(t){tp(t)}},Ot=class extends So{logger=new $u("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Ot=A([Xu({})],Ot);function tp(e){e.apply(ze).forRoutes(ep).apply(He).forRoutes("{*path}")}var _n="CLIENT_WEB_APP_URL";var be=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as op,Injectable as rp}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=A([rp(),I(0,op(be))],ke);import{Module as np}from"@nestjs/common";import{ConfigModule as ip,ConfigService as ap}from"@nestjs/config";function sp(e){let t={client:{clientWebAppUrl:e.get(_n)}};return be.assertValidConfig(t),t}var Dt=class{};Dt=A([np({imports:[ip],providers:[{provide:be,inject:[ap],useFactory:sp},ke],exports:[ke]})],Dt);var vn="SERVER_ENV_TOKEN";import{Inject as cp,Injectable as up}from"@nestjs/common";function Nn(){return process.env.NODE_ENV==="test"}var Mt=class{constructor(t){this.env=t}get isTestingEnv(){return Nn()}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}};Mt=A([up(),I(0,cp(vn))],Mt);import{dirname as yp}from"node:path";import{chmod as pp,mkdirSync as dp,readFile as lp,writeFile as hp}from"node:fs";import{rm as mp}from"node:fs/promises";function ye(e){return new Promise((t,o)=>{lp(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 _t(e){return dp(e.dirPath,{recursive:!0}),new Promise((t,o)=>{hp(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():pp(e.filePath,e.mode,n=>{n?o(n):t()})})})}function ut(e){return mp(e,{force:!0})}var gp=384;function wn(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??gp;async function a(){let p=await ye(t),d;if(p==null)d={};else if(r==null)d=p;else{d={};for(let y of Object.keys(p)){let l=r(p[y]);l!=null&&(d[y]=l)}}return d}async function s(p){let d=n==null?p:Object.fromEntries(Object.entries(p).map(([y,l])=>[y,n(l)]));await _t({filePath:t,dirPath:yp(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 y=await a();await s({...y,[p]:d})}),remove:p=>u(async()=>{let y={...await a()};delete y[p],await s(y)}),clear:()=>u(async()=>{await ut(t)})}}var rf=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 ye(e.configFilePath)}function fp(e){return _t({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 fp({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:Rp(e?.commands,t)}}function Rp(e,t){let o;if("commands"in t)if(t.commands){let r={...e};for(let n of Object.keys(t.commands))r[n]={...e?.[n],...t.commands[n]};o=r}else o=void 0;else o=e;return o}function Un(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 de(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as Tp}from"node:os";import{join as bo}from"node:path";function vt(e){let t=e.configDirOverride??bo(Tp(),`.${e.cliName}`);return{configDir:t,configFilePath:bo(t,"config.json"),tokenCachePath:bo(t,".tokens.json")}}function Ln(e){let t=vt({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=>{Zr(!!n.verbose),Fr(typeof n.timeout=="number"&&n.timeout>0?n.timeout*1e3:void 0);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("."),f={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(l,f)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,y=p?Un({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};oo({dumpDir:y.dumpDir,pick:n.pickAll?void 0:y.pick,commandPath:i,pretty:!!n.pretty})}}function Cp(e){let t=vt({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 Gn(e){let t=Cp(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:Et(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:Et(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:Et(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:S}}import{writeFileSync as xp,appendFileSync as Zp}from"node:fs";function Kn(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,s;if(i){let c=0,u=g=>{let R;if(r){let Z=Se(g.data,r);R={...g,data:Z}}else R=g;return R},p=g=>{let R=g.append?Zp:xp;R(i,g.mainContent),a&&g.pickContent!==void 0&&R(a,g.pickContent)},d=(g,R)=>{let Z=JSON.stringify(g,null,2),F=a?JSON.stringify(u(g),null,2):void 0;p({mainContent:Z,pickContent:F,append:R})},y=(g,R)=>{let Z=JSON.stringify(g)+`
4
+ var gc=Object.defineProperty;var fc=Object.getOwnPropertyDescriptor;var A=(e,t,o,r)=>{for(var n=r>1?void 0:r?fc(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&&gc(t,o,n),n},I=(e,t)=>(o,r)=>t(o,r,e);import{existsSync as Rc,mkdirSync as Tc,writeFileSync as Cc}from"node:fs";import{join as xc}from"node:path";var Cr=1;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],Ne={},xr=[...to],eo,Zc=!1,Fc;function oo(e){Ne=e}function At(){return Ne}function Zr(e){Zc=e}function Fr(e){Fc=e}function ro(e){xr=e}function Sr(e){eo=e}function pe(e){let t=e;for(let o of xr)t=t.replace(o,"[REDACTED]");return t}function Ar(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function at(e,t){let{dumpDir:o,commandPath:r}=Ne,n;if(o){Rc(o)||Tc(o,{recursive:!0});let i=r?.length?r.join("_"):"response",a=Ar(),s=t?`${i}_${a}_${t}`:`${i}_${a}`;n=xc(o,`${s}.${e}`)}else n=void 0;return n}function Sc(e,t){let o=at("json");if(!o)return;let r={ok:!0,data:e,...t?{meta:t}:{}};Cc(o,JSON.stringify(r,null,2))}function Se(e,t){let o=t.split(",").map(n=>n.trim()),r;return Array.isArray(e)?r=e.map(n=>Tr(n,o)):e!=null&&typeof e=="object"?r=Tr(e,o):r=e,r}function Tr(e,t){let o;if(e==null||typeof e!="object")o=e;else{let r={};for(let n of t)n in e&&(r[n]=e[n]);o=r}return o}function br(e){return Ne.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}function l(e,t){Sc(e,t);let r={ok:!0,data:Ne.pick?Se(e,Ne.pick):e,...t?{meta:t}:{}};console.log(br(r))}function kr(e){console.log(br(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){let t=eo?eo(e):void 0,o;return t?o=t:e instanceof it?o={ok:!1,error:pe(e.message),code:e.code,...e.suggestion?{suggestion:e.suggestion}:{}}:e instanceof Error?o={ok:!1,error:pe(e.message),code:"ERROR"}:o={ok:!1,error:pe(String(e)),code:"UNKNOWN_ERROR"},o}function we(e,t=!1){let o;return typeof e=="string"?o=t:e!=null&&typeof e=="object"&&Symbol.iterator in e?o=!0:o=!1,o}function st(e){let t=!0;for(let o of e){t=!1;break}return t}function io(e,t){for(let o of e)t(o)}function q(e,t,o=!1){e!=null&&(we(e,o)?io(e,t):t(e))}function Ir(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 Ac(e){return e!=null?bc(e):[]}var C=Ac;function bc(e){return Array.isArray(e)?e:[e]}function Pr(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function ao(e){return Object.keys(e).length===0}function Er(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Or(e){return{...e}}function Dr(e){return e!=null}function bt(e){return we(e,!1)?!st(e):Mr(e)}function so(e){let t;return we(e,!0)?t=!st(e):Mr(e)?t=typeof e=="object"?!ao(e):!0:t=!1,t}function Mr(e){return e!=null&&e!==""}function kc(e){return t=>{let o;return t!=null?o=t.filter((r,n,i)=>e(r,n,i)):o=[],o}}var he=kc(Dr);function _r({base:e,build:t}){let o=e??{};return t(o),o}var Ic=(e=>e);function vr(){return Ic}function Ue(e,t){let o=Pc(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Pc(e,t){return Er(Ec(e,t))}function Ec(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 Nr(e,t,o){return C(t).forEach(r=>e.set(r,o)),e}function co(e){return Array.from(e.entries())}function wr(e){return Oc(co(e))}function Oc(e){let t=[];return e.forEach(([o,r])=>{q(r,n=>{t.push([o,n])})}),t}function Ur(){let e=new Map,t=(n,i)=>{let a=e.get(n);a==null&&(a=[],e.set(n,a)),q(i,s=>a.push(s))},o=(n,i)=>t(n,Ir(i));return{map:()=>e,entries:()=>co(e),tuples:()=>wr(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,i)=>q(n,a=>t(a,i)),addTuplesToKeys:(n,i)=>q(n,a=>o(a,i)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function Dc(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function Lr(e){let t=Dc(e);return t!=null&&t!=="class"}function Gr(e){return Lr(e)?e:()=>e}function Kr(e,t){return Math.log(t)/Math.log(e)}var Vr=",",Mc=" ";function _c(e,t=Vr,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;switch(o){case 1:r=[e];break;case 2:{let n=e.indexOf(t);r=n<0?[e]:[e.slice(0,n),e.slice(n+t.length)];break}default:{let n=e.split(t),i=[];if(n.length>1){let a=n.length>o,s=a?o-1:n.length;for(let c=0;c<s;c+=1)i.push(n[c]);a&&i.push(n.slice(s).join(t))}else i.push(n[0]);r=i;break}}return r}function vc(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,i=o){return _c(n,t,i)};return r.joiner=t,r.trimByDefault=o,r}function Hr(e){let{joiner:t}=e,o=vc(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=Hr({joiner:Vr}),Nc=Hr({joiner:Mc,trimByDefault:!0});var P=po.joinStrings,Wh=po.splitStrings,Bh=po.splitStringsToSet,qh=Nc.joinStrings;var zr=Pr;function Wr(e,{forEach:t,filter:o}){wc(e,o).forEach((n,i)=>t(n,i))}function wc(e,t){return lo(t)(e)}function lo(e){let t;if(e!=null){let o=Uc(e);t=r=>jr(r).filter((n,i)=>o(n,i))}else t=jr;return t}function jr(e){return Object.entries(e)}function ho(e){return typeof e=="object"?e:{valueFilter:e}}function Uc(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])=>bt(a);break;case 5:i=([,a])=>so(a);break;case 6:i=([,a])=>!!a&&bt(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 zr(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 Lc({filter:e,copy:t,dynamic:o=!1}){let r=e!=null?Le({filter:e,copy:!1}):Kc;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=Or(s)),Object.assign(s,c),s}}}function Br(e,t){return Gc(t)(e)}function Gc(e){let t=Lc({filter:e,copy:!1,dynamic:!0});return o=>t(he(o))({})}var sm=Le({copy:!0,filter:{valueFilter:1}}),cm=Le({copy:!0,filter:{valueFilter:2}}),qr=Le({copy:!0,filter:{valueFilter:4}}),um=Le({copy:!0,filter:{valueFilter:6}}),pm=mo({valueFilter:1}),dm=mo({valueFilter:6}),lm=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 Le({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 Kc=Le({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 $r(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 Xr(e){let t,o,r=0;function n(){let i;if(t==null){if(o==null){let a=r;o=e.load().then(s=>(r===a&&(t={entries:s},o=void 0),s),s=>{throw r===a&&(o=void 0),s})}i=o}else i=Promise.resolve(t.entries);return i}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 Yr(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 kt(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=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],Tm=new Set(Vc);function Qr(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=kt(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 y=n[p],T=n.substring(u,p)+o(y);s.push(T),u=p+1}s.push(n.substring(u)),a=s.join("");break}}return a}}function Hc(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 Hc(e)(t,o)}function zc(e,t){return It(e,t,1)[0]}function jc(e){return t=>{let r=zc(typeof e=="string"?new Set([e]):e,t),n;return r!=null?n=yo(t,r,!1):n=[t,void 0],n}}function en(e,t){return jc(t)(e)}var Ge="/",Wc=".";function Bc(e){let t=e.split(Wc,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===Ge?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function tn(e){return Bc(e)!=="invalid"}var qc=/^\/+/,Jc=/\/+$/;var $c=/\/{2,}/g;function on(e){return e.startsWith(Ge)?e.replace(qc,Ge):`${Ge}${e}`}function rn(e){return e.replaceAll($c,Ge)}function nn(e){return e.replace(Jc,"")}function Xc(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var an=/:(\d+)/;function Yc(e){return an.test(e)}function Qc(e){let t=an.exec(e);return t?Number(t[1]):void 0}function eu(e){let t=pn(e),o=tu(t),{domain:r,path:n}=o,i=Xc(r),a=Yc(e),s=a?Qc(e)??void 0:void 0,[c,u]=en(o.path,"?"),p=i&&(c===""||tn(c+"/")),d=ru(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 sn(e){let t=eu(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function cn(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=kt(n,i,"&")),n}function tu(e){let t=pn(e);return ou(t)}function ou(e){let t=uo(e,"/",2),o=t[0],r=t[1];return{domain:o,path:on(r??"/")}}var un=/^https:\/\/|http:\/\//;function pn(e){return e.replace(un,"")}function ru(e){return un.test(e)}function S(){}function dn(e){let t;return e==null||pu(e)?t=e:t=nu(e),t}function nu(e){return e==null?e:new Date(e)}var ln=24,iu=60;var au=60,su=au*iu,L=1e3,Ae=L*60,go=Ae*60,cu=go*ln,Dm=su*ln,uu=7,Mm=cu*uu;function pu(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function hn(e){return e.getTime()<Date.now()}function mn(e,t){return e!=null?new Date(e.getTime()+(t??0)):e}function du(e){let{expiresAt:t,expires:o,now:r,expiresFromDate:n,defaultExpiresFromDateToNow:i,expiresIn:a}=e,s=n==null?null:dn(n);function c(y){return y??r??new Date}function u(y,m=!1){let T=c(y),g=d(T),f;return g==null?f=m:f=g<=T,f}function p(y){let m=c(y);return d(m)}function d(y){let m=null;return o!=null?m=o.expiresAt??null:t!=null?m=t:a!=null&&(m=mn(s??(i!==!1?y:null),a)),m}return{input:e,hasExpired:u,getExpirationDate:p}}function yn(e,t){let o=!0;return e!=null&&(o=du(e).hasExpired(t,!0)),o}function gn(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 lu(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;m(e??i);function p(){return{...i}}function d(){return u}function y(F){u=F}function m(F,U=!1){let z=Math.max(0,F.startLimitAt??1),b=F.cooldownRate??1,v=F.maxWaitTime??n,V=F.exponentRate??2;i={startLimitAt:z,cooldownRate:b,maxWaitTime:v,exponentRate:V},s=Kr(V,v/L+1),U&&T()}function T(){a=0,c=new Date}function g(F){let U;if(u){let{cooldownRate:z}=i,v=(Date.now()-c.getTime())*z/L,V=Math.max(a-v,0),j=Math.max(0,V-i.startLimitAt);F&&(a=V+F,c=new Date),U=j>=s?i.maxWaitTime:(Math.pow(i.exponentRate,Math.max(j,0))-1)*L}else U=0;return U}function f(F){return g(F??0)}function Z(){let F=g(1);return fo(F)}return{waitForRateLimit:Z,getNextWaitTime:f,getConfig:p,setConfig:m,getEnabled:d,setEnabled:y,reset:T}}function fn(e){let o=lu({exponentRate:1.5,maxWaitTime:L*8,...e}),r=Ae,n=new Date,i=0,a=0,s=!0;Z(e,!0);function c(){hn(n)&&d()}function u(){return s}function p(b){s=b}function d(){a=i,n=new Date(Date.now()+r)}function y(){return n}function m(){return Math.max(0,n.getTime()-Date.now())}function T(b){n=b}function g(){return c(),a}function f(b){a=b}function Z(b,v=!1){i=b.limit??i,r=b.resetPeriod??r;let V={cooldownRate:b.cooldownRate??Math.max(.1,r/L),exponentRate:b.exponentRate??1.5,maxWaitTime:b.maxWaitTime??L*8};o.setConfig(V,v),v&&d(),n=b.resetAt??n}function F(b){let v=0;if(s){let j=function(){return a-=b,o.getNextWaitTime(b)};var V=j;a>0?v=j():(c(),a>0?v=j():v=m())}return v}function U(b){return F(b??0)}function z(){let b=F(1);return fo(b)}return{getRemainingLimit:g,setRemainingLimit:f,getTimeUntilNextReset:m,getResetAt:y,setNextResetAt:T,setConfig:Z,reset:d,getNextWaitTime:U,waitForRateLimit:z,getEnabled:u,setEnabled:p}}var hu="__CATCH_ALL_HANDLE_RESULT_KEY__";function Rn(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===hu?a(p):Nr(i,u,p)},c=(u,p,d)=>{let y=d.bind(u);s(p,y)};return _r({base:(u=>{let p=e(u),d=(p!=null?i.get(p):void 0)??n,y;return d?y=Promise.resolve(d(u)).then(m=>m??o):y=Promise.resolve(r),y}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=a}})}}function mu(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function yu(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function gu(e,t,o){let r=yu(e,t);return n=>{r(function(i){let a=o(i);return n.call(this,a)})}}function Tn(e,t){return o=>gu(e,o,t)}function Cn(e){return t=>(o,r)=>{let n=mu(o,t),i=e.configurerForAccessor(n);r(i)}}var fu=-1,xn=0;function Ru(e){return e?.page??fu}function Zn(e){return Ru(e)+1}import{BaseError as Fn}from"make-error";var J=class extends Fn{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function Sn(e){return(t,o)=>Tu(e(t,o))}var Ke=class extends Fn{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function Tu(e){return e.then(t=>{if(!t.ok)throw new Ke(t);return t})}import{BaseError as Xm}from"make-error";function An(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??void 0);if(n){let a=setTimeout(()=>{r?.abort()},n);i=i.finally(()=>{clearTimeout(a)})}return i}}function kn(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>In({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>xu({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var Cu=(e,t)=>t(e);function xu(e){let{makeFetch:t=fetch,fetchHandler:o=Cu,useTimeout:r,requireOkResponse:n,mapResponse:i}=e,a=t;r&&(a=An(a)),n&&(a=Sn(a));let s=In(e);return async(c,u)=>{let p=await s(c,u),d=o(p,a);return i&&(d=i(d)),d}}var Zu=(e,t)=>new Request(e,t??void 0);function In(e){let{makeRequest:t=Zu,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:i,useBaseUrlForConfiguredFetchRequests:a=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=a}=e,c=o?new URL(nn(o)):void 0,u=c?m=>{let T,g=m.toString();if(!s&&sn(g))T=new URL(g);else{let f=c.origin+rn("/"+c.pathname+"/"+m);T=new URL(f,c)}return T}:void 0;async function p(m){let T=gn(m)?await m:m;return bn(T)?T:t(T)}let d=u?async m=>{let T,g,f;if(typeof m=="string"?T=m:bn(m)?a?(T=m.url,g=m):f=m:f=await t(m),!f){let Z=u(T);f=await t(Z.href,g)}return f}:p,y;if(r!=null||n!=null){let m=Gr(r);async function T(){let f=await m();return n?{...f,timeout:n}:f}async function g(f,Z){let F=await T(),U=Fu(F,await Z),z=U.timeout===void 0?f.timeout:U.timeout;return{...U,timeout:z}}i?y=(f,Z)=>i(f,g(f,Z)):y=(f,Z)=>g(f,Z)}else i?y=i:y=(m,T)=>T;return async(m,T)=>{try{let g=await d(m);T=await y(g,T??void 0);let f=await t(g,T);return f.timeout=n,f}catch(g){throw g instanceof J?g:new J(g)}}}function Fu(e,t){let o;if(t){let r=Su([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function Su(e){let t=Ur();return he(e).forEach(o=>{let r=Au(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 Au(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 bn(e){return!!e.url}import{safeParse as bu}from"fast-content-type-parse";function Pt(e){let t=e.headers.get("content-type"),o=bu(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Pn(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(m){d=m,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 J{constructor(o){super("There was no next page for this.");this.page=o}},To=class extends J{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},ku=100;function Ve(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??ku;function y(T,g=void 0){return async()=>{let f=await t(T),{cursor:Z,nextPageCursor:F,hasNext:U}=await o(f),z=Z??g?.cursor,b=U!==!1,v=g?g.page+1:xn,V=v>=d,j={input:T,result:f,page:v,previous:g,hasNext:b,isAtMaxPage:V,cursor:z,nextPageCursor:F,fetchNext:ct(async()=>{if(V)throw new To(j,d);let Rr=b?await r(j,T,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Rr)throw new Ro(j);return y({...T,...Rr},j)()})};return j}}return{input:a,fetchNext:ct(()=>y(a)())}}}function R(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?Br(e):e,i=r??!0?qr(n??{}):n,a=new URLSearchParams(i);return o!=null&&q(o,s=>a.delete(s),!1),a}function Co(e){let t;if(typeof e=="string")t=e;else if(Iu(e))t=e.href;else{let o=Co(e.url);if(e.queryParams){let r=Ou(e.queryParams);st(r)?t=o:t=cn(o+`?${r.toString()}`)}else t=o}return t}function Iu(e){return typeof e=="object"&&e instanceof URL}function Pu(e){return typeof e=="object"&&e instanceof URLSearchParams}function Eu(e){let t=[];return io(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let i=String(r);q(n,a=>{a!=null&&t.push([i,String(a)])})}}),t}function Ou(e){let t;return Pu(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):we(e)?t=new URLSearchParams(Eu(e)):t=Du(e),t}function Du(e){let t=[];return Wr(e,{forEach:o=>{let[r,n]=o,i=String(r);n!=null&&q(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 Mu(e){return e!=null?typeof e=="string"?e:JSON.stringify(e):void 0}var _u=e=>{throw new xo(e)},Y=e=>null;function Q(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??_u};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,i=En(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(m=>{let T=m.json().catch(r),g=n?T.then(f=>n(f,m)):T;return d?g.then(f=>d(f,m)):g})}}function En(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=vr()}=e;return(r=t,n)=>{let i;return typeof r=="string"?i={method:r,body:n}:i=r??{method:t,body:n},i=o(i),{...i,method:i.method,body:Mu(i.body)}}}var gy=En();var ee=kn({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function On(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}}}function Et(e,t=Cr){return async o=>{try{await e(o)}catch(r){kr(r),process.exit(t)}}}var vu=["raw","page_by_line","data_by_line"],Nu=["replace","concat"],wu=["meta","pages","merged_page"];function Zo(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:wu,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:vu,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:Nu,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}import{createParamDecorator as Uu}from"@nestjs/common";var By=Uu((e,t)=>Lu(t));function Lu(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Fo,BadRequestException as Gu,InternalServerErrorException as Ku,Logger as Vu}from"@nestjs/common";import Hu from"raw-body";import{parse as zu}from"querystring";var Dn=new Vu("RawBody"),Yy=Fo(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Dn.error("RawBody request was not readable. This is generally due to bad configuration."),new Gu("Invalid body");return Hu(o)}),Mn=Fo(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Dn.error("RawBody expected a buffer set to req.body."),new Ku("failed parsing body");return r}),Qy=Fo(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=ju(o.body),o.body});function ju(e){let t=Wu(e);return zu(t)}function Wu(e){return e.toString("utf8").trim()}import{Injectable as Bu}from"@nestjs/common";import qu from"body-parser";var He=class{use(t,o,r){qu.json()(t,o,r)}};He=A([Bu()],He);import{Injectable as Ju}from"@nestjs/common";import $u from"body-parser";var ze=class{use(t,o,r){$u.raw({type:"*/*"})(t,o,r)}};ze=A([Ju()],ze);import{Logger as Xu,Module as Yu,RequestMethod as Qu}from"@nestjs/common";var ep="/webhook",tp={path:`${ep}/{*path}`,method:Qu.POST},So=class{configure(t){op(t)}},Ot=class extends So{logger=new Xu("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};Ot=A([Yu({})],Ot);function op(e){e.apply(ze).forRoutes(tp).apply(He).forRoutes("{*path}")}var _n="CLIENT_WEB_APP_URL";var be=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as rp,Injectable as np}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=A([np(),I(0,rp(be))],ke);import{Module as ip}from"@nestjs/common";import{ConfigModule as ap,ConfigService as sp}from"@nestjs/config";function cp(e){let t={client:{clientWebAppUrl:e.get(_n)}};return be.assertValidConfig(t),t}var Dt=class{};Dt=A([ip({imports:[ap],providers:[{provide:be,inject:[sp],useFactory:cp},ke],exports:[ke]})],Dt);var vn="SERVER_ENV_TOKEN";import{Inject as up,Injectable as pp}from"@nestjs/common";function Nn(){return process.env.NODE_ENV==="test"}var Mt=class{constructor(t){this.env=t}get isTestingEnv(){return Nn()}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}};Mt=A([pp(),I(0,up(vn))],Mt);import{dirname as gp}from"node:path";import{chmod as dp,mkdirSync as lp,readFile as hp,writeFile as mp}from"node:fs";import{rm as yp}from"node:fs/promises";function me(e){return new Promise((t,o)=>{hp(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 _t(e){return lp(e.dirPath,{recursive:!0}),new Promise((t,o)=>{mp(e.filePath,JSON.stringify(e.data,null,2),{mode:e.mode},r=>{r?o(r):e.mode==null?t():dp(e.filePath,e.mode,n=>{n?o(n):t()})})})}function ut(e){return yp(e,{force:!0})}var fp=384;function wn(e){let{filePath:t,mode:o,reviver:r,replacer:n}=e,i=o??fp;async function a(){let p=await me(t),d;if(p==null)d={};else if(r==null)d=p;else{d={};for(let y of Object.keys(p)){let m=r(p[y]);m!=null&&(d[y]=m)}}return d}async function s(p){let d=n==null?p:Object.fromEntries(Object.entries(p).map(([y,m])=>[y,n(m)]));await _t({filePath:t,dirPath:gp(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 y=await a();await s({...y,[p]:d})}),remove:p=>u(async()=>{let y={...await a()};delete y[p],await s(y)}),clear:()=>u(async()=>{await ut(t)})}}var ff=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 Rp(e){return _t({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 Rp({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:Tp(e?.commands,t)}}function Tp(e,t){let o;if("commands"in t)if(t.commands){let r={...e};for(let n of Object.keys(t.commands))r[n]={...e?.[n],...t.commands[n]};o=r}else o=void 0;else o=e;return o}function Un(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 ye(e){let t;return e==null?t=e:e.length<=4?t="***":t=e.substring(0,4)+"***",t}import{homedir as Cp}from"node:os";import{join as bo}from"node:path";function vt(e){let t=e.configDirOverride??bo(Cp(),`.${e.cliName}`);return{configDir:t,configFilePath:bo(t,"config.json"),tokenCachePath:bo(t,".tokens.json")}}function Ln(e){let t=vt({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=>{Zr(!!n.verbose),Fr(typeof n.timeout=="number"&&n.timeout>0?n.timeout*1e3:void 0);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 m=i.join("."),T={...s===void 0?{}:{dumpDir:s},...c===void 0?{}:{pick:c}};await r(m,T)}let p=a&&!e.skipCommands.has(a),d=p?await o():void 0,y=p?Un({outputConfig:d,commandPath:i,cliFlags:{dumpDir:n.dumpDir??s,pick:n.pick??c}}):{dumpDir:void 0,pick:void 0};oo({dumpDir:y.dumpDir,pick:n.pickAll?void 0:y.pick,commandPath:i,pretty:!!n.pretty})}}function xp(e){let t=vt({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 Gn(e){let t=xp(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:Et(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();l({saved:!0,output:p??{}})})},r={command:"show",describe:"Show current output configuration",builder:i=>i,handler:Et(async()=>{let i=await t.loadOutputConfig();l({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:Et(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}),l({cleared:!0,command:a})}else await t.clearOutputConfig(),l({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:S}}import{writeFileSync as Zp,appendFileSync as Fp}from"node:fs";function Kn(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,s;if(i){let c=0,u=g=>{let f;if(r){let Z=Se(g.data,r);f={...g,data:Z}}else f=g;return f},p=g=>{let f=g.append?Fp:Zp;f(i,g.mainContent),a&&g.pickContent!==void 0&&f(a,g.pickContent)},d=(g,f)=>{let Z=JSON.stringify(g,null,2),F=a?JSON.stringify(u(g),null,2):void 0;p({mainContent:Z,pickContent:F,append:f})},y=(g,f)=>{let Z=JSON.stringify(g)+`
5
5
  `,F=a?JSON.stringify(u(g))+`
6
- `:void 0;p({mainContent:Z,pickContent:F,append:R})},l=(g,R)=>{let Z=g.data??[],F=a?Se(Z,r):void 0;Z.length===0?R||p({mainContent:"",pickContent:a?"":void 0,append:!1}):Z.forEach((U,z)=>{let b=R||z>0,v=JSON.stringify(U)+`
6
+ `:void 0;p({mainContent:Z,pickContent:F,append:f})},m=(g,f)=>{let Z=g.data??[],F=a?Se(Z,r):void 0;Z.length===0?f||p({mainContent:"",pickContent:a?"":void 0,append:!1}):Z.forEach((U,z)=>{let b=f||z>0,v=JSON.stringify(U)+`
7
7
  `,V=a&&F?JSON.stringify(F[z])+`
8
- `:void 0;p({mainContent:v,pickContent:V,append:b})})};s={mainPath:i,pickPath:a,writePage:g=>{let Z=o==="concat"&&!(c===0);t==="raw"?d(g,Z):t==="page_by_line"?y(g,Z):l(g,Z),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}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 y=n.nextInput(u,d);if(!y)break;u=y}return c}function Sp(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:Se(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?Se(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)),c;if(s<=1)c={handled:!1,result:await o(t)};else{let u=At();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let p=Kn({dumpOutput:i,dumpMerge:a}),d;try{d=await Fp({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:p,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{p.close()}let y={pagesFetched:d.pagesFetched,totalRecords:d.totalRecords,hasMorePagesAvailable:d.hasMorePagesAvailable,dumpFile:p.mainPath??null};p.pickPath&&(y.dumpFilePick=p.pickPath),Sp({multiplePagesOutput:n,summaryMeta:y,state:d,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import Yl from"yargs";import{hideBin as Ql}from"yargs/helpers";import{writeFile as Ap,mkdirSync as bp}from"node:fs";import{join as ko}from"node:path";import{homedir as kp}from"node:os";var Nt=["recruit","crm","desk"];function Io(){return ko(kp(),".zoho-cli")}function lt(){return ko(Io(),"config.json")}function ht(){return ko(Io(),".tokens.json")}function Ie(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function H(){let e=lt(),t=await ye(e),o=Ie("ACCOUNTS_CLIENT_ID"),r=Ie("ACCOUNTS_CLIENT_SECRET"),n=Ie("ACCOUNTS_REFRESH_TOKEN"),i=o&&r&&n,a;if(!t&&!i)a=void 0;else{let s={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:Ie("ACCOUNTS_URL")??t?.shared?.region,apiMode:Ie("API_URL")??t?.shared?.apiMode},c=u=>{let p=u.toUpperCase(),d=Ie("API_URL",p),y=u==="desk"?Ie("DESK_ORG_ID"):void 0,l=t?.[u],f=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],g=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],R=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`],Z=f||g||R,F;return!l&&!Z&&!y?F=void 0:F={clientId:f??l?.clientId,clientSecret:g??l?.clientSecret,refreshToken:R??l?.refreshToken,apiUrl:d??l?.apiUrl,orgId:y??l?.orgId},F};a={shared:s,recruit:c("recruit")??t?.recruit,crm:c("crm")??t?.crm,desk:c("desk")??t?.desk,output:t?.output}}return a}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,s;return!n||!i||!a?s=void 0:s={clientId:n,clientSecret:i,refreshToken:a,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId},s}async function Ip(e){let t=lt();return bp(Io(),{recursive:!0}),new Promise((o,r)=>{Ap(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function W(e){let t=await H(),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 Ip(o),o}async function Vn(){await W({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Hn(){let e=lt(),t=ht();await ut(e),await ut(t)}function X(e){return Nt.filter(t=>{let o=mt(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as vs,Injectable as Fd}from"@nestjs/common";function je(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function N(e,t){return Ve({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:Zn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function wt(e){let t;switch(e){case"sandbox":t="https://recruitsandbox.zoho.com/recruit";break;case"production":t="https://recruit.zoho.com/recruit";break;default:t=e;break}return t}var We="Candidates",zn="Job_Openings",Ut="Notes",jn="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=me(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 Wn=Qr({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function Po(e){let t=Wn(e.value);return`(${e.field}:${e.filter}:${t})`}var Bn=Lt;import{BaseError as Kp}from"make-error";import{BaseError as Ep}from"make-error";var Op="__internal_data_array_blank_error";function Dp(e){return Array.isArray(e?.data)}var $e="success";function Y(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var ge=class extends Ep{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},G=class extends ge{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},Be=class extends G{constructor(t,o){super({code:Op,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function re(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof Be&&!o||(r instanceof G?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof ge?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ne(e,t){return(o,r=t,n)=>async(i,a)=>{try{return await o(i,a)}catch(s){if(s instanceof Ke){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function ie(e){return(t,o)=>{if(t?.error!=null){let n=new Ke(o),i=e(t,n);if(i)throw i}return t}}var Mp="INTERNAL_ERROR",_p="INVALID_TOKEN",K=class extends G{},qn="FAILURE",Eo=class extends G{},vp="4834",qe=class extends G{},Np="INVALID_QUERY",Oo=class extends G{get details(){return this.error.details}},Kt="MANDATORY_NOT_FOUND",fe="DUPLICATE_DATA",Vt="INVALID_DATA",wp="TOO_MANY_REQUESTS",Jn=429,Up="X-RATELIMIT-LIMIT",Lp="X-RATELIMIT-REMAINING",Gp="X-RATELIMIT-RESET",$n=100,Xn=Ae;function Do(e){let t=e.get(Up),o=e.get(Lp),r=e.get(Gp),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 Je=class extends G{get headerDetails(){return Do(this.responseError.response.headers)}};function ae(e,t){let o;if(Dp(e))o=new Be(e,t);else{let r=le(e,t);if(r){let n=Y(r);switch(n.code){case Mp:o=new Eo(n,e,t);break;case _p:o=new K(n,e,t);break;case vp:o=new qe(n,e,t);break;case Np:o=new Oo(n,e,t);break;case wp:o=new Je(n,e,t);break;default:o=new G(n,e,t);break}}}return o}function le(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var Yn="ALREADY_ASSOCIATED",Mo=class extends Kp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},Xe=class extends ge{},_o=class extends Xe{},vo=class extends Xe{},Ht=class extends Xe{get invalidFieldDetails(){return this.error.details}},No=class extends Ht{};function Qn(e){let t;switch(e.code){case Vt:{let o=new Ht(e);o.invalidFieldDetails.id?t=new No(e):t=o;break}case Kt:t=new _o(e);break;case fe:t=new vo(e);break;default:t=new Xe(e);break}return t}function ei(e,t){return o=>{if(!o?.data?.length)throw new Mo(e,t);return o}}var Vp=re("ZohoRecruit");async function Hp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ti(t,e)),o}function ti(e,t){let o,r=le(e,t);if(r)switch(Y(r).code){default:o=ae(e,t);break}return o}var oi=ie(ti),ri=ne(Hp,Vp);import{BaseError as zp}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=se(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Qn(p[0].result);c=u[0].result.details}return c}))}function ni(e){return Uo(e,"","POST")}function ii(e){return Uo(e,"/upsert","POST")}function ai(e){return Uo(e,"","PUT")}function si(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${T({ids:t,wf_trigger:r})}`,M("DELETE")).then(jp)}function ci(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,M("GET")).then(ei(t.module)).then(o=>o.data[0])}function ui(e){return(t=>e.fetchJson(`/v2/${t.module}?${fi(t).toString()}`,M("GET")))}function Lo(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Bn(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 fi(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,M("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function pi(e){return N(Lo(e))}function Ye(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?je():i))}}function Go(e){return Ye(e)({targetModule:jn})}function di(e){return N(Go(e))}function Ko(e){return Ye(e)({targetModule:yt})}function li(e){return N(Ko(e))}var fR=20*1024*1024;function hi(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 mi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function yi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"DELETE"})}var wo=class extends zp{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function gi(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?wt(t.apiUrl):""}${a}`;return e.fetchJson(c,M("POST")).then(u=>{if(u.code!=="success")throw new wo(u);return u.details})}}function fi(...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 jp(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===$e?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function se(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===$e?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function Ri(e){return t=>e.fetchJson(`/v2/${We}/actions/associate`,M("PUT",{data:C(t)})).then(o=>{let r=o.data.map(()=>t),n=se(r,o.data),{included:i,excluded:a}=Ue(n.errorItems,s=>s.result.code===qn&&s.result.details.error[0].code===Yn);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function Ti(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${Vo(t).toString()}`,M("GET")).then(o=>o??je())}function Ho(e){let t=Ti(e);return o=>t({...o,module:We})}function Ci(e){return N(Ho(e))}function zo(e,t=zn){let o=Ti(e);return r=>o({...r,module:t})}function xi(e){return N(zo(e))}function jo(e){return t=>e.fetchJson(`/v2/${Ut}`,M("POST",{data:t.data})).then(o=>se(C(t.data),o.data))}function Zi(e){return t=>e.fetchJson(`/v2/${Ut}?${T({ids:t.ids})}`,M("DELETE")).then(o=>se(C(t.ids),o.data))}function Wo(e){return Ye(e)({targetModule:Ut})}function Fi(e){return N(Wo(e))}function Si(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 ki(e){return t=>e.fetchJson(`/v2/settings/tags?${T({module:t.module})}`,M("POST",{tags:C(t.tags)})).then(o=>{let r=se(C(t.tags),o.tags),{included:n,excluded:i}=Ue(r.errorItems,a=>a.result.code===fe);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Ii(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 Ai=100;function Pi(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Ai)throw new Error(`Cannot add tags to more than ${Ai} records at once.`);return e.fetchJson(`/v2/${We}/actions/add_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var bi=100;function Ei(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>bi)throw new Error(`Cannot remove tags from more than ${bi} records at once.`);return e.fetchJson(`/v2/${We}/actions/remove_tags?${T({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var Wp="invalid_code",Bp="invalid_client",Bo=class extends ${constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},Qe=class extends ${constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},qp=re("ZohoAccounts");async function Jp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Oi(t,e)),o}function Oi(e,t){let o,r=e.error;if(r){let n=Y(r);switch(n.code){case Wp:case Bp:o=new Bo(n.code);break;default:o=ae(e,t);break}}return o}var Di=ie(Oi),Mi=ne(Jp,qp);function Re(e){return async()=>{let t=await e();if(!t.accessToken)throw new Qe;return t.accessToken}}var $p=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??$p,r=e.maxRateLimit??$n,n=e.resetPeriod??Xn;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=fn(a);return Pn({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,y=!1;if(p){let{remaining:l,limit:f,resetAt:g}=p;if(f!=null&&f!==r){let R=i(f,g??void 0);s.setConfig(R,!1)}if(s.setRemainingLimit(l),g&&s.setNextResetAt(g),y=!0,c.status===Jn){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(y),d}})}function Te(e){return qo({...e,readRateLimitDetails:Xp})}function Xp(e){let t=Do(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function _i(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=Te(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.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=wt(a.apiUrl),c=i({apiUrl:s}),u=ri(c,n,l=>{l instanceof K&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:oi,handleFetchJsonParseErrorFunction:ee});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function zt(e){let t;switch(e){case"sandbox":t="https://crmsandbox.zoho.com/crm";break;case"production":t="https://www.zohoapis.com/crm";break;default:t=e;break}return t}var jt="Notes",vi="Emails",gt="Attachments";var Ni=Lt;import{BaseError as Yp}from"make-error";var Jo=class extends Yp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},et=class extends ge{},$o=class extends et{},Xo=class extends et{},Wt=class extends et{get invalidFieldDetails(){return this.error.details}},Yo=class extends Wt{};function wi(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 fe:t=new Xo(e);break;default:t=new et(e);break}return t}function Ui(e,t){return o=>{if(!o?.data?.length)throw new Jo(e,t);return o}}var Qp=re("ZohoCrm",{logDataArrayErrors:!1});async function ed(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Li(t,e)),o}function Li(e,t){let o,r=le(e,t);if(r)switch(Y(r).code){default:o=ae(e,t);break}return o}var Gi=ie(Li),Ki=ne(ed,Qp);import{BaseError as td}from"make-error";function er(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,w(o,{data:C(r)})).catch(oa).then(i=>{let a=Array.isArray(r),s=Ce(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw wi(p[0].result);c=u[0].result.details}return c}))}function Vi(e){return er(e,"","POST")}function Hi(e){return er(e,"/upsert","POST")}function zi(e){return er(e,"","PUT")}function ji(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${T({ids:t,wf_trigger:r})}`,w("DELETE")).catch(oa).then(rd)}function Wi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,w("GET")).then(Ui(t.module)).then(o=>o.data[0])}function Bi(e){return(t=>e.fetchJson(`/v8/${t.module}?${ta(t).toString()}`,w("GET")))}function tr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Ni(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 ta(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,w("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function qi(e){return N(tr(e))}function tt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${od(n,n.filter).toString()}`,w("GET")).then(i=>i??(r!==!1?je():i))}}function or(e){let t=tt(e)({targetModule:vi});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function Ji(e){return N(or(e))}function rr(e){return tt(e)({targetModule:gt})}function $i(e){return N(rr(e))}var ET=20*1024*1024;function Xi(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 Yi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function Qi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"DELETE"})}var Qo=class extends td{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function ea(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?zt(t.apiUrl):""}${a}`;return e.fetchJson(c,w("POST")).then(u=>{if(u.code!=="success")throw new Qo(u);return u.details})}}function ta(...e){return T(e,{omitKeys:"module"})}function od(...e){return T(e,{omitKeys:["id","module"]})}function w(e,t){return{method:e,body:t??void 0}}function oa(e){let t;if(e instanceof Be)t={data:e.errorDataArray};else throw e;return t}function rd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===$e?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function Ce(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===$e?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}`,w("POST",{data:t.data})).then(o=>Ce(C(t.data),o.data))}function ra(e){return t=>e.fetchJson(`/v2/${jt}?${T({ids:t.ids})}`,w("DELETE")).then(o=>Ce(C(t.ids),o.data))}function ir(e){return tt(e)({targetModule:jt})}function na(e){return N(ir(e))}function ia(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 sa(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module})}`,w("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=Ce(C(t.tags),o.tags),{included:n,excluded:i}=Ue(r.errorItems,a=>a.result.code===fe);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function ca(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,w("DELETE")).then(o=>o.tags)}function ua(e){return t=>e.fetchJson(`/v8/settings/tags?${T({module:t.module,my_tags:t.my_tags})}`,w("GET")).then(o=>({...o,data:o.tags}))}var aa=100;function pa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,w("POST",da(t))).then(o=>{let r=o.data.map(()=>t);return Ce(r,o.data)})}function da(e){if(Array.isArray(e.ids)&&e.ids.length>aa)throw new Error(`Cannot add/remove tags from more than ${aa} 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 la(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,w("POST",da(t))).then(o=>{let r=o.data.map(()=>t);return Ce(r,o.data)})}function ha(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=Te(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.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=zt(a.apiUrl),c=i({apiUrl:s}),u=Ki(c,n,l=>{l instanceof K&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Gi,handleFetchJsonParseErrorFunction:ee});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function ma(e,t){return Ve({...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 Pe(e,t){return{method:e,body:t??void 0}}function ya(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,Pe("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)}},Pe("GET"))}}function ga(e){let t=ar(e);return ma(t)}function fa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,Pe("GET"))}function Ra(e){return()=>e.fetchJson("/fieldtypes",Pe("GET"))}function Ta(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 Ca(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function xa(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 Za(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,Pe("PUT",{requests:o}))}function Fa(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,Pe("POST",r))}}function Sa(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,Pe("PUT",{expire_by:o}))}function Aa(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 ba(e){let t;switch(e){case"sandbox":t="https://signsandbox.zoho.com/api/v1";break;case"production":t="https://sign.zoho.com/api/v1";break;default:t=e;break}return t}var nd=re("ZohoSign",{logDataArrayErrors:!1});async function id(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ka(t,e)),o}function ka(e,t){let o,r=le(e,t);if(r)switch(Y(r).code){default:o=ae(e,t);break}return o}var Ia=ie(ka),Pa=ne(id,nd);function Ea(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=Te(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.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=ba(a.apiUrl),c=i({apiUrl:s}),u=Pa(c,n,l=>{l instanceof K&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Ia,handleFetchJsonParseErrorFunction:ee});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Oa(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var ad=re("ZohoDesk",{logDataArrayErrors:!1});async function sd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Da(t,e)),o}function Da(e,t){let o,r=le(e,t);if(r)switch(Y(r).code){default:o=ae(e,t);break}return o}var Ma=ie(Da),_a=ne(sd,ad);var cd="X-Rate-Limit-Remaining-v3",ud="Retry-After",pd=200;function dd(e){let t=e.get(cd),o;if(t!=null){let r=Number(t),n,i=e.get(ud);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 va(e){return qo({maxRateLimit:pd,...e,readRateLimitDetails:dd})}function Na(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=va(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>oe.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=Oa(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=_a(c,n,l=>{l instanceof K&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Ma,handleFetchJsonParseErrorFunction:ee});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var wa=25;function Q(e,t){return Ve({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=wa}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??wa,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Ee(e,t){return{method:e,body:t??void 0}}function ot(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=ot([{...r,include:Bt(o)}]);return e.fetchJson(`/tickets?${n}`,Ee("GET")).then(i=>i??{data:[]})}}function Ua(e){return t=>{let{ticketId:o,include:r}=t,i=ot([{include:Bt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Ee("GET"))}}function cr(e){return t=>{let o=ot([t]);return e.fetchJson(`/tickets/search?${o}`,Ee("GET")).then(r=>r??{data:[]})}}function La(e){return t=>{let{contactId:o,include:r,...n}=t,i=ot([{...n,include:Bt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function Ga(e){return t=>{let{productId:o,include:r,...n}=t,i=ot([{...n,include:Bt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function Ka(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ee("GET"))}function Va(e){return t=>{let o=ot([{agentIds:P(C(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ee("GET"))}}function Ha(e){return Q(sr(e))}function za(e){return Q(cr(e))}function ja(e){return{method:e}}function Wa(e){return t=>{let o=T([t]);return e.fetchJson(`/departments?${o}`,ja("GET")).then(r=>r??{data:[]})}}function Ba(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,ja("GET"))}function ur(e){return{method:e}}function qa(e){let t;return e&&(t=P(C(e))),t}function pr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:qa(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:qa(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,ur("GET"))}}function $a(e){return t=>{let o=T([{contactIds:P(C(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,ur("GET")).then(r=>r??[])}}function Xa(e){return Q(pr(e))}function ft(e,t){return{method:e,body:t??void 0}}function Ya(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("GET")).then(o=>o??[])}function Qa(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 es(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,ft("DELETE"))}function ts(e){return t=>{let o=T([t]);return e.fetchJson(`/tags/search?${o}`,ft("GET")).then(r=>r??{data:[]})}}function os(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 rs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("GET")).then(o=>o??[])}function ns(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("POST",o))}}function is(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("DELETE",o))}}function as(e,t){return{method:e,body:t??void 0}}function ld(e){let t;return e&&(t=P(C(e))),t}function ss(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:ld(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,as("GET")).then(a=>a??{data:[]})}}function cs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,as("DELETE"))}function qt(e,t){return{method:e,body:t??void 0}}function us(e){let t;return e&&(t=P(C(e))),t}function ps(e){return t=>{let{ticketId:o,include:r,...n}=t,i=T([{...n,include:us(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,qt("GET")).then(a=>a??{data:[]})}}function ds(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=T([{include:us(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,qt("GET"))}}function ls(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,qt("POST",r))}}function hs(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 ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Rt("GET"))}function ys(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Rt("POST",r))}}function gs(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 fs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Rt("GET"))}function Rs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Rt("GET"))}function Ts(e){return{method:e}}function Cs(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:Cs(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,Ts("GET")).then(a=>a??{data:[]})}}function xs(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=T([{include:Cs(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,Ts("GET"))}}function Zs(e){return Q(lr(e))}function hd(e){return{method:e}}function md(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:md(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,hd("GET")).then(a=>a??{data:[]})}}function Fs(e){return Q(hr(e))}function Jt(e){return{method:e}}function Ss(e){let t;return e&&(t=P(C(e))),t}function mr(e){return t=>{let{include:o,...r}=t,n=T([{...r,include:Ss(o)}]);return e.fetchJson(`/agents?${n}`,Jt("GET")).then(i=>i??{data:[]})}}function As(e){return t=>{let{agentId:o,include:r}=t,i=T([{include:Ss(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,Jt("GET"))}}function bs(e){return t=>{let o=T([{agentIds:P(C(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,Jt("GET")).then(r=>r?.data??[])}}function ks(e){return()=>e.fetchJson("/myinfo",Jt("GET"))}function Is(e){return Q(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}`,yd("POST"))}}function yd(e,t){return{method:e,body:t}}var gd="https://accounts.zoho.com";function Ps(e){let t;return e==="us"?t=gd:t=e,t}function Es(e){let t=Te(),{logZohoServerErrorFunction:o,fetchFactory:r=n=>oe.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=Ps(n.apiUrl??"us"),a=r({apiUrl:i}),s=Mi(a,o),c=te(s,{interceptJsonResponse:Di,handleFetchJsonParseErrorFunction:ee}),u=async()=>{let l=Date.now(),{access_token:f,api_domain:g,scope:R,expires_in:Z}=await $t(d)();return{accessToken:f,apiDomain:g,expiresIn:Z,expiresAt:new Date(l+Z*L),scope:R}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=fd({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function fd(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Ae,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 Qe("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function xe(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Ze=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 Rd}from"@nestjs/common";var rt=class{};rt=A([Rd()],rt);function Td(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!yn(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function Cd(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function xd(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Ds(e,t){let o=[...e],r=typeof t=="function"?t:t!==!1?xd: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(Td),c=Yr(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>Cd(d,u)));if(r!=null){let d=me(p.map(y=>y.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function Ms(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=$r(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 Zd=".tmp/zoho-access-tokens.json";function Os(e){let t;if(e==null||typeof e!="object")t=void 0;else{let o=e,r=o.expiresAt,n=r!=null&&!(r instanceof Date)?new Date(r):r;t={...o,expiresAt:n}}return t}function _s(e=Zd,t=!0){let o=wn({filePath:e,reviver:Os}),r=t?Xr(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 ye(e),u;if(c==null)u=void 0;else{let p={};for(let d of Object.keys(c))p[d]=Os(c[d]);u=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=Es(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return $t(this.accountsContext)}};_=A([Fd(),I(0,vs(Ze)),I(1,vs(rt))],_);import{Inject as Ns,Injectable as Sd}from"@nestjs/common";var Tt=class{zohoCrm;factoryConfig;static assertValidConfig(t){xe(t.zohoCrm)}};var Oe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=ha({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Vi(this.crmContext)}get upsertRecord(){return Hi(this.crmContext)}get updateRecord(){return zi(this.crmContext)}get deleteRecord(){return ji(this.crmContext)}get getRecordById(){return Wi(this.crmContext)}get getRecords(){return Bi(this.crmContext)}get searchRecords(){return tr(this.crmContext)}get searchRecordsPageFactory(){return qi(this.crmContext)}get getRelatedRecordsFunctionFactory(){return tt(this.crmContext)}get getEmailsForRecord(){return or(this.crmContext)}get getEmailsForRecordPageFactory(){return Ji(this.crmContext)}get getAttachmentsForRecord(){return rr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return $i(this.crmContext)}get uploadAttachmentForRecord(){return Xi(this.crmContext)}get downloadAttachmentForRecord(){return Yi(this.crmContext)}get deleteAttachmentFromRecord(){return Qi(this.crmContext)}get createNotes(){return nr(this.crmContext)}get deleteNotes(){return ra(this.crmContext)}get createNotesForRecord(){return ia(this.crmContext)}get getNotesForRecord(){return ir(this.crmContext)}get getNotesForRecordPageFactory(){return na(this.crmContext)}get executeRestApiFunction(){return ea(this.crmContext)}get createTagsForModule(){return sa(this.crmContext)}get deleteTag(){return ca(this.crmContext)}get getTagsForModule(){return ua(this.crmContext)}get addTagsToRecords(){return pa(this.crmContext)}get removeTagsFromRecords(){return la(this.crmContext)}};Oe=A([Sd(),I(0,Ns(Tt)),I(1,Ns(_))],Oe);import{ConfigModule as QZ,ConfigService as eF}from"@nestjs/config";import{Inject as ws,Injectable as Ad}from"@nestjs/common";var Ct=class{zohoRecruit;factoryConfig;static assertValidConfig(t){xe(t.zohoRecruit)}};var De=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=_i({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return ni(this.recruitContext)}get upsertRecord(){return ii(this.recruitContext)}get updateRecord(){return ai(this.recruitContext)}get deleteRecord(){return si(this.recruitContext)}get getRecordById(){return ci(this.recruitContext)}get getRecords(){return ui(this.recruitContext)}get searchRecords(){return Lo(this.recruitContext)}get searchRecordsPageFactory(){return pi(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return Ye(this.recruitContext)}get getEmailsForRecord(){return Go(this.recruitContext)}get getEmailsForRecordPageFactory(){return di(this.recruitContext)}get getAttachmentsForRecord(){return Ko(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return li(this.recruitContext)}get uploadAttachmentForRecord(){return hi(this.recruitContext)}get downloadAttachmentForRecord(){return mi(this.recruitContext)}get deleteAttachmentFromRecord(){return yi(this.recruitContext)}get createNotes(){return jo(this.recruitContext)}get deleteNotes(){return Zi(this.recruitContext)}get createNotesForRecord(){return Si(this.recruitContext)}get getNotesForRecord(){return Wo(this.recruitContext)}get getNotesForRecordPageFactory(){return Fi(this.recruitContext)}get executeRestApiFunction(){return gi(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return Ri(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Ho(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return Ci(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return zo(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return xi(this.recruitContext)}get createTagsForModule(){return ki(this.recruitContext)}get getTagsForModule(){return Ii(this.recruitContext)}get addTagsToRecords(){return Pi(this.recruitContext)}get removeTagsFromRecords(){return Ei(this.recruitContext)}};De=A([Ad(),I(0,ws(Ct)),I(1,ws(_))],De);import{ConfigModule as ZF,ConfigService as FF}from"@nestjs/config";import{Inject as Us,Injectable as bd}from"@nestjs/common";var xt=class{zohoSign;factoryConfig;static assertValidConfig(t){xe(t.zohoSign)}};var Zt=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=Ea({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return ya(this.signContext)}get getDocuments(){return ar(this.signContext)}get getDocumentsPageFactory(){return ga(this.signContext)}get getDocumentFormData(){return fa(this.signContext)}get retrieveFieldTypes(){return Ra(this.signContext)}get downloadPdf(){return Ta(this.signContext)}get downloadCompletionCertificate(){return Ca(this.signContext)}get createDocument(){return xa(this.signContext)}get updateDocument(){return Za(this.signContext)}get sendDocumentForSignature(){return Fa(this.signContext)}get extendDocument(){return Sa(this.signContext)}get deleteDocument(){return Aa(this.signContext)}};Zt=A([bd(),I(0,Us(xt)),I(1,Us(_))],Zt);import{ConfigModule as jF,ConfigService as WF}from"@nestjs/config";function Ls(e){return{...e,operationType:e.notifications.operation_type}}var Gs=Rn(e=>e.operationType),Ks=Cn({configurerForAccessor:e=>{let t=Tn(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 Vs="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Me=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as Md,Inject as _d,Post as vd,Req as Nd}from"@nestjs/common";import{Inject as Ed,Injectable as Od,Logger as Dd}from"@nestjs/common";import{createHmac as kd,timingSafeEqual as Id}from"node:crypto";var Pd="x-zs-webhook-signature";function Hs(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Pd],i={valid:!1};if(n){let a=r.toString("utf-8"),s=kd("sha256",t).update(a,"utf-8").digest("base64"),c=!1;try{let p=Buffer.from(n,"base64"),d=Buffer.from(s,"base64");p.length===d.length&&(c=Id(p,d))}catch{c=!1}let u;if(c)try{let p=JSON.parse(a);u=Ls(p)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var he=class{logger=new Dd("ZohoSignWebhookService");_verifier;handler=Gs();configure=Ks(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Hs({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)}};he=A([Od(),I(0,Ed(Me))],he);var _e=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};A([vd(),I(0,Nd()),I(1,Mn())],_e.prototype,"handleZohoSignWebhook",1),_e=A([Md("/webhook/zoho/sign"),I(0,_d(he))],_e);import{Module as wd}from"@nestjs/common";import{ConfigModule as Ud,ConfigService as Ld}from"@nestjs/config";function Gd(e){let t={zohoSignWebhook:{webhookSecret:e.get(Vs)}};return Me.assertValidConfig(t),t}var Yt=class{};Yt=A([wd({imports:[Ud],controllers:[_e],providers:[{provide:Me,inject:[Ld],useFactory:Gd},he],exports:[he]})],Yt);import{Inject as zs,Injectable as Kd}from"@nestjs/common";var Ft=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(xe(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Na({...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 Ua(this.deskContext)}get searchTickets(){return cr(this.deskContext)}get getTicketsForContact(){return La(this.deskContext)}get getTicketsForProduct(){return Ga(this.deskContext)}get getTicketMetrics(){return Ka(this.deskContext)}get getAgentsTicketsCount(){return Va(this.deskContext)}get getTicketsPageFactory(){return Ha(this.deskContext)}get searchTicketsPageFactory(){return za(this.deskContext)}get getDepartments(){return Wa(this.deskContext)}get getDepartmentById(){return Ba(this.deskContext)}get getContacts(){return pr(this.deskContext)}get getContactById(){return Ja(this.deskContext)}get getContactsByIds(){return $a(this.deskContext)}get getContactsPageFactory(){return Xa(this.deskContext)}get getTicketTags(){return Ya(this.deskContext)}get associateTicketTags(){return Qa(this.deskContext)}get dissociateTicketTag(){return es(this.deskContext)}get searchTags(){return ts(this.deskContext)}get getAllTags(){return os(this.deskContext)}get getTicketFollowers(){return rs(this.deskContext)}get addTicketFollowers(){return ns(this.deskContext)}get removeTicketFollowers(){return is(this.deskContext)}get getTicketAttachments(){return ss(this.deskContext)}get deleteTicketAttachment(){return cs(this.deskContext)}get getTicketComments(){return ps(this.deskContext)}get getTicketCommentById(){return ds(this.deskContext)}get createTicketComment(){return ls(this.deskContext)}get deleteTicketComment(){return hs(this.deskContext)}get getTicketTimer(){return ms(this.deskContext)}get performTicketTimerAction(){return ys(this.deskContext)}get getTicketTimeEntries(){return gs(this.deskContext)}get getTicketTimeEntryById(){return fs(this.deskContext)}get getTicketTimeEntrySummation(){return Rs(this.deskContext)}get getTicketThreads(){return lr(this.deskContext)}get getTicketThreadById(){return xs(this.deskContext)}get getTicketThreadsPageFactory(){return Zs(this.deskContext)}get getTicketActivities(){return hr(this.deskContext)}get getTicketActivitiesPageFactory(){return Fs(this.deskContext)}get getAgents(){return mr(this.deskContext)}get getAgentById(){return As(this.deskContext)}get getAgentsByIds(){return bs(this.deskContext)}get getMyInfo(){return ks(this.deskContext)}get getAgentsPageFactory(){return Is(this.deskContext)}};ve=A([Kd(),I(0,zs(Ft)),I(1,zs(_))],ve);import{ConfigModule as WS,ConfigService as BS}from"@nestjs/config";function Vd(e){return`${e.clientId}:${e.refreshToken}`}function nt(e){let t=Ds([Ms(),_s(ht())]),o=new Map;function r(p,d){let y=Vd(p),l=o.get(y),f;if(l)f=l;else{let g={zohoAccounts:{serviceAccessTokenKey:d,refreshToken:p.refreshToken,clientId:p.clientId,clientSecret:p.clientSecret,apiUrl:p.region??"us"}};f=new _(g,t),o.set(y,f)}return f}let n,i=mt(e,"recruit");if(i){let p=r(i,"recruit"),d={zohoRecruit:{apiUrl:i.apiMode}};n=new De(d,p)}let a,s=mt(e,"crm");if(s){let p=r(s,"crm"),d={zohoCrm:{apiUrl:s.apiMode}};a=new Oe(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 ve(d,p)}return{recruitApi:n,crmApi:a,deskApi:c}}ro([...to,/1000\.\w{20,}/g]);function js(e){let t;return e instanceof K?t={ok:!1,error:pe(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof qe?t={ok:!1,error:pe(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Je?t={ok:!1,error:pe(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof G?t={ok:!1,error:pe(e.message),code:"API_ERROR"}:t=no(e),t}Sr(e=>e instanceof K||e instanceof qe||e instanceof Je||e instanceof G?js(e):void 0);function m(e){console.log(JSON.stringify(js(e)))}var Ws={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"},Bs={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 Hd(e){let t;if(!e)t=void 0;else if(e.startsWith("http://")||e.startsWith("https://"))try{let r=new URL(e).searchParams.get("code");if(!r)throw new Error('No "code" parameter found in the provided URL.');t=r}catch(o){throw o instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`,{cause:o}):o}else t=e;return t}var zd={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:[...Nt],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 H(),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=Hd(e.code),u=e.token,p=Ws[a]??Ws.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 y={...d,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0},l=await W({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:y});h({success:!0,product:o,refreshToken:de(u),configSaved:!0,configuredProducts:X(l)})}else{let y=await W({shared:{...d,region:a,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0});h({success:!0,refreshToken:de(u),configSaved:!0,configuredProducts:X(y)})}}else if(c){let d=`${p}/oauth/v2/token`,y=new URLSearchParams({grant_type:"authorization_code",client_id:r,client_secret:n,redirect_uri:i,code:c}),f=await(await fetch(d,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:y.toString()})).json();if(f.error)throw new Error(`Token exchange failed: ${f.error}`);let g=f.refresh_token;if(!g)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:g},Z;o?Z=await W({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:{...R,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0}}):Z=await W({shared:{...R,region:a,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({step:2,success:!0,product:o??"shared",refreshToken:de(g),accessToken:f.access_token?de(f.access_token):null,scope:f.scope,configSaved:!0,configuredProducts:X(Z)})}else{let d=s.flatMap(l=>Bs[l]??[]);if(d.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Bs).join(", ")}`);let y=`${p}/oauth/v2/auth?scope=${d.join(",")}&client_id=${encodeURIComponent(r)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(i)}`;await W({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:y,redirectUri:i,scopes:d,credentialsSaved:!0,nextStep:'zoho-cli auth setup --code "PASTE_REDIRECT_URL_OR_AUTH_CODE"'})}}catch(t){m(t),process.exit(1)}}},jd={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:[...Nt],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 W({shared:(await H())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await W({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),h({saved:!0,product:t??"shared",configuredProducts:X(r)})}catch(t){m(t),process.exit(1)}}},Wd={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){return r?{clientId:r.clientId?de(r.clientId):void 0,clientSecret:r.clientSecret?de(r.clientSecret):void 0,refreshToken:r.refreshToken?de(r.refreshToken):void 0}:void 0};var e=o;let t=await H();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:X(t)})}catch(t){m(t),process.exit(1)}}},Bd={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await H();if(e){let t=X(e);if(t.length===0)h({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});else{let o=nt(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})}}else h({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"})}catch(e){m(e),process.exit(1)}}},qd={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Hn(),h({cleared:!0})}catch(e){m(e),process.exit(1)}}},qs={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(zd).command(jd).command(Wd).command(Bd).command(qd).demandCommand(1,"Please specify an auth subcommand."),handler:S};import{access as Jd,constants as $d}from"node:fs";import{dirname as Xd}from"node:path";var Js={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=[],t=await H();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=Xd(ht());if(await Yd(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=X(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=nt(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 Yd(e){return new Promise(t=>{Jd(e,$d.W_OK,o=>{t(!o)})})}var $s=On({notInitializedMessage:"CLI context not initialized. This is a bug."});function Xs(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await H();r||(m(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),X(r).length===0&&(m(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),$s.set(nt(r))}catch(r){m(r),process.exit(4)}}}function fr(e){return $s.require()}function B(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 q(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 ce(e){return Zo(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 Zo(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 Qd={nextInput:(e,t)=>{let o;if(t.info?.more_records){let r=e.page??1;o={...e,page:r+1}}else o=void 0;return o},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,r=t.data?.length??0,n;if(o<=0||r<o)n=void 0;else{let i=e.from??1;n={...e,from:i+o}}return n},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,r=t.data?.length??0;return o>0&&r>=o}};async function ue(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:r,adapter:Qd,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 el={command:"list",describe:"List records from a module",builder:e=>Qt(St(ce(D(e)))),handler:async e=>{try{let t=B(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await ue({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){m(t),process.exit(1)}}},tl={command:"get",describe:"Get a record by ID",builder:e=>Fe(D(e)),handler:async e=>{try{let o=await B(e).getRecordById({module:e.module,id:e.id});h(o)}catch(t){m(t),process.exit(1)}}},ol={command:"search",describe:"Search records in a module",builder:e=>ce(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=B(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 ue({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){m(t),process.exit(1)}}},rl={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=B(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});h(r)}catch(t){m(t),process.exit(1)}}},nl={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=B(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});h(r)}catch(t){m(t),process.exit(1)}}},il={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=B(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});h(r)}catch(t){m(t),process.exit(1)}}},al={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=B(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});h(r)}catch(t){m(t),process.exit(1)}}},sl={command:"emails",describe:"Get emails for a record",builder:e=>ce(Fe(D(e))),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ue({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){m(t),process.exit(1)}}},cl={command:"attachments",describe:"Get attachments for a record",builder:e=>ce(Fe(D(e))),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ue({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){m(t),process.exit(1)}}},Ys={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(el).command(tl).command(ol).command(rl).command(nl).command(il).command(al).command(sl).command(cl).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:S};var ul={command:"list",describe:"List records from a module",builder:e=>Qt(St(ce(D(e)),!0)),handler:async e=>{try{let t=q(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await ue({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){m(t),process.exit(1)}}},pl={command:"get",describe:"Get a record by ID",builder:e=>Fe(D(e)),handler:async e=>{try{let o=await q(e).getRecordById({module:e.module,id:e.id});h(o)}catch(t){m(t),process.exit(1)}}},dl={command:"search",describe:"Search records in a module",builder:e=>ce(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=q(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 ue({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){m(t),process.exit(1)}}},ll={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=q(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});h(r)}catch(t){m(t),process.exit(1)}}},hl={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=q(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});h(r)}catch(t){m(t),process.exit(1)}}},ml={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=q(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});h(r)}catch(t){m(t),process.exit(1)}}},yl={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=q(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});h(r)}catch(t){m(t),process.exit(1)}}},gl={command:"emails",describe:"Get emails for a record",builder:e=>ce(Fe(D(e))),handler:async e=>{try{let t=q(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ue({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){m(t),process.exit(1)}}},fl={command:"attachments",describe:"Get attachments for a record",builder:e=>St(ce(Fe(D(e))),!0),handler:async e=>{try{let t=q(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await ue({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){m(t),process.exit(1)}}},Qs={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(ul).command(pl).command(dl).command(ll).command(hl).command(ml).command(yl).command(gl).command(fl).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:S};var Rl={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){m(t),process.exit(1)}}},Tl={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){m(t),process.exit(1)}}},Cl={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){m(t),process.exit(1)}}},xl={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){m(t),process.exit(1)}}},Zl={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){m(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){m(t),process.exit(1)}}},ec={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Rl).command(Tl).command(Cl).command(xl).command(Zl).command(Fl).demandCommand(1),handler:S};var Sl={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){m(t),process.exit(1)}}},Al={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){m(t),process.exit(1)}}},tc={command:"departments",describe:"Desk department operations",builder:e=>e.command(Sl).command(Al).demandCommand(1),handler:S};var bl={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){m(t),process.exit(1)}}},kl={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){m(t),process.exit(1)}}},oc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(bl).command(kl).demandCommand(1),handler:S};var Il={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){m(t),process.exit(1)}}},Pl={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){m(t),process.exit(1)}}},El={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){m(t),process.exit(1)}}},rc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(Il).command(Pl).command(El).demandCommand(1),handler:S};var Ol={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){m(t),process.exit(1)}}},Dl={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){m(t),process.exit(1)}}},Ml={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){m(t),process.exit(1)}}},_l={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){m(t),process.exit(1)}}},vl={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){m(t),process.exit(1)}}},nc={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Ol).command(Dl).command(Ml).command(_l).command(vl).demandCommand(1),handler:S};var Nl={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){m(t),process.exit(1)}}},wl={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){m(t),process.exit(1)}}},Ul={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){m(t),process.exit(1)}}},Ll={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){m(t),process.exit(1)}}},ic={command:"comments",describe:"Desk comment operations",builder:e=>e.command(Nl).command(wl).command(Ul).command(Ll).demandCommand(1),handler:S};var Gl={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){m(t),process.exit(1)}}},Kl={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){m(t),process.exit(1)}}},ac={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(Gl).command(Kl).demandCommand(1),handler:S};var Vl={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){m(t),process.exit(1)}}},Hl={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){m(t),process.exit(1)}}},zl={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){m(t),process.exit(1)}}},sc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(Vl).command(Hl).command(zl).demandCommand(1),handler:S};var jl={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){m(t),process.exit(1)}}},Wl={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){m(t),process.exit(1)}}},Bl={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){m(t),process.exit(1)}}},ql={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){m(t),process.exit(1)}}},cc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(jl).command(Wl).command(Bl).command(ql).demandCommand(1),handler:S};var Jl={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){m(t),process.exit(1)}}},$l={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){m(t),process.exit(1)}}},uc={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(Jl).command($l).demandCommand(1),handler:S};var Xl={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){m(t),process.exit(1)}}},pc={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Xl).demandCommand(1),handler:S};var dc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(ec).command(tc).command(oc).command(rc).command(nc).command(ic).command(ac).command(sc).command(cc).command(uc).command(pc).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:S};var lc={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=B(e).recruitContext;break;case"crm":n=q(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){m(t),process.exit(1)}}};var eh=Gn({cliName:"zoho-cli",loadOutputConfig:async()=>(await H())?.output,mergeOutputConfig:e=>W({output:e}),clearOutputConfig:Vn}),th=[Ys,Qs,dc,lc],hc=[qs,eh,Js];function oh(e){return e.command.split(" ")[0]}var mc=new Set(hc.map(oh)),rh=Ln({cliName:"zoho-cli",skipCommands:mc,loadOutputConfig:async()=>(await H())?.output,saveCommandOutputConfig:async(e,t)=>{await W({output:{commands:{[e]:t}}})}});async function nh(){try{await Yl(Ql(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([Xs(mc),rh],!0).command(hc).command(th).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){m(e),process.exit(1)}}await nh();
8
+ `:void 0;p({mainContent:v,pickContent:V,append:b})})};s={mainPath:i,pickPath:a,writePage:g=>{let Z=o==="concat"&&!(c===0);t==="raw"?d(g,Z):t==="page_by_line"?y(g,Z):m(g,Z),c+=1},close:()=>{}}}else s={mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};return s}async function Sp(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 m of d.data??[])c.collectedRecords.push(m);c.hasMorePagesAvailable=n.hasMorePagesAvailable(u,d);let y=n.nextInput(u,d);if(!y)break;u=y}return c}function Ap(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:Se(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?Se(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)),c;if(s<=1)c={handled:!1,result:await o(t)};else{let u=At();u.dumpDir||console.error("[cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let p=Kn({dumpOutput:i,dumpMerge:a}),d;try{d=await Sp({initialInput:t,requestedPages:s,fetchPage:o,adapter:r,stream:p,shouldCollectPages:n==="pages",shouldCollectRecords:n==="merged_page"})}finally{p.close()}let y={pagesFetched:d.pagesFetched,totalRecords:d.totalRecords,hasMorePagesAvailable:d.hasMorePagesAvailable,dumpFile:p.mainPath??null};p.pickPath&&(y.dumpFilePick=p.pickPath),Ap({multiplePagesOutput:n,summaryMeta:y,state:d,adapter:r,pickFilter:u.pick}),c={handled:!0}}return c}import dh from"yargs";import{hideBin as lh}from"yargs/helpers";import{writeFile as bp,mkdirSync as kp}from"node:fs";import{join as ko}from"node:path";import{homedir as Ip}from"node:os";var Nt=["recruit","crm","desk"];function Io(){return ko(Ip(),".zoho-cli")}function lt(){return ko(Io(),"config.json")}function ht(){return ko(Io(),".tokens.json")}function Ie(e,t){return(t?process.env[`ZOHO_${t}_${e}`]:void 0)??process.env[`ZOHO_${e}`]}async function H(){let e=lt(),t=await me(e),o=Ie("ACCOUNTS_CLIENT_ID"),r=Ie("ACCOUNTS_CLIENT_SECRET"),n=Ie("ACCOUNTS_REFRESH_TOKEN"),i=o&&r&&n,a;if(!t&&!i)a=void 0;else{let s={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:Ie("ACCOUNTS_URL")??t?.shared?.region,apiMode:Ie("API_URL")??t?.shared?.apiMode},c=u=>{let p=u.toUpperCase(),d=Ie("API_URL",p),y=u==="desk"?Ie("DESK_ORG_ID"):void 0,m=t?.[u],T=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],g=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],f=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`],Z=T||g||f,F;return!m&&!Z&&!y?F=void 0:F={clientId:T??m?.clientId,clientSecret:g??m?.clientSecret,refreshToken:f??m?.refreshToken,apiUrl:d??m?.apiUrl,orgId:y??m?.orgId},F};a={shared:s,recruit:c("recruit")??t?.recruit,crm:c("crm")??t?.crm,desk:c("desk")??t?.desk,output:t?.output}}return a}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,s;return!n||!i||!a?s=void 0:s={clientId:n,clientSecret:i,refreshToken:a,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId},s}async function Pp(e){let t=lt();return kp(Io(),{recursive:!0}),new Promise((o,r)=>{bp(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function te(e){let t=await H(),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 Pp(o),o}async function Vn(){await te({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function Hn(){let e=lt(),t=ht();await ut(e),await ut(t)}function oe(e){return Nt.filter(t=>{let o=mt(e,t);return o!=null&&(t!=="desk"||o.orgId!=null)})}import{Inject as vs,Injectable as Sd}from"@nestjs/common";function je(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function N(e,t){return Ve({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:Zn(o),per_page:n.maxItemsPerPage??r.per_page}}})}function wt(e){let t;switch(e){case"sandbox":t="https://recruitsandbox.zoho.com/recruit";break;case"production":t="https://recruit.zoho.com/recruit";break;default:t=e;break}return t}var We="Candidates",zn="Job_Openings",Ut="Notes",jn="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 Wn=Qr({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function Po(e){let t=Wn(e.value);return`(${e.field}:${e.filter}:${t})`}var Bn=Lt;import{BaseError as Vp}from"make-error";import{BaseError as Op}from"make-error";var Dp="__internal_data_array_blank_error";function Mp(e){return Array.isArray(e?.data)}var $e="success";function $(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var ge=class extends Op{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},G=class extends ge{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},Be=class extends G{constructor(t,o){super({code:Dp,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function re(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof Be&&!o||(r instanceof G?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof ge?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ne(e,t){return(o,r=t,n)=>async(i,a)=>{try{return await o(i,a)}catch(s){if(s instanceof Ke){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function ie(e){return(t,o)=>{if(t?.error!=null){let n=new Ke(o),i=e(t,n);if(i)throw i}return t}}var _p="INTERNAL_ERROR",vp="INVALID_TOKEN",K=class extends G{},qn="FAILURE",Eo=class extends G{},Np="4834",qe=class extends G{},wp="INVALID_QUERY",Oo=class extends G{get details(){return this.error.details}},Kt="MANDATORY_NOT_FOUND",fe="DUPLICATE_DATA",Vt="INVALID_DATA",Up="TOO_MANY_REQUESTS",Jn=429,Lp="X-RATELIMIT-LIMIT",Gp="X-RATELIMIT-REMAINING",Kp="X-RATELIMIT-RESET",$n=100,Xn=Ae;function Do(e){let t=e.get(Lp),o=e.get(Gp),r=e.get(Kp),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 Je=class extends G{get headerDetails(){return Do(this.responseError.response.headers)}};function ae(e,t){let o;if(Mp(e))o=new Be(e,t);else{let r=de(e,t);if(r){let n=$(r);switch(n.code){case _p:o=new Eo(n,e,t);break;case vp:o=new K(n,e,t);break;case Np:o=new qe(n,e,t);break;case wp:o=new Oo(n,e,t);break;case Up:o=new Je(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 Yn="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}},Xe=class extends ge{},_o=class extends Xe{},vo=class extends Xe{},Ht=class extends Xe{get invalidFieldDetails(){return this.error.details}},No=class extends Ht{};function Qn(e){let t;switch(e.code){case Vt:{let o=new Ht(e);o.invalidFieldDetails.id?t=new No(e):t=o;break}case Kt:t=new _o(e);break;case fe:t=new vo(e);break;default:t=new Xe(e);break}return t}function ei(e,t){return o=>{if(!o?.data?.length)throw new Mo(e,t);return o}}var Hp=re("ZohoRecruit");async function zp(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ti(t,e)),o}function ti(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var oi=ie(ti),ri=ne(zp,Hp);import{BaseError as jp}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=se(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw Qn(p[0].result);c=u[0].result.details}return c}))}function ni(e){return Uo(e,"","POST")}function ii(e){return Uo(e,"/upsert","POST")}function ai(e){return Uo(e,"","PUT")}function si(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${R({ids:t,wf_trigger:r})}`,M("DELETE")).then(Wp)}function ci(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,M("GET")).then(ei(t.module)).then(o=>o.data[0])}function ui(e){return(t=>e.fetchJson(`/v2/${t.module}?${fi(t).toString()}`,M("GET")))}function Lo(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Bn(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 fi(r)}return o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,M("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function pi(e){return N(Lo(e))}function Ye(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?je():i))}}function Go(e){return Ye(e)({targetModule:jn})}function di(e){return N(Go(e))}function Ko(e){return Ye(e)({targetModule:yt})}function li(e){return N(Ko(e))}var ER=20*1024*1024;function hi(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}?${R(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}&${R({attachment_url:i}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function mi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function yi(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${yt}/${t.attachment_id}`,{method:"DELETE"})}var wo=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 gi(e){return t=>{let r=R(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?wt(t.apiUrl):""}${a}`;return e.fetchJson(c,M("POST")).then(u=>{if(u.code!=="success")throw new wo(u);return u.details})}}function fi(...e){return R(e,{omitKeys:"module"})}function Vo(...e){return R(e,{omitKeys:["id","module"]})}function M(e,t){return{method:e,body:t??void 0}}function Wp(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===$e?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function se(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===$e?o.push({input:i,result:s}):r.push({input:i,result:s})}),{successItems:o,errorItems:r}}function Ri(e){return t=>e.fetchJson(`/v2/${We}/actions/associate`,M("PUT",{data:C(t)})).then(o=>{let r=o.data.map(()=>t),n=se(r,o.data),{included:i,excluded:a}=Ue(n.errorItems,s=>s.result.code===qn&&s.result.details.error[0].code===Yn);return{...n,errorItems:a,alreadyAssociatedErrorItems:i,allErrorItems:n.errorItems}})}function Ti(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${Vo(t).toString()}`,M("GET")).then(o=>o??je())}function Ho(e){let t=Ti(e);return o=>t({...o,module:We})}function Ci(e){return N(Ho(e))}function zo(e,t=zn){let o=Ti(e);return r=>o({...r,module:t})}function xi(e){return N(zo(e))}function jo(e){return t=>e.fetchJson(`/v2/${Ut}`,M("POST",{data:t.data})).then(o=>se(C(t.data),o.data))}function Zi(e){return t=>e.fetchJson(`/v2/${Ut}?${R({ids:t.ids})}`,M("DELETE")).then(o=>se(C(t.ids),o.data))}function Wo(e){return Ye(e)({targetModule:Ut})}function Fi(e){return N(Wo(e))}function Si(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 ki(e){return t=>e.fetchJson(`/v2/settings/tags?${R({module:t.module})}`,M("POST",{tags:C(t.tags)})).then(o=>{let r=se(C(t.tags),o.tags),{included:n,excluded:i}=Ue(r.errorItems,a=>a.result.code===fe);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Ii(e){return t=>e.fetchJson(`/v2/settings/tags?${R({module:t.module,my_tags:t.my_tags})}`,M("GET")).then(o=>({...o,data:o.tags}))}var Ai=100;function Pi(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>Ai)throw new Error(`Cannot add tags to more than ${Ai} records at once.`);return e.fetchJson(`/v2/${We}/actions/add_tags?${R({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var bi=100;function Ei(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>bi)throw new Error(`Cannot remove tags from more than ${bi} records at once.`);return e.fetchJson(`/v2/${We}/actions/remove_tags?${R({tag_names:t.tag_names,ids:t.ids})}`,M("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var Bp="invalid_code",qp="invalid_client",Bo=class extends J{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},Qe=class extends J{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},Jp=re("ZohoAccounts");async function $p(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Oi(t,e)),o}function Oi(e,t){let o,r=e.error;if(r){let n=$(r);switch(n.code){case Bp:case qp:o=new Bo(n.code);break;default:o=ae(e,t);break}}return o}var Di=ie(Oi),Mi=ne($p,Jp);function Re(e){return async()=>{let t=await e();if(!t.accessToken)throw new Qe;return t.accessToken}}var Xp=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??Xp,r=e.maxRateLimit??$n,n=e.resetPeriod??Xn;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=fn(a);return Pn({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,y=!1;if(p){let{remaining:m,limit:T,resetAt:g}=p;if(T!=null&&T!==r){let f=i(T,g??void 0);s.setConfig(f,!1)}if(s.setRemainingLimit(m),g&&s.setNextResetAt(g),y=!0,c.status===Jn){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(y),d}})}function Te(e){return qo({...e,readRateLimitDetails:Yp})}function Yp(e){let t=Do(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function _i(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=Te(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.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=wt(a.apiUrl),c=i({apiUrl:s}),u=ri(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:oi,handleFetchJsonParseErrorFunction:Y});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function zt(e){let t;switch(e){case"sandbox":t="https://crmsandbox.zoho.com/crm";break;case"production":t="https://www.zohoapis.com/crm";break;default:t=e;break}return t}var jt="Notes",vi="Emails",gt="Attachments";var Ni=Lt;import{BaseError as Qp}from"make-error";var Jo=class extends Qp{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},et=class extends ge{},$o=class extends et{},Xo=class extends et{},Wt=class extends et{get invalidFieldDetails(){return this.error.details}},Yo=class extends Wt{};function wi(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 fe:t=new Xo(e);break;default:t=new et(e);break}return t}function Ui(e,t){return o=>{if(!o?.data?.length)throw new Jo(e,t);return o}}var ed=re("ZohoCrm",{logDataArrayErrors:!1});async function td(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Li(t,e)),o}function Li(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var Gi=ie(Li),Ki=ne(td,ed);import{BaseError as od}from"make-error";function er(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,w(o,{data:C(r)})).catch(oa).then(i=>{let a=Array.isArray(r),s=Ce(C(r),i.data),c;if(a)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw wi(p[0].result);c=u[0].result.details}return c}))}function Vi(e){return er(e,"","POST")}function Hi(e){return er(e,"/upsert","POST")}function zi(e){return er(e,"","PUT")}function ji(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${R({ids:t,wf_trigger:r})}`,w("DELETE")).catch(oa).then(nd)}function Wi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,w("GET")).then(Ui(t.module)).then(o=>o.data[0])}function Bi(e){return(t=>e.fetchJson(`/v8/${t.module}?${ta(t).toString()}`,w("GET")))}function tr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Ni(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 ta(r)}return o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,w("GET")).then(r=>r??{data:[],info:{more_records:!1}})}function qi(e){return N(tr(e))}function tt(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${rd(n,n.filter).toString()}`,w("GET")).then(i=>i??(r!==!1?je():i))}}function or(e){let t=tt(e)({targetModule:vi});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function Ji(e){return N(or(e))}function rr(e){return tt(e)({targetModule:gt})}function $i(e){return N(rr(e))}var HT=20*1024*1024;function Xi(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}?${R(i).toString()}`,s=new FormData;return s.append("file",n),e.fetch(a,{method:"POST",headers:{"Content-Type":""},body:s})}}function Yi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"GET"}).then(Pt)}function Qi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${gt}/${t.attachment_id}`,{method:"DELETE"})}var Qo=class extends od{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function ea(e){return t=>{let r=R(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?zt(t.apiUrl):""}${a}`;return e.fetchJson(c,w("POST")).then(u=>{if(u.code!=="success")throw new Qo(u);return u.details})}}function ta(...e){return R(e,{omitKeys:"module"})}function rd(...e){return R(e,{omitKeys:["id","module"]})}function w(e,t){return{method:e,body:t??void 0}}function oa(e){let t;if(e instanceof Be)t={data:e.errorDataArray};else throw e;return t}function nd(e){let{data:t}=e,o=[],r=[];return t.forEach(i=>{i.status===$e?o.push(i):r.push(i)}),{...e,successItems:o,errorItems:r}}function Ce(e,t){let o=[],r=[];return e.forEach((i,a)=>{let s=t[a];s.status===$e?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}`,w("POST",{data:t.data})).then(o=>Ce(C(t.data),o.data))}function ra(e){return t=>e.fetchJson(`/v2/${jt}?${R({ids:t.ids})}`,w("DELETE")).then(o=>Ce(C(t.ids),o.data))}function ir(e){return tt(e)({targetModule:jt})}function na(e){return N(ir(e))}function ia(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 sa(e){return t=>e.fetchJson(`/v8/settings/tags?${R({module:t.module})}`,w("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=Ce(C(t.tags),o.tags),{included:n,excluded:i}=Ue(r.errorItems,a=>a.result.code===fe);return{...r,errorItems:i,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function ca(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,w("DELETE")).then(o=>o.tags)}function ua(e){return t=>e.fetchJson(`/v8/settings/tags?${R({module:t.module,my_tags:t.my_tags})}`,w("GET")).then(o=>({...o,data:o.tags}))}var aa=100;function pa(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,w("POST",da(t))).then(o=>{let r=o.data.map(()=>t);return Ce(r,o.data)})}function da(e){if(Array.isArray(e.ids)&&e.ids.length>aa)throw new Error(`Cannot add/remove tags from more than ${aa} 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 la(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,w("POST",da(t))).then(o=>{let r=o.data.map(()=>t);return Ce(r,o.data)})}function ha(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=Te(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.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=zt(a.apiUrl),c=i({apiUrl:s}),u=Ki(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:Gi,handleFetchJsonParseErrorFunction:Y});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function ma(e,t){return Ve({...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 Pe(e,t){return{method:e,body:t??void 0}}function ya(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,Pe("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)}},Pe("GET"))}}function ga(e){let t=ar(e);return ma(t)}function fa(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,Pe("GET"))}function Ra(e){return()=>e.fetchJson("/fieldtypes",Pe("GET"))}function Ta(e){return({requestId:t,...o})=>{let n=R(o).toString(),i=n?`?${n}`:"",a=`/requests/${t}/pdf${i}`;return e.fetch(a,{method:"GET"})}}function Ca(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function xa(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 Za(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,Pe("PUT",{requests:o}))}function Fa(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,Pe("POST",r))}}function Sa(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,Pe("PUT",{expire_by:o}))}function Aa(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=R(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 ba(e){let t;switch(e){case"sandbox":t="https://signsandbox.zoho.com/api/v1";break;case"production":t="https://sign.zoho.com/api/v1";break;default:t=e;break}return t}var id=re("ZohoSign",{logDataArrayErrors:!1});async function ad(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ka(t,e)),o}function ka(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var Ia=ie(ka),Pa=ne(ad,id);function Ea(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=Te(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.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=ba(a.apiUrl),c=i({apiUrl:s}),u=Pa(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:Ia,handleFetchJsonParseErrorFunction:Y});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Oa(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var sd=re("ZohoDesk",{logDataArrayErrors:!1});async function cd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=Da(t,e)),o}function Da(e,t){let o,r=de(e,t);if(r)switch($(r).code){default:o=ae(e,t);break}return o}var Ma=ie(Da),_a=ne(cd,sd);var ud="X-Rate-Limit-Remaining-v3",pd="Retry-After",dd=200;function ld(e){let t=e.get(ud),o;if(t!=null){let r=Number(t),n,i=e.get(pd);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 va(e){return qo({maxRateLimit:dd,...e,readRateLimitDetails:ld})}function Na(e){let{accountsContext:t}=e,o=Re(t.loadAccessToken),r=va(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:i=a=>ee.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=Oa(a.apiUrl),c=i({apiUrl:s,orgId:a.orgId}),u=_a(c,n,m=>{m instanceof K&&t.loadAccessToken.resetAccessToken()}),p=Q(u,{interceptJsonResponse:Ma,handleFetchJsonParseErrorFunction:Y});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...a,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var wa=25;function X(e,t){return Ve({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=wa}},buildInputForNextPage:function(o,r,n){let i=n.maxItemsPerPage??r.limit??wa,s=(r.from??1)+i;return{...r,from:s,limit:i}}})}function Ee(e,t){return{method:e,body:t??void 0}}function ot(e,t){return R(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=ot([{...r,include:Bt(o)}]);return e.fetchJson(`/tickets?${n}`,Ee("GET")).then(i=>i??{data:[]})}}function Ua(e){return t=>{let{ticketId:o,include:r}=t,i=ot([{include:Bt(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/tickets/${o}${a}`,Ee("GET"))}}function cr(e){return t=>{let o=ot([t]);return e.fetchJson(`/tickets/search?${o}`,Ee("GET")).then(r=>r??{data:[]})}}function La(e){return t=>{let{contactId:o,include:r,...n}=t,i=ot([{...n,include:Bt(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function Ga(e){return t=>{let{productId:o,include:r,...n}=t,i=ot([{...n,include:Bt(r)}]);return e.fetchJson(`/products/${o}/tickets?${i}`,Ee("GET")).then(a=>a??{data:[]})}}function Ka(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ee("GET"))}function Va(e){return t=>{let o=ot([{agentIds:P(C(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ee("GET"))}}function Ha(e){return X(sr(e))}function za(e){return X(cr(e))}function ja(e){return{method:e}}function Wa(e){return t=>{let o=R([t]);return e.fetchJson(`/departments?${o}`,ja("GET")).then(r=>r??{data:[]})}}function Ba(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,ja("GET"))}function ur(e){return{method:e}}function qa(e){let t;return e&&(t=P(C(e))),t}function pr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:qa(o)}]);return e.fetchJson(`/contacts?${n}`,ur("GET")).then(i=>i??{data:[]})}}function Ja(e){return t=>{let{contactId:o,include:r}=t,i=R([{include:qa(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/contacts/${o}${a}`,ur("GET"))}}function $a(e){return t=>{let o=R([{contactIds:P(C(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,ur("GET")).then(r=>r??[])}}function Xa(e){return X(pr(e))}function ft(e,t){return{method:e,body:t??void 0}}function Ya(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,ft("GET")).then(o=>o??[])}function Qa(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 es(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,ft("DELETE"))}function ts(e){return t=>{let o=R([t]);return e.fetchJson(`/tags/search?${o}`,ft("GET")).then(r=>r??{data:[]})}}function os(e){return t=>{let o=R([t]);return e.fetchJson(`/ticketTags?${o}`,ft("GET")).then(r=>r??{data:[]})}}function dr(e,t){return{method:e,body:t??void 0}}function rs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("GET")).then(o=>o??[])}function ns(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("POST",o))}}function is(e){return t=>{let o={ids:C(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,dr("DELETE",o))}}function as(e,t){return{method:e,body:t??void 0}}function hd(e){let t;return e&&(t=P(C(e))),t}function ss(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:hd(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${i}`,as("GET")).then(a=>a??{data:[]})}}function cs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,as("DELETE"))}function qt(e,t){return{method:e,body:t??void 0}}function us(e){let t;return e&&(t=P(C(e))),t}function ps(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:us(r)}]);return e.fetchJson(`/tickets/${o}/comments?${i}`,qt("GET")).then(a=>a??{data:[]})}}function ds(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,a=R([{include:us(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,qt("GET"))}}function ls(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,qt("POST",r))}}function hs(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 ms(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,Rt("GET"))}function ys(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,Rt("POST",r))}}function gs(e){return t=>{let{ticketId:o,...r}=t,n=R([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,Rt("GET")).then(i=>i??{data:[]})}}function fs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,Rt("GET"))}function Rs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,Rt("GET"))}function Ts(e){return{method:e}}function Cs(e){let t;return e&&(t=P(C(e))),t}function lr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:Cs(r)}]);return e.fetchJson(`/tickets/${o}/threads?${i}`,Ts("GET")).then(a=>a??{data:[]})}}function xs(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,a=R([{include:Cs(n)}]).toString(),s=a?"?"+a:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,Ts("GET"))}}function Zs(e){return X(lr(e))}function md(e){return{method:e}}function yd(e){let t;return e&&(t=P(C(e))),t}function hr(e){return t=>{let{ticketId:o,include:r,...n}=t,i=R([{...n,include:yd(r)}]);return e.fetchJson(`/tickets/${o}/activities?${i}`,md("GET")).then(a=>a??{data:[]})}}function Fs(e){return X(hr(e))}function Jt(e){return{method:e}}function Ss(e){let t;return e&&(t=P(C(e))),t}function mr(e){return t=>{let{include:o,...r}=t,n=R([{...r,include:Ss(o)}]);return e.fetchJson(`/agents?${n}`,Jt("GET")).then(i=>i??{data:[]})}}function As(e){return t=>{let{agentId:o,include:r}=t,i=R([{include:Ss(r)}]).toString(),a=i?"?"+i:"";return e.fetchJson(`/agents/${o}${a}`,Jt("GET"))}}function bs(e){return t=>{let o=R([{agentIds:P(C(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,Jt("GET")).then(r=>r?.data??[])}}function ks(e){return()=>e.fetchJson("/myinfo",Jt("GET"))}function Is(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=R({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:a??n});return e.fetchJson(`/oauth/v2/token?${p}`,gd("POST"))}}function gd(e,t){return{method:e,body:t}}var fd="https://accounts.zoho.com";function Ps(e){let t;return e==="us"?t=fd:t=e,t}function Es(e){let t=Te(),{logZohoServerErrorFunction:o,fetchFactory:r=n=>ee.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=Ps(n.apiUrl??"us"),a=r({apiUrl:i}),s=Mi(a,o),c=Q(s,{interceptJsonResponse:Di,handleFetchJsonParseErrorFunction:Y}),u=async()=>{let m=Date.now(),{access_token:T,api_domain:g,scope:f,expires_in:Z}=await $t(d)();return{accessToken:T,apiDomain:g,expiresIn:Z,expiresAt:new Date(m+Z*L),scope:f}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=Rd({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:i}};return{accountsContext:d}}}function Rd(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??Ae,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 Qe("Token Refresh Failed")}try{await o?.updateCachedToken(i)}catch{}}return i};return s.resetAccessToken=a,s}function xe(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Ze=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 Td}from"@nestjs/common";var rt=class{};rt=A([Td()],rt);function Cd(e){return{load:async()=>{let t=await e.loadCachedToken().catch(()=>{});return t!=null&&!yn(t)?t:void 0},update:t=>e.updateCachedToken(t),clear:()=>e.clearCachedToken()}}function xd(e,t){return e.updateCachedToken(t).then(()=>null).catch(o=>[e,o])}function Zd(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function Ds(e,t){let o=[...e],r=typeof t=="function"?t:t!==!1?Zd: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(Cd),c=Yr(s);return{loadCachedToken:()=>c.load(),updateCachedToken:async u=>{let p=await Promise.allSettled(a.map(d=>xd(d,u)));if(r!=null){let d=he(p.map(y=>y.value));d.length&&r(d)}},clearCachedToken:async()=>{await Promise.allSettled(a.map(u=>u.clearCachedToken()))}}}return{loadZohoAccessTokenCache:n}}function Ms(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=$r(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 Fd=".tmp/zoho-access-tokens.json";function Os(e){let t;if(e==null||typeof e!="object")t=void 0;else{let o=e,r=o.expiresAt,n=r!=null&&!(r instanceof Date)?new Date(r):r;t={...o,expiresAt:n}}return t}function _s(e=Fd,t=!0){let o=wn({filePath:e,reviver:Os}),r=t?Xr(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),u;if(c==null)u=void 0;else{let p={};for(let d of Object.keys(c))p[d]=Os(c[d]);u=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=Es(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return $t(this.accountsContext)}};_=A([Sd(),I(0,vs(Ze)),I(1,vs(rt))],_);import{Inject as Ns,Injectable as Ad}from"@nestjs/common";var Tt=class{zohoCrm;factoryConfig;static assertValidConfig(t){xe(t.zohoCrm)}};var Oe=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=ha({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Vi(this.crmContext)}get upsertRecord(){return Hi(this.crmContext)}get updateRecord(){return zi(this.crmContext)}get deleteRecord(){return ji(this.crmContext)}get getRecordById(){return Wi(this.crmContext)}get getRecords(){return Bi(this.crmContext)}get searchRecords(){return tr(this.crmContext)}get searchRecordsPageFactory(){return qi(this.crmContext)}get getRelatedRecordsFunctionFactory(){return tt(this.crmContext)}get getEmailsForRecord(){return or(this.crmContext)}get getEmailsForRecordPageFactory(){return Ji(this.crmContext)}get getAttachmentsForRecord(){return rr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return $i(this.crmContext)}get uploadAttachmentForRecord(){return Xi(this.crmContext)}get downloadAttachmentForRecord(){return Yi(this.crmContext)}get deleteAttachmentFromRecord(){return Qi(this.crmContext)}get createNotes(){return nr(this.crmContext)}get deleteNotes(){return ra(this.crmContext)}get createNotesForRecord(){return ia(this.crmContext)}get getNotesForRecord(){return ir(this.crmContext)}get getNotesForRecordPageFactory(){return na(this.crmContext)}get executeRestApiFunction(){return ea(this.crmContext)}get createTagsForModule(){return sa(this.crmContext)}get deleteTag(){return ca(this.crmContext)}get getTagsForModule(){return ua(this.crmContext)}get addTagsToRecords(){return pa(this.crmContext)}get removeTagsFromRecords(){return la(this.crmContext)}};Oe=A([Ad(),I(0,Ns(Tt)),I(1,Ns(_))],Oe);import{ConfigModule as lF,ConfigService as hF}from"@nestjs/config";import{Inject as ws,Injectable as bd}from"@nestjs/common";var Ct=class{zohoRecruit;factoryConfig;static assertValidConfig(t){xe(t.zohoRecruit)}};var De=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=_i({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return ni(this.recruitContext)}get upsertRecord(){return ii(this.recruitContext)}get updateRecord(){return ai(this.recruitContext)}get deleteRecord(){return si(this.recruitContext)}get getRecordById(){return ci(this.recruitContext)}get getRecords(){return ui(this.recruitContext)}get searchRecords(){return Lo(this.recruitContext)}get searchRecordsPageFactory(){return pi(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return Ye(this.recruitContext)}get getEmailsForRecord(){return Go(this.recruitContext)}get getEmailsForRecordPageFactory(){return di(this.recruitContext)}get getAttachmentsForRecord(){return Ko(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return li(this.recruitContext)}get uploadAttachmentForRecord(){return hi(this.recruitContext)}get downloadAttachmentForRecord(){return mi(this.recruitContext)}get deleteAttachmentFromRecord(){return yi(this.recruitContext)}get createNotes(){return jo(this.recruitContext)}get deleteNotes(){return Zi(this.recruitContext)}get createNotesForRecord(){return Si(this.recruitContext)}get getNotesForRecord(){return Wo(this.recruitContext)}get getNotesForRecordPageFactory(){return Fi(this.recruitContext)}get executeRestApiFunction(){return gi(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return Ri(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Ho(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return Ci(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return zo(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return xi(this.recruitContext)}get createTagsForModule(){return ki(this.recruitContext)}get getTagsForModule(){return Ii(this.recruitContext)}get addTagsToRecords(){return Pi(this.recruitContext)}get removeTagsFromRecords(){return Ei(this.recruitContext)}};De=A([bd(),I(0,ws(Ct)),I(1,ws(_))],De);import{ConfigModule as vF,ConfigService as NF}from"@nestjs/config";import{Inject as Us,Injectable as kd}from"@nestjs/common";var xt=class{zohoSign;factoryConfig;static assertValidConfig(t){xe(t.zohoSign)}};var Zt=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=Ea({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return ya(this.signContext)}get getDocuments(){return ar(this.signContext)}get getDocumentsPageFactory(){return ga(this.signContext)}get getDocumentFormData(){return fa(this.signContext)}get retrieveFieldTypes(){return Ra(this.signContext)}get downloadPdf(){return Ta(this.signContext)}get downloadCompletionCertificate(){return Ca(this.signContext)}get createDocument(){return xa(this.signContext)}get updateDocument(){return Za(this.signContext)}get sendDocumentForSignature(){return Fa(this.signContext)}get extendDocument(){return Sa(this.signContext)}get deleteDocument(){return Aa(this.signContext)}};Zt=A([kd(),I(0,Us(xt)),I(1,Us(_))],Zt);import{ConfigModule as nS,ConfigService as iS}from"@nestjs/config";function Ls(e){return{...e,operationType:e.notifications.operation_type}}var Gs=Rn(e=>e.operationType),Ks=Cn({configurerForAccessor:e=>{let t=Tn(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 Vs="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",Me=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{Controller as _d,Inject as vd,Post as Nd,Req as wd}from"@nestjs/common";import{Inject as Od,Injectable as Dd,Logger as Md}from"@nestjs/common";import{createHmac as Id,timingSafeEqual as Pd}from"node:crypto";var Ed="x-zs-webhook-signature";function Hs(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[Ed],i={valid:!1};if(n){let a=r.toString("utf-8"),s=Id("sha256",t).update(a,"utf-8").digest("base64"),c=!1;try{let p=Buffer.from(n,"base64"),d=Buffer.from(s,"base64");p.length===d.length&&(c=Pd(p,d))}catch{c=!1}let u;if(c)try{let p=JSON.parse(a);u=Ls(p)}catch{c=!1}c&&u&&(i={valid:!0,event:u})}return i}}var le=class{logger=new Md("ZohoSignWebhookService");_verifier;handler=Gs();configure=Ks(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Hs({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=A([Dd(),I(0,Od(Me))],le);var _e=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};A([Nd(),I(0,wd()),I(1,Mn())],_e.prototype,"handleZohoSignWebhook",1),_e=A([_d("/webhook/zoho/sign"),I(0,vd(le))],_e);import{Module as Ud}from"@nestjs/common";import{ConfigModule as Ld,ConfigService as Gd}from"@nestjs/config";function Kd(e){let t={zohoSignWebhook:{webhookSecret:e.get(Vs)}};return Me.assertValidConfig(t),t}var Yt=class{};Yt=A([Ud({imports:[Ld],controllers:[_e],providers:[{provide:Me,inject:[Gd],useFactory:Kd},le],exports:[le]})],Yt);import{Inject as zs,Injectable as Vd}from"@nestjs/common";var Ft=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(xe(t.zohoDesk),!t.zohoDesk.orgId)throw new Error("No Zoho Desk orgId specified.")}};var ve=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoDesk=Na({...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 Ua(this.deskContext)}get searchTickets(){return cr(this.deskContext)}get getTicketsForContact(){return La(this.deskContext)}get getTicketsForProduct(){return Ga(this.deskContext)}get getTicketMetrics(){return Ka(this.deskContext)}get getAgentsTicketsCount(){return Va(this.deskContext)}get getTicketsPageFactory(){return Ha(this.deskContext)}get searchTicketsPageFactory(){return za(this.deskContext)}get getDepartments(){return Wa(this.deskContext)}get getDepartmentById(){return Ba(this.deskContext)}get getContacts(){return pr(this.deskContext)}get getContactById(){return Ja(this.deskContext)}get getContactsByIds(){return $a(this.deskContext)}get getContactsPageFactory(){return Xa(this.deskContext)}get getTicketTags(){return Ya(this.deskContext)}get associateTicketTags(){return Qa(this.deskContext)}get dissociateTicketTag(){return es(this.deskContext)}get searchTags(){return ts(this.deskContext)}get getAllTags(){return os(this.deskContext)}get getTicketFollowers(){return rs(this.deskContext)}get addTicketFollowers(){return ns(this.deskContext)}get removeTicketFollowers(){return is(this.deskContext)}get getTicketAttachments(){return ss(this.deskContext)}get deleteTicketAttachment(){return cs(this.deskContext)}get getTicketComments(){return ps(this.deskContext)}get getTicketCommentById(){return ds(this.deskContext)}get createTicketComment(){return ls(this.deskContext)}get deleteTicketComment(){return hs(this.deskContext)}get getTicketTimer(){return ms(this.deskContext)}get performTicketTimerAction(){return ys(this.deskContext)}get getTicketTimeEntries(){return gs(this.deskContext)}get getTicketTimeEntryById(){return fs(this.deskContext)}get getTicketTimeEntrySummation(){return Rs(this.deskContext)}get getTicketThreads(){return lr(this.deskContext)}get getTicketThreadById(){return xs(this.deskContext)}get getTicketThreadsPageFactory(){return Zs(this.deskContext)}get getTicketActivities(){return hr(this.deskContext)}get getTicketActivitiesPageFactory(){return Fs(this.deskContext)}get getAgents(){return mr(this.deskContext)}get getAgentById(){return As(this.deskContext)}get getAgentsByIds(){return bs(this.deskContext)}get getMyInfo(){return ks(this.deskContext)}get getAgentsPageFactory(){return Is(this.deskContext)}};ve=A([Vd(),I(0,zs(Ft)),I(1,zs(_))],ve);import{ConfigModule as iA,ConfigService as aA}from"@nestjs/config";function Hd(e){return`${e.clientId}:${e.refreshToken}`}function nt(e){let t=Ds([Ms(),_s(ht())]),o=new Map;function r(p,d){let y=Hd(p),m=o.get(y),T;if(m)T=m;else{let g={zohoAccounts:{serviceAccessTokenKey:d,refreshToken:p.refreshToken,clientId:p.clientId,clientSecret:p.clientSecret,apiUrl:p.region??"us"}};T=new _(g,t),o.set(y,T)}return T}let n,i=mt(e,"recruit");if(i){let p=r(i,"recruit"),d={zohoRecruit:{apiUrl:i.apiMode}};n=new De(d,p)}let a,s=mt(e,"crm");if(s){let p=r(s,"crm"),d={zohoCrm:{apiUrl:s.apiMode}};a=new Oe(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 ve(d,p)}return{recruitApi:n,crmApi:a,deskApi:c}}ro([...to,/1000\.\w{20,}/g]);function js(e){let t;return e instanceof K?t={ok:!1,error:pe(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof qe?t={ok:!1,error:pe(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Je?t={ok:!1,error:pe(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof G?t={ok:!1,error:pe(e.message),code:"API_ERROR"}:t=no(e),t}Sr(e=>e instanceof K||e instanceof qe||e instanceof Je||e instanceof G?js(e):void 0);function h(e){console.log(JSON.stringify(js(e)))}var Ws={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"},Bs={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 zd(e){let t;if(!e)t=void 0;else if(e.startsWith("http://")||e.startsWith("https://"))try{let r=new URL(e).searchParams.get("code");if(!r)throw new Error('No "code" parameter found in the provided URL.');t=r}catch(o){throw o instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`,{cause:o}):o}else t=e;return t}var jd={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:[...Nt],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 H(),o=Wd(e,t);if(!o.clientId||!o.clientSecret)throw new Error("--client-id and --client-secret are required. Get them from https://api-console.zoho.com/");o.token?await Bd(o,t):o.code?await qd(o,t):await Jd(o,t)}catch(t){h(t),process.exit(1)}}};function Wd(e,t){let o=e.region??t?.shared?.region??"us";return{product:e.product,clientId:e.clientId??t?.shared?.clientId,clientSecret:e.clientSecret??t?.shared?.clientSecret,redirectUri:e.redirectUri,region:o,scopes:e.scopes.split(",").map(r=>r.trim()),code:zd(e.code),token:e.token,accountsUrl:Ws[o]??Ws.us,apiMode:e.apiMode,orgId:e.orgId}}async function qs(e,t,o){return e.product?te({shared:o??{clientId:"",clientSecret:"",refreshToken:""},[e.product]:{...t,apiUrl:e.apiMode,orgId:e.product==="desk"?e.orgId:void 0}}):te({shared:{...t,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0})}async function Bd(e,t){let o={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.token},r=await qs(e,o,t?.shared);l({success:!0,...e.product?{product:e.product}:{},refreshToken:ye(e.token),configSaved:!0,configuredProducts:oe(r)})}async function qd(e,t){let o=`${e.accountsUrl}/oauth/v2/token`,r=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUri,code:e.code}),i=await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()})).json();if(i.error)throw new Error(`Token exchange failed: ${i.error}`);let a=i.refresh_token;if(!a)throw new Error("No refresh_token in response. The authorization code may have expired (valid for 2 minutes). Generate a new one.");let s={clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:a},c=await qs(e,s,t?.shared);l({step:2,success:!0,product:e.product??"shared",refreshToken:ye(a),accessToken:i.access_token?ye(i.access_token):null,scope:i.scope,configSaved:!0,configuredProducts:oe(c)})}async function Jd(e,t){let o=e.scopes.flatMap(n=>Bs[n]??[]);if(o.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Bs).join(", ")}`);let r=`${e.accountsUrl}/oauth/v2/auth?scope=${o.join(",")}&client_id=${encodeURIComponent(e.clientId)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(e.redirectUri)}`;await te({shared:{clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:t?.shared?.refreshToken??"",region:e.region,apiMode:e.apiMode??t?.shared?.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({step:1,instructions:'Open the authorization URL in a browser. Authorize the application. Copy the "code" parameter from the redirect URL.',authorizationUrl:r,redirectUri:e.redirectUri,scopes:o,credentialsSaved:!0,nextStep:'zoho-cli auth setup --code "PASTE_REDIRECT_URL_OR_AUTH_CODE"'})}var $d={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:[...Nt],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 te({shared:(await H())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await te({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({saved:!0,product:t??"shared",configuredProducts:oe(r)})}catch(t){h(t),process.exit(1)}}},Xd={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){return r?{clientId:r.clientId?ye(r.clientId):void 0,clientSecret:r.clientSecret?ye(r.clientSecret):void 0,refreshToken:r.refreshToken?ye(r.refreshToken):void 0}:void 0};var e=o;let t=await H();if(!t){l({configured:!1});return}l({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:oe(t)})}catch(t){h(t),process.exit(1)}}},Yd={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await H();if(e){let t=oe(e);if(t.length===0)l({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});else{let o=nt(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}}l({products:r})}}else l({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"})}catch(e){h(e),process.exit(1)}}},Qd={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await Hn(),l({cleared:!0})}catch(e){h(e),process.exit(1)}}},Js={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(jd).command($d).command(Xd).command(Yd).command(Qd).demandCommand(1,"Please specify an auth subcommand."),handler:S};import{access as el,constants as tl}from"node:fs";import{dirname as ol}from"node:path";var $s={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=await H(),t=[];t.push(rl(e));let o=nl(e);if(o&&t.push(o),t.push(await il()),e){let n=oe(e);t.push(al(n),...await sl(e,n));let i=pl(e,n);i&&t.push(i)}let r=t.every(n=>n.status==="pass");l({checks:t,healthy:r}),r||process.exit(t.some(n=>n.status==="fail")?1:0)}};function rl(e){return e?{name:"config",status:"pass",message:`Config loaded from ${lt()}`}:{name:"config",status:"fail",message:"No config found. Run: zoho-cli auth setup"}}function nl(e){if(e?.shared?.clientId&&e?.shared?.clientSecret&&e?.shared?.refreshToken)return{name:"shared-credentials",status:"pass",message:"Shared credentials present"};if(e)return{name:"shared-credentials",status:"warn",message:"Missing shared credentials. Per-product credentials may still work."}}async function il(){let e=ol(ht());return await dl(e)?{name:"token-cache",status:"pass",message:`Token cache directory writable: ${e}`}:{name:"token-cache",status:"warn",message:`Token cache directory not writable: ${e}`}}function al(e){return e.length>0?{name:"products",status:"pass",message:`Configured products: ${e.join(", ")}`}:{name:"products",status:"fail",message:"No products have complete credentials"}}async function sl(e,t){let o=nt(e),r=[];for(let n of t)r.push(await cl(o,n));return r}async function cl(e,t){let o=ul(e,t);if(!o)return{name:`${t}-token`,status:"warn",message:`${t}: API not configured`};let r;try{let i=await o.zohoAccountsApi.accessToken();r={name:`${t}-token`,status:"pass",message:`${t}: Token exchange successful. Scope: ${i.scope}`}}catch(n){let i=n instanceof Error?n.message:String(n);r={name:`${t}-token`,status:"fail",message:`${t}: Token exchange failed: ${i}`}}return r}function ul(e,t){return t==="recruit"?e.recruitApi:t==="crm"?e.crmApi:e.deskApi}function pl(e,t){if(e.desk?.orgId)return{name:"desk-org-id",status:"pass",message:`Desk org ID configured: ${e.desk.orgId}`};if(!t.includes("desk"))return{name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."}}function dl(e){return new Promise(t=>{el(e,tl.W_OK,o=>{t(!o)})})}var Xs=On({notInitializedMessage:"CLI context not initialized. This is a bug."});function Ys(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await H();r||(h(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),oe(r).length===0&&(h(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),Xs.set(nt(r))}catch(r){h(r),process.exit(4)}}}function fr(e){return Xs.require()}function W(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 B(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 ce(e){return Zo(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 Zo(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 ll={nextInput:(e,t)=>{let o;if(t.info?.more_records){let r=e.page??1;o={...e,page:r+1}}else o=void 0;return o},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,r=t.data?.length??0,n;if(o<=0||r<o)n=void 0;else{let i=e.from??1;n={...e,from:i+o}}return n},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,r=t.data?.length??0;return o>0&&r>=o}};async function ue(e){let{argv:t,initialInput:o,fetchPage:r}=e,n=await k({initialInput:o,fetchPage:r,adapter:ll,multiplePages:t.multiplePages,multiplePagesOutput:t.multiplePagesOutput,dumpOutput:t.dumpOutput,dumpMerge:t.dumpMerge});if(n.handled===!1){let i=n.result;l(i.data,{page:i.info?.page,per_page:i.info?.per_page,more_records:i.info?.more_records})}}var hl={command:"list",describe:"List records from a module",builder:e=>Qt(St(ce(D(e)))),handler:async e=>{try{let t=W(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder};await ue({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},ml={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});l(o)}catch(t){h(t),process.exit(1)}}},yl={command:"search",describe:"Search records in a module",builder:e=>ce(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 ue({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){h(t),process.exit(1)}}},gl={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});l(r)}catch(t){h(t),process.exit(1)}}},fl={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});l(r)}catch(t){h(t),process.exit(1)}}},Rl={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});l(r)}catch(t){h(t),process.exit(1)}}},Tl={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});l(r)}catch(t){h(t),process.exit(1)}}},Cl={command:"emails",describe:"Get emails for a record",builder:e=>ce(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 ue({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){h(t),process.exit(1)}}},xl={command:"attachments",describe:"Get attachments for a record",builder:e=>ce(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 ue({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},Qs={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(hl).command(ml).command(yl).command(gl).command(fl).command(Rl).command(Tl).command(Cl).command(xl).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:S};var Zl={command:"list",describe:"List records from a module",builder:e=>Qt(St(ce(D(e)),!0)),handler:async e=>{try{let t=B(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder};await ue({argv:e,initialInput:o,fetchPage:r=>t.getRecords(r)})}catch(t){h(t),process.exit(1)}}},Fl={command:"get",describe:"Get a record by ID",builder:e=>Fe(D(e)),handler:async e=>{try{let o=await B(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){h(t),process.exit(1)}}},Sl={command:"search",describe:"Search records in a module",builder:e=>ce(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=B(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 ue({argv:e,initialInput:o,fetchPage:r=>t.searchRecords(r)})}catch(t){h(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=B(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},bl={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=B(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},kl={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=B(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){h(t),process.exit(1)}}},Il={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=B(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){h(t),process.exit(1)}}},Pl={command:"emails",describe:"Get emails for a record",builder:e=>ce(Fe(D(e))),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage};await ue({argv:e,initialInput:o,fetchPage:r=>t.getEmailsForRecord(r)})}catch(t){h(t),process.exit(1)}}},El={command:"attachments",describe:"Get attachments for a record",builder:e=>St(ce(Fe(D(e))),!0),handler:async e=>{try{let t=B(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage};await ue({argv:e,initialInput:o,fetchPage:r=>t.getAttachmentsForRecord(r)})}catch(t){h(t),process.exit(1)}}},ec={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(Zl).command(Fl).command(Sl).command(Al).command(bl).command(kl).command(Il).command(Pl).command(El).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:S};var Ol={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Dl={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});l(o)}catch(t){h(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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},_l={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},vl={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});l(o)}catch(t){h(t),process.exit(1)}}},Nl={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});l(r)}catch(t){h(t),process.exit(1)}}},tc={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(Ol).command(Dl).command(Ml).command(_l).command(vl).command(Nl).demandCommand(1),handler:S};var wl={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;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Ul={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});l(o)}catch(t){h(t),process.exit(1)}}},oc={command:"departments",describe:"Desk department operations",builder:e=>e.command(wl).command(Ul).demandCommand(1),handler:S};var Ll={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Gl={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});l(o)}catch(t){h(t),process.exit(1)}}},rc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(Ll).command(Gl).demandCommand(1),handler:S};var Kl={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Vl={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});l(o)}catch(t){h(t),process.exit(1)}}},Hl={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await x(e).getMyInfo();l(o)}catch(t){h(t),process.exit(1)}}},nc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(Kl).command(Vl).command(Hl).demandCommand(1),handler:S};var zl={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;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},jl={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;l(n.data,{count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},Wl={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});l(o)}catch(t){h(t),process.exit(1)}}},Bl={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});l(r)}catch(t){h(t),process.exit(1)}}},ql={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}),l({removed:!0})}catch(t){h(t),process.exit(1)}}},ic={command:"tags",describe:"Desk tag operations",builder:e=>e.command(zl).command(jl).command(Wl).command(Bl).command(ql).demandCommand(1),handler:S};var Jl={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},$l={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});l(o)}catch(t){h(t),process.exit(1)}}},Xl={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});l(o)}catch(t){h(t),process.exit(1)}}},Yl={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}),l({deleted:!0})}catch(t){h(t),process.exit(1)}}},ac={command:"comments",describe:"Desk comment operations",builder:e=>e.command(Jl).command($l).command(Xl).command(Yl).demandCommand(1),handler:S};var Ql={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},eh={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}),l({deleted:!0})}catch(t){h(t),process.exit(1)}}},sc={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(Ql).command(eh).demandCommand(1),handler:S};var th={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});l(o)}catch(t){h(t),process.exit(1)}}},oh={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}),l({added:!0})}catch(t){h(t),process.exit(1)}}},rh={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}),l({removed:!0})}catch(t){h(t),process.exit(1)}}},cc={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(th).command(oh).command(rh).demandCommand(1),handler:S};var nh={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});l(o)}catch(t){h(t),process.exit(1)}}},ih={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});l(o)}catch(t){h(t),process.exit(1)}}},ah={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},sh={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});l(o)}catch(t){h(t),process.exit(1)}}},uc={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(nh).command(ih).command(ah).command(sh).demandCommand(1),handler:S};var ch={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},uh={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});l(o)}catch(t){h(t),process.exit(1)}}},pc={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(ch).command(uh).demandCommand(1),handler:S};var ph={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;l(n.data,{from:e.from,limit:e.limit,count:n.data?.length})}}catch(t){h(t),process.exit(1)}}},dc={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(ph).demandCommand(1),handler:S};var lc={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(tc).command(oc).command(rc).command(nc).command(ic).command(ac).command(sc).command(cc).command(uc).command(pc).command(dc).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:S};var hc={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=W(e).recruitContext;break;case"crm":n=B(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);l(s)}catch(t){h(t),process.exit(1)}}};var hh=Gn({cliName:"zoho-cli",loadOutputConfig:async()=>(await H())?.output,mergeOutputConfig:e=>te({output:e}),clearOutputConfig:Vn}),mh=[Qs,ec,lc,hc],mc=[Js,hh,$s];function yh(e){return e.command.split(" ")[0]}var yc=new Set(mc.map(yh)),gh=Ln({cliName:"zoho-cli",skipCommands:yc,loadOutputConfig:async()=>(await H())?.output,saveCommandOutputConfig:async(e,t)=>{await te({output:{commands:{[e]:t}}})}});async function fh(){try{await dh(lh(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([Ys(yc),gh],!0).command(mc).command(mh).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){h(e),process.exit(1)}}await fh();
package/cli/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@dereekb/zoho/cli",
3
- "version": "13.11.18",
3
+ "version": "13.12.1",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "zoho-cli": "index.js"
7
7
  },
8
8
  "peerDependencies": {
9
- "@dereekb/dbx-cli": "13.11.18",
10
- "@dereekb/nestjs": "13.11.18",
11
- "@dereekb/rxjs": "13.11.18",
12
- "@dereekb/util": "13.11.18",
13
- "@dereekb/zoho": "13.11.18",
14
- "@dereekb/zoho/nestjs": "13.11.18",
9
+ "@dereekb/dbx-cli": "13.12.1",
10
+ "@dereekb/nestjs": "13.12.1",
11
+ "@dereekb/rxjs": "13.12.1",
12
+ "@dereekb/util": "13.12.1",
13
+ "@dereekb/zoho": "13.12.1",
14
+ "@dereekb/zoho/nestjs": "13.12.1",
15
15
  "yargs": "^18.0.0"
16
16
  },
17
17
  "devDependencies": {
package/index.cjs.js CHANGED
@@ -5116,7 +5116,7 @@ function _is_native_reflect_construct() {
5116
5116
  *
5117
5117
  * @param e - The error to catch and potentially convert.
5118
5118
  * @returns The error data array wrapped as a change object response.
5119
- * @throws Re-throws `e` when it is not a {@link ZohoServerFetchResponseDataArrayError}.
5119
+ * @throws {Error} Re-throws `e` when it is not a {@link ZohoServerFetchResponseDataArrayError}.
5120
5120
  */ function zohoCrmCatchZohoCrmChangeObjectLikeResponseError(e) {
5121
5121
  var result;
5122
5122
  if (_instanceof$4(e, ZohoServerFetchResponseDataArrayError)) {
package/index.esm.js CHANGED
@@ -5114,7 +5114,7 @@ function _is_native_reflect_construct() {
5114
5114
  *
5115
5115
  * @param e - The error to catch and potentially convert.
5116
5116
  * @returns The error data array wrapped as a change object response.
5117
- * @throws Re-throws `e` when it is not a {@link ZohoServerFetchResponseDataArrayError}.
5117
+ * @throws {Error} Re-throws `e` when it is not a {@link ZohoServerFetchResponseDataArrayError}.
5118
5118
  */ function zohoCrmCatchZohoCrmChangeObjectLikeResponseError(e) {
5119
5119
  var result;
5120
5120
  if (_instanceof$4(e, ZohoServerFetchResponseDataArrayError)) {
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@dereekb/zoho/nestjs",
3
- "version": "13.11.18",
3
+ "version": "13.12.1",
4
4
  "peerDependencies": {
5
- "@dereekb/nestjs": "13.11.18",
6
- "@dereekb/rxjs": "13.11.18",
7
- "@dereekb/util": "13.11.18",
8
- "@dereekb/zoho": "13.11.18",
5
+ "@dereekb/nestjs": "13.12.1",
6
+ "@dereekb/rxjs": "13.12.1",
7
+ "@dereekb/util": "13.12.1",
8
+ "@dereekb/zoho": "13.12.1",
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.18",
3
+ "version": "13.12.1",
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.18",
27
- "@dereekb/dbx-cli": "13.11.18",
28
- "@dereekb/firebase": "13.11.18",
29
- "@dereekb/model": "13.11.18",
30
- "@dereekb/nestjs": "13.11.18",
31
- "@dereekb/rxjs": "13.11.18",
32
- "@dereekb/util": "13.11.18",
26
+ "@dereekb/date": "13.12.1",
27
+ "@dereekb/dbx-cli": "13.12.1",
28
+ "@dereekb/firebase": "13.12.1",
29
+ "@dereekb/model": "13.12.1",
30
+ "@dereekb/nestjs": "13.12.1",
31
+ "@dereekb/rxjs": "13.12.1",
32
+ "@dereekb/util": "13.12.1",
33
33
  "@nestjs/common": "^11.1.19",
34
34
  "@nestjs/config": "^4.0.4",
35
35
  "express": "^5.2.1",
@@ -897,7 +897,7 @@ export declare function zohoCrmApiFetchJsonInput(method: string, body?: Maybe<Fe
897
897
  *
898
898
  * @param e - The error to catch and potentially convert.
899
899
  * @returns The error data array wrapped as a change object response.
900
- * @throws Re-throws `e` when it is not a {@link ZohoServerFetchResponseDataArrayError}.
900
+ * @throws {Error} Re-throws `e` when it is not a {@link ZohoServerFetchResponseDataArrayError}.
901
901
  */
902
902
  export declare function zohoCrmCatchZohoCrmChangeObjectLikeResponseError<R extends ZohoCrmChangeObjectLikeResponse<any>>(e: unknown): R;
903
903
  export type ZohoCrmChangeObjectLikeResponse<T extends ZohoCrmChangeObjectLikeResponseEntry = ZohoCrmChangeObjectLikeResponseEntry> = ZohoDataArrayResultRef<T>;