jaz-clio 9.4.0 → 9.4.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/assets/skills/api/SKILL.md +1 -1
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-kit/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +1 -1
- package/package.json +1 -1
package/cli.mjs
CHANGED
|
@@ -659,7 +659,7 @@ actual: `+e._bytesWritten),cJ.prototype._finish.call(e)}});var Hfe=I(($7r,Wtt)=>
|
|
|
659
659
|
Unsupported type: `+e.type,"ENOTSUP");e._finish()})};Jc.prototype._stat=function(e){var t=this,r=t.props,n=r.follow?"stat":"lstat",i=t._proxy||t;e?o(null,e):zc[n](t._path,o);function o(s,a){if(t.filter&&!t.filter.call(i,i,a)){t._aborted=!0,t.emit("end"),t.emit("close");return}if(s||!a)return zfe(t);t._old=a;var c=Xtt(a);if(c!==t.type||t.type==="File"&&a.nlink>1)return jyr(t._path,function(u){if(u)return t.error(u);t._old=null,zfe(t)});zfe(t)}};function zfe(e){Yyr(UB.dirname(e._path),Jc.dirmode,function(t,r){return t?e.error(t):(e._madeDir=r,e._create())})}function trt(e,t,r,n,i){var o=t.mode,s=t.follow||e.type!=="SymbolicLink"?"chmod":"lchmod";if(!zc[s]||typeof o!="number")return i();var a=r.mode&parseInt("0777",8);if(o=o&parseInt("0777",8),o===a)return i();zc[s](n,o,i)}function rrt(e,t,r,n,i){if(process.platform==="win32"||!process.getuid||process.getuid()!==0||typeof t.uid!="number"&&typeof t.gid!="number"||r.uid===t.uid&&r.gid===t.gid)return i();var o=e.props.follow||e.type!=="SymbolicLink"?"chown":"lchown";if(!zc[o])return i();typeof t.uid!="number"&&(t.uid=r.uid),typeof t.gid!="number"&&(t.gid=r.gid),zc[o](n,t.uid,t.gid,i)}function nrt(e,t,r,n,i){if(!zc.utimes||process.platform==="win32")return i();var o=t.follow||e.type!=="SymbolicLink"?"utimes":"lutimes";if(o==="lutimes"&&!zc[o]&&(o="utimes"),!zc[o])return i();var s=r.atime,a=r.mtime,c=t.atime,u=t.mtime;if(c===void 0&&(c=s),u===void 0&&(u=a),Ktt(c)||(c=new Date(c)),Ktt(u)||(c=new Date(u)),c.getTime()===s.getTime()&&u.getTime()===a.getTime())return i();zc[o](n,c,u,i)}Jc.prototype._finish=function(){var e=this;if(e._finishing)return;e._finishing=!0;var t=0,r=null,n=!1;if(e._old)e._old.atime=new Date(0),e._old.mtime=new Date(0),o(e._old);else{var i=e.props.follow?"stat":"lstat";zc[i](e._path,function(a,c){if(a)if(a.code==="ENOENT"&&(e.type==="Link"||e.type==="SymbolicLink")&&process.platform==="win32"){e.ready=!0,e.emit("ready"),e.emit("end"),e.emit("close"),e.end=e._finish=function(){};return}else return e.error(a);o(e._old=c)})}return;function o(a){t+=3,trt(e,e.props,a,e._path,s("chmod")),rrt(e,e.props,a,e._path,s("chown")),nrt(e,e.props,a,e._path,s("utimes"))}function s(a){return function(c){if(r)return;if(c)return c.fstream_finish_call=a,e.error(r=c);if(--t>0||n)return;if(n=!0,e._madeDir)irt(e,e._path,u);else return u();function u(d){if(d)return d.fstream_finish_call="setupMadeDir",e.error(d);e.emit("end"),e.emit("close")}}}};function irt(e,t,r){var n=e._madeDir,i=UB.dirname(t);Vyr(e,i,function(o){if(o)return r(o);if(i===n)return r();irt(e,i,r)})}function Vyr(e,t,r){var n={};Object.keys(e.props).forEach(function(a){n[a]=e.props[a],a==="mode"&&e.type!=="Directory"&&(n[a]=n[a]|parseInt("0111",8))});var i=3,o=null;zc.stat(t,function(a,c){if(a)return r(o=a);trt(e,n,c,t,s),rrt(e,n,c,t,s),nrt(e,n,c,t,s)});function s(a){if(!o){if(a)return r(o=a);if(--i===0)return r()}}}Jc.prototype.pipe=function(){this.error("Can't pipe from writable stream")};Jc.prototype.add=function(){this.error("Can't add to non-Directory type")};Jc.prototype.write=function(){return!0};function Wyr(e){return Object.prototype.toString.call(e)}function Ktt(e){return typeof e=="object"&&Wyr(e)==="[object Date]"}});var Jfe=I(Lr=>{Lr.Abstract=tJ();Lr.Reader=eE();Lr.Writer=Rw();Lr.File={Reader:xfe(),Writer:jfe()};Lr.Dir={Reader:Tfe(),Writer:$fe()};Lr.Link={Reader:Dfe(),Writer:qfe()};Lr.Proxy={Reader:Bfe(),Writer:Hfe()};Lr.Reader.Dir=Lr.DirReader=Lr.Dir.Reader;Lr.Reader.File=Lr.FileReader=Lr.File.Reader;Lr.Reader.Link=Lr.LinkReader=Lr.Link.Reader;Lr.Reader.Proxy=Lr.ProxyReader=Lr.Proxy.Reader;Lr.Writer.Dir=Lr.DirWriter=Lr.Dir.Writer;Lr.Writer.File=Lr.FileWriter=Lr.File.Writer;Lr.Writer.Link=Lr.LinkWriter=Lr.Link.Writer;Lr.Writer.Proxy=Lr.ProxyWriter=Lr.Proxy.Writer;Lr.collect=sJ()});var art=I((Y7r,srt)=>{srt.exports=rEr;var Kyr=eJ(),Zyr=Jfe().Writer,Gfe=H("path"),Xyr=H("stream"),eEr=wfe(),tEr=Fm();function rEr(e){e.path=Gfe.resolve(Gfe.normalize(e.path));var t=new Kyr(e),r=new Xyr.Writable({objectMode:!0});r._write=function(i,o,s){if(i.type=="Directory")return s();var a=Gfe.join(e.path,i.path);if(a.indexOf(e.path)!=0)return s();let c=e.getWriter?e.getWriter({path:a}):Zyr({path:a});i.pipe(c).on("error",s).on("close",s)};var n=eEr(t,r);return t.once("crx-header",function(i){n.crxHeader=i}),t.pipe(r).on("finish",function(){n.emit("close")}),n.promise=function(){return new tEr(function(i,o){n.on("close",i),n.on("error",o)})},n}});var crt=I((H7r,lJ)=>{var mo=(function(e){"use strict";var t=1e7,r=7,n=9007199254740992,i=p(n),o="0123456789abcdefghijklmnopqrstuvwxyz",s=typeof BigInt=="function";function a(v,x,L,j){return typeof v>"u"?a[0]:typeof x<"u"?+x==10&&!L?ae(v):Ve(v,x,L,j):ae(v)}function c(v,x){this.value=v,this.sign=x,this.isSmall=!1}c.prototype=Object.create(a.prototype);function u(v){this.value=v,this.sign=v<0,this.isSmall=!0}u.prototype=Object.create(a.prototype);function d(v){this.value=v}d.prototype=Object.create(a.prototype);function f(v){return-n<v&&v<n}function p(v){return v<1e7?[v]:v<1e14?[v%1e7,Math.floor(v/1e7)]:[v%1e7,Math.floor(v/1e7)%1e7,Math.floor(v/1e14)]}function h(v){m(v);var x=v.length;if(x<4&&V(v,i)<0)switch(x){case 0:return 0;case 1:return v[0];case 2:return v[0]+v[1]*t;default:return v[0]+(v[1]+v[2]*t)*t}return v}function m(v){for(var x=v.length;v[--x]===0;);v.length=x+1}function A(v){for(var x=new Array(v),L=-1;++L<v;)x[L]=0;return x}function g(v){return v>0?Math.floor(v):Math.ceil(v)}function y(v,x){var L=v.length,j=x.length,ie=new Array(L),te=0,se=t,ce,pe;for(pe=0;pe<j;pe++)ce=v[pe]+x[pe]+te,te=ce>=se?1:0,ie[pe]=ce-te*se;for(;pe<L;)ce=v[pe]+te,te=ce===se?1:0,ie[pe++]=ce-te*se;return te>0&&ie.push(te),ie}function b(v,x){return v.length>=x.length?y(v,x):y(x,v)}function E(v,x){var L=v.length,j=new Array(L),ie=t,te,se;for(se=0;se<L;se++)te=v[se]-ie+x,x=Math.floor(te/ie),j[se]=te-x*ie,x+=1;for(;x>0;)j[se++]=x%ie,x=Math.floor(x/ie);return j}c.prototype.add=function(v){var x=ae(v);if(this.sign!==x.sign)return this.subtract(x.negate());var L=this.value,j=x.value;return x.isSmall?new c(E(L,Math.abs(j)),this.sign):new c(b(L,j),this.sign)},c.prototype.plus=c.prototype.add,u.prototype.add=function(v){var x=ae(v),L=this.value;if(L<0!==x.sign)return this.subtract(x.negate());var j=x.value;if(x.isSmall){if(f(L+j))return new u(L+j);j=p(Math.abs(j))}return new c(E(j,Math.abs(L)),L<0)},u.prototype.plus=u.prototype.add,d.prototype.add=function(v){return new d(this.value+ae(v).value)},d.prototype.plus=d.prototype.add;function C(v,x){var L=v.length,j=x.length,ie=new Array(L),te=0,se=t,ce,pe;for(ce=0;ce<j;ce++)pe=v[ce]-te-x[ce],pe<0?(pe+=se,te=1):te=0,ie[ce]=pe;for(ce=j;ce<L;ce++){if(pe=v[ce]-te,pe<0)pe+=se;else{ie[ce++]=pe;break}ie[ce]=pe}for(;ce<L;ce++)ie[ce]=v[ce];return m(ie),ie}function w(v,x,L){var j;return V(v,x)>=0?j=C(v,x):(j=C(x,v),L=!L),j=h(j),typeof j=="number"?(L&&(j=-j),new u(j)):new c(j,L)}function T(v,x,L){var j=v.length,ie=new Array(j),te=-x,se=t,ce,pe;for(ce=0;ce<j;ce++)pe=v[ce]+te,te=Math.floor(pe/se),pe%=se,ie[ce]=pe<0?pe+se:pe;return ie=h(ie),typeof ie=="number"?(L&&(ie=-ie),new u(ie)):new c(ie,L)}c.prototype.subtract=function(v){var x=ae(v);if(this.sign!==x.sign)return this.add(x.negate());var L=this.value,j=x.value;return x.isSmall?T(L,Math.abs(j),this.sign):w(L,j,this.sign)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(v){var x=ae(v),L=this.value;if(L<0!==x.sign)return this.add(x.negate());var j=x.value;return x.isSmall?new u(L-j):T(j,Math.abs(L),L>=0)},u.prototype.minus=u.prototype.subtract,d.prototype.subtract=function(v){return new d(this.value-ae(v).value)},d.prototype.minus=d.prototype.subtract,c.prototype.negate=function(){return new c(this.value,!this.sign)},u.prototype.negate=function(){var v=this.sign,x=new u(-this.value);return x.sign=!v,x},d.prototype.negate=function(){return new d(-this.value)},c.prototype.abs=function(){return new c(this.value,!1)},u.prototype.abs=function(){return new u(Math.abs(this.value))},d.prototype.abs=function(){return new d(this.value>=0?this.value:-this.value)};function R(v,x){var L=v.length,j=x.length,ie=L+j,te=A(ie),se=t,ce,pe,Le,Je,st;for(Le=0;Le<L;++Le){Je=v[Le];for(var Zt=0;Zt<j;++Zt)st=x[Zt],ce=Je*st+te[Le+Zt],pe=Math.floor(ce/se),te[Le+Zt]=ce-pe*se,te[Le+Zt+1]+=pe}return m(te),te}function B(v,x){var L=v.length,j=new Array(L),ie=t,te=0,se,ce;for(ce=0;ce<L;ce++)se=v[ce]*x+te,te=Math.floor(se/ie),j[ce]=se-te*ie;for(;te>0;)j[ce++]=te%ie,te=Math.floor(te/ie);return j}function O(v,x){for(var L=[];x-- >0;)L.push(0);return L.concat(v)}function J(v,x){var L=Math.max(v.length,x.length);if(L<=30)return R(v,x);L=Math.ceil(L/2);var j=v.slice(L),ie=v.slice(0,L),te=x.slice(L),se=x.slice(0,L),ce=J(ie,se),pe=J(j,te),Le=J(b(ie,j),b(se,te)),Je=b(b(ce,O(C(C(Le,ce),pe),L)),O(pe,2*L));return m(Je),Je}function Y(v,x){return-.012*v-.012*x+15e-6*v*x>0}c.prototype.multiply=function(v){var x=ae(v),L=this.value,j=x.value,ie=this.sign!==x.sign,te;if(x.isSmall){if(j===0)return a[0];if(j===1)return this;if(j===-1)return this.negate();if(te=Math.abs(j),te<t)return new c(B(L,te),ie);j=p(te)}return Y(L.length,j.length)?new c(J(L,j),ie):new c(R(L,j),ie)},c.prototype.times=c.prototype.multiply;function S(v,x,L){return v<t?new c(B(x,v),L):new c(R(x,p(v)),L)}u.prototype._multiplyBySmall=function(v){return f(v.value*this.value)?new u(v.value*this.value):S(Math.abs(v.value),p(Math.abs(this.value)),this.sign!==v.sign)},c.prototype._multiplyBySmall=function(v){return v.value===0?a[0]:v.value===1?this:v.value===-1?this.negate():S(Math.abs(v.value),this.value,this.sign!==v.sign)},u.prototype.multiply=function(v){return ae(v)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,d.prototype.multiply=function(v){return new d(this.value*ae(v).value)},d.prototype.times=d.prototype.multiply;function k(v){var x=v.length,L=A(x+x),j=t,ie,te,se,ce,pe;for(se=0;se<x;se++){ce=v[se],te=0-ce*ce;for(var Le=se;Le<x;Le++)pe=v[Le],ie=2*(ce*pe)+L[se+Le]+te,te=Math.floor(ie/j),L[se+Le]=ie-te*j;L[se+x]=te}return m(L),L}c.prototype.square=function(){return new c(k(this.value),!1)},u.prototype.square=function(){var v=this.value*this.value;return f(v)?new u(v):new c(k(p(Math.abs(this.value))),!1)},d.prototype.square=function(v){return new d(this.value*this.value)};function P(v,x){var L=v.length,j=x.length,ie=t,te=A(x.length),se=x[j-1],ce=Math.ceil(ie/(2*se)),pe=B(v,ce),Le=B(x,ce),Je,st,Zt,yn,ti,ro,nl;for(pe.length<=L&&pe.push(0),Le.push(0),se=Le[j-1],st=L-j;st>=0;st--){for(Je=ie-1,pe[st+j]!==se&&(Je=Math.floor((pe[st+j]*ie+pe[st+j-1])/se)),Zt=0,yn=0,ro=Le.length,ti=0;ti<ro;ti++)Zt+=Je*Le[ti],nl=Math.floor(Zt/ie),yn+=pe[st+ti]-(Zt-nl*ie),Zt=nl,yn<0?(pe[st+ti]=yn+ie,yn=-1):(pe[st+ti]=yn,yn=0);for(;yn!==0;){for(Je-=1,Zt=0,ti=0;ti<ro;ti++)Zt+=pe[st+ti]-ie+Le[ti],Zt<0?(pe[st+ti]=Zt+ie,Zt=0):(pe[st+ti]=Zt,Zt=1);yn+=Zt}te[st]=Je}return pe=N(pe,ce)[0],[h(te),h(pe)]}function K(v,x){for(var L=v.length,j=x.length,ie=[],te=[],se=t,ce,pe,Le,Je,st;L;){if(te.unshift(v[--L]),m(te),V(te,x)<0){ie.push(0);continue}pe=te.length,Le=te[pe-1]*se+te[pe-2],Je=x[j-1]*se+x[j-2],pe>j&&(Le=(Le+1)*se),ce=Math.ceil(Le/Je);do{if(st=B(x,ce),V(st,te)<=0)break;ce--}while(ce);ie.push(ce),te=C(te,st)}return ie.reverse(),[h(ie),h(te)]}function N(v,x){var L=v.length,j=A(L),ie=t,te,se,ce,pe;for(ce=0,te=L-1;te>=0;--te)pe=ce*ie+v[te],se=g(pe/x),ce=pe-se*x,j[te]=se|0;return[j,ce|0]}function z(v,x){var L,j=ae(x);if(s)return[new d(v.value/j.value),new d(v.value%j.value)];var ie=v.value,te=j.value,se;if(te===0)throw new Error("Cannot divide by zero");if(v.isSmall)return j.isSmall?[new u(g(ie/te)),new u(ie%te)]:[a[0],v];if(j.isSmall){if(te===1)return[v,a[0]];if(te==-1)return[v.negate(),a[0]];var ce=Math.abs(te);if(ce<t){L=N(ie,ce),se=h(L[0]);var pe=L[1];return v.sign&&(pe=-pe),typeof se=="number"?(v.sign!==j.sign&&(se=-se),[new u(se),new u(pe)]):[new c(se,v.sign!==j.sign),new u(pe)]}te=p(ce)}var Le=V(ie,te);if(Le===-1)return[a[0],v];if(Le===0)return[a[v.sign===j.sign?1:-1],a[0]];ie.length+te.length<=200?L=P(ie,te):L=K(ie,te),se=L[0];var Je=v.sign!==j.sign,st=L[1],Zt=v.sign;return typeof se=="number"?(Je&&(se=-se),se=new u(se)):se=new c(se,Je),typeof st=="number"?(Zt&&(st=-st),st=new u(st)):st=new c(st,Zt),[se,st]}c.prototype.divmod=function(v){var x=z(this,v);return{quotient:x[0],remainder:x[1]}},d.prototype.divmod=u.prototype.divmod=c.prototype.divmod,c.prototype.divide=function(v){return z(this,v)[0]},d.prototype.over=d.prototype.divide=function(v){return new d(this.value/ae(v).value)},u.prototype.over=u.prototype.divide=c.prototype.over=c.prototype.divide,c.prototype.mod=function(v){return z(this,v)[1]},d.prototype.mod=d.prototype.remainder=function(v){return new d(this.value%ae(v).value)},u.prototype.remainder=u.prototype.mod=c.prototype.remainder=c.prototype.mod,c.prototype.pow=function(v){var x=ae(v),L=this.value,j=x.value,ie,te,se;if(j===0)return a[1];if(L===0)return a[0];if(L===1)return a[1];if(L===-1)return x.isEven()?a[1]:a[-1];if(x.sign)return a[0];if(!x.isSmall)throw new Error("The exponent "+x.toString()+" is too large.");if(this.isSmall&&f(ie=Math.pow(L,j)))return new u(g(ie));for(te=this,se=a[1];j&!0&&(se=se.times(te),--j),j!==0;)j/=2,te=te.square();return se},u.prototype.pow=c.prototype.pow,d.prototype.pow=function(v){var x=ae(v),L=this.value,j=x.value,ie=BigInt(0),te=BigInt(1),se=BigInt(2);if(j===ie)return a[1];if(L===ie)return a[0];if(L===te)return a[1];if(L===BigInt(-1))return x.isEven()?a[1]:a[-1];if(x.isNegative())return new d(ie);for(var ce=this,pe=a[1];(j&te)===te&&(pe=pe.times(ce),--j),j!==ie;)j/=se,ce=ce.square();return pe},c.prototype.modPow=function(v,x){if(v=ae(v),x=ae(x),x.isZero())throw new Error("Cannot take modPow with modulus 0");var L=a[1],j=this.mod(x);for(v.isNegative()&&(v=v.multiply(a[-1]),j=j.modInv(x));v.isPositive();){if(j.isZero())return a[0];v.isOdd()&&(L=L.multiply(j).mod(x)),v=v.divide(2),j=j.square().mod(x)}return L},d.prototype.modPow=u.prototype.modPow=c.prototype.modPow;function V(v,x){if(v.length!==x.length)return v.length>x.length?1:-1;for(var L=v.length-1;L>=0;L--)if(v[L]!==x[L])return v[L]>x[L]?1:-1;return 0}c.prototype.compareAbs=function(v){var x=ae(v),L=this.value,j=x.value;return x.isSmall?1:V(L,j)},u.prototype.compareAbs=function(v){var x=ae(v),L=Math.abs(this.value),j=x.value;return x.isSmall?(j=Math.abs(j),L===j?0:L>j?1:-1):-1},d.prototype.compareAbs=function(v){var x=this.value,L=ae(v).value;return x=x>=0?x:-x,L=L>=0?L:-L,x===L?0:x>L?1:-1},c.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),L=this.value,j=x.value;return this.sign!==x.sign?x.sign?1:-1:x.isSmall?this.sign?-1:1:V(L,j)*(this.sign?-1:1)},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),L=this.value,j=x.value;return x.isSmall?L==j?0:L>j?1:-1:L<0!==x.sign?L<0?-1:1:L<0?1:-1},u.prototype.compareTo=u.prototype.compare,d.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=this.value,L=ae(v).value;return x===L?0:x>L?1:-1},d.prototype.compareTo=d.prototype.compare,c.prototype.equals=function(v){return this.compare(v)===0},d.prototype.eq=d.prototype.equals=u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals,c.prototype.notEquals=function(v){return this.compare(v)!==0},d.prototype.neq=d.prototype.notEquals=u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals,c.prototype.greater=function(v){return this.compare(v)>0},d.prototype.gt=d.prototype.greater=u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater,c.prototype.lesser=function(v){return this.compare(v)<0},d.prototype.lt=d.prototype.lesser=u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser,c.prototype.greaterOrEquals=function(v){return this.compare(v)>=0},d.prototype.geq=d.prototype.greaterOrEquals=u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals,c.prototype.lesserOrEquals=function(v){return this.compare(v)<=0},d.prototype.leq=d.prototype.lesserOrEquals=u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals,c.prototype.isEven=function(){return(this.value[0]&1)===0},u.prototype.isEven=function(){return(this.value&1)===0},d.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},c.prototype.isOdd=function(){return(this.value[0]&1)===1},u.prototype.isOdd=function(){return(this.value&1)===1},d.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},c.prototype.isPositive=function(){return!this.sign},u.prototype.isPositive=function(){return this.value>0},d.prototype.isPositive=u.prototype.isPositive,c.prototype.isNegative=function(){return this.sign},u.prototype.isNegative=function(){return this.value<0},d.prototype.isNegative=u.prototype.isNegative,c.prototype.isUnit=function(){return!1},u.prototype.isUnit=function(){return Math.abs(this.value)===1},d.prototype.isUnit=function(){return this.abs().value===BigInt(1)},c.prototype.isZero=function(){return!1},u.prototype.isZero=function(){return this.value===0},d.prototype.isZero=function(){return this.value===BigInt(0)},c.prototype.isDivisibleBy=function(v){var x=ae(v);return x.isZero()?!1:x.isUnit()?!0:x.compareAbs(2)===0?this.isEven():this.mod(x).isZero()},d.prototype.isDivisibleBy=u.prototype.isDivisibleBy=c.prototype.isDivisibleBy;function Z(v){var x=v.abs();if(x.isUnit())return!1;if(x.equals(2)||x.equals(3)||x.equals(5))return!0;if(x.isEven()||x.isDivisibleBy(3)||x.isDivisibleBy(5))return!1;if(x.lesser(49))return!0}function oe(v,x){for(var L=v.prev(),j=L,ie=0,te,se,ce,pe;j.isEven();)j=j.divide(2),ie++;e:for(ce=0;ce<x.length;ce++)if(!v.lesser(x[ce])&&(pe=mo(x[ce]).modPow(j,v),!(pe.isUnit()||pe.equals(L)))){for(te=ie-1;te!=0;te--){if(pe=pe.square().mod(v),pe.isUnit())return!1;if(pe.equals(L))continue e}return!1}return!0}c.prototype.isPrime=function(v){var x=Z(this);if(x!==e)return x;var L=this.abs(),j=L.bitLength();if(j<=64)return oe(L,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var ie=Math.log(2)*j.toJSNumber(),te=Math.ceil(v===!0?2*Math.pow(ie,2):ie),se=[],ce=0;ce<te;ce++)se.push(mo(ce+2));return oe(L,se)},d.prototype.isPrime=u.prototype.isPrime=c.prototype.isPrime,c.prototype.isProbablePrime=function(v,x){var L=Z(this);if(L!==e)return L;for(var j=this.abs(),ie=v===e?5:v,te=[],se=0;se<ie;se++)te.push(mo.randBetween(2,j.minus(2),x));return oe(j,te)},d.prototype.isProbablePrime=u.prototype.isProbablePrime=c.prototype.isProbablePrime,c.prototype.modInv=function(v){for(var x=mo.zero,L=mo.one,j=ae(v),ie=this.abs(),te,se,ce;!ie.isZero();)te=j.divide(ie),se=x,ce=j,x=L,j=ie,L=se.subtract(te.multiply(L)),ie=ce.subtract(te.multiply(ie));if(!j.isUnit())throw new Error(this.toString()+" and "+v.toString()+" are not co-prime");return x.compare(0)===-1&&(x=x.add(v)),this.isNegative()?x.negate():x},d.prototype.modInv=u.prototype.modInv=c.prototype.modInv,c.prototype.next=function(){var v=this.value;return this.sign?T(v,1,this.sign):new c(E(v,1),this.sign)},u.prototype.next=function(){var v=this.value;return v+1<n?new u(v+1):new c(i,!1)},d.prototype.next=function(){return new d(this.value+BigInt(1))},c.prototype.prev=function(){var v=this.value;return this.sign?new c(E(v,1),!0):T(v,1,this.sign)},u.prototype.prev=function(){var v=this.value;return v-1>-n?new u(v-1):new c(i,!0)},d.prototype.prev=function(){return new d(this.value-BigInt(1))};for(var me=[1];2*me[me.length-1]<=t;)me.push(2*me[me.length-1]);var Te=me.length,ve=me[Te-1];function ft(v){return Math.abs(v)<=t}c.prototype.shiftLeft=function(v){var x=ae(v).toJSNumber();if(!ft(x))throw new Error(String(x)+" is too large for shifting.");if(x<0)return this.shiftRight(-x);var L=this;if(L.isZero())return L;for(;x>=Te;)L=L.multiply(ve),x-=Te-1;return L.multiply(me[x])},d.prototype.shiftLeft=u.prototype.shiftLeft=c.prototype.shiftLeft,c.prototype.shiftRight=function(v){var x,L=ae(v).toJSNumber();if(!ft(L))throw new Error(String(L)+" is too large for shifting.");if(L<0)return this.shiftLeft(-L);for(var j=this;L>=Te;){if(j.isZero()||j.isNegative()&&j.isUnit())return j;x=z(j,ve),j=x[1].isNegative()?x[0].prev():x[0],L-=Te-1}return x=z(j,me[L]),x[1].isNegative()?x[0].prev():x[0]},d.prototype.shiftRight=u.prototype.shiftRight=c.prototype.shiftRight;function Be(v,x,L){x=ae(x);for(var j=v.isNegative(),ie=x.isNegative(),te=j?v.not():v,se=ie?x.not():x,ce=0,pe=0,Le=null,Je=null,st=[];!te.isZero()||!se.isZero();)Le=z(te,ve),ce=Le[1].toJSNumber(),j&&(ce=ve-1-ce),Je=z(se,ve),pe=Je[1].toJSNumber(),ie&&(pe=ve-1-pe),te=Le[0],se=Je[0],st.push(L(ce,pe));for(var Zt=L(j?1:0,ie?1:0)!==0?mo(-1):mo(0),yn=st.length-1;yn>=0;yn-=1)Zt=Zt.multiply(ve).add(mo(st[yn]));return Zt}c.prototype.not=function(){return this.negate().prev()},d.prototype.not=u.prototype.not=c.prototype.not,c.prototype.and=function(v){return Be(this,v,function(x,L){return x&L})},d.prototype.and=u.prototype.and=c.prototype.and,c.prototype.or=function(v){return Be(this,v,function(x,L){return x|L})},d.prototype.or=u.prototype.or=c.prototype.or,c.prototype.xor=function(v){return Be(this,v,function(x,L){return x^L})},d.prototype.xor=u.prototype.xor=c.prototype.xor;var Me=1<<30,fe=(t&-t)*(t&-t)|Me;function le(v){var x=v.value,L=typeof x=="number"?x|Me:typeof x=="bigint"?x|BigInt(Me):x[0]+x[1]*t|fe;return L&-L}function we(v,x){if(x.compareTo(v)<=0){var L=we(v,x.square(x)),j=L.p,ie=L.e,te=j.multiply(x);return te.compareTo(v)<=0?{p:te,e:ie*2+1}:{p:j,e:ie*2}}return{p:mo(1),e:0}}c.prototype.bitLength=function(){var v=this;return v.compareTo(mo(0))<0&&(v=v.negate().subtract(mo(1))),v.compareTo(mo(0))===0?mo(0):mo(we(v,mo(2)).e).add(mo(1))},d.prototype.bitLength=u.prototype.bitLength=c.prototype.bitLength;function Fe(v,x){return v=ae(v),x=ae(x),v.greater(x)?v:x}function ze(v,x){return v=ae(v),x=ae(x),v.lesser(x)?v:x}function $t(v,x){if(v=ae(v).abs(),x=ae(x).abs(),v.equals(x))return v;if(v.isZero())return x;if(x.isZero())return v;for(var L=a[1],j,ie;v.isEven()&&x.isEven();)j=ze(le(v),le(x)),v=v.divide(j),x=x.divide(j),L=L.multiply(j);for(;v.isEven();)v=v.divide(le(v));do{for(;x.isEven();)x=x.divide(le(x));v.greater(x)&&(ie=x,x=v,v=ie),x=x.subtract(v)}while(!x.isZero());return L.isUnit()?v:v.multiply(L)}function Ot(v,x){return v=ae(v).abs(),x=ae(x).abs(),v.divide($t(v,x)).multiply(x)}function fr(v,x,L){v=ae(v),x=ae(x);var j=L||Math.random,ie=ze(v,x),te=Fe(v,x),se=te.subtract(ie).add(1);if(se.isSmall)return ie.add(Math.floor(j()*se));for(var ce=Ue(se,t).value,pe=[],Le=!0,Je=0;Je<ce.length;Je++){var st=Le?ce[Je]+(Je+1<ce.length?ce[Je+1]/t:0):t,Zt=g(j()*st);pe.push(Zt),Zt<ce[Je]&&(Le=!1)}return ie.add(a.fromArray(pe,t,!1))}var Ve=function(v,x,L,j){L=L||o,v=String(v),j||(v=v.toLowerCase(),L=L.toLowerCase());var ie=v.length,te,se=Math.abs(x),ce={};for(te=0;te<L.length;te++)ce[L[te]]=te;for(te=0;te<ie;te++){var pe=v[te];if(pe!=="-"&&pe in ce&&ce[pe]>=se){if(pe==="1"&&se===1)continue;throw new Error(pe+" is not a valid digit in base "+x+".")}}x=ae(x);var Le=[],Je=v[0]==="-";for(te=Je?1:0;te<v.length;te++){var pe=v[te];if(pe in ce)Le.push(ae(ce[pe]));else if(pe==="<"){var st=te;do te++;while(v[te]!==">"&&te<v.length);Le.push(ae(v.slice(st+1,te)))}else throw new Error(pe+" is not a valid character")}return qe(Le,x,Je)};function qe(v,x,L){var j=a[0],ie=a[1],te;for(te=v.length-1;te>=0;te--)j=j.add(v[te].times(ie)),ie=ie.times(x);return L?j.negate():j}function bt(v,x){return x=x||o,v<x.length?x[v]:"<"+v+">"}function Ue(v,x){if(x=mo(x),x.isZero()){if(v.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(x.equals(-1)){if(v.isZero())return{value:[0],isNegative:!1};if(v.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-v.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var L=Array.apply(null,Array(v.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return L.unshift([1]),{value:[].concat.apply([],L),isNegative:!1}}var j=!1;if(v.isNegative()&&x.isPositive()&&(j=!0,v=v.abs()),x.isUnit())return v.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(v.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:j};for(var ie=[],te=v,se;te.isNegative()||te.compareAbs(x)>=0;){se=te.divmod(x),te=se.quotient;var ce=se.remainder;ce.isNegative()&&(ce=x.minus(ce).abs(),te=te.next()),ie.push(ce.toJSNumber())}return ie.push(te.toJSNumber()),{value:ie.reverse(),isNegative:j}}function Ke(v,x,L){var j=Ue(v,x);return(j.isNegative?"-":"")+j.value.map(function(ie){return bt(ie,L)}).join("")}c.prototype.toArray=function(v){return Ue(this,v)},u.prototype.toArray=function(v){return Ue(this,v)},d.prototype.toArray=function(v){return Ue(this,v)},c.prototype.toString=function(v,x){if(v===e&&(v=10),v!==10||x)return Ke(this,v,x);for(var L=this.value,j=L.length,ie=String(L[--j]),te="0000000",se;--j>=0;)se=String(L[j]),ie+=te.slice(se.length)+se;var ce=this.sign?"-":"";return ce+ie},u.prototype.toString=function(v,x){return v===e&&(v=10),v!=10||x?Ke(this,v,x):String(this.value)},d.prototype.toString=u.prototype.toString,d.prototype.toJSON=c.prototype.toJSON=u.prototype.toJSON=function(){return this.toString()},c.prototype.valueOf=function(){return parseInt(this.toString(),10)},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=function(){return this.value},u.prototype.toJSNumber=u.prototype.valueOf,d.prototype.valueOf=d.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};function et(v){if(f(+v)){var x=+v;if(x===g(x))return s?new d(BigInt(x)):new u(x);throw new Error("Invalid integer: "+v)}var L=v[0]==="-";L&&(v=v.slice(1));var j=v.split(/e/i);if(j.length>2)throw new Error("Invalid integer: "+j.join("e"));if(j.length===2){var ie=j[1];if(ie[0]==="+"&&(ie=ie.slice(1)),ie=+ie,ie!==g(ie)||!f(ie))throw new Error("Invalid integer: "+ie+" is not a valid exponent.");var te=j[0],se=te.indexOf(".");if(se>=0&&(ie-=te.length-se-1,te=te.slice(0,se)+te.slice(se+1)),ie<0)throw new Error("Cannot include negative exponent part for integers");te+=new Array(ie+1).join("0"),v=te}var ce=/^([0-9][0-9]*)$/.test(v);if(!ce)throw new Error("Invalid integer: "+v);if(s)return new d(BigInt(L?"-"+v:v));for(var pe=[],Le=v.length,Je=r,st=Le-Je;Le>0;)pe.push(+v.slice(st,Le)),st-=Je,st<0&&(st=0),Le-=Je;return m(pe),new c(pe,L)}function Xe(v){if(s)return new d(BigInt(v));if(f(v)){if(v!==g(v))throw new Error(v+" is not an integer.");return new u(v)}return et(v.toString())}function ae(v){return typeof v=="number"?Xe(v):typeof v=="string"?et(v):typeof v=="bigint"?new d(v):v}for(var X=0;X<1e3;X++)a[X]=ae(X),X>0&&(a[-X]=ae(-X));return a.one=a[1],a.zero=a[0],a.minusOne=a[-1],a.max=Fe,a.min=ze,a.gcd=$t,a.lcm=Ot,a.isInstance=function(v){return v instanceof c||v instanceof u||v instanceof d},a.randBetween=fr,a.fromArray=function(v,x,L){return qe(v.map(ae),ae(x||10),L)},a})();typeof lJ<"u"&&lJ.hasOwnProperty("exports")&&(lJ.exports=mo);typeof define=="function"&&define.amd&&define(function(){return mo})});var drt=I((z7r,urt)=>{var Um=crt(),uJ=H("stream");(!uJ.Writable||!uJ.Writable.prototype.destroy)&&(uJ=pa());var dJ;function nEr(){var e=3988292384,t,r,n;for(dJ=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=t&1?e^t>>>1:t=t>>>1;dJ[r]=t>>>0}}function lrt(e,t){return dJ||nEr(),e.charCodeAt&&(e=e.charCodeAt(0)),Um(t).shiftRight(8).and(16777215).xor(dJ[Um(t).xor(e).and(255)]).value}function Tw(){if(!(this instanceof Tw))return new Tw;this.key0=305419896,this.key1=591751049,this.key2=878082192}Tw.prototype.update=function(e){this.key0=lrt(e,this.key0),this.key1=Um(this.key0).and(255).and(4294967295).add(this.key1),this.key1=Um(this.key1).multiply(134775813).add(1).and(4294967295).value,this.key2=lrt(Um(this.key1).shiftRight(24).and(255),this.key2)};Tw.prototype.decryptByte=function(e){var t=Um(this.key2).or(2);return e=e^Um(t).multiply(Um(t^1)).shiftRight(8).and(255),this.update(e),e};Tw.prototype.stream=function(){var e=uJ.Transform(),t=this;return e._transform=function(r,n,i){for(var o=0;o<r.length;o++)r[o]=t.decryptByte(r[o]);this.push(r),i()},e};urt.exports=Tw});var prt=I((J7r,frt)=>{var iEr=Fm(),oEr=drt(),sEr=Vz(),$B=H("stream"),aEr=DB(),cEr=H("zlib"),lEr=Zz(),uEr=_w(),dEr=Xz();(!$B.Writable||!$B.Writable.prototype.destroy)&&($B=pa());frt.exports=function(t,r,n,i){var o=sEr(),s=$B.PassThrough(),a=t.stream(r);return a.pipe(o).on("error",function(c){s.emit("error",c)}),s.vars=o.pull(30).then(function(c){var u=aEr.parse(c).word32lu("signature").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;return u.lastModifiedDateTime=dEr(u.lastModifiedDate,u.lastModifiedTime),o.pull(u.fileNameLength).then(function(d){return u.fileName=d.toString("utf8"),o.pull(u.extraFieldLength)}).then(function(d){var f;return u.extra=lEr(d,u),i&&i.compressedSize&&(u=i),u.flags&1&&(f=o.pull(12).then(function(p){if(!n)throw new Error("MISSING_PASSWORD");var h=oEr();String(n).split("").forEach(function(g){h.update(g)});for(var m=0;m<p.length;m++)p[m]=h.decryptByte(p[m]);u.decrypt=h,u.compressedSize-=12;var A=u.flags&8?u.lastModifiedTime>>8&255:u.crc32>>24&255;if(p[11]!==A)throw new Error("BAD_PASSWORD");return u})),iEr.resolve(f).then(function(){return s.emit("vars",u),u})})}),s.vars.then(function(c){var u=!(c.flags&8)||c.compressedSize>0,d,f=c.compressionMethod?cEr.createInflateRaw():$B.PassThrough();u?(s.size=c.uncompressedSize,d=c.compressedSize):(d=uEr.alloc(4),d.writeUInt32LE(134695760,0));var p=o.stream(d);c.decrypt&&(p=p.pipe(c.decrypt.stream())),p.pipe(f).on("error",function(h){s.emit("error",h)}).pipe(s).on("finish",function(){a.destroy?a.destroy():a.abort?a.abort():a.close?a.close():a.push?a.push():console.log("warning - unable to close stream")})}).catch(function(c){s.emit("error",c)}),s}});var Art=I((G7r,mrt)=>{var YB=DB(),jB=Vz(),fEr=prt(),qB=Fm(),pEr=Kz(),hEr=Zz(),mEr=_w(),Vfe=H("path"),AEr=Jfe().Writer,gEr=Xz(),hrt=mEr.alloc(4);hrt.writeUInt32LE(101010256,0);function yEr(e){var t=e.stream(0).pipe(jB());return t.pull(4).then(function(r){var n=r.readUInt32LE(0);if(n===875721283){var i;return t.pull(12).then(function(o){i=YB.parse(o).word32lu("version").word32lu("pubKeyLength").word32lu("signatureLength").vars}).then(function(){return t.pull(i.pubKeyLength+i.signatureLength)}).then(function(o){return i.publicKey=o.slice(0,i.pubKeyLength),i.signature=o.slice(i.pubKeyLength),i.size=16+i.pubKeyLength+i.signatureLength,i})}})}function EEr(e,t){var r=YB.parse(t).word32lu("signature").word32lu("diskNumber").word64lu("offsetToStartOfCentralDirectory").word32lu("numberOfDisks").vars;if(r.signature!=117853008)throw new Error("invalid zip64 end of central dir locator signature (0x07064b50): 0x"+r.signature.toString(16));var n=jB();return e.stream(r.offsetToStartOfCentralDirectory).pipe(n),n.pull(56)}function bEr(e){var t=YB.parse(e).word32lu("signature").word64lu("sizeOfCentralDirectory").word16lu("version").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskStart").word64lu("numberOfRecordsOnDisk").word64lu("numberOfRecords").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;if(t.signature!=101075792)throw new Error("invalid zip64 end of central dir locator signature (0x06064b50): 0x0"+t.signature.toString(16));return t}mrt.exports=function(t,r){var n=jB(),i=jB(),o=r&&r.tailSize||80,s,a,c,u;return r&&r.crx&&(a=yEr(t)),t.size().then(function(d){return s=d,t.stream(Math.max(0,d-o)).on("error",function(f){n.emit("error",f)}).pipe(n),n.pull(hrt)}).then(function(){return qB.props({directory:n.pull(22),crxHeader:a})}).then(function(d){var f=d.directory;if(c=d.crxHeader&&d.crxHeader.size||0,u=YB.parse(f).word32lu("signature").word16lu("diskNumber").word16lu("diskStart").word16lu("numberOfRecordsOnDisk").word16lu("numberOfRecords").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars,u.numberOfRecords==65535||u.numberOfRecords==65535||u.offsetToStartOfCentralDirectory==4294967295){let h=s-(o-n.match+20),m=jB();return t.stream(h).pipe(m),m.pull(20).then(function(A){return EEr(t,A)}).then(function(A){u=bEr(A)})}else u.offsetToStartOfCentralDirectory+=c}).then(function(){if(u.commentLength)return n.pull(u.commentLength).then(function(d){u.comment=d.toString("utf8")})}).then(function(){return t.stream(u.offsetToStartOfCentralDirectory).pipe(i),u.extract=function(d){if(!d||!d.path)throw new Error("PATH_MISSING");return d.path=Vfe.resolve(Vfe.normalize(d.path)),u.files.then(function(f){return qB.map(f,function(p){if(p.type!="Directory"){var h=Vfe.join(d.path,p.path);if(h.indexOf(d.path)==0){var m=d.getWriter?d.getWriter({path:h}):AEr({path:h});return new qB(function(A,g){p.stream(d.password).on("error",g).pipe(m).on("close",A).on("error",g)})}}},{concurrency:d.concurrency>1?d.concurrency:1})})},u.files=qB.mapSeries(Array(u.numberOfRecords),function(){return i.pull(46).then(function(d){var f=YB.parse(d).word32lu("signature").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;return f.offsetToLocalFileHeader+=c,f.lastModifiedDateTime=gEr(f.lastModifiedDate,f.lastModifiedTime),i.pull(f.fileNameLength).then(function(p){return f.pathBuffer=p,f.path=p.toString("utf8"),f.isUnicode=(f.flags&2048)!=0,i.pull(f.extraFieldLength)}).then(function(p){return f.extra=hEr(p,f),i.pull(f.fileCommentLength)}).then(function(p){return f.comment=p,f.type=f.uncompressedSize===0&&/[\/\\]$/.test(f.path)?"Directory":"File",f.stream=function(h){return fEr(t,f.offsetToLocalFileHeader,h,f)},f.buffer=function(h){return pEr(f.stream(h))},f})})}),qB.props(u)})}});var Ert=I((V7r,yrt)=>{var grt=Ea(),fJ=Fm(),HB=Art(),pJ=H("stream");(!pJ.Writable||!pJ.Writable.prototype.destroy)&&(pJ=pa());yrt.exports={buffer:function(e,t){var r={stream:function(n,i){var o=pJ.PassThrough();return o.end(e.slice(n,i)),o},size:function(){return fJ.resolve(e.length)}};return HB(r,t)},file:function(e,t){var r={stream:function(n,i){return grt.createReadStream(e,{start:n,end:i&&n+i})},size:function(){return new fJ(function(n,i){grt.stat(e,function(o,s){o?i(o):n(s.size)})})}};return HB(r,t)},url:function(e,t,r){if(typeof t=="string"&&(t={url:t}),!t.url)throw"URL missing";t.headers=t.headers||{};var n={stream:function(i,o){var s=Object.create(t);return s.headers=Object.create(t.headers),s.headers.range="bytes="+i+"-"+(o||""),e(s)},size:function(){return new fJ(function(i,o){var s=e(t);s.on("response",function(a){s.abort(),a.headers["content-length"]?i(a.headers["content-length"]):o(new Error("Missing content length header"))}).on("error",o)})}};return HB(n,r)},s3:function(e,t,r){var n={size:function(){return new fJ(function(i,o){e.headObject(t,function(s,a){s?o(s):i(a.ContentLength)})})},stream:function(i,o){var s={};for(var a in t)s[a]=t[a];return s.Range="bytes="+i+"-"+(o||""),e.getObject(s).createReadStream()}};return HB(n,r)},custom:function(e,t){return HB(e,t)}}});var brt=I(zB=>{"use strict";ZZe();rXe();Ute();zB.Parse=eJ();zB.ParseOne=utt();zB.Extract=art();zB.Open=Ert()});var Prt=I((K7r,Wf)=>{var un=H("fs"),mJ=H("os"),Ao=H("path"),Irt=H("crypto"),sd={fs:un.constants,os:mJ.constants},Crt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Srt=/XXXXXX/,IEr=3,Drt=(sd.O_CREAT||sd.fs.O_CREAT)|(sd.O_EXCL||sd.fs.O_EXCL)|(sd.O_RDWR||sd.fs.O_RDWR),CEr=mJ.platform()==="win32",_Er=sd.EBADF||sd.os.errno.EBADF,wEr=sd.ENOENT||sd.os.errno.ENOENT,Rrt=448,Trt=384,vEr="exit",xw=[],xrt=un.rmdirSync.bind(un),krt=!1;function SEr(e,t){return un.rm(e,{recursive:!0},t)}function Brt(e){return un.rmSync(e,{recursive:!0})}function Xfe(e,t){let r=kw(e,t),n=r[0],i=r[1];QEr(n,function(o,s){if(o)return i(o);let a=s.tries;(function c(){try{let u=Ort(s);un.stat(u,function(d){if(!d)return a-- >0?c():i(new Error("Could not get a unique tmp filename, max tries reached "+u));i(null,u)})}catch(u){i(u)}})()})}function epe(e){let t=kw(e),r=t[0],n=LEr(r),i=n.tries;do{let o=Ort(n);try{un.statSync(o)}catch{return o}}while(i-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function DEr(e,t){let r=kw(e,t),n=r[0],i=r[1];Xfe(n,function(s,a){if(s)return i(s);un.open(a,Drt,n.mode||Trt,function(u,d){if(u)return i(u);if(n.discardDescriptor)return un.close(d,function(p){return i(p,a,void 0,Kfe(a,-1,n,!1))});{let f=n.discardDescriptor||n.detachDescriptor;i(null,a,d,Kfe(a,f?-1:d,n,!1))}})})}function REr(e){let t=kw(e),r=t[0],n=r.discardDescriptor||r.detachDescriptor,i=epe(r),o=un.openSync(i,Drt,r.mode||Trt);return r.discardDescriptor&&(un.closeSync(o),o=void 0),{name:i,fd:o,removeCallback:Kfe(i,n?-1:o,r,!0)}}function TEr(e,t){let r=kw(e,t),n=r[0],i=r[1];Xfe(n,function(s,a){if(s)return i(s);un.mkdir(a,n.mode||Rrt,function(u){if(u)return i(u);i(null,a,Nrt(a,n,!1))})})}function xEr(e){let t=kw(e),r=t[0],n=epe(r);return un.mkdirSync(n,r.mode||Rrt),{name:n,removeCallback:Nrt(n,r,!0)}}function kEr(e,t){let r=function(n){if(n&&!Zfe(n))return t(n);t()};0<=e[0]?un.close(e[0],function(){un.unlink(e[1],r)}):un.unlink(e[1],r)}function BEr(e){let t=null;try{0<=e[0]&&un.closeSync(e[0])}catch(r){if(!PEr(r)&&!Zfe(r))throw r}finally{try{un.unlinkSync(e[1])}catch(r){Zfe(r)||(t=r)}}if(t!==null)throw t}function Kfe(e,t,r,n){let i=hJ(BEr,[t,e],n),o=hJ(kEr,[t,e],n,i);return r.keep||xw.unshift(i),n?i:o}function Nrt(e,t,r){let n=t.unsafeCleanup?SEr:un.rmdir.bind(un),i=t.unsafeCleanup?Brt:xrt,o=hJ(i,e,r),s=hJ(n,e,r,o);return t.keep||xw.unshift(o),r?o:s}function hJ(e,t,r,n){let i=!1;return function o(s){if(!i){let a=n||o,c=xw.indexOf(a);return c>=0&&xw.splice(c,1),i=!0,r||e===xrt||e===Brt?e(t):e(t,s||function(){})}}}function NEr(){if(krt)for(;xw.length;)try{xw[0]()}catch{}}function _rt(e){let t=[],r=null;try{r=Irt.randomBytes(e)}catch{r=Irt.pseudoRandomBytes(e)}for(let n=0;n<e;n++)t.push(Crt[r[n]%Crt.length]);return t.join("")}function ba(e){return typeof e>"u"}function kw(e,t){if(typeof e=="function")return[{},e];if(ba(e))return[{},t];let r={};for(let n of Object.getOwnPropertyNames(e))r[n]=e[n];return[r,t]}function OEr(e,t,r){let n=Ao.isAbsolute(e)?e:Ao.join(t,e);un.stat(n,function(i){i?un.realpath(Ao.dirname(n),function(o,s){if(o)return r(o);r(null,Ao.join(s,Ao.basename(n)))}):un.realpath(n,r)})}function FEr(e,t){let r=Ao.isAbsolute(e)?e:Ao.join(t,e);try{return un.statSync(r),un.realpathSync(r)}catch{let i=un.realpathSync(Ao.dirname(r));return Ao.join(i,Ao.basename(r))}}function Ort(e){let t=e.tmpdir;if(!ba(e.name))return Ao.join(t,e.dir,e.name);if(!ba(e.template))return Ao.join(t,e.dir,e.template).replace(Srt,_rt(6));let r=[e.prefix?e.prefix:"tmp","-",process.pid,"-",_rt(12),e.postfix?"-"+e.postfix:""].join("");return Ao.join(t,e.dir,r)}function Wfe(e,t){if(typeof t!="string")throw new Error(`${e} option must be a string, got "${typeof t}".`);if(t.includes(".."))throw new Error("Relative value not allowed");return t}function Frt(e){if(!ba(e.name)){let t=e.name;if(Ao.isAbsolute(t))throw new Error(`name option must not contain an absolute path, found "${t}".`);let r=Ao.basename(t);if(r===".."||r==="."||r!==t)throw new Error(`name option must not contain a path, found "${t}".`)}if(!ba(e.template)){if(typeof e.template!="string")throw new Error(`template option must be a string, got "${typeof e.template}".`);if(!e.template.match(Srt))throw new Error(`Invalid template, found "${e.template}".`)}if(!ba(e.tries)&&isNaN(e.tries)||e.tries<0)throw new Error(`Invalid tries, found "${e.tries}".`);e.tries=ba(e.name)?e.tries||IEr:1,e.keep=!!e.keep,e.detachDescriptor=!!e.detachDescriptor,e.discardDescriptor=!!e.discardDescriptor,e.unsafeCleanup=!!e.unsafeCleanup,e.prefix=ba(e.prefix)?"":Wfe("prefix",e.prefix),e.postfix=ba(e.postfix)?"":Wfe("postfix",e.postfix),e.template=ba(e.template)?void 0:Wfe("template",e.template)}function wrt(e,t,r,n){if(ba(t))return n(null);OEr(t,r,function(i,o){if(i)return n(i);let s=Ao.relative(r,o);if(s.startsWith("..")||Ao.isAbsolute(s))return n(new Error(`${e} option must be relative to "${r}", found "${s}".`));n(null,s)})}function vrt(e,t,r){if(ba(t))return;let n=FEr(t,r),i=Ao.relative(r,n);if(i.startsWith("..")||Ao.isAbsolute(i))throw new Error(`${e} option must be relative to "${r}", found "${i}".`);return i}function QEr(e,t){UEr(e,function(r,n){if(r)return t(r);e.tmpdir=n;try{Frt(e,n)}catch(i){return t(i)}wrt("dir",e.dir,n,function(i,o){if(i)return t(i);e.dir=ba(o)?"":o,wrt("template",e.template,n,function(s,a){if(s)return t(s);e.template=a,t(null,e)})})})}function LEr(e){let t=e.tmpdir=Lrt(e);Frt(e,t);let r=vrt("dir",e.dir,t);return e.dir=ba(r)?"":r,e.template=vrt("template",e.template,t),e}function PEr(e){return Qrt(e,-_Er,"EBADF")}function Zfe(e){return Qrt(e,-wEr,"ENOENT")}function Qrt(e,t,r){return CEr?e.code===r:e.code===r&&e.errno===t}function MEr(){krt=!0}function UEr(e,t){return un.realpath(e&&e.tmpdir||mJ.tmpdir(),t)}function Lrt(e){return un.realpathSync(e&&e.tmpdir||mJ.tmpdir())}process.addListener(vEr,NEr);Object.defineProperty(Wf.exports,"tmpdir",{enumerable:!0,configurable:!1,get:function(){return Lrt()}});Wf.exports.dir=TEr;Wf.exports.dirSync=xEr;Wf.exports.file=DEr;Wf.exports.fileSync=REr;Wf.exports.tmpName=Xfe;Wf.exports.tmpNameSync=epe;Wf.exports.setGracefulCleanup=MEr});var Urt=I((Z7r,Mrt)=>{Mrt.exports=async function*(t){let r=[];t.on("data",a=>r.push(a));let n,i=new Promise(a=>n=a),o=!1;t.on("end",()=>{o=!0,n()});let s=!1;for(t.on("error",a=>{s=a,n()});!o||r.length>0;)if(r.length===0?(t.resume(),await Promise.race([$Er(t,"data"),i])):(t.pause(),yield r.shift()),s)throw s;n()};function $Er(e,t){return new Promise(r=>{let n=!1,i=()=>{n||(n=!0,e.removeListener(t,i),r())};e.addListener(t,i)})}});var Yrt=I((X7r,jrt)=>{var{EventEmitter:qEr}=H("events"),jEr=nk(),YEr=vi(),AJ=Is(),$rt=si(),HEr=Cf(),zEr=G2(),qrt=V2(),tpe=class extends qEr{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i||{},this.name=`Sheet${this.id}`,this._columns=null,this._keys={},this._dimensions=new HEr}destroy(){throw new Error("Invalid Operation: destroy")}get dimensions(){return this._dimensions}get columns(){return this._columns}getColumn(t){if(typeof t=="string"){let r=this._keys[t];if(r)return r;t=$rt.l2n(t)}if(this._columns||(this._columns=[]),t>this._columns.length){let r=this._columns.length+1;for(;r<=t;)this._columns.push(new qrt(this,r++))}return this._columns[t-1]}getColumnKey(t){return this._keys[t]}setColumnKey(t,r){this._keys[t]=r}deleteColumnKey(t){delete this._keys[t]}eachColumnKey(t){YEr.each(this._keys,t)}async read(){try{for await(let t of this.parse())for(let{eventType:r,value:n}of t)this.emit(r,n);this.emit("finished")}catch(t){this.emit("error",t)}}async*[Symbol.asyncIterator](){for await(let t of this.parse())for(let{eventType:r,value:n}of t)r==="row"&&(yield n)}async*parse(){let{iterator:t,options:r}=this,n=!1,i=!1,o=null;switch(r.worksheets){case"emit":n=!0;break;case"prep":break;default:break}switch(r.hyperlinks){case"emit":i=!0;break;case"cache":this.hyperlinks=o={};break;default:break}if(!n&&!i&&!o)return;let{sharedStrings:s,styles:a,properties:c}=this.workbook,u=!1,d=!1,f=!1,p=null,h=null,m=null,A=null;for await(let g of jEr(t)){let y=[];for(let{eventType:b,value:E}of g)if(b==="opentag"){let C=E;if(n)switch(C.name){case"cols":u=!0,p=[];break;case"sheetData":d=!0;break;case"col":u&&p.push({min:parseInt(C.attributes.min,10),max:parseInt(C.attributes.max,10),width:parseFloat(C.attributes.width),styleId:parseInt(C.attributes.style||"0",10)});break;case"row":if(d){let w=parseInt(C.attributes.r,10);if(h=new zEr(this,w),C.attributes.ht&&(h.height=parseFloat(C.attributes.ht)),C.attributes.s){let T=parseInt(C.attributes.s,10),R=a.getStyleModel(T);R&&(h.style=R)}}break;case"c":h&&(m={ref:C.attributes.r,s:parseInt(C.attributes.s,10),t:C.attributes.t});break;case"f":m&&(A=m.f={text:""});break;case"v":m&&(A=m.v={text:""});break;case"is":case"t":m&&(A=m.v={text:""});break;case"mergeCell":break;default:break}if(i||o)switch(C.name){case"hyperlinks":f=!0;break;case"hyperlink":if(f){let w={ref:C.attributes.ref,rId:C.attributes["r:id"]};i?y.push({eventType:"hyperlink",value:w}):o[w.ref]=w}break;default:break}}else if(b==="text")n&&A&&(A.text+=E);else if(b==="closetag"){let C=E;if(n)switch(C.name){case"cols":u=!1,this._columns=qrt.fromModel(p);break;case"sheetData":d=!1;break;case"row":this._dimensions.expandRow(h),y.push({eventType:"row",value:h}),h=null;break;case"c":if(h&&m){let w=$rt.decodeAddress(m.ref),T=h.getCell(w.col);if(m.s){let R=a.getStyleModel(m.s);R&&(T.style=R)}if(m.f){let R={formula:m.f.text};m.v&&(m.t==="str"?R.result=AJ.xmlDecode(m.v.text):R.result=parseFloat(m.v.text)),T.value=R}else if(m.v)switch(m.t){case"s":{let R=parseInt(m.v.text,10);s?T.value=s[R]:T.value={sharedString:R};break}case"inlineStr":case"str":T.value=AJ.xmlDecode(m.v.text);break;case"e":T.value={error:m.v.text};break;case"b":T.value=parseInt(m.v.text,10)!==0;break;default:AJ.isDateFmt(T.numFmt)?T.value=AJ.excelToDate(parseFloat(m.v.text),c.model&&c.model.date1904):T.value=parseFloat(m.v.text);break}if(o){let R=o[m.ref];R&&(T.text=T.value,T.value=void 0,T.hyperlink=R)}m=null}break;default:break}(i||o)&&C.name==="hyperlinks"&&(f=!1)}y.length>0&&(yield y)}}};jrt.exports=tpe});var zrt=I((eZr,Hrt)=>{var{EventEmitter:JEr}=H("events"),GEr=nk(),VEr=Pl(),WEr=Mh(),rpe=class extends JEr{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i}get count(){return this.hyperlinks&&this.hyperlinks.length||0}each(t){return this.hyperlinks.forEach(t)}async read(){let{iterator:t,options:r}=this,n=!1,i=null;switch(r.hyperlinks){case"emit":n=!0;break;case"cache":this.hyperlinks=i={};break;default:break}if(!n&&!i){this.emit("finished");return}try{for await(let o of GEr(t))for(let{eventType:s,value:a}of o)if(s==="opentag"){let c=a;if(c.name==="Relationship"){let u=c.attributes.Id;switch(c.attributes.Type){case WEr.Hyperlink:{let d={type:VEr.RelationshipType.Styles,rId:u,target:c.attributes.Target,targetMode:c.attributes.TargetMode};n?this.emit("hyperlink",d):i[d.rId]=d}break;default:break}}}this.emit("finished")}catch(o){this.emit("error",o)}}};Hrt.exports=rpe});var Wrt=I((tZr,Vrt)=>{var npe=H("fs"),{EventEmitter:KEr}=H("events"),{PassThrough:ZEr,Readable:XEr}=Zx(),ebr=H("stream"),tbr=brt(),Grt=Prt(),iE=Urt(),rbr=nk(),Jrt=Dj(),nbr=Nj(),ibr=kj(),obr=Yrt(),sbr=zrt();Grt.setGracefulCleanup();var gJ=class extends KEr{constructor(t,r={}){super(),this.input=t,this.options={worksheets:"emit",sharedStrings:"cache",hyperlinks:"ignore",styles:"ignore",entries:"ignore",...r},this.styles=new Jrt,this.styles.init()}_getStream(t){if(t instanceof ebr.Readable||t instanceof XEr)return t;if(typeof t=="string")return npe.createReadStream(t);throw new Error(`Could not recognise input: ${t}`)}async read(t,r){try{for await(let{eventType:n,value:i}of this.parse(t,r))switch(n){case"shared-strings":this.emit(n,i);break;case"worksheet":this.emit(n,i),await i.read();break;case"hyperlinks":this.emit(n,i);break}this.emit("end"),this.emit("finished")}catch(n){this.emit("error",n)}}async*[Symbol.asyncIterator](){for await(let{eventType:t,value:r}of this.parse())t==="worksheet"&&(yield r)}async*parse(t,r){r&&(this.options=r);let n=this.stream=this._getStream(t||this.input),i=tbr.Parse({forceStream:!0});n.pipe(i);let o=[];for await(let s of iE(i)){let a,c;switch(s.path){case"_rels/.rels":break;case"xl/_rels/workbook.xml.rels":await this._parseRels(s);break;case"xl/workbook.xml":await this._parseWorkbook(s);break;case"xl/sharedStrings.xml":yield*this._parseSharedStrings(s);break;case"xl/styles.xml":await this._parseStyles(s);break;default:s.path.match(/xl\/worksheets\/sheet\d+[.]xml/)?(a=s.path.match(/xl\/worksheets\/sheet(\d+)[.]xml/),c=a[1],this.sharedStrings&&this.workbookRels?yield*this._parseWorksheet(iE(s),c):await new Promise((u,d)=>{Grt.file((f,p,h,m)=>{if(f)return d(f);o.push({sheetNo:c,path:p,tempFileCleanupCallback:m});let A=npe.createWriteStream(p);return A.on("error",d),s.pipe(A),A.on("finish",()=>u())})})):s.path.match(/xl\/worksheets\/_rels\/sheet\d+[.]xml.rels/)&&(a=s.path.match(/xl\/worksheets\/_rels\/sheet(\d+)[.]xml.rels/),c=a[1],yield*this._parseHyperlinks(iE(s),c));break}s.autodrain()}for(let{sheetNo:s,path:a,tempFileCleanupCallback:c}of o){let u=npe.createReadStream(a);u[Symbol.asyncIterator]||(u=u.pipe(new ZEr)),yield*this._parseWorksheet(u,s),c()}}_emitEntry(t){this.options.entries==="emit"&&this.emit("entry",t)}async _parseRels(t){let r=new ibr;this.workbookRels=await r.parseStream(iE(t))}async _parseWorkbook(t){this._emitEntry({type:"workbook"});let r=new nbr;await r.parseStream(iE(t)),this.properties=r.map.workbookPr,this.model=r.model}async*_parseSharedStrings(t){switch(this._emitEntry({type:"shared-strings"}),this.options.sharedStrings){case"cache":this.sharedStrings=[];break;case"emit":break;default:return}let r=null,n=[],i=0,o=null;for await(let s of rbr(iE(t)))for(let{eventType:a,value:c}of s)if(a==="opentag"){let u=c;switch(u.name){case"b":o=o||{},o.bold=!0;break;case"charset":o=o||{},o.charset=parseInt(u.attributes.charset,10);break;case"color":o=o||{},o.color={},u.attributes.rgb&&(o.color.argb=u.attributes.argb),u.attributes.val&&(o.color.argb=u.attributes.val),u.attributes.theme&&(o.color.theme=u.attributes.theme);break;case"family":o=o||{},o.family=parseInt(u.attributes.val,10);break;case"i":o=o||{},o.italic=!0;break;case"outline":o=o||{},o.outline=!0;break;case"rFont":o=o||{},o.name=u.value;break;case"si":o=null,n=[],r=null;break;case"sz":o=o||{},o.size=parseInt(u.attributes.val,10);break;case"strike":break;case"t":r=null;break;case"u":o=o||{},o.underline=!0;break;case"vertAlign":o=o||{},o.vertAlign=u.attributes.val;break}}else if(a==="text")r=r?r+c:c;else if(a==="closetag")switch(c.name){case"r":n.push({font:o,text:r}),o=null,r=null;break;case"si":this.options.sharedStrings==="cache"?this.sharedStrings.push(n.length?{richText:n}:r):this.options.sharedStrings==="emit"&&(yield{index:i++,text:n.length?{richText:n}:r}),n=[],o=null,r=null;break}}async _parseStyles(t){this._emitEntry({type:"styles"}),this.options.styles==="cache"&&(this.styles=new Jrt,await this.styles.parseStream(iE(t)))}*_parseWorksheet(t,r){this._emitEntry({type:"worksheet",id:r});let n=new obr({workbook:this,id:r,iterator:t,options:this.options}),i=(this.workbookRels||[]).find(s=>s.Target===`worksheets/sheet${r}.xml`),o=i&&(this.model.sheets||[]).find(s=>s.rId===i.Id);o&&(n.id=o.id,n.name=o.name,n.state=o.state),this.options.worksheets==="emit"&&(yield{eventType:"worksheet",value:n})}*_parseHyperlinks(t,r){this._emitEntry({type:"hyperlinks",id:r});let n=new sbr({workbook:this,id:r,iterator:t,options:this.options});this.options.hyperlinks==="emit"&&(yield{eventType:"hyperlinks",value:n})}};gJ.Options={worksheets:["emit","ignore"],sharedStrings:["cache","emit","ignore"],hyperlinks:["cache","emit","ignore"],styles:["cache","ignore"],entries:["emit","ignore"]};Vrt.exports=gJ});var Xrt=I((rZr,Zrt)=>{var Krt={Workbook:K8e(),ModelContainer:X8e(),stream:{xlsx:{WorkbookWriter:WZe(),WorkbookReader:Wrt()}}};Object.assign(Krt,Pl());Zrt.exports=Krt});var tnt=I((nZr,ent)=>{if(parseInt(process.versions.node.split(".")[0],10)<10)throw new Error("For node versions older than 10, please use the ES5 Import: https://github.com/exceljs/exceljs#es5-imports");ent.exports=Xrt()});function int(e){let t=new Set;for(let r=0;r<e.length;r++){let n=e[r];if(!n.trim())throw new Error(`Header row contains a blank column at position ${r+1}`);let i=n.trim().toLowerCase();if(t.has(i))throw new Error(`Header row contains a duplicate column: "${n}"`);t.add(i)}}function lbr(e,t){let r=new URL(e).pathname.toLowerCase();if(r.endsWith(".xls")||r.endsWith(".xlsx")||r.endsWith(".xlsm")||r.endsWith(".xlsb")||r.endsWith(".ods"))return"excel";let n=(t??"").toLowerCase();return n.includes("spreadsheet")||n.includes("excel")||n.includes("sheet")?"excel":"csv"}async function ubr(e){let r=(await Promise.resolve().then(()=>no(BPe(),1))).default.parse(e,{header:!1,skipEmptyLines:"greedy",dynamicTyping:!1,transform:o=>o.trim()});if(r.errors.length>0&&r.data.length===0){let o=r.errors[0];throw new Error(`CSV parse error at row ${o.row}: ${o.message}`)}if(r.data.length===0)return{columns:[],rows:[]};let n=(r.data[0]??[]).map(o=>String(o??"").trim());int(n);let i=[];for(let o=1;o<r.data.length;o++){let s=r.data[o]??[],a={};for(let c=0;c<n.length;c++)a[n[c]]=s[c]??null;i.push(a)}return{columns:n,rows:i}}function ipe(e){if(e==null)return null;if(e instanceof Date)return e.toISOString().slice(0,10);if(typeof e=="number")return String(e);if(typeof e=="string"||typeof e=="boolean")return e;let t=e;return"text"in t?String(t.text??""):"result"in t?ipe(t.result):"richText"in t&&Array.isArray(t.richText)?t.richText.map(r=>r.text??"").join(""):"hyperlink"in t?String(t.hyperlink??""):String(e)}async function dbr(e){let t=(await Promise.resolve().then(()=>no(R7(),1))).default,n=new t(Buffer.from(e)).getEntries().reduce((i,o)=>i+o.header.size,0);if(n>rnt)throw new Error(`XLSX uncompressed size ${n} bytes exceeds ${rnt}-byte safety cap`)}function ont(e){let t=0,r=[];return e.eachRow({includeEmpty:!1},(n,i)=>{if(t>0)return;let o=n.values.slice(1);o.some(s=>s!=null&&s!=="")&&(t=i,r=o.map(s=>String(ipe(s)??"").trim()))}),{headerRowNum:t,columns:r}}function nnt(e){let{headerRowNum:t,columns:r}=ont(e);if(!t)return{columns:[],rows:[]};int(r);let n=[];return e.eachRow({includeEmpty:!1},(i,o)=>{if(o<=t)return;let s=i.values.slice(1);if(s.every(c=>c==null||c===""))return;let a={};for(let c=0;c<r.length;c++)a[r[c]]=ipe(s[c]);n.push(a)}),{columns:r,rows:n}}async function fbr(e,t,r){await dbr(e);let n=await Promise.resolve().then(()=>no(tnt(),1)),i=n.default??n,o=new i.Workbook;await o.xlsx.load(e);let s=o.worksheets.map(u=>u.name);if(t<0||t>=s.length)throw new Error(`sheetIndex ${t} out of range (have ${s.length} sheets: ${s.join(", ")})`);let a=()=>s.map((u,d)=>`${d}:"${u}"`).join(", "),c=(u,d)=>{throw new Error(`${u.message} on sheet ${d} ("${s[d]}"). availableSheets: [${a()}]. Re-call with a sheetIndex pointing at the data sheet.`)};if(r)try{return{...nnt(o.worksheets[t]),sheetName:o.worksheets[t].name,sheetIndex:t,availableSheets:s}}catch(u){c(u,t)}for(let u=t;u<s.length;u++){let d=o.worksheets[u];if(ont(d).headerRowNum!==0)try{return{...nnt(d),sheetName:d.name,sheetIndex:u,availableSheets:s}}catch(f){c(f,u)}}throw new Error(`No sheet with a header row was found. availableSheets: [${a()}].`)}async function snt(e){let t=Math.max(0,e.offset??0),r=Math.min(abr,Math.max(1,e.limit??cbr)),n=e.sheetIndex??0,i=await tf(e.sourceUrl),o=await yc(i,{timeoutMs:xI,maxBytes:yP});if(!o.ok)throw new Error(`fetch ${e.sourceUrl}: ${o.status} ${o.statusText}`);let s=await o.arrayBuffer(),a=e.kind??lbr(e.sourceUrl,o.headers.get("content-type")),c,u,d,f,p=n;if(a==="csv"){let A=await ubr(new TextDecoder("utf-8").decode(s));c=A.columns,u=A.rows}else{let A=await fbr(s,n,e.sheetIndex!==void 0);c=A.columns,u=A.rows,d=A.sheetName,f=A.availableSheets,p=A.sheetIndex}let h=u.length,m=u.slice(t,t+r);return{sourceUrl:e.sourceUrl,kind:a,...a==="excel"?{sheetIndex:p,sheetName:d,availableSheets:f}:{},totalRows:h,offset:t,limit:r,returned:m.length,hasMore:t+m.length<h,columns:c,rows:m}}var abr,cbr,rnt,ant=G(()=>{"use strict";Ru();abr=500,cbr=200,rnt=100*1024*1024});function pbr(e){if(e.internalNotes!==void 0)throw Jt(new Error("A cash entry's notes cannot be edited via the API today (the update fails upstream). Nothing was changed. To change the notes, void the entry and create a new one."));if((Array.isArray(e.lines)?e.lines:[]).some(r=>!!r?.taxProfileResourceId))throw Jt(new Error("A taxed cash entry's lines cannot be edited via the API today: void it and create a new one. Nothing was changed."))}function cnt(e){return{create:(t,r)=>t.post(`/api/v1/${Bw[e]}`,{saveAsDraft:!1,...r,currency:zt(r.currency),taxCurrency:zt(r.taxCurrency)},Hi),list:(t,r)=>t.list(`/api/v1/${Bw[e]}`,r),get:(t,r)=>t.get(`/api/v1/${Bw[e]}/${r}`),update:async(t,r,n,i)=>{pbr(n);let o={...n,resourceId:r};if(!o.accountResourceId){let s=i??(await t.get(`/api/v1/${Bw[e]}/${r}`)).data;if(o.accountResourceId=s.organizationAccountResourceId??s.account?.resourceId,!o.accountResourceId)throw new Error(`accountResourceId required for ${Bw[e]} update and could not be derived from existing entry`)}return o.currency&&(o.currency=zt(o.currency)),t.put(`/api/v1/${Bw[e]}/${r}`,o)}}}var Bw,yJ,EJ,bJ,IJ,oE,CJ,_J,wJ,sE,vJ,SJ=G(()=>{"use strict";Ar();ut();Bw={IN:"cash-in-entries",OUT:"cash-out-entries"};yJ=cnt("IN"),EJ=cnt("OUT"),bJ=yJ.create,IJ=yJ.list,oE=yJ.get,CJ=yJ.update,_J=EJ.create,wJ=EJ.list,sE=EJ.get,vJ=EJ.update});async function JB(e,t){return e.post("/api/v1/cash-transfers",{saveAsDraft:!1,...t},Hi)}async function DJ(e,t){return e.list("/api/v1/cash-transfers",t)}async function RJ(e,t){return e.get(`/api/v1/cash-transfers/${t}`)}var ope=G(()=>{"use strict";Ar();Cn()});async function TJ(e,t){return e.list("/api/v1/scheduled/invoices",t)}async function xJ(e,t){return e.list("/api/v1/scheduled/bills",t)}async function kJ(e,t){return e.list("/api/v1/scheduled/journals",t)}async function Nw(e,t){return e.get(`/api/v1/scheduled/invoices/${t}`)}async function BJ(e,t,r){return e.put(`/api/v1/scheduled/invoices/${t}`,r)}async function NJ(e,t){await e.delete(`/api/v1/scheduled/invoices/${t}`)}async function Ow(e,t){return e.get(`/api/v1/scheduled/bills/${t}`)}async function OJ(e,t,r){return e.put(`/api/v1/scheduled/bills/${t}`,r)}async function FJ(e,t){await e.delete(`/api/v1/scheduled/bills/${t}`)}async function Fw(e,t){return e.get(`/api/v1/scheduled/journals/${t}`)}async function QJ(e,t,r){let{currency:n,...i}=hbr(r);return e.put(`/api/v1/scheduled/journals/${t}`,n===void 0?i:{...i,currency:zt(n)})}function hbr(e){let t={...e};DP(t);let r=Array.isArray(t.schedulerEntries)?t.schedulerEntries:[];if(typeof t.taxVatApplicable!="boolean"&&r.some(n=>!!n?.taxProfileResourceId)&&(t.taxVatApplicable=!0),t.taxVatApplicable===!0&&typeof t.taxInclusion!="boolean")throw Jt(new Error("taxInclusion is required when the schedule is taxed (a schedulerEntries line carries a tax profile, or taxVatApplicable is true): the update resets it when omitted, and the stored value cannot be read back. Send taxInclusion true (prices include tax) or false (CLI: --tax-inclusion inclusive|exclusive). Nothing was changed."));return t}async function LJ(e,t){await e.delete(`/api/v1/scheduled/journals/${t}`)}var PJ=G(()=>{"use strict";ut()});import{statSync as lnt}from"node:fs";function unt(e){for(let t of e)try{if(lnt(t).isFile())return t}catch{}return null}function dnt(e){for(let t of e)try{if(lnt(t).isDirectory())return t}catch{}return null}var spe=G(()=>{"use strict"});import{readFileSync as cpe}from"node:fs";import{dirname as mnt,join as $m}from"node:path";import{fileURLToPath as Ant}from"node:url";function gnt(e){let t=new Set(e);for(let r of e){let n=gbr.get(r);if(n)for(let i of n)t.add(i)}return Array.from(t)}function ynt(e){let t=e.toLowerCase();return t=t.replace(/https?:\/\/\S+/g,""),t=t.replace(/[*#`|_\-~\[\]()>]/g," "),(t.match(/[a-z0-9]+/g)??[]).filter(n=>n.length>1&&!Abr.has(n))}function GB(e){let t=e??Cbr();if(MJ&&hnt===t)return MJ;let r=cpe(t,"utf-8");return MJ=JSON.parse(r),hnt=t,MJ}function Ent(){let e=Ant(import.meta.url),t=mnt(e),r=[$m(t,"..","..","..","help-center-mirror","help-center-index.json"),$m(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-index.json"),$m(t,"help-center-mirror","help-center-index.json")];return unt(r)??void 0}function Cbr(){let e=Ent();if(!e)throw new Error("Help center index not found. Run the help center sync or reinstall the package.");return e}function VB(){return ape===null&&(ape=Ent()!==void 0),ape}function aE(e,t,r={}){let n=r.limit??5,i=ynt(t);if(i.length===0)return[];let o=gnt(i).slice(0,bbr),s=new Map(e.sections.map(c=>[c.slug,c])),a=[];for(let c of e.articles){if(r.section&&c.section!==r.section)continue;let u=new Map;for(let h of c.tokens)u.set(h,(u.get(h)??0)+1);let d=0,f=[],p=c.title.toLowerCase();for(let h of o){let m=u.get(h)??0,A=e.idf[h]??0,g=!1;if(m===0&&h.length>=Ebr){let C=0;for(let[w,T]of u)if(w.startsWith(h)&&w!==h&&(m+=T,A=Math.max(A,e.idf[w]??0),g=!0,++C>=Ibr))break}if(m===0)continue;f.push(g?`${h}*`:h);let y=m*(fnt+1),b=m+fnt*(1-pnt+pnt*(c.tokenCount/e.avgDocLen)),E=A*(y/b);g&&(E*=ybr),p.includes(h)&&(E*=mbr),d+=E}if(d>0){let h=s.get(c.section);h&&a.push({article:c,score:d,scoreKind:"bm25",section:h,matchedTerms:f})}}return a.sort((c,u)=>u.score-c.score),a.slice(0,n)}function lpe(e,t){let r=t??_br();if(!r)return null;try{let n=$m(r,`${e.section}.md`),i=cpe(n,"utf-8"),o=`### ${e.title}`,s=i.indexOf(o);if(s===-1)return null;let a=s+o.length,c=i.indexOf(`
|
|
660
660
|
---
|
|
661
661
|
`,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function _br(){let e=Ant(import.meta.url),t=mnt(e),r=[$m(t,"..","..","..","help-center-mirror"),$m(t,"..","..","..","assets","skills","api","help-center-mirror"),$m(t,"help-center-mirror")];for(let n of r)try{return cpe($m(n,"index.md"),"utf-8"),n}catch{}return null}var fnt,pnt,mbr,Abr,gbr,ybr,Ebr,bbr,Ibr,MJ,hnt,ape,WB=G(()=>{"use strict";spe();hg();fnt=1.2,pnt=.75,mbr=1.5,Abr=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","shall","should","may","might","must","can","could","am","i","me","my","we","our","you","your","he","she","it","they","them","this","that","these","those","what","which","who","whom","how","when","where","why","if","then","than","so","no","not","or","and","but","in","on","at","to","for","of","with","by","from","as","into","about","between","through","after","before","during","above","below","up","down","out","off","over","under","again","further","just","also","very","too","only","own","same","both","each","all","any","few","more","most","other","some","such","here","there"]),gbr=new Map([["recon",["reconciliation","reconcile","reconciled"]],["txn",["transaction","transactions"]],["txns",["transactions","transaction"]],["acct",["account","accounts"]],["accts",["accounts","account"]],["inv",["invoice","invoices"]],["cn",["credit","note"]],["ar",["receivable","receivables"]],["ap",["payable","payables"]],["pmt",["payment","payments"]],["stmt",["statement","statements"]],["bal",["balance","balances"]],["fa",["fixed","assets","asset"]],["gst",["tax","goods","services"]],["vat",["tax","value","added"]],["fx",["foreign","exchange","currency"]],["config",["configuration","configure","settings"]],["depr",["depreciation"]],["amort",["amortization"]],["coa",["chart","accounts"]],["po",["purchase","order"]],["so",["sales","order"]],["org",["organization"]],["subs",["subscription","subscriptions"]],["amt",["amount","amounts"]],["qty",["quantity"]],["desc",["description"]],["ref",["reference"]],["num",["number"]]]);ybr=.7,Ebr=3,bbr=32,Ibr=5;MJ=null,hnt=null;ape=null});import{existsSync as wbr,readFileSync as vbr}from"node:fs";import{dirname as Sbr,join as upe}from"node:path";import{fileURLToPath as Dbr}from"node:url";function KB(e){let t=e??Bbr();if(!t)return null;if(UJ&&Int===t)return UJ;try{let r=vbr(t,"utf-8");return UJ=JSON.parse(r),Int=t,UJ}catch{return null}}function Bbr(){let e=Dbr(import.meta.url),t=Sbr(e),r=[upe(t,"..","..","..","help-center-mirror","help-center-embeddings.json"),upe(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),upe(t,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(wbr(n))return n;return null}function wnt(e,t){let r=Math.min(e.length,t.length),n=0;for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function vnt(){return $J!==null?$J:($J=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",$J||null)}async function dpe(e){let t=vnt();if(!t)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),Tbr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:Rbr,input:e}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Cnt&&(Cnt=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
|
|
662
|
-
`)),null)}catch{return null}}async function ZB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??xbr,c=n.minBm25??kbr;if(i==="bm25"||!t)return aE(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await dpe(r);return m?_nt(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):aE(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([dpe(r),Promise.resolve(aE(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=_nt(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Snt(p,h,o)}function _nt(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=wnt(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Snt(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(bnt+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(bnt+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function fpe(e){return e!==null&&!!vnt()}var Rbr,Tbr,bnt,xbr,kbr,UJ,Int,$J,Cnt,qJ=G(()=>{"use strict";WB();Rbr="text-embedding-3-small",Tbr=2e3,bnt=60,xbr=.3,kbr=1.5,UJ=null,Int=null,$J=null,Cnt=!1});async function Dnt(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=GB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:KB(),u=await ZB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(lpe(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Rnt(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:Nbr}async function jJ(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Rnt())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(Obr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return Fbr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function Fbr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function ppe(e,t={}){return process.env.CLIO_DAEMON==="1"||VB()?Dnt(e,t):jJ(e,t)}var Nbr,Obr,Tnt=G(()=>{"use strict";WB();qJ();Nbr="https://mcp.jaz.ai/help-center/search",Obr=4e3});var hpe=G(()=>{"use strict";WB();qJ();Tnt();WB()});async function qm(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function jm(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var XB=G(()=>{"use strict";Cn()});async function YJ(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:zt(t.currency),taxCurrency:zt(t.taxCurrency)},gTe)}var mpe=G(()=>{"use strict";ut();Ar()});async function HJ(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function zJ(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function eN(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function JJ(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Ape=G(()=>{"use strict"});function Qbr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Qw(e,t){return e.post("/api/v1/jots",{entries:t.map(Qbr)})}async function GJ(e,t){return e.post("/api/v1/jots/search",t,Qt)}async function xnt(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var VJ=G(()=>{"use strict";Ar()});async function knt(e,t){return e.post("/api/v1/agents/memories",t)}async function gpe(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Bnt=G(()=>{"use strict";Ar()});function WJ(){return process.env.ENABLE_MEMORY==="true"}function ype(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Nnt(e){return!WJ()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Epe=G(()=>{"use strict"});import{createHash as Lbr}from"node:crypto";function Gbr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:Qnt.some(r=>t.includes(r))?[null,"directive_invalid"]:Fnt.test(t)?[null,"directive_invalid"]:jbr.test(t)?[null,"directive_contains_url"]:Ybr.test(t)?[null,"directive_contains_email"]:[t,null]}function Vbr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>Hbr?[null,"match_condition_too_long"]:Qnt.some(r=>t.includes(r))?[null,"match_condition_invalid"]:Fnt.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function Wbr(e){return e==null?[null,null]:Number.isInteger(e)?e<zbr||e>Jbr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function Kbr(e,t,r,n,i,o,s,a){if(e)return Lbr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function Zbr(e){Promise.resolve().then(()=>(GS(),JS)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Unt(e,t,r){let n=t.action,i=t.category,o=$br[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(Zbr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Nnt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>Pbr||!qbr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=Gbr(t.directive);if(E)return u(E);p=b;let[C,w]=Wbr(t.importance);if(w)return u(w);h=C}let[m,A]=Vbr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=Mbr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,Ubr));let E=Kbr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await bpe(()=>knt(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await bpe(()=>gpe(e.client,b))}else{let b={forgetAll:!0};y=await bpe(()=>gpe(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function bpe(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof gr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var Fnt,Qnt,Pbr,Mbr,Ubr,Lnt,Pnt,Mnt,$br,qbr,jbr,Ybr,Hbr,zbr,Jbr,$nt=G(()=>{"use strict";Bnt();zi();Epe();Epe();Fnt=/[\x00-\x1f\x7f]/,Qnt=["{{","}}","```","<",">"],Pbr=120,Mbr=3,Ubr=140,Lnt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Pnt=["set","forget","forget_all"],Mnt=["this_org","all_orgs"],$br={this_org:"ORG_USER",all_orgs:"USER"},qbr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,jbr=/https?:\/\//i,Ybr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Hbr=255,zbr=0,Jbr=100});async function KJ(e,t){return e.list("/api/v1/organization-users",t)}async function ZJ(e,t){return e.search("/api/v1/organization-users/search",t)}async function Lw(e,t){return e.post("/api/v1/organization-users/invite",t)}async function XJ(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function eG(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var Ipe=G(()=>{"use strict"});async function tG(e,t){return e.get(`/api/v1/payments/${t}`)}async function rG(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:zt(r.currency)})}async function nG(e,t){await e.delete(`/api/v1/payments/${t}`)}function iG(e){return(t,r)=>t.post(`/api/v1/${Xbr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:zt(n.currency)}))},fTe)}var Xbr,sXr,qnt,aXr,cXr,Cpe=G(()=>{"use strict";ut();Ar();Xbr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};sXr=iG("saleBulk"),qnt=iG("saleBatch"),aXr=iG("purchaseBulk"),cXr=iG("purchaseBatch")});async function Kf(e,t,r,n,i,o=ATe){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof gr?c.status<500&&c.status!==401?Jt(c):new Gd(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof Pp?Jt(c):c}let a=s?.data;if(!i(a))throw new Gd(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function sG(e,t,r){try{Ji(e,t,r)}catch(n){throw Jt(n)}}function cE(e){return sG(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function aG(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function cG(e,t){return Kf(e,"POST",eIr,t,Ym)}async function lG(e,t,r){return Kf(e,"PUT",`/api/v1/unapplied-payments/${cE(t)}`,r,Ym)}async function uG(e,t,r){return Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/activate`,{hash:r},Ym)}async function dG(e,t,r,n){return Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/attributions`,{hash:r,attributions:n},Ym)}async function fG(e,t,r,n){return sG(n,"paymentResourceId","Pass the payment record resourceId."),Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/payments`,{hash:r,paymentResourceId:n},Ym)}async function pG(e,t,r,n){return sG(r,"childResourceId","Pass the payment record resourceId from the children list."),Kf(e,"DELETE",`/api/v1/unapplied-payments/${cE(t)}/children/${encodeURIComponent(r)}`,{hash:n},Ym)}async function hG(e,t,r){return Kf(e,"DELETE",`/api/v1/unapplied-payments/${cE(t)}`,{hash:r},Ym)}async function mG(e,t,r){return Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/unbatch`,{hash:r},Ym)}async function AG(e,t){return sG(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),Kf(e,"POST",tIr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,la)}var eIr,tIr,oG,jnt,Ynt,Ym,_pe=G(()=>{"use strict";zi();Ar();cL();ut();eIr="/api/v1/unapplied-payments",tIr="/api/v1/reconciliations/unapplied-payment",oG=["SALE","PURCHASE"],jnt=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ynt=["AMOUNT","PERCENTAGE"];Ym=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function gG(e,t,r={},n=wpe){let i=rIr.has(t)?`/api/v1/${bc(Hnt,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=xg.get(t);if(o!==void 0){if(!a)throw new he(`${t} does not take a report template. Templates apply to: ${[...xg.keys()].join(", ")}.`);let A=await bf(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...Qt,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new he(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...tN].join(", ")}.`}:d}var Hnt,rIr,wpe,tN,znt,vpe=G(()=>{"use strict";Ar();ut();HT();Qu();Hnt=["statement-of-account-export"],rIr=new Set(Hnt),wpe=9e4,tN=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),znt={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as nIr}from"node:crypto";import{writeFile as iIr,mkdir as oIr}from"node:fs/promises";import{dirname as sIr,isAbsolute as aIr,join as cIr}from"node:path";async function yG(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},Qt)}async function rN(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function Pw(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Jnt(e){return`query-export-${e.slice(0,8)}.csv`}function Spe(e){return nIr("sha256").update(e).digest("hex").slice(0,16)}async function EG(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Spe(t),o=await rN(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await Pw(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await Pw(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!aIr(r.outPath))throw new he(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??cIr(f,"Downloads",`pseudo-sql-${s}.csv`);return await oIr(sIr(p),{recursive:!0}),await iIr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function bG(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new he(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function Mw(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var Dpe=G(()=>{"use strict";ut();Ar()});async function ui(e,t,r){let n=await e.get(`/api/v1/${Rpe[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function IG(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${Rpe[r]}/${n}/attachments`,o)}async function CG(e,t,r,n){return e.delete(`/api/v1/${Rpe[t]}/${r}/attachments/${n}`)}var Rpe,nN,Hm=G(()=>{"use strict";Rpe={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders"},nN=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function mIr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&hIr.some(n=>r.startsWith(n)))}async function Zf(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&mIr(t)&&(t.refusal=pIr),t}}function Gnt(e,t,r){return Ji(e,t,r),e.toLowerCase()}function Uw(e,t){return{type:bc(Tpe,e,"entityType"),record:Gnt(t,"entityId",lIr)}}function iN(e){s7(e,"threadId",dIr)}function Vnt(e){s7(e,"commentId",fIr)}function $w(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Gnt(e.bankAccountResourceId,"bankAccountResourceId",uIr)}}async function Wnt(e,t,r,n={}){let{type:i,record:o}=Uw(t,r),s={...$w(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return Zf(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Knt(e,t,r,n,i={}){let{type:o,record:s}=Uw(t,r),a={...$w(i),limit:i.limit,offset:i.offset};return iN(n),Zf(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Znt(e,t,r,n,i){let{type:o,record:s}=Uw(t,r),a=$w(i);return n.threadId!==void 0&&iN(n.threadId),(await Zf(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...mTe,query:a}))).data}async function Xnt(e,t,r,n,i,o,s){let{type:a,record:c}=Uw(t,r),u=$w(s);return iN(n),Vnt(i),(await Zf(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function eit(e,t,r,n,i,o){let{type:s,record:a}=Uw(t,r),c=$w(o);return iN(n),Vnt(i),(await Zf(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function tit(e,t,r,n,i){let{type:o,record:s}=Uw(t,r),a=$w(i);return iN(n),(await Zf(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function rit(e,t={}){return Zf(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function nit(e,t,r){return fxe(t,"Get it from list_notifications."),(await Zf(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function iit(e){return(await Zf(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Tpe,lIr,uIr,dIr,fIr,pIr,hIr,oit=G(()=>{"use strict";zi();ut();Ar();Tpe=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],lIr="Pass the resourceId of the bill, invoice, credit note or bank record.",uIr="Pass the resourceId of the bank account that holds the bank record.",dIr="Get it from list_comment_threads.",fIr="Get it from list_comments or list_comment_threads.",pIr={code:"USER_CREDENTIAL_REQUIRED",hint:"Comments and notifications act as a user, so the credential must name an active member of the organization. A service or organization key with no user is refused with this 401. Use a user credential: sign in with `clio auth login`, a personal access token, or an API key a member created."},hIr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Bo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var qw=G(()=>{"use strict"});async function _G(e,t){return e.post("/api/v1/claims/conversion/preview",t,Qt)}async function wG(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new he('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:pL)}var oN,xpe=G(()=>{"use strict";ut();Ar();oN=["POST","POST_AND_RECORD"]});async function vG(e,t){if(!(t.amount>0))throw new he("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,pTe)}async function SG(e,t){return e.search("/api/v1/employees/payouts/search",t)}var sit,kpe=G(()=>{"use strict";ut();Ar();sit=["REIMBURSEMENT","ADVANCE"]});async function DG(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Bpe=G(()=>{"use strict"});function Npe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function Ope(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${ait(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>xu.has(u)),s=i.filter(u=>!xu.has(u)&&Cc.has(u)),a=[`Nothing here can be extracted: found ${ait(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=yke[u];d&&a.push(d)}return o.length>0&&a.push(`${KP(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${KP(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!xu.has(u)&&!Cc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${KP([...xu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function ait(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var cit=G(()=>{"use strict";ku()});function RG(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function sN(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&RG()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function lE(e,t){return{error:e,hint:t,...Fpe}}function lit(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${sN(e)}.`,...Fpe}}function uE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function zm(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${sN({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...Fpe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var Fpe,uit=G(()=>{"use strict";Fpe={kind:"validation",retriable:!1}});import{randomUUID as AIr}from"node:crypto";import{rmSync as gIr}from"node:fs";function Lpe(e){for(let t of e.tempDirs??[])try{gIr(t,{recursive:!0,force:!0})}catch{}}function fit(e){for(let[t,r]of dE)e-r.createdAt>dit&&(Lpe(r.plan),dE.delete(t))}function EIr(){Qpe||(Qpe=setInterval(()=>fit(Date.now()),yIr),Qpe.unref?.())}function Ppe(e,t){let r=Date.now();fit(r),EIr();let n=`dc_${AIr()}`;return dE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function Mpe(e,t){let r=dE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>dit?(Lpe(r.plan),dE.delete(e),null):r.plan}function pit(e,t){let r=dE.get(e);!r||r.ownerKey!==t||(Lpe(r.plan),dE.delete(e))}var dit,yIr,dE,Qpe,hit=G(()=>{"use strict";dit=1800*1e3,yIr=300*1e3,dE=new Map});function bIr(e){if(!e||typeof e!="object")return{};let t=e,r=t.validFiles?.[0],n=r?.workflowResourceId??t.workflowResourceId;return{...n?{workflowId:n}:{},...r?.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},...r?.subscriptionFBPath?{subscriptionFBPath:r.subscriptionFBPath}:{},...r?.backgroundJobFBPath?{backgroundJobFBPath:r.backgroundJobFBPath}:{}}}function mit(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>cg(i.documentType)&&r.has(i.documentType))}))}}async function Ait(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?mit(t,i):t;if(!n&&IIr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");iD(o);let a=await fM({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,...d.status==="uploaded"?bIr(d.response):{},error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function git(e,t){return(t&&t.length>0?mit(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>cg(o.documentType)).length,0)}function IIr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var yit=G(()=>{"use strict";Q7();ku();lf()});function CIr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function wIr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function vIr(e,t){if(e!==_Ir)return;let r=wIr(t);if(r)return Eit.get(r)??Eit.get(r.replace(/_ERROR$/,""))}function TG(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function SIr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=TG(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function Upe(e){return vIr(e.status,e.body)??e.refusal?.hint??SIr(e)}function fE(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function xG(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function aN(e,t={}){let r=t.readOnly===!1&&gD()?oNe:"";if(e instanceof gr){let o=[Upe(e)??CIr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...TG(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=kG(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof ht;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var _Ir,Eit,pE=G(()=>{"use strict";zi();vo();BG();mM();_Ir=422,Eit=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});async function ad(e,t,r){if(!t)return e;let n=DIr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}async function cd(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${fE(i)}`],...n}}}function DIr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function Xf(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var bit=G(()=>{"use strict";pE()});async function NG(e,t){return e.list("/api/v1/bank-rules",t)}async function cN(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function OG(e,t){return e.search("/api/v1/bank-rules/search",t)}async function FG(e,t){return e.post("/api/v1/bank-rules",t)}async function QG(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function LG(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var $pe=G(()=>{"use strict"});async function PG(e,t){return e.list("/api/v1/fixed-assets",t)}async function jw(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function MG(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function UG(e,t){return e.post("/api/v1/fixed-assets",t,CS)}async function $G(e,t,r,n){let i=n??(await jw(e,t)).data,o={};for(let s of RIr){let a=i[s];if(a==null)continue;let c=TIr.has(s)?Xd(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=t,e.put(`/api/v1/fixed-assets/${t}`,o)}async function qG(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function jG(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},CS)}async function lN(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,CS)}async function YG(e,t){return e.post("/api/v1/transfer-fixed-assets",t,CS)}async function HG(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function zG(e,t){return So(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var hE,RIr,TIr,JG=G(()=>{"use strict";Cn();xS();Ar();hE=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];RIr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],TIr=new Set(["purchaseDate","depreciationStartDate"])});async function GG(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function mE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function VG(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Mp)}async function WG(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await mE(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw xIr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function xIr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function KG(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function ZG(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function XG(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var eV=G(()=>{"use strict";Ar()});async function tV(e,t){return e.list("/api/v1/contact-groups",t)}async function rV(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function nV(e,t){return e.search("/api/v1/contact-groups/search",t)}async function iV(e,t){return e.post("/api/v1/contact-groups",t)}async function oV(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,dI(r,JK))}async function sV(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var qpe=G(()=>{"use strict";Cn()});async function aV(e,t){return e.list("/api/v1/inventory-items",t)}async function cV(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function lV(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function dV(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&kIr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var uV,kIr,jpe=G(()=>{"use strict";zi();uV=["ALL","AVAILABLE","FULLY_DRAWN"],kIr=/Inventory balance Not Found/i});async function fV(e,t){return e.list("/api/v1/custom-fields",t)}async function uN(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function pV(e,t){return e.search("/api/v1/custom-fields/search",t)}async function hV(e,t){return e.post("/api/v1/custom-fields",t)}function NIr(e){return e!==void 0&&BIr.every(t=>e[t]!==void 0)}function OIr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function FIr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function mV(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!NIr(n.appliesTo)){let i=await uN(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??FIr(i.data),n.appliesTo={...OIr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function AV(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var BIr,Ype=G(()=>{"use strict";BIr=["invoices","bills","customerCredits","supplierCredits","payments"]});var Gc,AE,QIr,LIr,Hpe,gV,yV,PIr,Ia,Wl,gE,Yw,yE,zpe=G(()=>{"use strict";Gc={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217). Required whenever this settings object is sent."}},required:["sourceCurrencyCode"]},AE={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field. Required unless resourceId is given; when resourceId is given, the organization's own name for that field is stored instead of this one."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition. Required unless customFieldName is given. When omitted, the field is matched by customFieldName (case-insensitive) and linked only if exactly one active custom field in the organization has that name."}}},QIr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},LIr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},Hpe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},gV={type:"object",properties:{billingAddress:{...Hpe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},yV={type:"object",properties:{billingAddress:{...Hpe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...Hpe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},PIr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Ia={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:PIr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},Wl={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},gE={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},Yw={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:AE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...QIr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...LIr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...gV,description:"Issuer identity and billing address (credit from)."},creditTo:{...yV,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:AE},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...gV,description:"Seller identity and billing address."},billTo:{...yV,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:AE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:AE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...gV,description:"Seller identity and billing address."},billTo:{...yV,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:AE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...gV,description:"Seller identity and billing address."},billTo:{...yV,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:AE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:AE},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},yE={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}}}});function Gpe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function Vpe(e){let t=e.updated??[],r=Gpe(e.failed);return{...t.length===0&&r.length>0?{error:$Ir}:{},updated:t,failed:r}}function Cit(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function EV(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _it(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=Cit(s);if(a)for(let c of Array.isArray(o)?o:[o])EV(c)&&n.push(..._it(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function qIr(e){return Object.entries(e).map(([t,r])=>{let n=Cit(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function Wpe(e,t,r){if(!EV(t))return;let n=_it(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw Jt(new ht(`${e} has no field ${i.join("; ")}. Fields: ${qIr(r)}. Nothing was changed.`))}function jIr(e){let t=Yw[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function YIr(e){let t=yE[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function HIr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!EV(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw Jt(new ht(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!EV(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw Jt(new ht(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));Wpe(`${e} line items`,a.attributes,t.fields)}}}function wit(e){if(Hw.includes(e))return;let t=IV.includes(e);throw Jt(new ht(t?`${e} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${e} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${e} has no quick fix route. Transaction-level entities: ${Hw.join(", ")}.`))}async function Jw(e,t,r){wit(t),Wpe(`${t} quick fix`,r.attributes,jIr(t));let n=await e.post(`/api/v1/quick-fix/${bc(Hw,t)}`,r);return Vpe(n)}async function zIr(e,t){try{return await oE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return sE(e,t);throw r}}async function vit(e,t,r,n){wit(t);let i=Kpe[t],o=async d=>i.tags(await ef(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Iit)s.push(...await Promise.all(r.resourceIds.slice(d,d+Iit).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=Du(s[f],n),h=JSON.stringify(p);a.set(h,{tags:p,resourceIds:[...a.get(h)?.resourceIds??[],d]})});let c=[],u=[];for(let{tags:d,resourceIds:f}of a.values())try{let p=await Jw(e,t,{resourceIds:f,attributes:{...r.attributes,tags:d}});c.push(...p.updated),u.push(...p.failed)}catch(p){if(c.length===0)throw p;u.push(...f.map(h=>({resourceId:h,error:p instanceof Error?p.message:String(p)})))}return Vpe({updated:c,failed:u})}async function dN(e,t,r){let n=bc(zw,t),i=YIr(t);i.entryKeys?HIr(t,i,r.schedulerUpdates):Wpe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return Vpe(o)}var MIr,UIr,bV,IV,Hw,zw,$Ir,EE,Jpe,Kpe,Iit,CV=G(()=>{"use strict";zi();ut();vo();zpe();SI();kg();Zd();KT();nx();Bg();SJ();PJ();eV();MIr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],UIr=["journals","cash-entries"],bV=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],IV=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],Hw=[...MIr,...UIr,...bV],zw=[...Hw,...IV],$Ir="Nothing changed: every record failed. See failed for each reason.";EE=e=>e?.tags,Jpe=e=>e?.data?.tags,Kpe={invoices:{noun:"invoice",get:(e,t)=>uo(e,t),tags:EE},bills:{noun:"bill",get:(e,t)=>oo(e,t),tags:EE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>$s(e,t),tags:EE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>qs(e,t),tags:EE},journals:{noun:"journal",get:(e,t)=>gs(e,t),tags:EE},"cash-entries":{noun:"cash entry",get:(e,t)=>zIr(e,t),tags:EE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Nw(e,t),tags:Jpe},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Ow(e,t),tags:Jpe},"subscription-schedules":{noun:"subscription",get:(e,t)=>mE(e,t),tags:Jpe},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Fw(e,t),tags:EE}},Iit=10});function _V(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=_V(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<GIr&&i.length<=VIr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,_V(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function Dit(e,t,r){let n=WIr(t);if(!n)return[];let i=KIr(r);if(!i){if(Sit[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?Dit(o,s,i[o]):[])}function ZIr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function Zpe(e,t,r={}){let n=Object.keys(e),i=[...new Set(n.flatMap(c=>Object.keys(e[c])))].sort(),o={},s=new Map;for(let c of i){let u=n.filter(y=>e[y][c]),d=new Map;for(let y of u){let b=XIr(e[y][c]);d.set(b,[...d.get(b)??[],y])}let[[,f],...p]=[...d].sort((y,b)=>b[1].length-y[1].length),{description:h,...m}=r[c]??_V(e[f[0]][c]),A=p.length&&m.properties&&!r[c]?{...m,required:void 0,properties:Object.assign({},...[f,...p.map(([,y])=>y)].map(y=>_V(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[Sit[c],ZIr(u,n),...p.map(([,y])=>{let b=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(b.properties??b.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[b,E]of Dit(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(b))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function kit(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>JIr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var JIr,Sit,GIr,VIr,WIr,KIr,XIr,eCr,tCr,Gw,Rit,Tit,xit,Bit,Nit,Oit,Xpe=G(()=>{"use strict";zpe();SI();JIr={valueDate:"date",dueDate:"due date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},Sit={currencySettings:"sourceCurrencyCode alone takes the platform rate (not on schedules); add rateFunctionalToSource to set one.",taxCurrencySettings:"Cash entries: sourceCurrency; every other record: sourceCurrencyCode, always sent.",tags:`${Ua.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}."},GIr=2,VIr=8;WIr=e=>e.properties??e.items?.properties,KIr=e=>e.properties??e.items?.properties;XIr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),eCr={tags:Ua};tCr=Object.entries(yE).filter(([,e])=>!e.entryKeys),Gw=Object.entries(yE).filter(([,e])=>e.entryKeys),Rit=Zpe({...Yw},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",eCr),Tit=Zpe(Object.fromEntries(tCr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),xit=(()=>{let e=n=>Gw.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=Gw[0],r=[...new Set(Gw.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>Gw.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${Gw.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:Zpe(Object.fromEntries(Gw.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Bit=[...new Set([...Object.keys(Yw),...Object.keys(yE)])].map(e=>e.replace(/-/g," ")).join(", "),Nit=kit(Object.values(Yw)),Oit=kit(Object.values(yE).map(e=>e.fields))});function wV(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var ehe=G(()=>{"use strict"});function SV(){return Jm.map(e=>`${e} sets ${Ww[e].change.join(", ")}`).join("; ")}function qit(e){let t={};for(let r of e)t[r]=Object.hasOwn(Qit,r)?Qit[r]:iCr.find(([n])=>n.test(r))?.[1]??oCr;return Object.keys(t).length>0?t:void 0}function jit(e){if(!(e instanceof gr)||!e.endpoint.startsWith(nCr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Lit,n))return;let{hint:i,repairTool:o,command:s}=Lit[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Uit.LINE_ITEMS?"line items":"records",...e.endpoint===vV?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function cCr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function lCr(e){return typeof e=="string"&&Jm.includes(e)}function uCr(e,t){if(!lCr(e))throw new ht(`level must be one of ${Jm.join(", ")}.`);let r=Jm.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))Ww[e][i].includes(s)||n.push(Ww[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=Ww[e];throw new ht(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Pit(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new ht(`${e} must be a JSON object, not ${n}.`)}async function RV(e,t,r){let n={filter:Pit("filter",r.filter),change:Pit("change",r.change)};uCr(t,n);let i;try{i=await e.post(Uit[t],{filter:n.filter,change:n.change},Qt)}catch(u){throw jit(u),u}let{data:o,...s}=i,a=qit([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=cCr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function rhe(e,t){return{error:`${t} ${Hit}`,outcome:"UNKNOWN",previewId:e,next:Yit}}function pCr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return rhe(e,"The apply answered without a per-record result.");let i=Gpe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=qit(Object.keys(o)),a=o[sCr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:fCr}:a==="UNKNOWN"?{error:Hit}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Yit:dCr},failed:i.slice(0,the),...i.length>the?{failedNotShown:i.length-the}:{},data:r}}async function TV(e,t,r=aCr){let n;try{n=await e.post(vV,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=jit(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw Jt(i);return rhe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof Pp)throw Jt(i);let o=i instanceof Error?i.message:String(i);return rhe(t,`No answer arrived from the apply (${o}).`)}return pCr(t,n)}var Mit,Jm,Uit,vV,nCr,$it,Fit,Ww,Qit,iCr,oCr,sCr,aCr,DV,the,Kw,$en,Vw,Lit,Yit,dCr,fCr,Hit,nhe=G(()=>{"use strict";zi();CV();cL();ut();vo();Ar();ehe();Mit=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],Jm=["TRANSACTIONS","LINE_ITEMS"],Uit={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},vV="/api/v1/ledger/find-fix/apply",nCr=vV.slice(0,vV.lastIndexOf("/")+1),$it={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},Fit=["types","resourceIds","reference","valueDate","contactResourceId"],Ww={TRANSACTIONS:{filter:Fit,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Fit,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Qit={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},iCr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],oCr="Not described by this client version; read the records that carry it.";sCr="OUTCOME_UNKNOWN",aCr=25e3,DV=3e5,the=50,Kw=12,$en=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${Kw}}(?![A-Za-z0-9_-])`,"i"),Vw=e=>e.resourceId?` (${e.resourceId})`:"",Lit={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${Vw(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${Vw(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${Vw(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${Vw(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${Vw(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${Vw(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};Yit="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",dCr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",fCr="Nothing changed: every record in the preview failed.",Hit="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function xV(e,t){return e.list("/api/v1/nano-classifiers",t)}async function bE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function kV(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function fN(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function pN(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function BV(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await hCr(e,t):{};let{data:n}=await bE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Jit(n)}async function hCr(e,t){let{data:r}=await bE(e,t);return Jit(r)}function Jit(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function NV(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var zit,ihe=G(()=>{"use strict";zit=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function OV(e,t){return e.post("/api/v1/export-records",t,Qt)}async function FV(e,t){return e.post("/api/v1/export-records/preview",t,Qt)}async function QV(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var ohe=G(()=>{"use strict";Ar()});function LV(e,t){if(!t.has(e))throw new he(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Kit(e,t,r,n=!1){if(!Array.isArray(e))throw new he(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new he(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new he(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new he(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function PV(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function MV(e,t,r){return LV(t,Vit),Ji(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${bc(ep,t)}/${encodeURIComponent(r)}/approve`,void 0,uTe)}async function UV(e,t,r){return LV(t,Vit),Kit(r,mCr,"bulk approve",!0),r.forEach(n=>Ji(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${bc(ep,t)}/bulk-approve`,{resourceIds:r},dTe)}async function $V(e,t,r,n){LV(t,Wit),Ji(r,"resourceId","Pass the document resourceId."),Zit(n);let i=await e.post(`/api/v1/${bc(IE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:yCr(i)}}}async function qV(e,t,r,n){return LV(t,Wit),Zit(n),Kit(r,ACr,"bulk request changes"),r.forEach(i=>Ji(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(gCr(t),{resourceIds:r,message:n})}function gCr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${bc(Git,e)}/bulk-request-changes`}function Zit(e){if(!e||e.trim().length===0)throw new he("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function yCr(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ep,Git,IE,Vit,Wit,mCr,ACr,she=G(()=>{"use strict";ut();Ar();ep=["invoices","bills","customer-credit-notes","supplier-credit-notes"],Git=[...ep,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],IE=[...Git,"claims"],Vit=new Set(ep),Wit=new Set(IE);mCr=100,ACr=500});function ECr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${Xit(t)}:${Xit(r)}:${n}`}function Xit(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function ahe(e){if(!eot.has(e))throw new he(`unknown entity "${e}" \u2014 expected one of ${[...eot].join(", ")}`)}async function tot(e,t,r){return ahe(t),Ji(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function rot(e,t,r,n){return ahe(t),Ji(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function not(e,t,r,n,i){if(ahe(t),Ji(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new he('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??ECr(t,r,n)}})}async function iot(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var eot,oot=G(()=>{"use strict";ut();eot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function Zw(e){Ut(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new he(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!eNe(n.btResourceId))throw new he(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!bCr.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new he(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function jV(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},Qt);return{data:CCr(r.data)}}function ICr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function CCr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(ICr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function YV(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function HV(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var bCr,che=G(()=>{"use strict";ut();L7();Cn();Ar();bCr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function lot(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new he("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function lhe(e,t){if(!e||typeof e!="object")throw new he(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new he(`${t}.lineItems array is empty.`);if(n.length>500)throw new he(`max 500 ${t}.lineItems per call.`);Cl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&Cl([i],["valueDate"])}async function JV(e,t,r=uhe){return e.post("/api/v1/search-magic-reconciliation",t,{...Qt,timeoutMs:r})}function zV(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function SCr(e){let t=zV(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=zV(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function DCr(e){return e?e.value>=(e.from==="confidenceScore"?_Cr:wCr)?"high":e.value>=vCr?"medium":"low":"low"}function TCr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(sot,t))return;let r=sot[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function Gm(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function aot(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function xCr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>aot({account:Gm(n?.account),taxProfile:Gm(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!Gm(e.contact)&&!Gm(e.account)&&!Gm(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return aot({contact:Gm(e.contact),account:Gm(e.account),taxProfile:Gm(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function uot(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>FCr(c,h??{},u.length-1,t)).sort(kCr),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function kCr(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function BCr(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return Ec.test(t)?t:void 0}function NCr(e){let{recommendationId:t,...r}=e;return r}function OCr(e,t,r){return!t||!r?t:e===CE.learnedPrediction?{...t,recommendationId:r}:e===CE.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function FCr(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=zV(t.matchScore),s=zV(t.confidenceScore),a=SCr(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=CE.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=CE.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let O=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,J=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,Y=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;O&&J&&Y&&(m=CE.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:O,predictedPayload:J,predictedPayloadSchemaVersion:Y});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let O=t.actionShortcut??{},J=typeof O.resourceId=="string"?O.resourceId:void 0;J&&(m=CE.applyBankRule,A={actionShortcutResourceId:J,businessTransactionResourceIds:[e]});break}default:break}let g=OCr(m,A,BCr(t)),y=m?DCr(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==CE.withPayments||b,T=TCr(t),R=!m||!g?"NO_PLAN":T?RCr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",B=xCr(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:g,confidenceTier:y,autoCommitEligible:R===void 0,...R?{checkpointReason:R}:{},...B?{proposedPosting:B}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:T===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(NCr(t))}`}}function QCr(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function LCr(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await oo(e,i):await uo(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${fE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function dot(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,cot);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await UI(e,t,{filter:{resourceId:{in:u}},limit:cot}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${fE(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return QCr(u,f,await LCr(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function GV(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,la)}async function VV(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,la)}async function WV(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,la)}async function KV(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,la)}async function ZV(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,la)}async function XV(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,la)}async function e8(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,la)}async function t8(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,la)}async function r8(e,t){return e.post("/api/v1/reconciliations/with-payments",t,la)}async function n8(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,la)}async function i8(e,t){return e.post("/api/v1/reconciliations/magic-match",t,la)}async function o8(e,t){return e.post("/api/v1/reconciliations/reset",t)}var CE,uhe,_Cr,wCr,vCr,RCr,sot,cot,s8=G(()=>{"use strict";pg();pE();ut();Zd();Cn();kg();Ar();CE={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},uhe=6e4;_Cr=.9,wCr=.95,vCr=.7;RCr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},sot={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};cot=25});function Ws(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function No(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:dhe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=dhe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=dhe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function dhe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function Jo(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ws(e,t,n),a=No(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var Ca,Vc,go,Kl,fot=G(()=>{"use strict";Ca=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],Vc=[...Ca],go=Ca.filter(e=>e.field!=="dueDate"),Kl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function ld(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=gc(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function a8(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=mI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var pot=G(()=>{"use strict";$p()});var fhe=G(()=>{"use strict";fot();$p();pot()});var hN,c8,Go,_a,phe=G(()=>{"use strict";hN="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",c8=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],Go="If the result says it runs in the background, do not poll: its result arrives by itself.",_a=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${Go} PARTIAL_SUCCESS: errorDetails.`});function hot(e){return PCr.get(e)}function mot(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!l8.has(o));return n.length===0?[]:Ni.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Ni,l8,PCr,ud=G(()=>{"use strict";phe();Xpe();Ni=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Thirteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Tracking categories (nano classifiers; dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"],channelToolsDescription:"Check the progress of background tasks a request started, add to a waiting one, or cancel it."},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${Bit}. On a record: ${Nit}. On lines: ${Oit}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${c8.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"collaboration",title:"Collaboration",description:"Comment threads on bills, invoices, credit notes and bank records: list threads and comments, add a reply or start a thread, mention a teammate, update or delete your own comment, resolve a thread. Notifications: list unread mentions and comments, mark one read or unread, mark all read.",groups:["collaboration"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],l8=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),PCr=new Map(Ni.flatMap(e=>e.groups.map(t=>[t,e.name])))});function dd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function MCr(e){let t=Aot.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(dd(r),n);for(let r of e.enum??[])t.set(dd(r),r);Aot.set(e,t)}return t}function got(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=dd(e);if(!r)return null;let n=MCr(t).get(r);return n!==void 0&&n!==e?n:null}function UCr(e){let t=yot.get(e);return t||(t=new Map(Object.keys(e).map(r=>[dd(r),r])),yot.set(e,t)),t}function $Cr(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function qCr(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function hhe(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=UCr(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=dd(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?$Cr(d):qCr(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=got(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=got(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=z7(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=hhe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=hhe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Eot(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:hhe(t,e.params,"",r),coercions:r}}function bot(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var Aot,yot,mhe=G(()=>{"use strict";DM();Aot=new WeakMap;yot=new WeakMap});function Xw(e){let t=new Set,r=[];for(let n of e)for(let i of Zl(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function mN(){return Ni.map(e=>{let t=Xw(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function jCr(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function YCr(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function Vm(e,t=!1){let r=Wm(void 0).length,n=Ni.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:YCr(r)}:e&&i!==void 0?{packaging:jCr(e,i,r)}:{},map:mN(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var u8=G(()=>{"use strict";ud();Xl()});function d8(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=d8(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=d8(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function eu(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=d8(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function AN(e){return{name:e.name,description:e.description,input_schema:eu(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var ev=G(()=>{"use strict"});function gN(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function Ahe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function f8(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&gN(e),idempotentHint:e.readOnly,openWorldHint:Ahe(e)}}function zCr(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function JCr(e){let t=zCr(e);return!t||HCr.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!l8.has(n)).length===0}function ghe(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function yhe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?yhe(o,`${i}.`):[]]})}function VCr(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
662
|
+
`)),null)}catch{return null}}async function ZB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??xbr,c=n.minBm25??kbr;if(i==="bm25"||!t)return aE(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await dpe(r);return m?_nt(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):aE(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([dpe(r),Promise.resolve(aE(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=_nt(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Snt(p,h,o)}function _nt(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=wnt(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Snt(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(bnt+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(bnt+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function fpe(e){return e!==null&&!!vnt()}var Rbr,Tbr,bnt,xbr,kbr,UJ,Int,$J,Cnt,qJ=G(()=>{"use strict";WB();Rbr="text-embedding-3-small",Tbr=2e3,bnt=60,xbr=.3,kbr=1.5,UJ=null,Int=null,$J=null,Cnt=!1});async function Dnt(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=GB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:KB(),u=await ZB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(lpe(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Rnt(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:Nbr}async function jJ(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Rnt())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(Obr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return Fbr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function Fbr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function ppe(e,t={}){return process.env.CLIO_DAEMON==="1"||VB()?Dnt(e,t):jJ(e,t)}var Nbr,Obr,Tnt=G(()=>{"use strict";WB();qJ();Nbr="https://mcp.jaz.ai/help-center/search",Obr=4e3});var hpe=G(()=>{"use strict";WB();qJ();Tnt();WB()});async function qm(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function jm(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var XB=G(()=>{"use strict";Cn()});async function YJ(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:zt(t.currency),taxCurrency:zt(t.taxCurrency)},gTe)}var mpe=G(()=>{"use strict";ut();Ar()});async function HJ(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function zJ(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function eN(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function JJ(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Ape=G(()=>{"use strict"});function Qbr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Qw(e,t){return e.post("/api/v1/jots",{entries:t.map(Qbr)})}async function GJ(e,t){return e.post("/api/v1/jots/search",t,Qt)}async function xnt(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var VJ=G(()=>{"use strict";Ar()});async function knt(e,t){return e.post("/api/v1/agents/memories",t)}async function gpe(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Bnt=G(()=>{"use strict";Ar()});function WJ(){return process.env.ENABLE_MEMORY==="true"}function ype(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Nnt(e){return!WJ()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Epe=G(()=>{"use strict"});import{createHash as Lbr}from"node:crypto";function Gbr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:Qnt.some(r=>t.includes(r))?[null,"directive_invalid"]:Fnt.test(t)?[null,"directive_invalid"]:jbr.test(t)?[null,"directive_contains_url"]:Ybr.test(t)?[null,"directive_contains_email"]:[t,null]}function Vbr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>Hbr?[null,"match_condition_too_long"]:Qnt.some(r=>t.includes(r))?[null,"match_condition_invalid"]:Fnt.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function Wbr(e){return e==null?[null,null]:Number.isInteger(e)?e<zbr||e>Jbr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function Kbr(e,t,r,n,i,o,s,a){if(e)return Lbr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function Zbr(e){Promise.resolve().then(()=>(GS(),JS)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Unt(e,t,r){let n=t.action,i=t.category,o=$br[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(Zbr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Nnt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>Pbr||!qbr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=Gbr(t.directive);if(E)return u(E);p=b;let[C,w]=Wbr(t.importance);if(w)return u(w);h=C}let[m,A]=Vbr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=Mbr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,Ubr));let E=Kbr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await bpe(()=>knt(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await bpe(()=>gpe(e.client,b))}else{let b={forgetAll:!0};y=await bpe(()=>gpe(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function bpe(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof gr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var Fnt,Qnt,Pbr,Mbr,Ubr,Lnt,Pnt,Mnt,$br,qbr,jbr,Ybr,Hbr,zbr,Jbr,$nt=G(()=>{"use strict";Bnt();zi();Epe();Epe();Fnt=/[\x00-\x1f\x7f]/,Qnt=["{{","}}","```","<",">"],Pbr=120,Mbr=3,Ubr=140,Lnt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Pnt=["set","forget","forget_all"],Mnt=["this_org","all_orgs"],$br={this_org:"ORG_USER",all_orgs:"USER"},qbr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,jbr=/https?:\/\//i,Ybr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Hbr=255,zbr=0,Jbr=100});async function KJ(e,t){return e.list("/api/v1/organization-users",t)}async function ZJ(e,t){return e.search("/api/v1/organization-users/search",t)}async function Lw(e,t){return e.post("/api/v1/organization-users/invite",t)}async function XJ(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function eG(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var Ipe=G(()=>{"use strict"});async function tG(e,t){return e.get(`/api/v1/payments/${t}`)}async function rG(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:zt(r.currency)})}async function nG(e,t){await e.delete(`/api/v1/payments/${t}`)}function iG(e){return(t,r)=>t.post(`/api/v1/${Xbr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:zt(n.currency)}))},fTe)}var Xbr,sXr,qnt,aXr,cXr,Cpe=G(()=>{"use strict";ut();Ar();Xbr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};sXr=iG("saleBulk"),qnt=iG("saleBatch"),aXr=iG("purchaseBulk"),cXr=iG("purchaseBatch")});async function Kf(e,t,r,n,i,o=ATe){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof gr?c.status<500&&c.status!==401?Jt(c):new Gd(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof Pp?Jt(c):c}let a=s?.data;if(!i(a))throw new Gd(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function sG(e,t,r){try{Ji(e,t,r)}catch(n){throw Jt(n)}}function cE(e){return sG(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function aG(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function cG(e,t){return Kf(e,"POST",eIr,t,Ym)}async function lG(e,t,r){return Kf(e,"PUT",`/api/v1/unapplied-payments/${cE(t)}`,r,Ym)}async function uG(e,t,r){return Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/activate`,{hash:r},Ym)}async function dG(e,t,r,n){return Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/attributions`,{hash:r,attributions:n},Ym)}async function fG(e,t,r,n){return sG(n,"paymentResourceId","Pass the payment record resourceId."),Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/payments`,{hash:r,paymentResourceId:n},Ym)}async function pG(e,t,r,n){return sG(r,"childResourceId","Pass the payment record resourceId from the children list."),Kf(e,"DELETE",`/api/v1/unapplied-payments/${cE(t)}/children/${encodeURIComponent(r)}`,{hash:n},Ym)}async function hG(e,t,r){return Kf(e,"DELETE",`/api/v1/unapplied-payments/${cE(t)}`,{hash:r},Ym)}async function mG(e,t,r){return Kf(e,"POST",`/api/v1/unapplied-payments/${cE(t)}/unbatch`,{hash:r},Ym)}async function AG(e,t){return sG(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),Kf(e,"POST",tIr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,la)}var eIr,tIr,oG,jnt,Ynt,Ym,_pe=G(()=>{"use strict";zi();Ar();cL();ut();eIr="/api/v1/unapplied-payments",tIr="/api/v1/reconciliations/unapplied-payment",oG=["SALE","PURCHASE"],jnt=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ynt=["AMOUNT","PERCENTAGE"];Ym=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function gG(e,t,r={},n=wpe){let i=rIr.has(t)?`/api/v1/${bc(Hnt,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=xg.get(t);if(o!==void 0){if(!a)throw new he(`${t} does not take a report template. Templates apply to: ${[...xg.keys()].join(", ")}.`);let A=await bf(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...Qt,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new he(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...tN].join(", ")}.`}:d}var Hnt,rIr,wpe,tN,znt,vpe=G(()=>{"use strict";Ar();ut();HT();Qu();Hnt=["statement-of-account-export"],rIr=new Set(Hnt),wpe=9e4,tN=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),znt={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as nIr}from"node:crypto";import{writeFile as iIr,mkdir as oIr}from"node:fs/promises";import{dirname as sIr,isAbsolute as aIr,join as cIr}from"node:path";async function yG(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},Qt)}async function rN(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function Pw(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Jnt(e){return`query-export-${e.slice(0,8)}.csv`}function Spe(e){return nIr("sha256").update(e).digest("hex").slice(0,16)}async function EG(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Spe(t),o=await rN(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await Pw(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await Pw(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!aIr(r.outPath))throw new he(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??cIr(f,"Downloads",`pseudo-sql-${s}.csv`);return await oIr(sIr(p),{recursive:!0}),await iIr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function bG(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new he(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function Mw(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var Dpe=G(()=>{"use strict";ut();Ar()});async function ui(e,t,r){let n=await e.get(`/api/v1/${Rpe[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function IG(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${Rpe[r]}/${n}/attachments`,o)}async function CG(e,t,r,n){return e.delete(`/api/v1/${Rpe[t]}/${r}/attachments/${n}`)}var Rpe,nN,Hm=G(()=>{"use strict";Rpe={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders"},nN=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function mIr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&hIr.some(n=>r.startsWith(n)))}async function Zf(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&mIr(t)&&(t.refusal=pIr),t}}function Gnt(e,t,r){return Ji(e,t,r),e.toLowerCase()}function Uw(e,t){return{type:bc(Tpe,e,"entityType"),record:Gnt(t,"entityId",lIr)}}function iN(e){s7(e,"threadId",dIr)}function Vnt(e){s7(e,"commentId",fIr)}function $w(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Gnt(e.bankAccountResourceId,"bankAccountResourceId",uIr)}}async function Wnt(e,t,r,n={}){let{type:i,record:o}=Uw(t,r),s={...$w(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return Zf(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Knt(e,t,r,n,i={}){let{type:o,record:s}=Uw(t,r),a={...$w(i),limit:i.limit,offset:i.offset};return iN(n),Zf(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Znt(e,t,r,n,i){let{type:o,record:s}=Uw(t,r),a=$w(i);return n.threadId!==void 0&&iN(n.threadId),(await Zf(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...mTe,query:a}))).data}async function Xnt(e,t,r,n,i,o,s){let{type:a,record:c}=Uw(t,r),u=$w(s);return iN(n),Vnt(i),(await Zf(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function eit(e,t,r,n,i,o){let{type:s,record:a}=Uw(t,r),c=$w(o);return iN(n),Vnt(i),(await Zf(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function tit(e,t,r,n,i){let{type:o,record:s}=Uw(t,r),a=$w(i);return iN(n),(await Zf(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function rit(e,t={}){return Zf(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function nit(e,t,r){return fxe(t,"Get it from list_notifications."),(await Zf(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function iit(e){return(await Zf(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Tpe,lIr,uIr,dIr,fIr,pIr,hIr,oit=G(()=>{"use strict";zi();ut();Ar();Tpe=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],lIr="Pass the resourceId of the bill, invoice, credit note or bank record.",uIr="Pass the resourceId of the bank account that holds the bank record.",dIr="Get it from list_comment_threads.",fIr="Get it from list_comments or list_comment_threads.",pIr={code:"USER_CREDENTIAL_REQUIRED",hint:"Comments and notifications act as a user, so the credential must name an active member of the organization. A service or organization key with no user is refused with this 401. Use a user credential: sign in with `clio auth login`, a personal access token, or an API key a member created."},hIr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Bo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var qw=G(()=>{"use strict"});async function _G(e,t){return e.post("/api/v1/claims/conversion/preview",t,Qt)}async function wG(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new he('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:pL)}var oN,xpe=G(()=>{"use strict";ut();Ar();oN=["POST","POST_AND_RECORD"]});async function vG(e,t){if(!(t.amount>0))throw new he("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,pTe)}async function SG(e,t){return e.search("/api/v1/employees/payouts/search",t)}var sit,kpe=G(()=>{"use strict";ut();Ar();sit=["REIMBURSEMENT","ADVANCE"]});async function DG(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Bpe=G(()=>{"use strict"});function Npe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function Ope(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${ait(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>xu.has(u)),s=i.filter(u=>!xu.has(u)&&Cc.has(u)),a=[`Nothing here can be extracted: found ${ait(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=yke[u];d&&a.push(d)}return o.length>0&&a.push(`${KP(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${KP(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!xu.has(u)&&!Cc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${KP([...xu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function ait(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var cit=G(()=>{"use strict";ku()});function RG(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function sN(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&RG()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function lE(e,t){return{error:e,hint:t,...Fpe}}function lit(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${sN(e)}.`,...Fpe}}function uE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function zm(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${sN({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...Fpe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var Fpe,uit=G(()=>{"use strict";Fpe={kind:"validation",retriable:!1}});import{randomUUID as AIr}from"node:crypto";import{rmSync as gIr}from"node:fs";function Lpe(e){for(let t of e.tempDirs??[])try{gIr(t,{recursive:!0,force:!0})}catch{}}function fit(e){for(let[t,r]of dE)e-r.createdAt>dit&&(Lpe(r.plan),dE.delete(t))}function EIr(){Qpe||(Qpe=setInterval(()=>fit(Date.now()),yIr),Qpe.unref?.())}function Ppe(e,t){let r=Date.now();fit(r),EIr();let n=`dc_${AIr()}`;return dE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function Mpe(e,t){let r=dE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>dit?(Lpe(r.plan),dE.delete(e),null):r.plan}function pit(e,t){let r=dE.get(e);!r||r.ownerKey!==t||(Lpe(r.plan),dE.delete(e))}var dit,yIr,dE,Qpe,hit=G(()=>{"use strict";dit=1800*1e3,yIr=300*1e3,dE=new Map});function bIr(e){if(!e||typeof e!="object")return{};let t=e,r=t.validFiles?.[0],n=r?.workflowResourceId??t.workflowResourceId;return{...n?{workflowId:n}:{},...r?.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},...r?.subscriptionFBPath?{subscriptionFBPath:r.subscriptionFBPath}:{},...r?.backgroundJobFBPath?{backgroundJobFBPath:r.backgroundJobFBPath}:{}}}function mit(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>cg(i.documentType)&&r.has(i.documentType))}))}}async function Ait(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?mit(t,i):t;if(!n&&IIr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");iD(o);let a=await fM({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,...d.status==="uploaded"?bIr(d.response):{},error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function git(e,t){return(t&&t.length>0?mit(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>cg(o.documentType)).length,0)}function IIr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var yit=G(()=>{"use strict";Q7();ku();lf()});function CIr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function wIr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function vIr(e,t){if(e!==_Ir)return;let r=wIr(t);if(r)return Eit.get(r)??Eit.get(r.replace(/_ERROR$/,""))}function TG(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function SIr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=TG(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function Upe(e){return vIr(e.status,e.body)??e.refusal?.hint??SIr(e)}function fE(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function xG(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function aN(e,t={}){let r=t.readOnly===!1&&gD()?oNe:"";if(e instanceof gr){let o=[Upe(e)??CIr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...TG(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=kG(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof ht;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var _Ir,Eit,pE=G(()=>{"use strict";zi();vo();BG();mM();_Ir=422,Eit=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});async function ad(e,t,r){if(!t)return e;let n=DIr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}async function cd(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${fE(i)}`],...n}}}function DIr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function Xf(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var bit=G(()=>{"use strict";pE()});async function NG(e,t){return e.list("/api/v1/bank-rules",t)}async function cN(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function OG(e,t){return e.search("/api/v1/bank-rules/search",t)}async function FG(e,t){return e.post("/api/v1/bank-rules",t)}async function QG(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function LG(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var $pe=G(()=>{"use strict"});async function PG(e,t){return e.list("/api/v1/fixed-assets",t)}async function jw(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function MG(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function UG(e,t){return e.post("/api/v1/fixed-assets",t,CS)}async function $G(e,t,r,n){let i=n??(await jw(e,t)).data,o={};for(let s of RIr){let a=i[s];if(a==null)continue;let c=TIr.has(s)?Xd(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=t,e.put(`/api/v1/fixed-assets/${t}`,o)}async function qG(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function jG(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},CS)}async function lN(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,CS)}async function YG(e,t){return e.post("/api/v1/transfer-fixed-assets",t,CS)}async function HG(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function zG(e,t){return So(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var hE,RIr,TIr,JG=G(()=>{"use strict";Cn();xS();Ar();hE=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];RIr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],TIr=new Set(["purchaseDate","depreciationStartDate"])});async function GG(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function mE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function VG(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Mp)}async function WG(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await mE(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw xIr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function xIr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function KG(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function ZG(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function XG(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var eV=G(()=>{"use strict";Ar()});async function tV(e,t){return e.list("/api/v1/contact-groups",t)}async function rV(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function nV(e,t){return e.search("/api/v1/contact-groups/search",t)}async function iV(e,t){return e.post("/api/v1/contact-groups",t)}async function oV(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,dI(r,JK))}async function sV(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var qpe=G(()=>{"use strict";Cn()});async function aV(e,t){return e.list("/api/v1/inventory-items",t)}async function cV(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function lV(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function dV(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&kIr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var uV,kIr,jpe=G(()=>{"use strict";zi();uV=["ALL","AVAILABLE","FULLY_DRAWN"],kIr=/Inventory balance Not Found/i});async function fV(e,t){return e.list("/api/v1/custom-fields",t)}async function uN(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function pV(e,t){return e.search("/api/v1/custom-fields/search",t)}async function hV(e,t){return e.post("/api/v1/custom-fields",t)}function NIr(e){return e!==void 0&&BIr.every(t=>e[t]!==void 0)}function OIr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function FIr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function mV(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!NIr(n.appliesTo)){let i=await uN(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??FIr(i.data),n.appliesTo={...OIr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function AV(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var BIr,Ype=G(()=>{"use strict";BIr=["invoices","bills","customerCredits","supplierCredits","payments"]});var Gc,AE,QIr,LIr,Hpe,gV,yV,PIr,Ia,Wl,gE,Yw,yE,zpe=G(()=>{"use strict";Gc={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217). Required whenever this settings object is sent."}},required:["sourceCurrencyCode"]},AE={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field. Required unless resourceId is given; when resourceId is given, the organization's own name for that field is stored instead of this one."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition. Required unless customFieldName is given. When omitted, the field is matched by customFieldName (case-insensitive) and linked only if exactly one active custom field in the organization has that name."}}},QIr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},LIr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},Hpe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},gV={type:"object",properties:{billingAddress:{...Hpe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},yV={type:"object",properties:{billingAddress:{...Hpe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...Hpe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},PIr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Ia={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:PIr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},Wl={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},gE={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},Yw={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:AE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...QIr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...LIr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...gV,description:"Issuer identity and billing address (credit from)."},creditTo:{...yV,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:AE},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...gV,description:"Seller identity and billing address."},billTo:{...yV,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:AE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:AE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...gV,description:"Seller identity and billing address."},billTo:{...yV,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:AE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...gV,description:"Seller identity and billing address."},billTo:{...yV,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:AE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...Gc,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:AE},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...Gc,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},yE={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},description:{type:"string",description:"Line item description or memo."},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ia},discount:{...Wl,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...gE,description:"Withholding tax details for this line item."}}}}});function Gpe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function Vpe(e){let t=e.updated??[],r=Gpe(e.failed);return{...t.length===0&&r.length>0?{error:$Ir}:{},updated:t,failed:r}}function Cit(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function EV(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _it(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=Cit(s);if(a)for(let c of Array.isArray(o)?o:[o])EV(c)&&n.push(..._it(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function qIr(e){return Object.entries(e).map(([t,r])=>{let n=Cit(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function Wpe(e,t,r){if(!EV(t))return;let n=_it(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw Jt(new ht(`${e} has no field ${i.join("; ")}. Fields: ${qIr(r)}. Nothing was changed.`))}function jIr(e){let t=Yw[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function YIr(e){let t=yE[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function HIr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!EV(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw Jt(new ht(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!EV(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw Jt(new ht(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));Wpe(`${e} line items`,a.attributes,t.fields)}}}function wit(e){if(Hw.includes(e))return;let t=IV.includes(e);throw Jt(new ht(t?`${e} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${e} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${e} has no quick fix route. Transaction-level entities: ${Hw.join(", ")}.`))}async function Jw(e,t,r){wit(t),Wpe(`${t} quick fix`,r.attributes,jIr(t));let n=await e.post(`/api/v1/quick-fix/${bc(Hw,t)}`,r);return Vpe(n)}async function zIr(e,t){try{return await oE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return sE(e,t);throw r}}async function vit(e,t,r,n){wit(t);let i=Kpe[t],o=async d=>i.tags(await ef(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Iit)s.push(...await Promise.all(r.resourceIds.slice(d,d+Iit).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=Du(s[f],n),h=JSON.stringify(p);a.set(h,{tags:p,resourceIds:[...a.get(h)?.resourceIds??[],d]})});let c=[],u=[];for(let{tags:d,resourceIds:f}of a.values())try{let p=await Jw(e,t,{resourceIds:f,attributes:{...r.attributes,tags:d}});c.push(...p.updated),u.push(...p.failed)}catch(p){if(c.length===0)throw p;u.push(...f.map(h=>({resourceId:h,error:p instanceof Error?p.message:String(p)})))}return Vpe({updated:c,failed:u})}async function dN(e,t,r){let n=bc(zw,t),i=YIr(t);i.entryKeys?HIr(t,i,r.schedulerUpdates):Wpe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return Vpe(o)}var MIr,UIr,bV,IV,Hw,zw,$Ir,EE,Jpe,Kpe,Iit,CV=G(()=>{"use strict";zi();ut();vo();zpe();SI();kg();Zd();KT();nx();Bg();SJ();PJ();eV();MIr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],UIr=["journals","cash-entries"],bV=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],IV=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],Hw=[...MIr,...UIr,...bV],zw=[...Hw,...IV],$Ir="Nothing changed: every record failed. See failed for each reason.";EE=e=>e?.tags,Jpe=e=>e?.data?.tags,Kpe={invoices:{noun:"invoice",get:(e,t)=>uo(e,t),tags:EE},bills:{noun:"bill",get:(e,t)=>oo(e,t),tags:EE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>$s(e,t),tags:EE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>qs(e,t),tags:EE},journals:{noun:"journal",get:(e,t)=>gs(e,t),tags:EE},"cash-entries":{noun:"cash entry",get:(e,t)=>zIr(e,t),tags:EE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Nw(e,t),tags:Jpe},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Ow(e,t),tags:Jpe},"subscription-schedules":{noun:"subscription",get:(e,t)=>mE(e,t),tags:Jpe},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Fw(e,t),tags:EE}},Iit=10});function _V(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=_V(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<GIr&&i.length<=VIr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,_V(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function Dit(e,t,r){let n=WIr(t);if(!n)return[];let i=KIr(r);if(!i){if(Sit[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?Dit(o,s,i[o]):[])}function ZIr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function Zpe(e,t,r={}){let n=Object.keys(e),i=[...new Set(n.flatMap(c=>Object.keys(e[c])))].sort(),o={},s=new Map;for(let c of i){let u=n.filter(y=>e[y][c]),d=new Map;for(let y of u){let b=XIr(e[y][c]);d.set(b,[...d.get(b)??[],y])}let[[,f],...p]=[...d].sort((y,b)=>b[1].length-y[1].length),{description:h,...m}=r[c]??_V(e[f[0]][c]),A=p.length&&m.properties&&!r[c]?{...m,required:void 0,properties:Object.assign({},...[f,...p.map(([,y])=>y)].map(y=>_V(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[Sit[c],ZIr(u,n),...p.map(([,y])=>{let b=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(b.properties??b.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[b,E]of Dit(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(b))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function kit(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>JIr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var JIr,Sit,GIr,VIr,WIr,KIr,XIr,eCr,tCr,Gw,Rit,Tit,xit,Bit,Nit,Oit,Xpe=G(()=>{"use strict";zpe();SI();JIr={valueDate:"date",dueDate:"due date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},Sit={currencySettings:"sourceCurrencyCode alone takes the platform rate (not on schedules); add rateFunctionalToSource to set one.",taxCurrencySettings:"Cash entries: sourceCurrency; every other record: sourceCurrencyCode, always sent.",tags:`${Ua.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}."},GIr=2,VIr=8;WIr=e=>e.properties??e.items?.properties,KIr=e=>e.properties??e.items?.properties;XIr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),eCr={tags:Ua};tCr=Object.entries(yE).filter(([,e])=>!e.entryKeys),Gw=Object.entries(yE).filter(([,e])=>e.entryKeys),Rit=Zpe({...Yw},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",eCr),Tit=Zpe(Object.fromEntries(tCr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),xit=(()=>{let e=n=>Gw.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=Gw[0],r=[...new Set(Gw.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>Gw.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${Gw.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:Zpe(Object.fromEntries(Gw.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Bit=[...new Set([...Object.keys(Yw),...Object.keys(yE)])].map(e=>e.replace(/-/g," ")).join(", "),Nit=kit(Object.values(Yw)),Oit=kit(Object.values(yE).map(e=>e.fields))});function wV(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var ehe=G(()=>{"use strict"});function SV(){return Jm.map(e=>`${e} sets ${Ww[e].change.join(", ")}`).join("; ")}function qit(e){let t={};for(let r of e)t[r]=Object.hasOwn(Qit,r)?Qit[r]:iCr.find(([n])=>n.test(r))?.[1]??oCr;return Object.keys(t).length>0?t:void 0}function jit(e){if(!(e instanceof gr)||!e.endpoint.startsWith(nCr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Lit,n))return;let{hint:i,repairTool:o,command:s}=Lit[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Uit.LINE_ITEMS?"line items":"records",...e.endpoint===vV?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function cCr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function lCr(e){return typeof e=="string"&&Jm.includes(e)}function uCr(e,t){if(!lCr(e))throw new ht(`level must be one of ${Jm.join(", ")}.`);let r=Jm.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))Ww[e][i].includes(s)||n.push(Ww[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=Ww[e];throw new ht(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Pit(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new ht(`${e} must be a JSON object, not ${n}.`)}async function RV(e,t,r){let n={filter:Pit("filter",r.filter),change:Pit("change",r.change)};uCr(t,n);let i;try{i=await e.post(Uit[t],{filter:n.filter,change:n.change},Qt)}catch(u){throw jit(u),u}let{data:o,...s}=i,a=qit([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=cCr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function rhe(e,t){return{error:`${t} ${Hit}`,outcome:"UNKNOWN",previewId:e,next:Yit}}function pCr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return rhe(e,"The apply answered without a per-record result.");let i=Gpe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=qit(Object.keys(o)),a=o[sCr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:fCr}:a==="UNKNOWN"?{error:Hit}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Yit:dCr},failed:i.slice(0,the),...i.length>the?{failedNotShown:i.length-the}:{},data:r}}async function TV(e,t,r=aCr){let n;try{n=await e.post(vV,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=jit(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw Jt(i);return rhe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof Pp)throw Jt(i);let o=i instanceof Error?i.message:String(i);return rhe(t,`No answer arrived from the apply (${o}).`)}return pCr(t,n)}var Mit,Jm,Uit,vV,nCr,$it,Fit,Ww,Qit,iCr,oCr,sCr,aCr,DV,the,Kw,$en,Vw,Lit,Yit,dCr,fCr,Hit,nhe=G(()=>{"use strict";zi();CV();cL();ut();vo();Ar();ehe();Mit=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],Jm=["TRANSACTIONS","LINE_ITEMS"],Uit={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},vV="/api/v1/ledger/find-fix/apply",nCr=vV.slice(0,vV.lastIndexOf("/")+1),$it={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},Fit=["types","resourceIds","reference","valueDate","contactResourceId"],Ww={TRANSACTIONS:{filter:Fit,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Fit,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Qit={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},iCr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],oCr="Not described by this client version; read the records that carry it.";sCr="OUTCOME_UNKNOWN",aCr=25e3,DV=3e5,the=50,Kw=12,$en=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${Kw}}(?![A-Za-z0-9_-])`,"i"),Vw=e=>e.resourceId?` (${e.resourceId})`:"",Lit={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${Vw(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${Vw(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${Vw(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${Vw(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${Vw(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${Vw(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};Yit="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",dCr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",fCr="Nothing changed: every record in the preview failed.",Hit="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function xV(e,t){return e.list("/api/v1/nano-classifiers",t)}async function bE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function kV(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function fN(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function pN(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function BV(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await hCr(e,t):{};let{data:n}=await bE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Jit(n)}async function hCr(e,t){let{data:r}=await bE(e,t);return Jit(r)}function Jit(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function NV(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var zit,ihe=G(()=>{"use strict";zit=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function OV(e,t){return e.post("/api/v1/export-records",t,Qt)}async function FV(e,t){return e.post("/api/v1/export-records/preview",t,Qt)}async function QV(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var ohe=G(()=>{"use strict";Ar()});function LV(e,t){if(!t.has(e))throw new he(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Kit(e,t,r,n=!1){if(!Array.isArray(e))throw new he(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new he(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new he(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new he(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function PV(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function MV(e,t,r){return LV(t,Vit),Ji(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${bc(ep,t)}/${encodeURIComponent(r)}/approve`,void 0,uTe)}async function UV(e,t,r){return LV(t,Vit),Kit(r,mCr,"bulk approve",!0),r.forEach(n=>Ji(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${bc(ep,t)}/bulk-approve`,{resourceIds:r},dTe)}async function $V(e,t,r,n){LV(t,Wit),Ji(r,"resourceId","Pass the document resourceId."),Zit(n);let i=await e.post(`/api/v1/${bc(IE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:yCr(i)}}}async function qV(e,t,r,n){return LV(t,Wit),Zit(n),Kit(r,ACr,"bulk request changes"),r.forEach(i=>Ji(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(gCr(t),{resourceIds:r,message:n})}function gCr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${bc(Git,e)}/bulk-request-changes`}function Zit(e){if(!e||e.trim().length===0)throw new he("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function yCr(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ep,Git,IE,Vit,Wit,mCr,ACr,she=G(()=>{"use strict";ut();Ar();ep=["invoices","bills","customer-credit-notes","supplier-credit-notes"],Git=[...ep,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],IE=[...Git,"claims"],Vit=new Set(ep),Wit=new Set(IE);mCr=100,ACr=500});function ECr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${Xit(t)}:${Xit(r)}:${n}`}function Xit(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function ahe(e){if(!eot.has(e))throw new he(`unknown entity "${e}" \u2014 expected one of ${[...eot].join(", ")}`)}async function tot(e,t,r){return ahe(t),Ji(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function rot(e,t,r,n){return ahe(t),Ji(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function not(e,t,r,n,i){if(ahe(t),Ji(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new he('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??ECr(t,r,n)}})}async function iot(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var eot,oot=G(()=>{"use strict";ut();eot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function Zw(e){Ut(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new he(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!eNe(n.btResourceId))throw new he(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!bCr.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new he(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function jV(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},Qt);return{data:CCr(r.data)}}function ICr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function CCr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(ICr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function YV(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function HV(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var bCr,che=G(()=>{"use strict";ut();L7();Cn();Ar();bCr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function lot(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new he("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function lhe(e,t){if(!e||typeof e!="object")throw new he(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new he(`${t}.lineItems array is empty.`);if(n.length>500)throw new he(`max 500 ${t}.lineItems per call.`);Cl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&Cl([i],["valueDate"])}async function JV(e,t,r=uhe){return e.post("/api/v1/search-magic-reconciliation",t,{...Qt,timeoutMs:r})}function zV(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function SCr(e){let t=zV(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=zV(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function DCr(e){return e?e.value>=(e.from==="confidenceScore"?_Cr:wCr)?"high":e.value>=vCr?"medium":"low":"low"}function TCr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(sot,t))return;let r=sot[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function Gm(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function aot(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function xCr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>aot({account:Gm(n?.account),taxProfile:Gm(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!Gm(e.contact)&&!Gm(e.account)&&!Gm(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return aot({contact:Gm(e.contact),account:Gm(e.account),taxProfile:Gm(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function uot(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>FCr(c,h??{},u.length-1,t)).sort(kCr),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function kCr(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function BCr(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return Ec.test(t)?t:void 0}function NCr(e){let{recommendationId:t,...r}=e;return r}function OCr(e,t,r){return!t||!r?t:e===CE.learnedPrediction?{...t,recommendationId:r}:e===CE.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function FCr(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=zV(t.matchScore),s=zV(t.confidenceScore),a=SCr(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=CE.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=CE.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let O=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,J=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,Y=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;O&&J&&Y&&(m=CE.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:O,predictedPayload:J,predictedPayloadSchemaVersion:Y});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let O=t.actionShortcut??{},J=typeof O.resourceId=="string"?O.resourceId:void 0;J&&(m=CE.applyBankRule,A={actionShortcutResourceId:J,businessTransactionResourceIds:[e]});break}default:break}let g=OCr(m,A,BCr(t)),y=m?DCr(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==CE.withPayments||b,T=TCr(t),R=!m||!g?"NO_PLAN":T?RCr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",B=xCr(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:g,confidenceTier:y,autoCommitEligible:R===void 0,...R?{checkpointReason:R}:{},...B?{proposedPosting:B}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:T===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(NCr(t))}`}}function QCr(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function LCr(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await oo(e,i):await uo(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${fE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function dot(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,cot);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await UI(e,t,{filter:{resourceId:{in:u}},limit:cot}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${fE(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return QCr(u,f,await LCr(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function GV(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,la)}async function VV(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,la)}async function WV(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,la)}async function KV(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,la)}async function ZV(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,la)}async function XV(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,la)}async function e8(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,la)}async function t8(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,la)}async function r8(e,t){return e.post("/api/v1/reconciliations/with-payments",t,la)}async function n8(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,la)}async function i8(e,t){return e.post("/api/v1/reconciliations/magic-match",t,la)}async function o8(e,t){return e.post("/api/v1/reconciliations/reset",t)}var CE,uhe,_Cr,wCr,vCr,RCr,sot,cot,s8=G(()=>{"use strict";pg();pE();ut();Zd();Cn();kg();Ar();CE={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},uhe=6e4;_Cr=.9,wCr=.95,vCr=.7;RCr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},sot={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};cot=25});function Ws(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function No(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:dhe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=dhe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=dhe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function dhe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function Jo(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ws(e,t,n),a=No(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var Ca,Vc,go,Kl,fot=G(()=>{"use strict";Ca=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],Vc=[...Ca],go=Ca.filter(e=>e.field!=="dueDate"),Kl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function ld(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=gc(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function a8(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=mI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var pot=G(()=>{"use strict";$p()});var fhe=G(()=>{"use strict";fot();$p();pot()});var hN,c8,Go,_a,phe=G(()=>{"use strict";hN="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",c8=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],Go="If the result says it runs in the background, do not poll: its result arrives by itself.",_a=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${Go} PARTIAL_SUCCESS: errorDetails.`});function hot(e){return PCr.get(e)}function mot(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!l8.has(o));return n.length===0?[]:Ni.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Ni,l8,PCr,ud=G(()=>{"use strict";phe();Xpe();Ni=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Thirteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Tracking categories (nano classifiers; dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"],channelToolsDescription:"Check the progress of background tasks a request started, add to a waiting one, or cancel it."},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${Bit}. On a record: ${Nit}. On lines: ${Oit}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${c8.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"collab",title:"Collaboration",description:"Comment threads on bills, invoices, credit notes and bank records: list threads and comments, add a reply or start a thread, mention a teammate, update or delete your own comment, resolve a thread. Notifications: list unread mentions and comments, mark one read or unread, mark all read.",groups:["collaboration"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],l8=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),PCr=new Map(Ni.flatMap(e=>e.groups.map(t=>[t,e.name])))});function dd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function MCr(e){let t=Aot.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(dd(r),n);for(let r of e.enum??[])t.set(dd(r),r);Aot.set(e,t)}return t}function got(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=dd(e);if(!r)return null;let n=MCr(t).get(r);return n!==void 0&&n!==e?n:null}function UCr(e){let t=yot.get(e);return t||(t=new Map(Object.keys(e).map(r=>[dd(r),r])),yot.set(e,t)),t}function $Cr(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function qCr(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function hhe(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=UCr(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=dd(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?$Cr(d):qCr(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=got(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=got(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=z7(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=hhe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=hhe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Eot(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:hhe(t,e.params,"",r),coercions:r}}function bot(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var Aot,yot,mhe=G(()=>{"use strict";DM();Aot=new WeakMap;yot=new WeakMap});function Xw(e){let t=new Set,r=[];for(let n of e)for(let i of Zl(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function mN(){return Ni.map(e=>{let t=Xw(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function jCr(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function YCr(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function Vm(e,t=!1){let r=Wm(void 0).length,n=Ni.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:YCr(r)}:e&&i!==void 0?{packaging:jCr(e,i,r)}:{},map:mN(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var u8=G(()=>{"use strict";ud();Xl()});function d8(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=d8(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=d8(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function eu(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=d8(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function AN(e){return{name:e.name,description:e.description,input_schema:eu(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var ev=G(()=>{"use strict"});function gN(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function Ahe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function f8(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&gN(e),idempotentHint:e.readOnly,openWorldHint:Ahe(e)}}function zCr(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function JCr(e){let t=zCr(e);return!t||HCr.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!l8.has(n)).length===0}function ghe(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function yhe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?yhe(o,`${i}.`):[]]})}function VCr(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
663
663
|
`)[0]}`.toLowerCase(),n=[...e.description.split(`
|
|
664
664
|
`).slice(1),...yhe(e.params)].map(i=>i.trim()).filter(Boolean);for(let i of t){if(r.includes(i))continue;let o=n.find(s=>s.replace(/\b(Only|Not): [^.]*\./g,"").toLowerCase().includes(i));if(o)return o.length>Iot?`${o.slice(0,Iot-1)}\u2026`:o}}function p8(e,t="meta"){let r=t==="meta"?"search_tools with an empty query":"describe_capabilities with no arguments";if(JCr(e)){if(t!=="meta")return Vm(t);let{next:a,...c}=Vm();return{...c,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let n=Il(e.trim());if(n)return{matches:[],hint:n};let i=mot(e,5);if(i.length===0){let{operations:a,namespaces:c}=Vm();return{matches:[],hint:`No operation matches "${e}". Jaz has ${a} operations across ${c} namespaces \u2014 call ${r} for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let s=e.toLowerCase().split(/\s+/).filter(Boolean);return{matches:i.map(a=>{let c=a.groups.flatMap(m=>Zl(m)),u=c.map(m=>`${m.name} ${(m.aliases??[]).join(" ")} ${m.searchHint??""} ${m.description} ${yhe(m.params).join(" ")}`.toLowerCase()),d=new Map(s.map(m=>{let A=u.filter(g=>g.includes(m)).length;return[m,Math.log((c.length+1)/(A+1))]})),f=s.slice(1).map((m,A)=>`${s[A]} ${m}`),p=c.map((m,A)=>{let g=u[A],y=s.reduce((b,E)=>g.includes(E)?b+(d.get(E)??0):b,0)+f.filter(b=>g.includes(b)).length;return{tool:m,score:y}}).sort((m,A)=>A.score-m.score),h=[...d].filter(([m,A])=>A>0&&m.length>=3&&!l8.has(m)&&!GCr.has(m)).sort((m,A)=>A[1]-m[1]).map(([m])=>m);return{namespace:a.name,description:a.description,tools:p.map(m=>{let A=m.score>0?VCr(m.tool,h):void 0;return{name:m.tool.name,description:m.tool.description.split(`
|
|
665
665
|
`)[0],...m.tool.searchHint?{searchHint:m.tool.searchHint}:{},...A?{matched:A}:{}}})}}),hint:t==="meta"?"Call describe_tools with the tool names you need, then execute_tool to run them.":`These are summaries. Before concluding something is unsupported, open the namespace with describe_capabilities({ namespace }) for every operation and its parameters. ${ghe(t)}`}}function Cot(e){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(e.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let t=[],r=[];for(let n of e){let i=yN(n);if(!i){r.push(n);continue}t.push({...AN(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&gN(i),group:i.group})}return{tools:t,...r.length>0?{notFound:r,hint:r.map(Il).find(Boolean)??`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var HCr,Iot,GCr,WCr,KCr,ZCr,tv,Km,_E=G(()=>{"use strict";ud();u8();Xl();ev();XA();HCr=new Set(["capabilities","capability","overview","everything","catalog","catalogue","menu","features","feature list","functions","tool list","all tools","all operations","list tools","list all tools","list operations","full list","full catalog","full catalogue","whats available","what is available","whats possible","show everything","show me everything","what else can you do","how many tools","how many operations"]);Iot=160,GCr=new Set(["change","changes","changing","update","updates","updating","edit","modify","set","make","existing","new","add","create","remove","delete","all","every","each","these","those","record","records","want","need","keep","keeping","remaining","unchanged","while","only"]);WCr={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:eu({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};KCr={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:eu({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},ZCr={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:eu({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},tv={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs to pass as org_id on other tool calls.",inputSchema:eu({},[])},Km=[WCr,KCr,ZCr]});function r_r(e){if(!(wa in e))return{cleanedInput:e};let{[wa]:t,...r}=e;return{jotText:typeof t=="string"&&t.trim()!==""?t.trim():void 0,cleanedInput:r}}function EN(e){return!e.readOnly&&!e.params[wa]&&e.group!=="jots"}function vot(e,t){if(e.params[wa])return{cleanedInput:t};let{jotText:r,cleanedInput:n}=r_r(t);return EN(e)?{jotText:r,cleanedInput:n}:{cleanedInput:n}}function n_r(e){let t=e_r.exec(e);return t?{kind:t[1],call:e.slice(t[0].length)||e}:{call:e}}function o_r(e){let t=e.toLowerCase();for(let[r,n]of i_r)if(n.test(t))return r}function s_r(e,t){let r=o_r(e),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=_ot||a>t_r||!s||typeof s!="object")){if(Array.isArray(s)){for(let c of s)o(c,a+1);return}for(let[c,u]of Object.entries(s)){if(n.length>=_ot)return;c==="resourceId"&&typeof u=="string"&&u&&!i.has(u)?(i.add(u),n.push(u)):o(u,a+1)}}};return o(t,0),n.map(s=>({id:s,...r?{relation:r}:{}}))}function h8(e,t,r,n){let{kind:i,call:o}=n_r(r),s=s_r(t,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${t}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};Qw(e,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(GS(),JS)).then(({log:d})=>d.error({tool:t,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${t}): ${u}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jaz-clio",
|
|
3
|
-
"version": "9.4.
|
|
3
|
+
"version": "9.4.1",
|
|
4
4
|
"description": "Fastest ledger for agents. Jaz accounting CLI and MCP server: invoicing, bills, payments, quotes & orders, bank reconciliation, fixed assets, inventory, expense claims, tax, reports, and period close.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|