@dereekb/zoho 13.10.0 → 13.10.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 +4 -4
- package/cli/package.json +8 -8
- package/index.cjs.js +21 -9
- package/index.esm.js +21 -9
- package/nestjs/index.cjs.js +3 -3
- package/nestjs/index.esm.js +3 -3
- package/nestjs/package.json +9 -9
- package/package.json +10 -10
- package/src/lib/crm/crm.d.ts +1 -1
- package/src/lib/desk/desk.agent.d.ts +1 -1
- package/src/lib/desk/desk.ticket.d.ts +3 -3
- package/src/lib/recruit/recruit.d.ts +1 -1
- package/src/lib/sign/sign.api.page.d.ts +1 -1
- package/src/lib/sign/sign.d.ts +3 -3
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 pu=Object.defineProperty;var du=Object.getOwnPropertyDescriptor;var O=(e,t,o,r)=>{for(var n=r>1?void 0:r?du(t,o):t,a=e.length-1,i;a>=0;a--)(i=e[a])&&(n=(r?i(t,o,n):i(n))||n);return r&&n&&pu(t,o,n),n},A=(e,t)=>(o,r)=>t(o,r,e);import qy from"yargs";import{hideBin as $y}from"yargs/helpers";import{readFile as lu,writeFile as mu,rm as yu,mkdirSync as hu}from"node:fs";import{join as Po}from"node:path";import{homedir as fu}from"node:os";var Kt=["recruit","crm","desk"];function Ao(){return Po(fu(),".zoho-cli")}function lt(){return Po(Ao(),"config.json")}function mt(){return Po(Ao(),".tokens.json")}function ee(e,t){if(t){let o=process.env[`ZOHO_${t}_${e}`];if(o)return o}return process.env[`ZOHO_${e}`]}async function B(){let e=lt(),t=await xu(e),o=ee("ACCOUNTS_CLIENT_ID"),r=ee("ACCOUNTS_CLIENT_SECRET"),n=ee("ACCOUNTS_REFRESH_TOKEN");if(!t&&!(o&&r&&n))return;let i={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:ee("ACCOUNTS_URL")??t?.shared?.region,apiMode:ee("API_URL")??t?.shared?.apiMode};function s(u){let p=u.toUpperCase(),d=ee("ACCOUNTS_CLIENT_ID",p),g=ee("ACCOUNTS_CLIENT_SECRET",p),y=ee("ACCOUNTS_REFRESH_TOKEN",p),h=ee("API_URL",p),T=u==="desk"?ee("DESK_ORG_ID"):void 0,R=t?.[u],S=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],M=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],v=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`];if(!(!R&&!(S||M||v)&&!T))return{clientId:S??R?.clientId,clientSecret:M??R?.clientSecret,refreshToken:v??R?.refreshToken,apiUrl:h??R?.apiUrl,orgId:T??R?.orgId}}return{shared:i,recruit:s("recruit")??t?.recruit,crm:s("crm")??t?.crm,desk:s("desk")??t?.desk,output:t?.output}}function yt(e,t){let o=e[t],r=e.shared,n=o?.clientId??r.clientId,a=o?.clientSecret??r.clientSecret,i=o?.refreshToken??r.refreshToken;if(!(!n||!a||!i))return{clientId:n,clientSecret:a,refreshToken:i,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId}}async function gu(e){let t=lt();return hu(Ao(),{recursive:!0}),new Promise((o,r)=>{mu(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function G(e){let t=await B(),o={shared:{...t?.shared,...e.shared},recruit:e.recruit!==void 0?{...t?.recruit,...e.recruit}:t?.recruit,crm:e.crm!==void 0?{...t?.crm,...e.crm}:t?.crm,desk:e.desk!==void 0?{...t?.desk,...e.desk}:t?.desk,output:e.output!==void 0?Tu(t?.output,e.output):t?.output};return await gu(o),o}function Tu(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:"commands"in t?t.commands?{...e?.commands,...t.commands}:void 0:e?.commands}}function sn(e,t,o){let r=t.join("."),n=r?e?.commands?.[r]:void 0;return{dumpDir:o.dumpDir??n?.dumpDir??e?.dumpDir,pick:o.pick??n?.pick??e?.pick}}async function cn(){await G({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function un(){let e=lt(),t=mt();await an(e),await an(t)}function J(e){return Kt.filter(t=>{let o=yt(e,t);return!(!o||t==="desk"&&!o.orgId)})}function xu(e){return new Promise(t=>{lu(e,{encoding:"utf-8"},(o,r)=>{if(o){t(void 0);return}try{t(JSON.parse(r))}catch{t(void 0)}})})}function an(e){return new Promise(t=>{yu(e,()=>t())})}function Te(e){return e.length<=4?"***":e.substring(0,4)+"***"}function C(){}import{Inject as fc,Injectable as Il}from"@nestjs/common";function Ut(e,t){let o;return t&&typeof e=="string"?o=[e]:de(e)?o=[...e]:o=[e],o}function Eo(e,t){return new Map(Ut(e).map(o=>[t(o),o]))}function de(e,t=!1){return typeof e=="string"?t:e!=null&&typeof e=="object"&&Symbol.iterator in e}function ht(e){for(let t of e)return!1;return!0}function xe(e,t){for(let o of e)t(o)}function q(e,t,o=!1){e!=null&&(de(e,o)?xe(e,t):t(e))}function pn(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(i=>Array.isArray(i)?i.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function Ru(e){return e!=null?ko(e):[]}var f=Ru;function ko(e){return Array.isArray(e)?e:[e]}function Zo(e){return dn([],...e)}function dn(e,...t){return e??=[],t.forEach(o=>{o!=null&&ln(e,o)}),e}function ln(e,t){return Array.prototype.push.apply(e,t),e}import{symmetricDifference as hh}from"extra-set";function bu(e,t){let o=new Set(e??void 0);return t(o),o}function mn(e,t){return bu(e,o=>ft(o,t))}function ft(e,t){q(t,o=>e.add(o))}function gt(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function yn(e){return Object.keys(e).length===0}function le(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function hn(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function Lo(e){return{...e}}function Tt(e){return e!=null}function Ee(e){return de(e,!1)?!ht(e):fn(e)}function vo(e){let t;return de(e,!0)?t=!ht(e):fn(e)?t=typeof e=="object"?!yn(e):!0:t=!1,t}function fn(e){return e!=null&&e!==""}function gn(e){return(t=>{let o;return t!=null?o=t.filter(e):o=[],o})}var N=gn(Tt),Fu=gn(Ee);function Bt({base:e,build:t}){let o=e??{};return t(o),o}function Gt(e){return t=>t.map(e)}var Ke=(e=>e);function Re(){return Ke}function Su(e,t){return N(e!=null?Array.isArray(e)?e:xn(e,t):[])}function xn(e,t){let o=new Set(e.keys);return e.values&&ft(o,e.values.map(t)),Array.from(o)}function No(e,t){let o=Su(t,e);function r(n){let a=n?Array.isArray(n)?n.map(e):xn(n,e):[];return a.length?Zo([N(a),o]):o}return(n,a)=>{let i=r(a),s=new Set(i);return n.filter(u=>{let p=e(u);return s.has(p)?!1:(s.add(p),!0)})}}var Cu=e=>e.id;function _o(e,t,o){let r=o(t);return wo(e,r,o)}function wo(e,t,o=Cu){return e.filter(r=>o(r)!==t)}function Vo(e){return t=>{let o=e(t);if(o==="")throw new Error('Cannot use "empty" string for BooleanKey.');return o}}function bn(e){return!e||e.length<=0}function Iu(e){return!bn(e)}function Ou(e,t,o){return e?[..._o(e,t,Vo(o)),t]:[t]}function Mu(e,t,o){return e&&_o(e,t,Vo(o))}function Pu(e,t,o){return e&&wo(e,t,Vo(o))}function Au(e){let t=s=>bn(s),o=s=>Iu(s),r=(s,c,u=!0)=>u?n(s,c):a(s,c),n=(s,c)=>Ou(s,c,e),a=(s,c)=>Mu(s,c,e);return{isFalse:t,isTrue:o,set:r,insert:n,remove:a,removeByKey:(s,c)=>Pu(s,c,e)}}var $h=Au(e=>e||void 0);function be(e,t){let o=Eu(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function Eu(e,t){let o=Fn(e,t);return hn(o)}function Fn(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),a=o.get(n);a!=null?a.push(r):o.set(n,[r])}),o}function Sn(e,t,o){return f(t).forEach(r=>e.set(r,o)),e}function Ko(e){return Array.from(e.entries())}function Cn(e){return ku(Ko(e))}function ku(e){let t=[];return e.forEach(([o,r])=>{q(r,n=>{t.push([o,n])})}),t}function Uo(){let e=new Map,t=(n,a)=>{let i=e.get(n);i==null&&(i=[],e.set(n,i)),q(a,s=>i.push(s))},o=(n,a)=>t(n,pn(a));return{map:()=>e,entries:()=>Ko(e),tuples:()=>Cn(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,a)=>q(n,i=>t(i,a)),addTuplesToKeys:(n,a)=>q(n,i=>o(i,a)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function In(e){let{readKey:t,defaultIfKeyNull:o=!1}=e;return r=>{let n=new Set(r);return a=>{let i=t(a);return i!=null?n.has(i):o}}}var Zu=32;function Du(e){return t=>{let o=new Set;for(let r=0;r<e;r+=1)t&1<<r&&o.add(r);return o}}var pf=Du(Zu);function Lu(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function On(e){let t=Lu(e);return t!=null&&t!=="class"}function me(e){return On(e)?e:()=>e}function xt(e={}){let{startAt:t,increaseBy:o}=e,r=me(o??1),n=t??0;return()=>{let a=n;return n+=r(),a}}function vu(e){let{min:t,max:o}=e;return t<=o}function Nu(e){let{min:t,max:o}=e;if(!vu(e))throw new Error("Invalid bounds. Min was greater than the max.");return r=>r>=t&&r<=o}function jt(e){let{min:t,max:o,fencePosts:r=!1}=e,n=o-t,a=Nu(e),i=(s=>{let c;if(a(s))c=s;else{let u=r?s<t?1:-1:0;c=((s-t)%n+n)%n+t+u}return c});return i._wrap=e,i}function qt(e){let{min:t,max:o,wrap:r}=e;return r?jt(e):n=>_u(n,t,o)}function _u(e,t,o){return Math.max(Math.min(e,o),t)}function Mn(e){let t;switch(typeof e){case"number":t=e;break;case"string":t=Number(e);break;default:t=0;break}return t}function Pn(e,t){return Math.log(t)/Math.log(e)}function Wo(e){let t;switch(e){case"floor":t=Math.floor;break;case"ceil":t=Math.ceil;break;case"none":t=o=>o;break;default:t=Math.round;break}return t}var Ff=Rt(0);function Rt(e,t="cut"){let o=Vu(e,t),r=(n=>o(Mn(n)));return r._precision=e,r}function Vu(e,t="round"){let o;if(t==="cut")o=r=>An(r,e);else{let r=Wo(t);o=n=>+(r(+(n+"e+"+e))+"e-"+e)}return o}function An(e,t){return+((e>0?Math.floor:Math.ceil)(+(e+"e+"+t))+"e-"+t)}function Ue(e,t){let o=typeof e=="number"?{min:0,max:e}:e,{min:r,max:n,round:a}=o,i=t??a,s;if(r!=null){let c=n-r;s=()=>Math.random()*c+r}else s=()=>Math.random()*n;if(i&&i!=="none"){let c=typeof i=="function"?i:Wo(i),u=s;s=()=>c(u())}return s}function En(e){return(t,o)=>{let r=e(t),n=e(o);return r-n}}var Pf=En(e=>e);function Zn(e){return e.i}var pg=No(Zn);var dg=In({readKey:Zn});var Dn=",",Uu=" ";function Wu(e,t=Dn,o=!1){if(e==null)return e;let r=f(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function Ht(e,t,o){let r=e.split(t),n=[];if(r.length>1){let a=r.length>o,i=a?o-1:r.length;for(let s=0;s<i;s+=1)n.push(r[s]);a&&n.push(r.slice(i).join(t))}else n.push(r[0]);return n}function Bu(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,a=o){return Wu(n,t,a)};return r.joiner=t,r.trimByDefault=o,r}function Ln(e){let{joiner:t}=e,o=Bu(e),r=(n,a=i=>i)=>n.split(t).map(s=>a(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,a){return Ht(n,t,a)}}}var Go=Ln({joiner:Dn}),Gu=Ln({joiner:Uu,trimByDefault:!0});var E=Go.joinStrings,Hg=Go.splitStrings,zg=Go.splitStringsToSet,ju=Gu.joinStrings;function vn(e){return e.trim()}function Nn(e){return e.toUpperCase()}function _n(e){return e.toLowerCase()}var hT=Gt(vn),fT=Gt(Nn),gT=Gt(_n);import{BaseError as $u}from"make-error";var Hu="DBX_ASSERTION_ERROR",jo=class extends $u{code=Hu;_target;_property;constructor(t,o){super(o),this.name="AssertionError",this._target=t.target,this._property=t.propertyKey}get target(){return this._target}get propertyKey(){return this._property}},qo=class{handle(t){throw this.buildException(t)}buildException(t){let o=this.buildExceptionString(t);return new jo(t,o)}buildExceptionString(t){let o;return t.options?.message?o=t.options.message:o="Assertion failed for property '"+t.propertyKey+'".',o}},zu=new qo;var wn=gt;function We(e,{forEach:t,filter:o}){Vn(e,o).forEach(t)}function Vn(e,t){return zo(t)(e)}function zo(e){let t;if(e!=null){let o=Yu(e);t=r=>Ho(r).filter(o)}else t=Ho;return t}function Ho(e){return Object.entries(e)}function Jo(e){return typeof e=="object"?e:{valueFilter:e}}function Yu(e){let t=Jo(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,a;switch(o){case 1:a=([,i])=>i!==void 0;break;case 2:a=([,i])=>i!=null;break;case 3:a=([,i])=>!!i;break;case 4:a=([,i])=>Ee(i);break;case 5:a=([,i])=>vo(i);break;case 6:a=([,i])=>!!i&&Ee(i);break;case 7:a=([,i])=>!!i&&vo(i);break;default:a=()=>!0;break}if(n){let i=a,s=new Set(n.map(c=>c.toString()));a=(c,u)=>i(c,u)&&s.has(c[0])}return wn(a,r)}function Be(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 Xu({filter:e,copy:t,dynamic:o=!1}){let r=e!=null?Ge({filter:e,copy:!1}):ep;return n=>{let a=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},i=o?a:Be(a);return s=>{let c=i();return t&&(s=Lo(s)),Object.assign(s,c),s}}}function zt(e,t){return Qu(t)(e)}function Qu(e){let t=Xu({filter:e,copy:!1,dynamic:!0});return o=>t(N(o))({})}var Rx=Ge({copy:!0,filter:{valueFilter:1}}),bx=Ge({copy:!0,filter:{valueFilter:2}}),Kn=Ge({copy:!0,filter:{valueFilter:4}}),Fx=Ge({copy:!0,filter:{valueFilter:6}}),Sx=Yo({valueFilter:1}),Cx=Yo({valueFilter:6}),Ix=Yo({valueFilter:2});function Yo(e){let t=Xo({filter:e,forEach:([o],r,n,a)=>{a.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ge({copy:e=!1,filter:t={valueFilter:1}}={}){let o=Jo(t);o.invertFilter=!o.invertFilter;let r=Xo({filter:o,forEach:([n],a,i)=>{delete i[n]}});return(n,a)=>((typeof a=="boolean"?a:e)&&(n={...n}),r(n),n)}var ep=Ge({copy:!1});function Xo({forEach:e,filter:t}){let o=zo(t);return((r,n)=>{o(r).forEach((i,s)=>e(i,s,r,n))})}function tp(e){let{readKey:t,isModifiedFunction:o=()=>{}}=e;return(r,n)=>{let a=[],i=Eo(r,t),s=Eo(n,t),c=new Set(i.keys()),u=new Set(s.keys()),p=mn(c,u);return xe(p,d=>{if(d==null)return;let g=c.has(d),y=u.has(d),h;y&&g?h=0:g?h=-1:h=1;let T=g?i.get(d):void 0,R=y?s.get(d):void 0,S=T&&R?o(T,R):void 0;a.push({key:d,pastValue:T,nextValue:R,change:h,isModified:S,value:R??T})}),a}}var Nx=tp({readKey:e=>e});function Ft(e,t,o){let[r,n]=Jt(e,t,!1);return r+o+n}function Jt(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}function Wn(e){let t={};for(let[o,r]of[...e].entries())t[r]=o;return t}var op=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],rp=new Set(op);function Qo(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let a=Yt(r,n),i;switch(a.length){case 0:i=n;break;case 1:{let s=n[a[0]];i=Ft(n,a[0],o(s));break}default:{let s=[],c=a.length,u=0,p=0;for(let d=0;d<c;d+=1){p=a[d];let g=n[p],h=n.substring(u,p)+o(g);s.push(h),u=p+1}s.push(n.substring(u)),i=s.join("");break}}return i}}var Bn=Qo({escapeTargets:rp,escapeCharacter(e){return`\\${e}`}});function np(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[a,i]of[...t].entries())if(e.has(i)&&(n.push(a),n.length>=r))break;return n}}function Yt(e,t,o){return np(e)(t,o)}function ap(e,t){return Yt(e,t,1)[0]}function Xt(e){return t=>{let r=ap(typeof e=="string"?new Set([e]):e,t),n;return r!=null?n=Jt(t,r,!1):n=[t,void 0],n}}function Gn(e,t){return Xt(t)(e)}function jn(e){let t=Xt(e);return o=>t(o)[0]}var dR=jn("#"),lR=Xt("#");var je="/",ip=".";function sp(e){let t=e.split(ip,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e[e.length-1]===je?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function qn(e){return sp(e)!=="invalid"}var cp=/^\/+/,up=/\/+$/;var pp=/\/{2,}/g;function $n(e){return e.startsWith(je)?e.replace(cp,je):`${je}${e}`}function Hn(e){return e.replace(pp,je)}function zn(e){return e.replace(up,"")}var dp=/(.+)\.(.+)/;function lp(e){return dp.test(e)}var Jn=/:(\d+)/;function mp(e){return Jn.test(e)}function yp(e){let t=Jn.exec(e);return t?Number(t[1]):void 0}function hp(e){let t=ea(e),o=Xn(t),{domain:r,path:n}=o,a=lp(r),i=mp(e),s=i?yp(e)??void 0:void 0,[c,u]=Gn(o.path,"?"),p=a&&(c===""||qn(c+"/")),d=gp(e);return{input:e,isWebsiteUrl:p,hasWebsiteDomain:a,hasHttpPrefix:d,hasPortNumber:i,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function er(e){let t=hp(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function Yn(e,t=!1){let o=Yt(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(a=>n=Ft(n,a,"&")),n}function Xn(e){let t=ea(e);return fp(t)}function fp(e){let t=Ht(e,"/",2),o=t[0],r=t[1];return{domain:o,path:$n(r??"/")}}var Qn=/^https:\/\/|http:\/\//;function ea(e){return e.replace(Qn,"")}function gp(e){return Qn.test(e)}var rb={prefixes:"email.",domains:"test.dereekb.com",numberFactory:xt()};var nb={internationalAreaCodes:[1210,1979,1512,1303],numberFactory:Ue({min:2e6,max:1e7,round:"floor"})};import{BaseError as mb}from"make-error";var Tp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_",xp="!";function Rp(e){let{negativePrefix:t,digits:o}=e,r=t?"integer":"positive_integer",n=Math.min(6,Math.floor(Math.log2(o.length))),a=Math.pow(2,n),i=a-1,s=Wn(o);function c(p){let d="",g=p<0;g&&(p=-p);do{let y=p&i;d=o[y]+d,p>>>=n}while(p!==0);return g&&t&&(d=t+d),d}function u(p){let d=!1;p[0]===t&&(d=!0);let g=d?1:0,y=0;for(let h=g;h<p.length;h+=1)y=(y<<n)+s[p[h]];return d&&(y=-y),y}return{type:r,digits:o,bitDepth:a,negativePrefix:t,encodeNumber:c,decodeNumber:u}}var bp=Rp({negativePrefix:xp,digits:Tp});var ta=-90,oa=90,nF=oa-ta,ra=-180,na=180,Fp=na-ra;var aF=qt({min:ta,max:oa}),iF=jt({min:ra,max:na});var Cp=24,Ip=60,aa=1440,ia=60,bF=ia*Ip,_=1e3,ye=_*60,Qt=ye*60,sa=Qt*Cp,Op=7,Mp=sa*Op;function eo(e){return e.getTime()<Date.now()}var IF=Rt(3);var OF=aa-1;function ca(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function Ct(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function Zp(e){let n=Qt,a={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},i=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;y(e??a);function p(){return{...a}}function d(){return u}function g(M){u=M}function y(M,v=!1){let U=Math.max(0,M.startLimitAt??1),I=M.cooldownRate??1,D=M.maxWaitTime??n,P=M.exponentRate??2;a={startLimitAt:U,cooldownRate:I,maxWaitTime:D,exponentRate:P},s=Pn(P,D/_+1),v&&h()}function h(){i=0,c=new Date}function T(M){if(!u)return 0;let{cooldownRate:v}=a,I=(Date.now()-c.getTime())*v/_,D=Math.max(i-I,0),P=Math.max(0,D-a.startLimitAt);return M&&(i=D+M,c=new Date),P>=s?a.maxWaitTime:(Math.pow(a.exponentRate,Math.max(P,0))-1)*_}function R(M){return T(M??0)}function S(){let M=T(1);return Ct(M)}return{waitForRateLimit:S,getNextWaitTime:R,getConfig:p,setConfig:y,getEnabled:d,setEnabled:g,reset:h}}function da(e){let o=Zp({exponentRate:1.5,maxWaitTime:_*8,...e}),r=ye,n=new Date,a=0,i=0,s=!0;S(e,!0);function c(){eo(n)&&d()}function u(){return s}function p(I){s=I}function d(){i=a,n=new Date(Date.now()+r)}function g(){return n}function y(){return Math.max(0,n.getTime()-Date.now())}function h(I){n=I}function T(){return c(),i}function R(I){i=I}function S(I,D=!1){a=I.limit??a,r=I.resetPeriod??r;let P={cooldownRate:I.cooldownRate??Math.max(.1,r/_),exponentRate:I.exponentRate??1.5,maxWaitTime:I.maxWaitTime??_*8};o.setConfig(P,D),D&&d(),n=I.resetAt??n}function M(I){if(!s)return 0;function D(){return i-=I,o.getNextWaitTime(I)}let P=0;return i>0?P=D():(c(),i>0?P=D():P=y()),P}function v(I){return M(I??0)}function U(){let I=M(1);return Ct(I)}return{getRemainingLimit:T,setRemainingLimit:R,getTimeUntilNextReset:y,getResetAt:g,setNextResetAt:h,setConfig:S,reset:d,getNextWaitTime:v,waitForRateLimit:U,getEnabled:u,setEnabled:p}}function la(e){let{promiseFactories:t,successOnMaybe:o,throwErrors:r}=e;return async(n,a)=>{let{successOnMaybe:i,throwErrors:s}=a??{},c=i??o,u=s??r,p;for(let d of t)try{if(p=await d(n),p!=null||c)break}catch(g){if(u)throw g}return p}}import{BaseError as kC}from"make-error";function Dp(e){return t=>{let o={};return Object.entries(t).forEach(([r,n])=>{let a=e(r,n);o[a]=n}),o}}var sI=Dp(e=>{let t=e;return typeof e=="string"&&(t=e.toLowerCase()),t});function Lp(e){return t=>vp(t).then(o=>o.toString(e))}var jI=Lp("base64");function vp(e){let t=[];return new Promise((o,r)=>{e.on("data",n=>t.push(Buffer.from(n))),e.on("end",()=>o(Buffer.concat(t))),e.on("error",r)})}var Np="__CATCH_ALL_HANDLE_RESULT_KEY__";function ya(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,a=new Map,i=u=>{n=u},s=(u,p)=>{u===Np?i(p):Sn(a,u,p)},c=(u,p,d)=>{let g=d.bind(u);s(p,g)};return Bt({base:(u=>{let p=e(u),d=(p!=null?a.get(p):void 0)??n,g;return d?g=Promise.resolve(d(u)).then(y=>y??o):g=Promise.resolve(r),g}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=i}})}}function _p(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function wp(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function Vp(e,t,o){let r=wp(e,t);return n=>{r(function(a){let i=o(a);return n.call(this,i)})}}function ha(e,t){return o=>Vp(e,o,t)}function fa(e){return t=>(o,r)=>{let n=_p(o,t),a=e.configurerForAccessor(n);r(a)}}import{BaseError as xO}from"make-error";var tr=class{_length=0;_storage={};get length(){return this._length}key(t){return Object.keys(this._storage)[t]??null}hasKey(t){return le(this._storage,t)}getItem(t){return this._storage[t]??null}setItem(t,o){o==null?this.removeItem(t):(this.hasKey(t)||(this._length=this._length+1),this._storage[t]=String(o))}removeItem(t){this.hasKey(t)&&(delete this._storage[t],this._length=this._length-1)}clear(){this._storage={},this._length=0}},FO=new tr;function to(e){let t={};return Object.entries(e).forEach(([o,r])=>{t[r]=o}),t}var ga="image/jpeg",Kp="image/png",Up="image/webp",Wp="image/gif",Bp="image/heif",Gp="image/tiff",jp="image/svg+xml",qp="image/raw",$p={jpeg:ga,jpg:ga,png:Kp,webp:Up,gif:Wp,svg:jp,raw:qp,heif:Bp,tiff:Gp},VO=to($p);var Hp="application/pdf",zp="application/vnd.openxmlformats-officedocument.wordprocessingml.document",Jp="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",Yp="text/plain",Xp="text/csv",Qp="text/html",ed="application/xml",td="application/json",od="application/yaml",rd="text/markdown",nd={pdf:Hp,docx:zp,xlsx:Jp,txt:Yp,csv:Xp,html:Qp,xml:ed,json:td,yaml:od,md:rd},KO=to(nd);var ad="application/zip",id={zip:ad},UO=to(id);function sd(e){let{prefix:t,suffix:o,prefixEmptyString:r,suffixEmptyString:n}=e,a=t??"",i=o??"";function s(u){let p=u;if(a)for(;p.startsWith(a);)p=p.slice(a.length);if(i)for(;p.endsWith(i);)p=p.slice(0,p.length-i.length);return p}function c(u){let p=s(u),d;return p===""?(d="",r&&(d=`${a}${p}`),n&&(d=`${d}${i}`)):d=`${a}${p}${i}`,d}return{prefix:a,suffix:i,prefixEmptyString:r,suffixEmptyString:n,prefixSuffixString:c,cleanString:s}}var BO=sd({prefix:"-"});function cd(e){return(t,o)=>{let r=e(t),n=e(o);return r.localeCompare(n)}}var jO=cd(e=>e.label);var It={VISIT_ALL:0,VISIT_NODE_ONLY:1,VISIT_CHILDREN_ONLY:2,SKIP_ALL:3};var RM={ADD_ALL:It.VISIT_ALL,ADD_NODE_ONLY:It.VISIT_NODE_ONLY,ADD_CHILDREN_ONLY:It.VISIT_CHILDREN_ONLY,SKIP_ALL:It.SKIP_ALL};var ud=-1,or=0;function pd(e){return e?.page??ud}function rr(e){return pd(e)+1}import{BaseError as Ta}from"make-error";var Y=class extends Ta{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function xa(e){return(t,o)=>dd(e(t,o))}var qe=class extends Ta{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function dd(e){return e.then(t=>{if(!t.ok)throw new qe(t);return t})}import{BaseError as wP}from"make-error";function Ra(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let i=new AbortController;r=i,o={...o,signal:i.signal}}let a=e(t,o);if(n){let i=setTimeout(()=>{r?.abort()},n);a=a.finally(()=>{clearTimeout(i)})}return a}}function Fa(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>Sa({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>md({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var ld=(e,t)=>t(e);function md(e){let{makeFetch:t=fetch,fetchHandler:o=ld,useTimeout:r,requireOkResponse:n,mapResponse:a}=e,i=t;r&&(i=Ra(i)),n&&(i=xa(i));let s=Sa(e);return async(c,u)=>{let p=await s(c,u),d=o(p,i);return a&&(d=a(d)),d}}var yd=(e,t)=>new Request(e,t);function Sa(e){let{makeRequest:t=yd,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:a,useBaseUrlForConfiguredFetchRequests:i=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=i}=e,c=o?new URL(zn(o)):void 0,u=c?y=>{let h,T=y.toString();if(!s&&er(T))h=new URL(T);else{let R=c.origin+Hn("/"+c.pathname+"/"+y);h=new URL(R,c)}return h}:void 0;async function p(y){let h=ca(y)?await y:y;return ba(h)?h:t(h)}let d=u?async y=>{let h,T,R;if(typeof y=="string"?h=y:ba(y)?i?(h=y.url,T=y):R=y:R=await t(y),!R){let S=u(h);R=await t(S.href,T)}return R}:p,g;if(r!=null||n!=null){let y=me(r);async function h(){let R=await y();return n?{...R,timeout:n}:R}async function T(R,S){let M=await h(),v=hd(M,await S),U=v.timeout===void 0?R.timeout:v.timeout;return{...v,timeout:U}}a?g=(R,S)=>a(R,T(R,S)):g=(R,S)=>T(R,S)}else a?g=a:g=(y,h)=>h;return async(y,h)=>{try{let T=await d(y);h=await g(T,h);let R=await t(T,h);return R.timeout=n,R}catch(T){throw T instanceof Y?T:new Y(T)}}}function hd(e,t){let o;if(t){let r=fd([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function fd(e){let t=Uo();return N(e).forEach(o=>{let r=gd(o),n=new Set;r.forEach(([a,i])=>{n.has(a)||(t.delete(a),n.add(a)),i&&t.add(a,i)})}),t.tuples()}function gd(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 ba(e){return!!e.url}import{safeParse as Td}from"fast-content-type-parse";function oo(e){let t=e.headers.get("content-type"),o=Td(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Ca(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,a=async(i,s)=>{async function c(u){await n.waitForRateLimit();let p,d;try{p=await s(i.clone())}catch(y){d=y,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 a._rateLimiter=n,a}var nr=class extends Y{constructor(o){super("There was no next page for this.");this.page=o}},ar=class extends Y{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},xd=100;function $e(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:a}=e;return(i,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},p=u??a,d=c===null?Number.MAX_SAFE_INTEGER:c??xd;function g(h,T=void 0){return async()=>{let R=await t(h),{cursor:S,nextPageCursor:M,hasNext:v}=await o(R),U=S??T?.cursor,I=v!==!1,D=T?T.page+1:or,P=D>=d,ge={input:h,result:R,page:D,previous:T,hasNext:I,isAtMaxPage:P,cursor:U,nextPageCursor:M,fetchNext:Be(async()=>{if(P)throw new ar(ge,d);let Vt=I?await r(ge,h,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Vt)throw new nr(ge);return g({...h,...Vt},ge)()})};return ge}}return{input:i,fetchNext:Be(()=>g(i)())}}}function x(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?zt(e):e,a=r??!0?Kn(n??{}):n,i=new URLSearchParams(a);return o!=null&&q(o,s=>i.delete(s),!1),i}function ir(e){let t;if(typeof e=="string")t=e;else if(Rd(e))t=e.href;else{let o=ir(e.url);if(e.queryParams){let r=Sd(e.queryParams);ht(r)?t=o:t=Yn(o+`?${r.toString()}`)}else t=o}return t}function Rd(e){return typeof e=="object"&&e instanceof URL}function bd(e){return typeof e=="object"&&e instanceof URLSearchParams}function Fd(e){let t=[];return xe(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let a=String(r);q(n,i=>{i!=null&&t.push([a,String(i)])})}}),t}function Sd(e){let t;return bd(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):de(e)?t=new URLSearchParams(Fd(e)):t=Cd(e),t}function Cd(e){let t=[];return We(e,{forEach:o=>{let[r,n]=o,a=String(r);n!=null&&q(n,i=>{t.push([a,String(i)])})}}),new URLSearchParams(t)}var sr=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function Id(e){return e!=null?typeof e=="string"?e:JSON.stringify(e):void 0}var Od=e=>{throw new sr(e)},te=e=>null;function oe(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Od};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,a=Ia(o);return(i,s,c)=>{let u=ir(i),p=a(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(y=>{let h=y.json().catch(r),T=n?h.then(R=>n(R,y)):h;return d?T.then(R=>d(R,y)):T})}}function Ia(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=Re()}=e;return(r=t,n)=>{let a;return typeof r=="string"?a={method:r,body:n}:a=r,a=o(a),{...a,method:a.method,body:Id(a.body)}}}var cA=Ia();var re=Fa({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function He(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function K(e,t){return $e({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:rr(o),per_page:n.maxItemsPerPage??r.per_page}}})}function ro(e){switch(e){case"sandbox":return"https://recruitsandbox.zoho.com/recruit";case"production":return"https://recruit.zoho.com/recruit";default:return e}}var ze="Candidates",Oa="Job_Openings",no="Notes",Ma="Emails",Ot="Attachments";function ao(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=io(o);break}default:break}return t}function io(e){function t(i){let s;return typeof i=="object"?Array.isArray(i)?s=i.map(cr):i&&(s=io(i)):s=i,s}function o(i,s){return i.length>1?`(${i.join(s)})`:i[0]}function r(i,s){let c=N(i.map(t)).flatMap(f);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,a=n;return e.and&&(a=r([r(e.and,"and"),n],"and")),a}var Pa=Qo({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function cr(e){let t=Pa(e.value);return`(${e.field}:${e.filter}:${t})`}var Aa=ao;import{BaseError as Kd}from"make-error";import{BaseError as Ad}from"make-error";var Ed="__internal_data_array_blank_error";function kd(e){return Array.isArray(e?.data)}var Ye="success";function X(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var Fe=class extends Ad{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},j=class extends Fe{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},Je=class extends j{constructor(t,o){super({code:Ed,message:"Check data for individual errors."},t,o)}get errorDataArray(){return this.errorResponseData.data}};function ne(e,t){let{logDataArrayErrors:o=!1}=t??{};return r=>{r instanceof Je&&!o||(r instanceof j?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof Fe?console.log(`${e}Error(code:${r.code}): `,{error:r}):console.log(`${e}Error(name:${r.name}): `,{error:r}))}}function ae(e,t){return(o,r=t,n)=>async(a,i)=>{try{return await o(a,i)}catch(s){if(s instanceof qe){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 qe(o),a=e(t,n);if(a)throw a}return t}}var Zd="INTERNAL_ERROR",Dd="INVALID_TOKEN",$=class extends j{},Ea="FAILURE",ur=class extends j{},Ld="4834",Mt=class extends j{},vd="INVALID_QUERY",pr=class extends j{get details(){return this.error.details}},so="MANDATORY_NOT_FOUND",Se="DUPLICATE_DATA",co="INVALID_DATA",Nd="TOO_MANY_REQUESTS",ka=429,_d="X-RATELIMIT-LIMIT",wd="X-RATELIMIT-REMAINING",Vd="X-RATELIMIT-RESET",Za=100,Da=ye;function dr(e){let t=e.get(_d),o=e.get(wd),r=e.get(Vd),n=null;if(t!=null&&o!=null&&r!=null){let a=Number(t),i=Number(o),s=Number(r),c=new Date(s);n={limit:a,remaining:i,reset:s,resetAt:c}}return n}var Pt=class extends j{get headerDetails(){return dr(this.responseError.response.headers)}};function se(e,t){let o;if(kd(e))o=new Je(e,t);else{let r=he(e,t);if(r){let n=X(r);switch(n.code){case Zd:o=new ur(n,e,t);break;case Dd:o=new $(n,e,t);break;case Ld:o=new Mt(n,e,t);break;case vd:o=new pr(n,e,t);break;case Nd:o=new Pt(n,e,t);break;default:o=new j(n,e,t);break}}}return o}function he(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var La="ALREADY_ASSOCIATED",lr=class extends Kd{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 Fe{},mr=class extends Xe{},yr=class extends Xe{},uo=class extends Xe{get invalidFieldDetails(){return this.error.details}},hr=class extends uo{};function va(e){let t;switch(e.code){case co:{let o=new uo(e);o.invalidFieldDetails.id?t=new hr(e):t=o;break}case so:t=new mr(e);break;case Se:t=new yr(e);break;default:t=new Xe(e);break}return t}function Na(e,t){return o=>{if(o?.data?.length)return o;throw new lr(e,t)}}var Ud=ne("ZohoRecruit");async function Wd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=_a(t,e)),o}function _a(e,t){let o,r=he(e,t);if(r)switch(X(r).code){default:o=se(e,t);break}return o}var wa=ie(_a),Va=ae(Wd,Ud);import{BaseError as Bd}from"make-error";function gr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,w(o,{data:f(r)})).then(a=>{let i=Array.isArray(r),s=ce(f(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw va(p[0].result);c=u[0].result.details}return c}))}function Ka(e){return gr(e,"","POST")}function Ua(e){return gr(e,"/upsert","POST")}function Wa(e){return gr(e,"","PUT")}function Ba(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${x({ids:t,wf_trigger:r})}`,w("DELETE")).then(Gd)}function Ga(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,w("GET")).then(Na(t.module)).then(o=>o.data[0])}function ja(e){return(t=>e.fetchJson(`/v2/${t.module}?${Qa(t).toString()}`,w("GET")))}function Tr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Aa(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 Qa(r)}return(o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,w("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function qa(e){return K(Tr(e))}function Qe(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${br(n,n.filter).toString()}`,w("GET")).then(a=>a??(r!==!1?He():a))}}function xr(e){return Qe(e)({targetModule:Ma})}function $a(e){return K(xr(e))}function Rr(e){return Qe(e)({targetModule:Ot})}function Ha(e){return K(Rr(e))}var QA=20*1024*1024;function za(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:a}=t,i={attachments_category_id:E(o),attachments_category:E(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${Ot}?${x(i).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(a){let u=`${s}&${x({attachment_url:a}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function Ja(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"GET"}).then(oo)}function Ya(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"DELETE"})}var fr=class extends Bd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Xa(e){return t=>{let r=x(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v2/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?ro(t.apiUrl):""}${i}`;return e.fetchJson(c,w("POST")).then(u=>{if(u.code!=="success")throw new fr(u);return u.details})}}function Qa(...e){return x(e,{omitKeys:"module"})}function br(...e){return x(e,{omitKeys:["id","module"]})}function w(e,t){return{method:e,body:t??void 0}}function Gd(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===Ye?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function ce(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===Ye?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function ei(e){return t=>e.fetchJson(`/v2/${ze}/actions/associate`,w("PUT",{data:f(t)})).then(o=>{let r=o.data.map(()=>t),n=ce(r,o.data),{included:a,excluded:i}=be(n.errorItems,s=>s.result.code===Ea&&s.result.details.error[0].code===La);return{...n,errorItems:i,alreadyAssociatedErrorItems:a,allErrorItems:n.errorItems}})}function ti(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${br(t).toString()}`,w("GET")).then(o=>o??He())}function Fr(e){let t=ti(e);return o=>t({...o,module:ze})}function oi(e){return K(Fr(e))}function Sr(e,t=Oa){let o=ti(e);return r=>o({...r,module:t})}function ri(e){return K(Sr(e))}function Cr(e){return t=>e.fetchJson(`/v2/${no}`,w("POST",{data:t.data})).then(o=>ce(f(t.data),o.data))}function ni(e){return t=>e.fetchJson(`/v2/${no}?${x({ids:t.ids})}`,w("DELETE")).then(o=>ce(f(t.ids),o.data))}function Ir(e){return Qe(e)({targetModule:no})}function ai(e){return K(Ir(e))}function ii(e){let t=Cr(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:f(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function ui(e){return t=>e.fetchJson(`/v2/settings/tags?${x({module:t.module})}`,w("POST",{tags:f(t.tags)})).then(o=>{let r=ce(f(t.tags),o.tags),{included:n,excluded:a}=be(r.errorItems,i=>i.result.code===Se);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function pi(e){return t=>e.fetchJson(`/v2/settings/tags?${x({module:t.module,my_tags:t.my_tags})}`,w("GET")).then(o=>({...o,data:o.tags}))}var si=100;function di(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>si)throw new Error(`Cannot add tags to more than ${si} records at once.`);return e.fetchJson(`/v2/${ze}/actions/add_tags?${x({tag_names:t.tag_names,ids:t.ids})}`,w("POST")).then(o=>{let r=o.data.map(()=>t);return ce(r,o.data)})}}var ci=100;function li(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>ci)throw new Error(`Cannot remove tags from more than ${ci} records at once.`);return e.fetchJson(`/v2/${ze}/actions/remove_tags?${x({tag_names:t.tag_names,ids:t.ids})}`,w("POST")).then(o=>{let r=o.data.map(()=>t);return ce(r,o.data)})}}var jd="invalid_code",qd="invalid_client",Or=class extends Y{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},et=class extends Y{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},$d=ne("ZohoAccounts");async function Hd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=mi(t,e)),o}function mi(e,t){let o,r=e.error;if(r){let n=X(r);switch(n.code){case jd:case qd:o=new Or(n.code);break;default:o=se(e,t);break}}return o}var yi=ie(mi),hi=ae(Hd,$d);function Ce(e){return async()=>{let t=await e();if(!t.accessToken)throw new et;return t.accessToken}}var zd=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 Mr(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests!==!1?e.onTooManyRequests??zd:void 0,r=e.maxRateLimit??Za,n=e.resetPeriod??Da;function a(c,u){return{limit:c,startLimitAt:Math.ceil(c/10),cooldownRate:1.2*(c/(n/_)),exponentRate:1.08,maxWaitTime:_*10,resetPeriod:n,resetAt:u}}let i=a(r),s=da(i);return Ca({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,g=!1;if(p){let{remaining:y,limit:h,resetAt:T}=p;if(h!=null&&h!==r){let R=a(h,T??void 0);s.setConfig(R,!1)}if(s.setRemainingLimit(y),T&&s.setNextResetAt(T),g=!0,c.status===ka){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(g),d}})}function Ie(e){return Mr({...e,readRateLimitDetails:Jd})}function Jd(e){let t=dr(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function fi(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=Ie(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>re.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=ro(i.apiUrl),c=a({apiUrl:s}),u=Va(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=oe(u,{interceptJsonResponse:wa,handleFetchJsonParseErrorFunction:te});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function po(e){switch(e){case"sandbox":return"https://crmsandbox.zoho.com/crm";case"production":return"https://www.zohoapis.com/crm";default:return e}}var lo="Notes",gi="Emails",At="Attachments";var Ti=ao;import{BaseError as Yd}from"make-error";var Pr=class extends Yd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},tt=class extends Fe{},Ar=class extends tt{},Er=class extends tt{},mo=class extends tt{get invalidFieldDetails(){return this.error.details}},kr=class extends mo{};function xi(e){let t;switch(e.code){case co:{let o=new mo(e);o.invalidFieldDetails.api_name==="id"?t=new kr(e):t=o;break}case so:t=new Ar(e);break;case Se:t=new Er(e);break;default:t=new tt(e);break}return t}function Ri(e,t){return o=>{if(o?.data?.length)return o;throw new Pr(e,t)}}var Xd=ne("ZohoCrm",{logDataArrayErrors:!1});async function Qd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=bi(t,e)),o}function bi(e,t){let o,r=he(e,t);if(r)switch(X(r).code){default:o=se(e,t);break}return o}var Fi=ie(bi),Si=ae(Qd,Xd);import{BaseError as el}from"make-error";function Dr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,W(o,{data:f(r)})).catch(wi).then(a=>{let i=Array.isArray(r),s=Oe(f(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw xi(p[0].result);c=u[0].result.details}return c}))}function Ci(e){return Dr(e,"","POST")}function Ii(e){return Dr(e,"/upsert","POST")}function Oi(e){return Dr(e,"","PUT")}function Mi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${x({ids:t,wf_trigger:r})}`,W("DELETE")).catch(wi).then(ol)}function Pi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,W("GET")).then(Ri(t.module)).then(o=>o.data[0])}function Ai(e){return(t=>e.fetchJson(`/v8/${t.module}?${_i(t).toString()}`,W("GET")))}function Lr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Ti(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 _i(r)}return(o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,W("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function Ei(e){return K(Lr(e))}function ot(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${tl(n,n.filter).toString()}`,W("GET")).then(a=>a??(r!==!1?He():a))}}function vr(e){let t=ot(e)({targetModule:gi});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function ki(e){return K(vr(e))}function Nr(e){return ot(e)({targetModule:At})}function Zi(e){return K(Nr(e))}var mk=20*1024*1024;function Di(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,a={attachments_category_id:E(o),attachments_category:E(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let i=`/v8/${t.module}/${t.id}/${At}?${x(a).toString()}`,s=new FormData;return s.append("file",n),e.fetch(i,{method:"POST",headers:{"Content-Type":""},body:s})}}function Li(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${At}/${t.attachment_id}`,{method:"GET"}).then(oo)}function vi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${At}/${t.attachment_id}`,{method:"DELETE"})}var Zr=class extends el{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Ni(e){return t=>{let r=x(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v8/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?po(t.apiUrl):""}${i}`;return e.fetchJson(c,W("POST")).then(u=>{if(u.code!=="success")throw new Zr(u);return u.details})}}function _i(...e){return x(e,{omitKeys:"module"})}function tl(...e){return x(e,{omitKeys:["id","module"]})}function W(e,t){return{method:e,body:t??void 0}}function wi(e){let t;if(e instanceof Je)t={data:e.errorDataArray};else throw e;return t}function ol(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===Ye?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function Oe(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===Ye?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function _r(e){return t=>e.fetchJson(`/v2/${lo}`,W("POST",{data:t.data})).then(o=>Oe(f(t.data),o.data))}function Vi(e){return t=>e.fetchJson(`/v2/${lo}?${x({ids:t.ids})}`,W("DELETE")).then(o=>Oe(f(t.ids),o.data))}function wr(e){return ot(e)({targetModule:lo})}function Ki(e){return K(wr(e))}function Ui(e){let t=_r(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:f(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function Bi(e){return t=>e.fetchJson(`/v8/settings/tags?${x({module:t.module})}`,W("POST",{tags:f(t.tags)})).catch(o=>{let r;if(o instanceof j){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Oe(f(t.tags),o.tags),{included:n,excluded:a}=be(r.errorItems,i=>i.result.code===Se);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Gi(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,W("DELETE")).then(o=>o.tags)}function ji(e){return t=>e.fetchJson(`/v8/settings/tags?${x({module:t.module,my_tags:t.my_tags})}`,W("GET")).then(o=>({...o,data:o.tags}))}var Wi=100;function qi(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,W("POST",$i(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function $i(e){if(Array.isArray(e.ids)&&e.ids.length>Wi)throw new Error(`Cannot add/remove tags from more than ${Wi} records at once.`);let t=[...f(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&f(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:f(e.ids)}}function Hi(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,W("POST",$i(t))).then(o=>{let r=o.data.map(()=>t);return Oe(r,o.data)})}function zi(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=Ie(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>re.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=po(i.apiUrl),c=a({apiUrl:s}),u=Si(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=oe(u,{interceptJsonResponse:Fi,handleFetchJsonParseErrorFunction:te});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Ji(e,t){return $e({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.page_context?.has_more_rows??!1}},buildInputForNextPage:function(o,r,n){let i=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??i?.row_count??20,c=(i?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function ke(e,t){return{method:e,body:t??void 0}}function Yi(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,ke("GET"))}function Vr(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)}},ke("GET"))}}function Xi(e){let t=Vr(e);return Ji(t)}function Qi(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,ke("GET"))}function es(e){return()=>e.fetchJson("/fieldtypes",ke("GET"))}function ts(e){return({requestId:t,...o})=>{let n=x(o).toString(),a=n?`?${n}`:"",i=`/requests/${t}/pdf${a}`;return e.fetch(i,{method:"GET"})}}function os(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function rs(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 ns(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,ke("PUT",{requests:o}))}function as(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,ke("POST",r))}}function is(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,ke("PUT",{expire_by:o}))}function ss(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let a=x(n),i=a.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...i?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()}:{}})}}function cs(e){switch(e){case"sandbox":return"https://signsandbox.zoho.com/api/v1";case"production":return"https://sign.zoho.com/api/v1";default:return e}}var rl=ne("ZohoSign",{logDataArrayErrors:!1});async function nl(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=us(t,e)),o}function us(e,t){let o,r=he(e,t);if(r)switch(X(r).code){default:o=se(e,t);break}return o}var ps=ie(us),ds=ae(nl,rl);function ls(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=Ie(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>re.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=cs(i.apiUrl),c=a({apiUrl:s}),u=ds(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=oe(u,{interceptJsonResponse:ps,handleFetchJsonParseErrorFunction:te});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function ms(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var al=ne("ZohoDesk",{logDataArrayErrors:!1});async function il(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ys(t,e)),o}function ys(e,t){let o,r=he(e,t);if(r)switch(X(r).code){default:o=se(e,t);break}return o}var hs=ie(ys),fs=ae(il,al);var sl="X-Rate-Limit-Remaining-v3",cl="Retry-After",ul=200;function pl(e){let t=e.get(sl),o;if(t!=null){let r=Number(t),n,a=e.get(cl);if(a!=null){let i=Number(a);isNaN(i)||(n=new Date(Date.now()+i*_))}isNaN(r)||(o={remaining:r,resetAt:n})}return o}function gs(e){return Mr({maxRateLimit:ul,...e,readRateLimitDetails:pl})}function Ts(e){let{accountsContext:t}=e,o=Ce(t.loadAccessToken),r=gs(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>re.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:i.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!i.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=ms(i.apiUrl),c=a({apiUrl:s,orgId:i.orgId}),u=fs(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=oe(u,{interceptJsonResponse:hs,handleFetchJsonParseErrorFunction:te});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var xs=25;function Q(e,t){return $e({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=xs}},buildInputForNextPage:function(o,r,n){let a=n.maxItemsPerPage??r.limit??xs,s=(r.from??1)+a;return{...r,from:s,limit:a}}})}function Ze(e,t){return{method:e,body:t??void 0}}function rt(e,t){return x(e,{omitKeys:t})}function yo(e){let t;return e&&(t=E(f(e))),t}function Kr(e){return t=>{let{include:o,...r}=t,n=rt([{...r,include:yo(o)}]);return e.fetchJson(`/tickets?${n}`,Ze("GET")).then(a=>a??{data:[]})}}function Rs(e){return t=>{let{ticketId:o,include:r}=t,a=rt([{include:yo(r)}]).toString();return e.fetchJson(`/tickets/${o}${a?`?${a}`:""}`,Ze("GET"))}}function Ur(e){return t=>{let o=rt([t]);return e.fetchJson(`/tickets/search?${o}`,Ze("GET")).then(r=>r??{data:[]})}}function bs(e){return t=>{let{contactId:o,include:r,...n}=t,a=rt([{...n,include:yo(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${a}`,Ze("GET")).then(i=>i??{data:[]})}}function Fs(e){return t=>{let{productId:o,include:r,...n}=t,a=rt([{...n,include:yo(r)}]);return e.fetchJson(`/products/${o}/tickets?${a}`,Ze("GET")).then(i=>i??{data:[]})}}function Ss(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ze("GET"))}function Cs(e){return t=>{let o=rt([{agentIds:E(f(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ze("GET"))}}function Is(e){return Q(Kr(e))}function Os(e){return Q(Ur(e))}function Ms(e){return{method:e}}function Ps(e){return t=>{let o=x([t]);return e.fetchJson(`/departments?${o}`,Ms("GET")).then(r=>r??{data:[]})}}function As(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ms("GET"))}function Wr(e){return{method:e}}function Es(e){let t;return e&&(t=E(f(e))),t}function Br(e){return t=>{let{include:o,...r}=t,n=x([{...r,include:Es(o)}]);return e.fetchJson(`/contacts?${n}`,Wr("GET")).then(a=>a??{data:[]})}}function ks(e){return t=>{let{contactId:o,include:r}=t,a=x([{include:Es(r)}]).toString();return e.fetchJson(`/contacts/${o}${a?`?${a}`:""}`,Wr("GET"))}}function Zs(e){return t=>{let o=x([{contactIds:E(f(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Wr("GET")).then(r=>r??[])}}function Ds(e){return Q(Br(e))}function Et(e,t){return{method:e,body:t??void 0}}function Ls(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Et("GET")).then(o=>o??[])}function vs(e){return t=>{let o={tags:f(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,Et("POST",o)).then(r=>r??[])}}function Ns(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Et("DELETE"))}function _s(e){return t=>{let o=x([t]);return e.fetchJson(`/tags/search?${o}`,Et("GET")).then(r=>r??{data:[]})}}function ws(e){return t=>{let o=x([t]);return e.fetchJson(`/ticketTags?${o}`,Et("GET")).then(r=>r??{data:[]})}}function Gr(e,t){return{method:e,body:t??void 0}}function Vs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("GET")).then(o=>o??[])}function Ks(e){return t=>{let o={ids:f(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("POST",o))}}function Us(e){return t=>{let o={ids:f(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,Gr("DELETE",o))}}function Ws(e,t){return{method:e,body:t??void 0}}function dl(e){let t;return e&&(t=E(f(e))),t}function Bs(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:dl(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${a}`,Ws("GET")).then(i=>i??{data:[]})}}function Gs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,Ws("DELETE"))}function ho(e,t){return{method:e,body:t??void 0}}function js(e){let t;return e&&(t=E(f(e))),t}function qs(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:js(r)}]);return e.fetchJson(`/tickets/${o}/comments?${a}`,ho("GET")).then(i=>i??{data:[]})}}function $s(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,i=x([{include:js(n)}]).toString();return e.fetchJson(`/tickets/${o}/comments/${r}${i?`?${i}`:""}`,ho("GET"))}}function Hs(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,ho("POST",r))}}function zs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,ho("DELETE"))}function kt(e,t){return{method:e,body:t??void 0}}function Js(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,kt("GET"))}function Ys(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,kt("POST",r))}}function Xs(e){return t=>{let{ticketId:o,...r}=t,n=x([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,kt("GET")).then(a=>a??{data:[]})}}function Qs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,kt("GET"))}function ec(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,kt("GET"))}function tc(e){return{method:e}}function oc(e){let t;return e&&(t=E(f(e))),t}function jr(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:oc(r)}]);return e.fetchJson(`/tickets/${o}/threads?${a}`,tc("GET")).then(i=>i??{data:[]})}}function rc(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,i=x([{include:oc(n)}]).toString();return e.fetchJson(`/tickets/${o}/threads/${r}${i?`?${i}`:""}`,tc("GET"))}}function nc(e){return Q(jr(e))}function ll(e){return{method:e}}function ml(e){let t;return e&&(t=E(f(e))),t}function qr(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:ml(r)}]);return e.fetchJson(`/tickets/${o}/activities?${a}`,ll("GET")).then(i=>i??{data:[]})}}function ac(e){return Q(qr(e))}function fo(e){return{method:e}}function ic(e){let t;return e&&(t=E(f(e))),t}function $r(e){return t=>{let{include:o,...r}=t,n=x([{...r,include:ic(o)}]);return e.fetchJson(`/agents?${n}`,fo("GET")).then(a=>a??{data:[]})}}function sc(e){return t=>{let{agentId:o,include:r}=t,a=x([{include:ic(r)}]).toString();return e.fetchJson(`/agents/${o}${a?`?${a}`:""}`,fo("GET"))}}function cc(e){return t=>{let o=x([{agentIds:E(f(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,fo("GET")).then(r=>r?.data??[])}}function uc(e){return()=>e.fetchJson("/myinfo",fo("GET"))}function pc(e){return Q($r(e))}function go(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:a,refreshToken:i}=t??{},s=a?.clientId??o,c=a?.clientSecret??r,p=x({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:i??n});return e.fetchJson(`/oauth/v2/token?${p}`,yl("POST"))}}function yl(e,t){return{method:e,body:t}}var hl="https://accounts.zoho.com";function dc(e){return e==="us"?hl:e}function lc(e){let t=Ie(),{logZohoServerErrorFunction:o,fetchFactory:r=n=>re.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 a=dc(n.apiUrl??"us"),i=r({apiUrl:a}),s=hi(i,o),c=oe(s,{interceptJsonResponse:yi,handleFetchJsonParseErrorFunction:te}),u=async()=>{let y=new Date().getTime(),{access_token:h,api_domain:T,scope:R,expires_in:S}=await go(d)();return{accessToken:h,apiDomain:T,expiresIn:S,expiresAt:new Date(y+S*_),scope:R}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=fl({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:a}};return{accountsContext:d}}}function fl(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??ye,a=null,i=async()=>{a=null},s=async()=>{if(!a){let c=await o?.loadCachedToken();c&&(a=c)}if(a!=null&&new Date().getTime()+n>=a.expiresAt.getTime()&&(a=null),!a){try{a=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new et("Token Refresh Failed")}try{await o?.updateCachedToken(a)}catch{}}return a};return s.resetAccessToken=i,s}function Me(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Pe=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 gl}from"@nestjs/common";import{dirname as Tl}from"node:path";import{readFile as xl,writeFile as Rl,rm as bl,mkdirSync as Fl}from"node:fs";var nt=class{};nt=O([gl()],nt);function Sl(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function mc(e,t){let o=[...e],r=typeof t=="function"?t:t!==!1?Sl:void 0;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");return{loadZohoAccessTokenCache:function(a){let i=o.map(u=>u.loadZohoAccessTokenCache(a)),s=la({promiseFactories:i.map(u=>()=>u.loadCachedToken().catch(()=>null).then(p=>{let d;return p&&!eo(p.expiresAt)&&(d=p),d})),successOnMaybe:!1,throwErrors:!1});return{loadCachedToken:function(){return s()},updateCachedToken:async function(u){return Promise.allSettled(i.map(p=>p.updateCachedToken(u).then(()=>null).catch(d=>[p,d]))).then(p=>{if(r!=null){let d=N(p.map(g=>g.value));d.length&&r(d)}})},clearCachedToken:async function(){await Promise.allSettled(i.map(u=>u.clearCachedToken()))}}}}}function yc(e,t){let o=e??{};function r(n){return{loadCachedToken:async function(){let i=o[n];return t&&console.log("retrieving access token from memory: ",{token:i,service:n}),i},updateCachedToken:async function(i){o[n]=i,t&&console.log("updating access token in memory: ",{accessToken:i,service:n})},clearCachedToken:async function(){delete o[n],t&&console.log("clearing access token in memory: ",{service:n})}}}return{loadZohoAccessTokenCache:r}}var Cl=".tmp/zoho-access-tokens.json";function hc(e=Cl,t=!0){let o=null;async function r(){return o||(await n()??{})}function n(){return new Promise(c=>{Fl(Tl(e),{recursive:!0}),xl(e,{},(u,p)=>{let d;if(!u)try{d=JSON.parse(p.toString()),We(d,{forEach:g=>{g[1]&&(g[1].expiresAt=new Date(g[1].expiresAt))}})}catch(g){console.error("Failed reading token file: ",g)}c(d)})}).then(c=>(t&&(o={...o,...c}),c))}async function a(c){return new Promise((u,p)=>{Rl(e,JSON.stringify(c),{},d=>{d?p(d):u()})})}async function i(){return new Promise((c,u)=>{bl(e,p=>{p?u(p):c()})})}function s(c){return{loadCachedToken:async function(){return(await r())[c]},updateCachedToken:async function(p){let d=await r();d&&(d[c]=p);try{await a(d)}catch(g){console.error("Failed updating access token in file: ",g)}},clearCachedToken:async function(){try{await a({})}catch(p){console.error("Failed clearing access token in file: ",p)}}}}return{loadZohoAccessTokenCache:s,readTokenFile:n,writeTokenFile:a,deleteTokenFile:i}}var V=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=lc(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return go(this.accountsContext)}};V=O([Il(),A(0,fc(Pe)),A(1,fc(nt))],V);import{Inject as gc,Injectable as Ol}from"@nestjs/common";var Zt=class{zohoCrm;factoryConfig;static assertValidConfig(t){Me(t.zohoCrm)}};var De=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=zi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Ci(this.crmContext)}get upsertRecord(){return Ii(this.crmContext)}get updateRecord(){return Oi(this.crmContext)}get deleteRecord(){return Mi(this.crmContext)}get getRecordById(){return Pi(this.crmContext)}get getRecords(){return Ai(this.crmContext)}get searchRecords(){return Lr(this.crmContext)}get searchRecordsPageFactory(){return Ei(this.crmContext)}get getRelatedRecordsFunctionFactory(){return ot(this.crmContext)}get getEmailsForRecord(){return vr(this.crmContext)}get getEmailsForRecordPageFactory(){return ki(this.crmContext)}get getAttachmentsForRecord(){return Nr(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Zi(this.crmContext)}get uploadAttachmentForRecord(){return Di(this.crmContext)}get downloadAttachmentForRecord(){return Li(this.crmContext)}get deleteAttachmentFromRecord(){return vi(this.crmContext)}get createNotes(){return _r(this.crmContext)}get deleteNotes(){return Vi(this.crmContext)}get createNotesForRecord(){return Ui(this.crmContext)}get getNotesForRecord(){return wr(this.crmContext)}get getNotesForRecordPageFactory(){return Ki(this.crmContext)}get executeRestApiFunction(){return Ni(this.crmContext)}get createTagsForModule(){return Bi(this.crmContext)}get deleteTag(){return Gi(this.crmContext)}get getTagsForModule(){return ji(this.crmContext)}get addTagsToRecords(){return qi(this.crmContext)}get removeTagsFromRecords(){return Hi(this.crmContext)}};De=O([Ol(),A(0,gc(Zt)),A(1,gc(V))],De);import{ConfigModule as _L,ConfigService as wL}from"@nestjs/config";import{Inject as Tc,Injectable as Ml}from"@nestjs/common";var Dt=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Me(t.zohoRecruit)}};var Le=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=fi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return Ka(this.recruitContext)}get upsertRecord(){return Ua(this.recruitContext)}get updateRecord(){return Wa(this.recruitContext)}get deleteRecord(){return Ba(this.recruitContext)}get getRecordById(){return Ga(this.recruitContext)}get getRecords(){return ja(this.recruitContext)}get searchRecords(){return Tr(this.recruitContext)}get searchRecordsPageFactory(){return qa(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return Qe(this.recruitContext)}get getEmailsForRecord(){return xr(this.recruitContext)}get getEmailsForRecordPageFactory(){return $a(this.recruitContext)}get getAttachmentsForRecord(){return Rr(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return Ha(this.recruitContext)}get uploadAttachmentForRecord(){return za(this.recruitContext)}get downloadAttachmentForRecord(){return Ja(this.recruitContext)}get deleteAttachmentFromRecord(){return Ya(this.recruitContext)}get createNotes(){return Cr(this.recruitContext)}get deleteNotes(){return ni(this.recruitContext)}get createNotesForRecord(){return ii(this.recruitContext)}get getNotesForRecord(){return Ir(this.recruitContext)}get getNotesForRecordPageFactory(){return ai(this.recruitContext)}get executeRestApiFunction(){return Xa(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return ei(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Fr(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return oi(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Sr(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return ri(this.recruitContext)}get createTagsForModule(){return ui(this.recruitContext)}get getTagsForModule(){return pi(this.recruitContext)}get addTagsToRecords(){return di(this.recruitContext)}get removeTagsFromRecords(){return li(this.recruitContext)}};Le=O([Ml(),A(0,Tc(Dt)),A(1,Tc(V))],Le);import{ConfigModule as iv,ConfigService as sv}from"@nestjs/config";import{Inject as xc,Injectable as Pl}from"@nestjs/common";var Lt=class{zohoSign;factoryConfig;static assertValidConfig(t){Me(t.zohoSign)}};var vt=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=ls({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return Yi(this.signContext)}get getDocuments(){return Vr(this.signContext)}get getDocumentsPageFactory(){return Xi(this.signContext)}get getDocumentFormData(){return Qi(this.signContext)}get retrieveFieldTypes(){return es(this.signContext)}get downloadPdf(){return ts(this.signContext)}get downloadCompletionCertificate(){return os(this.signContext)}get createDocument(){return rs(this.signContext)}get updateDocument(){return ns(this.signContext)}get sendDocumentForSignature(){return as(this.signContext)}get extendDocument(){return is(this.signContext)}get deleteDocument(){return ss(this.signContext)}};vt=O([Pl(),A(0,xc(Lt)),A(1,xc(V))],vt);import{ConfigModule as Av,ConfigService as Ev}from"@nestjs/config";function Rc(e){return{...e,operationType:e.notifications.operation_type}}var bc=ya(e=>e.operationType),Fc=fa({configurerForAccessor:e=>{let t=ha(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 Sc="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",ve=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{defer as jv,from as qv}from"rxjs";import{combineLatest as yN,filter as hN,skipWhile as fN,startWith as gN,switchMap as TN,of as xN,map as RN,delay as bN,EMPTY as FN}from"rxjs";import{switchMap as cN,of as uN,isObservable as pN}from"rxjs";import{switchMap as VN,distinctUntilChanged as KN,shareReplay as UN,map as WN,BehaviorSubject as BN,of as GN,combineLatest as jN,EMPTY as qN,skip as $N,defaultIfEmpty as HN}from"rxjs";import{distinctUntilChanged as AN,filter as EN,mergeMap as kN,isObservable as ZN}from"rxjs";import{BehaviorSubject as n_,switchMap as a_,map as i_,distinctUntilChanged as s_,shareReplay as c_,first as u_,merge as p_,finalize as d_}from"rxjs";import{map as y_}from"rxjs";import{first as S_,shareReplay as C_,firstValueFrom as I_,switchMap as O_,of as M_}from"rxjs";import{startWith as GW,map as jW,shareReplay as qW,skipWhile as $W,distinctUntilChanged as HW,filter as zW,first as JW,firstValueFrom as YW,switchMap as XW,from as QW}from"rxjs";import{exhaustMap as k_,map as Z_,scan as D_,shareReplay as L_,startWith as v_,distinctUntilChanged as N_,switchMap as __,combineLatest as w_,of as V_,first as K_}from"rxjs";import{identity as J_,map as Y_}from"rxjs";import{filter as G_,map as j_,scan as q_}from"rxjs";import{combineLatest as rw,map as nw,of as aw,switchMap as iw,throttleTime as sw}from"rxjs";import{filter as lw,map as mw,skipWhile as yw,switchMap as hw,takeWhile as fw}from"rxjs";import{of as xw,timeout as Rw,tap as bw,throwError as Fw,map as Sw,startWith as Cw}from"rxjs";import{takeWhile as Aw,map as Ew,timer as kw}from"rxjs";import{distinctUntilChanged as _w}from"rxjs";import{finalize as Uw,of as Ww,scan as Bw,switchMap as Gw}from"rxjs";import{startWith as $w,distinctUntilChanged as Hw,shareReplay as zw,map as Jw,first as Yw}from"rxjs";import{tap as tV,delayWhen as oV,timer as rV,asyncScheduler as nV}from"rxjs";import{map as lV,switchMap as mV,shareReplay as yV,distinctUntilChanged as hV}from"rxjs";import{scan as FV}from"rxjs";import{combineLatest as OV,skipWhile as MV,startWith as PV,BehaviorSubject as AV,shareReplay as EV,map as kV,finalize as ZV,of as DV,mergeMap as LV,from as vV}from"rxjs";import{map as VV}from"rxjs";import{throttleTime as GV,distinctUntilChanged as jV,BehaviorSubject as qV}from"rxjs";import{map as QV,combineLatest as eK,of as tK}from"rxjs";import{map as cK,of as uK,switchMap as pK}from"rxjs";import{distinctUntilChanged as TK}from"rxjs";import{map as CK,switchMap as IK}from"rxjs";import{first as PK}from"rxjs";import{switchMap as oU,of as rU}from"rxjs";import{map as WU,switchMap as BU,shareReplay as GU,distinctUntilChanged as jU,BehaviorSubject as qU,isObservable as $U,of as HU}from"rxjs";function Ic(e){let t=!bo(e),o;return t?o="loading":le(e,"value")?o="success":le(e,"error")?o="error":o="idle",o}function bo(e){let t=!1;if(e){let o=e.loading;o===!0?t=!1:t=o===!1||!!(e.value??e.error)||e.value===null}return t}function Fo(e){let t=e==="idle";return o=>o?Ic(o)===e:t}var uU=Fo("idle"),Nt=Fo("loading");var pU=Fo("success"),dU=Fo("error");import{startWith as bU,filter as FU,map as SU,tap as CU,catchError as IU,combineLatest as OU,distinctUntilChanged as MU,first as PU,of as AU,shareReplay as EU,switchMap as kU,firstValueFrom as ZU,scan as DU}from"rxjs";import{distinctUntilChanged as lW,map as mW,shareReplay as yW,skipWhile as hW}from"rxjs";import{map as oW}from"rxjs";import{BehaviorSubject as FW}from"rxjs";import{combineLatest as cB,map as uB,shareReplay as pB,skipWhile as dB}from"rxjs";import{map as fB,shareReplay as gB}from"rxjs";import{distinctUntilChanged as EB,map as kB,scan as ZB,startWith as DB,catchError as LB,skip as vB,mergeMap as NB,delay as _B,BehaviorSubject as wB,combineLatest as VB,exhaustMap as KB,filter as UB,first as WB,of as BB,shareReplay as GB,defaultIfEmpty as jB}from"rxjs";import{defaultIfEmpty as sG,delay as cG,filter as uG,first as pG,map as dG,shareReplay as lG,switchMap as mG,tap as yG,startWith as hG,timeout as fG,of as gG,BehaviorSubject as TG,Subject as xG}from"rxjs";import{isObservable as WG}from"rxjs";import{filter as OG,map as MG,BehaviorSubject as PG,of as AG,first as EG,shareReplay as kG,switchMap as ZG,delay as DG,from as LG,tap as vG}from"rxjs";import{createParamDecorator as Nl}from"@nestjs/common";var xj=Nl((e,t)=>_l(t));function _l(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Xr,BadRequestException as wl,InternalServerErrorException as Vl,Logger as Kl}from"@nestjs/common";import Ul from"raw-body";import{parse as Wl}from"querystring";var Pc=new Kl("RawBody"),Cj=Xr(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Pc.error("RawBody request was not readable. This is generally due to bad configuration."),new wl("Invalid body");return await Ul(o)}),Ac=Xr(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Pc.error("RawBody expected a buffer set to req.body."),new Vl("failed parsing body");return r}),Ij=Xr(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=Bl(o.body),o.body});function Bl(e){let t=Gl(e);return Wl(t)}function Gl(e){return e.toString("utf8").trim()}import{Injectable as jl}from"@nestjs/common";import ql from"body-parser";var it=class{use(t,o,r){ql.json()(t,o,r)}};it=O([jl()],it);import{Injectable as $l}from"@nestjs/common";import Hl from"body-parser";var st=class{use(t,o,r){Hl.raw({type:"*/*"})(t,o,r)}};st=O([$l()],st);import{Logger as zl,Module as Jl,RequestMethod as Yl}from"@nestjs/common";var Xl="/webhook",Ql={path:`${Xl}/{*path}`,method:Yl.POST},Qr=class{configure(t){em(t)}},So=class extends Qr{logger=new zl("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};So=O([Jl({})],So);function em(e){e.apply(st).forRoutes(Ql).apply(it).forRoutes("{*path}")}var Ec="CLIENT_WEB_APP_URL";var Ne=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as tm,Injectable as om}from"@nestjs/common";var _e=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]}};_e=O([om(),A(0,tm(Ne))],_e);import{Module as rm}from"@nestjs/common";import{ConfigModule as nm,ConfigService as am}from"@nestjs/config";function im(e){let t={client:{clientWebAppUrl:e.get(Ec)}};return Ne.assertValidConfig(t),t}var Co=class{};Co=O([rm({imports:[nm],providers:[{provide:Ne,inject:[am],useFactory:im},_e],exports:[_e]})],Co);var kc="SERVER_ENV_TOKEN";import{Inject as sm,Injectable as cm}from"@nestjs/common";function Zc(){return process.env.NODE_ENV==="test"}var Io=class{constructor(t){this.env=t}get isTestingEnv(){return Zc()}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}};Io=O([cm(),A(0,sm(kc))],Io);import{Controller as hm,Inject as fm,Post as gm,Req as Tm}from"@nestjs/common";import{Inject as lm,Injectable as mm,Logger as ym}from"@nestjs/common";import{createHmac as um,timingSafeEqual as pm}from"node:crypto";var dm="x-zs-webhook-signature";function Dc(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[dm];if(!n)return{valid:!1};let a=r.toString("utf-8"),i=um("sha256",t).update(a,"utf-8").digest("base64"),s=!1;try{let u=Buffer.from(n,"base64"),p=Buffer.from(i,"base64");u.length===p.length&&(s=pm(u,p))}catch{s=!1}let c;if(s)try{let u=JSON.parse(a);c=Rc(u)}catch{s=!1}return s&&c?{valid:!0,event:c}:{valid:!1}}}var fe=class{logger=new ym("ZohoSignWebhookService");_verifier;handler=bc();configure=Fc(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Dc({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)}};fe=O([mm(),A(0,lm(ve))],fe);var we=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};O([gm(),A(0,Tm()),A(1,Ac())],we.prototype,"handleZohoSignWebhook",1),we=O([hm("/webhook/zoho/sign"),A(0,fm(fe))],we);import{Module as xm}from"@nestjs/common";import{ConfigModule as Rm,ConfigService as bm}from"@nestjs/config";function Fm(e){let t={zohoSignWebhook:{webhookSecret:e.get(Sc)}};return ve.assertValidConfig(t),t}var Oo=class{};Oo=O([xm({imports:[Rm],controllers:[we],providers:[{provide:ve,inject:[bm],useFactory:Fm},fe],exports:[fe]})],Oo);import{Inject as Lc,Injectable as Sm}from"@nestjs/common";var _t=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Me(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=Ts({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return Kr(this.deskContext)}get getTicketById(){return Rs(this.deskContext)}get searchTickets(){return Ur(this.deskContext)}get getTicketsForContact(){return bs(this.deskContext)}get getTicketsForProduct(){return Fs(this.deskContext)}get getTicketMetrics(){return Ss(this.deskContext)}get getAgentsTicketsCount(){return Cs(this.deskContext)}get getTicketsPageFactory(){return Is(this.deskContext)}get searchTicketsPageFactory(){return Os(this.deskContext)}get getDepartments(){return Ps(this.deskContext)}get getDepartmentById(){return As(this.deskContext)}get getContacts(){return Br(this.deskContext)}get getContactById(){return ks(this.deskContext)}get getContactsByIds(){return Zs(this.deskContext)}get getContactsPageFactory(){return Ds(this.deskContext)}get getTicketTags(){return Ls(this.deskContext)}get associateTicketTags(){return vs(this.deskContext)}get dissociateTicketTag(){return Ns(this.deskContext)}get searchTags(){return _s(this.deskContext)}get getAllTags(){return ws(this.deskContext)}get getTicketFollowers(){return Vs(this.deskContext)}get addTicketFollowers(){return Ks(this.deskContext)}get removeTicketFollowers(){return Us(this.deskContext)}get getTicketAttachments(){return Bs(this.deskContext)}get deleteTicketAttachment(){return Gs(this.deskContext)}get getTicketComments(){return qs(this.deskContext)}get getTicketCommentById(){return $s(this.deskContext)}get createTicketComment(){return Hs(this.deskContext)}get deleteTicketComment(){return zs(this.deskContext)}get getTicketTimer(){return Js(this.deskContext)}get performTicketTimerAction(){return Ys(this.deskContext)}get getTicketTimeEntries(){return Xs(this.deskContext)}get getTicketTimeEntryById(){return Qs(this.deskContext)}get getTicketTimeEntrySummation(){return ec(this.deskContext)}get getTicketThreads(){return jr(this.deskContext)}get getTicketThreadById(){return rc(this.deskContext)}get getTicketThreadsPageFactory(){return nc(this.deskContext)}get getTicketActivities(){return qr(this.deskContext)}get getTicketActivitiesPageFactory(){return ac(this.deskContext)}get getAgents(){return $r(this.deskContext)}get getAgentById(){return sc(this.deskContext)}get getAgentsByIds(){return cc(this.deskContext)}get getMyInfo(){return uc(this.deskContext)}get getAgentsPageFactory(){return pc(this.deskContext)}};Ve=O([Sm(),A(0,Lc(_t)),A(1,Lc(V))],Ve);import{ConfigModule as L$,ConfigService as v$}from"@nestjs/config";function Cm(e){return`${e.clientId}:${e.refreshToken}`}function ct(e){let t=mc([yc(),hc(mt())]),o=new Map;function r(p,d){let g=Cm(p),y=o.get(g);if(y)return y;let h={zohoAccounts:{serviceAccessTokenKey:d,refreshToken:p.refreshToken,clientId:p.clientId,clientSecret:p.clientSecret,apiUrl:p.region??"us"}},T=new V(h,t);return o.set(g,T),T}let n,a=yt(e,"recruit");if(a){let p=r(a,"recruit"),d={zohoRecruit:{apiUrl:a.apiMode}};n=new Le(d,p)}let i,s=yt(e,"crm");if(s){let p=r(s,"crm"),d={zohoCrm:{apiUrl:s.apiMode}};i=new De(d,p)}let c,u=yt(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:i,deskApi:c}}import{existsSync as Nc,mkdirSync as _c,writeFileSync as Im}from"node:fs";import{join as wc}from"node:path";var pt={};function Vc(e){pt=e}var Om=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/1000\.\w{20,}/g];function ut(e){let t=e;for(let o of Om)t=t.replace(o,"[REDACTED]");return t}function Kc(){return new Date().toISOString().replace(/[:.]/g,"-")}function en(){return pt}function tn(e,t){let{dumpDir:o,commandPath:r}=pt;if(!o)return;Nc(o)||_c(o,{recursive:!0});let n=r?.length?r.join("_"):"response",a=Kc(),i=t?`${n}_${a}_${t}`:`${n}_${a}`;return wc(o,`${i}.${e}`)}function Mm(e,t){let{dumpDir:o,commandPath:r}=pt;if(!o)return;Nc(o)||_c(o,{recursive:!0});let a=`${r?.length?r.join("_"):"response"}_${Kc()}.json`,i=wc(o,a),s={ok:!0,data:e,...t?{meta:t}:{}};Im(i,JSON.stringify(s,null,2))}function dt(e,t){let o=t.split(",").map(r=>r.trim());return Array.isArray(e)?e.map(r=>vc(r,o)):e!=null&&typeof e=="object"?vc(e,o):e}function vc(e,t){if(e==null||typeof e!="object")return e;let o={};for(let r of t)r in e&&(o[r]=e[r]);return o}function l(e,t){Mm(e,t);let r={ok:!0,data:pt.pick?dt(e,pt.pick):e,...t?{meta:t}:{}};console.log(JSON.stringify(r))}function m(e){let t=Pm(e);console.log(JSON.stringify(t))}function Pm(e){return e instanceof $?{ok:!1,error:ut(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof Mt?{ok:!1,error:ut(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Pt?{ok:!1,error:ut(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof j?{ok:!1,error:ut(e.message),code:"API_ERROR"}:e instanceof Error?{ok:!1,error:ut(e.message),code:"ERROR"}:{ok:!1,error:ut(String(e)),code:"UNKNOWN_ERROR"}}var Uc={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"},Wc={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 Am(e){if(e){if(e.startsWith("http://")||e.startsWith("https://"))try{let o=new URL(e).searchParams.get("code");if(!o)throw new Error('No "code" parameter found in the provided URL.');return o}catch(t){throw t instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`):t}return e}}var Em={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:[...Kt],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 B(),o=e.product,r=e.clientId??t?.shared?.clientId,n=e.clientSecret??t?.shared?.clientSecret,a=e.redirectUri,i=e.region??t?.shared?.region??"us",s=e.scopes.split(",").map(d=>d.trim()),c=Am(e.code),u=e.token,p=Uc[i]??Uc.us;if(!r||!n)throw new Error("--client-id and --client-secret are required. Get them from https://api-console.zoho.com/");if(u){let d={clientId:r,clientSecret:n,refreshToken:u};if(o){let g={...d,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0},y=await G({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:g});l({success:!0,product:o,refreshToken:Te(u),configSaved:!0,configuredProducts:J(y)})}else{let g=await G({shared:{...d,region:i,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0});l({success:!0,refreshToken:Te(u),configSaved:!0,configuredProducts:J(g)})}}else if(c){let d=`${p}/oauth/v2/token`,g=new URLSearchParams({grant_type:"authorization_code",client_id:r,client_secret:n,redirect_uri:a,code:c}),h=await(await fetch(d,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:g.toString()})).json();if(h.error)throw new Error(`Token exchange failed: ${h.error}`);let T=h.refresh_token;if(!T)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:T},S;o?S=await G({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:{...R,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0}}):S=await G({shared:{...R,region:i,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({step:2,success:!0,product:o??"shared",refreshToken:Te(T),accessToken:h.access_token?Te(h.access_token):null,scope:h.scope,configSaved:!0,configuredProducts:J(S)})}else{let d=s.flatMap(y=>Wc[y]??[]);if(d.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Wc).join(", ")}`);let g=`${p}/oauth/v2/auth?scope=${d.join(",")}&client_id=${encodeURIComponent(r)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(a)}`;await G({shared:{clientId:r,clientSecret:n,refreshToken:t?.shared?.refreshToken??"",region:i,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:g,redirectUri:a,scopes:d,credentialsSaved:!0,nextStep:'zoho-cli auth setup --code "PASTE_REDIRECT_URL_OR_AUTH_CODE"'})}}catch(t){m(t),process.exit(1)}}},km={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:[...Kt],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 G({shared:(await B())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await G({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({saved:!0,product:t??"shared",configuredProducts:J(r)})}catch(t){m(t),process.exit(1)}}},Zm={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){if(r)return{clientId:r.clientId?Te(r.clientId):void 0,clientSecret:r.clientSecret?Te(r.clientSecret):void 0,refreshToken:r.refreshToken?Te(r.refreshToken):void 0}};var e=o;let t=await B();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:J(t)})}catch(t){m(t),process.exit(1)}}},Dm={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await B();if(!e){l({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"});return}let t=J(e);if(t.length===0){l({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});return}let o=ct(e),r={};for(let n of t)try{let a=n==="recruit"?o.recruitApi:n==="crm"?o.crmApi:o.deskApi;if(!a){r[n]={authenticated:!1,error:"Not configured"};continue}let s=await a.zohoAccountsApi.accessToken();r[n]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(a){let i=a instanceof Error?a.message:String(a);r[n]={authenticated:!1,error:i}}l({products:r})}catch(e){m(e),process.exit(1)}}},Lm={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await un(),l({cleared:!0})}catch(e){m(e),process.exit(1)}}},Bc={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(Em).command(km).command(Zm).command(Dm).command(Lm).demandCommand(1,"Please specify an auth subcommand."),handler:C};import{access as vm,constants as Nm}from"node:fs";import{dirname as _m}from"node:path";var Gc={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=[],t=await B();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=_m(mt());if(await wm(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 a=J(t);a.length>0?e.push({name:"products",status:"pass",message:`Configured products: ${a.join(", ")}`}):e.push({name:"products",status:"fail",message:"No products have complete credentials"});let i=ct(t);for(let s of a)try{let c=s==="recruit"?i.recruitApi:s==="crm"?i.crmApi:i.deskApi;if(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}`}):a.includes("desk")||e.push({name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."})}let n=e.every(a=>a.status==="pass");l({checks:e,healthy:n}),n||process.exit(e.some(a=>a.status==="fail")?1:0)}};function wm(e){return new Promise(t=>{vm(e,Nm.W_OK,o=>{t(!o)})})}var on;function jc(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await B();r||(m(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),J(r).length===0&&(m(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),on=ct(r)}catch(r){m(r),process.exit(4)}}}function rn(e){if(!on)throw new Error("CLI context not initialized. This is a bug.");return on}function H(e){let{recruitApi:t}=rn(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 z(e){let{crmApi:t}=rn(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 b(e){let{deskApi:t}=rn(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}var Vm=["raw","page_by_line","data_by_line"],Km=["replace","concat"],Um=["meta","pages","merged_page"];function qc(e){return e.option("multiple-pages",{type:"number",default:1,describe:"Pages to fetch in this invocation (>=1). Continues from --page (CRM/Recruit) or --from (Desk)."}).option("multiple-pages-output",{type:"string",choices:Um,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:Vm,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:Km,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}function ue(e){return qc(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function k(e){return qc(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function L(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function Ae(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function wt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function Mo(e){return e.option("sort-by",{type:"string",describe:"Field to sort by"}).option("sort-order",{type:"string",choices:["asc","desc"],describe:"Sort direction"})}import{writeFileSync as Wm,appendFileSync as Bm}from"node:fs";var pe={nextInput:(e,t)=>{if(!t.info?.more_records)return;let o=e.page??1;return{...e,page:o+1}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({page:t.info?.page??e.page,per_page:t.info?.per_page??e.per_page,more_records:t.info?.more_records??!1}),hasMorePagesAvailable:(e,t)=>t.info?.more_records??!1},Z={nextInput:(e,t)=>{let o=e.limit??25;if(o<=0||(t.data?.length??0)<o)return;let n=e.from??1;return{...e,from:n+o}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({from:e.from,limit:e.limit,count:t.data?.length??0}),hasMorePagesAvailable:(e,t)=>{let o=e.limit??25;return o<=0?!1:(t.data?.length??0)>=o}};function Gm(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=en(),n=t==="raw"?"json":"ndjson",a=tn(n),i=r?tn(n,"pick"):void 0;if(!a)return{mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};let s=0;function c(d){if(!r)return d;let g=dt(d.data,r);return{...d,data:g}}function u(d){let g=d.append?Bm:Wm;a&&g(a,d.mainContent),i&&d.pickContent!==void 0&&g(i,d.pickContent)}function p(d){let y=o==="concat"&&!(s===0);if(t==="raw"){let h=JSON.stringify(d,null,2),T=i?JSON.stringify(c(d),null,2):void 0;u({mainContent:h,pickContent:T,append:y})}else if(t==="page_by_line"){let h=JSON.stringify(d)+`
|
|
4
|
+
var pu=Object.defineProperty;var du=Object.getOwnPropertyDescriptor;var I=(e,t,o,r)=>{for(var n=r>1?void 0:r?du(t,o):t,a=e.length-1,i;a>=0;a--)(i=e[a])&&(n=(r?i(t,o,n):i(n))||n);return r&&n&&pu(t,o,n),n},A=(e,t)=>(o,r)=>t(o,r,e);import qy from"yargs";import{hideBin as $y}from"yargs/helpers";import{readFile as lu,writeFile as mu,rm as yu,mkdirSync as hu}from"node:fs";import{join as Po}from"node:path";import{homedir as fu}from"node:os";var Kt=["recruit","crm","desk"];function Ao(){return Po(fu(),".zoho-cli")}function lt(){return Po(Ao(),"config.json")}function mt(){return Po(Ao(),".tokens.json")}function Ae(e,t){if(t){let o=process.env[`ZOHO_${t}_${e}`];if(o)return o}return process.env[`ZOHO_${e}`]}async function B(){let e=lt(),t=await Ru(e),o=Ae("ACCOUNTS_CLIENT_ID"),r=Ae("ACCOUNTS_CLIENT_SECRET"),n=Ae("ACCOUNTS_REFRESH_TOKEN");if(!t&&!(o&&r&&n))return;let i={clientId:o??t?.shared?.clientId??"",clientSecret:r??t?.shared?.clientSecret??"",refreshToken:n??t?.shared?.refreshToken??"",region:Ae("ACCOUNTS_URL")??t?.shared?.region,apiMode:Ae("API_URL")??t?.shared?.apiMode};function s(u){let p=u.toUpperCase(),d=Ae("API_URL",p),h=u==="desk"?Ae("DESK_ORG_ID"):void 0,y=t?.[u],f=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_ID`],T=process.env[`ZOHO_${p}_ACCOUNTS_CLIENT_SECRET`],R=process.env[`ZOHO_${p}_ACCOUNTS_REFRESH_TOKEN`];if(!(!y&&!(f||T||R)&&!h))return{clientId:f??y?.clientId,clientSecret:T??y?.clientSecret,refreshToken:R??y?.refreshToken,apiUrl:d??y?.apiUrl,orgId:h??y?.orgId}}return{shared:i,recruit:s("recruit")??t?.recruit,crm:s("crm")??t?.crm,desk:s("desk")??t?.desk,output:t?.output}}function yt(e,t){let o=e[t],r=e.shared,n=o?.clientId??r.clientId,a=o?.clientSecret??r.clientSecret,i=o?.refreshToken??r.refreshToken;if(!(!n||!a||!i))return{clientId:n,clientSecret:a,refreshToken:i,region:r.region??"us",apiMode:o?.apiUrl??r.apiMode??"production",orgId:o?.orgId}}async function gu(e){let t=lt();return hu(Ao(),{recursive:!0}),new Promise((o,r)=>{mu(t,JSON.stringify(e,null,2),{},n=>{n?r(n):o()})})}async function G(e){let t=await B(),o={shared:{...t?.shared,...e.shared},recruit:e.recruit!==void 0?{...t?.recruit,...e.recruit}:t?.recruit,crm:e.crm!==void 0?{...t?.crm,...e.crm}:t?.crm,desk:e.desk!==void 0?{...t?.desk,...e.desk}:t?.desk,output:e.output!==void 0?Tu(t?.output,e.output):t?.output};return await gu(o),o}function Tu(e,t){return{dumpDir:"dumpDir"in t?t.dumpDir:e?.dumpDir,pick:"pick"in t?t.pick:e?.pick,commands:xu(e?.commands,t)}}function xu(e,t){return"commands"in t?t.commands?{...e,...t.commands}:void 0:e}function cn(e,t,o){let r=t.join("."),n=r?e?.commands?.[r]:void 0;return{dumpDir:o.dumpDir??n?.dumpDir??e?.dumpDir,pick:o.pick??n?.pick??e?.pick}}async function un(){await G({output:{dumpDir:void 0,pick:void 0,commands:void 0}})}async function pn(){let e=lt(),t=mt();await sn(e),await sn(t)}function J(e){return Kt.filter(t=>{let o=yt(e,t);return!(!o||t==="desk"&&!o.orgId)})}function Ru(e){return new Promise(t=>{lu(e,{encoding:"utf-8"},(o,r)=>{if(o){t(void 0);return}try{t(JSON.parse(r))}catch{t(void 0)}})})}function sn(e){return new Promise(t=>{yu(e,()=>t())})}function ge(e){return e.length<=4?"***":e.substring(0,4)+"***"}function S(){}import{Inject as fc,Injectable as Il}from"@nestjs/common";function Ut(e,t){let o;return t&&typeof e=="string"?o=[e]:pe(e)?o=[...e]:o=[e],o}function Eo(e,t){return new Map(Ut(e).map(o=>[t(o),o]))}function pe(e,t=!1){return typeof e=="string"?t:e!=null&&typeof e=="object"&&Symbol.iterator in e}function ht(e){for(let t of e)return!1;return!0}function Te(e,t){for(let o of e)t(o)}function q(e,t,o=!1){e!=null&&(pe(e,o)?Te(e,t):t(e))}function dn(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(i=>Array.isArray(i)?i.length!==n:!0)!==-1}else r=!0;t=r?[e]:e}else t=e;return t}function bu(e){return e!=null?ko(e):[]}var g=bu;function ko(e){return Array.isArray(e)?e:[e]}function Zo(e){return ln([],...e)}function ln(e,...t){return e??=[],t.forEach(o=>{o!=null&&mn(e,o)}),e}function mn(e,t){return Array.prototype.push.apply(e,t),e}import{symmetricDifference as hh}from"extra-set";function Fu(e,t){let o=new Set(e??void 0);return t(o),o}function yn(e,t){return Fu(e,o=>ft(o,t))}function ft(e,t){q(t,o=>e.add(o))}function gt(e,t=!0){return t?((...o)=>!e.call(void 0,...o)):e}function Lo(e){return Object.keys(e).length===0}function de(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function hn(e){let t={};return e.forEach((o,r)=>{t[r]=o}),t}function vo(e){return{...e}}function Tt(e){return e!=null}function Ee(e){return pe(e,!1)?!ht(e):fn(e)}function No(e){let t;return pe(e,!0)?t=!ht(e):fn(e)?t=typeof e=="object"?!Lo(e):!0:t=!1,t}function fn(e){return e!=null&&e!==""}function gn(e){return(t=>{let o;return t!=null?o=t.filter((r,n,a)=>e(r,n,a)):o=[],o})}var v=gn(Tt),Su=gn(Ee);function Bt({base:e,build:t}){let o=e??{};return t(o),o}function Gt(e){return t=>t.map(e)}var Ke=(e=>e);function xe(){return Ke}function Cu(e,t){return v(e!=null?Array.isArray(e)?e:xn(e,t):[])}function xn(e,t){let o=new Set(e.keys);return e.values&&ft(o,e.values.map(t)),Array.from(o)}function _o(e,t){let o=Cu(t,e);function r(n){let a=n?Array.isArray(n)?n.map(e):xn(n,e):[];return a.length?Zo([v(a),o]):o}return(n,a)=>{let i=r(a),s=new Set(i);return n.filter(u=>{let p=e(u);return s.has(p)?!1:(s.add(p),!0)})}}var Iu=e=>e.id;function wo(e,t,o){let r=o(t);return Vo(e,r,o)}function Vo(e,t,o=Iu){return e.filter(r=>o(r)!==t)}function Ko(e){return t=>{let o=e(t);if(o==="")throw new Error('Cannot use "empty" string for BooleanKey.');return o}}function bn(e){return!e||e.length<=0}function Ou(e){return!bn(e)}function Mu(e,t,o){return e?[...wo(e,t,Ko(o)),t]:[t]}function Pu(e,t,o){return e&&wo(e,t,Ko(o))}function Au(e,t,o){return e&&Vo(e,t,Ko(o))}function Eu(e){let t=s=>bn(s),o=s=>Ou(s),r=(s,c,u=!0)=>u?n(s,c):a(s,c),n=(s,c)=>Mu(s,c,e),a=(s,c)=>Pu(s,c,e);return{isFalse:t,isTrue:o,set:r,insert:n,remove:a,removeByKey:(s,c)=>Au(s,c,e)}}var $h=Eu(e=>e||void 0);function Re(e,t){let o=ku(e,r=>t(r)?"in":"out");return{included:o.in??[],excluded:o.out??[]}}function ku(e,t){let o=Fn(e,t);return hn(o)}function Fn(e,t){let o=new Map;return e?.forEach(r=>{let n=t(r),a=o.get(n);a!=null?a.push(r):o.set(n,[r])}),o}function Sn(e,t,o){return g(t).forEach(r=>e.set(r,o)),e}function Uo(e){return Array.from(e.entries())}function Cn(e){return Zu(Uo(e))}function Zu(e){let t=[];return e.forEach(([o,r])=>{q(r,n=>{t.push([o,n])})}),t}function Wo(){let e=new Map,t=(n,a)=>{let i=e.get(n);i==null&&(i=[],e.set(n,i)),q(a,s=>i.push(s))},o=(n,a)=>t(n,dn(a));return{map:()=>e,entries:()=>Uo(e),tuples:()=>Cn(e),delete:n=>e.delete(n),add:t,addTuples:o,addToKeys:(n,a)=>q(n,i=>t(i,a)),addTuplesToKeys:(n,a)=>q(n,i=>o(i,a)),has:n=>e.has(n),get:n=>e.get(n)??[]}}function In(e){let{readKey:t,defaultIfKeyNull:o=!1}=e;return r=>{let n=new Set(r);return a=>{let i=t(a);return i!=null?n.has(i):o}}}var Du=32;function Lu(e){return t=>{let o=new Set;for(let r=0;r<e;r+=1)t&1<<r&&o.add(r);return o}}var pf=Lu(Du);function vu(e){return typeof e=="function"?e.prototype?Object.getOwnPropertyDescriptor(e,"prototype")?.writable?"function":"class":e.constructor.name==="AsyncFunction"?"function":"arrow":null}function On(e){let t=vu(e);return t!=null&&t!=="class"}function le(e){return On(e)?e:()=>e}function xt(e={}){let{startAt:t,increaseBy:o}=e,r=le(o??1),n=t??0;return()=>{let a=n;return n+=r(),a}}function Nu(e){let{min:t,max:o}=e;return t<=o}function _u(e){let{min:t,max:o}=e;if(!Nu(e))throw new Error("Invalid bounds. Min was greater than the max.");return r=>r>=t&&r<=o}function jt(e){let{min:t,max:o,fencePosts:r=!1}=e,n=o-t,a=_u(e),i=(s=>{let c;if(a(s))c=s;else{let u=r?s<t?1:-1:0;c=((s-t)%n+n)%n+t+u}return c});return i._wrap=e,i}function qt(e){let{min:t,max:o,wrap:r}=e;return r?jt(e):n=>wu(n,t,o)}function wu(e,t,o){return Math.max(Math.min(e,o),t)}function Mn(e){let t;switch(typeof e){case"number":t=e;break;case"string":t=Number(e);break;default:t=0;break}return t}function Pn(e,t){return Math.log(t)/Math.log(e)}function Bo(e){let t;switch(e){case"floor":t=Math.floor;break;case"ceil":t=Math.ceil;break;case"none":t=o=>o;break;default:t=Math.round;break}return t}var Ff=Rt(0);function Rt(e,t="cut"){let o=Ku(e,t),r=(n=>o(Mn(n)));return r._precision=e,r}function Ku(e,t="round"){let o;if(t==="cut")o=r=>An(r,e);else{let r=Bo(t);o=n=>+(r(+(n+"e+"+e))+"e-"+e)}return o}function An(e,t){return+((e>0?Math.floor:Math.ceil)(+(e+"e+"+t))+"e-"+t)}function Ue(e,t){let o=typeof e=="number"?{min:0,max:e}:e,{min:r,max:n,round:a}=o,i=t??a,s;if(r!=null){let c=n-r;s=()=>Math.random()*c+r}else s=()=>Math.random()*n;if(i&&i!=="none"){let c=typeof i=="function"?i:Bo(i),u=s;s=()=>c(u())}return s}function En(e){return(t,o)=>{let r=e(t),n=e(o);return r-n}}var Pf=En(e=>e);function Zn(e){return e.i}var pg=_o(Zn);var dg=In({readKey:Zn});var Dn=",",Wu=" ";function Bu(e,t=Dn,o=!1){if(e==null)return e;let r=g(e);return o&&(r=r.map(n=>n?.trim())),r.filter(Boolean).join(t)}function Ht(e,t,o){let r=e.split(t),n=[];if(r.length>1){let a=r.length>o,i=a?o-1:r.length;for(let s=0;s<i;s+=1)n.push(r[s]);a&&n.push(r.slice(i).join(t))}else n.push(r[0]);return n}function Gu(e){let{joiner:t,trimByDefault:o=!1}=e,r=function(n,a=o){return Bu(n,t,a)};return r.joiner=t,r.trimByDefault=o,r}function Ln(e){let{joiner:t}=e,o=Gu(e),r=(n,a=i=>i)=>n.split(t).map(s=>a(s.trim()));return{joiner:t,trimByDefault:o.trimByDefault,joinStrings:o,splitStrings:r,splitStringsToSet(n){return new Set(n==null?[]:r(n))},splitJoinRemainder(n,a){return Ht(n,t,a)}}}var jo=Ln({joiner:Dn}),ju=Ln({joiner:Wu,trimByDefault:!0});var E=jo.joinStrings,Hg=jo.splitStrings,zg=jo.splitStringsToSet,qu=ju.joinStrings;function vn(e){return e.trim()}function Nn(e){return e.toUpperCase()}function _n(e){return e.toLowerCase()}var hT=Gt(vn),fT=Gt(Nn),gT=Gt(_n);import{BaseError as Hu}from"make-error";var zu="DBX_ASSERTION_ERROR",qo=class extends Hu{code=zu;_target;_property;constructor(t,o){super(o),this.name="AssertionError",this._target=t.target,this._property=t.propertyKey}get target(){return this._target}get propertyKey(){return this._property}},$o=class{handle(t){throw this.buildException(t)}buildException(t){let o=this.buildExceptionString(t);return new qo(t,o)}buildExceptionString(t){let o;return t.options?.message?o=t.options.message:o="Assertion failed for property '"+t.propertyKey+'".',o}},Ju=new $o;var wn=gt;function We(e,{forEach:t,filter:o}){Vn(e,o).forEach((n,a)=>t(n,a))}function Vn(e,t){return Jo(t)(e)}function Jo(e){let t;if(e!=null){let o=Xu(e);t=r=>zo(r).filter((n,a)=>o(n,a))}else t=zo;return t}function zo(e){return Object.entries(e)}function Yo(e){return typeof e=="object"?e:{valueFilter:e}}function Xu(e){let t=Yo(e),{valueFilter:o=1,invertFilter:r=!1,keysFilter:n}=t,a;switch(o){case 1:a=([,i])=>i!==void 0;break;case 2:a=([,i])=>i!=null;break;case 3:a=([,i])=>!!i;break;case 4:a=([,i])=>Ee(i);break;case 5:a=([,i])=>No(i);break;case 6:a=([,i])=>!!i&&Ee(i);break;case 7:a=([,i])=>!!i&&No(i);break;default:a=()=>!0;break}if(n){let i=a,s=new Set(n.map(c=>c.toString()));a=(c,u)=>i(c,u)&&s.has(c[0])}return wn(a,r)}function Be(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 Qu({filter:e,copy:t,dynamic:o=!1}){let r=e!=null?Ge({filter:e,copy:!1}):tp;return n=>{let a=()=>{let s={};return n.forEach(c=>{let u=r({...c});Object.assign(s,u)}),s},i=o?a:Be(a);return s=>{let c=i();return t&&(s=vo(s)),Object.assign(s,c),s}}}function zt(e,t){return ep(t)(e)}function ep(e){let t=Qu({filter:e,copy:!1,dynamic:!0});return o=>t(v(o))({})}var Rx=Ge({copy:!0,filter:{valueFilter:1}}),bx=Ge({copy:!0,filter:{valueFilter:2}}),Kn=Ge({copy:!0,filter:{valueFilter:4}}),Fx=Ge({copy:!0,filter:{valueFilter:6}}),Sx=Xo({valueFilter:1}),Cx=Xo({valueFilter:6}),Ix=Xo({valueFilter:2});function Xo(e){let t=Qo({filter:e,forEach:([o],r,n,a)=>{a.keys.push(o)}});return o=>{let r={keys:[]};return t(o,r),r.keys}}function Ge({copy:e=!1,filter:t={valueFilter:1}}={}){let o=Yo(t);o.invertFilter=!o.invertFilter;let r=Qo({filter:o,forEach:([n],a,i)=>{delete i[n]}});return(n,a)=>((typeof a=="boolean"?a:e)&&(n={...n}),r(n),n)}var tp=Ge({copy:!1});function Qo({forEach:e,filter:t}){let o=Jo(t);return((r,n)=>{o(r).forEach((i,s)=>e(i,s,r,n))})}function op(e){let{readKey:t,isModifiedFunction:o=()=>{}}=e;return(r,n)=>{let a=[],i=Eo(r,t),s=Eo(n,t),c=new Set(i.keys()),u=new Set(s.keys()),p=yn(c,u);return Te(p,d=>{if(d==null)return;let h=c.has(d),y=u.has(d),f;y&&h?f=0:h?f=-1:f=1;let T=h?i.get(d):void 0,R=y?s.get(d):void 0,O=T&&R?o(T,R):void 0;a.push({key:d,pastValue:T,nextValue:R,change:f,isModified:O,value:R??T})}),a}}var Nx=op({readKey:e=>e});function Ft(e,t,o){let[r,n]=Jt(e,t,!1);return r+o+n}function Jt(e,t,o=!1){let r=e.substring(0,t),n=e.substring(t+(o?0:1));return[r,n]}function Wn(e){let t={};for(let[o,r]of[...e].entries())t[r]=o;return t}var rp=["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"],np=new Set(rp);function er(e){let{escapeTargets:t,escapeCharacter:o}=e,r=t instanceof Set?t:new Set(t);return n=>{let a=Yt(r,n),i;switch(a.length){case 0:i=n;break;case 1:{let s=n[a[0]];i=Ft(n,a[0],o(s));break}default:{let s=[],c=a.length,u=0,p=0;for(let d=0;d<c;d+=1){p=a[d];let h=n[p],f=n.substring(u,p)+o(h);s.push(f),u=p+1}s.push(n.substring(u)),i=s.join("");break}}return i}}var Bn=er({escapeTargets:np,escapeCharacter(e){return`\\${e}`}});function ap(e){return(t,o)=>{let r=o??Number.MAX_SAFE_INTEGER,n=[];for(let[a,i]of[...t].entries())if(e.has(i)&&(n.push(a),n.length>=r))break;return n}}function Yt(e,t,o){return ap(e)(t,o)}function ip(e,t){return Yt(e,t,1)[0]}function Xt(e){return t=>{let r=ip(typeof e=="string"?new Set([e]):e,t),n;return r!=null?n=Jt(t,r,!1):n=[t,void 0],n}}function Gn(e,t){return Xt(t)(e)}function jn(e){let t=Xt(e);return o=>t(o)[0]}var dR=jn("#"),lR=Xt("#");var je="/",sp=".";function cp(e){let t=e.split(sp,3).length-1,o;switch(t){case 0:e.length===0?o="invalid":e.at(-1)===je?o="folder":o="file";break;case 1:o="typedfile";break;default:o="invalid";break}return o}function qn(e){return cp(e)!=="invalid"}var up=/^\/+/,pp=/\/+$/;var dp=/\/{2,}/g;function $n(e){return e.startsWith(je)?e.replace(up,je):`${je}${e}`}function Hn(e){return e.replaceAll(dp,je)}function zn(e){return e.replace(pp,"")}function lp(e){let t=e.indexOf(".");return t>0&&t<e.length-1}var Jn=/:(\d+)/;function mp(e){return Jn.test(e)}function yp(e){let t=Jn.exec(e);return t?Number(t[1]):void 0}function hp(e){let t=ea(e),o=Xn(t),{domain:r,path:n}=o,a=lp(r),i=mp(e),s=i?yp(e)??void 0:void 0,[c,u]=Gn(o.path,"?"),p=a&&(c===""||qn(c+"/")),d=gp(e);return{input:e,isWebsiteUrl:p,hasWebsiteDomain:a,hasHttpPrefix:d,hasPortNumber:i,portNumber:s,splitPair:o,domain:r,websitePath:n,path:c,query:u}}function tr(e){let t=hp(e);return t.hasHttpPrefix&&t.isWebsiteUrl}function Yn(e,t=!1){let o=Yt(new Set("?"),e),r,n=e;return t&&o.length?r=o:o.length>1&&(r=o.reverse(),r.pop()),r?.length&&r.forEach(a=>n=Ft(n,a,"&")),n}function Xn(e){let t=ea(e);return fp(t)}function fp(e){let t=Ht(e,"/",2),o=t[0],r=t[1];return{domain:o,path:$n(r??"/")}}var Qn=/^https:\/\/|http:\/\//;function ea(e){return e.replace(Qn,"")}function gp(e){return Qn.test(e)}var rb={prefixes:"email.",domains:"test.dereekb.com",numberFactory:xt()};var nb={internationalAreaCodes:[1210,1979,1512,1303],numberFactory:Ue({min:2e6,max:1e7,round:"floor"})};import{BaseError as mb}from"make-error";var Tp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_",xp="!";function Rp(e){let{negativePrefix:t,digits:o}=e,r=t?"integer":"positive_integer",n=Math.min(6,Math.floor(Math.log2(o.length))),a=Math.pow(2,n),i=a-1,s=Wn(o);function c(p){let d="",h=p<0;h&&(p=-p);do{let y=p&i;d=o[y]+d,p>>>=n}while(p!==0);return h&&t&&(d=t+d),d}function u(p){let d=!1;p[0]===t&&(d=!0);let h=d?1:0,y=0;for(let f=h;f<p.length;f+=1)y=(y<<n)+s[p[f]];return d&&(y=-y),y}return{type:r,digits:o,bitDepth:a,negativePrefix:t,encodeNumber:c,decodeNumber:u}}var bp=Rp({negativePrefix:xp,digits:Tp});var ta=-90,oa=90,nF=oa-ta,ra=-180,na=180,Fp=na-ra;var aF=qt({min:ta,max:oa}),iF=jt({min:ra,max:na});var Cp=24,Ip=60,aa=1440,ia=60,bF=ia*Ip,N=1e3,me=N*60,Qt=me*60,sa=Qt*Cp,Op=7,Mp=sa*Op;function eo(e){return e.getTime()<Date.now()}var IF=Rt(3);var OF=aa-1;function ca(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}async function Ct(e,t){return new Promise(o=>setTimeout(()=>o(t),e))}function Zp(e){let n=Qt,a={startLimitAt:1,cooldownRate:1,exponentRate:2,maxWaitTime:n},i=0,s=Number.MAX_SAFE_INTEGER,c=new Date,u=!0;y(e??a);function p(){return{...a}}function d(){return u}function h(P){u=P}function y(P,K=!1){let W=Math.max(0,P.startLimitAt??1),C=P.cooldownRate??1,D=P.maxWaitTime??n,M=P.exponentRate??2;a={startLimitAt:W,cooldownRate:C,maxWaitTime:D,exponentRate:M},s=Pn(M,D/N+1),K&&f()}function f(){i=0,c=new Date}function T(P){if(!u)return 0;let{cooldownRate:K}=a,C=(Date.now()-c.getTime())*K/N,D=Math.max(i-C,0),M=Math.max(0,D-a.startLimitAt);return P&&(i=D+P,c=new Date),M>=s?a.maxWaitTime:(Math.pow(a.exponentRate,Math.max(M,0))-1)*N}function R(P){return T(P??0)}function O(){let P=T(1);return Ct(P)}return{waitForRateLimit:O,getNextWaitTime:R,getConfig:p,setConfig:y,getEnabled:d,setEnabled:h,reset:f}}function da(e){let o=Zp({exponentRate:1.5,maxWaitTime:N*8,...e}),r=me,n=new Date,a=0,i=0,s=!0;O(e,!0);function c(){eo(n)&&d()}function u(){return s}function p(C){s=C}function d(){i=a,n=new Date(Date.now()+r)}function h(){return n}function y(){return Math.max(0,n.getTime()-Date.now())}function f(C){n=C}function T(){return c(),i}function R(C){i=C}function O(C,D=!1){a=C.limit??a,r=C.resetPeriod??r;let M={cooldownRate:C.cooldownRate??Math.max(.1,r/N),exponentRate:C.exponentRate??1.5,maxWaitTime:C.maxWaitTime??N*8};o.setConfig(M,D),D&&d(),n=C.resetAt??n}function P(C){if(!s)return 0;function D(){return i-=C,o.getNextWaitTime(C)}let M=0;return i>0?M=D():(c(),i>0?M=D():M=y()),M}function K(C){return P(C??0)}function W(){let C=P(1);return Ct(C)}return{getRemainingLimit:T,setRemainingLimit:R,getTimeUntilNextReset:y,getResetAt:h,setNextResetAt:f,setConfig:O,reset:d,getNextWaitTime:K,waitForRateLimit:W,getEnabled:u,setEnabled:p}}function la(e){let{promiseFactories:t,successOnMaybe:o,throwErrors:r}=e;return async(n,a)=>{let{successOnMaybe:i,throwErrors:s}=a??{},c=i??o,u=s??r,p;for(let d of t)try{if(p=await d(n),p!=null||c)break}catch(h){if(u)throw h}return p}}import{BaseError as kC}from"make-error";function Dp(e){return t=>{let o={};return Object.entries(t).forEach(([r,n])=>{let a=e(r,n);o[a]=n}),o}}var sI=Dp(e=>{let t=e;return typeof e=="string"&&(t=e.toLowerCase()),t});function Lp(e){return t=>vp(t).then(o=>o.toString(e))}var jI=Lp("base64");function vp(e){let t=[];return new Promise((o,r)=>{e.on("data",n=>t.push(Buffer.from(n))),e.on("end",()=>o(Buffer.concat(t))),e.on("error",r)})}var Np="__CATCH_ALL_HANDLE_RESULT_KEY__";function ya(e,t){let o=t?.defaultResult??!0,r=t?.negativeResult??!1;return()=>{let n,a=new Map,i=u=>{n=u},s=(u,p)=>{u===Np?i(p):Sn(a,u,p)},c=(u,p,d)=>{let h=d.bind(u);s(p,h)};return Bt({base:(u=>{let p=e(u),d=(p!=null?a.get(p):void 0)??n,h;return d?h=Promise.resolve(d(u)).then(y=>y??o):h=Promise.resolve(r),h}),build:u=>{u.readKey=e,u.set=s,u.bindSet=c,u.setCatchAll=i}})}}function _p(e,t){return{accessor:t,boundTo:e,set:(o,r)=>{t.bindSet(e,o,r)},setCatchAll:o=>{t.setCatchAll(o)}}}function wp(e,t){let o=r=>{e.set(t,r)};return o.key=t,o}function Vp(e,t,o){let r=wp(e,t);return n=>{r(function(a){let i=o(a);return n.call(this,i)})}}function ha(e,t){return o=>Vp(e,o,t)}function fa(e){return t=>(o,r)=>{let n=_p(o,t),a=e.configurerForAccessor(n);r(a)}}import{BaseError as xO}from"make-error";var or=class{_length=0;_storage={};get length(){return this._length}key(t){return Object.keys(this._storage)[t]??null}hasKey(t){return de(this._storage,t)}getItem(t){return this._storage[t]??null}setItem(t,o){o==null?this.removeItem(t):(this.hasKey(t)||(this._length=this._length+1),this._storage[t]=String(o))}removeItem(t){this.hasKey(t)&&(delete this._storage[t],this._length=this._length-1)}clear(){this._storage={},this._length=0}},FO=new or;function to(e){let t={};return Object.entries(e).forEach(([o,r])=>{t[r]=o}),t}var ga="image/jpeg",Kp="image/png",Up="image/webp",Wp="image/gif",Bp="image/heif",Gp="image/tiff",jp="image/svg+xml",qp="image/raw",$p={jpeg:ga,jpg:ga,png:Kp,webp:Up,gif:Wp,svg:jp,raw:qp,heif:Bp,tiff:Gp},VO=to($p);var Hp="application/pdf",zp="application/vnd.openxmlformats-officedocument.wordprocessingml.document",Jp="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",Yp="text/plain",Xp="text/csv",Qp="text/html",ed="application/xml",td="application/json",od="application/yaml",rd="text/markdown",nd={pdf:Hp,docx:zp,xlsx:Jp,txt:Yp,csv:Xp,html:Qp,xml:ed,json:td,yaml:od,md:rd},KO=to(nd);var ad="application/zip",id={zip:ad},UO=to(id);function sd(e){let{prefix:t,suffix:o,prefixEmptyString:r,suffixEmptyString:n}=e,a=t??"",i=o??"";function s(u){let p=u;if(a)for(;p.startsWith(a);)p=p.slice(a.length);if(i)for(;p.endsWith(i);)p=p.slice(0,p.length-i.length);return p}function c(u){let p=s(u),d;return p===""?(d="",r&&(d=`${a}${p}`),n&&(d=`${d}${i}`)):d=`${a}${p}${i}`,d}return{prefix:a,suffix:i,prefixEmptyString:r,suffixEmptyString:n,prefixSuffixString:c,cleanString:s}}var BO=sd({prefix:"-"});function cd(e){return(t,o)=>{let r=e(t),n=e(o);return r.localeCompare(n)}}var jO=cd(e=>e.label);var It={VISIT_ALL:0,VISIT_NODE_ONLY:1,VISIT_CHILDREN_ONLY:2,SKIP_ALL:3};var RM={ADD_ALL:It.VISIT_ALL,ADD_NODE_ONLY:It.VISIT_NODE_ONLY,ADD_CHILDREN_ONLY:It.VISIT_CHILDREN_ONLY,SKIP_ALL:It.SKIP_ALL};var ud=-1,rr=0;function pd(e){return e?.page??ud}function nr(e){return pd(e)+1}import{BaseError as Ta}from"make-error";var Y=class extends Ta{constructor(o){super(`Fetch request failed to build due to an unexpected error: ${typeof o=="object"?o.message:o}`);this.error=o}};function xa(e){return(t,o)=>dd(e(t,o))}var qe=class extends Ta{constructor(o){super(`Fetch response was a non-ok status code (${o.status}): ${o.statusText}`);this.response=o}};function dd(e){return e.then(t=>{if(!t.ok)throw new qe(t);return t})}import{BaseError as wP}from"make-error";function Ra(e){return(t,o)=>{let r,n=o?.timeout??t.timeout;if(!o?.signal&&n){let i=new AbortController;r=i,o={...o,signal:i.signal}}let a=e(t,o);if(n){let i=setTimeout(()=>{r?.abort()},n);a=a.finally(()=>{clearTimeout(i)})}return a}}function Fa(e){let{makeFetch:t,makeRequest:o,baseRequest:r}=e;return{fetchRequestFactory:n=>Sa({makeRequest:o,baseRequest:r,...n}),makeFetch:(n={})=>md({makeRequest:o,makeFetch:t,baseRequest:r,...n}),makeRequest:e.makeRequest}}var ld=(e,t)=>t(e);function md(e){let{makeFetch:t=fetch,fetchHandler:o=ld,useTimeout:r,requireOkResponse:n,mapResponse:a}=e,i=t;r&&(i=Ra(i)),n&&(i=xa(i));let s=Sa(e);return async(c,u)=>{let p=await s(c,u),d=o(p,i);return a&&(d=a(d)),d}}var yd=(e,t)=>new Request(e,t);function Sa(e){let{makeRequest:t=yd,baseUrl:o,baseRequest:r,timeout:n,requestInitFactory:a,useBaseUrlForConfiguredFetchRequests:i=!1,forceBaseUrlForWebsiteUrlWithPrefix:s=i}=e,c=o?new URL(zn(o)):void 0,u=c?y=>{let f,T=y.toString();if(!s&&tr(T))f=new URL(T);else{let R=c.origin+Hn("/"+c.pathname+"/"+y);f=new URL(R,c)}return f}:void 0;async function p(y){let f=ca(y)?await y:y;return ba(f)?f:t(f)}let d=u?async y=>{let f,T,R;if(typeof y=="string"?f=y:ba(y)?i?(f=y.url,T=y):R=y:R=await t(y),!R){let O=u(f);R=await t(O.href,T)}return R}:p,h;if(r!=null||n!=null){let y=le(r);async function f(){let R=await y();return n?{...R,timeout:n}:R}async function T(R,O){let P=await f(),K=hd(P,await O),W=K.timeout===void 0?R.timeout:K.timeout;return{...K,timeout:W}}a?h=(R,O)=>a(R,T(R,O)):h=(R,O)=>T(R,O)}else a?h=a:h=(y,f)=>f;return async(y,f)=>{try{let T=await d(y);f=await h(T,f);let R=await t(T,f);return R.timeout=n,R}catch(T){throw T instanceof Y?T:new Y(T)}}}function hd(e,t){let o;if(t){let r=fd([e.headers,t.headers]);o={...e,...t,headers:r}}else o=e;return o}function fd(e){let t=Wo();return v(e).forEach(o=>{let r=gd(o),n=new Set;r.forEach(([a,i])=>{n.has(a)||(t.delete(a),n.add(a)),i&&t.add(a,i)})}),t.tuples()}function gd(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 ba(e){return!!e.url}import{safeParse as Td}from"fast-content-type-parse";function oo(e){let t=e.headers.get("content-type"),o=Td(t??""),r=o.type===""?void 0:o;return{response:e,rawContentType:t,contentType:r,mimeType:r?.type}}function Ca(e){let{updateWithResponse:t,maxRetries:o}=e,r=o??1,n=e.rateLimiter,a=async(i,s)=>{async function c(u){await n.waitForRateLimit();let p,d;try{p=await s(i.clone())}catch(y){d=y,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 a._rateLimiter=n,a}var ar=class extends Y{constructor(o){super("There was no next page for this.");this.page=o}},ir=class extends Y{constructor(o,r){super(`The limit of ${r} for the number of pages to read was reached.`);this.page=o;this.limit=r}},xd=100;function $e(e){let{fetch:t,readFetchPageResultInfo:o,buildInputForNextPage:r,defaultMaxPage:n,defaultMaxItemsPerPage:a}=e;return(i,s)=>{let{maxPage:c=n,maxItemsPerPage:u}=s??{},p=u??a,d=c===null?Number.MAX_SAFE_INTEGER:c??xd;function h(f,T=void 0){return async()=>{let R=await t(f),{cursor:O,nextPageCursor:P,hasNext:K}=await o(R),W=O??T?.cursor,C=K!==!1,D=T?T.page+1:rr,M=D>=d,fe={input:f,result:R,page:D,previous:T,hasNext:C,isAtMaxPage:M,cursor:W,nextPageCursor:P,fetchNext:Be(async()=>{if(M)throw new ir(fe,d);let Vt=C?await r(fe,f,{maxPage:d,maxItemsPerPage:p}):void 0;if(!Vt)throw new ar(fe);return h({...f,...Vt},fe)()})};return fe}}return{input:i,fetchNext:Be(()=>h(i)())}}}function x(e,t){let{omitKeys:o,filterEmptyValues:r}=t??{},n=Array.isArray(e)?zt(e):e,a=r??!0?Kn(n??{}):n,i=new URLSearchParams(a);return o!=null&&q(o,s=>i.delete(s),!1),i}function sr(e){let t;if(typeof e=="string")t=e;else if(Rd(e))t=e.href;else{let o=sr(e.url);if(e.queryParams){let r=Sd(e.queryParams);ht(r)?t=o:t=Yn(o+`?${r.toString()}`)}else t=o}return t}function Rd(e){return typeof e=="object"&&e instanceof URL}function bd(e){return typeof e=="object"&&e instanceof URLSearchParams}function Fd(e){let t=[];return Te(e,o=>{let[r,n]=o;if(r!=null&&n!=null){let a=String(r);q(n,i=>{i!=null&&t.push([a,String(i)])})}}),t}function Sd(e){let t;return bd(e)?t=e:typeof e=="string"?t=new URLSearchParams(e):pe(e)?t=new URLSearchParams(Fd(e)):t=Cd(e),t}function Cd(e){let t=[];return We(e,{forEach:o=>{let[r,n]=o,a=String(r);n!=null&&q(n,i=>{t.push([a,String(i)])})}}),new URLSearchParams(t)}var cr=class extends Error{constructor(o){super("Failed to parse the JSON body.");this.response=o}};function Id(e){return e!=null?typeof e=="string"?e:JSON.stringify(e):void 0}var Od=e=>{throw new cr(e)},ee=e=>null;function te(e,t){let o;typeof t=="function"?o={handleFetchJsonParseErrorFunction:t}:o=t??{},o={...o,handleFetchJsonParseErrorFunction:o.handleFetchJsonParseErrorFunction??Od};let{handleFetchJsonParseErrorFunction:r,interceptJsonResponse:n}=o,a=Ia(o);return(i,s,c)=>{let u=sr(i),p=a(s,c),d=typeof s=="object"?s.interceptResponse:void 0;return e(u,p).then(y=>{let f=y.json().catch(r),T=n?f.then(R=>n(R,y)):f;return d?T.then(R=>d(R,y)):T})}}function Ia(e={}){let{defaultMethod:t="GET",mapFetchJsonInput:o=xe()}=e;return(r=t,n)=>{let a;return typeof r=="string"?a={method:r,body:n}:a=r,a=o(a),{...a,method:a.method,body:Id(a.body)}}}var cA=Ia();var oe=Fa({makeFetch:fetch,makeRequest:(e,t)=>new Request(e,t)});function He(){return{data:[],info:{page:1,per_page:100,count:0,more_records:!1}}}function V(e,t){return $e({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.info?.more_records??!1}},buildInputForNextPage:function(o,r,n){return{...r,page:nr(o),per_page:n.maxItemsPerPage??r.per_page}}})}function ro(e){switch(e){case"sandbox":return"https://recruitsandbox.zoho.com/recruit";case"production":return"https://recruit.zoho.com/recruit";default:return e}}var ze="Candidates",Oa="Job_Openings",no="Notes",Ma="Emails",Ot="Attachments";function ao(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=io(o);break}default:break}return t}function io(e){function t(i){let s;return typeof i=="object"?Array.isArray(i)?s=i.map(ur):i&&(s=io(i)):s=i,s}function o(i,s){return i.length>1?`(${i.join(s)})`:i[0]}function r(i,s){let c=v(i.map(t)).flatMap(g);return o(c,s)}let n=e.or?r(e.or,"or"):void 0,a=n;return e.and&&(a=r([r(e.and,"and"),n],"and")),a}var Pa=er({escapeTargets:["(",")",","],escapeCharacter:e=>`\\\\${e}`});function ur(e){let t=Pa(e.value);return`(${e.field}:${e.filter}:${t})`}var Aa=ao;import{BaseError as Kd}from"make-error";import{BaseError as Ad}from"make-error";var Ed="__internal_data_array_blank_error";function kd(e){return Array.isArray(e?.data)}var Ye="success";function X(e){let t=typeof e,o;return t==="object"?o=e:o={code:e,message:""},o}var be=class extends Ad{constructor(o){super(o.message);this.error=o}get code(){return this.error.code}},j=class extends be{constructor(o,r,n){super(o);this.data=o;this.errorResponseData=r;this.responseError=n}},Je=class extends j{constructor(t,o){super({code:Ed,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 Je&&!o||(r instanceof j?console.log(`${e}Error(${r.responseError.response.status}): `,{error:r,errorData:r.data}):r instanceof be?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(a,i)=>{try{return await o(a,i)}catch(s){if(s instanceof qe){let c=await e(s);if(c)throw r(c),n?.(c),c}throw s}}}function ae(e){return(t,o)=>{if(t?.error!=null){let n=new qe(o),a=e(t,n);if(a)throw a}return t}}var Zd="INTERNAL_ERROR",Dd="INVALID_TOKEN",$=class extends j{},Ea="FAILURE",pr=class extends j{},Ld="4834",Mt=class extends j{},vd="INVALID_QUERY",dr=class extends j{get details(){return this.error.details}},so="MANDATORY_NOT_FOUND",Fe="DUPLICATE_DATA",co="INVALID_DATA",Nd="TOO_MANY_REQUESTS",ka=429,_d="X-RATELIMIT-LIMIT",wd="X-RATELIMIT-REMAINING",Vd="X-RATELIMIT-RESET",Za=100,Da=me;function lr(e){let t=e.get(_d),o=e.get(wd),r=e.get(Vd),n=null;if(t!=null&&o!=null&&r!=null){let a=Number(t),i=Number(o),s=Number(r),c=new Date(s);n={limit:a,remaining:i,reset:s,resetAt:c}}return n}var Pt=class extends j{get headerDetails(){return lr(this.responseError.response.headers)}};function ie(e,t){let o;if(kd(e))o=new Je(e,t);else{let r=ye(e,t);if(r){let n=X(r);switch(n.code){case Zd:o=new pr(n,e,t);break;case Dd:o=new $(n,e,t);break;case Ld:o=new Mt(n,e,t);break;case vd:o=new dr(n,e,t);break;case Nd:o=new Pt(n,e,t);break;default:o=new j(n,e,t);break}}}return o}function ye(e,t){return e.error??e.data?.[0]??(t.response.ok?void 0:e)}var La="ALREADY_ASSOCIATED",mr=class extends Kd{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 be{},yr=class extends Xe{},hr=class extends Xe{},uo=class extends Xe{get invalidFieldDetails(){return this.error.details}},fr=class extends uo{};function va(e){let t;switch(e.code){case co:{let o=new uo(e);o.invalidFieldDetails.id?t=new fr(e):t=o;break}case so:t=new yr(e);break;case Fe:t=new hr(e);break;default:t=new Xe(e);break}return t}function Na(e,t){return o=>{if(o?.data?.length)return o;throw new mr(e,t)}}var Ud=re("ZohoRecruit");async function Wd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=_a(t,e)),o}function _a(e,t){let o,r=ye(e,t);if(r)switch(X(r).code){default:o=ie(e,t);break}return o}var wa=ae(_a),Va=ne(Wd,Ud);import{BaseError as Bd}from"make-error";function Tr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v2/${n}${t}`,_(o,{data:g(r)})).then(a=>{let i=Array.isArray(r),s=se(g(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw va(p[0].result);c=u[0].result.details}return c}))}function Ka(e){return Tr(e,"","POST")}function Ua(e){return Tr(e,"/upsert","POST")}function Wa(e){return Tr(e,"","PUT")}function Ba(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v2/${o}?${x({ids:t,wf_trigger:r})}`,_("DELETE")).then(Gd)}function Ga(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}`,_("GET")).then(Na(t.module)).then(o=>o.data[0])}function ja(e){return(t=>e.fetchJson(`/v2/${t.module}?${Qa(t).toString()}`,_("GET")))}function xr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Aa(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 Qa(r)}return(o=>e.fetchJson(`/v2/${o.module}/search?${t(o).toString()}`,_("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function qa(e){return V(xr(e))}function Qe(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v2/${n.module}/${n.id}/${o}?${Fr(n,n.filter).toString()}`,_("GET")).then(a=>a??(r!==!1?He():a))}}function Rr(e){return Qe(e)({targetModule:Ma})}function $a(e){return V(Rr(e))}function br(e){return Qe(e)({targetModule:Ot})}function Ha(e){return V(br(e))}var QA=20*1024*1024;function za(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n,attachmentUrl:a}=t,i={attachments_category_id:E(o),attachments_category:E(r)};if(!i.attachments_category_id?.length&&!i.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let s=`/v2/${t.module}/${t.id}/${Ot}?${x(i).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(a){let u=`${s}&${x({attachment_url:a}).toString()}`;c=e.fetch(u,{method:"POST"})}else throw new Error("file or attachmentUrl must be provided.");return c}}function Ja(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"GET"}).then(oo)}function Ya(e){return t=>e.fetch(`/v2/${t.module}/${t.id}/${Ot}/${t.attachment_id}`,{method:"DELETE"})}var gr=class extends Bd{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Xa(e){return t=>{let r=x(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v2/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?ro(t.apiUrl):""}${i}`;return e.fetchJson(c,_("POST")).then(u=>{if(u.code!=="success")throw new gr(u);return u.details})}}function Qa(...e){return x(e,{omitKeys:"module"})}function Fr(...e){return x(e,{omitKeys:["id","module"]})}function _(e,t){return{method:e,body:t??void 0}}function Gd(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===Ye?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function se(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===Ye?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function ei(e){return t=>e.fetchJson(`/v2/${ze}/actions/associate`,_("PUT",{data:g(t)})).then(o=>{let r=o.data.map(()=>t),n=se(r,o.data),{included:a,excluded:i}=Re(n.errorItems,s=>s.result.code===Ea&&s.result.details.error[0].code===La);return{...n,errorItems:i,alreadyAssociatedErrorItems:a,allErrorItems:n.errorItems}})}function ti(e){return t=>e.fetchJson(`/v2/${t.module}/${t.id}/associate?${Fr(t).toString()}`,_("GET")).then(o=>o??He())}function Sr(e){let t=ti(e);return o=>t({...o,module:ze})}function oi(e){return V(Sr(e))}function Cr(e,t=Oa){let o=ti(e);return r=>o({...r,module:t})}function ri(e){return V(Cr(e))}function Ir(e){return t=>e.fetchJson(`/v2/${no}`,_("POST",{data:t.data})).then(o=>se(g(t.data),o.data))}function ni(e){return t=>e.fetchJson(`/v2/${no}?${x({ids:t.ids})}`,_("DELETE")).then(o=>se(g(t.ids),o.data))}function Or(e){return Qe(e)({targetModule:no})}function ai(e){return V(Or(e))}function ii(e){let t=Ir(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:g(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function ui(e){return t=>e.fetchJson(`/v2/settings/tags?${x({module:t.module})}`,_("POST",{tags:g(t.tags)})).then(o=>{let r=se(g(t.tags),o.tags),{included:n,excluded:a}=Re(r.errorItems,i=>i.result.code===Fe);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function pi(e){return t=>e.fetchJson(`/v2/settings/tags?${x({module:t.module,my_tags:t.my_tags})}`,_("GET")).then(o=>({...o,data:o.tags}))}var si=100;function di(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>si)throw new Error(`Cannot add tags to more than ${si} records at once.`);return e.fetchJson(`/v2/${ze}/actions/add_tags?${x({tag_names:t.tag_names,ids:t.ids})}`,_("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var ci=100;function li(e){return t=>{if(Array.isArray(t.ids)&&t.ids.length>ci)throw new Error(`Cannot remove tags from more than ${ci} records at once.`);return e.fetchJson(`/v2/${ze}/actions/remove_tags?${x({tag_names:t.tag_names,ids:t.ids})}`,_("POST")).then(o=>{let r=o.data.map(()=>t);return se(r,o.data)})}}var jd="invalid_code",qd="invalid_client",Mr=class extends Y{constructor(o){super(`ZohoAccountsAccessTokenError: ${o}`);this.errorCode=o}},et=class extends Y{constructor(o){super(`Failed to retrieve proper authentication for the API call. Reason: ${o}`);this.reason=o}},$d=re("ZohoAccounts");async function Hd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=mi(t,e)),o}function mi(e,t){let o,r=e.error;if(r){let n=X(r);switch(n.code){case jd:case qd:o=new Mr(n.code);break;default:o=ie(e,t);break}}return o}var yi=ae(mi),hi=ne(Hd,$d);function Se(e){return async()=>{let t=await e();if(!t.accessToken)throw new et;return t.accessToken}}var zd=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 Pr(e){let{readRateLimitDetails:t}=e,o=e.onTooManyRequests!==!1?e.onTooManyRequests??zd:void 0,r=e.maxRateLimit??Za,n=e.resetPeriod??Da;function a(c,u){return{limit:c,startLimitAt:Math.ceil(c/10),cooldownRate:1.2*(c/(n/N)),exponentRate:1.08,maxWaitTime:N*10,resetPeriod:n,resetAt:u}}let i=a(r),s=da(i);return Ca({rateLimiter:s,maxRetries:e.maxRetries,updateWithResponse:function(c,u){let p=t(c.headers),d=!1,h=!1;if(p){let{remaining:y,limit:f,resetAt:T}=p;if(f!=null&&f!==r){let R=a(f,T??void 0);s.setConfig(R,!1)}if(s.setRemainingLimit(y),T&&s.setNextResetAt(T),h=!0,c.status===ka){d=!0;try{o?.(p,c,u)}catch{}}}return s.setEnabled(h),d}})}function Ce(e){return Pr({...e,readRateLimitDetails:Jd})}function Jd(e){let t=lr(e),o;return t&&(o={remaining:t.remaining,limit:t.limit,resetAt:t.resetAt}),o}function fi(e){let{accountsContext:t}=e,o=Se(t.loadAccessToken),r=Ce(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>oe.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=ro(i.apiUrl),c=a({apiUrl:s}),u=Va(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:wa,handleFetchJsonParseErrorFunction:ee});return{recruitContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function po(e){switch(e){case"sandbox":return"https://crmsandbox.zoho.com/crm";case"production":return"https://www.zohoapis.com/crm";default:return e}}var lo="Notes",gi="Emails",At="Attachments";var Ti=ao;import{BaseError as Yd}from"make-error";var Ar=class extends Yd{constructor(o,r){super("There was no content or matching records for the content. It may not exist.");this.moduleName=o;this.recordId=r}},tt=class extends be{},Er=class extends tt{},kr=class extends tt{},mo=class extends tt{get invalidFieldDetails(){return this.error.details}},Zr=class extends mo{};function xi(e){let t;switch(e.code){case co:{let o=new mo(e);o.invalidFieldDetails.api_name==="id"?t=new Zr(e):t=o;break}case so:t=new Er(e);break;case Fe:t=new kr(e);break;default:t=new tt(e);break}return t}function Ri(e,t){return o=>{if(o?.data?.length)return o;throw new Ar(e,t)}}var Xd=re("ZohoCrm",{logDataArrayErrors:!1});async function Qd(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=bi(t,e)),o}function bi(e,t){let o,r=ye(e,t);if(r)switch(X(r).code){default:o=ie(e,t);break}return o}var Fi=ae(bi),Si=ne(Qd,Xd);import{BaseError as el}from"make-error";function Lr(e,t,o){return(({data:r,module:n})=>e.fetchJson(`/v8/${n}${t}`,U(o,{data:g(r)})).catch(wi).then(a=>{let i=Array.isArray(r),s=Ie(g(r),a.data),c;if(i)c=s;else{let{successItems:u,errorItems:p}=s;if(p[0]!=null)throw xi(p[0].result);c=u[0].result.details}return c}))}function Ci(e){return Lr(e,"","POST")}function Ii(e){return Lr(e,"/upsert","POST")}function Oi(e){return Lr(e,"","PUT")}function Mi(e){return({ids:t,module:o,wf_trigger:r})=>e.fetchJson(`/v8/${o}?${x({ids:t,wf_trigger:r})}`,U("DELETE")).catch(wi).then(ol)}function Pi(e){return t=>e.fetchJson(`/v8/${t.module}/${t.id}`,U("GET")).then(Ri(t.module)).then(o=>o.data[0])}function Ai(e){return(t=>e.fetchJson(`/v8/${t.module}?${_i(t).toString()}`,U("GET")))}function vr(e){function t(o){let r={...o};if(delete r.criteria,o.criteria!=null){let n=Ti(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 _i(r)}return(o=>e.fetchJson(`/v8/${o.module}/search?${t(o).toString()}`,U("GET")).then(r=>r??{data:[],info:{more_records:!1}}))}function Ei(e){return V(vr(e))}function ot(e){return t=>{let{targetModule:o,returnEmptyRecordsInsteadOfNull:r=!0}=t;return n=>e.fetchJson(`/v8/${n.module}/${n.id}/${o}?${tl(n,n.filter).toString()}`,U("GET")).then(a=>a??(r!==!1?He():a))}}function Nr(e){let t=ot(e)({targetModule:gi});return o=>t(o).then(r=>{let n=r.data??r.Emails;return{...r,data:n}})}function ki(e){return V(Nr(e))}function _r(e){return ot(e)({targetModule:At})}function Zi(e){return V(_r(e))}var mk=20*1024*1024;function Di(e){return t=>{let{attachmentCategoryId:o,attachmentCategoryName:r,file:n}=t,a={attachments_category_id:E(o),attachments_category:E(r)};if(!a.attachments_category_id?.length&&!a.attachments_category?.length)throw new Error("attachmentCategoryId or attachmentCategoryName must be provided and not empty.");let i=`/v8/${t.module}/${t.id}/${At}?${x(a).toString()}`,s=new FormData;return s.append("file",n),e.fetch(i,{method:"POST",headers:{"Content-Type":""},body:s})}}function Li(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${At}/${t.attachment_id}`,{method:"GET"}).then(oo)}function vi(e){return t=>e.fetch(`/v8/${t.module}/${t.id}/${At}/${t.attachment_id}`,{method:"DELETE"})}var Dr=class extends el{constructor(o){super(`An error occured during the execution of the function. Code: ${o.code}, Message: ${o.message}`);this.error=o}};function Ni(e){return t=>{let r=x(t.params).toString(),n=!!t.apiKey,a=(n?`auth_type=apikey&zapikey=${t.apiKey}`:"auth_type=oauth")+(r?`&${r}`:""),i=`/v8/functions/${t.functionName}/actions/execute?${a}`,c=`${n&&t.apiUrl!=null?po(t.apiUrl):""}${i}`;return e.fetchJson(c,U("POST")).then(u=>{if(u.code!=="success")throw new Dr(u);return u.details})}}function _i(...e){return x(e,{omitKeys:"module"})}function tl(...e){return x(e,{omitKeys:["id","module"]})}function U(e,t){return{method:e,body:t??void 0}}function wi(e){let t;if(e instanceof Je)t={data:e.errorDataArray};else throw e;return t}function ol(e){let{data:t}=e,o=[],r=[];return t.forEach(a=>{a.status===Ye?o.push(a):r.push(a)}),{...e,successItems:o,errorItems:r}}function Ie(e,t){let o=[],r=[];return e.forEach((a,i)=>{let s=t[i];s.status===Ye?o.push({input:a,result:s}):r.push({input:a,result:s})}),{successItems:o,errorItems:r}}function wr(e){return t=>e.fetchJson(`/v2/${lo}`,U("POST",{data:t.data})).then(o=>Ie(g(t.data),o.data))}function Vi(e){return t=>e.fetchJson(`/v2/${lo}?${x({ids:t.ids})}`,U("DELETE")).then(o=>Ie(g(t.ids),o.data))}function Vr(e){return ot(e)({targetModule:lo})}function Ki(e){return V(Vr(e))}function Ui(e){let t=wr(e);return o=>{let{module:r,id:n,notes:a}=o,i={data:g(a).map(s=>({...s,se_module:r,Parent_Id:n}))};return t(i)}}function Bi(e){return t=>e.fetchJson(`/v8/settings/tags?${x({module:t.module})}`,U("POST",{tags:g(t.tags)})).catch(o=>{let r;if(o instanceof j){let n=o.data?.tags;Array.isArray(n)&&(r={tags:n})}if(!r)throw o;return r}).then(o=>{let r=Ie(g(t.tags),o.tags),{included:n,excluded:a}=Re(r.errorItems,i=>i.result.code===Fe);return{...r,errorItems:a,duplicateErrorItems:n,allErrorItems:r.errorItems}})}function Gi(e){return t=>e.fetchJson(`/v8/settings/tags/${t.id}`,U("DELETE")).then(o=>o.tags)}function ji(e){return t=>e.fetchJson(`/v8/settings/tags?${x({module:t.module,my_tags:t.my_tags})}`,U("GET")).then(o=>({...o,data:o.tags}))}var Wi=100;function qi(e){return t=>e.fetchJson(`/v8/${t.module}/actions/add_tags`,U("POST",$i(t))).then(o=>{let r=o.data.map(()=>t);return Ie(r,o.data)})}function $i(e){if(Array.isArray(e.ids)&&e.ids.length>Wi)throw new Error(`Cannot add/remove tags from more than ${Wi} records at once.`);let t=[...g(e.tags)],o=new Set(t.map(r=>r.name));return e.tag_names&&g(e.tag_names).forEach(r=>{o.has(r)||(t.push({name:r}),o.add(r))}),{tags:t,ids:g(e.ids)}}function Hi(e){return t=>e.fetchJson(`/v8/${t.module}/actions/remove_tags`,U("POST",$i(t))).then(o=>{let r=o.data.map(()=>t);return Ie(r,o.data)})}function zi(e){let{accountsContext:t}=e,o=Se(t.loadAccessToken),r=Ce(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>oe.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=po(i.apiUrl),c=a({apiUrl:s}),u=Si(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:Fi,handleFetchJsonParseErrorFunction:ee});return{crmContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function Ji(e,t){return $e({...t,fetch:e,readFetchPageResultInfo:function(o){return{hasNext:o.page_context?.has_more_rows??!1}},buildInputForNextPage:function(o,r,n){let i=o.result?.page_context,s=n.maxItemsPerPage??r.row_count??i?.row_count??20,c=(i?.start_index??r.start_index??1)+s;return{...r,start_index:c,row_count:s}}})}function ke(e,t){return{method:e,body:t??void 0}}function Yi(e){return({requestId:t})=>e.fetchJson(`/requests/${t}`,ke("GET"))}function Kr(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)}},ke("GET"))}}function Xi(e){let t=Kr(e);return Ji(t)}function Qi(e){return({requestId:t})=>e.fetchJson(`/requests/${t}/fielddata`,ke("GET"))}function es(e){return()=>e.fetchJson("/fieldtypes",ke("GET"))}function ts(e){return({requestId:t,...o})=>{let n=x(o).toString(),a=n?`?${n}`:"",i=`/requests/${t}/pdf${a}`;return e.fetch(i,{method:"GET"})}}function os(e){return({requestId:t})=>e.fetch(`/requests/${t}/completioncertificate`,{method:"GET"})}function rs(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 ns(e){return({requestId:t,data:o})=>e.fetchJson(`/requests/${t}`,ke("PUT",{requests:o}))}function as(e){return({requestId:t,data:o})=>{let r=o?{requests:o}:void 0;return e.fetchJson(`/requests/${t}/submit`,ke("POST",r))}}function is(e){return({requestId:t,expire_by:o})=>e.fetchJson(`/requests/${t}/extend`,ke("PUT",{expire_by:o}))}function ss(e){return({requestId:t,recall_inprogress:o,reason:r})=>{let n={};o!=null&&(n.recall_inprogress=String(o)),r!=null&&(n.reason=r);let a=x(n),i=a.toString().length>0;return e.fetchJson(`/requests/${t}/delete`,{method:"PUT",...i?{headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()}:{}})}}function cs(e){switch(e){case"sandbox":return"https://signsandbox.zoho.com/api/v1";case"production":return"https://sign.zoho.com/api/v1";default:return e}}var rl=re("ZohoSign",{logDataArrayErrors:!1});async function nl(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=us(t,e)),o}function us(e,t){let o,r=ye(e,t);if(r)switch(X(r).code){default:o=ie(e,t);break}return o}var ps=ae(us),ds=ne(nl,rl);function ls(e){let{accountsContext:t}=e,o=Se(t.loadAccessToken),r=Ce(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>oe.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoConfig missing api url.");let s=cs(i.apiUrl),c=a({apiUrl:s}),u=ds(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:ps,handleFetchJsonParseErrorFunction:ee});return{signContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}function ms(e){let t;switch(e){case"sandbox":case"production":t="https://desk.zoho.com/api/v1";break;default:t=e;break}return t}var al=re("ZohoDesk",{logDataArrayErrors:!1});async function il(e){let t=await e.response.json().catch(()=>{}),o;return t&&(o=ys(t,e)),o}function ys(e,t){let o,r=ye(e,t);if(r)switch(X(r).code){default:o=ie(e,t);break}return o}var hs=ae(ys),fs=ne(il,al);var sl="X-Rate-Limit-Remaining-v3",cl="Retry-After",ul=200;function pl(e){let t=e.get(sl),o;if(t!=null){let r=Number(t),n,a=e.get(cl);if(a!=null){let i=Number(a);Number.isNaN(i)||(n=new Date(Date.now()+i*N))}Number.isNaN(r)||(o={remaining:r,resetAt:n})}return o}function gs(e){return Pr({maxRateLimit:ul,...e,readRateLimitDetails:pl})}function Ts(e){let{accountsContext:t}=e,o=Se(t.loadAccessToken),r=gs(e.rateLimiterConfig),{logZohoServerErrorFunction:n,fetchFactory:a=i=>oe.makeFetch({baseUrl:i.apiUrl,baseRequest:async()=>({headers:{"Content-Type":"application/json",Authorization:`Bearer ${await o()}`,orgId:i.orgId}}),fetchHandler:r,timeout:20*1e3,requireOkResponse:!0,useTimeout:!0})}=e;return i=>{if(!i.apiUrl)throw new Error("ZohoDeskConfig missing api url.");if(!i.orgId)throw new Error("ZohoDeskConfig missing orgId.");let s=ms(i.apiUrl),c=a({apiUrl:s,orgId:i.orgId}),u=fs(c,n,y=>{y instanceof $&&t.loadAccessToken.resetAccessToken()}),p=te(u,{interceptJsonResponse:hs,handleFetchJsonParseErrorFunction:ee});return{deskContext:{fetch:u,fetchJson:p,accessTokenStringFactory:o,config:{...i,apiUrl:s},zohoRateLimiter:r._rateLimiter}}}}var xs=25;function Q(e,t){return $e({...t,fetch:e,readFetchPageResultInfo:function(o){let r=o.data?.length??0;return{hasNext:r>0&&r>=xs}},buildInputForNextPage:function(o,r,n){let a=n.maxItemsPerPage??r.limit??xs,s=(r.from??1)+a;return{...r,from:s,limit:a}}})}function Ze(e,t){return{method:e,body:t??void 0}}function rt(e,t){return x(e,{omitKeys:t})}function yo(e){let t;return e&&(t=E(g(e))),t}function Ur(e){return t=>{let{include:o,...r}=t,n=rt([{...r,include:yo(o)}]);return e.fetchJson(`/tickets?${n}`,Ze("GET")).then(a=>a??{data:[]})}}function Rs(e){return t=>{let{ticketId:o,include:r}=t,a=rt([{include:yo(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/tickets/${o}${i}`,Ze("GET"))}}function Wr(e){return t=>{let o=rt([t]);return e.fetchJson(`/tickets/search?${o}`,Ze("GET")).then(r=>r??{data:[]})}}function bs(e){return t=>{let{contactId:o,include:r,...n}=t,a=rt([{...n,include:yo(r)}]);return e.fetchJson(`/contacts/${o}/tickets?${a}`,Ze("GET")).then(i=>i??{data:[]})}}function Fs(e){return t=>{let{productId:o,include:r,...n}=t,a=rt([{...n,include:yo(r)}]);return e.fetchJson(`/products/${o}/tickets?${a}`,Ze("GET")).then(i=>i??{data:[]})}}function Ss(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/metrics`,Ze("GET"))}function Cs(e){return t=>{let o=rt([{agentIds:E(g(t.agentIds)),departmentId:t.departmentId}]);return e.fetchJson(`/agentsTicketsCount?${o}`,Ze("GET"))}}function Is(e){return Q(Ur(e))}function Os(e){return Q(Wr(e))}function Ms(e){return{method:e}}function Ps(e){return t=>{let o=x([t]);return e.fetchJson(`/departments?${o}`,Ms("GET")).then(r=>r??{data:[]})}}function As(e){return t=>e.fetchJson(`/departments/${t.departmentId}`,Ms("GET"))}function Br(e){return{method:e}}function Es(e){let t;return e&&(t=E(g(e))),t}function Gr(e){return t=>{let{include:o,...r}=t,n=x([{...r,include:Es(o)}]);return e.fetchJson(`/contacts?${n}`,Br("GET")).then(a=>a??{data:[]})}}function ks(e){return t=>{let{contactId:o,include:r}=t,a=x([{include:Es(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/contacts/${o}${i}`,Br("GET"))}}function Zs(e){return t=>{let o=x([{contactIds:E(g(t.contactIds))}]);return e.fetchJson(`/contacts/contactsByIds?${o}`,Br("GET")).then(r=>r??[])}}function Ds(e){return Q(Gr(e))}function Et(e,t){return{method:e,body:t??void 0}}function Ls(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags`,Et("GET")).then(o=>o??[])}function vs(e){return t=>{let o={tags:g(t.tags).map(r=>({name:r}))};return e.fetchJson(`/tickets/${t.ticketId}/tags`,Et("POST",o)).then(r=>r??[])}}function Ns(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/tags/${t.tagId}`,Et("DELETE"))}function _s(e){return t=>{let o=x([t]);return e.fetchJson(`/tags/search?${o}`,Et("GET")).then(r=>r??{data:[]})}}function ws(e){return t=>{let o=x([t]);return e.fetchJson(`/ticketTags?${o}`,Et("GET")).then(r=>r??{data:[]})}}function jr(e,t){return{method:e,body:t??void 0}}function Vs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/followers`,jr("GET")).then(o=>o??[])}function Ks(e){return t=>{let o={ids:g(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,jr("POST",o))}}function Us(e){return t=>{let o={ids:g(t.agentIds)};return e.fetchJson(`/tickets/${t.ticketId}/followers`,jr("DELETE",o))}}function Ws(e,t){return{method:e,body:t??void 0}}function dl(e){let t;return e&&(t=E(g(e))),t}function Bs(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:dl(r)}]);return e.fetchJson(`/tickets/${o}/attachments?${a}`,Ws("GET")).then(i=>i??{data:[]})}}function Gs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/attachments/${t.attachmentId}`,Ws("DELETE"))}function ho(e,t){return{method:e,body:t??void 0}}function js(e){let t;return e&&(t=E(g(e))),t}function qs(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:js(r)}]);return e.fetchJson(`/tickets/${o}/comments?${a}`,ho("GET")).then(i=>i??{data:[]})}}function $s(e){return t=>{let{ticketId:o,commentId:r,include:n}=t,i=x([{include:js(n)}]).toString(),s=i?"?"+i:"";return e.fetchJson(`/tickets/${o}/comments/${r}${s}`,ho("GET"))}}function Hs(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/comments`,ho("POST",r))}}function zs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/comments/${t.commentId}`,ho("DELETE"))}function kt(e,t){return{method:e,body:t??void 0}}function Js(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timer`,kt("GET"))}function Ys(e){return t=>{let{ticketId:o,...r}=t;return e.fetchJson(`/tickets/${o}/timer`,kt("POST",r))}}function Xs(e){return t=>{let{ticketId:o,...r}=t,n=x([r]);return e.fetchJson(`/tickets/${o}/timeEntries?${n}`,kt("GET")).then(a=>a??{data:[]})}}function Qs(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/${t.timeEntryId}`,kt("GET"))}function ec(e){return t=>e.fetchJson(`/tickets/${t.ticketId}/timeEntries/summation`,kt("GET"))}function tc(e){return{method:e}}function oc(e){let t;return e&&(t=E(g(e))),t}function qr(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:oc(r)}]);return e.fetchJson(`/tickets/${o}/threads?${a}`,tc("GET")).then(i=>i??{data:[]})}}function rc(e){return t=>{let{ticketId:o,threadId:r,include:n}=t,i=x([{include:oc(n)}]).toString(),s=i?"?"+i:"";return e.fetchJson(`/tickets/${o}/threads/${r}${s}`,tc("GET"))}}function nc(e){return Q(qr(e))}function ll(e){return{method:e}}function ml(e){let t;return e&&(t=E(g(e))),t}function $r(e){return t=>{let{ticketId:o,include:r,...n}=t,a=x([{...n,include:ml(r)}]);return e.fetchJson(`/tickets/${o}/activities?${a}`,ll("GET")).then(i=>i??{data:[]})}}function ac(e){return Q($r(e))}function fo(e){return{method:e}}function ic(e){let t;return e&&(t=E(g(e))),t}function Hr(e){return t=>{let{include:o,...r}=t,n=x([{...r,include:ic(o)}]);return e.fetchJson(`/agents?${n}`,fo("GET")).then(a=>a??{data:[]})}}function sc(e){return t=>{let{agentId:o,include:r}=t,a=x([{include:ic(r)}]).toString(),i=a?"?"+a:"";return e.fetchJson(`/agents/${o}${i}`,fo("GET"))}}function cc(e){return t=>{let o=x([{agentIds:E(g(t.agentIds))}]);return e.fetchJson(`/agentsByIds?${o}`,fo("GET")).then(r=>r?.data??[])}}function uc(e){return()=>e.fetchJson("/myinfo",fo("GET"))}function pc(e){return Q(Hr(e))}function go(e){return t=>{let{clientId:o,clientSecret:r,refreshToken:n}=e.config,{client:a,refreshToken:i}=t??{},s=a?.clientId??o,c=a?.clientSecret??r,p=x({grant_type:"refresh_token",client_id:s,client_secret:c,refresh_token:i??n});return e.fetchJson(`/oauth/v2/token?${p}`,yl("POST"))}}function yl(e,t){return{method:e,body:t}}var hl="https://accounts.zoho.com";function dc(e){return e==="us"?hl:e}function lc(e){let t=Ce(),{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 a=dc(n.apiUrl??"us"),i=r({apiUrl:a}),s=hi(i,o),c=te(s,{interceptJsonResponse:yi,handleFetchJsonParseErrorFunction:ee}),u=async()=>{let y=Date.now(),{access_token:f,api_domain:T,scope:R,expires_in:O}=await go(d)();return{accessToken:f,apiDomain:T,expiresIn:O,expiresAt:new Date(y+O*N),scope:R}};u.resetAccessToken=async()=>n.accessTokenCache?.clearCachedToken();let p=fl({tokenRefresher:u,accessTokenCache:n.accessTokenCache}),d={fetch:s,fetchJson:c,loadAccessToken:p,config:{...n,apiUrl:a}};return{accountsContext:d}}}function fl(e){let{tokenRefresher:t,accessTokenCache:o,tokenExpirationBuffer:r}=e,n=r??me,a=null,i=async()=>{a=null},s=async()=>{if(!a){let c=await o?.loadCachedToken();c&&(a=c)}if(a!=null&&Date.now()+n>=a.expiresAt.getTime()&&(a=null),!a){try{a=await t()}catch(c){throw console.error("zohoAccountsZohoAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ",c),new et("Token Refresh Failed")}try{await o?.updateCachedToken(a)}catch{}}return a};return s.resetAccessToken=i,s}function Oe(e){if(!e.apiUrl)throw new Error("No Zoho API url or type specified.")}var Me=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 gl}from"@nestjs/common";import{dirname as Tl}from"node:path";import{readFile as xl,writeFile as Rl,rm as bl,mkdirSync as Fl}from"node:fs";var nt=class{};nt=I([gl()],nt);function Sl(e){console.warn(`mergeZohoAccountsAccessTokenCacheServices(): failed updating ${e.length} caches.`),e.forEach(([t,o],r)=>{console.warn(`Cache update failure ${r+1}: - ${o}`)})}function mc(e,t){let o=[...e],r=typeof t=="function"?t:t!==!1?Sl:void 0;if(o.length===0)throw new Error("mergeZohoAccountsAccessTokenCacheServices() input cannot be empty.");return{loadZohoAccessTokenCache:function(a){let i=o.map(u=>u.loadZohoAccessTokenCache(a)),s=la({promiseFactories:i.map(u=>()=>u.loadCachedToken().catch(()=>null).then(p=>{let d;return p&&!eo(p.expiresAt)&&(d=p),d})),successOnMaybe:!1,throwErrors:!1});return{loadCachedToken:function(){return s()},updateCachedToken:async function(u){return Promise.allSettled(i.map(p=>p.updateCachedToken(u).then(()=>null).catch(d=>[p,d]))).then(p=>{if(r!=null){let d=v(p.map(h=>h.value));d.length&&r(d)}})},clearCachedToken:async function(){await Promise.allSettled(i.map(u=>u.clearCachedToken()))}}}}}function yc(e,t){let o=e??{};function r(n){return{loadCachedToken:async function(){let i=o[n];return t&&console.log("retrieving access token from memory: ",{token:i,service:n}),i},updateCachedToken:async function(i){o[n]=i,t&&console.log("updating access token in memory: ",{accessToken:i,service:n})},clearCachedToken:async function(){delete o[n],t&&console.log("clearing access token in memory: ",{service:n})}}}return{loadZohoAccessTokenCache:r}}var Cl=".tmp/zoho-access-tokens.json";function hc(e=Cl,t=!0){let o=null;async function r(){return o??await n()??{}}function n(){return new Promise(c=>{Fl(Tl(e),{recursive:!0}),xl(e,{},(u,p)=>{let d;if(!u)try{d=JSON.parse(p.toString()),We(d,{forEach:h=>{h[1]&&(h[1].expiresAt=new Date(h[1].expiresAt))}})}catch(h){console.error("Failed reading token file: ",h)}c(d)})}).then(c=>(t&&(o={...o,...c}),c))}async function a(c){return new Promise((u,p)=>{Rl(e,JSON.stringify(c),{},d=>{d?p(d):u()})})}async function i(){return new Promise((c,u)=>{bl(e,p=>{p?u(p):c()})})}function s(c){return{loadCachedToken:async function(){return(await r())[c]},updateCachedToken:async function(p){let d=await r();d&&(d[c]=p);try{await a(d)}catch(h){console.error("Failed updating access token in file: ",h)}},clearCachedToken:async function(){try{await a({})}catch(p){console.error("Failed clearing access token in file: ",p)}}}}return{loadZohoAccessTokenCache:s,readTokenFile:n,writeTokenFile:a,deleteTokenFile:i}}var w=class{constructor(t,o){this.config=t;this.cacheService=o;let r=t.zohoAccounts.accessTokenCache??o.loadZohoAccessTokenCache(t.zohoAccounts.serviceAccessTokenKey);this.zohoAccounts=lc(t.factoryConfig??{})({accessTokenCache:r,...t.zohoAccounts})}zohoAccounts;get accountsContext(){return this.zohoAccounts.accountsContext}get accessToken(){return go(this.accountsContext)}};w=I([Il(),A(0,fc(Me)),A(1,fc(nt))],w);import{Inject as gc,Injectable as Ol}from"@nestjs/common";var Zt=class{zohoCrm;factoryConfig;static assertValidConfig(t){Oe(t.zohoCrm)}};var De=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoCrm=zi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoCrm)}zohoCrm;get crmContext(){return this.zohoCrm.crmContext}get zohoRateLimiter(){return this.zohoCrm.crmContext.zohoRateLimiter}get insertRecord(){return Ci(this.crmContext)}get upsertRecord(){return Ii(this.crmContext)}get updateRecord(){return Oi(this.crmContext)}get deleteRecord(){return Mi(this.crmContext)}get getRecordById(){return Pi(this.crmContext)}get getRecords(){return Ai(this.crmContext)}get searchRecords(){return vr(this.crmContext)}get searchRecordsPageFactory(){return Ei(this.crmContext)}get getRelatedRecordsFunctionFactory(){return ot(this.crmContext)}get getEmailsForRecord(){return Nr(this.crmContext)}get getEmailsForRecordPageFactory(){return ki(this.crmContext)}get getAttachmentsForRecord(){return _r(this.crmContext)}get getAttachmentsForRecordPageFactory(){return Zi(this.crmContext)}get uploadAttachmentForRecord(){return Di(this.crmContext)}get downloadAttachmentForRecord(){return Li(this.crmContext)}get deleteAttachmentFromRecord(){return vi(this.crmContext)}get createNotes(){return wr(this.crmContext)}get deleteNotes(){return Vi(this.crmContext)}get createNotesForRecord(){return Ui(this.crmContext)}get getNotesForRecord(){return Vr(this.crmContext)}get getNotesForRecordPageFactory(){return Ki(this.crmContext)}get executeRestApiFunction(){return Ni(this.crmContext)}get createTagsForModule(){return Bi(this.crmContext)}get deleteTag(){return Gi(this.crmContext)}get getTagsForModule(){return ji(this.crmContext)}get addTagsToRecords(){return qi(this.crmContext)}get removeTagsFromRecords(){return Hi(this.crmContext)}};De=I([Ol(),A(0,gc(Zt)),A(1,gc(w))],De);import{ConfigModule as _L,ConfigService as wL}from"@nestjs/config";import{Inject as Tc,Injectable as Ml}from"@nestjs/common";var Dt=class{zohoRecruit;factoryConfig;static assertValidConfig(t){Oe(t.zohoRecruit)}};var Le=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoRecruit=fi({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoRecruit)}zohoRecruit;get recruitContext(){return this.zohoRecruit.recruitContext}get zohoRateLimiter(){return this.zohoRecruit.recruitContext.zohoRateLimiter}get insertRecord(){return Ka(this.recruitContext)}get upsertRecord(){return Ua(this.recruitContext)}get updateRecord(){return Wa(this.recruitContext)}get deleteRecord(){return Ba(this.recruitContext)}get getRecordById(){return Ga(this.recruitContext)}get getRecords(){return ja(this.recruitContext)}get searchRecords(){return xr(this.recruitContext)}get searchRecordsPageFactory(){return qa(this.recruitContext)}get getRelatedRecordsFunctionFactory(){return Qe(this.recruitContext)}get getEmailsForRecord(){return Rr(this.recruitContext)}get getEmailsForRecordPageFactory(){return $a(this.recruitContext)}get getAttachmentsForRecord(){return br(this.recruitContext)}get getAttachmentsForRecordPageFactory(){return Ha(this.recruitContext)}get uploadAttachmentForRecord(){return za(this.recruitContext)}get downloadAttachmentForRecord(){return Ja(this.recruitContext)}get deleteAttachmentFromRecord(){return Ya(this.recruitContext)}get createNotes(){return Ir(this.recruitContext)}get deleteNotes(){return ni(this.recruitContext)}get createNotesForRecord(){return ii(this.recruitContext)}get getNotesForRecord(){return Or(this.recruitContext)}get getNotesForRecordPageFactory(){return ai(this.recruitContext)}get executeRestApiFunction(){return Xa(this.recruitContext)}get associateCandidateRecordsWithJobOpenings(){return ei(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecords(){return Sr(this.recruitContext)}get searchCandidateAssociatedJobOpeningRecordsPageFactory(){return oi(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecords(){return Cr(this.recruitContext)}get searchJobOpeningAssociatedCandidateRecordsPageFactory(){return ri(this.recruitContext)}get createTagsForModule(){return ui(this.recruitContext)}get getTagsForModule(){return pi(this.recruitContext)}get addTagsToRecords(){return di(this.recruitContext)}get removeTagsFromRecords(){return li(this.recruitContext)}};Le=I([Ml(),A(0,Tc(Dt)),A(1,Tc(w))],Le);import{ConfigModule as iv,ConfigService as sv}from"@nestjs/config";import{Inject as xc,Injectable as Pl}from"@nestjs/common";var Lt=class{zohoSign;factoryConfig;static assertValidConfig(t){Oe(t.zohoSign)}};var vt=class{constructor(t,o){this.config=t;this.zohoAccountsApi=o;this.zohoSign=ls({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoSign)}zohoSign;get signContext(){return this.zohoSign.signContext}get zohoRateLimiter(){return this.zohoSign.signContext.zohoRateLimiter}get getDocument(){return Yi(this.signContext)}get getDocuments(){return Kr(this.signContext)}get getDocumentsPageFactory(){return Xi(this.signContext)}get getDocumentFormData(){return Qi(this.signContext)}get retrieveFieldTypes(){return es(this.signContext)}get downloadPdf(){return ts(this.signContext)}get downloadCompletionCertificate(){return os(this.signContext)}get createDocument(){return rs(this.signContext)}get updateDocument(){return ns(this.signContext)}get sendDocumentForSignature(){return as(this.signContext)}get extendDocument(){return is(this.signContext)}get deleteDocument(){return ss(this.signContext)}};vt=I([Pl(),A(0,xc(Lt)),A(1,xc(w))],vt);import{ConfigModule as Av,ConfigService as Ev}from"@nestjs/config";function Rc(e){return{...e,operationType:e.notifications.operation_type}}var bc=ya(e=>e.operationType),Fc=fa({configurerForAccessor:e=>{let t=ha(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 Sc="ZOHO_SIGN_WEBHOOK_SECRET_TOKEN",ve=class{zohoSignWebhook;static assertValidConfig(t){if(!t.zohoSignWebhook.webhookSecret)throw new Error("No Zoho Sign webhook secret specified.")}};import{defer as jv,from as qv}from"rxjs";import{combineLatest as yN,filter as hN,skipWhile as fN,startWith as gN,switchMap as TN,of as xN,map as RN,delay as bN,EMPTY as FN}from"rxjs";import{switchMap as cN,of as uN,isObservable as pN}from"rxjs";import{switchMap as VN,distinctUntilChanged as KN,shareReplay as UN,map as WN,BehaviorSubject as BN,of as GN,combineLatest as jN,EMPTY as qN,skip as $N,defaultIfEmpty as HN}from"rxjs";import{distinctUntilChanged as AN,filter as EN,mergeMap as kN,isObservable as ZN}from"rxjs";import{BehaviorSubject as n_,switchMap as a_,map as i_,distinctUntilChanged as s_,shareReplay as c_,first as u_,merge as p_,finalize as d_}from"rxjs";import{map as y_}from"rxjs";import{first as S_,shareReplay as C_,firstValueFrom as I_,switchMap as O_,of as M_}from"rxjs";import{startWith as GW,map as jW,shareReplay as qW,skipWhile as $W,distinctUntilChanged as HW,filter as zW,first as JW,firstValueFrom as YW,switchMap as XW,from as QW}from"rxjs";import{exhaustMap as k_,map as Z_,scan as D_,shareReplay as L_,startWith as v_,distinctUntilChanged as N_,switchMap as __,combineLatest as w_,of as V_,first as K_}from"rxjs";import{identity as J_,map as Y_}from"rxjs";import{filter as G_,map as j_,scan as q_}from"rxjs";import{combineLatest as rw,map as nw,of as aw,switchMap as iw,throttleTime as sw}from"rxjs";import{filter as lw,map as mw,skipWhile as yw,switchMap as hw,takeWhile as fw}from"rxjs";import{of as xw,timeout as Rw,tap as bw,throwError as Fw,map as Sw,startWith as Cw}from"rxjs";import{takeWhile as Aw,map as Ew,timer as kw}from"rxjs";import{distinctUntilChanged as _w}from"rxjs";import{finalize as Uw,of as Ww,scan as Bw,switchMap as Gw}from"rxjs";import{startWith as $w,distinctUntilChanged as Hw,shareReplay as zw,map as Jw,first as Yw}from"rxjs";import{tap as tV,delayWhen as oV,timer as rV,asyncScheduler as nV}from"rxjs";import{map as lV,switchMap as mV,shareReplay as yV,distinctUntilChanged as hV}from"rxjs";import{scan as FV}from"rxjs";import{combineLatest as OV,skipWhile as MV,startWith as PV,BehaviorSubject as AV,shareReplay as EV,map as kV,finalize as ZV,of as DV,mergeMap as LV,from as vV}from"rxjs";import{map as VV}from"rxjs";import{throttleTime as GV,distinctUntilChanged as jV,BehaviorSubject as qV}from"rxjs";import{map as QV,combineLatest as eK,of as tK}from"rxjs";import{map as cK,of as uK,switchMap as pK}from"rxjs";import{distinctUntilChanged as TK}from"rxjs";import{map as CK,switchMap as IK}from"rxjs";import{first as PK}from"rxjs";import{switchMap as oU,of as rU}from"rxjs";import{map as WU,switchMap as BU,shareReplay as GU,distinctUntilChanged as jU,BehaviorSubject as qU,isObservable as $U,of as HU}from"rxjs";function Ic(e){let t=!bo(e),o;return t?o="loading":de(e,"value")?o="success":de(e,"error")?o="error":o="idle",o}function bo(e){let t=!1;if(e){let o=e.loading;o===!0?t=!1:t=o===!1||!!(e.value??e.error)||e.value===null}return t}function Fo(e){let t=e==="idle";return o=>o?Ic(o)===e:t}var uU=Fo("idle"),Nt=Fo("loading");var pU=Fo("success"),dU=Fo("error");import{startWith as bU,filter as FU,map as SU,tap as CU,catchError as IU,combineLatest as OU,distinctUntilChanged as MU,first as PU,of as AU,shareReplay as EU,switchMap as kU,firstValueFrom as ZU,scan as DU}from"rxjs";import{distinctUntilChanged as lW,map as mW,shareReplay as yW,skipWhile as hW}from"rxjs";import{map as oW}from"rxjs";import{BehaviorSubject as FW}from"rxjs";import{combineLatest as cB,map as uB,shareReplay as pB,skipWhile as dB}from"rxjs";import{map as fB,shareReplay as gB}from"rxjs";import{distinctUntilChanged as EB,map as kB,scan as ZB,startWith as DB,catchError as LB,skip as vB,mergeMap as NB,delay as _B,BehaviorSubject as wB,combineLatest as VB,exhaustMap as KB,filter as UB,first as WB,of as BB,shareReplay as GB,defaultIfEmpty as jB}from"rxjs";import{defaultIfEmpty as sG,delay as cG,filter as uG,first as pG,map as dG,shareReplay as lG,switchMap as mG,tap as yG,startWith as hG,timeout as fG,of as gG,BehaviorSubject as TG,Subject as xG}from"rxjs";import{isObservable as WG}from"rxjs";import{filter as OG,map as MG,BehaviorSubject as PG,of as AG,first as EG,shareReplay as kG,switchMap as ZG,delay as DG,from as LG,tap as vG}from"rxjs";import{createParamDecorator as Nl}from"@nestjs/common";var xj=Nl((e,t)=>_l(t));function _l(e){let o=e.switchToHttp().getRequest().headers.origin??"";return o.startsWith("http://localhost")||o.startsWith("https://localhost")}import{createParamDecorator as Qr,BadRequestException as wl,InternalServerErrorException as Vl,Logger as Kl}from"@nestjs/common";import Ul from"raw-body";import{parse as Wl}from"querystring";var Pc=new Kl("RawBody"),Cj=Qr(async(e,t)=>{let o=t.switchToHttp().getRequest();if(!o.readable)throw Pc.error("RawBody request was not readable. This is generally due to bad configuration."),new wl("Invalid body");return await Ul(o)}),Ac=Qr(async(e,t)=>{let r=t.switchToHttp().getRequest().body;if(!Buffer.isBuffer(r))throw Pc.error("RawBody expected a buffer set to req.body."),new Vl("failed parsing body");return r}),Ij=Qr(async(e,t)=>{let o=t.switchToHttp().getRequest();return o.body=Bl(o.body),o.body});function Bl(e){let t=Gl(e);return Wl(t)}function Gl(e){return e.toString("utf8").trim()}import{Injectable as jl}from"@nestjs/common";import ql from"body-parser";var it=class{use(t,o,r){ql.json()(t,o,r)}};it=I([jl()],it);import{Injectable as $l}from"@nestjs/common";import Hl from"body-parser";var st=class{use(t,o,r){Hl.raw({type:"*/*"})(t,o,r)}};st=I([$l()],st);import{Logger as zl,Module as Jl,RequestMethod as Yl}from"@nestjs/common";var Xl="/webhook",Ql={path:`${Xl}/{*path}`,method:Yl.POST},en=class{configure(t){em(t)}},So=class extends en{logger=new zl("ConfigureWebhookMiddlewareModule");configure(t){super.configure(t),this.logger.debug("Configured webhook routes with proper middleware.")}};So=I([Jl({})],So);function em(e){e.apply(st).forRoutes(Ql).apply(it).forRoutes("{*path}")}var Ec="CLIENT_WEB_APP_URL";var Ne=class{client;static assertValidConfig(t){if(!t.client.clientWebAppUrl)throw new Error("No client app url specified.")}};import{Inject as tm,Injectable as om}from"@nestjs/common";var _e=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]}};_e=I([om(),A(0,tm(Ne))],_e);import{Module as rm}from"@nestjs/common";import{ConfigModule as nm,ConfigService as am}from"@nestjs/config";function im(e){let t={client:{clientWebAppUrl:e.get(Ec)}};return Ne.assertValidConfig(t),t}var Co=class{};Co=I([rm({imports:[nm],providers:[{provide:Ne,inject:[am],useFactory:im},_e],exports:[_e]})],Co);var kc="SERVER_ENV_TOKEN";import{Inject as sm,Injectable as cm}from"@nestjs/common";function Zc(){return process.env.NODE_ENV==="test"}var Io=class{constructor(t){this.env=t}get isTestingEnv(){return Zc()}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}};Io=I([cm(),A(0,sm(kc))],Io);import{Controller as hm,Inject as fm,Post as gm,Req as Tm}from"@nestjs/common";import{Inject as lm,Injectable as mm,Logger as ym}from"@nestjs/common";import{createHmac as um,timingSafeEqual as pm}from"node:crypto";var dm="x-zs-webhook-signature";function Dc(e){let{secret:t}=e;return async(o,r)=>{let n=o.headers[dm];if(!n)return{valid:!1};let a=r.toString("utf-8"),i=um("sha256",t).update(a,"utf-8").digest("base64"),s=!1;try{let u=Buffer.from(n,"base64"),p=Buffer.from(i,"base64");u.length===p.length&&(s=pm(u,p))}catch{s=!1}let c;if(s)try{let u=JSON.parse(a);c=Rc(u)}catch{s=!1}return s&&c?{valid:!0,event:c}:{valid:!1}}}var he=class{logger=new ym("ZohoSignWebhookService");_verifier;handler=bc();configure=Fc(this.handler);constructor(t){let{webhookSecret:o}=t.zohoSignWebhook;this._verifier=Dc({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=I([mm(),A(0,lm(ve))],he);var we=class{_zohoSignWebhookService;constructor(t){this._zohoSignWebhookService=t}async handleZohoSignWebhook(t,o){await this._zohoSignWebhookService.updateForWebhook(t,o)}};I([gm(),A(0,Tm()),A(1,Ac())],we.prototype,"handleZohoSignWebhook",1),we=I([hm("/webhook/zoho/sign"),A(0,fm(he))],we);import{Module as xm}from"@nestjs/common";import{ConfigModule as Rm,ConfigService as bm}from"@nestjs/config";function Fm(e){let t={zohoSignWebhook:{webhookSecret:e.get(Sc)}};return ve.assertValidConfig(t),t}var Oo=class{};Oo=I([xm({imports:[Rm],controllers:[we],providers:[{provide:ve,inject:[bm],useFactory:Fm},he],exports:[he]})],Oo);import{Inject as Lc,Injectable as Sm}from"@nestjs/common";var _t=class{zohoDesk;factoryConfig;static assertValidConfig(t){if(Oe(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=Ts({...t.factoryConfig,accountsContext:o.accountsContext})(t.zohoDesk)}zohoDesk;get deskContext(){return this.zohoDesk.deskContext}get zohoRateLimiter(){return this.zohoDesk.deskContext.zohoRateLimiter}get getTickets(){return Ur(this.deskContext)}get getTicketById(){return Rs(this.deskContext)}get searchTickets(){return Wr(this.deskContext)}get getTicketsForContact(){return bs(this.deskContext)}get getTicketsForProduct(){return Fs(this.deskContext)}get getTicketMetrics(){return Ss(this.deskContext)}get getAgentsTicketsCount(){return Cs(this.deskContext)}get getTicketsPageFactory(){return Is(this.deskContext)}get searchTicketsPageFactory(){return Os(this.deskContext)}get getDepartments(){return Ps(this.deskContext)}get getDepartmentById(){return As(this.deskContext)}get getContacts(){return Gr(this.deskContext)}get getContactById(){return ks(this.deskContext)}get getContactsByIds(){return Zs(this.deskContext)}get getContactsPageFactory(){return Ds(this.deskContext)}get getTicketTags(){return Ls(this.deskContext)}get associateTicketTags(){return vs(this.deskContext)}get dissociateTicketTag(){return Ns(this.deskContext)}get searchTags(){return _s(this.deskContext)}get getAllTags(){return ws(this.deskContext)}get getTicketFollowers(){return Vs(this.deskContext)}get addTicketFollowers(){return Ks(this.deskContext)}get removeTicketFollowers(){return Us(this.deskContext)}get getTicketAttachments(){return Bs(this.deskContext)}get deleteTicketAttachment(){return Gs(this.deskContext)}get getTicketComments(){return qs(this.deskContext)}get getTicketCommentById(){return $s(this.deskContext)}get createTicketComment(){return Hs(this.deskContext)}get deleteTicketComment(){return zs(this.deskContext)}get getTicketTimer(){return Js(this.deskContext)}get performTicketTimerAction(){return Ys(this.deskContext)}get getTicketTimeEntries(){return Xs(this.deskContext)}get getTicketTimeEntryById(){return Qs(this.deskContext)}get getTicketTimeEntrySummation(){return ec(this.deskContext)}get getTicketThreads(){return qr(this.deskContext)}get getTicketThreadById(){return rc(this.deskContext)}get getTicketThreadsPageFactory(){return nc(this.deskContext)}get getTicketActivities(){return $r(this.deskContext)}get getTicketActivitiesPageFactory(){return ac(this.deskContext)}get getAgents(){return Hr(this.deskContext)}get getAgentById(){return sc(this.deskContext)}get getAgentsByIds(){return cc(this.deskContext)}get getMyInfo(){return uc(this.deskContext)}get getAgentsPageFactory(){return pc(this.deskContext)}};Ve=I([Sm(),A(0,Lc(_t)),A(1,Lc(w))],Ve);import{ConfigModule as L$,ConfigService as v$}from"@nestjs/config";function Cm(e){return`${e.clientId}:${e.refreshToken}`}function ct(e){let t=mc([yc(),hc(mt())]),o=new Map;function r(p,d){let h=Cm(p),y=o.get(h);if(y)return y;let f={zohoAccounts:{serviceAccessTokenKey:d,refreshToken:p.refreshToken,clientId:p.clientId,clientSecret:p.clientSecret,apiUrl:p.region??"us"}},T=new w(f,t);return o.set(h,T),T}let n,a=yt(e,"recruit");if(a){let p=r(a,"recruit"),d={zohoRecruit:{apiUrl:a.apiMode}};n=new Le(d,p)}let i,s=yt(e,"crm");if(s){let p=r(s,"crm"),d={zohoCrm:{apiUrl:s.apiMode}};i=new De(d,p)}let c,u=yt(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:i,deskApi:c}}import{existsSync as Nc,mkdirSync as _c,writeFileSync as Im}from"node:fs";import{join as wc}from"node:path";var pt={};function Vc(e){pt=e}var Om=[/Bearer\s+\S+/gi,/access_token[=:]\s*\S+/gi,/refresh_token[=:]\s*\S+/gi,/client_secret[=:]\s*\S+/gi,/1000\.\w{20,}/g];function ut(e){let t=e;for(let o of Om)t=t.replace(o,"[REDACTED]");return t}function Kc(){return new Date().toISOString().replaceAll(/[:.]/g,"-")}function tn(){return pt}function on(e,t){let{dumpDir:o,commandPath:r}=pt;if(!o)return;Nc(o)||_c(o,{recursive:!0});let n=r?.length?r.join("_"):"response",a=Kc(),i=t?`${n}_${a}_${t}`:`${n}_${a}`;return wc(o,`${i}.${e}`)}function Mm(e,t){let{dumpDir:o,commandPath:r}=pt;if(!o)return;Nc(o)||_c(o,{recursive:!0});let a=`${r?.length?r.join("_"):"response"}_${Kc()}.json`,i=wc(o,a),s={ok:!0,data:e,...t?{meta:t}:{}};Im(i,JSON.stringify(s,null,2))}function dt(e,t){let o=t.split(",").map(r=>r.trim());return Array.isArray(e)?e.map(r=>vc(r,o)):e!=null&&typeof e=="object"?vc(e,o):e}function vc(e,t){if(e==null||typeof e!="object")return e;let o={};for(let r of t)r in e&&(o[r]=e[r]);return o}function l(e,t){Mm(e,t);let r={ok:!0,data:pt.pick?dt(e,pt.pick):e,...t?{meta:t}:{}};console.log(JSON.stringify(r))}function m(e){let t=Pm(e);console.log(JSON.stringify(t))}function Pm(e){return e instanceof $?{ok:!1,error:ut(e.message),code:"TOKEN_EXPIRED",suggestion:"Run: zoho-cli auth check"}:e instanceof Mt?{ok:!1,error:ut(e.message),code:"AUTH_ERROR",suggestion:"Check your client ID, secret, and refresh token."}:e instanceof Pt?{ok:!1,error:ut(e.message),code:"RATE_LIMITED",suggestion:"Wait and retry. Zoho rate limit exceeded."}:e instanceof j?{ok:!1,error:ut(e.message),code:"API_ERROR"}:e instanceof Error?{ok:!1,error:ut(e.message),code:"ERROR"}:{ok:!1,error:ut(String(e)),code:"UNKNOWN_ERROR"}}var Uc={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"},Wc={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 Am(e){if(e){if(e.startsWith("http://")||e.startsWith("https://"))try{let o=new URL(e).searchParams.get("code");if(!o)throw new Error('No "code" parameter found in the provided URL.');return o}catch(t){throw t instanceof TypeError?new Error(`Invalid URL provided for --code: ${e}`):t}return e}}var Em={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:[...Kt],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 B(),o=e.product,r=e.clientId??t?.shared?.clientId,n=e.clientSecret??t?.shared?.clientSecret,a=e.redirectUri,i=e.region??t?.shared?.region??"us",s=e.scopes.split(",").map(d=>d.trim()),c=Am(e.code),u=e.token,p=Uc[i]??Uc.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 h={...d,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0},y=await G({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:h});l({success:!0,product:o,refreshToken:ge(u),configSaved:!0,configuredProducts:J(y)})}else{let h=await G({shared:{...d,region:i,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0});l({success:!0,refreshToken:ge(u),configSaved:!0,configuredProducts:J(h)})}}else if(c){let d=`${p}/oauth/v2/token`,h=new URLSearchParams({grant_type:"authorization_code",client_id:r,client_secret:n,redirect_uri:a,code:c}),f=await(await fetch(d,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:h.toString()})).json();if(f.error)throw new Error(`Token exchange failed: ${f.error}`);let T=f.refresh_token;if(!T)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:T},O;o?O=await G({shared:t?.shared??{clientId:"",clientSecret:"",refreshToken:""},[o]:{...R,apiUrl:e.apiMode,orgId:o==="desk"?e.orgId:void 0}}):O=await G({shared:{...R,region:i,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({step:2,success:!0,product:o??"shared",refreshToken:ge(T),accessToken:f.access_token?ge(f.access_token):null,scope:f.scope,configSaved:!0,configuredProducts:J(O)})}else{let d=s.flatMap(y=>Wc[y]??[]);if(d.length===0)throw new Error(`No valid products specified. Choose from: ${Object.keys(Wc).join(", ")}`);let h=`${p}/oauth/v2/auth?scope=${d.join(",")}&client_id=${encodeURIComponent(r)}&response_type=code&access_type=offline&redirect_uri=${encodeURIComponent(a)}`;await G({shared:{clientId:r,clientSecret:n,refreshToken:t?.shared?.refreshToken??"",region:i,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:h,redirectUri:a,scopes:d,credentialsSaved:!0,nextStep:'zoho-cli auth setup --code "PASTE_REDIRECT_URL_OR_AUTH_CODE"'})}}catch(t){m(t),process.exit(1)}}},km={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:[...Kt],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 G({shared:(await B())?.shared??{clientId:"",clientSecret:"",refreshToken:""},[t]:{...o,apiUrl:e.apiMode,orgId:t==="desk"?e.orgId:void 0}}):r=await G({shared:{...o,region:e.region,apiMode:e.apiMode},desk:e.orgId?{orgId:e.orgId}:void 0}),l({saved:!0,product:t??"shared",configuredProducts:J(r)})}catch(t){m(t),process.exit(1)}}},Zm={command:"show",describe:"Show current configuration (secrets masked)",builder:e=>e,handler:async()=>{try{let o=function(r){if(r)return{clientId:r.clientId?ge(r.clientId):void 0,clientSecret:r.clientSecret?ge(r.clientSecret):void 0,refreshToken:r.refreshToken?ge(r.refreshToken):void 0}};var e=o;let t=await B();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:J(t)})}catch(t){m(t),process.exit(1)}}},Dm={command:"check",describe:"Verify credentials by exchanging tokens",builder:e=>e,handler:async()=>{try{let e=await B();if(!e){l({authenticated:!1,error:"No credentials configured. Run: zoho-cli auth setup"});return}let t=J(e);if(t.length===0){l({authenticated:!1,error:"No products have complete credentials. Run: zoho-cli auth setup"});return}let o=ct(e),r={};for(let n of t)try{let a;if(n==="recruit"?a=o.recruitApi:n==="crm"?a=o.crmApi:a=o.deskApi,!a){r[n]={authenticated:!1,error:"Not configured"};continue}let s=await a.zohoAccountsApi.accessToken();r[n]={authenticated:!0,scope:s.scope,expiresIn:s.expires_in}}catch(a){let i=a instanceof Error?a.message:String(a);r[n]={authenticated:!1,error:i}}l({products:r})}catch(e){m(e),process.exit(1)}}},Lm={command:"clear",describe:"Remove stored credentials and token cache",builder:e=>e,handler:async()=>{try{await pn(),l({cleared:!0})}catch(e){m(e),process.exit(1)}}},Bc={command:"auth",describe:"Manage Zoho API credentials",builder:e=>e.command(Em).command(km).command(Zm).command(Dm).command(Lm).demandCommand(1,"Please specify an auth subcommand."),handler:S};import{access as vm,constants as Nm}from"node:fs";import{dirname as _m}from"node:path";var Gc={command:"doctor",describe:"Check CLI configuration and connectivity",builder:e=>e,handler:async()=>{let e=[],t=await B();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=_m(mt());if(await wm(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 a=J(t);a.length>0?e.push({name:"products",status:"pass",message:`Configured products: ${a.join(", ")}`}):e.push({name:"products",status:"fail",message:"No products have complete credentials"});let i=ct(t);for(let s of a)try{let c;if(s==="recruit"?c=i.recruitApi:s==="crm"?c=i.crmApi:c=i.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}`}):a.includes("desk")||e.push({name:"desk-org-id",status:"warn",message:"No Desk org ID. Desk commands unavailable."})}let n=e.every(a=>a.status==="pass");l({checks:e,healthy:n}),n||process.exit(e.some(a=>a.status==="fail")?1:0)}};function wm(e){return new Promise(t=>{vm(e,Nm.W_OK,o=>{t(!o)})})}var rn;function jc(e){return async t=>{let o=t._?.[0];if(!(typeof o=="string"&&e.has(o)))try{let r=await B();r||(m(new Error("Not authenticated. Run: zoho-cli auth setup --client-id X --client-secret Y --token Z")),process.exit(4)),J(r).length===0&&(m(new Error("No products configured with complete credentials. Run: zoho-cli auth setup")),process.exit(4)),rn=ct(r)}catch(r){m(r),process.exit(4)}}}function nn(e){if(!rn)throw new Error("CLI context not initialized. This is a bug.");return rn}function H(e){let{recruitApi:t}=nn(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 z(e){let{crmApi:t}=nn(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 b(e){let{deskApi:t}=nn(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}var Vm=["raw","page_by_line","data_by_line"],Km=["replace","concat"],Um=["meta","pages","merged_page"];function qc(e){return e.option("multiple-pages",{type:"number",default:1,describe:"Pages to fetch in this invocation (>=1). Continues from --page (CRM/Recruit) or --from (Desk)."}).option("multiple-pages-output",{type:"string",choices:Um,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:Vm,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:Km,default:"replace",describe:"Across pages with multiple-pages > 1: replace (truncate file each iteration; only last page survives) or concat (append)."})}function ce(e){return qc(e.option("page",{type:"number",default:1,describe:"Page number (1-based)"}).option("per-page",{type:"number",default:20,describe:"Records per page"}))}function k(e){return qc(e.option("from",{type:"number",default:1,describe:"Start index (1-based)"}).option("limit",{type:"number",default:25,describe:"Max records (max 50)"}))}function L(e){return e.option("module",{alias:"m",type:"string",demandOption:!0,describe:"Zoho module name (e.g. Candidates, Contacts, Leads)"})}function Pe(e){return e.option("id",{type:"string",demandOption:!0,describe:"Record ID"})}function wt(e,t=!1){return e.option("fields",{type:"string",demandOption:t,describe:"Comma-separated field names to return"})}function Mo(e){return e.option("sort-by",{type:"string",describe:"Field to sort by"}).option("sort-order",{type:"string",choices:["asc","desc"],describe:"Sort direction"})}import{writeFileSync as Wm,appendFileSync as Bm}from"node:fs";var ue={nextInput:(e,t)=>{if(!t.info?.more_records)return;let o=e.page??1;return{...e,page:o+1}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({page:t.info?.page??e.page,per_page:t.info?.per_page??e.per_page,more_records:t.info?.more_records??!1}),hasMorePagesAvailable:(e,t)=>t.info?.more_records??!1},Z={nextInput:(e,t)=>{let o=e.limit??25;if(o<=0||(t.data?.length??0)<o)return;let n=e.from??1;return{...e,from:n+o}},countOf:e=>e.data?.length??0,metaOf:(e,t)=>({from:e.from,limit:e.limit,count:t.data?.length??0}),hasMorePagesAvailable:(e,t)=>{let o=e.limit??25;return o<=0?!1:(t.data?.length??0)>=o}};function Gm(e){let{dumpOutput:t,dumpMerge:o}=e,{pick:r}=tn(),n=t==="raw"?"json":"ndjson",a=on(n),i=r?on(n,"pick"):void 0;if(!a)return{mainPath:void 0,pickPath:void 0,writePage:()=>{},close:()=>{}};let s=0;function c(d){if(!r)return d;let h=dt(d.data,r);return{...d,data:h}}function u(d){let h=d.append?Bm:Wm;a&&h(a,d.mainContent),i&&d.pickContent!==void 0&&h(i,d.pickContent)}function p(d){let y=o==="concat"&&!(s===0);if(t==="raw"){let f=JSON.stringify(d,null,2),T=i?JSON.stringify(c(d),null,2):void 0;u({mainContent:f,pickContent:T,append:y})}else if(t==="page_by_line"){let f=JSON.stringify(d)+`
|
|
5
5
|
`,T=i?JSON.stringify(c(d))+`
|
|
6
|
-
`:void 0;u({mainContent:
|
|
7
|
-
`,
|
|
8
|
-
`:void 0;u({mainContent:v,pickContent:U,append:M})})}s+=1}return{mainPath:a,pickPath:i,writePage:p,close:()=>{}}}async function F(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:a,dumpMerge:i}=e,s=Math.max(1,Math.floor(e.multiplePages||1));if(s<=1)return{handled:!1,result:await o(t)};let c=en();c.dumpDir||console.error("[zoho-cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let u=Gm({dumpOutput:a,dumpMerge:i}),p=[],d=[],g=n==="pages",y=n==="merged_page",h=t,T=0,R=0,S=!1,M,v=t;try{for(let D=0;D<s;D++){let P=await o(h);if(T+=1,R+=r.countOf(P),M=P,v=h,u.writePage(P),g)p.push(P);else if(y)for(let Vt of P.data??[])d.push(Vt);let ge=r.nextInput(h,P);if(S=r.hasMorePagesAvailable(h,P),!ge)break;h=ge}}finally{u.close()}let U=c.pick,I={pagesFetched:T,totalRecords:R,hasMorePagesAvailable:S,dumpFile:u.mainPath??null};if(u.pickPath&&(I.dumpFilePick=u.pickPath),n==="meta")console.log(JSON.stringify({ok:!0,meta:I}));else if(n==="pages"){let D=U?p.map(P=>({...P,data:dt(P.data,U)})):p;console.log(JSON.stringify({ok:!0,data:D,meta:I}))}else{let D=M?r.metaOf(v,M):{},P=U?dt(d,U):d;console.log(JSON.stringify({ok:!0,data:P,meta:{...D,...I}}))}return{handled:!0}}var jm={command:"list",describe:"List records from a module",builder:e=>Mo(wt(ue(L(e)))),handler:async e=>{try{let t=H(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder},r=await F({initialInput:o,fetchPage:n=>t.getRecords(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},qm={command:"get",describe:"Get a record by ID",builder:e=>Ae(L(e)),handler:async e=>{try{let o=await H(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){m(t),process.exit(1)}}},$m={command:"search",describe:"Search records in a module",builder:e=>ue(L(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=H(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.searchRecords(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},Hm={command:"insert",describe:"Insert a record into a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=H(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},zm={command:"upsert",describe:"Upsert a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=H(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},Jm={command:"update",describe:"Update a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=H(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},Ym={command:"delete",describe:"Delete records from a module",builder:e=>L(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=H(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){m(t),process.exit(1)}}},Xm={command:"emails",describe:"Get emails for a record",builder:e=>ue(Ae(L(e))),handler:async e=>{try{let t=H(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getEmailsForRecord(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},Qm={command:"attachments",describe:"Get attachments for a record",builder:e=>ue(Ae(L(e))),handler:async e=>{try{let t=H(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getAttachmentsForRecord(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},$c={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(jm).command(qm).command($m).command(Hm).command(zm).command(Jm).command(Ym).command(Xm).command(Qm).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:C};var ey={command:"list",describe:"List records from a module",builder:e=>Mo(wt(ue(L(e)),!0)),handler:async e=>{try{let t=z(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder},r=await F({initialInput:o,fetchPage:n=>t.getRecords(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},ty={command:"get",describe:"Get a record by ID",builder:e=>Ae(L(e)),handler:async e=>{try{let o=await z(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){m(t),process.exit(1)}}},oy={command:"search",describe:"Search records in a module",builder:e=>ue(L(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=z(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.searchRecords(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},ry={command:"insert",describe:"Insert a record into a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=z(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},ny={command:"upsert",describe:"Upsert a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=z(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},ay={command:"update",describe:"Update a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=z(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},iy={command:"delete",describe:"Delete records from a module",builder:e=>L(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=z(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){m(t),process.exit(1)}}},sy={command:"emails",describe:"Get emails for a record",builder:e=>ue(Ae(L(e))),handler:async e=>{try{let t=z(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getEmailsForRecord(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},cy={command:"attachments",describe:"Get attachments for a record",builder:e=>wt(ue(Ae(L(e))),!0),handler:async e=>{try{let t=z(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getAttachmentsForRecord(n),adapter:pe,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},Hc={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(ey).command(ty).command(oy).command(ry).command(ny).command(ay).command(iy).command(sy).command(cy).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:C};var uy={command:"list",describe:"List tickets",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:Z,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){m(t),process.exit(1)}}},py={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 b(e).getTicketById({ticketId:e.ticketId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},dy={command:"search",describe:"Search tickets",builder:e=>k(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=b(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 F({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:Z,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){m(t),process.exit(1)}}},ly={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>k(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=b(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:Z,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){m(t),process.exit(1)}}},my={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 b(e).getTicketMetrics({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},yy={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=b(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});l(r)}catch(t){m(t),process.exit(1)}}},zc={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(uy).command(py).command(dy).command(ly).command(my).command(yy).demandCommand(1),handler:C};var hy={command:"list",describe:"List departments",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await F({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:Z,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){m(t),process.exit(1)}}},fy={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 b(e).getDepartmentById({departmentId:e.departmentId});l(o)}catch(t){m(t),process.exit(1)}}},Jc={command:"departments",describe:"Desk department operations",builder:e=>e.command(hy).command(fy).demandCommand(1),handler:C};var gy={command:"list",describe:"List contacts",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:Z,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){m(t),process.exit(1)}}},Ty={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 b(e).getContactById({contactId:e.contactId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},Yc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(gy).command(Ty).demandCommand(1),handler:C};var xy={command:"list",describe:"List agents",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:Z,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){m(t),process.exit(1)}}},Ry={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 b(e).getAgentById({agentId:e.agentId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},by={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await b(e).getMyInfo();l(o)}catch(t){m(t),process.exit(1)}}},Xc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(xy).command(Ry).command(by).demandCommand(1),handler:C};var Fy={command:"list",describe:"List all tags",builder:e=>k(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await F({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:Z,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){m(t),process.exit(1)}}},Sy={command:"search",describe:"Search tags",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await F({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:Z,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){m(t),process.exit(1)}}},Cy={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 b(e).getTicketTags({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},Iy={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=b(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});l(r)}catch(t){m(t),process.exit(1)}}},Oy={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 b(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),l({removed:!0})}catch(t){m(t),process.exit(1)}}},Qc={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Fy).command(Sy).command(Cy).command(Iy).command(Oy).demandCommand(1),handler:C};var My={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await F({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:Z,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){m(t),process.exit(1)}}},Py={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 b(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});l(o)}catch(t){m(t),process.exit(1)}}},Ay={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 b(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});l(o)}catch(t){m(t),process.exit(1)}}},Ey={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 b(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),l({deleted:!0})}catch(t){m(t),process.exit(1)}}},eu={command:"comments",describe:"Desk comment operations",builder:e=>e.command(My).command(Py).command(Ay).command(Ey).demandCommand(1),handler:C};var ky={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:Z,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){m(t),process.exit(1)}}},Zy={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 b(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),l({deleted:!0})}catch(t){m(t),process.exit(1)}}},tu={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(ky).command(Zy).demandCommand(1),handler:C};var Dy={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 b(e).getTicketFollowers({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},Ly={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=b(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({added:!0})}catch(t){m(t),process.exit(1)}}},vy={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=b(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({removed:!0})}catch(t){m(t),process.exit(1)}}},ou={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(Dy).command(Ly).command(vy).demandCommand(1),handler:C};var Ny={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 b(e).getTicketTimer({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},_y={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 b(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});l(o)}catch(t){m(t),process.exit(1)}}},wy={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:Z,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){m(t),process.exit(1)}}},Vy={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 b(e).getTicketTimeEntrySummation({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},ru={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(Ny).command(_y).command(wy).command(Vy).demandCommand(1),handler:C};var Ky={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:Z,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){m(t),process.exit(1)}}},Uy={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 b(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},nu={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(Ky).command(Uy).demandCommand(1),handler:C};var Wy={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:Z,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){m(t),process.exit(1)}}},au={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Wy).demandCommand(1),handler:C};var iu={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(zc).command(Jc).command(Yc).command(Xc).command(Qc).command(eu).command(tu).command(ou).command(ru).command(nu).command(au).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:C};var su={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=H(e).recruitContext;break;case"crm":n=z(e).crmContext;break;case"desk":n=b(e).deskContext;break;default:throw new Error(`Unknown product: ${t}`)}let a=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),p=a.includes("?")?"&":"?";a=`${a}${p}${u.toString()}`}let i={method:o};e.body&&(i.body=e.body,i.headers={"Content-Type":"application/json"});let s=await n.fetchJson(a,i);l(s)}catch(t){m(t),process.exit(1)}}};var By={command:"set",describe:"Configure output settings (global or per-command)",builder:e=>e.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. desk.tickets.list)"}).check(t=>{if(!t.setDumpDir&&!t.setPick)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:async e=>{try{let t=e.command,o=e.setDumpDir,r=e.setPick,n;if(t){let i={...o!==void 0?{dumpDir:o}:{},...r!==void 0?{pick:r}:{}};n={commands:{[t]:i}}}else n={...o!==void 0?{dumpDir:o}:{},...r!==void 0?{pick:r}:{}};let a=await G({output:n});l({saved:!0,output:a.output})}catch(t){m(t),process.exit(1)}}},Gy={command:"show",describe:"Show current output configuration",builder:e=>e,handler:async()=>{try{let e=await B();l({output:e?.output??{}})}catch(e){m(e),process.exit(1)}}},jy={command:"clear",describe:"Clear output configuration (global or per-command)",builder:e=>e.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:async e=>{try{let t=e.command;if(t){let o=await B(),r={...o?.output?.commands};delete r[t];let n={...o?.output,commands:r};await G({output:n}),l({cleared:!0,command:t})}else await cn(),l({cleared:!0})}catch(t){m(t),process.exit(1)}}},cu={command:"output",describe:"Configure output settings (dump, field filtering)",builder:e=>e.command(By).command(Gy).command(jy).demandCommand(1),handler:C};var Hy=[$c,Hc,iu,su],uu=[Bc,cu,Gc];function zy(e){return e.command.split(" ")[0]}var nn=new Set(uu.map(zy));function Jy(){return async e=>{let t=e._?e._.map(String):[],o=t[0],r=e.setDumpDir,n=e.setPick;if((r!==void 0||n!==void 0)&&o&&!nn.has(o)){let u=t.join("."),p={...r!==void 0?{dumpDir:r}:{},...n!==void 0?{pick:n}:{}};await G({output:{commands:{[u]:p}}})}let i=o&&!nn.has(o),s=await B(),c=i?sn(s?.output,t,{dumpDir:e.dumpDir??r,pick:e.pick??n}):{dumpDir:void 0,pick:void 0};Vc({dumpDir:c.dumpDir,pick:e.pickAll?void 0:c.pick,commandPath:t})}}async function Yy(){try{await qy($y(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([jc(nn),Jy()],!0).command(uu).command(Hy).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)}}Yy();
|
|
6
|
+
`:void 0;u({mainContent:f,pickContent:T,append:y})}else{let f=d.data??[],T=i?dt(f,r):void 0;f.length===0?y||u({mainContent:"",pickContent:i?"":void 0,append:!1}):f.forEach((R,O)=>{let P=y||O>0,K=JSON.stringify(R)+`
|
|
7
|
+
`,W=i&&T?JSON.stringify(T[O])+`
|
|
8
|
+
`:void 0;u({mainContent:K,pickContent:W,append:P})})}s+=1}return{mainPath:a,pickPath:i,writePage:p,close:()=>{}}}async function F(e){let{initialInput:t,fetchPage:o,adapter:r,multiplePagesOutput:n,dumpOutput:a,dumpMerge:i}=e,s=Math.max(1,Math.floor(e.multiplePages||1));if(s<=1)return{handled:!1,result:await o(t)};let c=tn();c.dumpDir||console.error("[zoho-cli] warning: --multiple-pages used without --dump-dir; results not persisted.");let u=Gm({dumpOutput:a,dumpMerge:i}),p=[],d=[],h=n==="pages",y=n==="merged_page",f=t,T=0,R=0,O=!1,P,K=t;try{for(let D=0;D<s;D++){let M=await o(f);if(T+=1,R+=r.countOf(M),P=M,K=f,u.writePage(M),h)p.push(M);else if(y)for(let Vt of M.data??[])d.push(Vt);let fe=r.nextInput(f,M);if(O=r.hasMorePagesAvailable(f,M),!fe)break;f=fe}}finally{u.close()}let W=c.pick,C={pagesFetched:T,totalRecords:R,hasMorePagesAvailable:O,dumpFile:u.mainPath??null};if(u.pickPath&&(C.dumpFilePick=u.pickPath),n==="meta")console.log(JSON.stringify({ok:!0,meta:C}));else if(n==="pages"){let D=W?p.map(M=>({...M,data:dt(M.data,W)})):p;console.log(JSON.stringify({ok:!0,data:D,meta:C}))}else{let D=P?r.metaOf(K,P):{},M=W?dt(d,W):d;console.log(JSON.stringify({ok:!0,data:M,meta:{...D,...C}}))}return{handled:!0}}var jm={command:"list",describe:"List records from a module",builder:e=>Mo(wt(ce(L(e)))),handler:async e=>{try{let t=H(e),o={module:e.module,page:e.page,per_page:e.perPage,fields:e.fields,sort_by:e.sortBy,sort_order:e.sortOrder},r=await F({initialInput:o,fetchPage:n=>t.getRecords(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},qm={command:"get",describe:"Get a record by ID",builder:e=>Pe(L(e)),handler:async e=>{try{let o=await H(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){m(t),process.exit(1)}}},$m={command:"search",describe:"Search records in a module",builder:e=>ce(L(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=H(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.searchRecords(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},Hm={command:"insert",describe:"Insert a record into a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=H(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},zm={command:"upsert",describe:"Upsert a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=H(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},Jm={command:"update",describe:"Update a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=H(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},Ym={command:"delete",describe:"Delete records from a module",builder:e=>L(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=H(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){m(t),process.exit(1)}}},Xm={command:"emails",describe:"Get emails for a record",builder:e=>ce(Pe(L(e))),handler:async e=>{try{let t=H(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getEmailsForRecord(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},Qm={command:"attachments",describe:"Get attachments for a record",builder:e=>ce(Pe(L(e))),handler:async e=>{try{let t=H(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getAttachmentsForRecord(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},$c={command:"recruit",describe:"Zoho Recruit operations",builder:e=>e.command(jm).command(qm).command($m).command(Hm).command(zm).command(Jm).command(Ym).command(Xm).command(Qm).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 ey={command:"list",describe:"List records from a module",builder:e=>Mo(wt(ce(L(e)),!0)),handler:async e=>{try{let t=z(e),o={module:e.module,fields:e.fields,page:e.page,per_page:e.perPage,sort_by:e.sortBy,sort_order:e.sortOrder},r=await F({initialInput:o,fetchPage:n=>t.getRecords(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},ty={command:"get",describe:"Get a record by ID",builder:e=>Pe(L(e)),handler:async e=>{try{let o=await z(e).getRecordById({module:e.module,id:e.id});l(o)}catch(t){m(t),process.exit(1)}}},oy={command:"search",describe:"Search records in a module",builder:e=>ce(L(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=z(e),o={module:e.module,criteria:e.criteria,word:e.word,email:e.email,phone:e.phone,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.searchRecords(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},ry={command:"insert",describe:"Insert a record into a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array)"}),handler:async e=>{try{let t=z(e),o=JSON.parse(e.data),r=await t.insertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},ny={command:"upsert",describe:"Upsert a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, include id for update)"}),handler:async e=>{try{let t=z(e),o=JSON.parse(e.data),r=await t.upsertRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},ay={command:"update",describe:"Update a record in a module",builder:e=>L(e).option("data",{type:"string",demandOption:!0,describe:"JSON record data (object or array, must include id)"}),handler:async e=>{try{let t=z(e),o=JSON.parse(e.data),r=await t.updateRecord({module:e.module,data:o});l(r)}catch(t){m(t),process.exit(1)}}},iy={command:"delete",describe:"Delete records from a module",builder:e=>L(e).option("ids",{type:"string",demandOption:!0,describe:"Comma-separated record IDs to delete"}),handler:async e=>{try{let t=z(e),o=e.ids.split(",").map(n=>n.trim()),r=await t.deleteRecord({module:e.module,ids:o});l(r)}catch(t){m(t),process.exit(1)}}},sy={command:"emails",describe:"Get emails for a record",builder:e=>ce(Pe(L(e))),handler:async e=>{try{let t=z(e),o={module:e.module,id:e.id,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getEmailsForRecord(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},cy={command:"attachments",describe:"Get attachments for a record",builder:e=>wt(ce(Pe(L(e))),!0),handler:async e=>{try{let t=z(e),o={module:e.module,id:e.id,fields:e.fields,page:e.page,per_page:e.perPage},r=await F({initialInput:o,fetchPage:n=>t.getAttachmentsForRecord(n),adapter:ue,multiplePages:e.multiplePages,multiplePagesOutput:e.multiplePagesOutput,dumpOutput:e.dumpOutput,dumpMerge:e.dumpMerge});if(r.handled===!1){let n=r.result;l(n.data,{page:n.info?.page,per_page:n.info?.per_page,more_records:n.info?.more_records})}}catch(t){m(t),process.exit(1)}}},Hc={command:"crm",describe:"Zoho CRM operations",builder:e=>e.command(ey).command(ty).command(oy).command(ry).command(ny).command(ay).command(iy).command(sy).command(cy).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 uy={command:"list",describe:"List tickets",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,sortBy:e.sortBy,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getTickets(n),adapter:Z,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){m(t),process.exit(1)}}},py={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 b(e).getTicketById({ticketId:e.ticketId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},dy={command:"search",describe:"Search tickets",builder:e=>k(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=b(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 F({initialInput:o,fetchPage:n=>t.searchTickets(n),adapter:Z,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){m(t),process.exit(1)}}},ly={command:"by-contact <contactId>",describe:"List tickets for a contact",builder:e=>k(e).positional("contactId",{type:"string",demandOption:!0,describe:"Contact ID"}),handler:async e=>{try{let t=b(e),o={contactId:e.contactId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketsForContact(n),adapter:Z,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){m(t),process.exit(1)}}},my={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 b(e).getTicketMetrics({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},yy={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=b(e),o=e.agentIds.split(",").map(n=>n.trim()),r=await t.getAgentsTicketsCount({agentIds:o,departmentId:e.departmentId});l(r)}catch(t){m(t),process.exit(1)}}},zc={command:"tickets",describe:"Desk ticket operations",builder:e=>e.command(uy).command(py).command(dy).command(ly).command(my).command(yy).demandCommand(1),handler:S};var hy={command:"list",describe:"List departments",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,searchStr:e.search,isEnabled:e.isEnabled},r=await F({initialInput:o,fetchPage:n=>t.getDepartments(n),adapter:Z,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){m(t),process.exit(1)}}},fy={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 b(e).getDepartmentById({departmentId:e.departmentId});l(o)}catch(t){m(t),process.exit(1)}}},Jc={command:"departments",describe:"Desk department operations",builder:e=>e.command(hy).command(fy).demandCommand(1),handler:S};var gy={command:"list",describe:"List contacts",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,sortBy:e.sortBy,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getContacts(n),adapter:Z,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){m(t),process.exit(1)}}},Ty={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 b(e).getContactById({contactId:e.contactId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},Yc={command:"contacts",describe:"Desk contact operations",builder:e=>e.command(gy).command(Ty).demandCommand(1),handler:S};var xy={command:"list",describe:"List agents",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,status:e.status,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getAgents(n),adapter:Z,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){m(t),process.exit(1)}}},Ry={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 b(e).getAgentById({agentId:e.agentId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},by={command:"my-info",describe:"Get current authenticated agent info",builder:e=>e,handler:async e=>{try{let o=await b(e).getMyInfo();l(o)}catch(t){m(t),process.exit(1)}}},Xc={command:"agents",describe:"Desk agent operations",builder:e=>e.command(xy).command(Ry).command(by).demandCommand(1),handler:S};var Fy={command:"list",describe:"List all tags",builder:e=>k(e).option("department-id",{alias:"d",type:"string",demandOption:!0,describe:"Department ID"}),handler:async e=>{try{let t=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId},r=await F({initialInput:o,fetchPage:n=>t.getAllTags(n),adapter:Z,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){m(t),process.exit(1)}}},Sy={command:"search",describe:"Search tags",builder:e=>k(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=b(e),o={from:e.from,limit:e.limit,departmentId:e.departmentId,searchVal:e.query},r=await F({initialInput:o,fetchPage:n=>t.searchTags(n),adapter:Z,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){m(t),process.exit(1)}}},Cy={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 b(e).getTicketTags({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},Iy={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=b(e),o=e.tags.split(",").map(n=>n.trim()),r=await t.associateTicketTags({ticketId:e.ticketId,tags:o});l(r)}catch(t){m(t),process.exit(1)}}},Oy={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 b(e).dissociateTicketTag({ticketId:e.ticketId,tagId:e.tagId}),l({removed:!0})}catch(t){m(t),process.exit(1)}}},Qc={command:"tags",describe:"Desk tag operations",builder:e=>e.command(Fy).command(Sy).command(Cy).command(Iy).command(Oy).demandCommand(1),handler:S};var My={command:"list <ticketId>",describe:"List comments on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("sort-by",{type:"string",describe:"Sort field"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,sortBy:e.sortBy},r=await F({initialInput:o,fetchPage:n=>t.getTicketComments(n),adapter:Z,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){m(t),process.exit(1)}}},Py={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 b(e).getTicketCommentById({ticketId:e.ticketId,commentId:e.commentId});l(o)}catch(t){m(t),process.exit(1)}}},Ay={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 b(e).createTicketComment({ticketId:e.ticketId,content:e.content,isPublic:e.public,contentType:e.contentType});l(o)}catch(t){m(t),process.exit(1)}}},Ey={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 b(e).deleteTicketComment({ticketId:e.ticketId,commentId:e.commentId}),l({deleted:!0})}catch(t){m(t),process.exit(1)}}},eu={command:"comments",describe:"Desk comment operations",builder:e=>e.command(My).command(Py).command(Ay).command(Ey).demandCommand(1),handler:S};var ky={command:"list <ticketId>",describe:"List attachments on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketAttachments(n),adapter:Z,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){m(t),process.exit(1)}}},Zy={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 b(e).deleteTicketAttachment({ticketId:e.ticketId,attachmentId:e.attachmentId}),l({deleted:!0})}catch(t){m(t),process.exit(1)}}},tu={command:"attachments",describe:"Desk attachment operations",builder:e=>e.command(ky).command(Zy).demandCommand(1),handler:S};var Dy={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 b(e).getTicketFollowers({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},Ly={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=b(e),o=e.agentIds.split(",").map(r=>r.trim());await t.addTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({added:!0})}catch(t){m(t),process.exit(1)}}},vy={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=b(e),o=e.agentIds.split(",").map(r=>r.trim());await t.removeTicketFollowers({ticketId:e.ticketId,agentIds:o}),l({removed:!0})}catch(t){m(t),process.exit(1)}}},ou={command:"followers",describe:"Desk ticket follower operations",builder:e=>e.command(Dy).command(Ly).command(vy).demandCommand(1),handler:S};var Ny={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 b(e).getTicketTimer({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},_y={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 b(e).performTicketTimerAction({ticketId:e.ticketId,timerAction:e.action});l(o)}catch(t){m(t),process.exit(1)}}},wy={command:"entries <ticketId>",describe:"List time entries for a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketTimeEntries(n),adapter:Z,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){m(t),process.exit(1)}}},Vy={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 b(e).getTicketTimeEntrySummation({ticketId:e.ticketId});l(o)}catch(t){m(t),process.exit(1)}}},ru={command:"time",describe:"Desk time tracking operations",builder:e=>e.command(Ny).command(_y).command(wy).command(Vy).demandCommand(1),handler:S};var Ky={command:"list <ticketId>",describe:"List threads on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}).option("include",{type:"string",describe:"Comma-separated includes"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit,include:e.include},r=await F({initialInput:o,fetchPage:n=>t.getTicketThreads(n),adapter:Z,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){m(t),process.exit(1)}}},Uy={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 b(e).getTicketThreadById({ticketId:e.ticketId,threadId:e.threadId,include:e.include});l(o)}catch(t){m(t),process.exit(1)}}},nu={command:"threads",describe:"Desk ticket thread operations",builder:e=>e.command(Ky).command(Uy).demandCommand(1),handler:S};var Wy={command:"list <ticketId>",describe:"List activities on a ticket",builder:e=>k(e).positional("ticketId",{type:"string",demandOption:!0,describe:"Ticket ID"}),handler:async e=>{try{let t=b(e),o={ticketId:e.ticketId,from:e.from,limit:e.limit},r=await F({initialInput:o,fetchPage:n=>t.getTicketActivities(n),adapter:Z,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){m(t),process.exit(1)}}},au={command:"activities",describe:"Desk ticket activity operations",builder:e=>e.command(Wy).demandCommand(1),handler:S};var iu={command:"desk",describe:"Zoho Desk operations",builder:e=>e.command(zc).command(Jc).command(Yc).command(Xc).command(Qc).command(eu).command(tu).command(ou).command(ru).command(nu).command(au).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 su={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=H(e).recruitContext;break;case"crm":n=z(e).crmContext;break;case"desk":n=b(e).deskContext;break;default:throw new Error(`Unknown product: ${t}`)}let a=r;if(e.query){let c=JSON.parse(e.query),u=new URLSearchParams(c),p=a.includes("?")?"&":"?";a=`${a}${p}${u.toString()}`}let i={method:o};e.body&&(i.body=e.body,i.headers={"Content-Type":"application/json"});let s=await n.fetchJson(a,i);l(s)}catch(t){m(t),process.exit(1)}}};var By={command:"set",describe:"Configure output settings (global or per-command)",builder:e=>e.option("command",{alias:"c",type:"string",describe:"Command path to configure (e.g. desk.tickets.list)"}).check(t=>{if(!t.setDumpDir&&!t.setPick)throw new Error("At least one of --set-dump-dir or --set-pick is required");return!0}),handler:async e=>{try{let t=e.command,o=e.setDumpDir,r=e.setPick,n;if(t){let i={...o!==void 0?{dumpDir:o}:{},...r!==void 0?{pick:r}:{}};n={commands:{[t]:i}}}else n={...o!==void 0?{dumpDir:o}:{},...r!==void 0?{pick:r}:{}};let a=await G({output:n});l({saved:!0,output:a.output})}catch(t){m(t),process.exit(1)}}},Gy={command:"show",describe:"Show current output configuration",builder:e=>e,handler:async()=>{try{let e=await B();l({output:e?.output??{}})}catch(e){m(e),process.exit(1)}}},jy={command:"clear",describe:"Clear output configuration (global or per-command)",builder:e=>e.option("command",{alias:"c",type:"string",describe:"Command path to clear (omit to clear all output config)"}),handler:async e=>{try{let t=e.command;if(t){let o=await B(),r={...o?.output?.commands};delete r[t];let n={...o?.output,commands:r};await G({output:n}),l({cleared:!0,command:t})}else await un(),l({cleared:!0})}catch(t){m(t),process.exit(1)}}},cu={command:"output",describe:"Configure output settings (dump, field filtering)",builder:e=>e.command(By).command(Gy).command(jy).demandCommand(1),handler:S};var Hy=[$c,Hc,iu,su],uu=[Bc,cu,Gc];function zy(e){return e.command.split(" ")[0]}var an=new Set(uu.map(zy));function Jy(){return async e=>{let t=e._?e._.map(String):[],o=t[0],r=e.setDumpDir,n=e.setPick;if((r!==void 0||n!==void 0)&&o&&!an.has(o)){let u=t.join("."),p={...r!==void 0?{dumpDir:r}:{},...n!==void 0?{pick:n}:{}};await G({output:{commands:{[u]:p}}})}let i=o&&!an.has(o),s=await B(),c=i?cn(s?.output,t,{dumpDir:e.dumpDir??r,pick:e.pick??n}):{dumpDir:void 0,pick:void 0};Vc({dumpDir:c.dumpDir,pick:e.pickAll?void 0:c.pick,commandPath:t})}}async function Yy(){try{await qy($y(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([jc(an),Jy()],!0).command(uu).command(Hy).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)}}Yy();
|
package/cli/package.json
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/cli",
|
|
3
|
-
"version": "13.10.
|
|
3
|
+
"version": "13.10.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
|
-
"zoho-cli": "
|
|
6
|
+
"zoho-cli": "index.js"
|
|
7
7
|
},
|
|
8
8
|
"peerDependencies": {
|
|
9
|
-
"@dereekb/nestjs": "13.10.
|
|
10
|
-
"@dereekb/rxjs": "13.10.
|
|
11
|
-
"@dereekb/util": "13.10.
|
|
12
|
-
"@dereekb/zoho": "13.10.
|
|
13
|
-
"@dereekb/zoho/nestjs": "13.10.
|
|
9
|
+
"@dereekb/nestjs": "13.10.1",
|
|
10
|
+
"@dereekb/rxjs": "13.10.1",
|
|
11
|
+
"@dereekb/util": "13.10.1",
|
|
12
|
+
"@dereekb/zoho": "13.10.1",
|
|
13
|
+
"@dereekb/zoho/nestjs": "13.10.1",
|
|
14
14
|
"yargs": "^18.0.0"
|
|
15
15
|
},
|
|
16
16
|
"devDependencies": {
|
|
17
17
|
"@types/yargs": "^17.0.35",
|
|
18
|
-
"date-fns": "^4.
|
|
18
|
+
"date-fns": "^4.1.0"
|
|
19
19
|
}
|
|
20
20
|
}
|
package/index.cjs.js
CHANGED
|
@@ -409,6 +409,7 @@ function _inherits$5(subClass, superClass) {
|
|
|
409
409
|
if (superClass) _set_prototype_of$5(subClass, superClass);
|
|
410
410
|
}
|
|
411
411
|
function _instanceof$6(left, right) {
|
|
412
|
+
"@swc/helpers - instanceof";
|
|
412
413
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
413
414
|
return !!right[Symbol.hasInstance](left);
|
|
414
415
|
} else {
|
|
@@ -3516,6 +3517,7 @@ function _define_property$j(obj, key, value) {
|
|
|
3516
3517
|
return obj;
|
|
3517
3518
|
}
|
|
3518
3519
|
function _instanceof$5(left, right) {
|
|
3520
|
+
"@swc/helpers - instanceof";
|
|
3519
3521
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
3520
3522
|
return !!right[Symbol.hasInstance](left);
|
|
3521
3523
|
} else {
|
|
@@ -4278,6 +4280,7 @@ function _inherits(subClass, superClass) {
|
|
|
4278
4280
|
if (superClass) _set_prototype_of(subClass, superClass);
|
|
4279
4281
|
}
|
|
4280
4282
|
function _instanceof$4(left, right) {
|
|
4283
|
+
"@swc/helpers - instanceof";
|
|
4281
4284
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
4282
4285
|
return !!right[Symbol.hasInstance](left);
|
|
4283
4286
|
} else {
|
|
@@ -5286,6 +5289,7 @@ function _define_property$f(obj, key, value) {
|
|
|
5286
5289
|
return obj;
|
|
5287
5290
|
}
|
|
5288
5291
|
function _instanceof$3(left, right) {
|
|
5292
|
+
"@swc/helpers - instanceof";
|
|
5289
5293
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
5290
5294
|
return !!right[Symbol.hasInstance](left);
|
|
5291
5295
|
} else {
|
|
@@ -5540,6 +5544,7 @@ function _define_property$e(obj, key, value) {
|
|
|
5540
5544
|
return obj;
|
|
5541
5545
|
}
|
|
5542
5546
|
function _instanceof$2(left, right) {
|
|
5547
|
+
"@swc/helpers - instanceof";
|
|
5543
5548
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
5544
5549
|
return !!right[Symbol.hasInstance](left);
|
|
5545
5550
|
} else {
|
|
@@ -6581,6 +6586,7 @@ function _define_property$b(obj, key, value) {
|
|
|
6581
6586
|
return obj;
|
|
6582
6587
|
}
|
|
6583
6588
|
function _instanceof$1(left, right) {
|
|
6589
|
+
"@swc/helpers - instanceof";
|
|
6584
6590
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
6585
6591
|
return !!right[Symbol.hasInstance](left);
|
|
6586
6592
|
} else {
|
|
@@ -7110,11 +7116,11 @@ function _object_spread_props$a(target, source) {
|
|
|
7110
7116
|
var retryAfterHeader = headers.get(ZOHO_DESK_RETRY_AFTER_HEADER);
|
|
7111
7117
|
if (retryAfterHeader != null) {
|
|
7112
7118
|
var retryAfterSeconds = Number(retryAfterHeader);
|
|
7113
|
-
if (!isNaN(retryAfterSeconds)) {
|
|
7119
|
+
if (!Number.isNaN(retryAfterSeconds)) {
|
|
7114
7120
|
resetAt = new Date(Date.now() + retryAfterSeconds * util.MS_IN_SECOND);
|
|
7115
7121
|
}
|
|
7116
7122
|
}
|
|
7117
|
-
if (!isNaN(remaining)) {
|
|
7123
|
+
if (!Number.isNaN(remaining)) {
|
|
7118
7124
|
result = {
|
|
7119
7125
|
remaining: remaining,
|
|
7120
7126
|
resetAt: resetAt
|
|
@@ -7183,6 +7189,7 @@ function _define_property$9(obj, key, value) {
|
|
|
7183
7189
|
return obj;
|
|
7184
7190
|
}
|
|
7185
7191
|
function _instanceof(left, right) {
|
|
7192
|
+
"@swc/helpers - instanceof";
|
|
7186
7193
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
7187
7194
|
return !!right[Symbol.hasInstance](left);
|
|
7188
7195
|
} else {
|
|
@@ -7671,7 +7678,8 @@ function _object_without_properties_loose$7(source, excluded) {
|
|
|
7671
7678
|
}
|
|
7672
7679
|
]);
|
|
7673
7680
|
var queryString = params.toString();
|
|
7674
|
-
|
|
7681
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
7682
|
+
return context.fetchJson("/tickets/".concat(ticketId).concat(querySuffix), zohoDeskApiFetchJsonInput('GET'));
|
|
7675
7683
|
};
|
|
7676
7684
|
}
|
|
7677
7685
|
/**
|
|
@@ -7963,7 +7971,8 @@ function zohoDeskContactApiFetchJsonInput(method) {
|
|
|
7963
7971
|
}
|
|
7964
7972
|
]);
|
|
7965
7973
|
var queryString = params.toString();
|
|
7966
|
-
|
|
7974
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
7975
|
+
return context.fetchJson("/contacts/".concat(contactId).concat(querySuffix), zohoDeskContactApiFetchJsonInput('GET'));
|
|
7967
7976
|
};
|
|
7968
7977
|
}
|
|
7969
7978
|
/**
|
|
@@ -8390,7 +8399,8 @@ function joinCommentInclude(include) {
|
|
|
8390
8399
|
}
|
|
8391
8400
|
]);
|
|
8392
8401
|
var queryString = params.toString();
|
|
8393
|
-
|
|
8402
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
8403
|
+
return context.fetchJson("/tickets/".concat(ticketId, "/comments/").concat(commentId).concat(querySuffix), zohoDeskCommentApiFetchJsonInput('GET'));
|
|
8394
8404
|
};
|
|
8395
8405
|
}
|
|
8396
8406
|
/**
|
|
@@ -8659,7 +8669,8 @@ function joinThreadInclude(include) {
|
|
|
8659
8669
|
}
|
|
8660
8670
|
]);
|
|
8661
8671
|
var queryString = params.toString();
|
|
8662
|
-
|
|
8672
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
8673
|
+
return context.fetchJson("/tickets/".concat(ticketId, "/threads/").concat(threadId).concat(querySuffix), zohoDeskThreadApiFetchJsonInput('GET'));
|
|
8663
8674
|
};
|
|
8664
8675
|
}
|
|
8665
8676
|
/**
|
|
@@ -8936,7 +8947,8 @@ function joinAgentInclude(include) {
|
|
|
8936
8947
|
}
|
|
8937
8948
|
]);
|
|
8938
8949
|
var queryString = params.toString();
|
|
8939
|
-
|
|
8950
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
8951
|
+
return context.fetchJson("/agents/".concat(agentId).concat(querySuffix), zohoDeskAgentApiFetchJsonInput('GET'));
|
|
8940
8952
|
};
|
|
8941
8953
|
}
|
|
8942
8954
|
/**
|
|
@@ -9340,7 +9352,7 @@ function _ts_generator(thisArg, body) {
|
|
|
9340
9352
|
return _ts_generator(this, function(_state) {
|
|
9341
9353
|
switch(_state.label){
|
|
9342
9354
|
case 0:
|
|
9343
|
-
createdAt =
|
|
9355
|
+
createdAt = Date.now();
|
|
9344
9356
|
return [
|
|
9345
9357
|
4,
|
|
9346
9358
|
zohoAccountsAccessToken(accountsContext)()
|
|
@@ -9445,7 +9457,7 @@ function _ts_generator(thisArg, body) {
|
|
|
9445
9457
|
case 2:
|
|
9446
9458
|
// check expiration
|
|
9447
9459
|
if (currentToken != null) {
|
|
9448
|
-
isExpired =
|
|
9460
|
+
isExpired = Date.now() + tokenExpirationBuffer >= currentToken.expiresAt.getTime();
|
|
9449
9461
|
if (isExpired) {
|
|
9450
9462
|
currentToken = null;
|
|
9451
9463
|
}
|
package/index.esm.js
CHANGED
|
@@ -407,6 +407,7 @@ function _inherits$5(subClass, superClass) {
|
|
|
407
407
|
if (superClass) _set_prototype_of$5(subClass, superClass);
|
|
408
408
|
}
|
|
409
409
|
function _instanceof$6(left, right) {
|
|
410
|
+
"@swc/helpers - instanceof";
|
|
410
411
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
411
412
|
return !!right[Symbol.hasInstance](left);
|
|
412
413
|
} else {
|
|
@@ -3514,6 +3515,7 @@ function _define_property$j(obj, key, value) {
|
|
|
3514
3515
|
return obj;
|
|
3515
3516
|
}
|
|
3516
3517
|
function _instanceof$5(left, right) {
|
|
3518
|
+
"@swc/helpers - instanceof";
|
|
3517
3519
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
3518
3520
|
return !!right[Symbol.hasInstance](left);
|
|
3519
3521
|
} else {
|
|
@@ -4276,6 +4278,7 @@ function _inherits(subClass, superClass) {
|
|
|
4276
4278
|
if (superClass) _set_prototype_of(subClass, superClass);
|
|
4277
4279
|
}
|
|
4278
4280
|
function _instanceof$4(left, right) {
|
|
4281
|
+
"@swc/helpers - instanceof";
|
|
4279
4282
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
4280
4283
|
return !!right[Symbol.hasInstance](left);
|
|
4281
4284
|
} else {
|
|
@@ -5284,6 +5287,7 @@ function _define_property$f(obj, key, value) {
|
|
|
5284
5287
|
return obj;
|
|
5285
5288
|
}
|
|
5286
5289
|
function _instanceof$3(left, right) {
|
|
5290
|
+
"@swc/helpers - instanceof";
|
|
5287
5291
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
5288
5292
|
return !!right[Symbol.hasInstance](left);
|
|
5289
5293
|
} else {
|
|
@@ -5538,6 +5542,7 @@ function _define_property$e(obj, key, value) {
|
|
|
5538
5542
|
return obj;
|
|
5539
5543
|
}
|
|
5540
5544
|
function _instanceof$2(left, right) {
|
|
5545
|
+
"@swc/helpers - instanceof";
|
|
5541
5546
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
5542
5547
|
return !!right[Symbol.hasInstance](left);
|
|
5543
5548
|
} else {
|
|
@@ -6579,6 +6584,7 @@ function _define_property$b(obj, key, value) {
|
|
|
6579
6584
|
return obj;
|
|
6580
6585
|
}
|
|
6581
6586
|
function _instanceof$1(left, right) {
|
|
6587
|
+
"@swc/helpers - instanceof";
|
|
6582
6588
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
6583
6589
|
return !!right[Symbol.hasInstance](left);
|
|
6584
6590
|
} else {
|
|
@@ -7108,11 +7114,11 @@ function _object_spread_props$a(target, source) {
|
|
|
7108
7114
|
var retryAfterHeader = headers.get(ZOHO_DESK_RETRY_AFTER_HEADER);
|
|
7109
7115
|
if (retryAfterHeader != null) {
|
|
7110
7116
|
var retryAfterSeconds = Number(retryAfterHeader);
|
|
7111
|
-
if (!isNaN(retryAfterSeconds)) {
|
|
7117
|
+
if (!Number.isNaN(retryAfterSeconds)) {
|
|
7112
7118
|
resetAt = new Date(Date.now() + retryAfterSeconds * MS_IN_SECOND);
|
|
7113
7119
|
}
|
|
7114
7120
|
}
|
|
7115
|
-
if (!isNaN(remaining)) {
|
|
7121
|
+
if (!Number.isNaN(remaining)) {
|
|
7116
7122
|
result = {
|
|
7117
7123
|
remaining: remaining,
|
|
7118
7124
|
resetAt: resetAt
|
|
@@ -7181,6 +7187,7 @@ function _define_property$9(obj, key, value) {
|
|
|
7181
7187
|
return obj;
|
|
7182
7188
|
}
|
|
7183
7189
|
function _instanceof(left, right) {
|
|
7190
|
+
"@swc/helpers - instanceof";
|
|
7184
7191
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
7185
7192
|
return !!right[Symbol.hasInstance](left);
|
|
7186
7193
|
} else {
|
|
@@ -7669,7 +7676,8 @@ function _object_without_properties_loose$7(source, excluded) {
|
|
|
7669
7676
|
}
|
|
7670
7677
|
]);
|
|
7671
7678
|
var queryString = params.toString();
|
|
7672
|
-
|
|
7679
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
7680
|
+
return context.fetchJson("/tickets/".concat(ticketId).concat(querySuffix), zohoDeskApiFetchJsonInput('GET'));
|
|
7673
7681
|
};
|
|
7674
7682
|
}
|
|
7675
7683
|
/**
|
|
@@ -7961,7 +7969,8 @@ function zohoDeskContactApiFetchJsonInput(method) {
|
|
|
7961
7969
|
}
|
|
7962
7970
|
]);
|
|
7963
7971
|
var queryString = params.toString();
|
|
7964
|
-
|
|
7972
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
7973
|
+
return context.fetchJson("/contacts/".concat(contactId).concat(querySuffix), zohoDeskContactApiFetchJsonInput('GET'));
|
|
7965
7974
|
};
|
|
7966
7975
|
}
|
|
7967
7976
|
/**
|
|
@@ -8388,7 +8397,8 @@ function joinCommentInclude(include) {
|
|
|
8388
8397
|
}
|
|
8389
8398
|
]);
|
|
8390
8399
|
var queryString = params.toString();
|
|
8391
|
-
|
|
8400
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
8401
|
+
return context.fetchJson("/tickets/".concat(ticketId, "/comments/").concat(commentId).concat(querySuffix), zohoDeskCommentApiFetchJsonInput('GET'));
|
|
8392
8402
|
};
|
|
8393
8403
|
}
|
|
8394
8404
|
/**
|
|
@@ -8657,7 +8667,8 @@ function joinThreadInclude(include) {
|
|
|
8657
8667
|
}
|
|
8658
8668
|
]);
|
|
8659
8669
|
var queryString = params.toString();
|
|
8660
|
-
|
|
8670
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
8671
|
+
return context.fetchJson("/tickets/".concat(ticketId, "/threads/").concat(threadId).concat(querySuffix), zohoDeskThreadApiFetchJsonInput('GET'));
|
|
8661
8672
|
};
|
|
8662
8673
|
}
|
|
8663
8674
|
/**
|
|
@@ -8934,7 +8945,8 @@ function joinAgentInclude(include) {
|
|
|
8934
8945
|
}
|
|
8935
8946
|
]);
|
|
8936
8947
|
var queryString = params.toString();
|
|
8937
|
-
|
|
8948
|
+
var querySuffix = queryString ? '?' + queryString : '';
|
|
8949
|
+
return context.fetchJson("/agents/".concat(agentId).concat(querySuffix), zohoDeskAgentApiFetchJsonInput('GET'));
|
|
8938
8950
|
};
|
|
8939
8951
|
}
|
|
8940
8952
|
/**
|
|
@@ -9338,7 +9350,7 @@ function _ts_generator(thisArg, body) {
|
|
|
9338
9350
|
return _ts_generator(this, function(_state) {
|
|
9339
9351
|
switch(_state.label){
|
|
9340
9352
|
case 0:
|
|
9341
|
-
createdAt =
|
|
9353
|
+
createdAt = Date.now();
|
|
9342
9354
|
return [
|
|
9343
9355
|
4,
|
|
9344
9356
|
zohoAccountsAccessToken(accountsContext)()
|
|
@@ -9443,7 +9455,7 @@ function _ts_generator(thisArg, body) {
|
|
|
9443
9455
|
case 2:
|
|
9444
9456
|
// check expiration
|
|
9445
9457
|
if (currentToken != null) {
|
|
9446
|
-
isExpired =
|
|
9458
|
+
isExpired = Date.now() + tokenExpirationBuffer >= currentToken.expiresAt.getTime();
|
|
9447
9459
|
if (isExpired) {
|
|
9448
9460
|
currentToken = null;
|
|
9449
9461
|
}
|
package/nestjs/index.cjs.js
CHANGED
|
@@ -607,7 +607,7 @@ var DEFAULT_FILE_ZOHO_ACCOUNTS_ACCESS_TOKEN_CACHE_SERVICE_PATH = '.tmp/zoho-acce
|
|
|
607
607
|
return _ts_generator$3(this, function(_state) {
|
|
608
608
|
switch(_state.label){
|
|
609
609
|
case 0:
|
|
610
|
-
if (!loadedTokens) return [
|
|
610
|
+
if (!(loadedTokens !== null && loadedTokens !== void 0)) return [
|
|
611
611
|
3,
|
|
612
612
|
1
|
|
613
613
|
];
|
|
@@ -622,12 +622,12 @@ var DEFAULT_FILE_ZOHO_ACCOUNTS_ACCESS_TOKEN_CACHE_SERVICE_PATH = '.tmp/zoho-acce
|
|
|
622
622
|
readTokenFile()
|
|
623
623
|
];
|
|
624
624
|
case 2:
|
|
625
|
-
_tmp =
|
|
625
|
+
_tmp = _state.sent();
|
|
626
626
|
_state.label = 3;
|
|
627
627
|
case 3:
|
|
628
628
|
return [
|
|
629
629
|
2,
|
|
630
|
-
_tmp
|
|
630
|
+
(_ref = _tmp) !== null && _ref !== void 0 ? _ref : {}
|
|
631
631
|
];
|
|
632
632
|
}
|
|
633
633
|
});
|
package/nestjs/index.esm.js
CHANGED
|
@@ -605,7 +605,7 @@ var DEFAULT_FILE_ZOHO_ACCOUNTS_ACCESS_TOKEN_CACHE_SERVICE_PATH = '.tmp/zoho-acce
|
|
|
605
605
|
return _ts_generator$3(this, function(_state) {
|
|
606
606
|
switch(_state.label){
|
|
607
607
|
case 0:
|
|
608
|
-
if (!loadedTokens) return [
|
|
608
|
+
if (!(loadedTokens !== null && loadedTokens !== void 0)) return [
|
|
609
609
|
3,
|
|
610
610
|
1
|
|
611
611
|
];
|
|
@@ -620,12 +620,12 @@ var DEFAULT_FILE_ZOHO_ACCOUNTS_ACCESS_TOKEN_CACHE_SERVICE_PATH = '.tmp/zoho-acce
|
|
|
620
620
|
readTokenFile()
|
|
621
621
|
];
|
|
622
622
|
case 2:
|
|
623
|
-
_tmp =
|
|
623
|
+
_tmp = _state.sent();
|
|
624
624
|
_state.label = 3;
|
|
625
625
|
case 3:
|
|
626
626
|
return [
|
|
627
627
|
2,
|
|
628
|
-
_tmp
|
|
628
|
+
(_ref = _tmp) !== null && _ref !== void 0 ? _ref : {}
|
|
629
629
|
];
|
|
630
630
|
}
|
|
631
631
|
});
|
package/nestjs/package.json
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho/nestjs",
|
|
3
|
-
"version": "13.10.
|
|
3
|
+
"version": "13.10.1",
|
|
4
4
|
"peerDependencies": {
|
|
5
|
-
"@dereekb/nestjs": "13.10.
|
|
6
|
-
"@dereekb/rxjs": "13.10.
|
|
7
|
-
"@dereekb/util": "13.10.
|
|
8
|
-
"@dereekb/zoho": "13.10.
|
|
9
|
-
"@nestjs/common": "^11.1.
|
|
5
|
+
"@dereekb/nestjs": "13.10.1",
|
|
6
|
+
"@dereekb/rxjs": "13.10.1",
|
|
7
|
+
"@dereekb/util": "13.10.1",
|
|
8
|
+
"@dereekb/zoho": "13.10.1",
|
|
9
|
+
"@nestjs/common": "^11.1.19",
|
|
10
10
|
"@nestjs/config": "^4.0.4",
|
|
11
|
-
"express": "^5.
|
|
11
|
+
"express": "^5.2.1"
|
|
12
12
|
},
|
|
13
13
|
"devDependencies": {
|
|
14
|
-
"@nestjs/testing": "^11.1.
|
|
15
|
-
"date-fns": "^4.
|
|
14
|
+
"@nestjs/testing": "^11.1.19",
|
|
15
|
+
"date-fns": "^4.1.0"
|
|
16
16
|
},
|
|
17
17
|
"exports": {
|
|
18
18
|
"./package.json": "./package.json",
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dereekb/zoho",
|
|
3
|
-
"version": "13.10.
|
|
3
|
+
"version": "13.10.1",
|
|
4
4
|
"bin": {
|
|
5
|
-
"zoho-cli": "
|
|
5
|
+
"zoho-cli": "cli/index.js"
|
|
6
6
|
},
|
|
7
7
|
"exports": {
|
|
8
8
|
"./nestjs": {
|
|
@@ -23,18 +23,18 @@
|
|
|
23
23
|
}
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
|
-
"@dereekb/nestjs": "13.10.
|
|
27
|
-
"@dereekb/rxjs": "13.10.
|
|
28
|
-
"@dereekb/util": "13.10.
|
|
29
|
-
"@nestjs/common": "^11.1.
|
|
26
|
+
"@dereekb/nestjs": "13.10.1",
|
|
27
|
+
"@dereekb/rxjs": "13.10.1",
|
|
28
|
+
"@dereekb/util": "13.10.1",
|
|
29
|
+
"@nestjs/common": "^11.1.19",
|
|
30
30
|
"@nestjs/config": "^4.0.4",
|
|
31
|
-
"express": "^5.
|
|
32
|
-
"make-error": "^1.3.
|
|
31
|
+
"express": "^5.2.1",
|
|
32
|
+
"make-error": "^1.3.6",
|
|
33
33
|
"yargs": "^18.0.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
-
"@nestjs/testing": "^11.1.
|
|
37
|
-
"date-fns": "^4.
|
|
36
|
+
"@nestjs/testing": "^11.1.19",
|
|
37
|
+
"date-fns": "^4.1.0"
|
|
38
38
|
},
|
|
39
39
|
"module": "./index.esm.js",
|
|
40
40
|
"main": "./index.cjs.js",
|
package/src/lib/crm/crm.d.ts
CHANGED
|
@@ -203,7 +203,7 @@ export interface ZohoCrmRecordEmailMetadata {
|
|
|
203
203
|
*/
|
|
204
204
|
status: ZohoCrmRecordEmailMetadataStatus[];
|
|
205
205
|
}
|
|
206
|
-
export type ZohoCrmRecordEmailMetadataStatusType = 'sent' | string;
|
|
206
|
+
export type ZohoCrmRecordEmailMetadataStatusType = 'sent' | (string & {});
|
|
207
207
|
export interface ZohoCrmRecordEmailMetadataStatus {
|
|
208
208
|
type: ZohoCrmRecordEmailMetadataStatusType;
|
|
209
209
|
}
|
|
@@ -7,7 +7,7 @@ export type ZohoDeskAgentStatus = 'ACTIVE' | 'DISABLED';
|
|
|
7
7
|
/**
|
|
8
8
|
* Agent role permission type in Zoho Desk.
|
|
9
9
|
*/
|
|
10
|
-
export type ZohoDeskAgentRolePermissionType = 'Light' | 'AgentPublic' | 'Custom' | 'AgentPersonal' | 'Admin' | string;
|
|
10
|
+
export type ZohoDeskAgentRolePermissionType = 'Light' | 'AgentPublic' | 'Custom' | 'AgentPersonal' | 'Admin' | (string & {});
|
|
11
11
|
/**
|
|
12
12
|
* Related entities that can be expanded when fetching agents.
|
|
13
13
|
*/
|
|
@@ -10,13 +10,13 @@ export type ZohoDeskTicketStatusType = 'Open' | 'Closed' | 'On Hold';
|
|
|
10
10
|
*
|
|
11
11
|
* Known values include Low, Medium, High, and Urgent. Custom priorities may also be defined.
|
|
12
12
|
*/
|
|
13
|
-
export type ZohoDeskTicketPriority = 'Low' | 'Medium' | 'High' | 'Urgent' | string;
|
|
13
|
+
export type ZohoDeskTicketPriority = 'Low' | 'Medium' | 'High' | 'Urgent' | (string & {});
|
|
14
14
|
/**
|
|
15
15
|
* Communication channel through which a Zoho Desk ticket was created.
|
|
16
16
|
*
|
|
17
17
|
* Known values include Phone, Email, Social, Web, Chat, and Forums. Custom channels may also be present.
|
|
18
18
|
*/
|
|
19
|
-
export type ZohoDeskTicketChannel = 'Phone' | 'Email' | 'Social' | 'Web' | 'Chat' | 'Forums' | string;
|
|
19
|
+
export type ZohoDeskTicketChannel = 'Phone' | 'Email' | 'Social' | 'Web' | 'Chat' | 'Forums' | (string & {});
|
|
20
20
|
/**
|
|
21
21
|
* Fields by which Zoho Desk ticket lists can be sorted.
|
|
22
22
|
*/
|
|
@@ -213,7 +213,7 @@ export interface ZohoDeskTicketTimer {
|
|
|
213
213
|
/**
|
|
214
214
|
* Communication channel for a thread.
|
|
215
215
|
*/
|
|
216
|
-
export type ZohoDeskThreadChannel = 'EMAIL' | 'PHONE' | 'WEB' | 'CUSTOMERPORTAL' | 'FORUMS' | 'FACEBOOK' | 'TWITTER' | 'TWITTER_DM' | 'ONLINE_CHAT' | 'OFFLINE_CHAT' | 'FEEDBACK' | 'FEEDBACK_WIDGET' | string;
|
|
216
|
+
export type ZohoDeskThreadChannel = 'EMAIL' | 'PHONE' | 'WEB' | 'CUSTOMERPORTAL' | 'FORUMS' | 'FACEBOOK' | 'TWITTER' | 'TWITTER_DM' | 'ONLINE_CHAT' | 'OFFLINE_CHAT' | 'FEEDBACK' | 'FEEDBACK_WIDGET' | (string & {});
|
|
217
217
|
/**
|
|
218
218
|
* Direction of a thread message relative to the support team.
|
|
219
219
|
*/
|
|
@@ -183,7 +183,7 @@ export interface ZohoRecruitRecordEmailMetadata {
|
|
|
183
183
|
*/
|
|
184
184
|
status: ZohoRecruitRecordEmailMetadataStatus[];
|
|
185
185
|
}
|
|
186
|
-
export type ZohoRecruitRecordEmailMetadataStatusType = 'sent' | string;
|
|
186
|
+
export type ZohoRecruitRecordEmailMetadataStatusType = 'sent' | (string & {});
|
|
187
187
|
export interface ZohoRecruitRecordEmailMetadataStatus {
|
|
188
188
|
type: ZohoRecruitRecordEmailMetadataStatusType;
|
|
189
189
|
}
|
|
@@ -27,7 +27,7 @@ export interface ZohoSignPageFilter {
|
|
|
27
27
|
/**
|
|
28
28
|
* Known sortable column names for Zoho Sign list endpoints, with a `string` fallback for custom columns.
|
|
29
29
|
*/
|
|
30
|
-
export type ZohoSignSortColumn = 'request_name' | 'folder_name' | 'owner_full_name' | 'recipient_email' | 'form_name' | 'created_time' | string;
|
|
30
|
+
export type ZohoSignSortColumn = 'request_name' | 'folder_name' | 'owner_full_name' | 'recipient_email' | 'form_name' | 'created_time' | (string & {});
|
|
31
31
|
/**
|
|
32
32
|
* Sort direction for Zoho Sign list queries.
|
|
33
33
|
*/
|
package/src/lib/sign/sign.d.ts
CHANGED
|
@@ -40,7 +40,7 @@ export type ZohoSignFieldTypeId = string;
|
|
|
40
40
|
/**
|
|
41
41
|
* Status of a Zoho Sign request.
|
|
42
42
|
*/
|
|
43
|
-
export type ZohoSignRequestStatus = 'inprogress' | 'completed' | 'recalled' | 'declined' | 'expired' | string;
|
|
43
|
+
export type ZohoSignRequestStatus = 'inprogress' | 'completed' | 'recalled' | 'declined' | 'expired' | (string & {});
|
|
44
44
|
/**
|
|
45
45
|
* Recipient action type in Zoho Sign.
|
|
46
46
|
*/
|
|
@@ -52,7 +52,7 @@ export type ZohoSignVerificationType = 'EMAIL' | 'SMS' | 'OFFLINE';
|
|
|
52
52
|
/**
|
|
53
53
|
* Field type name for document fields.
|
|
54
54
|
*/
|
|
55
|
-
export type ZohoSignFieldTypeName = 'Checkbox' | 'Radiogroup' | 'Signature' | 'Initial' | 'Textfield' | 'Email' | 'Date' | 'Name' | 'Company' | 'Jobtitle' | 'CustomDate' | 'Dropdown' | 'Attachment' | 'Checkout' | string;
|
|
55
|
+
export type ZohoSignFieldTypeName = 'Checkbox' | 'Radiogroup' | 'Signature' | 'Initial' | 'Textfield' | 'Email' | 'Date' | 'Name' | 'Company' | 'Jobtitle' | 'CustomDate' | 'Dropdown' | 'Attachment' | 'Checkout' | (string & {});
|
|
56
56
|
/**
|
|
57
57
|
* Name format for name fields.
|
|
58
58
|
*/
|
|
@@ -60,7 +60,7 @@ export type ZohoSignNameFormat = 'FIRST_NAME' | 'LAST_NAME' | 'FULL_NAME';
|
|
|
60
60
|
/**
|
|
61
61
|
* Field category classification.
|
|
62
62
|
*/
|
|
63
|
-
export type ZohoSignFieldCategory = 'textfield' | 'image' | 'datefield' | string;
|
|
63
|
+
export type ZohoSignFieldCategory = 'textfield' | 'image' | 'datefield' | (string & {});
|
|
64
64
|
/**
|
|
65
65
|
* Definition of a field type available in Zoho Sign.
|
|
66
66
|
*/
|