jaz-clio 9.5.3 → 9.5.5
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/api/references/endpoints.md +4 -4
- 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
|
@@ -2328,16 +2328,16 @@ Only included fields are changed; omitted fields are left unchanged.
|
|
|
2328
2328
|
|
|
2329
2329
|
<!-- quick-fix-fields:start (generated by scripts/gen-quick-fix-fields.ts from spec/openapi.yaml; do not edit) -->
|
|
2330
2330
|
**Transaction-level `attributes`**, per entity:
|
|
2331
|
-
- **bills**: `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `dueDate`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `valueDate`
|
|
2331
|
+
- **bills**: `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `dueDate`, `internalNotes`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `templateResourceId`, `valueDate`
|
|
2332
2332
|
- **cash-entries**: `capsuleResourceId`, `contactResourceId`, `currencySetting {exchangeToken, rateFunctionalToSource}`, `organizationAccountResourceId`, `reference`, `tags`, `taxCurrencySettings {exchangeRate, sourceCurrency}`, `valueDate`
|
|
2333
|
-
- **customer-credit-notes**: `capsuleResourceId`, `contactResourceId`, `creditFrom {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, taxId}`, `creditTo {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, shippingAddress {addressLine1, addressLine2, city, country, postalCode, state}, taxId}`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `notes`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `templateResourceId`, `valueDate`
|
|
2334
|
-
- **invoices**: `billFrom {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, taxId}`, `billTo {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, shippingAddress {addressLine1, addressLine2, city, country, postalCode, state}, taxId}`, `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `dueDate`, `invoiceNotes`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `templateResourceId`, `valueDate`
|
|
2333
|
+
- **customer-credit-notes**: `capsuleResourceId`, `contactResourceId`, `creditFrom {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, taxId}`, `creditTo {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, shippingAddress {addressLine1, addressLine2, city, country, postalCode, state}, taxId}`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `internalNotes`, `notes`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `templateResourceId`, `valueDate`
|
|
2334
|
+
- **invoices**: `billFrom {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, taxId}`, `billTo {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, shippingAddress {addressLine1, addressLine2, city, country, postalCode, state}, taxId}`, `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `deliverySlipTemplateResourceId`, `dueDate`, `internalNotes`, `invoiceNotes`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `templateResourceId`, `valueDate`
|
|
2335
2335
|
- **journal-schedules**: `capsuleResourceId`, `contactResourceId`, `endDate`, `internalNotes`, `interval`, `tags`
|
|
2336
2336
|
- **journals**: `capsuleResourceId`, `contactResourceId`, `internalNotes`, `tags`, `valueDate`
|
|
2337
2337
|
- **purchase-schedules**: `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `endDate`, `interval`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`
|
|
2338
2338
|
- **sale-schedules**: `billFrom {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, taxId}`, `billTo {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, shippingAddress {addressLine1, addressLine2, city, country, postalCode, state}, taxId}`, `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `endDate`, `interval`, `invoiceNotes`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `templateResourceId`
|
|
2339
2339
|
- **subscription-schedules**: `billFrom {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, taxId}`, `billTo {billingAddress {addressLine1, addressLine2, city, country, postalCode, state}, name, shippingAddress {addressLine1, addressLine2, city, country, postalCode, state}, taxId}`, `capsuleResourceId`, `contactResourceId`, `customFields`, `endDate`, `interval`, `invoiceNotes`, `tags`, `templateResourceId`
|
|
2340
|
-
- **supplier-credit-notes**: `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `valueDate`
|
|
2340
|
+
- **supplier-credit-notes**: `capsuleResourceId`, `contactResourceId`, `currencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `customFields`, `internalNotes`, `tags`, `taxCurrencySettings {exchangeToken, rateFunctionalToSource, sourceCurrencyCode}`, `valueDate`
|
|
2341
2341
|
|
|
2342
2342
|
**Line-item `attributes`**, per entity (schedules nest them: `lineItemUpdates: [{ <locator>, attributes }]`):
|
|
2343
2343
|
- **bills**: `classifierConfig {deleted, printable, resourceId, selectedClasses {className, entityResourceId, resourceId}, type}`, `discount {rateType, rateValue}`, `itemResourceId`, `name`, `organizationAccountResourceId`, `quantity`, `taxProfileResourceId`, `unit`, `unitPrice`, `withholdingTax {code, description, rate, rateType, type}`
|
package/cli.mjs
CHANGED
|
@@ -659,7 +659,7 @@ actual: `+e._bytesWritten),FG.prototype._finish.call(e)}});var fme=I((nrn,zit)=>
|
|
|
659
659
|
Unsupported type: `+e.type,"ENOTSUP");e._finish()})};Zc.prototype._stat=function(e){var t=this,r=t.props,n=r.follow?"stat":"lstat",i=t._proxy||t;e?o(null,e):Xc[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 pme(t);t._old=a;var c=Vit(a);if(c!==t.type||t.type==="File"&&a.nlink>1)return oCr(t._path,function(u){if(u)return t.error(u);t._old=null,pme(t)});pme(t)}};function pme(e){sCr(OB.dirname(e._path),Zc.dirmode,function(t,r){return t?e.error(t):(e._madeDir=r,e._create())})}function Kit(e,t,r,n,i){var o=t.mode,s=t.follow||e.type!=="SymbolicLink"?"chmod":"lchmod";if(!Xc[s]||typeof o!="number")return i();var a=r.mode&parseInt("0777",8);if(o=o&parseInt("0777",8),o===a)return i();Xc[s](n,o,i)}function Xit(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(!Xc[o])return i();typeof t.uid!="number"&&(t.uid=r.uid),typeof t.gid!="number"&&(t.gid=r.gid),Xc[o](n,t.uid,t.gid,i)}function Zit(e,t,r,n,i){if(!Xc.utimes||process.platform==="win32")return i();var o=t.follow||e.type!=="SymbolicLink"?"utimes":"lutimes";if(o==="lutimes"&&!Xc[o]&&(o="utimes"),!Xc[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),Jit(c)||(c=new Date(c)),Jit(u)||(c=new Date(u)),c.getTime()===s.getTime()&&u.getTime()===a.getTime())return i();Xc[o](n,c,u,i)}Zc.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";Xc[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,Kit(e,e.props,a,e._path,s("chmod")),Xit(e,e.props,a,e._path,s("chown")),Zit(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)eot(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 eot(e,t,r){var n=e._madeDir,i=OB.dirname(t);dCr(e,i,function(o){if(o)return r(o);if(i===n)return r();eot(e,i,r)})}function dCr(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;Xc.stat(t,function(a,c){if(a)return r(o=a);Kit(e,n,c,t,s),Xit(e,n,c,t,s),Zit(e,n,c,t,s)});function s(a){if(!o){if(a)return r(o=a);if(--i===0)return r()}}}Zc.prototype.pipe=function(){this.error("Can't pipe from writable stream")};Zc.prototype.add=function(){this.error("Can't add to non-Directory type")};Zc.prototype.write=function(){return!0};function fCr(e){return Object.prototype.toString.call(e)}function Jit(e){return typeof e=="object"&&fCr(e)==="[object Date]"}});var hme=I(Mr=>{Mr.Abstract=RG();Mr.Reader=AE();Mr.Writer=Yw();Mr.File={Reader:Khe(),Writer:ume()};Mr.Dir={Reader:Whe(),Writer:cme()};Mr.Link={Reader:Ghe(),Writer:lme()};Mr.Proxy={Reader:Zhe(),Writer:fme()};Mr.Reader.Dir=Mr.DirReader=Mr.Dir.Reader;Mr.Reader.File=Mr.FileReader=Mr.File.Reader;Mr.Reader.Link=Mr.LinkReader=Mr.Link.Reader;Mr.Reader.Proxy=Mr.ProxyReader=Mr.Proxy.Reader;Mr.Writer.Dir=Mr.DirWriter=Mr.Dir.Writer;Mr.Writer.File=Mr.FileWriter=Mr.File.Writer;Mr.Writer.Link=Mr.LinkWriter=Mr.Link.Writer;Mr.Writer.Proxy=Mr.ProxyWriter=Mr.Proxy.Writer;Mr.collect=BG()});var not=I((srn,rot)=>{rot.exports=yCr;var pCr=DG(),hCr=hme().Writer,mme=z("path"),mCr=z("stream"),ACr=Hhe(),gCr=Jm();function yCr(e){e.path=mme.resolve(mme.normalize(e.path));var t=new pCr(e),r=new mCr.Writable({objectMode:!0});r._write=function(i,o,s){if(i.type=="Directory")return s();var a=mme.join(e.path,i.path);if(a.indexOf(e.path)!=0)return s();let c=e.getWriter?e.getWriter({path:a}):hCr({path:a});i.pipe(c).on("error",s).on("close",s)};var n=ACr(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 gCr(function(i,o){n.on("close",i),n.on("error",o)})},n}});var iot=I((arn,LG)=>{var _o=(function(e){"use strict";var t=1e7,r=7,n=9007199254740992,i=p(n),o="0123456789abcdefghijklmnopqrstuvwxyz",s=typeof BigInt=="function";function a(v,x,P,H){return typeof v>"u"?a[0]:typeof x<"u"?+x==10&&!P?ae(v):Ve(v,x,P,H):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),P=-1;++P<v;)x[P]=0;return x}function g(v){return v>0?Math.floor(v):Math.ceil(v)}function y(v,x){var P=v.length,H=x.length,ie=new Array(P),re=0,se=t,ce,ge;for(ge=0;ge<H;ge++)ce=v[ge]+x[ge]+re,re=ce>=se?1:0,ie[ge]=ce-re*se;for(;ge<P;)ce=v[ge]+re,re=ce===se?1:0,ie[ge++]=ce-re*se;return re>0&&ie.push(re),ie}function b(v,x){return v.length>=x.length?y(v,x):y(x,v)}function E(v,x){var P=v.length,H=new Array(P),ie=t,re,se;for(se=0;se<P;se++)re=v[se]-ie+x,x=Math.floor(re/ie),H[se]=re-x*ie,x+=1;for(;x>0;)H[se++]=x%ie,x=Math.floor(x/ie);return H}c.prototype.add=function(v){var x=ae(v);if(this.sign!==x.sign)return this.subtract(x.negate());var P=this.value,H=x.value;return x.isSmall?new c(E(P,Math.abs(H)),this.sign):new c(b(P,H),this.sign)},c.prototype.plus=c.prototype.add,u.prototype.add=function(v){var x=ae(v),P=this.value;if(P<0!==x.sign)return this.subtract(x.negate());var H=x.value;if(x.isSmall){if(f(P+H))return new u(P+H);H=p(Math.abs(H))}return new c(E(H,Math.abs(P)),P<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 P=v.length,H=x.length,ie=new Array(P),re=0,se=t,ce,ge;for(ce=0;ce<H;ce++)ge=v[ce]-re-x[ce],ge<0?(ge+=se,re=1):re=0,ie[ce]=ge;for(ce=H;ce<P;ce++){if(ge=v[ce]-re,ge<0)ge+=se;else{ie[ce++]=ge;break}ie[ce]=ge}for(;ce<P;ce++)ie[ce]=v[ce];return m(ie),ie}function w(v,x,P){var H;return V(v,x)>=0?H=C(v,x):(H=C(x,v),P=!P),H=h(H),typeof H=="number"?(P&&(H=-H),new u(H)):new c(H,P)}function T(v,x,P){var H=v.length,ie=new Array(H),re=-x,se=t,ce,ge;for(ce=0;ce<H;ce++)ge=v[ce]+re,re=Math.floor(ge/se),ge%=se,ie[ce]=ge<0?ge+se:ge;return ie=h(ie),typeof ie=="number"?(P&&(ie=-ie),new u(ie)):new c(ie,P)}c.prototype.subtract=function(v){var x=ae(v);if(this.sign!==x.sign)return this.add(x.negate());var P=this.value,H=x.value;return x.isSmall?T(P,Math.abs(H),this.sign):w(P,H,this.sign)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(v){var x=ae(v),P=this.value;if(P<0!==x.sign)return this.add(x.negate());var H=x.value;return x.isSmall?new u(P-H):T(H,Math.abs(P),P>=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 D(v,x){var P=v.length,H=x.length,ie=P+H,re=A(ie),se=t,ce,ge,Pe,Je,dt;for(Pe=0;Pe<P;++Pe){Je=v[Pe];for(var Zt=0;Zt<H;++Zt)dt=x[Zt],ce=Je*dt+re[Pe+Zt],ge=Math.floor(ce/se),re[Pe+Zt]=ce-ge*se,re[Pe+Zt+1]+=ge}return m(re),re}function k(v,x){var P=v.length,H=new Array(P),ie=t,re=0,se,ce;for(ce=0;ce<P;ce++)se=v[ce]*x+re,re=Math.floor(se/ie),H[ce]=se-re*ie;for(;re>0;)H[ce++]=re%ie,re=Math.floor(re/ie);return H}function F(v,x){for(var P=[];x-- >0;)P.push(0);return P.concat(v)}function G(v,x){var P=Math.max(v.length,x.length);if(P<=30)return D(v,x);P=Math.ceil(P/2);var H=v.slice(P),ie=v.slice(0,P),re=x.slice(P),se=x.slice(0,P),ce=G(ie,se),ge=G(H,re),Pe=G(b(ie,H),b(se,re)),Je=b(b(ce,F(C(C(Pe,ce),ge),P)),F(ge,2*P));return m(Je),Je}function j(v,x){return-.012*v-.012*x+15e-6*v*x>0}c.prototype.multiply=function(v){var x=ae(v),P=this.value,H=x.value,ie=this.sign!==x.sign,re;if(x.isSmall){if(H===0)return a[0];if(H===1)return this;if(H===-1)return this.negate();if(re=Math.abs(H),re<t)return new c(k(P,re),ie);H=p(re)}return j(P.length,H.length)?new c(G(P,H),ie):new c(D(P,H),ie)},c.prototype.times=c.prototype.multiply;function R(v,x,P){return v<t?new c(k(x,v),P):new c(D(x,p(v)),P)}u.prototype._multiplyBySmall=function(v){return f(v.value*this.value)?new u(v.value*this.value):R(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():R(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 O(v){var x=v.length,P=A(x+x),H=t,ie,re,se,ce,ge;for(se=0;se<x;se++){ce=v[se],re=0-ce*ce;for(var Pe=se;Pe<x;Pe++)ge=v[Pe],ie=2*(ce*ge)+P[se+Pe]+re,re=Math.floor(ie/H),P[se+Pe]=ie-re*H;P[se+x]=re}return m(P),P}c.prototype.square=function(){return new c(O(this.value),!1)},u.prototype.square=function(){var v=this.value*this.value;return f(v)?new u(v):new c(O(p(Math.abs(this.value))),!1)},d.prototype.square=function(v){return new d(this.value*this.value)};function M(v,x){var P=v.length,H=x.length,ie=t,re=A(x.length),se=x[H-1],ce=Math.ceil(ie/(2*se)),ge=k(v,ce),Pe=k(x,ce),Je,dt,Zt,_n,ci,lo,ul;for(ge.length<=P&&ge.push(0),Pe.push(0),se=Pe[H-1],dt=P-H;dt>=0;dt--){for(Je=ie-1,ge[dt+H]!==se&&(Je=Math.floor((ge[dt+H]*ie+ge[dt+H-1])/se)),Zt=0,_n=0,lo=Pe.length,ci=0;ci<lo;ci++)Zt+=Je*Pe[ci],ul=Math.floor(Zt/ie),_n+=ge[dt+ci]-(Zt-ul*ie),Zt=ul,_n<0?(ge[dt+ci]=_n+ie,_n=-1):(ge[dt+ci]=_n,_n=0);for(;_n!==0;){for(Je-=1,Zt=0,ci=0;ci<lo;ci++)Zt+=ge[dt+ci]-ie+Pe[ci],Zt<0?(ge[dt+ci]=Zt+ie,Zt=0):(ge[dt+ci]=Zt,Zt=1);_n+=Zt}re[dt]=Je}return ge=B(ge,ce)[0],[h(re),h(ge)]}function W(v,x){for(var P=v.length,H=x.length,ie=[],re=[],se=t,ce,ge,Pe,Je,dt;P;){if(re.unshift(v[--P]),m(re),V(re,x)<0){ie.push(0);continue}ge=re.length,Pe=re[ge-1]*se+re[ge-2],Je=x[H-1]*se+x[H-2],ge>H&&(Pe=(Pe+1)*se),ce=Math.ceil(Pe/Je);do{if(dt=k(x,ce),V(dt,re)<=0)break;ce--}while(ce);ie.push(ce),re=C(re,dt)}return ie.reverse(),[h(ie),h(re)]}function B(v,x){var P=v.length,H=A(P),ie=t,re,se,ce,ge;for(ce=0,re=P-1;re>=0;--re)ge=ce*ie+v[re],se=g(ge/x),ce=ge-se*x,H[re]=se|0;return[H,ce|0]}function Y(v,x){var P,H=ae(x);if(s)return[new d(v.value/H.value),new d(v.value%H.value)];var ie=v.value,re=H.value,se;if(re===0)throw new Error("Cannot divide by zero");if(v.isSmall)return H.isSmall?[new u(g(ie/re)),new u(ie%re)]:[a[0],v];if(H.isSmall){if(re===1)return[v,a[0]];if(re==-1)return[v.negate(),a[0]];var ce=Math.abs(re);if(ce<t){P=B(ie,ce),se=h(P[0]);var ge=P[1];return v.sign&&(ge=-ge),typeof se=="number"?(v.sign!==H.sign&&(se=-se),[new u(se),new u(ge)]):[new c(se,v.sign!==H.sign),new u(ge)]}re=p(ce)}var Pe=V(ie,re);if(Pe===-1)return[a[0],v];if(Pe===0)return[a[v.sign===H.sign?1:-1],a[0]];ie.length+re.length<=200?P=M(ie,re):P=W(ie,re),se=P[0];var Je=v.sign!==H.sign,dt=P[1],Zt=v.sign;return typeof se=="number"?(Je&&(se=-se),se=new u(se)):se=new c(se,Je),typeof dt=="number"?(Zt&&(dt=-dt),dt=new u(dt)):dt=new c(dt,Zt),[se,dt]}c.prototype.divmod=function(v){var x=Y(this,v);return{quotient:x[0],remainder:x[1]}},d.prototype.divmod=u.prototype.divmod=c.prototype.divmod,c.prototype.divide=function(v){return Y(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 Y(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),P=this.value,H=x.value,ie,re,se;if(H===0)return a[1];if(P===0)return a[0];if(P===1)return a[1];if(P===-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(P,H)))return new u(g(ie));for(re=this,se=a[1];H&!0&&(se=se.times(re),--H),H!==0;)H/=2,re=re.square();return se},u.prototype.pow=c.prototype.pow,d.prototype.pow=function(v){var x=ae(v),P=this.value,H=x.value,ie=BigInt(0),re=BigInt(1),se=BigInt(2);if(H===ie)return a[1];if(P===ie)return a[0];if(P===re)return a[1];if(P===BigInt(-1))return x.isEven()?a[1]:a[-1];if(x.isNegative())return new d(ie);for(var ce=this,ge=a[1];(H&re)===re&&(ge=ge.times(ce),--H),H!==ie;)H/=se,ce=ce.square();return ge},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 P=a[1],H=this.mod(x);for(v.isNegative()&&(v=v.multiply(a[-1]),H=H.modInv(x));v.isPositive();){if(H.isZero())return a[0];v.isOdd()&&(P=P.multiply(H).mod(x)),v=v.divide(2),H=H.square().mod(x)}return P},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 P=v.length-1;P>=0;P--)if(v[P]!==x[P])return v[P]>x[P]?1:-1;return 0}c.prototype.compareAbs=function(v){var x=ae(v),P=this.value,H=x.value;return x.isSmall?1:V(P,H)},u.prototype.compareAbs=function(v){var x=ae(v),P=Math.abs(this.value),H=x.value;return x.isSmall?(H=Math.abs(H),P===H?0:P>H?1:-1):-1},d.prototype.compareAbs=function(v){var x=this.value,P=ae(v).value;return x=x>=0?x:-x,P=P>=0?P:-P,x===P?0:x>P?1:-1},c.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),P=this.value,H=x.value;return this.sign!==x.sign?x.sign?1:-1:x.isSmall?this.sign?-1:1:V(P,H)*(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),P=this.value,H=x.value;return x.isSmall?P==H?0:P>H?1:-1:P<0!==x.sign?P<0?-1:1:P<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,P=ae(v).value;return x===P?0:x>P?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 X(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 P=v.prev(),H=P,ie=0,re,se,ce,ge;H.isEven();)H=H.divide(2),ie++;e:for(ce=0;ce<x.length;ce++)if(!v.lesser(x[ce])&&(ge=_o(x[ce]).modPow(H,v),!(ge.isUnit()||ge.equals(P)))){for(re=ie-1;re!=0;re--){if(ge=ge.square().mod(v),ge.isUnit())return!1;if(ge.equals(P))continue e}return!1}return!0}c.prototype.isPrime=function(v){var x=X(this);if(x!==e)return x;var P=this.abs(),H=P.bitLength();if(H<=64)return oe(P,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var ie=Math.log(2)*H.toJSNumber(),re=Math.ceil(v===!0?2*Math.pow(ie,2):ie),se=[],ce=0;ce<re;ce++)se.push(_o(ce+2));return oe(P,se)},d.prototype.isPrime=u.prototype.isPrime=c.prototype.isPrime,c.prototype.isProbablePrime=function(v,x){var P=X(this);if(P!==e)return P;for(var H=this.abs(),ie=v===e?5:v,re=[],se=0;se<ie;se++)re.push(_o.randBetween(2,H.minus(2),x));return oe(H,re)},d.prototype.isProbablePrime=u.prototype.isProbablePrime=c.prototype.isProbablePrime,c.prototype.modInv=function(v){for(var x=_o.zero,P=_o.one,H=ae(v),ie=this.abs(),re,se,ce;!ie.isZero();)re=H.divide(ie),se=x,ce=H,x=P,H=ie,P=se.subtract(re.multiply(P)),ie=ce.subtract(re.multiply(ie));if(!H.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 Ee=[1];2*Ee[Ee.length-1]<=t;)Ee.push(2*Ee[Ee.length-1]);var ke=Ee.length,ve=Ee[ke-1];function yt(v){return Math.abs(v)<=t}c.prototype.shiftLeft=function(v){var x=ae(v).toJSNumber();if(!yt(x))throw new Error(String(x)+" is too large for shifting.");if(x<0)return this.shiftRight(-x);var P=this;if(P.isZero())return P;for(;x>=ke;)P=P.multiply(ve),x-=ke-1;return P.multiply(Ee[x])},d.prototype.shiftLeft=u.prototype.shiftLeft=c.prototype.shiftLeft,c.prototype.shiftRight=function(v){var x,P=ae(v).toJSNumber();if(!yt(P))throw new Error(String(P)+" is too large for shifting.");if(P<0)return this.shiftLeft(-P);for(var H=this;P>=ke;){if(H.isZero()||H.isNegative()&&H.isUnit())return H;x=Y(H,ve),H=x[1].isNegative()?x[0].prev():x[0],P-=ke-1}return x=Y(H,Ee[P]),x[1].isNegative()?x[0].prev():x[0]},d.prototype.shiftRight=u.prototype.shiftRight=c.prototype.shiftRight;function Ne(v,x,P){x=ae(x);for(var H=v.isNegative(),ie=x.isNegative(),re=H?v.not():v,se=ie?x.not():x,ce=0,ge=0,Pe=null,Je=null,dt=[];!re.isZero()||!se.isZero();)Pe=Y(re,ve),ce=Pe[1].toJSNumber(),H&&(ce=ve-1-ce),Je=Y(se,ve),ge=Je[1].toJSNumber(),ie&&(ge=ve-1-ge),re=Pe[0],se=Je[0],dt.push(P(ce,ge));for(var Zt=P(H?1:0,ie?1:0)!==0?_o(-1):_o(0),_n=dt.length-1;_n>=0;_n-=1)Zt=Zt.multiply(ve).add(_o(dt[_n]));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 Ne(this,v,function(x,P){return x&P})},d.prototype.and=u.prototype.and=c.prototype.and,c.prototype.or=function(v){return Ne(this,v,function(x,P){return x|P})},d.prototype.or=u.prototype.or=c.prototype.or,c.prototype.xor=function(v){return Ne(this,v,function(x,P){return x^P})},d.prototype.xor=u.prototype.xor=c.prototype.xor;var Ue=1<<30,Ae=(t&-t)*(t&-t)|Ue;function le(v){var x=v.value,P=typeof x=="number"?x|Ue:typeof x=="bigint"?x|BigInt(Ue):x[0]+x[1]*t|Ae;return P&-P}function we(v,x){if(x.compareTo(v)<=0){var P=we(v,x.square(x)),H=P.p,ie=P.e,re=H.multiply(x);return re.compareTo(v)<=0?{p:re,e:ie*2+1}:{p:H,e:ie*2}}return{p:_o(1),e:0}}c.prototype.bitLength=function(){var v=this;return v.compareTo(_o(0))<0&&(v=v.negate().subtract(_o(1))),v.compareTo(_o(0))===0?_o(0):_o(we(v,_o(2)).e).add(_o(1))},d.prototype.bitLength=u.prototype.bitLength=c.prototype.bitLength;function Le(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 Yt(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 P=a[1],H,ie;v.isEven()&&x.isEven();)H=ze(le(v),le(x)),v=v.divide(H),x=x.divide(H),P=P.multiply(H);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 P.isUnit()?v:v.multiply(P)}function Mt(v,x){return v=ae(v).abs(),x=ae(x).abs(),v.divide(Yt(v,x)).multiply(x)}function pr(v,x,P){v=ae(v),x=ae(x);var H=P||Math.random,ie=ze(v,x),re=Le(v,x),se=re.subtract(ie).add(1);if(se.isSmall)return ie.add(Math.floor(H()*se));for(var ce=$e(se,t).value,ge=[],Pe=!0,Je=0;Je<ce.length;Je++){var dt=Pe?ce[Je]+(Je+1<ce.length?ce[Je+1]/t:0):t,Zt=g(H()*dt);ge.push(Zt),Zt<ce[Je]&&(Pe=!1)}return ie.add(a.fromArray(ge,t,!1))}var Ve=function(v,x,P,H){P=P||o,v=String(v),H||(v=v.toLowerCase(),P=P.toLowerCase());var ie=v.length,re,se=Math.abs(x),ce={};for(re=0;re<P.length;re++)ce[P[re]]=re;for(re=0;re<ie;re++){var ge=v[re];if(ge!=="-"&&ge in ce&&ce[ge]>=se){if(ge==="1"&&se===1)continue;throw new Error(ge+" is not a valid digit in base "+x+".")}}x=ae(x);var Pe=[],Je=v[0]==="-";for(re=Je?1:0;re<v.length;re++){var ge=v[re];if(ge in ce)Pe.push(ae(ce[ge]));else if(ge==="<"){var dt=re;do re++;while(v[re]!==">"&&re<v.length);Pe.push(ae(v.slice(dt+1,re)))}else throw new Error(ge+" is not a valid character")}return je(Pe,x,Je)};function je(v,x,P){var H=a[0],ie=a[1],re;for(re=v.length-1;re>=0;re--)H=H.add(v[re].times(ie)),ie=ie.times(x);return P?H.negate():H}function wt(v,x){return x=x||o,v<x.length?x[v]:"<"+v+">"}function $e(v,x){if(x=_o(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 P=Array.apply(null,Array(v.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return P.unshift([1]),{value:[].concat.apply([],P),isNegative:!1}}var H=!1;if(v.isNegative()&&x.isPositive()&&(H=!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:H};for(var ie=[],re=v,se;re.isNegative()||re.compareAbs(x)>=0;){se=re.divmod(x),re=se.quotient;var ce=se.remainder;ce.isNegative()&&(ce=x.minus(ce).abs(),re=re.next()),ie.push(ce.toJSNumber())}return ie.push(re.toJSNumber()),{value:ie.reverse(),isNegative:H}}function Xe(v,x,P){var H=$e(v,x);return(H.isNegative?"-":"")+H.value.map(function(ie){return wt(ie,P)}).join("")}c.prototype.toArray=function(v){return $e(this,v)},u.prototype.toArray=function(v){return $e(this,v)},d.prototype.toArray=function(v){return $e(this,v)},c.prototype.toString=function(v,x){if(v===e&&(v=10),v!==10||x)return Xe(this,v,x);for(var P=this.value,H=P.length,ie=String(P[--H]),re="0000000",se;--H>=0;)se=String(P[H]),ie+=re.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?Xe(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 rt(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 P=v[0]==="-";P&&(v=v.slice(1));var H=v.split(/e/i);if(H.length>2)throw new Error("Invalid integer: "+H.join("e"));if(H.length===2){var ie=H[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 re=H[0],se=re.indexOf(".");if(se>=0&&(ie-=re.length-se-1,re=re.slice(0,se)+re.slice(se+1)),ie<0)throw new Error("Cannot include negative exponent part for integers");re+=new Array(ie+1).join("0"),v=re}var ce=/^([0-9][0-9]*)$/.test(v);if(!ce)throw new Error("Invalid integer: "+v);if(s)return new d(BigInt(P?"-"+v:v));for(var ge=[],Pe=v.length,Je=r,dt=Pe-Je;Pe>0;)ge.push(+v.slice(dt,Pe)),dt-=Je,dt<0&&(dt=0),Pe-=Je;return m(ge),new c(ge,P)}function Ze(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 rt(v.toString())}function ae(v){return typeof v=="number"?Ze(v):typeof v=="string"?rt(v):typeof v=="bigint"?new d(v):v}for(var ee=0;ee<1e3;ee++)a[ee]=ae(ee),ee>0&&(a[-ee]=ae(-ee));return a.one=a[1],a.zero=a[0],a.minusOne=a[-1],a.max=Le,a.min=ze,a.gcd=Yt,a.lcm=Mt,a.isInstance=function(v){return v instanceof c||v instanceof u||v instanceof d},a.randBetween=pr,a.fromArray=function(v,x,P){return je(v.map(ae),ae(x||10),P)},a})();typeof LG<"u"&&LG.hasOwnProperty("exports")&&(LG.exports=_o);typeof define=="function"&&define.amd&&define(function(){return _o})});var aot=I((crn,sot)=>{var Xm=iot(),QG=z("stream");(!QG.Writable||!QG.Writable.prototype.destroy)&&(QG=Ia());var PG;function ECr(){var e=3988292384,t,r,n;for(PG=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=t&1?e^t>>>1:t=t>>>1;PG[r]=t>>>0}}function oot(e,t){return PG||ECr(),e.charCodeAt&&(e=e.charCodeAt(0)),Xm(t).shiftRight(8).and(16777215).xor(PG[Xm(t).xor(e).and(255)]).value}function Hw(){if(!(this instanceof Hw))return new Hw;this.key0=305419896,this.key1=591751049,this.key2=878082192}Hw.prototype.update=function(e){this.key0=oot(e,this.key0),this.key1=Xm(this.key0).and(255).and(4294967295).add(this.key1),this.key1=Xm(this.key1).multiply(134775813).add(1).and(4294967295).value,this.key2=oot(Xm(this.key1).shiftRight(24).and(255),this.key2)};Hw.prototype.decryptByte=function(e){var t=Xm(this.key2).or(2);return e=e^Xm(t).multiply(Xm(t^1)).shiftRight(8).and(255),this.update(e),e};Hw.prototype.stream=function(){var e=QG.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};sot.exports=Hw});var lot=I((lrn,cot)=>{var bCr=Jm(),ICr=aot(),CCr=CG(),FB=z("stream"),_Cr=IB(),wCr=z("zlib"),vCr=vG(),SCr=Mw(),DCr=SG();(!FB.Writable||!FB.Writable.prototype.destroy)&&(FB=Ia());cot.exports=function(t,r,n,i){var o=CCr(),s=FB.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=_Cr.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=DCr(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=vCr(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=ICr();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})),bCr.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?wCr.createInflateRaw():FB.PassThrough();u?(s.size=c.uncompressedSize,d=c.compressedSize):(d=SCr.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 fot=I((urn,dot)=>{var PB=IB(),QB=CG(),RCr=lot(),LB=Jm(),TCr=wG(),xCr=vG(),kCr=Mw(),Ame=z("path"),NCr=hme().Writer,BCr=SG(),uot=kCr.alloc(4);uot.writeUInt32LE(101010256,0);function OCr(e){var t=e.stream(0).pipe(QB());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=PB.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 FCr(e,t){var r=PB.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=QB();return e.stream(r.offsetToStartOfCentralDirectory).pipe(n),n.pull(56)}function LCr(e){var t=PB.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}dot.exports=function(t,r){var n=QB(),i=QB(),o=r&&r.tailSize||80,s,a,c,u;return r&&r.crx&&(a=OCr(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(uot)}).then(function(){return LB.props({directory:n.pull(22),crxHeader:a})}).then(function(d){var f=d.directory;if(c=d.crxHeader&&d.crxHeader.size||0,u=PB.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=QB();return t.stream(h).pipe(m),m.pull(20).then(function(A){return FCr(t,A)}).then(function(A){u=LCr(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=Ame.resolve(Ame.normalize(d.path)),u.files.then(function(f){return LB.map(f,function(p){if(p.type!="Directory"){var h=Ame.join(d.path,p.path);if(h.indexOf(d.path)==0){var m=d.getWriter?d.getWriter({path:h}):NCr({path:h});return new LB(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=LB.mapSeries(Array(u.numberOfRecords),function(){return i.pull(46).then(function(d){var f=PB.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=BCr(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=xCr(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 RCr(t,f.offsetToLocalFileHeader,h,f)},f.buffer=function(h){return TCr(f.stream(h))},f})})}),LB.props(u)})}});var mot=I((drn,hot)=>{var pot=Da(),MG=Jm(),MB=fot(),UG=z("stream");(!UG.Writable||!UG.Writable.prototype.destroy)&&(UG=Ia());hot.exports={buffer:function(e,t){var r={stream:function(n,i){var o=UG.PassThrough();return o.end(e.slice(n,i)),o},size:function(){return MG.resolve(e.length)}};return MB(r,t)},file:function(e,t){var r={stream:function(n,i){return pot.createReadStream(e,{start:n,end:i&&n+i})},size:function(){return new MG(function(n,i){pot.stat(e,function(o,s){o?i(o):n(s.size)})})}};return MB(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 MG(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 MB(n,r)},s3:function(e,t,r){var n={size:function(){return new MG(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 MB(n,r)},custom:function(e,t){return MB(e,t)}}});var Aot=I(UB=>{"use strict";Ktt();trt();aie();UB.Parse=DG();UB.ParseOne=sit();UB.Extract=not();UB.Open=mot()});var Oot=I((prn,np)=>{var An=z("fs"),qG=z("os"),wo=z("path"),got=z("crypto"),hd={fs:An.constants,os:qG.constants},yot="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Cot=/XXXXXX/,QCr=3,_ot=(hd.O_CREAT||hd.fs.O_CREAT)|(hd.O_EXCL||hd.fs.O_EXCL)|(hd.O_RDWR||hd.fs.O_RDWR),PCr=qG.platform()==="win32",MCr=hd.EBADF||hd.os.errno.EBADF,UCr=hd.ENOENT||hd.os.errno.ENOENT,wot=448,vot=384,$Cr="exit",zw=[],Sot=An.rmdirSync.bind(An),Dot=!1;function qCr(e,t){return An.rm(e,{recursive:!0},t)}function Rot(e){return An.rmSync(e,{recursive:!0})}function bme(e,t){let r=Jw(e,t),n=r[0],i=r[1];XCr(n,function(o,s){if(o)return i(o);let a=s.tries;(function c(){try{let u=xot(s);An.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 Ime(e){let t=Jw(e),r=t[0],n=ZCr(r),i=n.tries;do{let o=xot(n);try{An.statSync(o)}catch{return o}}while(i-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function jCr(e,t){let r=Jw(e,t),n=r[0],i=r[1];bme(n,function(s,a){if(s)return i(s);An.open(a,_ot,n.mode||vot,function(u,d){if(u)return i(u);if(n.discardDescriptor)return An.close(d,function(p){return i(p,a,void 0,yme(a,-1,n,!1))});{let f=n.discardDescriptor||n.detachDescriptor;i(null,a,d,yme(a,f?-1:d,n,!1))}})})}function YCr(e){let t=Jw(e),r=t[0],n=r.discardDescriptor||r.detachDescriptor,i=Ime(r),o=An.openSync(i,_ot,r.mode||vot);return r.discardDescriptor&&(An.closeSync(o),o=void 0),{name:i,fd:o,removeCallback:yme(i,n?-1:o,r,!0)}}function HCr(e,t){let r=Jw(e,t),n=r[0],i=r[1];bme(n,function(s,a){if(s)return i(s);An.mkdir(a,n.mode||wot,function(u){if(u)return i(u);i(null,a,Tot(a,n,!1))})})}function zCr(e){let t=Jw(e),r=t[0],n=Ime(r);return An.mkdirSync(n,r.mode||wot),{name:n,removeCallback:Tot(n,r,!0)}}function JCr(e,t){let r=function(n){if(n&&!Eme(n))return t(n);t()};0<=e[0]?An.close(e[0],function(){An.unlink(e[1],r)}):An.unlink(e[1],r)}function GCr(e){let t=null;try{0<=e[0]&&An.closeSync(e[0])}catch(r){if(!e_r(r)&&!Eme(r))throw r}finally{try{An.unlinkSync(e[1])}catch(r){Eme(r)||(t=r)}}if(t!==null)throw t}function yme(e,t,r,n){let i=$G(GCr,[t,e],n),o=$G(JCr,[t,e],n,i);return r.keep||zw.unshift(i),n?i:o}function Tot(e,t,r){let n=t.unsafeCleanup?qCr:An.rmdir.bind(An),i=t.unsafeCleanup?Rot:Sot,o=$G(i,e,r),s=$G(n,e,r,o);return t.keep||zw.unshift(o),r?o:s}function $G(e,t,r,n){let i=!1;return function o(s){if(!i){let a=n||o,c=zw.indexOf(a);return c>=0&&zw.splice(c,1),i=!0,r||e===Sot||e===Rot?e(t):e(t,s||function(){})}}}function VCr(){if(Dot)for(;zw.length;)try{zw[0]()}catch{}}function Eot(e){let t=[],r=null;try{r=got.randomBytes(e)}catch{r=got.pseudoRandomBytes(e)}for(let n=0;n<e;n++)t.push(yot[r[n]%yot.length]);return t.join("")}function Ra(e){return typeof e>"u"}function Jw(e,t){if(typeof e=="function")return[{},e];if(Ra(e))return[{},t];let r={};for(let n of Object.getOwnPropertyNames(e))r[n]=e[n];return[r,t]}function WCr(e,t,r){let n=wo.isAbsolute(e)?e:wo.join(t,e);An.stat(n,function(i){i?An.realpath(wo.dirname(n),function(o,s){if(o)return r(o);r(null,wo.join(s,wo.basename(n)))}):An.realpath(n,r)})}function KCr(e,t){let r=wo.isAbsolute(e)?e:wo.join(t,e);try{return An.statSync(r),An.realpathSync(r)}catch{let i=An.realpathSync(wo.dirname(r));return wo.join(i,wo.basename(r))}}function xot(e){let t=e.tmpdir;if(!Ra(e.name))return wo.join(t,e.dir,e.name);if(!Ra(e.template))return wo.join(t,e.dir,e.template).replace(Cot,Eot(6));let r=[e.prefix?e.prefix:"tmp","-",process.pid,"-",Eot(12),e.postfix?"-"+e.postfix:""].join("");return wo.join(t,e.dir,r)}function gme(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 kot(e){if(!Ra(e.name)){let t=e.name;if(wo.isAbsolute(t))throw new Error(`name option must not contain an absolute path, found "${t}".`);let r=wo.basename(t);if(r===".."||r==="."||r!==t)throw new Error(`name option must not contain a path, found "${t}".`)}if(!Ra(e.template)){if(typeof e.template!="string")throw new Error(`template option must be a string, got "${typeof e.template}".`);if(!e.template.match(Cot))throw new Error(`Invalid template, found "${e.template}".`)}if(!Ra(e.tries)&&isNaN(e.tries)||e.tries<0)throw new Error(`Invalid tries, found "${e.tries}".`);e.tries=Ra(e.name)?e.tries||QCr:1,e.keep=!!e.keep,e.detachDescriptor=!!e.detachDescriptor,e.discardDescriptor=!!e.discardDescriptor,e.unsafeCleanup=!!e.unsafeCleanup,e.prefix=Ra(e.prefix)?"":gme("prefix",e.prefix),e.postfix=Ra(e.postfix)?"":gme("postfix",e.postfix),e.template=Ra(e.template)?void 0:gme("template",e.template)}function bot(e,t,r,n){if(Ra(t))return n(null);WCr(t,r,function(i,o){if(i)return n(i);let s=wo.relative(r,o);if(s.startsWith("..")||wo.isAbsolute(s))return n(new Error(`${e} option must be relative to "${r}", found "${s}".`));n(null,s)})}function Iot(e,t,r){if(Ra(t))return;let n=KCr(t,r),i=wo.relative(r,n);if(i.startsWith("..")||wo.isAbsolute(i))throw new Error(`${e} option must be relative to "${r}", found "${i}".`);return i}function XCr(e,t){r_r(e,function(r,n){if(r)return t(r);e.tmpdir=n;try{kot(e,n)}catch(i){return t(i)}bot("dir",e.dir,n,function(i,o){if(i)return t(i);e.dir=Ra(o)?"":o,bot("template",e.template,n,function(s,a){if(s)return t(s);e.template=a,t(null,e)})})})}function ZCr(e){let t=e.tmpdir=Bot(e);kot(e,t);let r=Iot("dir",e.dir,t);return e.dir=Ra(r)?"":r,e.template=Iot("template",e.template,t),e}function e_r(e){return Not(e,-MCr,"EBADF")}function Eme(e){return Not(e,-UCr,"ENOENT")}function Not(e,t,r){return PCr?e.code===r:e.code===r&&e.errno===t}function t_r(){Dot=!0}function r_r(e,t){return An.realpath(e&&e.tmpdir||qG.tmpdir(),t)}function Bot(e){return An.realpathSync(e&&e.tmpdir||qG.tmpdir())}process.addListener($Cr,VCr);Object.defineProperty(np.exports,"tmpdir",{enumerable:!0,configurable:!1,get:function(){return Bot()}});np.exports.dir=HCr;np.exports.dirSync=zCr;np.exports.file=jCr;np.exports.fileSync=YCr;np.exports.tmpName=bme;np.exports.tmpNameSync=Ime;np.exports.setGracefulCleanup=t_r});var Lot=I((hrn,Fot)=>{Fot.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([n_r(t,"data"),i])):(t.pause(),yield r.shift()),s)throw s;n()};function n_r(e,t){return new Promise(r=>{let n=!1,i=()=>{n||(n=!0,e.removeListener(t,i),r())};e.addListener(t,i)})}});var Uot=I((mrn,Mot)=>{var{EventEmitter:i_r}=z("events"),o_r=Kk(),s_r=ki(),jG=Ts(),Qot=mi(),a_r=Tf(),c_r=Ij(),Pot=Cj(),Cme=class extends i_r{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 a_r}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=Qot.l2n(t)}if(this._columns||(this._columns=[]),t>this._columns.length){let r=this._columns.length+1;for(;r<=t;)this._columns.push(new Pot(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){s_r.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 o_r(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 c_r(this,w),C.attributes.ht&&(h.height=parseFloat(C.attributes.ht)),C.attributes.s){let T=parseInt(C.attributes.s,10),D=a.getStyleModel(T);D&&(h.style=D)}}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=Pot.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=Qot.decodeAddress(m.ref),T=h.getCell(w.col);if(m.s){let D=a.getStyleModel(m.s);D&&(T.style=D)}if(m.f){let D={formula:m.f.text};m.v&&(m.t==="str"?D.result=jG.xmlDecode(m.v.text):D.result=parseFloat(m.v.text)),T.value=D}else if(m.v)switch(m.t){case"s":{let D=parseInt(m.v.text,10);s?T.value=s[D]:T.value={sharedString:D};break}case"inlineStr":case"str":T.value=jG.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:jG.isDateFmt(T.numFmt)?T.value=jG.excelToDate(parseFloat(m.v.text),c.model&&c.model.date1904):T.value=parseFloat(m.v.text);break}if(o){let D=o[m.ref];D&&(T.text=T.value,T.value=void 0,T.hyperlink=D)}m=null}break;default:break}(i||o)&&C.name==="hyperlinks"&&(f=!1)}y.length>0&&(yield y)}}};Mot.exports=Cme});var qot=I((Arn,$ot)=>{var{EventEmitter:l_r}=z("events"),u_r=Kk(),d_r=Yl(),f_r=Kh(),_me=class extends l_r{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 u_r(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 f_r.Hyperlink:{let d={type:d_r.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)}}};$ot.exports=_me});var zot=I((grn,Hot)=>{var wme=z("fs"),{EventEmitter:p_r}=z("events"),{PassThrough:h_r,Readable:m_r}=zk(),A_r=z("stream"),g_r=Aot(),Yot=Oot(),bE=Lot(),y_r=Kk(),jot=eH(),E_r=sH(),b_r=iH(),I_r=Uot(),C_r=qot();Yot.setGracefulCleanup();var YG=class extends p_r{constructor(t,r={}){super(),this.input=t,this.options={worksheets:"emit",sharedStrings:"cache",hyperlinks:"ignore",styles:"ignore",entries:"ignore",...r},this.styles=new jot,this.styles.init()}_getStream(t){if(t instanceof A_r.Readable||t instanceof m_r)return t;if(typeof t=="string")return wme.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=g_r.Parse({forceStream:!0});n.pipe(i);let o=[];for await(let s of bE(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(bE(s),c):await new Promise((u,d)=>{Yot.file((f,p,h,m)=>{if(f)return d(f);o.push({sheetNo:c,path:p,tempFileCleanupCallback:m});let A=wme.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(bE(s),c));break}s.autodrain()}for(let{sheetNo:s,path:a,tempFileCleanupCallback:c}of o){let u=wme.createReadStream(a);u[Symbol.asyncIterator]||(u=u.pipe(new h_r)),yield*this._parseWorksheet(u,s),c()}}_emitEntry(t){this.options.entries==="emit"&&this.emit("entry",t)}async _parseRels(t){let r=new b_r;this.workbookRels=await r.parseStream(bE(t))}async _parseWorkbook(t){this._emitEntry({type:"workbook"});let r=new E_r;await r.parseStream(bE(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 y_r(bE(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 jot,await this.styles.parseStream(bE(t)))}*_parseWorksheet(t,r){this._emitEntry({type:"worksheet",id:r});let n=new I_r({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 C_r({workbook:this,id:r,iterator:t,options:this.options});this.options.hyperlinks==="emit"&&(yield{eventType:"hyperlinks",value:n})}};YG.Options={worksheets:["emit","ignore"],sharedStrings:["cache","emit","ignore"],hyperlinks:["cache","emit","ignore"],styles:["cache","ignore"],entries:["emit","ignore"]};Hot.exports=YG});var Vot=I((yrn,Got)=>{var Jot={Workbook:J3e(),ModelContainer:V3e(),stream:{xlsx:{WorkbookWriter:Vtt(),WorkbookReader:zot()}}};Object.assign(Jot,Yl());Got.exports=Jot});var Kot=I((Ern,Wot)=>{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");Wot.exports=Vot()});function est(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 v_r(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 S_r(e){let r=(await Promise.resolve().then(()=>uo(R$e(),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());est(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 vme(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?vme(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 D_r(e){let t=(await Promise.resolve().then(()=>uo(VZ(),1))).default,n=new t(Buffer.from(e)).getEntries().reduce((i,o)=>i+o.header.size,0);if(n>Xot)throw new Error(`XLSX uncompressed size ${n} bytes exceeds ${Xot}-byte safety cap`)}function tst(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(vme(s)??"").trim()))}),{headerRowNum:t,columns:r}}function Zot(e){let{headerRowNum:t,columns:r}=tst(e);if(!t)return{columns:[],rows:[]};est(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]]=vme(s[c]);n.push(a)}),{columns:r,rows:n}}async function R_r(e,t,r){await D_r(e);let n=await Promise.resolve().then(()=>uo(Kot(),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{...Zot(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(tst(d).headerRowNum!==0)try{return{...Zot(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 rst(e){let t=Math.max(0,e.offset??0),r=Math.min(__r,Math.max(1,e.limit??w_r)),n=e.sheetIndex??0,i=await lf(e.sourceUrl),o=await wc(i,{timeoutMs:JI,maxBytes:IM});if(!o.ok)throw new Error(`fetch ${e.sourceUrl}: ${o.status} ${o.statusText}`);let s=await o.arrayBuffer(),a=e.kind??v_r(e.sourceUrl,o.headers.get("content-type")),c,u,d,f,p=n;if(a==="csv"){let A=await S_r(new TextDecoder("utf-8").decode(s));c=A.columns,u=A.rows}else{let A=await R_r(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 __r,w_r,Xot,nst=J(()=>{"use strict";Lu();__r=500,w_r=200,Xot=100*1024*1024});function T_r(e){if(e.internalNotes!==void 0)throw ut(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 ut(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 ist(e){return{create:(t,r)=>t.post(`/api/v1/${Gw[e]}`,{saveAsDraft:!1,...r,currency:Wt(r.currency),taxCurrency:Wt(r.taxCurrency)},Wi),list:(t,r)=>t.list(`/api/v1/${Gw[e]}`,r),get:(t,r)=>t.get(`/api/v1/${Gw[e]}/${r}`),update:async(t,r,n,i)=>{T_r(n);let o={...n,resourceId:r};if(!o.accountResourceId){let s=i??(await t.get(`/api/v1/${Gw[e]}/${r}`)).data;if(o.accountResourceId=s.organizationAccountResourceId??s.account?.resourceId,!o.accountResourceId)throw new Error(`accountResourceId required for ${Gw[e]} update and could not be derived from existing entry`)}return o.currency&&(o.currency=Wt(o.currency)),t.put(`/api/v1/${Gw[e]}/${r}`,o)}}}var Gw,HG,zG,JG,GG,IE,VG,WG,KG,CE,XG,ZG=J(()=>{"use strict";tr();ot();Gw={IN:"cash-in-entries",OUT:"cash-out-entries"};HG=ist("IN"),zG=ist("OUT"),JG=HG.create,GG=HG.list,IE=HG.get,VG=HG.update,WG=zG.create,KG=zG.list,CE=zG.get,XG=zG.update});async function $B(e,t){return e.post("/api/v1/cash-transfers",{saveAsDraft:!1,...t},Wi)}async function eV(e,t){return e.list("/api/v1/cash-transfers",t)}async function tV(e,t){return e.get(`/api/v1/cash-transfers/${t}`)}var Sme=J(()=>{"use strict";tr();an()});async function rV(e,t){return e.list("/api/v1/scheduled/invoices",t)}async function nV(e,t){return e.list("/api/v1/scheduled/bills",t)}async function iV(e,t){return e.list("/api/v1/scheduled/journals",t)}async function Vw(e,t){return e.get(`/api/v1/scheduled/invoices/${t}`)}async function oV(e,t,r){return e.put(`/api/v1/scheduled/invoices/${t}`,r)}async function sV(e,t){await e.delete(`/api/v1/scheduled/invoices/${t}`)}async function Ww(e,t){return e.get(`/api/v1/scheduled/bills/${t}`)}async function aV(e,t,r){return e.put(`/api/v1/scheduled/bills/${t}`,r)}async function cV(e,t){await e.delete(`/api/v1/scheduled/bills/${t}`)}async function Kw(e,t){return e.get(`/api/v1/scheduled/journals/${t}`)}async function lV(e,t,r){let{currency:n,...i}=x_r(r);return e.put(`/api/v1/scheduled/journals/${t}`,n===void 0?i:{...i,currency:Wt(n)})}function x_r(e){let t={...e};xM(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 ut(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 uV(e,t){await e.delete(`/api/v1/scheduled/journals/${t}`)}var dV=J(()=>{"use strict";ot()});import{statSync as ost}from"node:fs";function sst(e){for(let t of e)try{if(ost(t).isFile())return t}catch{}return null}function ast(e){for(let t of e)try{if(ost(t).isDirectory())return t}catch{}return null}var Dme=J(()=>{"use strict"});import{readFileSync as Tme}from"node:fs";import{dirname as dst,join as Zm}from"node:path";import{fileURLToPath as fst}from"node:url";function pst(e){let t=new Set(e);for(let r of e){let n=B_r.get(r);if(n)for(let i of n)t.add(i)}return Array.from(t)}function hst(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&&!N_r.has(n))}function qB(e){let t=e??P_r();if(fV&&ust===t)return fV;let r=Tme(t,"utf-8");return fV=JSON.parse(r),ust=t,fV}function mst(){let e=fst(import.meta.url),t=dst(e),r=[Zm(t,"..","..","..","help-center-mirror","help-center-index.json"),Zm(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-index.json"),Zm(t,"help-center-mirror","help-center-index.json")];return sst(r)??void 0}function P_r(){let e=mst();if(!e)throw new Error("Help center index not found. Run the help center sync or reinstall the package.");return e}function jB(){return Rme===null&&(Rme=mst()!==void 0),Rme}function _E(e,t,r={}){let n=r.limit??5,i=hst(t);if(i.length===0)return[];let o=pst(i).slice(0,L_r),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>=F_r){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>=Q_r))break}if(m===0)continue;f.push(g?`${h}*`:h);let y=m*(cst+1),b=m+cst*(1-lst+lst*(c.tokenCount/e.avgDocLen)),E=A*(y/b);g&&(E*=O_r),p.includes(h)&&(E*=k_r),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 xme(e,t){let r=t??M_r();if(!r)return null;try{let n=Zm(r,`${e.section}.md`),i=Tme(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 M_r(){let e=fst(import.meta.url),t=dst(e),r=[Zm(t,"..","..","..","help-center-mirror"),Zm(t,"..","..","..","assets","skills","api","help-center-mirror"),Zm(t,"help-center-mirror")];for(let n of r)try{return Tme(Zm(n,"index.md"),"utf-8"),n}catch{}return null}var cst,lst,k_r,N_r,B_r,O_r,F_r,L_r,Q_r,fV,ust,Rme,YB=J(()=>{"use strict";Dme();Tg();cst=1.2,lst=.75,k_r=1.5,N_r=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"]),B_r=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"]]]);O_r=.7,F_r=3,L_r=32,Q_r=5;fV=null,ust=null;Rme=null});import{existsSync as U_r,readFileSync as $_r}from"node:fs";import{dirname as q_r,join as kme}from"node:path";import{fileURLToPath as j_r}from"node:url";function HB(e){let t=e??G_r();if(!t)return null;if(pV&&gst===t)return pV;try{let r=$_r(t,"utf-8");return pV=JSON.parse(r),gst=t,pV}catch{return null}}function G_r(){let e=j_r(import.meta.url),t=q_r(e),r=[kme(t,"..","..","..","help-center-mirror","help-center-embeddings.json"),kme(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),kme(t,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(U_r(n))return n;return null}function bst(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 Ist(){return hV!==null?hV:(hV=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",hV||null)}async function Nme(e){let t=Ist();if(!t)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),H_r),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:Y_r,input:e}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!yst&&(yst=!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??z_r,c=n.minBm25??J_r;if(i==="bm25"||!t)return _E(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Nme(r);return m?Est(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):_E(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Nme(r),Promise.resolve(_E(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Est(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Cst(p,h,o)}function Est(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=bst(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 Cst(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Ast+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/(Ast+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 Bme(e){return e!==null&&!!Ist()}var Y_r,H_r,Ast,z_r,J_r,pV,gst,hV,yst,mV=J(()=>{"use strict";YB();Y_r="text-embedding-3-small",H_r=2e3,Ast=60,z_r=.3,J_r=1.5,pV=null,gst=null,hV=null,yst=!1});async function _st(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=qB();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:HB(),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=(xme(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 wst(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:V_r}async function AV(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(wst())}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(W_r),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return K_r(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 K_r(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Ome(e,t={}){return process.env.CLIO_DAEMON==="1"||jB()?_st(e,t):AV(e,t)}var V_r,W_r,vst=J(()=>{"use strict";YB();mV();V_r="https://mcp.jaz.ai/help-center/search",W_r=4e3});var Fme=J(()=>{"use strict";YB();mV();vst();YB()});async function eA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function tA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var JB=J(()=>{"use strict";an()});async function gV(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency)},zke)}var Lme=J(()=>{"use strict";ot();tr()});async function yV(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function EV(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function GB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function bV(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Qme=J(()=>{"use strict"});function X_r(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Xw(e,t){return e.post("/api/v1/jots",{entries:t.map(X_r)})}async function IV(e,t){return e.post("/api/v1/jots/search",t,et)}async function Sst(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var CV=J(()=>{"use strict";tr()});async function Dst(e,t){return e.post("/api/v1/agents/memories",t)}async function Pme(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Rst=J(()=>{"use strict";tr()});function _V(){return process.env.ENABLE_MEMORY==="true"}function Mme(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Tst(e){return!_V()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Ume=J(()=>{"use strict"});import{createHash as Z_r}from"node:crypto";function uwr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:Nst.some(r=>t.includes(r))?[null,"directive_invalid"]:kst.test(t)?[null,"directive_invalid"]:owr.test(t)?[null,"directive_contains_url"]:swr.test(t)?[null,"directive_contains_email"]:[t,null]}function dwr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>awr?[null,"match_condition_too_long"]:Nst.some(r=>t.includes(r))?[null,"match_condition_invalid"]:kst.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function fwr(e){return e==null?[null,null]:Number.isInteger(e)?e<cwr||e>lwr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function pwr(e,t,r,n,i,o,s,a){if(e)return Z_r("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function hwr(e){Promise.resolve().then(()=>(mD(),hD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Lst(e,t,r){let n=t.action,i=t.category,o=nwr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(hwr({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=Tst(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>ewr||!iwr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=uwr(t.directive);if(E)return u(E);p=b;let[C,w]=fwr(t.importance);if(w)return u(w);h=C}let[m,A]=dwr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=twr)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,rwr));let E=pwr(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 $me(()=>Dst(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await $me(()=>Pme(e.client,b))}else{let b={forgetAll:!0};y=await $me(()=>Pme(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function $me(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 kst,Nst,ewr,twr,rwr,Bst,Ost,Fst,nwr,iwr,owr,swr,awr,cwr,lwr,Qst=J(()=>{"use strict";Rst();Ki();Ume();Ume();kst=/[\x00-\x1f\x7f]/,Nst=["{{","}}","```","<",">"],ewr=120,twr=3,rwr=140,Bst=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Ost=["set","forget","forget_all"],Fst=["this_org","all_orgs"],nwr={this_org:"ORG_USER",all_orgs:"USER"},iwr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,owr=/https?:\/\//i,swr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,awr=255,cwr=0,lwr=100});async function wV(e,t){return e.list("/api/v1/organization-users",t)}async function vV(e,t){return e.search("/api/v1/organization-users/search",t)}async function Zw(e,t){return e.post("/api/v1/organization-users/invite",t)}async function SV(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function DV(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var qme=J(()=>{"use strict"});async function RV(e,t){return e.get(`/api/v1/payments/${t}`)}async function TV(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Wt(r.currency)})}async function xV(e,t){await e.delete(`/api/v1/payments/${t}`)}function kV(e){return(t,r)=>t.post(`/api/v1/${mwr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Wt(n.currency)}))},Lke)}var mwr,Cnn,Pst,_nn,wnn,jme=J(()=>{"use strict";ot();tr();mwr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};Cnn=kV("saleBulk"),Pst=kV("saleBatch"),_nn=kV("purchaseBulk"),wnn=kV("purchaseBatch")});async function ip(e,t,r,n,i,o=Hke){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?ut(c):new rf(`${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 zp?ut(c):c}let a=s?.data;if(!i(a))throw new rf(`${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 BV(e,t,r){try{Zi(e,t,r)}catch(n){throw ut(n)}}function wE(e){return BV(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function OV(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function FV(e,t){return ip(e,"POST",Awr,t,rA)}async function LV(e,t,r){return ip(e,"PUT",`/api/v1/unapplied-payments/${wE(t)}`,r,rA)}async function QV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/activate`,{hash:r},rA)}async function PV(e,t,r,n){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/attributions`,{hash:r,attributions:n},rA)}async function MV(e,t,r,n){return BV(n,"paymentResourceId","Pass the payment record resourceId."),ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/payments`,{hash:r,paymentResourceId:n},rA)}async function UV(e,t,r,n){return BV(r,"childResourceId","Pass the payment record resourceId from the children list."),ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}/children/${encodeURIComponent(r)}`,{hash:n},rA)}async function $V(e,t,r){return ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}`,{hash:r},rA)}async function qV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/unbatch`,{hash:r},rA)}async function jV(e,t){return BV(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),ip(e,"POST",gwr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,ya)}var Awr,gwr,NV,Mst,Ust,rA,Yme=J(()=>{"use strict";Ki();tr();lP();ot();Awr="/api/v1/unapplied-payments",gwr="/api/v1/reconciliations/unapplied-payment",NV=["SALE","PURCHASE"],Mst=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ust=["AMOUNT","PERCENTAGE"];rA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function YV(e,t,r={},n=Hme){let i=ywr.has(t)?`/api/v1/${Sc($st,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=Hg.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...Hg.keys()].join(", ")}.`);let A=await Df(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...et,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new ue(`${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: ${[...VB].join(", ")}.`}:d}var $st,ywr,Hme,VB,qst,zme=J(()=>{"use strict";tr();ot();Mx();Yu();$st=["statement-of-account-export"],ywr=new Set($st),Hme=9e4,VB=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"]),qst={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as Ewr}from"node:crypto";import{writeFile as bwr,mkdir as Iwr}from"node:fs/promises";import{dirname as Cwr,isAbsolute as _wr,join as wwr}from"node:path";async function HV(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},et)}async function WB(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 ev(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function jst(e){return`query-export-${e.slice(0,8)}.csv`}function Jme(e){return Ewr("sha256").update(e).digest("hex").slice(0,16)}async function zV(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Jme(t),o=await WB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await ev(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await ev(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&&!_wr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??wwr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Iwr(Cwr(p),{recursive:!0}),await bwr(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 JV(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 ue(`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 tv(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 Gme=J(()=>{"use strict";ot();tr()});async function Ei(e,t,r){let n=await e.get(`/api/v1/${Vme[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function GV(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/${Vme[r]}/${n}/attachments`,o)}async function VV(e,t,r,n){return e.delete(`/api/v1/${Vme[t]}/${r}/attachments/${n}`)}var Vme,KB,nA=J(()=>{"use strict";Vme={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"},KB=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function kwr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&xwr.some(n=>r.startsWith(n)))}async function op(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&kwr(t)&&(t.refusal=Twr),t}}function Yst(e,t,r){return Zi(e,t,r),e.toLowerCase()}function rv(e,t){return{type:Sc(Wme,e,"entityType"),record:Yst(t,"entityId",vwr)}}function XB(e){DZ(e,"threadId",Dwr)}function Hst(e){DZ(e,"commentId",Rwr)}function nv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Yst(e.bankAccountResourceId,"bankAccountResourceId",Swr)}}async function zst(e,t,r,n={}){let{type:i,record:o}=rv(t,r),s={...nv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return op(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Jst(e,t,r,n,i={}){let{type:o,record:s}=rv(t,r),a={...nv(i),limit:i.limit,offset:i.offset};return XB(n),op(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Gst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return n.threadId!==void 0&&XB(n.threadId),(await op(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...Yke,query:a}))).data}async function Vst(e,t,r,n,i,o,s){let{type:a,record:c}=rv(t,r),u=nv(s);return XB(n),Hst(i),(await op(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function Wst(e,t,r,n,i,o){let{type:s,record:a}=rv(t,r),c=nv(o);return XB(n),Hst(i),(await op(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function Kst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return XB(n),(await op(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function Xst(e,t={}){return op(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function Zst(e,t,r){return HNe(t,"Get it from list_notifications."),(await op(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function eat(e){return(await op(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Wme,vwr,Swr,Dwr,Rwr,Twr,xwr,tat=J(()=>{"use strict";Ki();ot();tr();Wme=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],vwr="Pass the resourceId of the bill, invoice, credit note or bank record.",Swr="Pass the resourceId of the bank account that holds the bank record.",Dwr="Get it from list_comment_threads.",Rwr="Get it from list_comments or list_comment_threads.",Twr={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."},xwr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Qo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var iv=J(()=>{"use strict"});async function WV(e,t){return e.post("/api/v1/claims/conversion/preview",t,et)}async function KV(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new ue('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:AP)}var ZB,Kme=J(()=>{"use strict";ot();tr();ZB=["POST","POST_AND_RECORD"]});async function XV(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,Qke)}async function ZV(e,t){return e.search("/api/v1/employees/payouts/search",t)}var rat,Xme=J(()=>{"use strict";ot();tr();rat=["REIMBURSEMENT","ADVANCE"]});async function e8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Zme=J(()=>{"use strict"});function eAe(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 tAe(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: ${nat(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=>Pu.has(u)),s=i.filter(u=>!Pu.has(u)&&Rc.has(u)),a=[`Nothing here can be extracted: found ${nat(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=KBe[u];d&&a.push(d)}return o.length>0&&a.push(`${eU(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(`${eU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Pu.has(u)&&!Rc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${eU([...Pu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function nat(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 iat=J(()=>{"use strict";Mu()});function t8(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function eO(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&&t8()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function vE(e,t){return{error:e,hint:t,...rAe}}function oat(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: ${eO(e)}.`,...rAe}}function SE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function iA(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: ${eO({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.",...rAe,...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 rAe,sat=J(()=>{"use strict";rAe={kind:"validation",retriable:!1}});import{randomUUID as Nwr}from"node:crypto";import{rmSync as Bwr}from"node:fs";function iAe(e){for(let t of e.tempDirs??[])try{Bwr(t,{recursive:!0,force:!0})}catch{}}function cat(e){for(let[t,r]of DE)e-r.createdAt>aat&&(iAe(r.plan),DE.delete(t))}function Fwr(){nAe||(nAe=setInterval(()=>cat(Date.now()),Owr),nAe.unref?.())}function oAe(e,t){let r=Date.now();cat(r),Fwr();let n=`dc_${Nwr()}`;return DE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function sAe(e,t){let r=DE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>aat?(iAe(r.plan),DE.delete(e),null):r.plan}function lat(e,t){let r=DE.get(e);!r||r.ownerKey!==t||(iAe(r.plan),DE.delete(e))}var aat,Owr,DE,nAe,uat=J(()=>{"use strict";aat=1800*1e3,Owr=300*1e3,DE=new Map});function Lwr(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 dat(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>_g(i.documentType)&&r.has(i.documentType))}))}}async function fat(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?dat(t,i):t;if(!n&&Qwr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");vD(o);let a=await mU({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"?Lwr(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 pat(e,t){return(t&&t.length>0?dat(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>_g(o.documentType)).length,0)}function Qwr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var hat=J(()=>{"use strict";nee();Mu();Af()});function Pwr(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 Uwr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function $wr(e,t){if(e!==Mwr)return;let r=Uwr(t);if(r)return mat.get(r)??mat.get(r.replace(/_ERROR$/,""))}function r8(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 qwr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=r8(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 aAe(e){return $wr(e.status,e.body)??e.refusal?.hint??qwr(e)}function RE(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 n8(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function tO(e,t={}){let r=t.readOnly===!1&&PD()?PFe:"";if(e instanceof gr){let o=[aAe(e)??Pwr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...r8(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=i8(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 ct;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var Mwr,mat,TE=J(()=>{"use strict";Ki();fo();o8();bU();Mwr=422,mat=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 md(e,t,r){if(!t)return e;let n=jwr(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 Ad(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${RE(i)}`],...n}}}function jwr(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 sp(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var Aat=J(()=>{"use strict";TE()});async function s8(e,t){return e.list("/api/v1/bank-rules",t)}async function rO(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 a8(e,t){return e.search("/api/v1/bank-rules/search",t)}async function c8(e,t){return e.post("/api/v1/bank-rules",t)}async function l8(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function u8(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var cAe=J(()=>{"use strict"});async function d8(e,t){return e.list("/api/v1/fixed-assets",t)}async function xE(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function nO(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function f8(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},iZ)}function yat(e,t){let r={};for(let n of Ywr){let i=e[n];if(i==null)continue;let o=Hwr.has(n)?cf(i):i;o!==void 0&&(r[n]=o)}for(let[n,i]of Object.entries(t))i!==void 0&&n!=="resourceId"&&(r[n]=i);return r}async function p8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ut(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await xE(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,yat(i,r))}async function h8(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function m8(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},hP)}async function iO(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,hP)}async function A8(e,t){return e.post("/api/v1/transfer-fixed-assets",t,iZ)}async function g8(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},hP)}async function y8(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},oZ)}async function E8(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},oZ)}async function zwr(e,t){let r=new Map;for(let i=0;i<t.length;i+=gat){let o=t.slice(i,i+gat),s=await nO(e,{filter:{resourceId:{in:o}},limit:o.length});for(let a of s.data)r.set(a.resourceId,a)}let n=t.filter(i=>!r.has(i));if(n.length>0)throw ut(new ue(`No fixed asset found for ${n.length} resourceId${n.length===1?"":"s"}: ${n.join(", ")}. Nothing was submitted; fix or remove those rows and retry.`));return r}async function b8(e,t){mt(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=HS(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw ut(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw ut(new ue(`resourceId ${u} appears more than once in fixedAssets; put all of an asset's changes in one row. Nothing was submitted.`));return r.add(u),u}),i=t.map((a,c)=>Xn(a.tags,`fixedAssets[${c}].tags`)),o=await zwr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...yat(u,{...a,tags:d&&ui(u.tags,d)})}});return En(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function I8(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function C8(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function _8(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,et)}async function w8(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},et)}async function v8(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function S8(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function D8(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function Gwr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function Vwr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=Gwr(i);if(o.length===0)return;let s=typeof i.reference=="string"&&i.reference?` (${i.reference})`:"";t.push(`row ${n}${s}: ${o.map(a=>`${a} (${Jwr[a]})`).join(", ")}`)}),t.length>0)throw ut(new ue(`Every fixed asset row needs its reference, registrationType and depreciationStartDate; the import job rejects a row without them. Missing: ${t.join("; ")}. Nothing was sent.`))}async function R8(e,t){return mt(t,"fixedAssets",500,"fixed assets"),SNe(t,["purchaseDate","depreciationStartDate"]),Vwr(t),En(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var oA,Ywr,Hwr,gat,Jwr,T8=J(()=>{"use strict";an();KS();tr();ot();xl();oA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];Ywr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],Hwr=new Set(["purchaseDate","depreciationStartDate"]);gat=100;Jwr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function x8(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function kE(e,t){return e.get(`/api/v1/leases/${t}`)}async function k8(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},Uke)}async function N8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names lease ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await kE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function B8(e,t){await e.delete(`/api/v1/leases/${t}`)}async function O8(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},qS)}async function F8(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},qS)}async function L8(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},qS)}async function Q8(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},et)}async function P8(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},qS)}async function M8(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function U8(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function $8(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function q8(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,et)}async function j8(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,et)}async function Y8(e,t){return mt(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`leases[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that lease. Bulk update does not take tags: change them with update_lease (clio leases update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/leases/bulk-update","leases",t)}var lAe=J(()=>{"use strict";an();ot();tr()});async function H8(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function NE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function z8(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Jp)}async function J8(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 NE(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 Wwr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function Wwr(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 G8(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function V8(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 W8(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var K8=J(()=>{"use strict";tr()});async function X8(e,t){return e.list("/api/v1/contact-groups",t)}async function Z8(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function eW(e,t){return e.search("/api/v1/contact-groups/search",t)}async function tW(e,t){return e.post("/api/v1/contact-groups",t)}async function rW(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,TI(r,hZ))}async function nW(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var uAe=J(()=>{"use strict";an()});async function iW(e,t){return e.list("/api/v1/inventory-items",t)}async function oW(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function sW(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function cW(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&Kwr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var aW,Kwr,dAe=J(()=>{"use strict";Ki();aW=["ALL","AVAILABLE","FULLY_DRAWN"],Kwr=/Inventory balance Not Found/i});async function lW(e,t){return e.list("/api/v1/custom-fields",t)}async function oO(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function uW(e,t){return e.search("/api/v1/custom-fields/search",t)}async function dW(e,t){return e.post("/api/v1/custom-fields",t)}function Zwr(e){return e!==void 0&&Xwr.every(t=>e[t]!==void 0)}function evr(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 tvr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function fW(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!Zwr(n.appliesTo)){let i=await oO(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??tvr(i.data),n.appliesTo={...evr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function pW(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var Xwr,fAe=J(()=>{"use strict";Xwr=["invoices","bills","customerCredits","supplierCredits","payments"]});var el,BE,rvr,nvr,pAe,hW,mW,ivr,Ta,ru,OE,ov,FE,hAe=J(()=>{"use strict";el={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"]},BE={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."}}},rvr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},nvr={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"]},pAe={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"]},hW={type:"object",properties:{billingAddress:{...pAe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},mW={type:"object",properties:{billingAddress:{...pAe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...pAe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},ivr={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"]},Ta={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:ivr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},ru={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)."}}},OE={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"]},ov={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...el,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:BE},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:{...el,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:{...rvr,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:{...nvr,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:{...hW,description:"Issuer identity and billing address (credit from)."},creditTo:{...mW,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...el,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:BE},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:{...el,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:{...hW,description:"Seller identity and billing address."},billTo:{...mW,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:{...el,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:BE},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:{...el,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:{...el,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:BE},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:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,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:{...el,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:BE},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:{...el,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:{...hW,description:"Seller identity and billing address."},billTo:{...mW,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:BE},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:{...el,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:BE},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,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)."}}},FE={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:Ta},discount:{...ru,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:{...OE,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:Ta},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:Ta},discount:{...ru,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:Ta},discount:{...ru,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:Ta},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:Ta},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:Ta},discount:{...ru,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:{...OE,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:Ta},discount:{...ru,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:{...OE,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:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,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:{...OE,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:Ta},discount:{...ru,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:Ta},discount:{...ru,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:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,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:{...OE,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:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,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:{...OE,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:Ta},discount:{...ru,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:{...OE,description:"Withholding tax details for this line item."}}}}});function AAe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function gAe(e){let t=e.updated??[],r=AAe(e.failed);return{...t.length===0&&r.length>0?{error:avr}:{},updated:t,failed:r}}function bat(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function AW(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Iat(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=bat(s);if(a)for(let c of Array.isArray(o)?o:[o])AW(c)&&n.push(...Iat(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function cvr(e){return Object.entries(e).map(([t,r])=>{let n=bat(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function yAe(e,t,r){if(!AW(t))return;let n=Iat(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw ut(new ct(`${e} has no field ${i.join("; ")}. Fields: ${cvr(r)}. Nothing was changed.`))}function lvr(e){let t=ov[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 uvr(e){let t=FE[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 dvr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!AW(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw ut(new ct(`${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(!AW(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw ut(new ct(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));yAe(`${e} line items`,a.attributes,t.fields)}}}function Cat(e){if(sv.includes(e))return;let t=yW.includes(e);throw ut(new ct(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: ${sv.join(", ")}.`))}async function cv(e,t,r){Cat(t),yAe(`${t} quick fix`,r.attributes,lvr(t));let n=await e.post(`/api/v1/quick-fix/${Sc(sv,t)}`,r);return gAe(n)}async function fvr(e,t){try{return await IE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return CE(e,t);throw r}}async function _at(e,t,r,n){Cat(t);let i=EAe[t],o=async d=>i.tags(await Xi(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Eat)s.push(...await Promise.all(r.resourceIds.slice(d,d+Eat).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=ui(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 cv(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 gAe({updated:c,failed:u})}async function sO(e,t,r){let n=Sc(av,t),i=uvr(t);i.entryKeys?dvr(t,i,r.schedulerUpdates):yAe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return gAe(o)}var ovr,svr,gW,yW,sv,av,avr,LE,mAe,EAe,Eat,EW=J(()=>{"use strict";Ki();ot();fo();hAe();xl();zg();af();Hx();Kx();Jg();ZG();dV();K8();ovr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],svr=["journals","cash-entries"],gW=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],yW=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],sv=[...ovr,...svr,...gW],av=[...sv,...yW],avr="Nothing changed: every record failed. See failed for each reason.";LE=e=>e?.tags,mAe=e=>e?.data?.tags,EAe={invoices:{noun:"invoice",get:(e,t)=>Eo(e,t),tags:LE},bills:{noun:"bill",get:(e,t)=>ho(e,t),tags:LE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>Vs(e,t),tags:LE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>Ws(e,t),tags:LE},journals:{noun:"journal",get:(e,t)=>vs(e,t),tags:LE},"cash-entries":{noun:"cash entry",get:(e,t)=>fvr(e,t),tags:LE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Vw(e,t),tags:mAe},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Ww(e,t),tags:mAe},"subscription-schedules":{noun:"subscription",get:(e,t)=>NE(e,t),tags:mAe},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Kw(e,t),tags:LE}},Eat=10});function bW(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=bW(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<hvr&&i.length<=mvr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,bW(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function vat(e,t,r){let n=Avr(t);if(!n)return[];let i=gvr(r);if(!i){if(wat[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]?vat(o,s,i[o]):[])}function yvr(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 bAe(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=Evr(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]??bW(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=>bW(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[wat[c],yvr(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 vat(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 Tat(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>pvr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var pvr,wat,hvr,mvr,Avr,gvr,Evr,bvr,Ivr,lv,Sat,Dat,Rat,xat,kat,Nat,IAe=J(()=>{"use strict";hAe();xl();pvr={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"},wat={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:`${Yo.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}."},hvr=2,mvr=8;Avr=e=>e.properties??e.items?.properties,gvr=e=>e.properties??e.items?.properties;Evr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),bvr={tags:Yo};Ivr=Object.entries(FE).filter(([,e])=>!e.entryKeys),lv=Object.entries(FE).filter(([,e])=>e.entryKeys),Sat=bAe({...ov},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",bvr),Dat=bAe(Object.fromEntries(Ivr.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."),Rat=(()=>{let e=n=>lv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=lv[0],r=[...new Set(lv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>lv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${lv.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:bAe(Object.fromEntries(lv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();xat=[...new Set([...Object.keys(ov),...Object.keys(FE)])].map(e=>e.replace(/-/g," ")).join(", "),kat=Tat(Object.values(ov)),Nat=Tat(Object.values(FE).map(e=>e.fields))});function IW(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var CAe=J(()=>{"use strict"});function _W(){return sA.map(e=>`${e} sets ${dv[e].change.join(", ")}`).join("; ")}function Uat(e){let t={};for(let r of e)t[r]=Object.hasOwn(Oat,r)?Oat[r]:wvr.find(([n])=>n.test(r))?.[1]??vvr;return Object.keys(t).length>0?t:void 0}function $at(e){if(!(e instanceof gr)||!e.endpoint.startsWith(_vr))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(Fat,n))return;let{hint:i,repairTool:o,command:s}=Fat[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===Pat.LINE_ITEMS?"line items":"records",...e.endpoint===CW?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function Rvr(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 Tvr(e){return typeof e=="string"&&sA.includes(e)}function xvr(e,t){if(!Tvr(e))throw new ct(`level must be one of ${sA.join(", ")}.`);let r=sA.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))dv[e][i].includes(s)||n.push(dv[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}=dv[e];throw new ct(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Lat(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 ct(`${e} must be a JSON object, not ${n}.`)}async function vW(e,t,r){let n={filter:Lat("filter",r.filter),change:Lat("change",r.change)};xvr(t,n);let i;try{i=await e.post(Pat[t],{filter:n.filter,change:n.change},et)}catch(u){throw $at(u),u}let{data:o,...s}=i,a=Uat([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=Rvr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function wAe(e,t){return{error:`${t} ${jat}`,outcome:"UNKNOWN",previewId:e,next:qat}}function Bvr(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 wAe(e,"The apply answered without a per-record result.");let i=AAe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=Uat(Object.keys(o)),a=o[Svr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Nvr}:a==="UNKNOWN"?{error:jat}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?qat:kvr},failed:i.slice(0,_Ae),...i.length>_Ae?{failedNotShown:i.length-_Ae}:{},data:r}}async function SW(e,t,r=Dvr){let n;try{n=await e.post(CW,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=$at(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw ut(i);return wAe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof zp)throw ut(i);let o=i instanceof Error?i.message:String(i);return wAe(t,`No answer arrived from the apply (${o}).`)}return Bvr(t,n)}var Qat,sA,Pat,CW,_vr,Mat,Bat,dv,Oat,wvr,vvr,Svr,Dvr,wW,_Ae,fv,lon,uv,Fat,qat,kvr,Nvr,jat,vAe=J(()=>{"use strict";Ki();EW();lP();ot();fo();tr();CAe();Qat=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],sA=["TRANSACTIONS","LINE_ITEMS"],Pat={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},CW="/api/v1/ledger/find-fix/apply",_vr=CW.slice(0,CW.lastIndexOf("/")+1),Mat={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"}},Bat=["types","resourceIds","reference","valueDate","contactResourceId"],dv={TRANSACTIONS:{filter:Bat,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Bat,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Oat={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."},wvr=[[/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."]],vvr="Not described by this client version; read the records that carry it.";Svr="OUTCOME_UNKNOWN",Dvr=25e3,wW=3e5,_Ae=50,fv=12,lon=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${fv}}(?![A-Za-z0-9_-])`,"i"),uv=e=>e.resourceId?` (${e.resourceId})`:"",Fat={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${uv(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${uv(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${uv(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${uv(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${uv(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${uv(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."}};qat="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.",kvr="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.",Nvr="Nothing changed: every record in the preview failed.",jat="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function DW(e,t){return e.list("/api/v1/nano-classifiers",t)}async function QE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function RW(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function aO(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function cO(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function TW(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Ovr(e,t):{};let{data:n}=await QE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Hat(n)}async function Ovr(e,t){let{data:r}=await QE(e,t);return Hat(r)}function Hat(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function xW(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var Yat,SAe=J(()=>{"use strict";Yat=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function kW(e,t){return e.post("/api/v1/export-records",t,et)}async function NW(e,t){return e.post("/api/v1/export-records/preview",t,et)}async function BW(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var DAe=J(()=>{"use strict";tr()});function OW(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Vat(e,t,r,n=!1){if(!Array.isArray(e))throw new ue(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new ue(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new ue(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new ue(`${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 FW(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 LW(e,t,r){return OW(t,Jat),Zi(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Sc(ap,t)}/${encodeURIComponent(r)}/approve`,void 0,Oke)}async function QW(e,t,r){return OW(t,Jat),Vat(r,Fvr,"bulk approve",!0),r.forEach(n=>Zi(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Sc(ap,t)}/bulk-approve`,{resourceIds:r},Fke)}async function PW(e,t,r,n){OW(t,Gat),Zi(r,"resourceId","Pass the document resourceId."),Wat(n);let i=await e.post(`/api/v1/${Sc(PE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Pvr(i)}}}async function MW(e,t,r,n){return OW(t,Gat),Wat(n),Vat(r,Lvr,"bulk request changes"),r.forEach(i=>Zi(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(Qvr(t),{resourceIds:r,message:n})}function Qvr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Sc(zat,e)}/bulk-request-changes`}function Wat(e){if(!e||e.trim().length===0)throw new ue("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 Pvr(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 ap,zat,PE,Jat,Gat,Fvr,Lvr,RAe=J(()=>{"use strict";ot();tr();ap=["invoices","bills","customer-credit-notes","supplier-credit-notes"],zat=[...ap,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],PE=[...zat,"claims"],Jat=new Set(ap),Gat=new Set(PE);Fvr=100,Lvr=500});function Mvr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${Kat(t)}:${Kat(r)}:${n}`}function Kat(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function TAe(e){if(!Xat.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...Xat].join(", ")}`)}async function Zat(e,t,r){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function ect(e,t,r,n){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function tct(e,t,r,n,i){if(TAe(t),Zi(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new ue('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??Mvr(t,r,n)}})}async function rct(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var Xat,nct=J(()=>{"use strict";ot();Xat=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function Uvr({fromPeriod:e,toPeriod:t},r){for(let[n,i]of[["fromPeriod",e],["toPeriod",t]])if(i!==void 0){if(!Number.isInteger(i)||i<1)throw new ct(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new ct("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new ct(`${n} ${i} is past the last period (${r}). Send a period from 1 to ${r}.`)}if(e!==void 0&&t!==void 0&&e>t)throw new ct(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function UW(e,t,r){let n=e.length;if(Uvr(t,e[n-1]),n===0)return{start:0,end:0,window:{totalPeriods:0}};let i=t.fromPeriod===void 0?0:e.filter(u=>u<t.fromPeriod).length,o=t.toPeriod===void 0?n:e.filter(u=>u<=t.toPeriod).length,s=o===0&&t.toPeriod!==void 0,a=s?Math.min(t.toPeriod-(t.fromPeriod??1)+1,n,r):Math.min(o,i+r);if(a<=i)throw new ct(`No period falls in that range: the schedule runs from period ${e[0]} to ${e[n-1]}.`);let c={totalPeriods:n,fromPeriod:e[i],toPeriod:e[a-1]};if(i>0||a<n){let u=[`Showing periods ${e[i]} to ${e[a-1]} of ${n}.`];a<n&&u.push(`Periods ${e[a]} to ${e[n-1]} are not shown: call again with fromPeriod ${e[a]} to read the next range (at most ${r} periods come back per call).`),i>0&&u.push(`Periods ${e[0]} to ${e[i-1]} are not shown: call again with fromPeriod ${e[0]} to read them.`),c.note=u.join(" ")}return s&&(c.note=`Periods ${t.fromPeriod??1} to ${t.toPeriod} come before this schedule, which starts at period ${e[0]}. Showing the first periods instead. ${c.note??""}`.trim()),{start:i,end:a,window:c}}function pv(e,t={},r=lO){let n=e.data,i=ME(n.rows),{start:o,end:s,window:a}=UW(xAe(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function $W(e,t={},r=lO){let n=e.data,i=ME(n.rows),o=h=>h.rowType==="PERIOD",s=i.findIndex(o),a=i.map(o).lastIndexOf(!0),c=s===-1?[]:i.slice(s,a+1),{start:u,end:d,window:f}=UW(xAe(c),t,r);if(s===-1)return{...e,data:{...f,...n}};let p=[...u===0?i.slice(0,s):[],...c.slice(u,d),...d===c.length?i.slice(a+1):[]];return{...e,data:{...f,...n,rows:p}}}function ict(e,t,r,n,i){let o=e.data,s=ME(o[t]),a=s.reduce((h,m)=>h+ME(m[r]).length,0),{start:c,end:u,window:d}=UW(Array.from({length:a},(h,m)=>m+1),n,i);if(a===0)return{...e,data:{...d,...o}};let f=0,p=[];for(let h of s){let m=ME(h[r]),A=m.slice(Math.max(c-f,0),Math.max(u-f,0));A.length>0&&p.push({...h,[r]:A}),f+=m.length}return{...e,data:{...d,...o,[t]:p}}}function gd(e,t={},r=lO){let n=e.data,i=ME(n.periods),{start:o,end:s,window:a}=UW(xAe(i,"period"),t,r);if(i.length===0)return{...e,data:{...a,...n}};let c=i[o].startDate,u=i[s-1].endDate,d=f=>typeof f.toDate!="string"||typeof f.fromDate!="string"||typeof c!="string"||typeof u!="string"||f.toDate>=c&&f.fromDate<=u;return typeof a.note=="string"&&(a.note+=" The timeline lists only the segments that touch these periods."),{...e,data:{...a,...n,periods:i.slice(o,s),timeline:ME(n.timeline).filter(d)}}}var lO,ME,xAe,qW,jW,hv=J(()=>{"use strict";fo();lO=60;ME=e=>Array.isArray(e)?e:[],xAe=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);qW=(e,t={},r=lO)=>ict(e,"depreciationScheduled","depreciation",t,r),jW=(e,t={},r=lO)=>ict(e,"amortizationScheduled","amortization",t,r)});async function UE(e,t){return e.get(`/api/v1/loans/${t}`)}async function YW(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function HW(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function zW(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},$ke)}async function JW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names loan ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await UE(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function GW(e,t){await e.delete(`/api/v1/loans/${t}`)}async function VW(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},sZ)}async function WW(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},sZ)}async function KW(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function XW(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function ZW(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function e4(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function t4(e,t){return e.post("/api/v1/loans/preview-schedule",t,et)}async function r4(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,et)}async function n4(e,t){return mt(t,"loans",500,"loans"),jo(t,oct),En(e,"/api/v1/loans/bulk-upsert","loans",t)}async function i4(e,t){return mt(t,"loans",500,"loans"),jo(t,$vr),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`loans[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that loan. Bulk update does not take tags: change them with update_loan (clio loans update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/loans/bulk-update","loans",t)}async function o4(e,t,r,n,i){let o=uO[t];if(i){if(!o.calculate)throw new Error(`Loan event ${t} has no preview.`);let s=Object.fromEntries(Object.entries(n).filter(([a])=>!o.recordOnly?.includes(a)));return e.post(o.calculate,{...s,resourceId:r},et)}return e.post(o.record(r),{...n,resourceId:r},qke)}var oct,$vr,uO,kAe=J(()=>{"use strict";an();ot();tr();oct=["drawdownDate","trackingStartDate","firstRepaymentDate"],$vr=[...oct,"capitalizationStartDate","capitalizationEndDate"];uO={drawdown:{calculate:"/api/v1/loans/calculate-drawdown",record:e=>`/api/v1/record-drawdown/loans/${e}`},prepayment:{calculate:"/api/v1/loans/calculate-prepayment",record:e=>`/api/v1/prepay/loans/${e}`},rateChange:{calculate:"/api/v1/loans/calculate-rate-change",record:e=>`/api/v1/change-rate/loans/${e}`},capitalization:{calculate:"/api/v1/loans/calculate-capitalization",record:e=>`/api/v1/capitalize-interest/loans/${e}`},paymentHoliday:{calculate:"/api/v1/loans/calculate-payment-holiday",record:e=>`/api/v1/payment-holiday/loans/${e}`},restructure:{calculate:"/api/v1/loans/calculate-restructure",record:e=>`/api/v1/restructure/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},settlement:{calculate:"/api/v1/loans/calculate-settlement",record:e=>`/api/v1/settle/loans/${e}`},forgiveness:{calculate:"/api/v1/loans/calculate-forgiveness",record:e=>`/api/v1/forgive/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},conversion:{calculate:"/api/v1/loans/calculate-conversion",record:e=>`/api/v1/convert-to-shares/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},refinance:{record:e=>`/api/v1/refinance/loans/${e}`},reclassifyAsCurrent:{record:e=>`/api/v1/reclassify-as-current/loans/${e}`},undo:{record:e=>`/api/v1/undo-event/loans/${e}`}}});function mv(e){mt(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new ue(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!BFe(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!qvr.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 ue(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function s4(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},et);return{data:Yvr(r.data)}}function jvr(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 Yvr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(jvr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function a4(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function c4(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var qvr,NAe=J(()=>{"use strict";ot();iee();an();tr();qvr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function lct(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new ue("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function BAe(e,t){if(!e||typeof e!="object")throw new ue(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new ue(`${t}.lineItems array is empty.`);if(n.length>500)throw new ue(`max 500 ${t}.lineItems per call.`);jo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&jo([i],["valueDate"])}async function u4(e,t,r=OAe){return e.post("/api/v1/search-magic-reconciliation",t,{...et,timeoutMs:r})}function l4(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Gvr(e){let t=l4(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=l4(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function Vvr(e){return e?e.value>=(e.from==="confidenceScore"?Hvr:zvr)?"high":e.value>=Jvr?"medium":"low":"low"}function Kvr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(sct,t))return;let r=sct[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function aA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function act(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function Xvr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>act({account:aA(n?.account),taxProfile:aA(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(!(!aA(e.contact)&&!aA(e.account)&&!aA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return act({contact:aA(e.contact),account:aA(e.account),taxProfile:aA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function uct(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=>n0r(c,h??{},u.length-1,t)).sort(Zvr),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 Zvr(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 e0r(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return vc.test(t)?t:void 0}function t0r(e){let{recommendationId:t,...r}=e;return r}function r0r(e,t,r){return!t||!r?t:e===$E.learnedPrediction?{...t,recommendationId:r}:e===$E.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function n0r(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=l4(t.matchScore),s=l4(t.confidenceScore),a=Gvr(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=$E.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=$E.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let F=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,G=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,j=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;F&&G&&j&&(m=$E.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:F,predictedPayload:G,predictedPayloadSchemaVersion:j});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let F=t.actionShortcut??{},G=typeof F.resourceId=="string"?F.resourceId:void 0;G&&(m=$E.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=r0r(m,A,e0r(t)),y=m?Vvr(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==$E.withPayments||b,T=Kvr(t),D=!m||!g?"NO_PLAN":T?Wvr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",k=Xvr(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:D===void 0,...D?{checkpointReason:D}:{},...k?{proposedPosting:k}:{},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(t0r(t))}`}}function i0r(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 o0r(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 ho(e,i):await Eo(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}): ${RE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function dct(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,cct);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 nC(e,t,{filter:{resourceId:{in:u}},limit:cct}),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: ${RE(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 i0r(u,f,await o0r(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function d4(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,ya)}async function f4(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,ya)}async function p4(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,ya)}async function h4(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,ya)}async function m4(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,ya)}async function A4(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,ya)}async function g4(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,ya)}async function y4(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,ya)}async function E4(e,t){return e.post("/api/v1/reconciliations/with-payments",t,ya)}async function b4(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,ya)}async function I4(e,t){return e.post("/api/v1/reconciliations/magic-match",t,ya)}async function C4(e,t){return e.post("/api/v1/reconciliations/reset",t)}var $E,OAe,Hvr,zvr,Jvr,Wvr,sct,cct,_4=J(()=>{"use strict";Rg();TE();ot();af();an();zg();tr();$E={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},OAe=6e4;Hvr=.9,zvr=.95,Jvr=.7;Wvr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},sct={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};cct=25});function ia(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 Po(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:FAe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=FAe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=FAe(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 FAe(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 ts(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=ia(e,t,n),a=Po(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 xa,tl,vo,nu,fct=J(()=>{"use strict";xa=[{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}],tl=[...xa],vo=xa.filter(e=>e.field!=="dueDate"),nu=[{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 yd(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=_c(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function w4(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=BI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var pct=J(()=>{"use strict";Vp()});var LAe=J(()=>{"use strict";fct();Vp();pct()});var dO,v4,rs,oo,QAe=J(()=>{"use strict";dO="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",v4=["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"],rs="If the result says it runs in the background, do not poll: its result arrives by itself.",oo=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${rs} PARTIAL_SUCCESS: errorDetails.`});function hct(e){return s0r.get(e)}function mct(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&&!S4.has(o));return n.length===0?[]:Mi.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 Mi,S4,s0r,Ed=J(()=>{"use strict";QAe();IAe();Mi=[{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. 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. Fixed asset register reports are in register_reports.",groups:["operational_reports","exports"]},{name:"register_reports",title:"Register Reports",description:"Register reports: fixed asset register summary by account, type, category or active/closed-out/disposed state (asset register roll-forward over a period), fixed asset register vs general ledger reconciliation (does the register agree with the GL), deferrals summary (prepaid and deferred revenue roll-forward) and deferrals reconciliation (does the prepaid register agree with the GL), lease register summary (IFRS 16 lease note, lease liability roll-forward) and lease register vs general ledger reconciliation (rent coded to the lease liability account). Loan reports: borrowings note summary, loan roll-forward, related-party (director, shareholder) loan balances, loan interest cost, maturity analysis (liquidity note), loan register vs ledger reconciliation.",groups:["register_reports"]},{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. For what-if questions and topics with no register; to keep a lease, loan, prepaid or deferred revenue use its register. Keywords: calculate, what-if, monthly payment, 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, set up to repeat every month.",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 (one or bulk), discard, sell, transfer, undo disposal, close out (stop depreciating, keep the asset) and reopen. Also: depreciation, asset register. Depreciation schedules, totals, eligible bill lines and asset types are in fixed_asset_schedules.",groups:["fixed_assets"]},{name:"fixed_asset_schedules",title:"Fixed Asset Schedules & Totals",description:"Read-only fixed asset views. Show one asset's depreciation by month and year, net book value, asset register totals as at a date, disposal totals (gain/loss), eligible bill lines to register as assets, asset types. Check custom depreciation ranges; calculate disposal (accumulated depreciation, net book value) before selling or discarding.",groups:["fixed_asset_schedules"]},{name:"deferrals",title:"Deferrals (Prepaid & Deferred Revenue)",description:"Deferrals register: prepaid expense, prepayment, deferred revenue, unearned revenue. Spread a bill over months, recognise an invoice over months (amortization, release schedule). Search, create, update, delete, stop amortising early (close out) and undo it, totals as at a date, schedule, eligible bill or invoice lines, deferral types and deferral accounts (mark the accounts first), bulk create and update.",groups:["deferrals"]},{name:"leases",title:"Leases (IFRS 16)",description:"Leases under IFRS 16: put an office rent lease on the books (right-of-use asset, ROU, and lease liability, current and non-current), hire purchase (flat rate to monthly discount rate), short-term or low-value exemption. Search, create, update, delete, close out, terminate lease (preview the gain or loss first) and undo either; lease schedule, liability totals as at a date, rent schedule preview, lease types.",groups:["leases"]},{name:"loans",title:"Loans (Borrowings)",description:"Loans and borrowings register: record a new bank loan, loan, borrowing, bank loan, term loan, director's loan (revolving credit and loans given are not in the register), instalment / installment loan. Search, create, update (one or bulk), delete, close out. What do we owe a lender or the bank: outstanding principal, current and non-current at a date, the repayment schedule, an on-demand loan ledger (an on-demand loan has no schedule, is all current and posts no interest), loan types, preview the monthly payment. Loan changes (drawdown, prepay, rate change, settle) are in loan_events; loan reports are in register_reports.",groups:["loans"]},{name:"loan_events",title:"Loan Events",description:"Events on an existing loan: drawdown, prepay or extra repayment, rate change, payment holiday, capitalize interest, restructure, refinance, settle / payoff, forgive / write off a loan, convert loan to shares, covenant breach (reclassify as current), undo loan event, balance after a missed payment. preview: true calculates the figures and saves nothing.",groups:["loan_events"]},{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 ${xat}. On a record: ${kat}. On lines: ${Nat}. 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, ${v4.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"]}],S4=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"]),s0r=new Map(Mi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function bd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function a0r(e){let t=Act.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(bd(r),n);for(let r of e.enum??[])t.set(bd(r),r);Act.set(e,t)}return t}function gct(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=bd(e);if(!r)return null;let n=a0r(t).get(r);return n!==void 0&&n!==e?n:null}function c0r(e){let t=yct.get(e);return t||(t=new Map(Object.keys(e).map(r=>[bd(r),r])),yct.set(e,t)),t}function l0r(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 u0r(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 PAe(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=c0r(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=bd(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"?l0r(d):u0r(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=gct(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=gct(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=fee(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=PAe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=PAe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Ect(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:PAe(t,e.params,"",r),coercions:r}}function bct(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 Act,yct,MAe=J(()=>{"use strict";NU();Act=new WeakMap;yct=new WeakMap});function Av(e){let t=new Set,r=[];for(let n of e)for(let i of iu(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function fO(){return Mi.map(e=>{let t=Av(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 d0r(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 f0r(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 cA(e,t=!1){let r=lA(void 0).length,n=Mi.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:f0r(r)}:e&&i!==void 0?{packaging:d0r(e,i,r)}:{},map:fO(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var D4=J(()=>{"use strict";Ed();ou()});function R4(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=R4(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=R4(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function su(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=R4(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function pO(e){return{name:e.name,description:e.description,input_schema:su(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var gv=J(()=>{"use strict"});function hO(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 UAe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function T4(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&hO(e),idempotentHint:e.readOnly,openWorldHint:UAe(e)}}function h0r(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function m0r(e){let t=h0r(e);return!t||p0r.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!S4.has(n)).length===0}function $Ae(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 qAe(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?qAe(o,`${i}.`):[]]})}function g0r(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??z_r,c=n.minBm25??J_r;if(i==="bm25"||!t)return _E(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Nme(r);return m?Est(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):_E(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Nme(r),Promise.resolve(_E(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Est(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Cst(p,h,o)}function Est(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=bst(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 Cst(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Ast+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/(Ast+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 Bme(e){return e!==null&&!!Ist()}var Y_r,H_r,Ast,z_r,J_r,pV,gst,hV,yst,mV=J(()=>{"use strict";YB();Y_r="text-embedding-3-small",H_r=2e3,Ast=60,z_r=.3,J_r=1.5,pV=null,gst=null,hV=null,yst=!1});async function _st(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=qB();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:HB(),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=(xme(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 wst(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:V_r}async function AV(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(wst())}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(W_r),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return K_r(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 K_r(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Ome(e,t={}){return process.env.CLIO_DAEMON==="1"||jB()?_st(e,t):AV(e,t)}var V_r,W_r,vst=J(()=>{"use strict";YB();mV();V_r="https://mcp.jaz.ai/help-center/search",W_r=4e3});var Fme=J(()=>{"use strict";YB();mV();vst();YB()});async function eA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function tA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var JB=J(()=>{"use strict";an()});async function gV(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency)},zke)}var Lme=J(()=>{"use strict";ot();tr()});async function yV(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function EV(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function GB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function bV(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Qme=J(()=>{"use strict"});function X_r(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Xw(e,t){return e.post("/api/v1/jots",{entries:t.map(X_r)})}async function IV(e,t){return e.post("/api/v1/jots/search",t,et)}async function Sst(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var CV=J(()=>{"use strict";tr()});async function Dst(e,t){return e.post("/api/v1/agents/memories",t)}async function Pme(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Rst=J(()=>{"use strict";tr()});function _V(){return process.env.ENABLE_MEMORY==="true"}function Mme(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Tst(e){return!_V()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Ume=J(()=>{"use strict"});import{createHash as Z_r}from"node:crypto";function uwr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:Nst.some(r=>t.includes(r))?[null,"directive_invalid"]:kst.test(t)?[null,"directive_invalid"]:owr.test(t)?[null,"directive_contains_url"]:swr.test(t)?[null,"directive_contains_email"]:[t,null]}function dwr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>awr?[null,"match_condition_too_long"]:Nst.some(r=>t.includes(r))?[null,"match_condition_invalid"]:kst.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function fwr(e){return e==null?[null,null]:Number.isInteger(e)?e<cwr||e>lwr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function pwr(e,t,r,n,i,o,s,a){if(e)return Z_r("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function hwr(e){Promise.resolve().then(()=>(mD(),hD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Lst(e,t,r){let n=t.action,i=t.category,o=nwr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(hwr({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=Tst(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>ewr||!iwr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=uwr(t.directive);if(E)return u(E);p=b;let[C,w]=fwr(t.importance);if(w)return u(w);h=C}let[m,A]=dwr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=twr)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,rwr));let E=pwr(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 $me(()=>Dst(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await $me(()=>Pme(e.client,b))}else{let b={forgetAll:!0};y=await $me(()=>Pme(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function $me(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 kst,Nst,ewr,twr,rwr,Bst,Ost,Fst,nwr,iwr,owr,swr,awr,cwr,lwr,Qst=J(()=>{"use strict";Rst();Ki();Ume();Ume();kst=/[\x00-\x1f\x7f]/,Nst=["{{","}}","```","<",">"],ewr=120,twr=3,rwr=140,Bst=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Ost=["set","forget","forget_all"],Fst=["this_org","all_orgs"],nwr={this_org:"ORG_USER",all_orgs:"USER"},iwr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,owr=/https?:\/\//i,swr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,awr=255,cwr=0,lwr=100});async function wV(e,t){return e.list("/api/v1/organization-users",t)}async function vV(e,t){return e.search("/api/v1/organization-users/search",t)}async function Zw(e,t){return e.post("/api/v1/organization-users/invite",t)}async function SV(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function DV(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var qme=J(()=>{"use strict"});async function RV(e,t){return e.get(`/api/v1/payments/${t}`)}async function TV(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Wt(r.currency)})}async function xV(e,t){await e.delete(`/api/v1/payments/${t}`)}function kV(e){return(t,r)=>t.post(`/api/v1/${mwr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Wt(n.currency)}))},Lke)}var mwr,Cnn,Pst,_nn,wnn,jme=J(()=>{"use strict";ot();tr();mwr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};Cnn=kV("saleBulk"),Pst=kV("saleBatch"),_nn=kV("purchaseBulk"),wnn=kV("purchaseBatch")});async function ip(e,t,r,n,i,o=Hke){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?ut(c):new rf(`${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 zp?ut(c):c}let a=s?.data;if(!i(a))throw new rf(`${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 BV(e,t,r){try{Zi(e,t,r)}catch(n){throw ut(n)}}function wE(e){return BV(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function OV(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function FV(e,t){return ip(e,"POST",Awr,t,rA)}async function LV(e,t,r){return ip(e,"PUT",`/api/v1/unapplied-payments/${wE(t)}`,r,rA)}async function QV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/activate`,{hash:r},rA)}async function PV(e,t,r,n){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/attributions`,{hash:r,attributions:n},rA)}async function MV(e,t,r,n){return BV(n,"paymentResourceId","Pass the payment record resourceId."),ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/payments`,{hash:r,paymentResourceId:n},rA)}async function UV(e,t,r,n){return BV(r,"childResourceId","Pass the payment record resourceId from the children list."),ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}/children/${encodeURIComponent(r)}`,{hash:n},rA)}async function $V(e,t,r){return ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}`,{hash:r},rA)}async function qV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/unbatch`,{hash:r},rA)}async function jV(e,t){return BV(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),ip(e,"POST",gwr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,ya)}var Awr,gwr,NV,Mst,Ust,rA,Yme=J(()=>{"use strict";Ki();tr();lP();ot();Awr="/api/v1/unapplied-payments",gwr="/api/v1/reconciliations/unapplied-payment",NV=["SALE","PURCHASE"],Mst=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ust=["AMOUNT","PERCENTAGE"];rA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function YV(e,t,r={},n=Hme){let i=ywr.has(t)?`/api/v1/${Sc($st,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=Hg.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...Hg.keys()].join(", ")}.`);let A=await Df(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...et,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new ue(`${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: ${[...VB].join(", ")}.`}:d}var $st,ywr,Hme,VB,qst,zme=J(()=>{"use strict";tr();ot();Mx();Yu();$st=["statement-of-account-export"],ywr=new Set($st),Hme=9e4,VB=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"]),qst={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as Ewr}from"node:crypto";import{writeFile as bwr,mkdir as Iwr}from"node:fs/promises";import{dirname as Cwr,isAbsolute as _wr,join as wwr}from"node:path";async function HV(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},et)}async function WB(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 ev(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function jst(e){return`query-export-${e.slice(0,8)}.csv`}function Jme(e){return Ewr("sha256").update(e).digest("hex").slice(0,16)}async function zV(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Jme(t),o=await WB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await ev(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await ev(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&&!_wr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??wwr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Iwr(Cwr(p),{recursive:!0}),await bwr(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 JV(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 ue(`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 tv(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 Gme=J(()=>{"use strict";ot();tr()});async function Ei(e,t,r){let n=await e.get(`/api/v1/${Vme[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function GV(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/${Vme[r]}/${n}/attachments`,o)}async function VV(e,t,r,n){return e.delete(`/api/v1/${Vme[t]}/${r}/attachments/${n}`)}var Vme,KB,nA=J(()=>{"use strict";Vme={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"},KB=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function kwr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&xwr.some(n=>r.startsWith(n)))}async function op(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&kwr(t)&&(t.refusal=Twr),t}}function Yst(e,t,r){return Zi(e,t,r),e.toLowerCase()}function rv(e,t){return{type:Sc(Wme,e,"entityType"),record:Yst(t,"entityId",vwr)}}function XB(e){DZ(e,"threadId",Dwr)}function Hst(e){DZ(e,"commentId",Rwr)}function nv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Yst(e.bankAccountResourceId,"bankAccountResourceId",Swr)}}async function zst(e,t,r,n={}){let{type:i,record:o}=rv(t,r),s={...nv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return op(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Jst(e,t,r,n,i={}){let{type:o,record:s}=rv(t,r),a={...nv(i),limit:i.limit,offset:i.offset};return XB(n),op(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Gst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return n.threadId!==void 0&&XB(n.threadId),(await op(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...Yke,query:a}))).data}async function Vst(e,t,r,n,i,o,s){let{type:a,record:c}=rv(t,r),u=nv(s);return XB(n),Hst(i),(await op(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function Wst(e,t,r,n,i,o){let{type:s,record:a}=rv(t,r),c=nv(o);return XB(n),Hst(i),(await op(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function Kst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return XB(n),(await op(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function Xst(e,t={}){return op(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function Zst(e,t,r){return HNe(t,"Get it from list_notifications."),(await op(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function eat(e){return(await op(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Wme,vwr,Swr,Dwr,Rwr,Twr,xwr,tat=J(()=>{"use strict";Ki();ot();tr();Wme=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],vwr="Pass the resourceId of the bill, invoice, credit note or bank record.",Swr="Pass the resourceId of the bank account that holds the bank record.",Dwr="Get it from list_comment_threads.",Rwr="Get it from list_comments or list_comment_threads.",Twr={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."},xwr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Qo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var iv=J(()=>{"use strict"});async function WV(e,t){return e.post("/api/v1/claims/conversion/preview",t,et)}async function KV(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new ue('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:AP)}var ZB,Kme=J(()=>{"use strict";ot();tr();ZB=["POST","POST_AND_RECORD"]});async function XV(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,Qke)}async function ZV(e,t){return e.search("/api/v1/employees/payouts/search",t)}var rat,Xme=J(()=>{"use strict";ot();tr();rat=["REIMBURSEMENT","ADVANCE"]});async function e8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Zme=J(()=>{"use strict"});function eAe(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 tAe(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: ${nat(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=>Pu.has(u)),s=i.filter(u=>!Pu.has(u)&&Rc.has(u)),a=[`Nothing here can be extracted: found ${nat(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=KBe[u];d&&a.push(d)}return o.length>0&&a.push(`${eU(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(`${eU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Pu.has(u)&&!Rc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${eU([...Pu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function nat(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 iat=J(()=>{"use strict";Mu()});function t8(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function eO(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&&t8()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function vE(e,t){return{error:e,hint:t,...rAe}}function oat(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: ${eO(e)}.`,...rAe}}function SE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function iA(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: ${eO({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.",...rAe,...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 rAe,sat=J(()=>{"use strict";rAe={kind:"validation",retriable:!1}});import{randomUUID as Nwr}from"node:crypto";import{rmSync as Bwr}from"node:fs";function iAe(e){for(let t of e.tempDirs??[])try{Bwr(t,{recursive:!0,force:!0})}catch{}}function cat(e){for(let[t,r]of DE)e-r.createdAt>aat&&(iAe(r.plan),DE.delete(t))}function Fwr(){nAe||(nAe=setInterval(()=>cat(Date.now()),Owr),nAe.unref?.())}function oAe(e,t){let r=Date.now();cat(r),Fwr();let n=`dc_${Nwr()}`;return DE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function sAe(e,t){let r=DE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>aat?(iAe(r.plan),DE.delete(e),null):r.plan}function lat(e,t){let r=DE.get(e);!r||r.ownerKey!==t||(iAe(r.plan),DE.delete(e))}var aat,Owr,DE,nAe,uat=J(()=>{"use strict";aat=1800*1e3,Owr=300*1e3,DE=new Map});function Lwr(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 dat(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>_g(i.documentType)&&r.has(i.documentType))}))}}async function fat(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?dat(t,i):t;if(!n&&Qwr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");vD(o);let a=await mU({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"?Lwr(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 pat(e,t){return(t&&t.length>0?dat(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>_g(o.documentType)).length,0)}function Qwr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var hat=J(()=>{"use strict";nee();Mu();Af()});function Pwr(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 Uwr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function $wr(e,t){if(e!==Mwr)return;let r=Uwr(t);if(r)return mat.get(r)??mat.get(r.replace(/_ERROR$/,""))}function r8(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 qwr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=r8(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 aAe(e){return $wr(e.status,e.body)??e.refusal?.hint??qwr(e)}function RE(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 n8(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function tO(e,t={}){let r=t.readOnly===!1&&PD()?PFe:"";if(e instanceof gr){let o=[aAe(e)??Pwr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...r8(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=i8(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 ct;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var Mwr,mat,TE=J(()=>{"use strict";Ki();fo();o8();bU();Mwr=422,mat=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 md(e,t,r){if(!t)return e;let n=jwr(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 Ad(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${RE(i)}`],...n}}}function jwr(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 sp(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var Aat=J(()=>{"use strict";TE()});async function s8(e,t){return e.list("/api/v1/bank-rules",t)}async function rO(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 a8(e,t){return e.search("/api/v1/bank-rules/search",t)}async function c8(e,t){return e.post("/api/v1/bank-rules",t)}async function l8(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function u8(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var cAe=J(()=>{"use strict"});async function d8(e,t){return e.list("/api/v1/fixed-assets",t)}async function xE(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function nO(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function f8(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},iZ)}function yat(e,t){let r={};for(let n of Ywr){let i=e[n];if(i==null)continue;let o=Hwr.has(n)?cf(i):i;o!==void 0&&(r[n]=o)}for(let[n,i]of Object.entries(t))i!==void 0&&n!=="resourceId"&&(r[n]=i);return r}async function p8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ut(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await xE(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,yat(i,r))}async function h8(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function m8(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},hP)}async function iO(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,hP)}async function A8(e,t){return e.post("/api/v1/transfer-fixed-assets",t,iZ)}async function g8(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},hP)}async function y8(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},oZ)}async function E8(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},oZ)}async function zwr(e,t){let r=new Map;for(let i=0;i<t.length;i+=gat){let o=t.slice(i,i+gat),s=await nO(e,{filter:{resourceId:{in:o}},limit:o.length});for(let a of s.data)r.set(a.resourceId,a)}let n=t.filter(i=>!r.has(i));if(n.length>0)throw ut(new ue(`No fixed asset found for ${n.length} resourceId${n.length===1?"":"s"}: ${n.join(", ")}. Nothing was submitted; fix or remove those rows and retry.`));return r}async function b8(e,t){mt(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=HS(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw ut(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw ut(new ue(`resourceId ${u} appears more than once in fixedAssets; put all of an asset's changes in one row. Nothing was submitted.`));return r.add(u),u}),i=t.map((a,c)=>Xn(a.tags,`fixedAssets[${c}].tags`)),o=await zwr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...yat(u,{...a,tags:d&&ui(u.tags,d)})}});return En(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function I8(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function C8(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function _8(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,et)}async function w8(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},et)}async function v8(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function S8(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function D8(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function Gwr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function Vwr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=Gwr(i);if(o.length===0)return;let s=typeof i.reference=="string"&&i.reference?` (${i.reference})`:"";t.push(`row ${n}${s}: ${o.map(a=>`${a} (${Jwr[a]})`).join(", ")}`)}),t.length>0)throw ut(new ue(`Every fixed asset row needs its reference, registrationType and depreciationStartDate; the import job rejects a row without them. Missing: ${t.join("; ")}. Nothing was sent.`))}async function R8(e,t){return mt(t,"fixedAssets",500,"fixed assets"),SNe(t,["purchaseDate","depreciationStartDate"]),Vwr(t),En(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var oA,Ywr,Hwr,gat,Jwr,T8=J(()=>{"use strict";an();KS();tr();ot();xl();oA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];Ywr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],Hwr=new Set(["purchaseDate","depreciationStartDate"]);gat=100;Jwr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function x8(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function kE(e,t){return e.get(`/api/v1/leases/${t}`)}async function k8(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},Uke)}async function N8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names lease ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await kE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function B8(e,t){await e.delete(`/api/v1/leases/${t}`)}async function O8(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},qS)}async function F8(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},qS)}async function L8(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},qS)}async function Q8(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},et)}async function P8(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},qS)}async function M8(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function U8(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function $8(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function q8(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,et)}async function j8(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,et)}async function Y8(e,t){return mt(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`leases[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that lease. Bulk update does not take tags: change them with update_lease (clio leases update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/leases/bulk-update","leases",t)}var lAe=J(()=>{"use strict";an();ot();tr()});async function H8(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function NE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function z8(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Jp)}async function J8(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 NE(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 Wwr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function Wwr(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 G8(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function V8(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 W8(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var K8=J(()=>{"use strict";tr()});async function X8(e,t){return e.list("/api/v1/contact-groups",t)}async function Z8(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function eW(e,t){return e.search("/api/v1/contact-groups/search",t)}async function tW(e,t){return e.post("/api/v1/contact-groups",t)}async function rW(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,TI(r,hZ))}async function nW(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var uAe=J(()=>{"use strict";an()});async function iW(e,t){return e.list("/api/v1/inventory-items",t)}async function oW(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function sW(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function cW(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&Kwr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var aW,Kwr,dAe=J(()=>{"use strict";Ki();aW=["ALL","AVAILABLE","FULLY_DRAWN"],Kwr=/Inventory balance Not Found/i});async function lW(e,t){return e.list("/api/v1/custom-fields",t)}async function oO(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function uW(e,t){return e.search("/api/v1/custom-fields/search",t)}async function dW(e,t){return e.post("/api/v1/custom-fields",t)}function Zwr(e){return e!==void 0&&Xwr.every(t=>e[t]!==void 0)}function evr(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 tvr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function fW(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!Zwr(n.appliesTo)){let i=await oO(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??tvr(i.data),n.appliesTo={...evr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function pW(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var Xwr,fAe=J(()=>{"use strict";Xwr=["invoices","bills","customerCredits","supplierCredits","payments"]});var el,BE,rvr,nvr,pAe,hW,mW,ivr,Ta,ru,OE,ov,FE,hAe=J(()=>{"use strict";el={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"]},BE={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."}}},rvr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},nvr={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"]},pAe={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"]},hW={type:"object",properties:{billingAddress:{...pAe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},mW={type:"object",properties:{billingAddress:{...pAe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...pAe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},ivr={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"]},Ta={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:ivr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},ru={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)."}}},OE={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"]},ov={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...el,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:BE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,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:"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:{...rvr,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:{...nvr,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:{...hW,description:"Issuer identity and billing address (credit from)."},creditTo:{...mW,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...el,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:BE},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},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:{...el,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:{...hW,description:"Seller identity and billing address."},billTo:{...mW,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:{...el,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:BE},deliverySlipTemplateResourceId:{type:"string",description:"UUID of the delivery slip PDF template."},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},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:{...el,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:{...el,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:BE},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:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,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:{...el,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:BE},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:{...el,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:{...hW,description:"Seller identity and billing address."},billTo:{...mW,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:BE},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:{...el,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:BE},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,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)."}}},FE={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:Ta},discount:{...ru,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:{...OE,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:Ta},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:Ta},discount:{...ru,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:Ta},discount:{...ru,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:Ta},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:Ta},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:Ta},discount:{...ru,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:{...OE,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:Ta},discount:{...ru,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:{...OE,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:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,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:{...OE,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:Ta},discount:{...ru,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:Ta},discount:{...ru,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:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,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:{...OE,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:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,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:{...OE,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:Ta},discount:{...ru,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:{...OE,description:"Withholding tax details for this line item."}}}}});function AAe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function gAe(e){let t=e.updated??[],r=AAe(e.failed);return{...t.length===0&&r.length>0?{error:avr}:{},updated:t,failed:r}}function bat(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function AW(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Iat(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=bat(s);if(a)for(let c of Array.isArray(o)?o:[o])AW(c)&&n.push(...Iat(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function cvr(e){return Object.entries(e).map(([t,r])=>{let n=bat(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function yAe(e,t,r){if(!AW(t))return;let n=Iat(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw ut(new ct(`${e} has no field ${i.join("; ")}. Fields: ${cvr(r)}. Nothing was changed.`))}function lvr(e){let t=ov[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 uvr(e){let t=FE[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 dvr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!AW(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw ut(new ct(`${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(!AW(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw ut(new ct(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));yAe(`${e} line items`,a.attributes,t.fields)}}}function Cat(e){if(sv.includes(e))return;let t=yW.includes(e);throw ut(new ct(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: ${sv.join(", ")}.`))}async function cv(e,t,r){Cat(t),yAe(`${t} quick fix`,r.attributes,lvr(t));let n=await e.post(`/api/v1/quick-fix/${Sc(sv,t)}`,r);return gAe(n)}async function fvr(e,t){try{return await IE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return CE(e,t);throw r}}async function _at(e,t,r,n){Cat(t);let i=EAe[t],o=async d=>i.tags(await Xi(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Eat)s.push(...await Promise.all(r.resourceIds.slice(d,d+Eat).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=ui(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 cv(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 gAe({updated:c,failed:u})}async function sO(e,t,r){let n=Sc(av,t),i=uvr(t);i.entryKeys?dvr(t,i,r.schedulerUpdates):yAe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return gAe(o)}var ovr,svr,gW,yW,sv,av,avr,LE,mAe,EAe,Eat,EW=J(()=>{"use strict";Ki();ot();fo();hAe();xl();zg();af();Hx();Kx();Jg();ZG();dV();K8();ovr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],svr=["journals","cash-entries"],gW=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],yW=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],sv=[...ovr,...svr,...gW],av=[...sv,...yW],avr="Nothing changed: every record failed. See failed for each reason.";LE=e=>e?.tags,mAe=e=>e?.data?.tags,EAe={invoices:{noun:"invoice",get:(e,t)=>Eo(e,t),tags:LE},bills:{noun:"bill",get:(e,t)=>ho(e,t),tags:LE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>Vs(e,t),tags:LE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>Ws(e,t),tags:LE},journals:{noun:"journal",get:(e,t)=>vs(e,t),tags:LE},"cash-entries":{noun:"cash entry",get:(e,t)=>fvr(e,t),tags:LE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Vw(e,t),tags:mAe},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Ww(e,t),tags:mAe},"subscription-schedules":{noun:"subscription",get:(e,t)=>NE(e,t),tags:mAe},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Kw(e,t),tags:LE}},Eat=10});function bW(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=bW(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<hvr&&i.length<=mvr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,bW(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function vat(e,t,r){let n=Avr(t);if(!n)return[];let i=gvr(r);if(!i){if(wat[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]?vat(o,s,i[o]):[])}function yvr(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 bAe(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=Evr(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]??bW(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=>bW(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[wat[c],yvr(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 vat(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 Tat(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>pvr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var pvr,wat,hvr,mvr,Avr,gvr,Evr,bvr,Ivr,lv,Sat,Dat,Rat,xat,kat,Nat,IAe=J(()=>{"use strict";hAe();xl();pvr={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",deliverySlipTemplateResourceId:"delivery slip 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"},wat={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:`${Yo.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}."},hvr=2,mvr=8;Avr=e=>e.properties??e.items?.properties,gvr=e=>e.properties??e.items?.properties;Evr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),bvr={tags:Yo};Ivr=Object.entries(FE).filter(([,e])=>!e.entryKeys),lv=Object.entries(FE).filter(([,e])=>e.entryKeys),Sat=bAe({...ov},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",bvr),Dat=bAe(Object.fromEntries(Ivr.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."),Rat=(()=>{let e=n=>lv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=lv[0],r=[...new Set(lv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>lv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${lv.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:bAe(Object.fromEntries(lv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();xat=[...new Set([...Object.keys(ov),...Object.keys(FE)])].map(e=>e.replace(/-/g," ")).join(", "),kat=Tat(Object.values(ov)),Nat=Tat(Object.values(FE).map(e=>e.fields))});function IW(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var CAe=J(()=>{"use strict"});function _W(){return sA.map(e=>`${e} sets ${dv[e].change.join(", ")}`).join("; ")}function Uat(e){let t={};for(let r of e)t[r]=Object.hasOwn(Oat,r)?Oat[r]:wvr.find(([n])=>n.test(r))?.[1]??vvr;return Object.keys(t).length>0?t:void 0}function $at(e){if(!(e instanceof gr)||!e.endpoint.startsWith(_vr))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(Fat,n))return;let{hint:i,repairTool:o,command:s}=Fat[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===Pat.LINE_ITEMS?"line items":"records",...e.endpoint===CW?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function Rvr(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 Tvr(e){return typeof e=="string"&&sA.includes(e)}function xvr(e,t){if(!Tvr(e))throw new ct(`level must be one of ${sA.join(", ")}.`);let r=sA.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))dv[e][i].includes(s)||n.push(dv[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}=dv[e];throw new ct(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Lat(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 ct(`${e} must be a JSON object, not ${n}.`)}async function vW(e,t,r){let n={filter:Lat("filter",r.filter),change:Lat("change",r.change)};xvr(t,n);let i;try{i=await e.post(Pat[t],{filter:n.filter,change:n.change},et)}catch(u){throw $at(u),u}let{data:o,...s}=i,a=Uat([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=Rvr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function wAe(e,t){return{error:`${t} ${jat}`,outcome:"UNKNOWN",previewId:e,next:qat}}function Bvr(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 wAe(e,"The apply answered without a per-record result.");let i=AAe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=Uat(Object.keys(o)),a=o[Svr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Nvr}:a==="UNKNOWN"?{error:jat}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?qat:kvr},failed:i.slice(0,_Ae),...i.length>_Ae?{failedNotShown:i.length-_Ae}:{},data:r}}async function SW(e,t,r=Dvr){let n;try{n=await e.post(CW,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=$at(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw ut(i);return wAe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof zp)throw ut(i);let o=i instanceof Error?i.message:String(i);return wAe(t,`No answer arrived from the apply (${o}).`)}return Bvr(t,n)}var Qat,sA,Pat,CW,_vr,Mat,Bat,dv,Oat,wvr,vvr,Svr,Dvr,wW,_Ae,fv,lon,uv,Fat,qat,kvr,Nvr,jat,vAe=J(()=>{"use strict";Ki();EW();lP();ot();fo();tr();CAe();Qat=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],sA=["TRANSACTIONS","LINE_ITEMS"],Pat={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},CW="/api/v1/ledger/find-fix/apply",_vr=CW.slice(0,CW.lastIndexOf("/")+1),Mat={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"}},Bat=["types","resourceIds","reference","valueDate","contactResourceId"],dv={TRANSACTIONS:{filter:Bat,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Bat,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Oat={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."},wvr=[[/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."]],vvr="Not described by this client version; read the records that carry it.";Svr="OUTCOME_UNKNOWN",Dvr=25e3,wW=3e5,_Ae=50,fv=12,lon=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${fv}}(?![A-Za-z0-9_-])`,"i"),uv=e=>e.resourceId?` (${e.resourceId})`:"",Fat={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${uv(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${uv(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${uv(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${uv(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${uv(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${uv(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."}};qat="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.",kvr="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.",Nvr="Nothing changed: every record in the preview failed.",jat="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function DW(e,t){return e.list("/api/v1/nano-classifiers",t)}async function QE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function RW(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function aO(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function cO(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function TW(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Ovr(e,t):{};let{data:n}=await QE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Hat(n)}async function Ovr(e,t){let{data:r}=await QE(e,t);return Hat(r)}function Hat(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function xW(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var Yat,SAe=J(()=>{"use strict";Yat=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function kW(e,t){return e.post("/api/v1/export-records",t,et)}async function NW(e,t){return e.post("/api/v1/export-records/preview",t,et)}async function BW(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var DAe=J(()=>{"use strict";tr()});function OW(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Vat(e,t,r,n=!1){if(!Array.isArray(e))throw new ue(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new ue(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new ue(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new ue(`${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 FW(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 LW(e,t,r){return OW(t,Jat),Zi(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Sc(ap,t)}/${encodeURIComponent(r)}/approve`,void 0,Oke)}async function QW(e,t,r){return OW(t,Jat),Vat(r,Fvr,"bulk approve",!0),r.forEach(n=>Zi(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Sc(ap,t)}/bulk-approve`,{resourceIds:r},Fke)}async function PW(e,t,r,n){OW(t,Gat),Zi(r,"resourceId","Pass the document resourceId."),Wat(n);let i=await e.post(`/api/v1/${Sc(PE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Pvr(i)}}}async function MW(e,t,r,n){return OW(t,Gat),Wat(n),Vat(r,Lvr,"bulk request changes"),r.forEach(i=>Zi(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(Qvr(t),{resourceIds:r,message:n})}function Qvr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Sc(zat,e)}/bulk-request-changes`}function Wat(e){if(!e||e.trim().length===0)throw new ue("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 Pvr(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 ap,zat,PE,Jat,Gat,Fvr,Lvr,RAe=J(()=>{"use strict";ot();tr();ap=["invoices","bills","customer-credit-notes","supplier-credit-notes"],zat=[...ap,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],PE=[...zat,"claims"],Jat=new Set(ap),Gat=new Set(PE);Fvr=100,Lvr=500});function Mvr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${Kat(t)}:${Kat(r)}:${n}`}function Kat(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function TAe(e){if(!Xat.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...Xat].join(", ")}`)}async function Zat(e,t,r){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function ect(e,t,r,n){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function tct(e,t,r,n,i){if(TAe(t),Zi(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new ue('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??Mvr(t,r,n)}})}async function rct(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var Xat,nct=J(()=>{"use strict";ot();Xat=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function Uvr({fromPeriod:e,toPeriod:t},r){for(let[n,i]of[["fromPeriod",e],["toPeriod",t]])if(i!==void 0){if(!Number.isInteger(i)||i<1)throw new ct(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new ct("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new ct(`${n} ${i} is past the last period (${r}). Send a period from 1 to ${r}.`)}if(e!==void 0&&t!==void 0&&e>t)throw new ct(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function UW(e,t,r){let n=e.length;if(Uvr(t,e[n-1]),n===0)return{start:0,end:0,window:{totalPeriods:0}};let i=t.fromPeriod===void 0?0:e.filter(u=>u<t.fromPeriod).length,o=t.toPeriod===void 0?n:e.filter(u=>u<=t.toPeriod).length,s=o===0&&t.toPeriod!==void 0,a=s?Math.min(t.toPeriod-(t.fromPeriod??1)+1,n,r):Math.min(o,i+r);if(a<=i)throw new ct(`No period falls in that range: the schedule runs from period ${e[0]} to ${e[n-1]}.`);let c={totalPeriods:n,fromPeriod:e[i],toPeriod:e[a-1]};if(i>0||a<n){let u=[`Showing periods ${e[i]} to ${e[a-1]} of ${n}.`];a<n&&u.push(`Periods ${e[a]} to ${e[n-1]} are not shown: call again with fromPeriod ${e[a]} to read the next range (at most ${r} periods come back per call).`),i>0&&u.push(`Periods ${e[0]} to ${e[i-1]} are not shown: call again with fromPeriod ${e[0]} to read them.`),c.note=u.join(" ")}return s&&(c.note=`Periods ${t.fromPeriod??1} to ${t.toPeriod} come before this schedule, which starts at period ${e[0]}. Showing the first periods instead. ${c.note??""}`.trim()),{start:i,end:a,window:c}}function pv(e,t={},r=lO){let n=e.data,i=ME(n.rows),{start:o,end:s,window:a}=UW(xAe(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function $W(e,t={},r=lO){let n=e.data,i=ME(n.rows),o=h=>h.rowType==="PERIOD",s=i.findIndex(o),a=i.map(o).lastIndexOf(!0),c=s===-1?[]:i.slice(s,a+1),{start:u,end:d,window:f}=UW(xAe(c),t,r);if(s===-1)return{...e,data:{...f,...n}};let p=[...u===0?i.slice(0,s):[],...c.slice(u,d),...d===c.length?i.slice(a+1):[]];return{...e,data:{...f,...n,rows:p}}}function ict(e,t,r,n,i){let o=e.data,s=ME(o[t]),a=s.reduce((h,m)=>h+ME(m[r]).length,0),{start:c,end:u,window:d}=UW(Array.from({length:a},(h,m)=>m+1),n,i);if(a===0)return{...e,data:{...d,...o}};let f=0,p=[];for(let h of s){let m=ME(h[r]),A=m.slice(Math.max(c-f,0),Math.max(u-f,0));A.length>0&&p.push({...h,[r]:A}),f+=m.length}return{...e,data:{...d,...o,[t]:p}}}function gd(e,t={},r=lO){let n=e.data,i=ME(n.periods),{start:o,end:s,window:a}=UW(xAe(i,"period"),t,r);if(i.length===0)return{...e,data:{...a,...n}};let c=i[o].startDate,u=i[s-1].endDate,d=f=>typeof f.toDate!="string"||typeof f.fromDate!="string"||typeof c!="string"||typeof u!="string"||f.toDate>=c&&f.fromDate<=u;return typeof a.note=="string"&&(a.note+=" The timeline lists only the segments that touch these periods."),{...e,data:{...a,...n,periods:i.slice(o,s),timeline:ME(n.timeline).filter(d)}}}var lO,ME,xAe,qW,jW,hv=J(()=>{"use strict";fo();lO=60;ME=e=>Array.isArray(e)?e:[],xAe=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);qW=(e,t={},r=lO)=>ict(e,"depreciationScheduled","depreciation",t,r),jW=(e,t={},r=lO)=>ict(e,"amortizationScheduled","amortization",t,r)});async function UE(e,t){return e.get(`/api/v1/loans/${t}`)}async function YW(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function HW(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function zW(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},$ke)}async function JW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names loan ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await UE(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function GW(e,t){await e.delete(`/api/v1/loans/${t}`)}async function VW(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},sZ)}async function WW(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},sZ)}async function KW(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function XW(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function ZW(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function e4(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function t4(e,t){return e.post("/api/v1/loans/preview-schedule",t,et)}async function r4(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,et)}async function n4(e,t){return mt(t,"loans",500,"loans"),jo(t,oct),En(e,"/api/v1/loans/bulk-upsert","loans",t)}async function i4(e,t){return mt(t,"loans",500,"loans"),jo(t,$vr),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`loans[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that loan. Bulk update does not take tags: change them with update_loan (clio loans update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/loans/bulk-update","loans",t)}async function o4(e,t,r,n,i){let o=uO[t];if(i){if(!o.calculate)throw new Error(`Loan event ${t} has no preview.`);let s=Object.fromEntries(Object.entries(n).filter(([a])=>!o.recordOnly?.includes(a)));return e.post(o.calculate,{...s,resourceId:r},et)}return e.post(o.record(r),{...n,resourceId:r},qke)}var oct,$vr,uO,kAe=J(()=>{"use strict";an();ot();tr();oct=["drawdownDate","trackingStartDate","firstRepaymentDate"],$vr=[...oct,"capitalizationStartDate","capitalizationEndDate"];uO={drawdown:{calculate:"/api/v1/loans/calculate-drawdown",record:e=>`/api/v1/record-drawdown/loans/${e}`},prepayment:{calculate:"/api/v1/loans/calculate-prepayment",record:e=>`/api/v1/prepay/loans/${e}`},rateChange:{calculate:"/api/v1/loans/calculate-rate-change",record:e=>`/api/v1/change-rate/loans/${e}`},capitalization:{calculate:"/api/v1/loans/calculate-capitalization",record:e=>`/api/v1/capitalize-interest/loans/${e}`},paymentHoliday:{calculate:"/api/v1/loans/calculate-payment-holiday",record:e=>`/api/v1/payment-holiday/loans/${e}`},restructure:{calculate:"/api/v1/loans/calculate-restructure",record:e=>`/api/v1/restructure/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},settlement:{calculate:"/api/v1/loans/calculate-settlement",record:e=>`/api/v1/settle/loans/${e}`},forgiveness:{calculate:"/api/v1/loans/calculate-forgiveness",record:e=>`/api/v1/forgive/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},conversion:{calculate:"/api/v1/loans/calculate-conversion",record:e=>`/api/v1/convert-to-shares/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},refinance:{record:e=>`/api/v1/refinance/loans/${e}`},reclassifyAsCurrent:{record:e=>`/api/v1/reclassify-as-current/loans/${e}`},undo:{record:e=>`/api/v1/undo-event/loans/${e}`}}});function mv(e){mt(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new ue(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!BFe(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!qvr.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 ue(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function s4(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},et);return{data:Yvr(r.data)}}function jvr(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 Yvr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(jvr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function a4(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function c4(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var qvr,NAe=J(()=>{"use strict";ot();iee();an();tr();qvr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function lct(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new ue("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function BAe(e,t){if(!e||typeof e!="object")throw new ue(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new ue(`${t}.lineItems array is empty.`);if(n.length>500)throw new ue(`max 500 ${t}.lineItems per call.`);jo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&jo([i],["valueDate"])}async function u4(e,t,r=OAe){return e.post("/api/v1/search-magic-reconciliation",t,{...et,timeoutMs:r})}function l4(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Gvr(e){let t=l4(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=l4(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function Vvr(e){return e?e.value>=(e.from==="confidenceScore"?Hvr:zvr)?"high":e.value>=Jvr?"medium":"low":"low"}function Kvr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(sct,t))return;let r=sct[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function aA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function act(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function Xvr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>act({account:aA(n?.account),taxProfile:aA(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(!(!aA(e.contact)&&!aA(e.account)&&!aA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return act({contact:aA(e.contact),account:aA(e.account),taxProfile:aA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function uct(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=>n0r(c,h??{},u.length-1,t)).sort(Zvr),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 Zvr(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 e0r(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return vc.test(t)?t:void 0}function t0r(e){let{recommendationId:t,...r}=e;return r}function r0r(e,t,r){return!t||!r?t:e===$E.learnedPrediction?{...t,recommendationId:r}:e===$E.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function n0r(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=l4(t.matchScore),s=l4(t.confidenceScore),a=Gvr(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=$E.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=$E.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let F=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,G=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,j=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;F&&G&&j&&(m=$E.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:F,predictedPayload:G,predictedPayloadSchemaVersion:j});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let F=t.actionShortcut??{},G=typeof F.resourceId=="string"?F.resourceId:void 0;G&&(m=$E.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=r0r(m,A,e0r(t)),y=m?Vvr(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==$E.withPayments||b,T=Kvr(t),D=!m||!g?"NO_PLAN":T?Wvr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",k=Xvr(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:D===void 0,...D?{checkpointReason:D}:{},...k?{proposedPosting:k}:{},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(t0r(t))}`}}function i0r(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 o0r(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 ho(e,i):await Eo(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}): ${RE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function dct(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,cct);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 nC(e,t,{filter:{resourceId:{in:u}},limit:cct}),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: ${RE(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 i0r(u,f,await o0r(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function d4(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,ya)}async function f4(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,ya)}async function p4(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,ya)}async function h4(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,ya)}async function m4(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,ya)}async function A4(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,ya)}async function g4(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,ya)}async function y4(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,ya)}async function E4(e,t){return e.post("/api/v1/reconciliations/with-payments",t,ya)}async function b4(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,ya)}async function I4(e,t){return e.post("/api/v1/reconciliations/magic-match",t,ya)}async function C4(e,t){return e.post("/api/v1/reconciliations/reset",t)}var $E,OAe,Hvr,zvr,Jvr,Wvr,sct,cct,_4=J(()=>{"use strict";Rg();TE();ot();af();an();zg();tr();$E={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},OAe=6e4;Hvr=.9,zvr=.95,Jvr=.7;Wvr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},sct={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};cct=25});function ia(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 Po(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:FAe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=FAe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=FAe(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 FAe(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 ts(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=ia(e,t,n),a=Po(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 xa,tl,vo,nu,fct=J(()=>{"use strict";xa=[{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}],tl=[...xa],vo=xa.filter(e=>e.field!=="dueDate"),nu=[{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 yd(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=_c(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function w4(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=BI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var pct=J(()=>{"use strict";Vp()});var LAe=J(()=>{"use strict";fct();Vp();pct()});var dO,v4,rs,oo,QAe=J(()=>{"use strict";dO="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",v4=["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"],rs="If the result says it runs in the background, do not poll: its result arrives by itself.",oo=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${rs} PARTIAL_SUCCESS: errorDetails.`});function hct(e){return s0r.get(e)}function mct(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&&!S4.has(o));return n.length===0?[]:Mi.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 Mi,S4,s0r,Ed=J(()=>{"use strict";QAe();IAe();Mi=[{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. 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. Fixed asset register reports are in register_reports.",groups:["operational_reports","exports"]},{name:"register_reports",title:"Register Reports",description:"Register reports: fixed asset register summary by account, type, category or active/closed-out/disposed state (asset register roll-forward over a period), fixed asset register vs general ledger reconciliation (does the register agree with the GL), deferrals summary (prepaid and deferred revenue roll-forward) and deferrals reconciliation (does the prepaid register agree with the GL), lease register summary (IFRS 16 lease note, lease liability roll-forward) and lease register vs general ledger reconciliation (rent coded to the lease liability account). Loan reports: borrowings note summary, loan roll-forward, related-party (director, shareholder) loan balances, loan interest cost, maturity analysis (liquidity note), loan register vs ledger reconciliation.",groups:["register_reports"]},{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. For what-if questions and topics with no register; to keep a lease, loan, prepaid or deferred revenue use its register. Keywords: calculate, what-if, monthly payment, 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, set up to repeat every month.",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 (one or bulk), discard, sell, transfer, undo disposal, close out (stop depreciating, keep the asset) and reopen. Also: depreciation, asset register. Depreciation schedules, totals, eligible bill lines and asset types are in fixed_asset_schedules.",groups:["fixed_assets"]},{name:"fixed_asset_schedules",title:"Fixed Asset Schedules & Totals",description:"Read-only fixed asset views. Show one asset's depreciation by month and year, net book value, asset register totals as at a date, disposal totals (gain/loss), eligible bill lines to register as assets, asset types. Check custom depreciation ranges; calculate disposal (accumulated depreciation, net book value) before selling or discarding.",groups:["fixed_asset_schedules"]},{name:"deferrals",title:"Deferrals (Prepaid & Deferred Revenue)",description:"Deferrals register: prepaid expense, prepayment, deferred revenue, unearned revenue. Spread a bill over months, recognise an invoice over months (amortization, release schedule). Search, create, update, delete, stop amortising early (close out) and undo it, totals as at a date, schedule, eligible bill or invoice lines, deferral types and deferral accounts (mark the accounts first), bulk create and update.",groups:["deferrals"]},{name:"leases",title:"Leases (IFRS 16)",description:"Leases under IFRS 16: put an office rent lease on the books (right-of-use asset, ROU, and lease liability, current and non-current), hire purchase (flat rate to monthly discount rate), short-term or low-value exemption. Search, create, update, delete, close out, terminate lease (preview the gain or loss first) and undo either; lease schedule, liability totals as at a date, rent schedule preview, lease types.",groups:["leases"]},{name:"loans",title:"Loans (Borrowings)",description:"Loans and borrowings register: record a new bank loan, loan, borrowing, bank loan, term loan, director's loan (revolving credit and loans given are not in the register), instalment / installment loan. Search, create, update (one or bulk), delete, close out. What do we owe a lender or the bank: outstanding principal, current and non-current at a date, the repayment schedule, an on-demand loan ledger (an on-demand loan has no schedule, is all current and posts no interest), loan types, preview the monthly payment. Loan changes (drawdown, prepay, rate change, settle) are in loan_events; loan reports are in register_reports.",groups:["loans"]},{name:"loan_events",title:"Loan Events",description:"Events on an existing loan: drawdown, prepay or extra repayment, rate change, payment holiday, capitalize interest, restructure, refinance, settle / payoff, forgive / write off a loan, convert loan to shares, covenant breach (reclassify as current), undo loan event, balance after a missed payment. preview: true calculates the figures and saves nothing.",groups:["loan_events"]},{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 ${xat}. On a record: ${kat}. On lines: ${Nat}. 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, ${v4.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"]}],S4=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"]),s0r=new Map(Mi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function bd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function a0r(e){let t=Act.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(bd(r),n);for(let r of e.enum??[])t.set(bd(r),r);Act.set(e,t)}return t}function gct(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=bd(e);if(!r)return null;let n=a0r(t).get(r);return n!==void 0&&n!==e?n:null}function c0r(e){let t=yct.get(e);return t||(t=new Map(Object.keys(e).map(r=>[bd(r),r])),yct.set(e,t)),t}function l0r(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 u0r(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 PAe(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=c0r(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=bd(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"?l0r(d):u0r(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=gct(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=gct(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=fee(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=PAe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=PAe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Ect(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:PAe(t,e.params,"",r),coercions:r}}function bct(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 Act,yct,MAe=J(()=>{"use strict";NU();Act=new WeakMap;yct=new WeakMap});function Av(e){let t=new Set,r=[];for(let n of e)for(let i of iu(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function fO(){return Mi.map(e=>{let t=Av(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 d0r(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 f0r(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 cA(e,t=!1){let r=lA(void 0).length,n=Mi.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:f0r(r)}:e&&i!==void 0?{packaging:d0r(e,i,r)}:{},map:fO(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var D4=J(()=>{"use strict";Ed();ou()});function R4(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=R4(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=R4(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function su(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=R4(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function pO(e){return{name:e.name,description:e.description,input_schema:su(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var gv=J(()=>{"use strict"});function hO(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 UAe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function T4(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&hO(e),idempotentHint:e.readOnly,openWorldHint:UAe(e)}}function h0r(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function m0r(e){let t=h0r(e);return!t||p0r.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!S4.has(n)).length===0}function $Ae(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 qAe(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?qAe(o,`${i}.`):[]]})}function g0r(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
663
663
|
`)[0]}`.toLowerCase(),n=[...e.description.split(`
|
|
664
664
|
`).slice(1),...qAe(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>Ict?`${o.slice(0,Ict-1)}\u2026`:o}}function x4(e,t="meta"){let r=t==="meta"?"search_tools with an empty query":"describe_capabilities with no arguments";if(m0r(e)){if(t!=="meta")return cA(t);let{next:a,...c}=cA();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=Rl(e.trim());if(n)return{matches:[],hint:n};let i=mct(e,5);if(i.length===0){let{operations:a,namespaces:c}=cA();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=>iu(m)),u=c.map(m=>`${m.name} ${(m.aliases??[]).join(" ")} ${m.searchHint??""} ${m.description} ${qAe(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&&!S4.has(m)&&!A0r.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?g0r(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. ${$Ae(t)}`}}function Cct(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=mO(n);if(!i){r.push(n);continue}t.push({...pO(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&hO(i),group:i.group})}return{tools:t,...r.length>0?{notFound:r,hint:r.map(Rl).find(Boolean)??`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var p0r,Ict,A0r,y0r,E0r,b0r,yv,uA,qE=J(()=>{"use strict";Ed();D4();ou();gv();hg();p0r=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"]);Ict=160,A0r=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"]);y0r={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:su({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};E0r={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:su({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},b0r={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:su({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"])},yv={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:su({},[])},uA=[y0r,E0r,b0r]});function w0r(e){if(!(ka in e))return{cleanedInput:e};let{[ka]:t,...r}=e;return{jotText:typeof t=="string"&&t.trim()!==""?t.trim():void 0,cleanedInput:r}}function AO(e){return!e.readOnly&&!e.params[ka]&&e.group!=="jots"}function vct(e,t){if(e.params[ka])return{cleanedInput:t};let{jotText:r,cleanedInput:n}=w0r(t);return AO(e)?{jotText:r,cleanedInput:n}:{cleanedInput:n}}function v0r(e){let t=C0r.exec(e);return t?{kind:t[1],call:e.slice(t[0].length)||e}:{call:e}}function D0r(e){let t=e.toLowerCase();for(let[r,n]of S0r)if(n.test(t))return r}function R0r(e,t){let r=D0r(e),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=_ct||a>_0r||!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>=_ct)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 k4(e,t,r,n){let{kind:i,call:o}=v0r(r),s=R0r(t,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${t}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};Xw(e,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(mD(),hD)).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.5.
|
|
3
|
+
"version": "9.5.5",
|
|
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": {
|