jaz-clio 5.52.0 → 5.52.2

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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-api
3
- version: 5.52.0
3
+ version: 5.52.2
4
4
  description: >-
5
5
  Use this skill whenever you call, debug, or review code that touches the Jaz
6
6
  REST API. Covers field names, response shapes, 159 production gotchas, error
@@ -642,7 +642,7 @@ All 28 `POST /*/search` endpoints accept this filter structure in the POST body:
642
642
 
643
643
  ### Pagination
644
644
 
645
- See `endpoints.md` § "Pagination (All List Endpoints)" for the full spec (limit/offset semantics, defaults, constraints, sort requirement, examples). Key points: `offset` is a 0-indexed page number (not row-skip), default limit=100, max 1000, sort required on POST /search when offset is present. Exception: `organization-report-template/search` returns a plain array (no pagination).
645
+ See `endpoints.md` § "Pagination (All List Endpoints)" for the full spec (limit/offset semantics, defaults, constraints, sort requirement, examples). Key points: `offset` is a 0-indexed page number (not row-skip), default limit=100, max 1000, sort required on POST /search when offset is present. Exception: `organization-report-template/search` returns a plain array upstream (no pagination); the tools normalize it to the standard envelope.
646
646
 
647
647
  ### Date Format Asymmetry (CRITICAL)
648
648
 
@@ -548,7 +548,7 @@ All search endpoints return:
548
548
  }
549
549
  ```
550
550
 
551
- **Exception**: `POST /organization-report-template/search` returns a plain array (no pagination metadata).
551
+ **Exception**: `POST /organization-report-template/search` returns a plain array upstream (no pagination metadata). The tools normalize it to the usual `{data, totalElements, totalPages}` envelope — read `.data`.
552
552
 
553
553
  ---
554
554
 
@@ -28,7 +28,7 @@ All search endpoints share this identical structure:
28
28
 
29
29
  **Response shape**: `{ totalElements, totalPages, data: [...] }` — all search/list endpoints return this flat structure directly (no outer `data` wrapper).
30
30
 
31
- > **Exception**: `POST /organization-report-template/search` returns a plain array (no pagination metadata, no `totalElements`/`totalPages`).
31
+ > **Exception**: `POST /organization-report-template/search` returns a plain array upstream (no pagination metadata, no `totalElements`/`totalPages`). The `search_organization_report_templates` / `list_organization_report_templates` TOOLS normalize it, so what you receive is the usual `{data, totalElements, totalPages}` envelope like every other list tool. Read `.data`; do not treat the tool result as a top-level array.
32
32
 
33
33
  ---
34
34
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-cli
3
- version: 5.52.0
3
+ version: 5.52.2
4
4
  description: >-
5
5
  Use this skill when running Clio CLI commands, building shell scripts with
6
6
  Clio, debugging auth issues, understanding --json output, paginating results,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-conversion
3
- version: 5.52.0
3
+ version: 5.52.2
4
4
  description: >-
5
5
  Use this skill when migrating accounting data into Jaz — importing from Xero,
6
6
  QuickBooks, Sage, MYOB, or Excel exports. Covers the full conversion pipeline:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-kit
3
- version: 5.52.0
3
+ version: 5.52.2
4
4
  description: >-
5
5
  Use this skill when an accountant, bookkeeper, or owner is running real books
6
6
  in Jaz across one or more organizations from the terminal — setting up a
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-pseudo-sql
3
- version: 5.52.0
3
+ version: 5.52.2
4
4
  description: >-
5
5
  Use this skill when answering ad-hoc data questions that aren't covered by
6
6
  download_export (canonical reports — anomaly, audit, aging, P&L, BS, GL,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-jobs
3
- version: 5.52.0
3
+ version: 5.52.2
4
4
  description: >-
5
5
  Use this skill for recurring accounting workflows — month/quarter/year-end
6
6
  close, bank reconciliation, GST/VAT filing, payment runs, credit control,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-recipes
3
- version: 5.52.0
3
+ version: 5.52.2
4
4
  description: >-
5
5
  Use this skill when modeling complex multi-step accounting transactions —
6
6
  anything that spans multiple periods, involves changing amounts, or requires
package/cli.mjs CHANGED
@@ -193,7 +193,7 @@ ${c}${s}
193
193
  ${a}`:""}`}default:{let s=e?`${Z("cyan",qe)} `:"",a=e?Z("cyan",fo):"";return`${r}${s}${i}
194
194
  ${a}
195
195
  `}}}}).prompt()});var x0e,T0e,twt,rwt,nwt,iwt,owt,gl,p$r,B0e=X(()=>{M4();x0e={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},T0e={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},twt={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},rwt={...x0e,...T0e},nwt={...x0e,...twt},iwt=Nw(),owt=iwt?rwt:nwt,gl=owt,p$r=Object.entries(T0e)});var D9={};So(D9,{COL_GAP:()=>qw,INDENT:()=>wt,accent:()=>_e,box:()=>yn,danger:()=>ne,highlight:()=>R,info:()=>Ac,isCI:()=>k0e,isTTY:()=>vF,muted:()=>H,shouldAnimate:()=>_9,subtle:()=>ta,success:()=>q,sym:()=>ss,underline:()=>w9,warning:()=>ke});function vF(){return!!process.stdout.isTTY}function k0e(){return!!process.env.CI}function _9(){return vF()&&!k0e()&&!process.env.NO_COLOR}var _e,H,q,ke,ne,Ac,R,ta,w9,ss,yn,wt,qw,Oe=X(()=>{"use strict";CE();B0e();_e=ar.hex("#6699ff"),H=ar.dim,q=ar.hex("#14b856"),ke=ar.hex("#ff9466"),ne=ar.hex("#f87777"),Ac=ar.cyan,R=ar.bold,ta=ar.gray,w9=ar.underline,ss={tick:gl.tick,cross:gl.cross,warning:gl.warning,info:gl.info,pointer:gl.pointer,bullet:gl.bullet,arrowRight:gl.arrowRight,ellipsis:gl.ellipsis,line:gl.line,pointerSmall:gl.pointerSmall},yn={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524"},wt=" ",qw=2});var $E,R9=X(()=>{"use strict";$E="pat-"});import{readFileSync as fwt,writeFileSync as pwt,renameSync as hwt,mkdirSync as mwt,unlinkSync as Awt,existsSync as gwt,openSync as ywt,fsyncSync as Ewt,closeSync as bwt}from"fs";import{join as U0e}from"path";import{homedir as Cwt}from"os";function Cu(){try{let t=fwt(jw,"utf-8"),e=JSON.parse(t);if(e.version===2)return e;if(e.apiKey){let r={version:2,active:"default",orgs:{default:{apiKey:e.apiKey,orgName:"Unknown (migrated)",orgId:"",currency:"",country:"",addedAt:e.createdAt??new Date().toISOString()}}};try{Yw(r)}catch{}return r}return null}catch{return null}}function Yw(t){mwt($0e,{recursive:!0});let e=jw+".tmp";pwt(e,JSON.stringify(t,null,2)+`
196
- `,{mode:384});let r=ywt(e,"r");try{Ewt(r)}finally{bwt(r)}hwt(e,jw)}function gc(t){return Cu()?.orgs[t]??null}function Hw(t,e){let r=Cu()??{version:2,active:"",orgs:{}};r.orgs[t]=e,(!r.active||Object.keys(r.orgs).length===1)&&(r.active=t),Yw(r)}function x9(t){let e=Cu();return!e||!(t in e.orgs)?!1:(delete e.orgs[t],e.active===t&&(e.active=""),Yw(e),!0)}function Ta(){return Cu()?.active||null}function T9(t){let e=Cu();if(!e)throw new Error("No credentials file found. Run `clio auth add <key>` first.");if(!(t in e.orgs)){let r=Object.keys(e.orgs).join(", ");throw new Error(`Org '${t}' not found. Available: ${r}`)}e.active=t,Yw(e)}function yl(){return Cu()?.orgs??{}}function B9(t){let e=Cu();if(!e)return null;for(let[r,n]of Object.entries(e.orgs))if(n.apiKey===t)return r;return null}function k9(){return gwt(jw)?(Awt(jw),!0):!1}var $0e,jw,zw=X(()=>{"use strict";$0e=U0e(Cwt(),".config","jaz-clio"),jw=U0e($0e,"credentials.json")});function N9(t){Gw=t}function CA(){return wF}function YE(){return Ba}function bA(t){let e=process.env[t];if(e===void 0)return;let r=e.trim();if(r!==""&&!r.includes("${"))return r}function Jw(t){let e=t.split(",").map(s=>s.trim()).filter(Boolean);if(e.length===0)throw new ko("Empty key value. Provide a Jaz API key (jk-...) or personal access token (pat-...).");let r=e.filter(s=>s.startsWith($E)),n=e.filter(s=>s.startsWith("jk-"));if(e.filter(s=>!s.startsWith($E)&&!s.startsWith("jk-")).length>0)throw new ko("Invalid key format (unrecognized prefix). Expected jk-... (API key) or pat-... (personal access token).");if(r.length>0&&n.length>0)throw new ko("Cannot mix PAT and API keys. Use either a single personal access token (pat-...) or one or more API keys (jk-...).");if(r.length>0&&e.length!==1)throw new ko("Only one personal access token allowed. Do not combine with other keys.");return r.length===1?[{mode:"pat",token:r[0]}]:[...new Set(n)].map(s=>({mode:"direct",apiKey:s}))}function _F(t){if(wF=null,Ba=null,t)return Ba="flag-api-key",Jw(t)[0];let e=bA("JAZ_API_KEY");if(e)return Ba="env-api-key",Jw(e)[0];if(Gw)return Ba="flag-org",qE(Gw);let r=bA("JAZ_ORG");if(r)return Ba="env-org",qE(r);let n=Ta();return n?(Ba="active-file",qE(n)):null}function qE(t){let e=gc(t);if(!e){let r=Cu(),n=r?Object.keys(r.orgs):[],i=n.length>0?` Available: ${n.join(", ")}`:" No orgs registered. Run `clio auth add <key>` first.";throw new ko(`Org '${t}' not found.${i}`)}return wF=t,{mode:"direct",apiKey:e.apiKey}}function DF(t){if(wF=null,Ba=null,t)return Ba="flag-api-key",Jw(t);let e=bA("JAZ_API_KEY");if(e)return Ba="env-api-key",Jw(e);if(Gw)return Ba="flag-org",[qE(Gw)];let r=bA("JAZ_ORG");if(r)return Ba="env-org",[qE(r)];let n=Ta();return n?(Ba="active-file",[qE(n)]):[]}function IA(t){let e=_F(t);if(!e)throw new ko("No API key configured. Run `clio auth add <key>`, set JAZ_API_KEY, or pass --api-key.");return e}var Gw,wF,Ba,ko,Vw=X(()=>{"use strict";R9();zw();wF=null;Ba=null;ko=class extends Error{constructor(e){super(e),this.name="AuthError"}}});function O9(t){return t.replace(/\/[a-f0-9-]{8,}(?=[/?#]|$)/gi,"/{id}")}function q0e(t){let e=O9(t),r=SF.get(e);if(!(!r||r.state==="closed")&&r.state==="open"){if(Date.now()-r.lastFailure>3e4){r.state="half-open";return}let n=Math.ceil((3e4-(Date.now()-r.lastFailure))/1e3);throw new Error(`Circuit open for ${e} \u2014 API endpoint appears down (${r.failures} consecutive failures). Retry in ${n}s.`)}}function j0e(t){let e=O9(t),r=SF.get(e);r&&(r.failures=0,r.state="closed")}function Y0e(t){let e=O9(t),r=SF.get(e)??{failures:0,lastFailure:0,state:"closed"};r.failures++,r.lastFailure=Date.now(),r.failures>=5&&(r.state="open"),SF.set(e,r)}var SF,H0e=X(()=>{"use strict";SF=new Map});import{createHash as Iwt}from"node:crypto";function W0e(t){V0e=t}function z0e(t){if(t.data||(t.data=[]),t.totalElements===void 0){let e=t.pagination?.total;t.totalElements=typeof e=="number"?e:t.data.length}return t.totalPages===void 0&&(t.totalPages=t.data.length?1:0),t}function Rwt(t,e){if(e.baseUrl!==void 0)return e.baseUrl;if(t.mode==="direct"){let r=process.env.JAZ_API_URL;if(r!==void 0){let n=r.trim();if(n!==""&&!n.includes("${"))return n}}return vwt}function G0e(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=()=>{clearTimeout(i),r()},i=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);e?.addEventListener("abort",n,{once:!0})})}function J0e(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t;if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"){let r=e.error;if(Array.isArray(r.errors)&&r.errors.length>0)return r.errors.join("; ");if(typeof r.error_type=="string")return r.error_type}return JSON.stringify(t)}return String(t)}var vwt,wwt,_wt,Dwt,Swt,V0e,Vi,Wi,ka=X(()=>{"use strict";H0e();vwt="https://api.getjaz.com",wwt=3e4,_wt=3,Dwt=[429],Swt=[500,502,503],V0e="0.0.0";Vi=class extends Error{status;body;endpoint;constructor(e,r,n,i){super(e),this.status=r,this.body=n,this.endpoint=i,this.name="JazApiError"}};Wi=class{baseUrl;timeout;maxRetries;auth;onRequest;channel;requestId;constructor(e,r,n={}){this.auth=e,this.channel=r,this.baseUrl=Rwt(e,n).replace(/\/$/,""),this.timeout=n.timeout??wwt,this.maxRetries=n.maxRetries??_wt,this.onRequest=n.onRequest,this.requestId=n.requestId&&n.requestId!=="none"?n.requestId:void 0}get isPatAuth(){return this.auth.mode==="pat"}get scopeKey(){let e=this.auth,r=e.mode==="direct"?`direct:${e.apiKey}`:e.mode==="pat"?`pat:${e.orgId??""}:${e.token}`:`delegated:${e.orgId}:${e.userId}:${e.orgUserId??""}`;return Iwt("sha256").update(r).digest("hex").slice(0,24)}emitRequestEvent(e){try{this.onRequest?.(e)}catch{}}buildHeaders(e){let r={"Content-Type":"application/json","User-Agent":`jaz-clio/${V0e} (${this.channel})`,...e};switch(this.requestId&&(r["x-request-id"]=this.requestId),this.auth.mode){case"direct":r["x-jk-api-key"]=this.auth.apiKey;break;case"pat":r.Authorization=`Bearer ${this.auth.token}`,this.auth.orgId&&(r["x-jaz-org-key"]=this.auth.orgId);break;case"delegated":this.auth.orgUserId?(r["x-channel-key"]=this.auth.adminKey,r["x-jaz-org-key"]=this.auth.orgId,r["x-jaz-org-user-key"]=this.auth.orgUserId):(r["x-clio-admin-key"]=this.auth.adminKey,r["x-user-id"]=this.auth.userId,r["x-org-id"]=this.auth.orgId);break}return r}async request(e,r,n={}){let i=new URL(`${this.baseUrl}${r}`);if(n.query)for(let[d,f]of Object.entries(n.query))f!==void 0&&i.searchParams.set(d,String(f));let o=this.buildHeaders(n.headers);n.raw&&delete o["Content-Type"];let s=AbortSignal.timeout(n.timeoutMs??this.timeout),a={method:e,headers:o,signal:s};n.body!==void 0&&e!=="GET"&&e!=="DELETE"&&(a.body=n.raw?n.body:JSON.stringify(n.body)),q0e(r);let c,u=Date.now();for(let d=0;d<=this.maxRetries;d++){let f=Date.now();try{let p=await fetch(i.toString(),a),h=["GET","HEAD"].includes(e);if((Dwt.includes(p.status)||h&&Swt.includes(p.status))&&d<this.maxRetries){this.emitRequestEvent({method:e,path:r,statusCode:p.status,durationMs:Date.now()-f,attempt:d,retried:!0});let A=Math.min(1e3*2**d,8e3);await G0e(A,s);continue}if(!p.ok){let A=await p.text(),g;try{g=A&&JSON.parse(A)}catch{g=A}throw this.emitRequestEvent({method:e,path:r,statusCode:p.status,durationMs:Date.now()-f,attempt:d,retried:!1,error:J0e(g)}),p.status>=500&&Y0e(r),new Vi(`${e} ${r} \u2192 ${p.status}: ${J0e(g)}`,p.status,g,r)}return this.emitRequestEvent({method:e,path:r,statusCode:p.status,durationMs:Date.now()-f,attempt:d,retried:!1}),j0e(r),p.status===204?void 0:await p.json()}catch(p){if(p instanceof Vi)throw p;if(c=p,this.emitRequestEvent({method:e,path:r,statusCode:0,durationMs:Date.now()-f,attempt:d,retried:d<this.maxRetries,error:c.message}),d<this.maxRetries){let h=Math.min(1e3*2**d,8e3);await G0e(h,s);continue}}}throw c??new Error(`Request failed: ${e} ${r}`)}async get(e,r,n){return this.request("GET",e,{query:r,...n?.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}})}async post(e,r,n){return this.request("POST",e,{body:r,headers:n?.headers})}async put(e,r,n){return this.request("PUT",e,{body:r,headers:n?.headers})}async delete(e,r){return this.request("DELETE",e,{query:r})}async postMultipart(e,r){return this.request("POST",e,{body:r,raw:!0})}async list(e,r){let n=await this.get(e,{limit:r?.limit??100,offset:r?.offset??0,...r?.view?{view:r.view}:{}});return z0e(n)}async search(e,r){let n={};r.query&&(n.query=r.query),r.filter&&(n.filter=r.filter),r.limit!==void 0&&(n.limit=r.limit),r.offset!==void 0&&(n.offset=r.offset),r.view&&(n.view=r.view),r.magicSort&&(n.magicSort=r.magicSort),r.transactionType&&(n.transactionType=r.transactionType),r.multiContactOnly!==void 0&&(n.multiContactOnly=r.multiContactOnly),r.sort?n.sort=r.sort:r.offset!==void 0&&(n.sort={sortBy:["createdAt"],order:"DESC"});let i=await this.post(e,n);return z0e(i)}async listAll(e,r=200){let n=[],i=0,o=!0;for(;o;){let s=await this.list(e,{limit:r,offset:i});if(n.push(...s.data),s.data.length<r)break;i+=1,o=i*r<s.totalElements}return n}}});async function Na(t){let e=await t.get("/api/v1/organization");return Array.isArray(e.data)?e.data[0]:e.data}async function xwt(t){let e=await t.get("/api/v1/me/organizations"),r=e.boundOrganizationResourceId;return{organizations:Array.isArray(e.data)?e.data:[],boundOrganizationResourceId:r===null?"":r}}async function Z0e(t){return(await xwt(t)).organizations}async function X0e(t){return(await t.get("/api/v1/me")).data}var vA=X(()=>{"use strict"});var awe={};So(awe,{collectValue:()=>F9,parseCustomFields:()=>pn,parseJournalEntries:()=>yc,parseJsonArray:()=>Iu,parseJsonObject:()=>L9,parseLineItems:()=>jn,parseMoney:()=>cr,parseNonNegativeInt:()=>it,parseOrderTerms:()=>wA,parsePositiveInt:()=>he,parseRate:()=>as,parseTaxRatePercent:()=>RF,parseTemplateOverrides:()=>Q9,readBodyInput:()=>be,requireFields:()=>Le,splitCsv:()=>Zi,todayLocal:()=>M9});import{readFileSync as owe}from"node:fs";function he(t){let e=String(t).trim(),r=Number.parseInt(e,10);return(!swe.test(e)||!Number.isSafeInteger(r)||r<=0)&&(console.error(ne(`Error: invalid positive integer: ${t}`)),process.exit(1)),r}function it(t){let e=String(t).trim(),r=Number.parseInt(e,10);return(!swe.test(e)||!Number.isSafeInteger(r)||r<0)&&(console.error(ne(`Error: invalid non-negative integer: ${t}`)),process.exit(1)),r}function wA(t){let e=Number.parseInt(t,10);return(!Number.isFinite(e)||![0,7,15,30,45,60].includes(e))&&(console.error(ne(`Error: terms must be one of 0, 7, 15, 30, 45, 60 (got: ${t})`)),process.exit(1)),e}function cr(t){return/^-?\d+(\.\d{1,2})?$/.test(t)||(console.error(ne(`Error: invalid amount: ${t} (max 2 decimal places)`)),process.exit(1)),Math.round(Number(t)*100)/100}function as(t){let e=Number(t);return(!Number.isFinite(e)||e<=0)&&(console.error(ne(`Error: invalid exchange rate: ${t}`)),process.exit(1)),e}function RF(t){let e=String(t).trim(),r=Number(e);return(e===""||!Number.isFinite(r)||r<0||r>100)&&(console.error(ne(`Error: invalid tax rate percentage: ${t} (expected 0-100)`)),process.exit(1)),r}function jn(t){try{let e=JSON.parse(t);if(!Array.isArray(e))throw new Error("Line items must be a JSON array");return e}catch{console.error(ne("Error: --lines must be valid JSON array")),console.error(H(`Example: --lines '[{"name":"Service","quantity":1,"unitPrice":100,"accountResourceId":"..."}]'`)),console.error(H("Tip: pipe the full request body via stdin, or use --input <file>")),process.exit(1)}}function yc(t){try{let e=JSON.parse(t);if(!Array.isArray(e))throw new Error("Entries must be a JSON array");return e}catch{console.error(ne("Error: --entries must be valid JSON array")),console.error(H(`Example: --entries '[{"accountResourceId":"...","amount":100,"type":"DEBIT"},...]'`)),console.error(H("Tip: pipe the full request body via stdin, or use --input <file>")),process.exit(1)}}function pn(t){try{let e=JSON.parse(t);if(!Array.isArray(e))throw new Error("Must be a JSON array");return e}catch{console.error(ne("Error: --custom-fields must be valid JSON array")),console.error(H(`Example: --custom-fields '[{"customFieldName":"PO Number","actualValue":"PO-123"}]'`)),process.exit(1)}}function F9(t,e=[]){return e.push(t),e}function Q9(t){return t.map(e=>{let r=e.indexOf("=");r===-1&&(console.error(ne(`Error: --template-override must be "slotKey=template" (got "${e}")`)),console.error(H("Example: --template-override capsule.title='Loan {{loanReference}}'")),process.exit(1));let n=e.slice(0,r).trim(),i=e.slice(r+1);return n||(console.error(ne("Error: --template-override slotKey must be non-empty (slotKey=template)")),process.exit(1)),{slotKey:n,template:i}})}function L9(t,e="--inputs"){try{let r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("not an object");return r}catch{return console.error(ne(`Error: ${e} must be a valid JSON object`)),process.exit(1),{}}}function be(t){if(t.input){let e;try{e=owe(t.input,"utf-8")}catch{console.error(ne(`Error: cannot read file: ${t.input}`)),process.exit(1)}try{let r=JSON.parse(e);return(typeof r!="object"||r===null||Array.isArray(r))&&(console.error(ne("Error: --input file must contain a JSON object")),process.exit(1)),r}catch{console.error(ne("Error: --input file contains invalid JSON")),process.exit(1)}}if(!process.stdin.isTTY)try{let e=owe(0,"utf-8").trim();if(e){let r=JSON.parse(e);return(typeof r!="object"||r===null||Array.isArray(r))&&(console.error(ne("Error: stdin must contain a JSON object")),process.exit(1)),r}}catch(e){e.message?.includes("JSON")&&(console.error(ne("Error: stdin contains invalid JSON")),process.exit(1))}return null}function Le(t,e){let r=e.filter(n=>t[n.key]===void 0);if(r.length>0){let n=r.map(i=>i.flag).join(", ");console.error(ne(`Error: missing required option(s): ${n}`)),console.error(H("Provide flags, or pipe JSON via stdin, or use --input <file>")),process.exit(1)}}function Zi(t){if(t!==void 0)return t.split(",").map(e=>e.trim()).filter(Boolean)}function Iu(t,e){let r;try{r=JSON.parse(t)}catch{throw new Error(`Invalid JSON for ${e}: ${t.slice(0,80)}`)}if(!Array.isArray(r))throw new Error(`${e} must be a JSON array (got ${typeof r}).`);return r}function M9(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}var swe,_t=X(()=>{"use strict";Oe();swe=/^[+-]?\d+$/});var fwe=b(en=>{"use strict";function cwe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}var lwe;function dwe(t,e,r,n,i){if(i===void 0&&(i=en.PaymentDueTime.End),t===0)return-(n+r*e);var o=Math.pow(1+t,e);return-n*o-r*(1+t*(i===en.PaymentDueTime.Begin?1:0))/t*(o-1)}function U9(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=en.PaymentDueTime.End);var o=t===0,s=Math.pow(1+t,e),a=i===en.PaymentDueTime.Begin?1:0,c=o?1:t;return-(n+r*s)/(o?e:(1+c*a)*(s-1)/c)}function uwe(t,e,r,n,i,o){if(i===void 0&&(i=0),o===void 0&&(o=en.PaymentDueTime.End),e<1)return Number.NaN;if(o===en.PaymentDueTime.Begin&&e===1)return 0;var s=Lwt(t,e,U9(t,r,n,i,o),n,o)*t;return o===en.PaymentDueTime.Begin&&e>1&&(s/=1+t),s}function P9(t,e){return e.reduce((function(r,n,i){return r+n/Math.pow(1+t,i)}),0)}function Lwt(t,e,r,n,i){return dwe(t,e-1,r,n,i)}function Mwt(t,e,r,n,i,o){var s=o===en.PaymentDueTime.Begin?1:0,a=Math.pow(t+1,e),c=Math.pow(t+1,e-1);return(i+a*n+r*(a-1)*(t*s+1)/t)/(e*c*n-r*(a-1)*(t*s+1)/Math.pow(t,2)+e*r*c*(t*s+1)/t+r*(a-1)*s/t)}function Pwt(t,e,r){for(var n=r+1,i=t[0],o=1;o<t.length;o++)i+=t[o]/Math.pow(n,(e[o]-e[0])/365);return i}function Uwt(t,e,r){for(var n=r+1,i=0,o=1;o<t.length;o++){var s=(e[o]-e[0])/365;i-=s*t[o]/Math.pow(n,s+1)}return i}Object.defineProperty(en,"__esModule",{value:!0}),en.PaymentDueTime=void 0,(lwe=en.PaymentDueTime||(en.PaymentDueTime={})).Begin="begin",lwe.End="end",en.fv=dwe,en.ipmt=uwe,en.irr=function(t,e,r,n){e===void 0&&(e=.1),r===void 0&&(r=1e-6),n===void 0&&(n=100);for(var i=[],o=!1,s=!1,a=0;a<t.length;a++)i[a]=a===0?0:i[a-1]+365,t[a]>0&&(o=!0),t[a]<0&&(s=!0);if(!o||!s)return Number.NaN;var c=e,u=0,d=0,f=0,p=0,h=!0;do u=c-(f=Pwt(t,i,c))/Uwt(t,i,c),d=Math.abs(u-c),c=u,h=d>r&&Math.abs(f)>r;while(h&&++p<n);return h?Number.NaN:c},en.mirr=function(t,e,r){for(var n,i=!1,o=!1,s=(function(d,f){var p=typeof Symbol<"u"&&d[Symbol.iterator]||d["@@iterator"];if(p)return(p=p.call(d)).next.bind(p);if(Array.isArray(d)||(p=(function(m,A){if(m){if(typeof m=="string")return cwe(m,A);var g=Object.prototype.toString.call(m).slice(8,-1);return g==="Object"&&m.constructor&&(g=m.constructor.name),g==="Map"||g==="Set"?Array.from(m):g==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(g)?cwe(m,A):void 0}})(d))){p&&(d=p);var h=0;return function(){return h>=d.length?{done:!0}:{done:!1,value:d[h++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
196
+ `,{mode:384});let r=ywt(e,"r");try{Ewt(r)}finally{bwt(r)}hwt(e,jw)}function gc(t){return Cu()?.orgs[t]??null}function Hw(t,e){let r=Cu()??{version:2,active:"",orgs:{}};r.orgs[t]=e,(!r.active||Object.keys(r.orgs).length===1)&&(r.active=t),Yw(r)}function x9(t){let e=Cu();return!e||!(t in e.orgs)?!1:(delete e.orgs[t],e.active===t&&(e.active=""),Yw(e),!0)}function Ta(){return Cu()?.active||null}function T9(t){let e=Cu();if(!e)throw new Error("No credentials file found. Run `clio auth add <key>` first.");if(!(t in e.orgs)){let r=Object.keys(e.orgs).join(", ");throw new Error(`Org '${t}' not found. Available: ${r}`)}e.active=t,Yw(e)}function yl(){return Cu()?.orgs??{}}function B9(t){let e=Cu();if(!e)return null;for(let[r,n]of Object.entries(e.orgs))if(n.apiKey===t)return r;return null}function k9(){return gwt(jw)?(Awt(jw),!0):!1}var $0e,jw,zw=X(()=>{"use strict";$0e=U0e(Cwt(),".config","jaz-clio"),jw=U0e($0e,"credentials.json")});function N9(t){Gw=t}function CA(){return wF}function YE(){return Ba}function bA(t){let e=process.env[t];if(e===void 0)return;let r=e.trim();if(r!==""&&!r.includes("${"))return r}function Jw(t){let e=t.split(",").map(s=>s.trim()).filter(Boolean);if(e.length===0)throw new ko("Empty key value. Provide a Jaz API key (jk-...) or personal access token (pat-...).");let r=e.filter(s=>s.startsWith($E)),n=e.filter(s=>s.startsWith("jk-"));if(e.filter(s=>!s.startsWith($E)&&!s.startsWith("jk-")).length>0)throw new ko("Invalid key format (unrecognized prefix). Expected jk-... (API key) or pat-... (personal access token).");if(r.length>0&&n.length>0)throw new ko("Cannot mix PAT and API keys. Use either a single personal access token (pat-...) or one or more API keys (jk-...).");if(r.length>0&&e.length!==1)throw new ko("Only one personal access token allowed. Do not combine with other keys.");return r.length===1?[{mode:"pat",token:r[0]}]:[...new Set(n)].map(s=>({mode:"direct",apiKey:s}))}function _F(t){if(wF=null,Ba=null,t)return Ba="flag-api-key",Jw(t)[0];let e=bA("JAZ_API_KEY");if(e)return Ba="env-api-key",Jw(e)[0];if(Gw)return Ba="flag-org",qE(Gw);let r=bA("JAZ_ORG");if(r)return Ba="env-org",qE(r);let n=Ta();return n?(Ba="active-file",qE(n)):null}function qE(t){let e=gc(t);if(!e){let r=Cu(),n=r?Object.keys(r.orgs):[],i=n.length>0?` Available: ${n.join(", ")}`:" No orgs registered. Run `clio auth add <key>` first.";throw new ko(`Org '${t}' not found.${i}`)}return wF=t,{mode:"direct",apiKey:e.apiKey}}function DF(t){if(wF=null,Ba=null,t)return Ba="flag-api-key",Jw(t);let e=bA("JAZ_API_KEY");if(e)return Ba="env-api-key",Jw(e);if(Gw)return Ba="flag-org",[qE(Gw)];let r=bA("JAZ_ORG");if(r)return Ba="env-org",[qE(r)];let n=Ta();return n?(Ba="active-file",[qE(n)]):[]}function IA(t){let e=_F(t);if(!e)throw new ko("No API key configured. Run `clio auth add <key>`, set JAZ_API_KEY, or pass --api-key.");return e}var Gw,wF,Ba,ko,Vw=X(()=>{"use strict";R9();zw();wF=null;Ba=null;ko=class extends Error{constructor(e){super(e),this.name="AuthError"}}});function O9(t){return t.replace(/\/[a-f0-9-]{8,}(?=[/?#]|$)/gi,"/{id}")}function q0e(t){let e=O9(t),r=SF.get(e);if(!(!r||r.state==="closed")&&r.state==="open"){if(Date.now()-r.lastFailure>3e4){r.state="half-open";return}let n=Math.ceil((3e4-(Date.now()-r.lastFailure))/1e3);throw new Error(`Circuit open for ${e} \u2014 API endpoint appears down (${r.failures} consecutive failures). Retry in ${n}s.`)}}function j0e(t){let e=O9(t),r=SF.get(e);r&&(r.failures=0,r.state="closed")}function Y0e(t){let e=O9(t),r=SF.get(e)??{failures:0,lastFailure:0,state:"closed"};r.failures++,r.lastFailure=Date.now(),r.failures>=5&&(r.state="open"),SF.set(e,r)}var SF,H0e=X(()=>{"use strict";SF=new Map});import{createHash as Iwt}from"node:crypto";function W0e(t){V0e=t}function z0e(t){if(Array.isArray(t)){let e=t;return{data:e,totalElements:e.length,totalPages:e.length?1:0}}if(t.data||(t.data=[]),t.totalElements===void 0){let e=t.pagination?.total;t.totalElements=typeof e=="number"?e:t.data.length}return t.totalPages===void 0&&(t.totalPages=t.data.length?1:0),t}function Rwt(t,e){if(e.baseUrl!==void 0)return e.baseUrl;if(t.mode==="direct"){let r=process.env.JAZ_API_URL;if(r!==void 0){let n=r.trim();if(n!==""&&!n.includes("${"))return n}}return vwt}function G0e(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=()=>{clearTimeout(i),r()},i=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);e?.addEventListener("abort",n,{once:!0})})}function J0e(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t;if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"){let r=e.error;if(Array.isArray(r.errors)&&r.errors.length>0)return r.errors.join("; ");if(typeof r.error_type=="string")return r.error_type}return JSON.stringify(t)}return String(t)}var vwt,wwt,_wt,Dwt,Swt,V0e,Vi,Wi,ka=X(()=>{"use strict";H0e();vwt="https://api.getjaz.com",wwt=3e4,_wt=3,Dwt=[429],Swt=[500,502,503],V0e="0.0.0";Vi=class extends Error{status;body;endpoint;constructor(e,r,n,i){super(e),this.status=r,this.body=n,this.endpoint=i,this.name="JazApiError"}};Wi=class{baseUrl;timeout;maxRetries;auth;onRequest;channel;requestId;constructor(e,r,n={}){this.auth=e,this.channel=r,this.baseUrl=Rwt(e,n).replace(/\/$/,""),this.timeout=n.timeout??wwt,this.maxRetries=n.maxRetries??_wt,this.onRequest=n.onRequest,this.requestId=n.requestId&&n.requestId!=="none"?n.requestId:void 0}get isPatAuth(){return this.auth.mode==="pat"}get scopeKey(){let e=this.auth,r=e.mode==="direct"?`direct:${e.apiKey}`:e.mode==="pat"?`pat:${e.orgId??""}:${e.token}`:`delegated:${e.orgId}:${e.userId}:${e.orgUserId??""}`;return Iwt("sha256").update(r).digest("hex").slice(0,24)}emitRequestEvent(e){try{this.onRequest?.(e)}catch{}}buildHeaders(e){let r={"Content-Type":"application/json","User-Agent":`jaz-clio/${V0e} (${this.channel})`,...e};switch(this.requestId&&(r["x-request-id"]=this.requestId),this.auth.mode){case"direct":r["x-jk-api-key"]=this.auth.apiKey;break;case"pat":r.Authorization=`Bearer ${this.auth.token}`,this.auth.orgId&&(r["x-jaz-org-key"]=this.auth.orgId);break;case"delegated":this.auth.orgUserId?(r["x-channel-key"]=this.auth.adminKey,r["x-jaz-org-key"]=this.auth.orgId,r["x-jaz-org-user-key"]=this.auth.orgUserId):(r["x-clio-admin-key"]=this.auth.adminKey,r["x-user-id"]=this.auth.userId,r["x-org-id"]=this.auth.orgId);break}return r}async request(e,r,n={}){let i=new URL(`${this.baseUrl}${r}`);if(n.query)for(let[d,f]of Object.entries(n.query))f!==void 0&&i.searchParams.set(d,String(f));let o=this.buildHeaders(n.headers);n.raw&&delete o["Content-Type"];let s=AbortSignal.timeout(n.timeoutMs??this.timeout),a={method:e,headers:o,signal:s};n.body!==void 0&&e!=="GET"&&e!=="DELETE"&&(a.body=n.raw?n.body:JSON.stringify(n.body)),q0e(r);let c,u=Date.now();for(let d=0;d<=this.maxRetries;d++){let f=Date.now();try{let p=await fetch(i.toString(),a),h=["GET","HEAD"].includes(e);if((Dwt.includes(p.status)||h&&Swt.includes(p.status))&&d<this.maxRetries){this.emitRequestEvent({method:e,path:r,statusCode:p.status,durationMs:Date.now()-f,attempt:d,retried:!0});let A=Math.min(1e3*2**d,8e3);await G0e(A,s);continue}if(!p.ok){let A=await p.text(),g;try{g=A&&JSON.parse(A)}catch{g=A}throw this.emitRequestEvent({method:e,path:r,statusCode:p.status,durationMs:Date.now()-f,attempt:d,retried:!1,error:J0e(g)}),p.status>=500&&Y0e(r),new Vi(`${e} ${r} \u2192 ${p.status}: ${J0e(g)}`,p.status,g,r)}return this.emitRequestEvent({method:e,path:r,statusCode:p.status,durationMs:Date.now()-f,attempt:d,retried:!1}),j0e(r),p.status===204?void 0:await p.json()}catch(p){if(p instanceof Vi)throw p;if(c=p,this.emitRequestEvent({method:e,path:r,statusCode:0,durationMs:Date.now()-f,attempt:d,retried:d<this.maxRetries,error:c.message}),d<this.maxRetries){let h=Math.min(1e3*2**d,8e3);await G0e(h,s);continue}}}throw c??new Error(`Request failed: ${e} ${r}`)}async get(e,r,n){return this.request("GET",e,{query:r,...n?.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}})}async post(e,r,n){return this.request("POST",e,{body:r,headers:n?.headers})}async put(e,r,n){return this.request("PUT",e,{body:r,headers:n?.headers})}async delete(e,r){return this.request("DELETE",e,{query:r})}async postMultipart(e,r){return this.request("POST",e,{body:r,raw:!0})}async list(e,r){let n=await this.get(e,{limit:r?.limit??100,offset:r?.offset??0,...r?.view?{view:r.view}:{}});return z0e(n)}async search(e,r){let n={};r.query&&(n.query=r.query),r.filter&&(n.filter=r.filter),r.limit!==void 0&&(n.limit=r.limit),r.offset!==void 0&&(n.offset=r.offset),r.view&&(n.view=r.view),r.magicSort&&(n.magicSort=r.magicSort),r.transactionType&&(n.transactionType=r.transactionType),r.multiContactOnly!==void 0&&(n.multiContactOnly=r.multiContactOnly),r.sort?n.sort=r.sort:r.offset!==void 0&&(n.sort={sortBy:["createdAt"],order:"DESC"});let i=await this.post(e,n);return z0e(i)}async listAll(e,r=200){let n=[],i=0,o=!0;for(;o;){let s=await this.list(e,{limit:r,offset:i});if(n.push(...s.data),s.data.length<r)break;i+=1,o=i*r<s.totalElements}return n}}});async function Na(t){let e=await t.get("/api/v1/organization");return Array.isArray(e.data)?e.data[0]:e.data}async function xwt(t){let e=await t.get("/api/v1/me/organizations"),r=e.boundOrganizationResourceId;return{organizations:Array.isArray(e.data)?e.data:[],boundOrganizationResourceId:r===null?"":r}}async function Z0e(t){return(await xwt(t)).organizations}async function X0e(t){return(await t.get("/api/v1/me")).data}var vA=X(()=>{"use strict"});var awe={};So(awe,{collectValue:()=>F9,parseCustomFields:()=>pn,parseJournalEntries:()=>yc,parseJsonArray:()=>Iu,parseJsonObject:()=>L9,parseLineItems:()=>jn,parseMoney:()=>cr,parseNonNegativeInt:()=>it,parseOrderTerms:()=>wA,parsePositiveInt:()=>he,parseRate:()=>as,parseTaxRatePercent:()=>RF,parseTemplateOverrides:()=>Q9,readBodyInput:()=>be,requireFields:()=>Le,splitCsv:()=>Zi,todayLocal:()=>M9});import{readFileSync as owe}from"node:fs";function he(t){let e=String(t).trim(),r=Number.parseInt(e,10);return(!swe.test(e)||!Number.isSafeInteger(r)||r<=0)&&(console.error(ne(`Error: invalid positive integer: ${t}`)),process.exit(1)),r}function it(t){let e=String(t).trim(),r=Number.parseInt(e,10);return(!swe.test(e)||!Number.isSafeInteger(r)||r<0)&&(console.error(ne(`Error: invalid non-negative integer: ${t}`)),process.exit(1)),r}function wA(t){let e=Number.parseInt(t,10);return(!Number.isFinite(e)||![0,7,15,30,45,60].includes(e))&&(console.error(ne(`Error: terms must be one of 0, 7, 15, 30, 45, 60 (got: ${t})`)),process.exit(1)),e}function cr(t){return/^-?\d+(\.\d{1,2})?$/.test(t)||(console.error(ne(`Error: invalid amount: ${t} (max 2 decimal places)`)),process.exit(1)),Math.round(Number(t)*100)/100}function as(t){let e=Number(t);return(!Number.isFinite(e)||e<=0)&&(console.error(ne(`Error: invalid exchange rate: ${t}`)),process.exit(1)),e}function RF(t){let e=String(t).trim(),r=Number(e);return(e===""||!Number.isFinite(r)||r<0||r>100)&&(console.error(ne(`Error: invalid tax rate percentage: ${t} (expected 0-100)`)),process.exit(1)),r}function jn(t){try{let e=JSON.parse(t);if(!Array.isArray(e))throw new Error("Line items must be a JSON array");return e}catch{console.error(ne("Error: --lines must be valid JSON array")),console.error(H(`Example: --lines '[{"name":"Service","quantity":1,"unitPrice":100,"accountResourceId":"..."}]'`)),console.error(H("Tip: pipe the full request body via stdin, or use --input <file>")),process.exit(1)}}function yc(t){try{let e=JSON.parse(t);if(!Array.isArray(e))throw new Error("Entries must be a JSON array");return e}catch{console.error(ne("Error: --entries must be valid JSON array")),console.error(H(`Example: --entries '[{"accountResourceId":"...","amount":100,"type":"DEBIT"},...]'`)),console.error(H("Tip: pipe the full request body via stdin, or use --input <file>")),process.exit(1)}}function pn(t){try{let e=JSON.parse(t);if(!Array.isArray(e))throw new Error("Must be a JSON array");return e}catch{console.error(ne("Error: --custom-fields must be valid JSON array")),console.error(H(`Example: --custom-fields '[{"customFieldName":"PO Number","actualValue":"PO-123"}]'`)),process.exit(1)}}function F9(t,e=[]){return e.push(t),e}function Q9(t){return t.map(e=>{let r=e.indexOf("=");r===-1&&(console.error(ne(`Error: --template-override must be "slotKey=template" (got "${e}")`)),console.error(H("Example: --template-override capsule.title='Loan {{loanReference}}'")),process.exit(1));let n=e.slice(0,r).trim(),i=e.slice(r+1);return n||(console.error(ne("Error: --template-override slotKey must be non-empty (slotKey=template)")),process.exit(1)),{slotKey:n,template:i}})}function L9(t,e="--inputs"){try{let r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("not an object");return r}catch{return console.error(ne(`Error: ${e} must be a valid JSON object`)),process.exit(1),{}}}function be(t){if(t.input){let e;try{e=owe(t.input,"utf-8")}catch{console.error(ne(`Error: cannot read file: ${t.input}`)),process.exit(1)}try{let r=JSON.parse(e);return(typeof r!="object"||r===null||Array.isArray(r))&&(console.error(ne("Error: --input file must contain a JSON object")),process.exit(1)),r}catch{console.error(ne("Error: --input file contains invalid JSON")),process.exit(1)}}if(!process.stdin.isTTY)try{let e=owe(0,"utf-8").trim();if(e){let r=JSON.parse(e);return(typeof r!="object"||r===null||Array.isArray(r))&&(console.error(ne("Error: stdin must contain a JSON object")),process.exit(1)),r}}catch(e){e.message?.includes("JSON")&&(console.error(ne("Error: stdin contains invalid JSON")),process.exit(1))}return null}function Le(t,e){let r=e.filter(n=>t[n.key]===void 0);if(r.length>0){let n=r.map(i=>i.flag).join(", ");console.error(ne(`Error: missing required option(s): ${n}`)),console.error(H("Provide flags, or pipe JSON via stdin, or use --input <file>")),process.exit(1)}}function Zi(t){if(t!==void 0)return t.split(",").map(e=>e.trim()).filter(Boolean)}function Iu(t,e){let r;try{r=JSON.parse(t)}catch{throw new Error(`Invalid JSON for ${e}: ${t.slice(0,80)}`)}if(!Array.isArray(r))throw new Error(`${e} must be a JSON array (got ${typeof r}).`);return r}function M9(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}var swe,_t=X(()=>{"use strict";Oe();swe=/^[+-]?\d+$/});var fwe=b(en=>{"use strict";function cwe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}var lwe;function dwe(t,e,r,n,i){if(i===void 0&&(i=en.PaymentDueTime.End),t===0)return-(n+r*e);var o=Math.pow(1+t,e);return-n*o-r*(1+t*(i===en.PaymentDueTime.Begin?1:0))/t*(o-1)}function U9(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=en.PaymentDueTime.End);var o=t===0,s=Math.pow(1+t,e),a=i===en.PaymentDueTime.Begin?1:0,c=o?1:t;return-(n+r*s)/(o?e:(1+c*a)*(s-1)/c)}function uwe(t,e,r,n,i,o){if(i===void 0&&(i=0),o===void 0&&(o=en.PaymentDueTime.End),e<1)return Number.NaN;if(o===en.PaymentDueTime.Begin&&e===1)return 0;var s=Lwt(t,e,U9(t,r,n,i,o),n,o)*t;return o===en.PaymentDueTime.Begin&&e>1&&(s/=1+t),s}function P9(t,e){return e.reduce((function(r,n,i){return r+n/Math.pow(1+t,i)}),0)}function Lwt(t,e,r,n,i){return dwe(t,e-1,r,n,i)}function Mwt(t,e,r,n,i,o){var s=o===en.PaymentDueTime.Begin?1:0,a=Math.pow(t+1,e),c=Math.pow(t+1,e-1);return(i+a*n+r*(a-1)*(t*s+1)/t)/(e*c*n-r*(a-1)*(t*s+1)/Math.pow(t,2)+e*r*c*(t*s+1)/t+r*(a-1)*s/t)}function Pwt(t,e,r){for(var n=r+1,i=t[0],o=1;o<t.length;o++)i+=t[o]/Math.pow(n,(e[o]-e[0])/365);return i}function Uwt(t,e,r){for(var n=r+1,i=0,o=1;o<t.length;o++){var s=(e[o]-e[0])/365;i-=s*t[o]/Math.pow(n,s+1)}return i}Object.defineProperty(en,"__esModule",{value:!0}),en.PaymentDueTime=void 0,(lwe=en.PaymentDueTime||(en.PaymentDueTime={})).Begin="begin",lwe.End="end",en.fv=dwe,en.ipmt=uwe,en.irr=function(t,e,r,n){e===void 0&&(e=.1),r===void 0&&(r=1e-6),n===void 0&&(n=100);for(var i=[],o=!1,s=!1,a=0;a<t.length;a++)i[a]=a===0?0:i[a-1]+365,t[a]>0&&(o=!0),t[a]<0&&(s=!0);if(!o||!s)return Number.NaN;var c=e,u=0,d=0,f=0,p=0,h=!0;do u=c-(f=Pwt(t,i,c))/Uwt(t,i,c),d=Math.abs(u-c),c=u,h=d>r&&Math.abs(f)>r;while(h&&++p<n);return h?Number.NaN:c},en.mirr=function(t,e,r){for(var n,i=!1,o=!1,s=(function(d,f){var p=typeof Symbol<"u"&&d[Symbol.iterator]||d["@@iterator"];if(p)return(p=p.call(d)).next.bind(p);if(Array.isArray(d)||(p=(function(m,A){if(m){if(typeof m=="string")return cwe(m,A);var g=Object.prototype.toString.call(m).slice(8,-1);return g==="Object"&&m.constructor&&(g=m.constructor.name),g==="Map"||g==="Set"?Array.from(m):g==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(g)?cwe(m,A):void 0}})(d))){p&&(d=p);var h=0;return function(){return h>=d.length?{done:!0}:{done:!1,value:d[h++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
197
197
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})(t);!(n=s()).done;){var a=n.value;a>0&&(i=!0),a<0&&(o=!0)}if(!i||!o)return Number.NaN;var c=Math.abs(P9(r,t.map((function(d){return d>0?d:0})))),u=Math.abs(P9(e,t.map((function(d){return d<0?d:0}))));return Math.pow(c/u,1/(t.length-1))*(1+r)-1},en.nper=function(t,e,r,n,i){if(n===void 0&&(n=0),i===void 0&&(i=en.PaymentDueTime.End),t===0)return-(n+r)/e;var o=e*(1+t*(i===en.PaymentDueTime.Begin?1:0))/t;return Math.log((-n+o)/(r+o))/Math.log(1+t)},en.npv=P9,en.pmt=U9,en.ppmt=function(t,e,r,n,i,o){return i===void 0&&(i=0),o===void 0&&(o=en.PaymentDueTime.End),U9(t,r,n,i,o)-uwe(t,e,r,n,i,o)},en.pv=function(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=en.PaymentDueTime.End);var o=i===en.PaymentDueTime.Begin?1:0,s=t===0,a=Math.pow(1+t,e);return-(n+r*(s?e:(1+t*o)*(a-1)/t))/a},en.rate=function(t,e,r,n,i,o,s,a){i===void 0&&(i=en.PaymentDueTime.End),o===void 0&&(o=.1),s===void 0&&(s=1e-6),a===void 0&&(a=100);for(var c=o,u=0,d=!1;u<a&&!d;){var f=c-Mwt(c,t,e,r,n,i);d=Math.abs(f-c)<s,u++,c=f}return d?c:Number.NaN}});var Awe=b(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});function $wt(t,e){if(t){if(typeof t=="string")return pwe(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return pwe(t,e)}}function pwe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function qwt(t,e){var r=typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=$wt(t))||e&&t&&typeof t.length=="number"){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
198
198
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}tn.PaymentDueTime=void 0;(function(t){t.Begin="begin",t.End="end"})(tn.PaymentDueTime||(tn.PaymentDueTime={}));function hwe(t,e,r,n,i){i===void 0&&(i=tn.PaymentDueTime.End);var o=t===0;if(o)return-(n+r*e);var s=Math.pow(1+t,e),a=i===tn.PaymentDueTime.Begin?1:0;return-n*s-r*(1+t*a)/t*(s-1)}function q9(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=tn.PaymentDueTime.End);var o=t===0,s=Math.pow(1+t,e),a=i===tn.PaymentDueTime.Begin?1:0,c=o?1:t,u=o?e:(1+c*a)*(s-1)/c;return-(n+r*s)/u}function jwt(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=tn.PaymentDueTime.End);var o=t===0;if(o)return-(n+r)/e;var s=i===tn.PaymentDueTime.Begin?1:0,a=e*(1+t*s)/t;return Math.log((-n+a)/(r+a))/Math.log(1+t)}function mwe(t,e,r,n,i,o){if(i===void 0&&(i=0),o===void 0&&(o=tn.PaymentDueTime.End),e<1)return Number.NaN;if(o===tn.PaymentDueTime.Begin&&e===1)return 0;var s=q9(t,r,n,i,o),a=Vwt(t,e,s,n,o)*t;return o===tn.PaymentDueTime.Begin&&e>1&&(a=a/(1+t)),a}function Ywt(t,e,r,n,i,o){i===void 0&&(i=0),o===void 0&&(o=tn.PaymentDueTime.End);var s=q9(t,r,n,i,o);return s-mwe(t,e,r,n,i,o)}function Hwt(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=tn.PaymentDueTime.End);var o=i===tn.PaymentDueTime.Begin?1:0,s=t===0,a=Math.pow(1+t,e),c=s?e:(1+t*o)*(a-1)/t;return-(n+r*c)/a}function zwt(t,e,r,n,i,o,s,a){i===void 0&&(i=tn.PaymentDueTime.End),o===void 0&&(o=.1),s===void 0&&(s=1e-6),a===void 0&&(a=100);for(var c=o,u=0,d=!1;u<a&&!d;){var f=c-Wwt(c,t,e,r,n,i),p=Math.abs(f-c);d=p<s,u++,c=f}return d?c:Number.NaN}function Gwt(t,e,r,n){e===void 0&&(e=.1),r===void 0&&(r=1e-6),n===void 0&&(n=100);for(var i=[],o=!1,s=!1,a=0;a<t.length;a++)i[a]=a===0?0:i[a-1]+365,t[a]>0&&(o=!0),t[a]<0&&(s=!0);if(!o||!s)return Number.NaN;var c=e,u=0,d=0,f=0,p=0,h=!0;do f=Zwt(t,i,c),u=c-f/Xwt(t,i,c),d=Math.abs(u-c),c=u,h=d>r&&Math.abs(f)>r;while(h&&++p<n);return h?Number.NaN:c}function $9(t,e){return e.reduce(function(r,n,i){return r+n/Math.pow(1+t,i)},0)}function Jwt(t,e,r){for(var n=!1,i=!1,o=qwt(t),s;!(s=o()).done;){var a=s.value;a>0&&(n=!0),a<0&&(i=!0)}if(!n||!i)return Number.NaN;var c=Math.abs($9(r,t.map(function(d){return d>0?d:0}))),u=Math.abs($9(e,t.map(function(d){return d<0?d:0})));return Math.pow(c/u,1/(t.length-1))*(1+r)-1}function Vwt(t,e,r,n,i){return hwe(t,e-1,r,n,i)}function Wwt(t,e,r,n,i,o){var s=o===tn.PaymentDueTime.Begin?1:0,a=Math.pow(t+1,e),c=Math.pow(t+1,e-1),u=i+a*n+r*(a-1)*(t*s+1)/t,d=e*c*n-r*(a-1)*(t*s+1)/Math.pow(t,2)+e*r*c*(t*s+1)/t+r*(a-1)*s/t;return u/d}function Zwt(t,e,r){for(var n=r+1,i=t[0],o=1;o<t.length;o++)i+=t[o]/Math.pow(n,(e[o]-e[0])/365);return i}function Xwt(t,e,r){for(var n=r+1,i=0,o=1;o<t.length;o++){var s=(e[o]-e[0])/365;i-=s*t[o]/Math.pow(n,s+1)}return i}tn.fv=hwe;tn.ipmt=mwe;tn.irr=Gwt;tn.mirr=Jwt;tn.nper=jwt;tn.npv=$9;tn.pmt=q9;tn.ppmt=Ywt;tn.pv=Hwt;tn.rate=zwt});var Ww=b((uqr,j9)=>{"use strict";process.env.NODE_ENV==="production"?j9.exports=fwe():j9.exports=Awe()});function re(t){return Math.round(t*100)/100}function po(t,e){let r=t.split("-");if(r.length!==3)throw new Error(`Invalid date format: ${t}`);let[n,i,o]=r.map(Number);if(!Number.isFinite(n)||!Number.isFinite(i)||!Number.isFinite(o))throw new Error(`Invalid date: ${t}`);let s=i-1+e,a=n+Math.floor(s/12),c=(s%12+12)%12,u=new Date(Date.UTC(a,c+1,0)).getUTCDate(),d=Math.min(o,u);return`${String(a).padStart(4,"0")}-${String(c+1).padStart(2,"0")}-${String(d).padStart(2,"0")}`}var Fs=X(()=>{"use strict"});var No,sp=X(()=>{"use strict";No=class extends Error{constructor(e){super(e),this.name="ValidationError"}}});function hn(t,e){if(!Number.isFinite(t)||t<=0)throw new $t(`${e} must be a positive number (got ${t})`)}function vu(t,e){if(!Number.isFinite(t)||t<0)throw new $t(`${e} must be zero or positive (got ${t})`)}function Mi(t,e){if(!Number.isInteger(t)||t<1)throw new $t(`${e} must be a positive integer (got ${t})`)}function xF(t,e){if(t>=e)throw new $t(`Salvage value (${t}) must be less than cost (${e})`)}function ki(t){if(!t)return;if(!/^\d{4}-\d{2}-\d{2}$/.test(t))throw new $t(`Date must be YYYY-MM-DD format (got "${t}")`);let e=new Date(t+"T00:00:00");if(isNaN(e.getTime()))throw new $t(`Invalid date: "${t}"`)}function ap(t,e="Rate"){vu(t,e),t>100&&process.stderr.write(`Warning: ${e} is ${t}% \u2014 are you sure this isn't a decimal? (e.g. 6 for 6%, not 0.06)
199
199
  `)}function gwe(t){if(!t||typeof t!="object")throw new $t("Input must be a JSON object with bankRecords and transactions arrays");let e=t;if(!Array.isArray(e.bankRecords))throw new $t("bankRecords must be an array");if(!Array.isArray(e.transactions))throw new $t("transactions must be an array");if(e.bankRecords.length===0)throw new $t("bankRecords array is empty \u2014 nothing to match");if(e.transactions.length===0)throw new $t("transactions array is empty \u2014 nothing to match");for(let i=0;i<e.bankRecords.length;i++){let o=e.bankRecords[i];if(!o.id||typeof o.id!="string")throw new $t(`bankRecords[${i}]: id is required (string)`);if(typeof o.amount!="number"||!Number.isFinite(o.amount))throw new $t(`bankRecords[${i}]: amount must be a finite number`);if(o.amount===0)throw new $t(`bankRecords[${i}]: amount must not be zero`);if(!o.date||typeof o.date!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(o.date))throw new $t(`bankRecords[${i}]: date must be YYYY-MM-DD format`)}for(let i=0;i<e.transactions.length;i++){let o=e.transactions[i];if(!o.id||typeof o.id!="string")throw new $t(`transactions[${i}]: id is required (string)`);if(o.direction!=="PAYIN"&&o.direction!=="PAYOUT")throw new $t(`transactions[${i}]: direction must be 'PAYIN' or 'PAYOUT'`);if(typeof o.amount!="number"||!Number.isFinite(o.amount)||o.amount<=0)throw new $t(`transactions[${i}]: amount must be a positive number`);if(!o.date||typeof o.date!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(o.date))throw new $t(`transactions[${i}]: date must be YYYY-MM-DD format`);if(o.crossCurrency&&(!o.currency||typeof o.currency!="string"))throw new $t(`transactions[${i}]: crossCurrency is true but currency is missing`)}let r=e.options;if(r){if(r.tolerance!==void 0&&(typeof r.tolerance!="number"||!Number.isFinite(r.tolerance)||r.tolerance<0))throw new $t("options.tolerance must be a non-negative number");if(r.dateWindowDays!==void 0&&(typeof r.dateWindowDays!="number"||!Number.isInteger(r.dateWindowDays)||r.dateWindowDays<0))throw new $t("options.dateWindowDays must be a non-negative integer");if(r.maxGroupSize!==void 0&&(typeof r.maxGroupSize!="number"||!Number.isInteger(r.maxGroupSize)||r.maxGroupSize<2||r.maxGroupSize>10))throw new $t("options.maxGroupSize must be an integer between 2 and 10")}let n=r?.exchangeRates;for(let i=0;i<e.transactions.length;i++){let o=e.transactions[i];if(o.crossCurrency&&o.currency&&(!n||typeof n[o.currency]!="number"))throw new $t(`transactions[${i}]: crossCurrency is true with currency "${o.currency}" but no exchange rate provided in options.exchangeRates`)}return t}var $t,cs=X(()=>{"use strict";sp();$t=class extends No{constructor(e){super(e),this.name="CalcValidationError"}}});function zr(t,e,r,n){return{step:t,action:"journal",description:e,date:r,lines:n}}function ywe(t,e,r,n){return{step:t,action:"bill",description:e,date:r,lines:n}}function Ewe(t,e,r,n){return{step:t,action:"invoice",description:e,date:r,lines:n}}function _A(t,e,r,n){return{step:t,action:"cash-out",description:e,date:r,lines:n}}function TF(t,e,r,n){return{step:t,action:"cash-in",description:e,date:r,lines:n}}function bwe(t,e,r=null){return{step:t,action:"fixed-asset",description:e,date:r,lines:[]}}function Cwe(t,e,r=null){return{step:t,action:"note",description:e,date:r,lines:[]}}function mi(t,e){let r=t.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0});return e?`${e} ${r}`:r}function Ue(t,e){let r=t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});return e?`${e} ${r}`:r}var Oa=X(()=>{"use strict"});function BF(t){let{principal:e,annualRate:r,termMonths:n,startDate:i,currency:o}=t;hn(e,"Principal"),ap(r,"Annual rate"),Mi(n,"Term (months)"),ki(i);let s=r/100/12,a=re(-(0,Iwe.pmt)(s,n,e)),c=[],u=e,d=0,f=0;for(let h=1;h<=n;h++){let m=re(u),A=h===n,g,y,C;A?(g=re(m*s),y=m,C=re(y+g)):(g=re(m*s),y=re(a-g),C=a),u=re(m-y),d=re(d+g),f=re(f+y);let E=i?po(i,h):null,I={description:`Loan payment \u2014 Month ${h} of ${n}`,lines:[{account:"Loan Payable",debit:y,credit:0},{account:"Interest Expense",debit:g,credit:0},{account:"Cash / Bank Account",debit:0,credit:C}]};c.push({period:h,date:E,openingBalance:m,payment:C,interest:g,principal:y,closingBalance:u,journal:I})}let p=null;if(i){let h=[TF(1,"Record loan proceeds received from bank",i,[{account:"Cash / Bank Account",debit:e,credit:0},{account:"Loan Payable",debit:0,credit:e}]),...c.map((g,y)=>zr(y+2,g.journal.description,g.date,g.journal.lines))],m=o??void 0,A=["Loan Amortization Workings",`Principal: ${Ue(e,m)} | Rate: ${r}% p.a. (${re(s*100)}% monthly)`,`Term: ${n} months | Monthly payment: ${Ue(a,m)}`,`Total payments: ${Ue(re(d+f),m)} | Total interest: ${Ue(d,m)}`,"Method: PMT formula, constant payment amortization","Rounding: 2dp per period, final period closes balance to $0.00"].join(`
@@ -277,7 +277,7 @@ Be more specific, or use the full name.`)}if(o.length>0){let a=o.map(c=>` ${c.i
277
277
  ${a}`)}throw new Error(`No bank account matching "${t}".
278
278
 
279
279
  Available accounts:
280
- ${s}`)}var TPt,SM=X(()=>{"use strict";Lp();AC();TPt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});import{readFileSync as kPt}from"node:fs";import{createHash as NPt}from"node:crypto";import{extname as OPt}from"node:path";async function RM(t){let{plan:e,client:r,bankAccountId:n,onProgress:i}=t,o=e.folders.flatMap(c=>c.files.filter(u=>gQ(u.documentType))),s=[],a=new Set;for(let c=0;c<o.length;c++){let u=o[c],d=u.documentType,f;try{let p=u.absolutePath;u.encrypted&&u.filePassword&&(f=w_(u.absolutePath,u.filePassword),p=f);let h=kPt(p),m=`${NPt("sha256").update(h).digest("hex")}:${d}`;if(a.has(m)){let E={file:`${u.folder}/${u.filename}`,type:d,status:"skipped",error:"Duplicate of an already-uploaded file (identical content + type)"};s.push(E),i?.(E,c,o.length);continue}a.add(m);let A=OPt(u.filename).toLowerCase();if(!I_.has(A))throw new Error(`Unsupported file extension "${A}" \u2014 expected one of: ${[...I_].join(", ")}`);let g=new Blob([h],{type:BA(A)}),y;d==="BANK_STATEMENT"?y=(await mC(r,{businessTransactionType:d,accountResourceId:n,sourceFile:g,sourceFileName:u.filename})).data:y=(await Ou(r,{businessTransactionType:d,sourceFile:g,sourceFileName:u.filename,...u.merged?{uploadMode:"MERGED"}:{}})).data;let C={file:`${u.folder}/${u.filename}`,type:d,status:"uploaded",response:y};s.push(C),i?.(C,c,o.length)}catch(p){let h=p instanceof Error?p.message:String(p),m={file:`${u.folder}/${u.filename}`,type:d,status:"failed",error:h};s.push(m),i?.(m,c,o.length)}finally{f&&ub(f)}}return{total:o.length,success:s.filter(c=>c.status==="uploaded").length,failed:s.filter(c=>c.status==="failed").length,results:s}}var V7=X(()=>{"use strict";xD();Lp();D_();gp();SM()});var gC=X(()=>{"use strict";R9();zw();Vw()});var xM,TD,TM=X(()=>{"use strict";xM=t=>typeof t!="string"||t.trim()==="",TD=t=>typeof t=="string"&&t.trim()!==""});function aFe(t,e){if(t==="create_sale_order"||t==="create_purchase_order"){let r=e.documentType;return typeof r=="string"&&W7.includes(r)?r:void 0}return LPt[t]}async function Z7(t,e){let r;try{r=await t.get("/api/v1/references/next",{type:e},{timeoutMs:1e4})}catch(n){let i=n instanceof Error?n.message:String(n);throw new yC(`next reference: ${i}. Nothing was created.`,{cause:n})}if(xM(r?.data?.reference))throw new yC("next reference: upstream returned no reference. Nothing was created.");return r}async function Mp(t,e,r,n){if(!xM(r))return r.trim();if(n!==!0)return;let{data:i}=await Z7(t,e);return i.reference}async function go(t,e,r,n,{optional:i=!1}={}){let{autoReference:o,...s}=r,a=s.reference,c=await Mp(t,e,a,n);if(c!==void 0)return{...s,reference:c};if(!i)throw new yC("reference is required: supply one, or set autoReference: true to take the next number from the organization's own series. Nothing was created.");return xM(a)&&delete s.reference,s}async function og(t,e,r,n){let i=await Mp(t,e,r,n);if(i===void 0)throw new yC("reference is required: supply one, or set autoReference: true to take the next number from the organization's own series. Nothing was created.");return i}var W7,yC,LPt,Fu=X(()=>{"use strict";TM();W7=["SALE","SALE_CREDIT_NOTE","PURCHASE","PURCHASE_CREDIT_NOTE","FIXED_ASSET","JOURNAL_MANUAL","SALE_QUOTE","SALE_ORDER","PURCHASE_REQUEST","PURCHASE_ORDER","CLAIM"],yC=class extends Error{noWrite=!0;constructor(e,r){super(e,r),this.name="ReferenceUnavailableError"}},LPt={create_invoice:"SALE",create_bill:"PURCHASE",create_journal:"JOURNAL_MANUAL",create_customer_credit_note:"SALE_CREDIT_NOTE",create_supplier_credit_note:"PURCHASE_CREDIT_NOTE",create_claim:"CLAIM",convert_sale_order_to_invoice:"SALE",convert_purchase_order_to_bill:"PURCHASE"}});function X7(t){let e=(process.env[t]??"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function cFe(t){let e=(process.env[t]??"").trim().toLowerCase();return!(e==="0"||e==="false"||e==="no")}var K7=X(()=>{"use strict"});function BD(){return cFe(MPt)}function dFe(t,e=BD()){if(e)for(let r of t)r.readOnly||r.group==="jots"||r.group==="memory"||r.description.includes(lFe)||(r.description=`${r.description} ${lFe}`)}var MPt,uFe,lFe,BM=X(()=>{"use strict";K7();MPt="JAZ_JOTS_NUDGES";uFe="If you decide not to retry, record the decision with the jot tool (kind: RECOVERY).",lFe="If this action involved a judgment call, record it (jot field or jot tool)."});var kM,NM,OM,FM,QM,fFe,LM,pFe,EC=X(()=>{"use strict";kM="CRITICAL = money out (PAY), data destroyed (DELETE), external send or period lock (FINALIZE), or a recovery that re-drove a write; HIGH = a withheld write, or RISK/MATCH backed by a write; LOW = a deviation with no write; MEDIUM = the rest.",NM="HIGH = clear rule or precedent applied; MEDIUM = pattern-based inference; LOW = a guess a reviewer should check.",OM="NOTE is the server fallback for a missing kind; never declare it.",FM="Use a canonical job name when one fits: month-end-close, quarter-end-close, year-end-close, bank-recon, gst-vat-filing, payment-run, credit-control, supplier-recon, audit-prep, fa-review, document-collection, statutory-filing; else short kebab-case.",QM="An ack with duplicateCount > 0 means this judgment is already recorded: do not re-jot identical calls; recall first on repeated workflows.",fFe="Style: tight, factual, plain punctuation; never repeat content across fields (refs carry the record, why carries the basis); detail belongs only in why/ruledOut/frame where it earns its place.",LM="For HIGH or CRITICAL calls, or when the why matters, use the jot tool instead.",pFe="Judgment journal: when a real judgment call precedes a write, record it with `jot` after the write succeeds; when you deliberately hold a write, record that decision immediately (a withheld write is tier HIGH, not CRITICAL). Check `recall` for prior judgments before repeating one (jots namespace)."});function hFe(t,e){if(t.length<=e)return t;let r=t.slice(0,e-1);return`${r.replace(/\s+\S*$/,"")||r}\u2026`}function MM(t,e){let r=t.params?.[e]?.description?.trim();return r?`. ${hFe(r,200)}`:""}function mFe(t,e){return`Validation failed for ${t.name}: ${e.join("; ")}`}function AFe(t,e){let r=[];for(let n of t.required){let i=e[n];if(i==null){r.push(`Missing required field: ${n}${MM(t,n)}`);continue}typeof i=="string"&&i.trim()===""&&r.push(`Required field "${n}" is empty${MM(t,n)}`),t.readOnly&&Array.isArray(i)&&i.length===0&&r.push(`Required field "${n}" is an empty array${MM(t,n)}`)}if(!t.readOnly)for(let[n,i]of Object.entries(e)){if(i==null)continue;let o=t.params?.[n];if(!o)continue;let s=PPt(n,i,o);s&&r.push(`${s}${MM(t,n)}`),o.enum&&typeof i=="string"&&(o.enum.includes(i)||r.push(`Field "${n}" value "${hFe(i,80)}" not in allowed values: ${o.enum.join(", ")}`))}return{valid:r.length===0,errors:r}}function PPt(t,e,r){switch(r.type){case"string":if(typeof e!="string")return`Field "${t}" expected string, got ${typeof e}`;break;case"number":if(typeof e!="number"||!Number.isFinite(e))return`Field "${t}" expected finite number, got ${typeof e=="number"?"non-finite":typeof e}`;break;case"boolean":if(typeof e!="boolean")return`Field "${t}" expected boolean, got ${typeof e}`;break;case"array":if(!Array.isArray(e))return`Field "${t}" expected array, got ${typeof e}`;break;case"object":if(typeof e!="object"||Array.isArray(e))return`Field "${t}" expected object, got ${Array.isArray(e)?"array":typeof e}`;break}return null}function $Pt(t,e){let r=tZ.get(t);if(r&&e.includes(r))return r;let n=t.toLowerCase();return e.find(i=>i!==t&&i.toLowerCase()===n)}function eZ(t,e,r,n,i){if(!e||!t||typeof t!="object"||Array.isArray(t))return;let o=Object.keys(e);for(let[s,a]of Object.entries(t)){if(a==null)continue;let c=e[s];if(!c){let u=qPt.get(n.name)?.get(s);if(u){i.add(`${n.name}: "${r}${s}" belongs to ${u}, not this tool. ${n.name} is the flat variant and takes one line per row via "totalAmount", "itemDescription" and the row-level account. Nothing on this call reads "${r}${s}", so the amounts inside it did not reach the record \u2014 a row with no "totalAmount" is written at zero. Re-send through ${u}, or flatten the row, and verify the saved amount.`);continue}let d=$Pt(s,o);d&&(UPt.has(n.name)?i.add(`${n.name}: "${r}${s}" is the read-side name and is not declared on this tool, but the endpoint accepts it as an alias for "${r}${d}". Do not retry solely because of this warning \u2014 read the saved record to confirm the call's outcome. Prefer "${r}${d}" on new calls; it is the documented name.`):i.add(`${n.name}: "${r}${s}" is not a parameter of this tool \u2014 did you mean "${r}${d}"? Nothing on this call reads the name you sent, so that value did not reach the declared field. Read the saved record back: if this call created one, UPDATE it under the declared name rather than creating a second.`));continue}if(c.type==="array"&&Array.isArray(a))for(let u of a)eZ(u,c.items?.properties,`${r}${s}[].`,n,i);else c.type==="object"&&eZ(a,c.properties,`${r}${s}.`,n,i)}}function gFe(t,e){if(t.readOnly)return[];let r=new Set;return eZ(e,t.params,"",t,r),[...r]}function yFe(t,e){if(e.length===0||!t||typeof t!="object"||Array.isArray(t))return t;let{_warnings:r,...n}=t,i=Array.isArray(r)?r:r==null?[]:[r];return{_warnings:[...e,...i],...n}}var tZ,UPt,qPt,rZ=X(()=>{"use strict";tZ=new Map([["organizationAccountResourceId","accountResourceId"]]),UPt=new Set(["create_invoice","update_invoice","finalize_invoice","create_bill","update_bill","finalize_bill","create_customer_credit_note","update_customer_credit_note","finalize_customer_credit_note","create_supplier_credit_note","update_supplier_credit_note","finalize_supplier_credit_note","create_sale_order","update_sale_order","create_purchase_order","update_purchase_order"]);qPt=new Map([["bulk_upsert_invoices",new Map([["lineItems","bulk_upsert_invoice_line_items"]])],["bulk_upsert_bills",new Map([["lineItems","bulk_upsert_bill_line_items"]])]])});function bFe(t){return EFe[t]??EFe.jaz}var EFe,CFe=X(()=>{"use strict";EFe={jaz:{displayName:"Jaz",supportEmail:"support@jaz.ai",domain:"jaz.ai",agentInboxDomain:"jaz.email",dashboardUrl:"https://app.jaz.ai"},juan:{displayName:"Juan",supportEmail:"help@juan.ac",domain:"juan.ac",agentInboxDomain:"sendjuan.com",dashboardUrl:"https://app.juan.ac"}}});import{readFileSync as jPt}from"node:fs";import{dirname as YPt,join as HPt}from"node:path";import{fileURLToPath as zPt}from"node:url";function _Fe(t,e,{dashboardUrl:r,orgResourceId:n}){let i=wFe(),o=i.screenByKey.get(t);if(o){if(e)throw new Error(`Destination '${t}' is a screen, not a record view \u2014 omit resourceId. To open a specific record, use a "<resource>.modal.view-*" destination instead.`);return{url:IFe(`${r}${o.path}`,n),kind:"screen",label:o.label}}let s=i.modalByKey.get(t);if(s){if(s.requiresId&&!e)throw new Error(`Destination '${t}' opens a specific record \u2014 pass the record's resourceId. For a create/blank modal, use a "new-*"/"create-*" destination instead.`);let u=s.requiresId?s.urlTemplate.replace(GPt,encodeURIComponent(e)):s.urlTemplate;return{url:IFe(`${r}${s.mountPath}${u}`,n),kind:"modal",label:s.label}}let a=VPt(i,t),c=a.length?` Did you mean: ${a.join(", ")}?`:"";throw new Error(`Unknown dashboard destination '${t}'.${c} Call navigate with no destination to discover valid keys.`)}function DFe({query:t,resource:e,kind:r}){let{manifest:n}=wFe(),i=t?.trim().toLowerCase(),o=[...r==="modal"?[]:n.screens.filter(c=>!e||XPt(c.path)===e).map(c=>({key:c.key,label:c.label,kind:"screen"})),...r==="screen"?[]:n.modals.filter(c=>!e||c.resource===e).map(c=>({key:c.key,label:c.label,kind:"modal"}))],s=i?ZPt(i):[],a=i?o.filter(c=>s.some(u=>c.key.toLowerCase().includes(u)||c.label.toLowerCase().includes(u))):o;return{results:a.slice(0,vFe),total:a.length,truncated:a.length>vFe}}var GPt,JPt,nZ,wFe,VPt,IFe,vFe,WPt,ZPt,XPt,SFe=X(()=>{"use strict";GPt="{id}",JPt=YPt(zPt(import.meta.url)),nZ=null,wFe=()=>{if(!nZ){let t=JSON.parse(jPt(HPt(JPt,"dashboard-routes-manifest.json"),"utf8"));nZ={manifest:t,screenByKey:new Map(t.screens.map(e=>[e.key,e])),modalByKey:new Map(t.modals.map(e=>[e.key,e]))}}return nZ},VPt=(t,e,r=5)=>{let n=e.toLowerCase(),i=[],o=[...t.screenByKey.keys(),...t.modalByKey.keys()];for(let s of o)if(s.toLowerCase().includes(n)&&(i.push(s),i.length>=r))break;return i},IFe=(t,e)=>e?`${t}${t.includes("?")?"&":"?"}org=${encodeURIComponent(e)}`:t;vFe=60,WPt=[["credit note","credit"],["invoice","sale"],["bill","purchase"]],ZPt=t=>{let e=[t];for(let[r,n]of WPt)t.includes(r)&&e.push(t.split(r).join(n));return e},XPt=t=>t.split("/")[1]??""});function oZ(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t.data;return e&&typeof e=="object"&&!Array.isArray(e)?e:t}function Oc(t,e,r){let n=oZ(t);return{outcome:(typeof n.status=="string"?KPt[n.status]:void 0)??(r?"DELETED":e2t),...n,resourceId:e}}function Qu(t,e,r){switch(r){case"DELETED":return`${t} ${e} deleted.`;case"VOIDED":return`${t} ${e} voided \u2014 it is still on the books, with status VOID.`;default:return`${t} ${e}: deleted if it was a draft, voided and kept if it was active. Re-read it to see which, or pass --force to hard-delete either.`}}var iZ,KPt,e2t,sg=X(()=>{"use strict";iZ={force:"Hard-delete instead of voiding.",internalNotes:"Note recorded with the void."},KPt={VOID:"VOIDED",SUCCEEDED:"DELETED"},e2t="DELETED_IF_DRAFT_VOIDED_IF_ACTIVE"});var bC,ag,cg,RFe,t2t,r2t,PM,tf,kD=X(()=>{"use strict";bC=["ORGANIZATION","USER_MANAGEMENT","BILLING","ACCOUNTING","SALES","PURCHASES","REPORTS","FIXED_ASSET"],ag=["ADMIN","PREPARER","MEMBER","NO_ACCESS"],cg=["ADMIN","CUSTOM_USER"],RFe=["trial-balance","balance-sheet","profit-and-loss","general-ledger","cashflow","cash-balance","ar-report","ap-report","sales-summary","sales-payments-summary","purchase-summary","purchase-payments-summary","customer-revenue-summary","product-sales-summary","periodic-revenue-summary","supplier-expense-summary","product-purchase-summary","periodic-expense-summary","credit-note-summary","sales-cost-margin","sale-inventory-movement","purchase-inventory-movement","analysis-anomalous-invoices","analysis-anomalous-bills","analysis-cashflow-anomalies","analysis-gl-journal-audit","analysis-receivables-customer-risk","analysis-cash-expense-health","analysis-exchange-rate-audit","statement-of-account-export","tax-ledger","equity-movement","bank-closing-balance","bank-reconciliation-summary","bank-reconciliation-details","fixed-assets-register","fixed-assets-reconciliation-summary","journal-summary"],t2t=["MAGIC_MATCH","MAGIC_RECONCILE_WITH_CASH_TRANSFER","MAGIC_RECONCILE_WITH_BANK_RULE","MAGIC_QUICK_RECONCILE","MAGIC_RECONCILE_WITH_CASH_IN_OUT"],r2t="RECOMMENDATIONS",PM=[...t2t,r2t],tf=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","SALE_PAYMENT","PURCHASE_PAYMENT","BATCH_PAYMENT","CONTACT","ITEM","CAPSULE","SCHEDULED_TRANSACTION","JOURNAL","BANK_RECORD","CASHFLOW_TRANSACTION","FIXED_ASSET","CHART_OF_ACCOUNT","TAX_PROFILE"]});var xFe,TFe,BFe,kFe,NFe,UM,OFe,FFe,QFe,$M,LFe,sZ,MFe,qM,PFe,UFe,$Fe,qFe,jFe,YFe,HFe,zFe,GFe,ND,jM,JFe,VFe,WFe,aZ,yGr,ZFe,XFe,ca=X(()=>{"use strict";xFe=["DRAFT","UNPAID","PARTIALLY_PAID","PAID","VOID"],TFe=["DRAFT","UNAPPLIED","PARTIALLY_APPLIED","APPLIED","VOID"],BFe=["DRAFT","ACTIVE","VOID"],kFe=["JOURNAL_MANUAL","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASHFLOW","JOURNAL_CASH_TRANSFER","JOURNAL_TRANSFER_BALANCE","JOURNAL_CASHFLOW_BANK_RECON","JOURNAL_CASHFLOW_ADJUSTMENT"],NFe=["CASH_TRANSFER","DIRECT_CASH_IN","DIRECT_CASH_OUT"],UM=["ACTIVE","INACTIVE"],OFe=["ACTIVE","INACTIVE"],FFe=["ACTIVE","INACTIVE"],QFe=["INVENTORY","NON_INVENTORY"],$M=["PENDING","APPROVED"],LFe=["RECONCILED","UNRECONCILED","ARCHIVED","POSSIBLE_DUPLICATE"],sZ=["PAYIN","PAYOUT"],MFe=["ALL_CASHFLOWS","CASH_ENTRIES"],qM=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE","JOURNAL_MANUAL","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASHFLOW","JOURNAL_CASH_TRANSFER","JOURNAL_CASHFLOW_BANK_RECON","JOURNAL_CASHFLOW_ADJUSTMENT","PAYMENT_SALE","PAYMENT_PURCHASE","PAYMENT_SALE_CREDIT_NOTE","PAYMENT_PURCHASE_CREDIT_NOTE","BATCH_SALE","BATCH_PURCHASE","FIXED_ASSETS"],PFe=["ACTIVE","UNPAID","PARTIALLY_PAID","PAID","VOID","DRAFT","UNAPPLIED","PARTIALLY_APPLIED","APPLIED"],UFe=["ACTIVE","ONGOING","COMPLETED","DRAFT","DISPOSED","SOLD","DISCARDED","CLOSED_OUT"],$Fe=["TANGIBLE","INTANGIBLE"],qFe=["ACTIVE","INACTIVE"],jFe=["ACTIVE","CANCELLED","INACTIVE"],YFe=["ONE_TIME","DAILY","WEEKLY","MONTHLY","QUARTERLY","YEARLY"],HFe=["DRAFT","CREATED","ACCEPTED","CONFIRMED","VOID"],zFe=["DRAFT","ACTIVE","ACCEPTED","CONFIRMED","VOID"],GFe=["Asset","Liability","Equity","Revenue","Expense"],ND={Asset:["Bank Accounts","Cash","Current Asset","Non-current Asset","Fixed Asset","Inventory","Investment","Goodwill"],Liability:["Current Liability","Non-current Liability"],Equity:["Shareholders Equity"],Revenue:["Operating Revenue","Other Revenue","Discontinued Income","Financing Income","Investing Income"],Expense:["Direct Costs","Operating Expense","Other Expense","Finance Cost","Investing Expense","Income Tax Expense","Discontinued Expense"]},jM=[...ND.Asset,...ND.Liability,...ND.Equity,...ND.Revenue,...ND.Expense],JFe=["TEXT","NUMBER","BOOLEAN","DATE","LINK"],VFe=["ADMIN","CUSTOM_USER"],WFe=["ACTIVE","INACTIVE"],aZ=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"],yGr=aZ.filter(t=>t!=="CUSTOM"),ZFe=["QUEUED","DISPATCHING","PROCESSING","SUCCESS","FAILED","PARTIAL_SUCCESS"],XFe=["CASH","CREDIT_CARD","BANK_TRANSFER","E_WALLET","CHEQUE","WITHHOLDING_TAX_CERTIFICATE","CLEARING_SETTLEMENT","DEBT_WRITE_OFF","INTER_COMPANY","OTHER","PAYMENT_GATEWAY"]});function rf(t,e,r){let n=e.split("."),i=t;for(let s=0;s<n.length-1;s++)(!i[n[s]]||typeof i[n[s]]!="object")&&(i[n[s]]={}),i=i[n[s]];let o=n[n.length-1];i[o]&&typeof i[o]=="object"&&r&&typeof r=="object"?Object.assign(i[o],r):i[o]=r}function n2t(t){return t.split(",").map(e=>e.trim()).filter(Boolean)}function OD(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let a=t[o];if(!(a==null||a===""))switch(s.op){case"contains":rf(n,s.path,{contains:String(a)});break;case"eq":rf(n,s.path,{eq:a});break;case"gte":{let c=s.type==="number"?e1e(a):a;c!==void 0&&rf(n,s.path,{gte:c});break}case"lte":{let c=s.type==="number"?e1e(a):a;c!==void 0&&rf(n,s.path,{lte:c});break}case"boolean":rf(n,s.path,{eq:!!a});break;case"multi":{let c=n2t(String(a));c.length>1?rf(n,s.path,{in:c}):c.length===1&&rf(n,s.path,{eq:c[0]});break}case"array":rf(n,s.path,a);break;case"plain":rf(n,s.path,String(a));break}}let i=Object.keys(n).length>0?n:void 0;if(!(!r&&!i))return r?i?i2t(r,i):r:i}function i2t(t,e){let r={...t};for(let[n,i]of Object.entries(e)){let o=r[n];KFe(o)&&KFe(i)?r[n]={...o,...i}:r[n]=i}return r}function KFe(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function e1e(t){let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:void 0}var YM=X(()=>{"use strict"});async function FD(t,e,r,n){return t(r??0,e??n)}var cZ=X(()=>{"use strict"});function t1e(t,e=!1){let r={};for(let[n,i]of Object.entries(t)){let o={type:i.type,description:i.description};i.enum&&(o.enum=[...i.enum]),i.type==="array"&&i.items&&(o.items=i.items),r[n]=o}return e&&(r.query=u2t),r.filter=o2t,r.sortBy=s2t,r.sortOrder=a2t,r.limit=c2t,r.offset=l2t,r}function lZ(t){let e=[];for(let[r,n]of Object.entries(t)){let i=n.cliFlag??d2t(r,n.type),o=n.cliFlag&&n.type!=="boolean"&&!i.includes("<")?`${i} <${i.replace(/^--/,"").split("-").pop()}>`:i;e.push([o,n.description,n.enum,r])}return e}function d2t(t,e){let r=t.replace(/([A-Z])/g,"-$1").toLowerCase();return e==="boolean"?`--${r}`:`--${r} <${r.split("-").pop()}>`}function f2t(t,e){if(!e)return{};let r={};for(let n of Object.keys(e))t[n]!==void 0&&(r[n]=t[n]);return r}function Zt(t){let e=t1e(t.fields,t.defaults.supportsQuery);e.sortBy={...e.sortBy,description:`Sort field (default: ${t.defaults.sortBy})`},t.pathParam&&(e[t.pathParam]={type:"string",description:t.pathParamDescription??`${t.pathParam} (required)`}),t.extraParams&&Object.assign(e,t.extraParams),t.defaults.supportsView&&(e.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). Search lean, then drill in with get_*."});let r=[...t.pathParam?[t.pathParam]:[],...t.extraRequired??[]];return{name:t.name,description:t.description,params:e,required:r,group:t.group,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...t.searchHint?{searchHint:t.searchHint}:{},execute:async(n,i)=>{let o=i.limit,s=i.offset,a=i.sortBy??t.defaults.sortBy,c=i.sortOrder??t.defaults.sortOrder,u=t.defaults.supportsQuery?i.query:void 0,d=t.defaults.supportsView?i.view==="full"?"full":"lean":void 0,f=i.filter,p=t.baseFilter?f?{...t.baseFilter,...f}:t.baseFilter:f,h=OD(i,t.fields,p),m={sortBy:[a],order:c},A=f2t(i,t.extraParams),g=t.pathParam?(C,E)=>t.fetcher(n.client,i[t.pathParam],{filter:h,sort:m,limit:E,offset:C,query:u,view:d,...A}):(C,E)=>t.fetcher(n.client,{filter:h,sort:m,limit:E,offset:C,query:u,view:d,...A}),y=d==="lean"&&t.defaults.leanDefaultLimit?t.defaults.leanDefaultLimit:t.defaults.defaultLimit;return FD(g,o,s,y)}}}var o2t,s2t,a2t,c2t,l2t,u2t,uZ=X(()=>{"use strict";cZ();YM();o2t={type:"object",description:"Raw filter JSON. Merged with named params (named win). Operators by type, others rejected: string eq/neq/contains/likeIn/reg/in/isNull; number eq/neq/gt/gte/lt/lte/in/inRange; date eq/gt/gte/lt/lte/between. Nest with and/or/andGroup/orGroup; a related field nests too: {contact:{name:{...}}}."},s2t={type:"string",description:"Sort field (default varies by entity)"},a2t={type:"string",description:"Sort direction",enum:["ASC","DESC"]},c2t={type:"number",description:"Max per page (\u22641000)"},l2t={type:"number",description:"Page (0-indexed). Requires sort."},u2t={type:"string",description:'Jaz search expression. Merged with named params (named win). Examples: "status:unpaid AND $500+", "customer:acme AND date:-30d". Supports amounts ($500+, $100-500), dates (date:this month, due:overdue), enums, string fields (customer:, supplier:, ref:, tag:), boolean (hasattachment:yes), AND/OR/NOT, inline sort (sort:amount:desc).'}});async function Pp(t,e={}){let r=Math.min(Math.max(e.pageSize??200,1),1e3),n=e.concurrency??5,i=Math.max(Math.floor(n),1),o=e.maxItems??1/0,s=e.onProgress,a=await t(0,r),c=a.data??[],u=a.totalElements??0,d=1;if(u<=r||c.length>=o){let g=o<1/0?c.slice(0,o):c;return s?.(g.length,u),{data:g,totalElements:u,truncated:g.length<u,requestCount:d}}let f=Math.ceil(u/r),p=[];for(let g=1;g<f&&g<=65536;g++)p.push(g);let h=f>65537,m=[...c];s?.(m.length,u);for(let g=0;g<p.length;g+=i){let y=p.slice(g,g+i),C=await Promise.all(y.map(E=>t(E,r)));d+=C.length;for(let E of C)m.push(...E.data??[]);if(s?.(m.length,u),m.length>=o)break}let A=o<1/0?m.slice(0,o):m;return{data:A,totalElements:u,truncated:h||A.length<m.length,requestCount:d}}var HM=X(()=>{"use strict"});var CC,DGr,SGr,RGr,xGr,TGr,BGr,kGr,NGr,OGr,QD,FGr,QGr,LGr,MGr,PGr,r1e=X(()=>{CC=globalThis.window?.document!==void 0,DGr=globalThis.process?.versions?.node!==void 0,SGr=globalThis.process?.versions?.bun!==void 0,RGr=globalThis.Deno?.version?.deno!==void 0,xGr=globalThis.process?.versions?.electron!==void 0,TGr=globalThis.navigator?.userAgent?.includes("jsdom")===!0,BGr=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,kGr=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,NGr=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,OGr=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,QD=globalThis.navigator?.userAgentData?.platform,FGr=QD==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",QGr=QD==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",LGr=QD==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",MGr=QD==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),PGr=QD==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var Us={};So(Us,{ConEmu:()=>u1e,beep:()=>q2t,beginSynchronizedOutput:()=>a1e,clearScreen:()=>F2t,clearTerminal:()=>M2t,clearViewport:()=>Q2t,cursorBackward:()=>b2t,cursorDown:()=>y2t,cursorForward:()=>E2t,cursorGetPosition:()=>v2t,cursorHide:()=>D2t,cursorLeft:()=>o1e,cursorMove:()=>g2t,cursorNextLine:()=>w2t,cursorPrevLine:()=>_2t,cursorRestorePosition:()=>I2t,cursorSavePosition:()=>C2t,cursorShow:()=>S2t,cursorTo:()=>A2t,cursorUp:()=>i1e,endSynchronizedOutput:()=>c1e,enterAlternativeScreen:()=>P2t,eraseDown:()=>B2t,eraseEndLine:()=>x2t,eraseLine:()=>s1e,eraseLines:()=>R2t,eraseScreen:()=>zM,eraseStartLine:()=>T2t,eraseUp:()=>k2t,exitAlternativeScreen:()=>U2t,iTerm:()=>l1e,image:()=>Y2t,link:()=>j2t,scrollDown:()=>O2t,scrollUp:()=>N2t,setCwd:()=>H2t,synchronizedOutput:()=>$2t});import IC from"node:process";import p2t from"node:os";var Ir,vC,lg,LD,n1e,h2t,m2t,dZ,wC,A2t,g2t,i1e,y2t,E2t,b2t,o1e,C2t,I2t,v2t,w2t,_2t,D2t,S2t,R2t,x2t,T2t,s1e,B2t,k2t,zM,N2t,O2t,F2t,Q2t,L2t,M2t,P2t,U2t,a1e,c1e,$2t,q2t,j2t,Y2t,l1e,u1e,H2t,fZ=X(()=>{r1e();Ir="\x1B[",vC="\x1B]",lg="\x07",LD=";",n1e=!CC&&IC.env.TERM_PROGRAM==="Apple_Terminal",h2t=!CC&&IC.platform==="win32",m2t=!CC&&(IC.env.TERM?.startsWith("screen")||IC.env.TERM?.startsWith("tmux")||IC.env.TMUX!==void 0),dZ=CC?()=>{throw new Error("`process.cwd()` only works in Node.js, not the browser.")}:IC.cwd,wC=t=>m2t?"\x1BPtmux;"+t.replaceAll("\x1B","\x1B\x1B")+"\x1B\\":t,A2t=(t,e)=>{if(typeof t!="number")throw new TypeError("The `x` argument is required");return typeof e!="number"?Ir+(t+1)+"G":Ir+(e+1)+LD+(t+1)+"H"},g2t=(t,e)=>{if(typeof t!="number")throw new TypeError("The `x` argument is required");let r="";return t<0?r+=Ir+-t+"D":t>0&&(r+=Ir+t+"C"),e<0?r+=Ir+-e+"A":e>0&&(r+=Ir+e+"B"),r},i1e=(t=1)=>Ir+t+"A",y2t=(t=1)=>Ir+t+"B",E2t=(t=1)=>Ir+t+"C",b2t=(t=1)=>Ir+t+"D",o1e=Ir+"G",C2t=n1e?"\x1B7":Ir+"s",I2t=n1e?"\x1B8":Ir+"u",v2t=Ir+"6n",w2t=Ir+"E",_2t=Ir+"F",D2t=Ir+"?25l",S2t=Ir+"?25h",R2t=t=>{let e="";for(let r=0;r<t;r++)e+=s1e+(r<t-1?i1e():"");return t&&(e+=o1e),e},x2t=Ir+"K",T2t=Ir+"1K",s1e=Ir+"2K",B2t=Ir+"J",k2t=Ir+"1J",zM=Ir+"2J",N2t=Ir+"S",O2t=Ir+"T",F2t="\x1Bc",Q2t=`${zM}${Ir}H`,L2t=()=>{if(CC||!h2t)return!1;let t=p2t.release().split("."),e=Number(t[0]),r=Number(t[2]??0);return e<10||e===10&&r<10586},M2t=L2t()?`${zM}${Ir}0f`:`${zM}${Ir}3J${Ir}H`,P2t=Ir+"?1049h",U2t=Ir+"?1049l",a1e=Ir+"?2026h",c1e=Ir+"?2026l",$2t=t=>a1e+t+c1e,q2t=lg,j2t=(t,e)=>{let r=wC(`${vC}8${LD}${LD}${e}${lg}`),n=wC(`${vC}8${LD}${LD}${lg}`);return r+t+n},Y2t=(t,e={})=>{let r=`${vC}1337;File=inline=1`;e.width&&(r+=`;width=${e.width}`),e.height&&(r+=`;height=${e.height}`),e.preserveAspectRatio===!1&&(r+=";preserveAspectRatio=0");let n=Buffer.from(t);return wC(r+`;size=${n.byteLength}:`+n.toString("base64")+lg)},l1e={setCwd:(t=dZ())=>wC(`${vC}50;CurrentDir=${t}${lg}`),annotation(t,e={}){let r=`${vC}1337;`,n=e.x!==void 0,i=e.y!==void 0;if((n||i)&&!(n&&i&&e.length!==void 0))throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");return t=t.replaceAll("|",""),r+=e.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",e.length>0?r+=(n?[t,e.length,e.x,e.y]:[e.length,t]).join("|"):r+=t,wC(r+lg)}},u1e={setCwd:(t=dZ())=>wC(`${vC}9;9;${t}${lg}`)},H2t=(t=dZ())=>l1e.setCwd(t)+u1e.setCwd(t)});var d1e=X(()=>{fZ();fZ()});function X2t(t){if(t.length>50)return!1;if(W2t.test(t))return!0;if(t.includes("\u200D")){let e=t.match(Z2t);return e!==null&&e.length>=2}return!1}function K2t(t){return t.replace(J2t,"")}function eUt(t){return G2t.test(t)}function tUt(t,e){let r=0;if(t.length>1)for(let n of t.slice(1))n>="\uFF00"&&n<="\uFFEF"&&(r+=Dw(n.codePointAt(0),e));return r}function Up(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:n=!1}=e,i=t;if(!n&&(i.includes("\x1B")||i.includes("\x9B"))&&(i=Sa(i)),i.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(i))return i.length;let o=0,s={ambiguousAsWide:!r};for(let{segment:a}of z2t.segment(i)){if(eUt(a))continue;if(V2t.test(a)||X2t(a)){o+=2;continue}let c=K2t(a).codePointAt(0);o+=Dw(c,s),o+=tUt(a,s)}return o}var z2t,G2t,J2t,V2t,W2t,Z2t,f1e=X(()=>{lA();LO();z2t=new Intl.Segmenter,G2t=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$","v"),J2t=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),V2t=new RegExp("^\\p{RGI_Emoji}$","v"),W2t=/^[\d#*]\u20E3$/,Z2t=new RegExp("\\p{Extended_Pictographic}","gu")});function mZ(t,e,r){return String(t).normalize().replaceAll(`\r
280
+ ${s}`)}var TPt,SM=X(()=>{"use strict";Lp();AC();TPt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});import{readFileSync as kPt}from"node:fs";import{createHash as NPt}from"node:crypto";import{extname as OPt}from"node:path";async function RM(t){let{plan:e,client:r,bankAccountId:n,onProgress:i}=t,o=e.folders.flatMap(c=>c.files.filter(u=>gQ(u.documentType))),s=[],a=new Set;for(let c=0;c<o.length;c++){let u=o[c],d=u.documentType,f;try{let p=u.absolutePath;u.encrypted&&u.filePassword&&(f=w_(u.absolutePath,u.filePassword),p=f);let h=kPt(p),m=`${NPt("sha256").update(h).digest("hex")}:${d}`;if(a.has(m)){let E={file:`${u.folder}/${u.filename}`,type:d,status:"skipped",error:"Duplicate of an already-uploaded file (identical content + type)"};s.push(E),i?.(E,c,o.length);continue}a.add(m);let A=OPt(u.filename).toLowerCase();if(!I_.has(A))throw new Error(`Unsupported file extension "${A}" \u2014 expected one of: ${[...I_].join(", ")}`);let g=new Blob([h],{type:BA(A)}),y;d==="BANK_STATEMENT"?y=(await mC(r,{businessTransactionType:d,accountResourceId:n,sourceFile:g,sourceFileName:u.filename})).data:y=(await Ou(r,{businessTransactionType:d,sourceFile:g,sourceFileName:u.filename,...u.merged?{uploadMode:"MERGED"}:{}})).data;let C={file:`${u.folder}/${u.filename}`,type:d,status:"uploaded",response:y};s.push(C),i?.(C,c,o.length)}catch(p){let h=p instanceof Error?p.message:String(p),m={file:`${u.folder}/${u.filename}`,type:d,status:"failed",error:h};s.push(m),i?.(m,c,o.length)}finally{f&&ub(f)}}return{total:o.length,success:s.filter(c=>c.status==="uploaded").length,failed:s.filter(c=>c.status==="failed").length,results:s}}var V7=X(()=>{"use strict";xD();Lp();D_();gp();SM()});var gC=X(()=>{"use strict";R9();zw();Vw()});var xM,TD,TM=X(()=>{"use strict";xM=t=>typeof t!="string"||t.trim()==="",TD=t=>typeof t=="string"&&t.trim()!==""});function aFe(t,e){if(t==="create_sale_order"||t==="create_purchase_order"){let r=e.documentType;return typeof r=="string"&&W7.includes(r)?r:void 0}return LPt[t]}async function Z7(t,e){let r;try{r=await t.get("/api/v1/references/next",{type:e},{timeoutMs:1e4})}catch(n){let i=n instanceof Error?n.message:String(n);throw new yC(`next reference: ${i}. Nothing was created.`,{cause:n})}if(xM(r?.data?.reference))throw new yC("next reference: upstream returned no reference. Nothing was created.");return r}async function Mp(t,e,r,n){if(!xM(r))return r.trim();if(n!==!0)return;let{data:i}=await Z7(t,e);return i.reference}async function go(t,e,r,n,{optional:i=!1}={}){let{autoReference:o,...s}=r,a=s.reference,c=await Mp(t,e,a,n);if(c!==void 0)return{...s,reference:c};if(!i)throw new yC("reference is required: supply one, or set autoReference: true to take the next number from the organization's own series. Nothing was created.");return xM(a)&&delete s.reference,s}async function og(t,e,r,n){let i=await Mp(t,e,r,n);if(i===void 0)throw new yC("reference is required: supply one, or set autoReference: true to take the next number from the organization's own series. Nothing was created.");return i}var W7,yC,LPt,Fu=X(()=>{"use strict";TM();W7=["SALE","SALE_CREDIT_NOTE","PURCHASE","PURCHASE_CREDIT_NOTE","FIXED_ASSET","JOURNAL_MANUAL","SALE_QUOTE","SALE_ORDER","PURCHASE_REQUEST","PURCHASE_ORDER","CLAIM"],yC=class extends Error{noWrite=!0;constructor(e,r){super(e,r),this.name="ReferenceUnavailableError"}},LPt={create_invoice:"SALE",create_bill:"PURCHASE",create_journal:"JOURNAL_MANUAL",create_customer_credit_note:"SALE_CREDIT_NOTE",create_supplier_credit_note:"PURCHASE_CREDIT_NOTE",create_claim:"CLAIM",convert_sale_order_to_invoice:"SALE",convert_purchase_order_to_bill:"PURCHASE"}});function X7(t){let e=(process.env[t]??"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function cFe(t){let e=(process.env[t]??"").trim().toLowerCase();return!(e==="0"||e==="false"||e==="no")}var K7=X(()=>{"use strict"});function BD(){return cFe(MPt)}function dFe(t,e=BD()){if(e)for(let r of t)r.readOnly||r.group==="jots"||r.group==="memory"||r.description.includes(lFe)||(r.description=`${r.description} ${lFe}`)}var MPt,uFe,lFe,BM=X(()=>{"use strict";K7();MPt="JAZ_JOTS_NUDGES";uFe="If you decide not to retry, record the decision with the jot tool (kind: RECOVERY).",lFe="If this action involved a judgment call, record it (jot field or jot tool)."});var kM,NM,OM,FM,QM,fFe,LM,pFe,EC=X(()=>{"use strict";kM="CRITICAL = money out (PAY), data destroyed (DELETE), external send or period lock (FINALIZE), or a recovery that re-drove a write; HIGH = a withheld write, or RISK/MATCH backed by a write; LOW = a deviation with no write; MEDIUM = the rest.",NM="HIGH = clear rule or precedent applied; MEDIUM = pattern-based inference; LOW = a guess a reviewer should check.",OM="NOTE is the server fallback for a missing kind; never declare it.",FM="Use a canonical job name when one fits: month-end-close, quarter-end-close, year-end-close, bank-recon, gst-vat-filing, payment-run, credit-control, supplier-recon, audit-prep, fa-review, document-collection, statutory-filing; else short kebab-case.",QM="An ack with duplicateCount > 0 means this judgment is already recorded: do not re-jot identical calls; recall first on repeated workflows.",fFe="Style: tight, factual, plain punctuation; never repeat content across fields (refs carry the record, why carries the basis); detail belongs only in why/ruledOut/frame where it earns its place.",LM="For HIGH or CRITICAL calls, or when the why matters, use the jot tool instead.",pFe="Judgment journal: when a real judgment call precedes a write, record it with `jot` after the write succeeds; when you deliberately hold a write, record that decision immediately (a withheld write is tier HIGH, not CRITICAL). Check `recall` for prior judgments before repeating one (jots namespace)."});function hFe(t,e){if(t.length<=e)return t;let r=t.slice(0,e-1);return`${r.replace(/\s+\S*$/,"")||r}\u2026`}function MM(t,e){let r=t.params?.[e]?.description?.trim();return r?`. ${hFe(r,200)}`:""}function mFe(t,e){return`Validation failed for ${t.name}: ${e.join("; ")}`}function AFe(t,e){let r=[];for(let n of t.required){let i=e[n];if(i==null){r.push(`Missing required field: ${n}${MM(t,n)}`);continue}typeof i=="string"&&i.trim()===""&&r.push(`Required field "${n}" is empty${MM(t,n)}`),t.readOnly&&Array.isArray(i)&&i.length===0&&r.push(`Required field "${n}" is an empty array${MM(t,n)}`)}if(!t.readOnly)for(let[n,i]of Object.entries(e)){if(i==null)continue;let o=t.params?.[n];if(!o)continue;let s=PPt(n,i,o);s&&r.push(`${s}${MM(t,n)}`),o.enum&&typeof i=="string"&&(o.enum.includes(i)||r.push(`Field "${n}" value "${hFe(i,80)}" not in allowed values: ${o.enum.join(", ")}`))}return{valid:r.length===0,errors:r}}function PPt(t,e,r){switch(r.type){case"string":if(typeof e!="string")return`Field "${t}" expected string, got ${typeof e}`;break;case"number":if(typeof e!="number"||!Number.isFinite(e))return`Field "${t}" expected finite number, got ${typeof e=="number"?"non-finite":typeof e}`;break;case"boolean":if(typeof e!="boolean")return`Field "${t}" expected boolean, got ${typeof e}`;break;case"array":if(!Array.isArray(e))return`Field "${t}" expected array, got ${typeof e}`;break;case"object":if(typeof e!="object"||Array.isArray(e))return`Field "${t}" expected object, got ${Array.isArray(e)?"array":typeof e}`;break}return null}function $Pt(t,e){let r=tZ.get(t);if(r&&e.includes(r))return r;let n=t.toLowerCase();return e.find(i=>i!==t&&i.toLowerCase()===n)}function eZ(t,e,r,n,i){if(!e||!t||typeof t!="object"||Array.isArray(t))return;let o=Object.keys(e);for(let[s,a]of Object.entries(t)){if(a==null)continue;let c=e[s];if(!c){let u=qPt.get(n.name)?.get(s);if(u){i.add(`${n.name}: "${r}${s}" belongs to ${u}, not this tool. ${n.name} is the flat variant and takes one line per row via "totalAmount", "itemDescription" and the row-level account. Nothing on this call reads "${r}${s}", so the amounts inside it did not reach the record \u2014 a row with no "totalAmount" is written at zero. Re-send through ${u}, or flatten the row, and verify the saved amount.`);continue}let d=$Pt(s,o);d&&(UPt.has(n.name)?i.add(`${n.name}: "${r}${s}" is the read-side name and is not declared on this tool, but the endpoint accepts it as an alias for "${r}${d}". Do not retry solely because of this warning \u2014 read the saved record to confirm the call's outcome. Prefer "${r}${d}" on new calls; it is the documented name.`):i.add(`${n.name}: "${r}${s}" is not a parameter of this tool \u2014 did you mean "${r}${d}"? Nothing on this call reads the name you sent, so that value did not reach the declared field. Read the saved record back: if this call created one, UPDATE it under the declared name rather than creating a second.`));continue}if(c.type==="array"&&Array.isArray(a))for(let u of a)eZ(u,c.items?.properties,`${r}${s}[].`,n,i);else c.type==="object"&&eZ(a,c.properties,`${r}${s}.`,n,i)}}function gFe(t,e){if(t.readOnly)return[];let r=new Set;return eZ(e,t.params,"",t,r),[...r]}function yFe(t,e){if(e.length===0||!t||typeof t!="object"||Array.isArray(t))return t;let{_warnings:r,...n}=t,i=Array.isArray(r)?r:r==null?[]:[r];return{_warnings:[...e,...i],...n}}var tZ,UPt,qPt,rZ=X(()=>{"use strict";tZ=new Map([["organizationAccountResourceId","accountResourceId"]]),UPt=new Set(["create_invoice","update_invoice","finalize_invoice","create_bill","update_bill","finalize_bill","create_customer_credit_note","update_customer_credit_note","finalize_customer_credit_note","create_supplier_credit_note","update_supplier_credit_note","finalize_supplier_credit_note","create_sale_order","update_sale_order","create_purchase_order","update_purchase_order"]);qPt=new Map([["bulk_upsert_invoices",new Map([["lineItems","bulk_upsert_invoice_line_items"]])],["bulk_upsert_bills",new Map([["lineItems","bulk_upsert_bill_line_items"]])]])});function bFe(t){return EFe[t]??EFe.jaz}var EFe,CFe=X(()=>{"use strict";EFe={jaz:{displayName:"Jaz",supportEmail:"support@jaz.ai",domain:"jaz.ai",agentInboxDomain:"jaz.email",dashboardUrl:"https://app.jaz.ai"},juan:{displayName:"Juan",supportEmail:"help@juan.ac",domain:"juan.ac",agentInboxDomain:"sendjuan.com",dashboardUrl:"https://app.juan.ac"}}});import{readFileSync as jPt}from"node:fs";import{dirname as YPt,join as HPt}from"node:path";import{fileURLToPath as zPt}from"node:url";function _Fe(t,e,{dashboardUrl:r,orgResourceId:n}){let i=wFe(),o=i.screenByKey.get(t);if(o){if(e)throw new Error(`Destination '${t}' is a screen, not a record view \u2014 omit resourceId. To open a specific record, use a "<resource>.modal.view-*" destination instead.`);return{url:IFe(`${r}${o.path}`,n),kind:"screen",label:o.label}}let s=i.modalByKey.get(t);if(s){if(s.requiresId&&!e)throw new Error(`Destination '${t}' opens a specific record \u2014 pass the record's resourceId. For a create/blank modal, use a "new-*"/"create-*" destination instead.`);let u=s.requiresId?s.urlTemplate.replace(GPt,encodeURIComponent(e)):s.urlTemplate;return{url:IFe(`${r}${s.mountPath}${u}`,n),kind:"modal",label:s.label}}let a=VPt(i,t),c=a.length?` Did you mean: ${a.join(", ")}?`:"";throw new Error(`Unknown dashboard destination '${t}'.${c} Call navigate with no destination to discover valid keys.`)}function DFe({query:t,resource:e,kind:r}){let{manifest:n}=wFe(),i=t?.trim().toLowerCase(),o=[...r==="modal"?[]:n.screens.filter(c=>!e||XPt(c.path)===e).map(c=>({key:c.key,label:c.label,kind:"screen"})),...r==="screen"?[]:n.modals.filter(c=>!e||c.resource===e).map(c=>({key:c.key,label:c.label,kind:"modal"}))],s=i?ZPt(i):[],a=i?o.filter(c=>s.some(u=>c.key.toLowerCase().includes(u)||c.label.toLowerCase().includes(u))):o;return{results:a.slice(0,vFe),total:a.length,truncated:a.length>vFe}}var GPt,JPt,nZ,wFe,VPt,IFe,vFe,WPt,ZPt,XPt,SFe=X(()=>{"use strict";GPt="{id}",JPt=YPt(zPt(import.meta.url)),nZ=null,wFe=()=>{if(!nZ){let t=JSON.parse(jPt(HPt(JPt,"dashboard-routes-manifest.json"),"utf8"));nZ={manifest:t,screenByKey:new Map(t.screens.map(e=>[e.key,e])),modalByKey:new Map(t.modals.map(e=>[e.key,e]))}}return nZ},VPt=(t,e,r=5)=>{let n=e.toLowerCase(),i=[],o=[...t.screenByKey.keys(),...t.modalByKey.keys()];for(let s of o)if(s.toLowerCase().includes(n)&&(i.push(s),i.length>=r))break;return i},IFe=(t,e)=>e?`${t}${t.includes("?")?"&":"?"}org=${encodeURIComponent(e)}`:t;vFe=60,WPt=[["credit note","credit"],["invoice","sale"],["bill","purchase"]],ZPt=t=>{let e=[t];for(let[r,n]of WPt)t.includes(r)&&e.push(t.split(r).join(n));return e},XPt=t=>t.split("/")[1]??""});function oZ(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t.data;return e&&typeof e=="object"&&!Array.isArray(e)?e:t}function Oc(t,e,r){let n=oZ(t);return{outcome:(typeof n.status=="string"?KPt[n.status]:void 0)??(r?"DELETED":e2t),...n,resourceId:e}}function Qu(t,e,r){switch(r){case"DELETED":return`${t} ${e} deleted.`;case"VOIDED":return`${t} ${e} voided \u2014 it is still on the books, with status VOID.`;default:return`${t} ${e}: deleted if it was a draft, voided and kept if it was active. Re-read it to see which, or pass --force to hard-delete either.`}}var iZ,KPt,e2t,sg=X(()=>{"use strict";iZ={force:"Hard-delete instead of voiding.",internalNotes:"Note recorded with the void."},KPt={VOID:"VOIDED",SUCCEEDED:"DELETED"},e2t="DELETED_IF_DRAFT_VOIDED_IF_ACTIVE"});var bC,ag,cg,RFe,t2t,r2t,PM,tf,kD=X(()=>{"use strict";bC=["ORGANIZATION","USER_MANAGEMENT","BILLING","ACCOUNTING","SALES","PURCHASES","REPORTS","FIXED_ASSET"],ag=["ADMIN","PREPARER","MEMBER","NO_ACCESS"],cg=["ADMIN","CUSTOM_USER"],RFe=["trial-balance","balance-sheet","profit-and-loss","general-ledger","cashflow","cash-balance","ar-report","ap-report","sales-summary","sales-payments-summary","purchase-summary","purchase-payments-summary","customer-revenue-summary","product-sales-summary","periodic-revenue-summary","supplier-expense-summary","product-purchase-summary","periodic-expense-summary","credit-note-summary","sales-cost-margin","sale-inventory-movement","purchase-inventory-movement","analysis-anomalous-invoices","analysis-anomalous-bills","analysis-cashflow-anomalies","analysis-gl-journal-audit","analysis-receivables-customer-risk","analysis-cash-expense-health","analysis-exchange-rate-audit","statement-of-account-export","tax-ledger","equity-movement","bank-closing-balance","bank-reconciliation-summary","bank-reconciliation-details","fixed-assets-register","fixed-assets-reconciliation-summary","journal-summary"],t2t=["MAGIC_MATCH","MAGIC_RECONCILE_WITH_CASH_TRANSFER","MAGIC_RECONCILE_WITH_BANK_RULE","MAGIC_QUICK_RECONCILE","MAGIC_RECONCILE_WITH_CASH_IN_OUT"],r2t="RECOMMENDATIONS",PM=[...t2t,r2t],tf=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","SALE_PAYMENT","PURCHASE_PAYMENT","BATCH_PAYMENT","CONTACT","ITEM","CAPSULE","SCHEDULED_TRANSACTION","JOURNAL","BANK_RECORD","CASHFLOW_TRANSACTION","FIXED_ASSET","CHART_OF_ACCOUNT","TAX_PROFILE"]});var xFe,TFe,BFe,kFe,NFe,UM,OFe,FFe,QFe,$M,LFe,sZ,MFe,qM,PFe,UFe,$Fe,qFe,jFe,YFe,HFe,zFe,GFe,ND,jM,JFe,VFe,WFe,aZ,yGr,ZFe,XFe,ca=X(()=>{"use strict";xFe=["DRAFT","UNPAID","PARTIALLY_PAID","PAID","VOID"],TFe=["DRAFT","UNAPPLIED","PARTIALLY_APPLIED","APPLIED","VOID"],BFe=["DRAFT","ACTIVE","VOID"],kFe=["JOURNAL_MANUAL","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASHFLOW","JOURNAL_CASH_TRANSFER","JOURNAL_TRANSFER_BALANCE","JOURNAL_CASHFLOW_BANK_RECON","JOURNAL_CASHFLOW_ADJUSTMENT"],NFe=["CASH_TRANSFER","DIRECT_CASH_IN","DIRECT_CASH_OUT"],UM=["ACTIVE","INACTIVE"],OFe=["ACTIVE","INACTIVE"],FFe=["ACTIVE","INACTIVE"],QFe=["INVENTORY","NON_INVENTORY"],$M=["PENDING","APPROVED"],LFe=["RECONCILED","UNRECONCILED","ARCHIVED","POSSIBLE_DUPLICATE"],sZ=["PAYIN","PAYOUT"],MFe=["ALL_CASHFLOWS","CASH_ENTRIES"],qM=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE","JOURNAL_MANUAL","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASHFLOW","JOURNAL_CASH_TRANSFER","JOURNAL_CASHFLOW_BANK_RECON","JOURNAL_CASHFLOW_ADJUSTMENT","PAYMENT_SALE","PAYMENT_PURCHASE","PAYMENT_SALE_CREDIT_NOTE","PAYMENT_PURCHASE_CREDIT_NOTE","BATCH_SALE","BATCH_PURCHASE","FIXED_ASSETS"],PFe=["ACTIVE","UNPAID","PARTIALLY_PAID","PAID","VOID","DRAFT","UNAPPLIED","PARTIALLY_APPLIED","APPLIED"],UFe=["ACTIVE","ONGOING","COMPLETED","DRAFT","DISPOSED","SOLD","DISCARDED","CLOSED_OUT"],$Fe=["TANGIBLE","INTANGIBLE"],qFe=["ACTIVE","INACTIVE"],jFe=["ACTIVE","CANCELLED","INACTIVE"],YFe=["ONE_TIME","DAILY","WEEKLY","MONTHLY","QUARTERLY","YEARLY"],HFe=["DRAFT","CREATED","ACCEPTED","CONFIRMED","VOID"],zFe=["DRAFT","ACTIVE","ACCEPTED","CONFIRMED","VOID"],GFe=["Asset","Liability","Equity","Revenue","Expense"],ND={Asset:["Bank Accounts","Cash","Current Asset","Non-current Asset","Fixed Asset","Inventory","Investment","Goodwill"],Liability:["Current Liability","Non-current Liability"],Equity:["Shareholders Equity"],Revenue:["Operating Revenue","Other Revenue","Discontinued Income","Financing Income","Investing Income"],Expense:["Direct Costs","Operating Expense","Other Expense","Finance Cost","Investing Expense","Income Tax Expense","Discontinued Expense"]},jM=[...ND.Asset,...ND.Liability,...ND.Equity,...ND.Revenue,...ND.Expense],JFe=["TEXT","NUMBER","BOOLEAN","DATE","LINK"],VFe=["ADMIN","CUSTOM_USER"],WFe=["ACTIVE","INACTIVE"],aZ=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"],yGr=aZ.filter(t=>t!=="CUSTOM"),ZFe=["QUEUED","DISPATCHING","PROCESSING","SUCCESS","FAILED","PARTIAL_SUCCESS"],XFe=["CASH","CREDIT_CARD","BANK_TRANSFER","E_WALLET","CHEQUE","WITHHOLDING_TAX_CERTIFICATE","CLEARING_SETTLEMENT","DEBT_WRITE_OFF","INTER_COMPANY","OTHER","PAYMENT_GATEWAY"]});function rf(t,e,r){let n=e.split("."),i=t;for(let s=0;s<n.length-1;s++)(!i[n[s]]||typeof i[n[s]]!="object")&&(i[n[s]]={}),i=i[n[s]];let o=n[n.length-1];i[o]&&typeof i[o]=="object"&&r&&typeof r=="object"?Object.assign(i[o],r):i[o]=r}function n2t(t){return t.split(",").map(e=>e.trim()).filter(Boolean)}function OD(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let a=t[o];if(!(a==null||a===""))switch(s.op){case"contains":rf(n,s.path,{contains:String(a)});break;case"eq":rf(n,s.path,{eq:a});break;case"gte":{let c=s.type==="number"?e1e(a):a;c!==void 0&&rf(n,s.path,{gte:c});break}case"lte":{let c=s.type==="number"?e1e(a):a;c!==void 0&&rf(n,s.path,{lte:c});break}case"boolean":rf(n,s.path,{eq:!!a});break;case"multi":{let c=n2t(String(a));c.length>1?rf(n,s.path,{in:c}):c.length===1&&rf(n,s.path,{eq:c[0]});break}case"array":rf(n,s.path,a);break;case"plain":rf(n,s.path,String(a));break}}let i=Object.keys(n).length>0?n:void 0;if(!(!r&&!i))return r?i?i2t(r,i):r:i}function i2t(t,e){let r={...t};for(let[n,i]of Object.entries(e)){let o=r[n];KFe(o)&&KFe(i)?r[n]={...o,...i}:r[n]=i}return r}function KFe(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).some(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function e1e(t){let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:void 0}var YM=X(()=>{"use strict"});async function FD(t,e,r,n){return t(r??0,e??n)}var cZ=X(()=>{"use strict"});function t1e(t,e=!1){let r={};for(let[n,i]of Object.entries(t)){let o={type:i.type,description:i.description};i.enum&&(o.enum=[...i.enum]),i.type==="array"&&i.items&&(o.items=i.items),r[n]=o}return e&&(r.query=u2t),r.filter=o2t,r.sortBy=s2t,r.sortOrder=a2t,r.limit=c2t,r.offset=l2t,r}function lZ(t){let e=[];for(let[r,n]of Object.entries(t)){let i=n.cliFlag??d2t(r,n.type),o=n.cliFlag&&n.type!=="boolean"&&!i.includes("<")?`${i} <${i.replace(/^--/,"").split("-").pop()}>`:i;e.push([o,n.description,n.enum,r])}return e}function d2t(t,e){let r=t.replace(/([A-Z])/g,"-$1").toLowerCase();return e==="boolean"?`--${r}`:`--${r} <${r.split("-").pop()}>`}function f2t(t,e){if(!e)return{};let r={};for(let n of Object.keys(e))t[n]!==void 0&&(r[n]=t[n]);return r}function Zt(t){let e=t1e(t.fields,t.defaults.supportsQuery);e.sortBy={...e.sortBy,description:`Sort field (default: ${t.defaults.sortBy})`},t.pathParam&&(e[t.pathParam]={type:"string",description:t.pathParamDescription??`${t.pathParam} (required)`}),t.extraParams&&Object.assign(e,t.extraParams),t.defaults.supportsView&&(e.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). Search lean, then drill in with get_*."});let r=[...t.pathParam?[t.pathParam]:[],...t.extraRequired??[]];return{name:t.name,description:t.description,params:e,required:r,group:t.group,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...t.searchHint?{searchHint:t.searchHint}:{},execute:async(n,i)=>{let o=i.limit,s=i.offset,a=i.sortBy??t.defaults.sortBy,c=i.sortOrder??t.defaults.sortOrder,u=t.defaults.supportsQuery?i.query:void 0,d=t.defaults.supportsView?i.view==="full"?"full":"lean":void 0,f=i.filter,p=t.baseFilter?f?{...t.baseFilter,...f}:t.baseFilter:f,h=OD(i,t.fields,p),m={sortBy:[a],order:c},A=f2t(i,t.extraParams),g=t.pathParam?(C,E)=>t.fetcher(n.client,i[t.pathParam],{filter:h,sort:m,limit:E,offset:C,query:u,view:d,...A}):(C,E)=>t.fetcher(n.client,{filter:h,sort:m,limit:E,offset:C,query:u,view:d,...A}),y=d==="lean"&&t.defaults.leanDefaultLimit?t.defaults.leanDefaultLimit:t.defaults.defaultLimit;return FD(g,o,s,y)}}}var o2t,s2t,a2t,c2t,l2t,u2t,uZ=X(()=>{"use strict";cZ();YM();o2t={type:"object",description:"Raw filter JSON. Merged with named params (named win). Operators by type, others rejected: string eq/neq/contains/likeIn/reg/in/isNull; number eq/neq/gt/gte/lt/lte/in/inRange; date eq/gt/gte/lt/lte/between. Nest with and/or/andGroup/orGroup; a related field nests too: {contact:{name:{...}}}."},s2t={type:"string",description:"Sort field (default varies by entity)"},a2t={type:"string",description:"Sort direction",enum:["ASC","DESC"]},c2t={type:"number",description:"Max per page (\u22641000)"},l2t={type:"number",description:"Page (0-indexed). Requires sort."},u2t={type:"string",description:'Jaz search expression. Merged with named params (named win). Examples: "status:unpaid AND $500+", "customer:acme AND date:-30d". Supports amounts ($500+, $100-500), dates (date:this month, due:overdue), enums, string fields (customer:, supplier:, ref:, tag:), boolean (hasattachment:yes), AND/OR/NOT, inline sort (sort:amount:desc).'}});async function Pp(t,e={}){let r=Math.min(Math.max(e.pageSize??200,1),1e3),n=e.concurrency??5,i=Math.max(Math.floor(n),1),o=e.maxItems??1/0,s=e.onProgress,a=await t(0,r),c=a.data??[],u=a.totalElements??0,d=1;if(u<=r||c.length>=u||c.length>=o){let g=o<1/0?c.slice(0,o):c;return s?.(g.length,u),{data:g,totalElements:u,truncated:g.length<u,requestCount:d}}let f=Math.ceil(u/r),p=[];for(let g=1;g<f&&g<=65536;g++)p.push(g);let h=f>65537,m=[...c];s?.(m.length,u);for(let g=0;g<p.length;g+=i){let y=p.slice(g,g+i),C=await Promise.all(y.map(E=>t(E,r)));d+=C.length;for(let E of C)m.push(...E.data??[]);if(s?.(m.length,u),m.length>=o)break}let A=o<1/0?m.slice(0,o):m;return{data:A,totalElements:u,truncated:h||A.length<m.length,requestCount:d}}var HM=X(()=>{"use strict"});var CC,DGr,SGr,RGr,xGr,TGr,BGr,kGr,NGr,OGr,QD,FGr,QGr,LGr,MGr,PGr,r1e=X(()=>{CC=globalThis.window?.document!==void 0,DGr=globalThis.process?.versions?.node!==void 0,SGr=globalThis.process?.versions?.bun!==void 0,RGr=globalThis.Deno?.version?.deno!==void 0,xGr=globalThis.process?.versions?.electron!==void 0,TGr=globalThis.navigator?.userAgent?.includes("jsdom")===!0,BGr=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,kGr=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,NGr=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,OGr=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,QD=globalThis.navigator?.userAgentData?.platform,FGr=QD==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",QGr=QD==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",LGr=QD==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",MGr=QD==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),PGr=QD==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var Us={};So(Us,{ConEmu:()=>u1e,beep:()=>q2t,beginSynchronizedOutput:()=>a1e,clearScreen:()=>F2t,clearTerminal:()=>M2t,clearViewport:()=>Q2t,cursorBackward:()=>b2t,cursorDown:()=>y2t,cursorForward:()=>E2t,cursorGetPosition:()=>v2t,cursorHide:()=>D2t,cursorLeft:()=>o1e,cursorMove:()=>g2t,cursorNextLine:()=>w2t,cursorPrevLine:()=>_2t,cursorRestorePosition:()=>I2t,cursorSavePosition:()=>C2t,cursorShow:()=>S2t,cursorTo:()=>A2t,cursorUp:()=>i1e,endSynchronizedOutput:()=>c1e,enterAlternativeScreen:()=>P2t,eraseDown:()=>B2t,eraseEndLine:()=>x2t,eraseLine:()=>s1e,eraseLines:()=>R2t,eraseScreen:()=>zM,eraseStartLine:()=>T2t,eraseUp:()=>k2t,exitAlternativeScreen:()=>U2t,iTerm:()=>l1e,image:()=>Y2t,link:()=>j2t,scrollDown:()=>O2t,scrollUp:()=>N2t,setCwd:()=>H2t,synchronizedOutput:()=>$2t});import IC from"node:process";import p2t from"node:os";var Ir,vC,lg,LD,n1e,h2t,m2t,dZ,wC,A2t,g2t,i1e,y2t,E2t,b2t,o1e,C2t,I2t,v2t,w2t,_2t,D2t,S2t,R2t,x2t,T2t,s1e,B2t,k2t,zM,N2t,O2t,F2t,Q2t,L2t,M2t,P2t,U2t,a1e,c1e,$2t,q2t,j2t,Y2t,l1e,u1e,H2t,fZ=X(()=>{r1e();Ir="\x1B[",vC="\x1B]",lg="\x07",LD=";",n1e=!CC&&IC.env.TERM_PROGRAM==="Apple_Terminal",h2t=!CC&&IC.platform==="win32",m2t=!CC&&(IC.env.TERM?.startsWith("screen")||IC.env.TERM?.startsWith("tmux")||IC.env.TMUX!==void 0),dZ=CC?()=>{throw new Error("`process.cwd()` only works in Node.js, not the browser.")}:IC.cwd,wC=t=>m2t?"\x1BPtmux;"+t.replaceAll("\x1B","\x1B\x1B")+"\x1B\\":t,A2t=(t,e)=>{if(typeof t!="number")throw new TypeError("The `x` argument is required");return typeof e!="number"?Ir+(t+1)+"G":Ir+(e+1)+LD+(t+1)+"H"},g2t=(t,e)=>{if(typeof t!="number")throw new TypeError("The `x` argument is required");let r="";return t<0?r+=Ir+-t+"D":t>0&&(r+=Ir+t+"C"),e<0?r+=Ir+-e+"A":e>0&&(r+=Ir+e+"B"),r},i1e=(t=1)=>Ir+t+"A",y2t=(t=1)=>Ir+t+"B",E2t=(t=1)=>Ir+t+"C",b2t=(t=1)=>Ir+t+"D",o1e=Ir+"G",C2t=n1e?"\x1B7":Ir+"s",I2t=n1e?"\x1B8":Ir+"u",v2t=Ir+"6n",w2t=Ir+"E",_2t=Ir+"F",D2t=Ir+"?25l",S2t=Ir+"?25h",R2t=t=>{let e="";for(let r=0;r<t;r++)e+=s1e+(r<t-1?i1e():"");return t&&(e+=o1e),e},x2t=Ir+"K",T2t=Ir+"1K",s1e=Ir+"2K",B2t=Ir+"J",k2t=Ir+"1J",zM=Ir+"2J",N2t=Ir+"S",O2t=Ir+"T",F2t="\x1Bc",Q2t=`${zM}${Ir}H`,L2t=()=>{if(CC||!h2t)return!1;let t=p2t.release().split("."),e=Number(t[0]),r=Number(t[2]??0);return e<10||e===10&&r<10586},M2t=L2t()?`${zM}${Ir}0f`:`${zM}${Ir}3J${Ir}H`,P2t=Ir+"?1049h",U2t=Ir+"?1049l",a1e=Ir+"?2026h",c1e=Ir+"?2026l",$2t=t=>a1e+t+c1e,q2t=lg,j2t=(t,e)=>{let r=wC(`${vC}8${LD}${LD}${e}${lg}`),n=wC(`${vC}8${LD}${LD}${lg}`);return r+t+n},Y2t=(t,e={})=>{let r=`${vC}1337;File=inline=1`;e.width&&(r+=`;width=${e.width}`),e.height&&(r+=`;height=${e.height}`),e.preserveAspectRatio===!1&&(r+=";preserveAspectRatio=0");let n=Buffer.from(t);return wC(r+`;size=${n.byteLength}:`+n.toString("base64")+lg)},l1e={setCwd:(t=dZ())=>wC(`${vC}50;CurrentDir=${t}${lg}`),annotation(t,e={}){let r=`${vC}1337;`,n=e.x!==void 0,i=e.y!==void 0;if((n||i)&&!(n&&i&&e.length!==void 0))throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");return t=t.replaceAll("|",""),r+=e.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",e.length>0?r+=(n?[t,e.length,e.x,e.y]:[e.length,t]).join("|"):r+=t,wC(r+lg)}},u1e={setCwd:(t=dZ())=>wC(`${vC}9;9;${t}${lg}`)},H2t=(t=dZ())=>l1e.setCwd(t)+u1e.setCwd(t)});var d1e=X(()=>{fZ();fZ()});function X2t(t){if(t.length>50)return!1;if(W2t.test(t))return!0;if(t.includes("\u200D")){let e=t.match(Z2t);return e!==null&&e.length>=2}return!1}function K2t(t){return t.replace(J2t,"")}function eUt(t){return G2t.test(t)}function tUt(t,e){let r=0;if(t.length>1)for(let n of t.slice(1))n>="\uFF00"&&n<="\uFFEF"&&(r+=Dw(n.codePointAt(0),e));return r}function Up(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:n=!1}=e,i=t;if(!n&&(i.includes("\x1B")||i.includes("\x9B"))&&(i=Sa(i)),i.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(i))return i.length;let o=0,s={ambiguousAsWide:!r};for(let{segment:a}of z2t.segment(i)){if(eUt(a))continue;if(V2t.test(a)||X2t(a)){o+=2;continue}let c=K2t(a).codePointAt(0);o+=Dw(c,s),o+=tUt(a,s)}return o}var z2t,G2t,J2t,V2t,W2t,Z2t,f1e=X(()=>{lA();LO();z2t=new Intl.Segmenter,G2t=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$","v"),J2t=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),V2t=new RegExp("^\\p{RGI_Emoji}$","v"),W2t=/^[\d#*]\u20E3$/,Z2t=new RegExp("\\p{Extended_Pictographic}","gu")});function mZ(t,e,r){return String(t).normalize().replaceAll(`\r
281
281
  `,`
282
282
  `).split(`
283
283
  `).map(n=>AUt(mUt(n),e,r)).join(`
@@ -439,7 +439,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
439
439
  `)?`"${t.replace(/"/g,'""')}"`:t}function XMe(t){return t==null?"":typeof t=="object"?JSON.stringify(t):String(t)}function KHt(t,e){let r=e.map(i=>e2(i.header)).join(","),n=t.map(i=>e.map(o=>{let s=ezt(i,o.key);if(s==null||s==="")return"";let a=o.format?XHt(o.format(s)):XMe(s);return e2(a)}).join(","));return[r,...n].join(`
440
440
  `)}function ezt(t,e){let r=e.split("."),n=t;for(let i of r){if(n==null||typeof n!="object")return;n=n[i]}return n}function et(t,e,r,n){let i=Xp(r),o=t.totalElements??t.data.length;switch(i){case"json":console.log(uK({...t,totalElements:o},r));break;case"csv":console.log(KHt(t.data,e));break;case"yaml":console.log((0,cK.stringify)({totalElements:o,totalPages:t.totalPages,truncated:t.truncated,...t.stats?{stats:t.stats}:{},data:t.data}).trimEnd());break;case"table":{console.log(R(`${n} (${t.data.length} of ${o}):
441
441
  `));let{items:s,overflow:a}=lK(t.data);if(s.length===0){console.log(" No results found.");return}console.log(gg(s,e)),a>0&&console.log(H(`
442
- ... and ${a.toLocaleString()} more (use --format json for full output)`));break}}}function bS(t,e){switch(Xp(e)){case"json":console.log(JSON.stringify(t,null,2));break;case"csv":{let n=Object.keys(t);console.log(n.map(e2).join(",")),console.log(n.map(i=>e2(XMe(t[i]))).join(","));break}case"yaml":console.log((0,cK.stringify)(t).trimEnd());break;case"table":console.log(WMe(t));break}}var cK,yg,dr=X(()=>{"use strict";Oe();sp();cK=sn(GMe(),1);aK();ln();ZMe();yg=class extends No{constructor(e){super(e),this.name="CliValidationError"}}});var tPe={};So(tPe,{displaySlice:()=>lK,paginatedFetch:()=>ot,paginatedJson:()=>uK});async function ot(t,e,r){let n=r.defaultLimit??100;if(t.all&&t.offset!==void 0)throw new Error("--all and --offset cannot be used together");if(t.all){let d=(t.format?.toLowerCase()??(t.json?"json":"table"))==="table"?iQe(r.label):void 0,f=t.maxRows??ePe,p=await Pp((y,C)=>e({limit:C,offset:y}),{pageSize:t.limit??200,maxItems:f,onProgress:d?(y,C)=>d.update(y,C):void 0});d?.clear();let{truncated:h}=p,{data:m}=p;m.length>f&&(m=m.slice(0,f),h=!0),h&&!Ml(t)&&console.error(ke(`Warning: dataset has ${p.totalElements.toLocaleString()} items \u2014 showing ${m.length.toLocaleString()} (max-rows: ${f.toLocaleString()})`));let A=t.limit??n,g=Math.ceil(p.totalElements/A);return{data:m,totalElements:p.totalElements,totalPages:g,truncated:h}}let i=t.limit??n,o=await e({limit:i,offset:t.offset??0}),s=o.data??[],a=(o.totalElements??0)>s.length;return{data:s,totalElements:o.totalElements??0,totalPages:o.totalPages??0,truncated:a}}function lK(t,e=tzt){return t.length<=e?{items:t,overflow:0}:{items:t.slice(0,e),overflow:t.length-e}}function uK(t,e){let{totalElements:r,totalPages:n,truncated:i,data:o,stats:s}=t,a=s?{stats:s}:{};if(i){let c=e.maxRows??ePe;return JSON.stringify({totalElements:r,totalPages:n,truncated:i,_meta:{fetchedRows:o.length,maxRows:c},...a,data:o},null,2)}return JSON.stringify({totalElements:r,totalPages:n,truncated:i,...a,data:o},null,2)}var ePe,tzt,ln=X(()=>{"use strict";Oe();HM();oQe();dr();ePe=1e3,tzt=500});async function rzt(){if(!dK){let[t,e,r,n]=await Promise.all([Promise.resolve().then(()=>(ft(),sPe)),Promise.resolve().then(()=>(ln(),tPe)),Promise.resolve().then(()=>(dr(),KMe)),Promise.resolve().then(()=>(_t(),awe))]);dK=t.apiAction,rPe=e.paginatedFetch,nPe=r.outputList,fK=n.parsePositiveInt,iPe=n.parseNonNegativeInt}}function Ye(t){let e=t.commandName??"search",r=t.positionalArg?` <${t.positionalArg}>`:"",n=t.parent.command(`${e}${r}`).description(`Search ${t.label.replace("Searching ","")}`);n.allowExcessArguments(!1);let i=new Map,o=lZ(t.fields);for(let[a,c,u,d]of o){let f=new Pt(a,c),p=t.fields[d];u&&p?.op!=="multi"&&f.choices(u),n.addOption(f);let h=nzt(a);h!==d&&i.set(h,d)}if(t.defaults.supportsQuery&&n.option("--query <expression>",'Jaz search expression (e.g. "status:unpaid AND $500+", "customer:acme AND date:-30d"). Merged with --filter; --filter fields win on conflict.'),n.option("--filter <json>","Raw API filter JSON (merged with flags; flags win on conflict)").addOption(new Pt("--sort <field>","Sort field name")).addOption(new Pt("--order <direction>","Sort direction").choices(["ASC","DESC"])).option("--limit <n>",`Max results (default ${t.defaults.defaultLimit})`).option("--offset <n>","Page number offset (0-indexed)").option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)").option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON"),t.defaults.supportsView&&n.addOption(new Pt("--view <tier>","Payload tier: 'lean' = summary rows; 'full' (default) = complete records").choices(["lean","full"])),t.pathParam&&t.pathParam!==t.positionalArg){let a=t.pathParam.replace(/([A-Z])/g,"-$1").toLowerCase();n.requiredOption(`--${a} <id>`,t.pathParamDescription??`${t.pathParam} (required)`)}let s=async(...a)=>{let c=t.positionalArg?a[0]:void 0,u=t.positionalArg?a[1]:a[0];c&&t.positionalArg&&(u[t.positionalArg]=c),await rzt(),await dK(async d=>{t.preProcess&&await t.preProcess(d,u),typeof u.limit=="string"&&(u.limit=fK(u.limit)),typeof u.offset=="string"&&(u.offset=iPe(u.offset)),typeof u.maxRows=="string"&&(u.maxRows=fK(u.maxRows));let f={...u};for(let[v,x]of i)f[v]!==void 0&&(f[x]=f[v]);let p;if(typeof u.filter=="string")try{p=JSON.parse(u.filter)}catch{throw new Error(`Invalid --filter JSON: ${u.filter}`)}let h=t.baseFilter?p?{...t.baseFilter,...p}:t.baseFilter:p,m=OD(f,t.fields,h),A;if(c&&t.positionalFilter){let v=t.positionalFilter(c);A=m?{...v,...m}:v}else A=m;let g={sortBy:[u.sort??t.defaults.sortBy],order:u.order??t.defaults.sortOrder},y=t.defaults.supportsQuery?u.query:void 0,C=t.defaults.supportsView?u.view:void 0,E=t.pathParam?({limit:v,offset:x})=>t.fetcher(d,u[t.pathParam],{filter:A,sort:g,limit:v,offset:x,query:y,view:C}):({limit:v,offset:x})=>t.fetcher(d,{filter:A,sort:g,limit:v,offset:x,query:y,view:C}),I=await rPe(u,E,{label:t.label,defaultLimit:t.defaults.defaultLimit});nPe(I,t.columns,u,t.label.replace("Searching ",""))})(u)};return n.action(s),n}function nzt(t){return t.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(r,n)=>n.toUpperCase())}var dK,rPe,nPe,fK,iPe,oPe=X(()=>{"use strict";is();uZ();YM()});var LC,MC,CS,IS,aPe=X(()=>{"use strict";ca();LC={reference:{path:"reference",op:"contains",type:"string",description:"Invoice reference number"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:xFe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact/customer name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:$M},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},MC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},CS=LC,IS=MC});var cPe,vS,wS,PC,_S,Kp,eh,lPe=X(()=>{"use strict";ca();cPe={reference:{path:"reference",op:"contains",type:"string",description:"Order reference number"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},vS={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:HFe},...cPe},wS={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:zFe},...cPe},PC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},_S=PC,Kp={name:{path:"name",op:"contains",type:"string",description:"Line item text/description"},reference:{path:"reference",op:"contains",type:"string",description:"Parent order reference"},orderId:{path:"btResourceId",op:"eq",type:"string",description:"Parent order resourceId"},contactName:{path:"contactName",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},status:{path:"status",op:"eq",type:"string",description:"Line item status"},account:{path:"organizationAccountName",op:"contains",type:"string",description:"Chart-of-account name on the line"},taxProfile:{path:"taxProfileName",op:"contains",type:"string",description:"Tax profile name on the line"},isOpen:{path:"isOpen",op:"boolean",type:"boolean",description:"Only open (unfulfilled) lines"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"totalItemAmount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"totalItemAmount",op:"lte",type:"number",description:"Maximum line amount"}},eh={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var th,UC,DS,uPe=X(()=>{"use strict";ca();th={reference:{path:"reference",op:"contains",type:"string",description:"Credit note reference"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:TFe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:$M},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},UC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},DS=UC});var SS,RS,dPe=X(()=>{"use strict";ca();SS={reference:{path:"reference",op:"contains",type:"string",description:"Journal reference"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:BFe},type:{path:"type",op:"multi",type:"string",description:"Journal type",enum:kFe},templateType:{path:"templateType",op:"multi",type:"string",description:"Template type",enum:NFe},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},internalNotes:{path:"internalNotes",op:"contains",type:"string",description:"Search internal notes"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},RS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var xS,TS,fPe=X(()=>{"use strict";ca();xS={name:{path:"name",op:"contains",type:"string",description:"Contact name"},email:{path:"email",op:"contains",type:"string",description:"Email address"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:UM},isCustomer:{path:"customer",op:"boolean",type:"boolean",description:"Filter to customers only",cliFlag:"--customer"},isSupplier:{path:"supplier",op:"boolean",type:"boolean",description:"Filter to suppliers only",cliFlag:"--supplier"},taxId:{path:"taxId",op:"contains",type:"string",description:"Tax ID"}},TS={sortBy:"name",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var sf,af,pK,BS,kS,pPe=X(()=>{"use strict";ca();sf={type:{path:"businessTransactionType",op:"multi",type:"string",description:"Transaction type",enum:qM},direction:{path:"direction",op:"eq",type:"string",description:"Direction (PAYIN or PAYOUT)",enum:sZ},status:{path:"businessTransactionStatus",op:"multi",type:"string",description:"Status",enum:PFe},reference:{path:"businessTransactionReference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},businessTransactionType:{path:"businessTransactionType",op:"multi",type:"string",description:"(alias for type)"}},af={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0},pK={magicSort:{type:"object",description:"Rank by match quality to a bank entry: {bankStatementEntryResourceId, magicSort:true}."},transactionType:{type:"string",enum:[...MFe],description:"Scope. Default ALL_CASHFLOWS."}},BS={type:{path:"businessTransactionType",op:"multi",type:"string",description:"Transaction type (SALE, PURCHASE, etc.)",enum:qM},direction:{path:"direction",op:"eq",type:"string",description:"Direction",enum:sZ},reference:{path:"businessTransactionReference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},businessTransactionType:{path:"businessTransactionType",op:"multi",type:"string",description:"(alias for type)",enum:qM},fromDate:{path:"valueDate",op:"gte",type:"string",description:"(alias for startDate)"},toDate:{path:"valueDate",op:"lte",type:"string",description:"(alias for endDate)"},accountResourceId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"(alias for accountId)"}},kS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20}});var NS,OS,hPe=X(()=>{"use strict";ca();NS={status:{path:"status",op:"multi",type:"string",description:"Status",enum:LFe},description:{path:"description",op:"contains",type:"string",description:"Description"},payer:{path:"extContactName",op:"contains",type:"string",description:"Payer/payee name"},reference:{path:"extReference",op:"contains",type:"string",description:"Bank reference",cliFlag:"--ref <reference>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"netAmount",op:"gte",type:"number",description:"Minimum net amount"},maxAmount:{path:"netAmount",op:"lte",type:"number",description:"Maximum net amount"}},OS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var FS,QS,mPe=X(()=>{"use strict";ca();FS={status:{path:"status",op:"multi",type:"string",description:"Status",enum:OFe},itemCategory:{path:"itemCategory",op:"eq",type:"string",description:"Category",enum:QFe},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale items only",cliFlag:"--sale"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase items only",cliFlag:"--purchase"}},QS={sortBy:"internalName",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var LS,MS,APe=X(()=>{"use strict";ca();LS={name:{path:"name",op:"contains",type:"string",description:"Asset name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:UFe},category:{path:"category",op:"eq",type:"string",description:"Category",enum:$Fe},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Asset type name"},startDate:{path:"purchaseDate",op:"gte",type:"string",description:"Purchase date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"purchaseDate",op:"lte",type:"string",description:"Purchase date to (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"purchaseAmount",op:"gte",type:"number",description:"Minimum purchase amount"},maxAmount:{path:"purchaseAmount",op:"lte",type:"number",description:"Maximum purchase amount"}},MS={sortBy:"name",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0}});var PS,US,gPe=X(()=>{"use strict";ca();PS={type:{path:"businessTransactionType",op:"eq",type:"string",description:"Transaction type (SALE, PURCHASE, JOURNAL_MANUAL)"},status:{path:"status",op:"multi",type:"string",description:"Scheduler status",enum:qFe},subscriptionStatus:{path:"subscriptionStatus",op:"multi",type:"string",description:"Subscription status",enum:jFe},schedulerType:{path:"schedulerType",op:"eq",type:"string",description:"Scheduler type"},interval:{path:"interval",op:"eq",type:"string",description:"Interval",enum:YFe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"}},US={sortBy:"nextScheduleDate",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0}});var $S,qS,yPe=X(()=>{"use strict";ca();$S={id:{path:"resourceId",op:"eq",type:"string",description:"Job ID (the jobId returned from bulk operations)",cliFlag:"--id"},status:{path:"status",op:"multi",type:"string",description:"Job status",enum:ZFe},type:{path:"jobType",op:"eq",type:"string",description:"Job type (e.g. UPSERT_CONTACTS, UPSERT_ITEMS, PROCESS_BANK_STATEMENT_FILES)",cliFlag:"--type"},fileName:{path:"fileName",op:"contains",type:"string",description:"File name (file-based jobs only)",cliFlag:"--file-name"},from:{path:"createdAt",op:"gte",type:"string",description:"On/after (ISO date)",cliFlag:"--from"},to:{path:"createdAt",op:"lte",type:"string",description:"On/before (ISO date)",cliFlag:"--to"}},qS={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20}});var jS,YS,EPe=X(()=>{"use strict";jS={name:{path:"name",op:"plain",type:"string",description:"Purchase item name"},reference:{path:"reference",op:"plain",type:"string",description:"Reference name"},currencyCode:{path:"currencyCode",op:"plain",type:"string",description:"Currency code (ISO 4217)"}},YS={sortBy:"name",sortOrder:"ASC",defaultLimit:20}});var HS,zS,hK,mK,bPe=X(()=>{"use strict";HS={catalogName:{path:"catalogName",op:"contains",type:"string",description:"Catalog name"},description:{path:"description",op:"contains",type:"string",description:"Catalog item description"},status:{path:"status",op:"multi",type:"string",description:"Record status (e.g. ACTIVE, INACTIVE)"},contactGroupResourceId:{path:"contactGroupResourceId",op:"eq",type:"string",description:"Contact group resourceId"}},zS={sortBy:"catalogName",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},hK={reportType:{path:"reportType",op:"eq",type:"string",description:"Report type"},reportCategory:{path:"reportCategory",op:"eq",type:"string",description:"Report category"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Only default templates",cliFlag:"--default"}},mK={sortBy:"reportType",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0}});async function t2(t,e){return t.search("/api/v1/claims/search",e)}async function r2(t,e){return t.get(`/api/v1/claims/${e}`)}async function n2(t,e){return t.post("/api/v1/claims",e)}async function i2(t,e,r){return t.put(`/api/v1/claims/${e}`,r)}async function o2(t,e){return t.delete(`/api/v1/claims/${e}`)}async function s2(t,e,r){return t.delete(`/api/v1/claims/${e}/attachments/${r}`)}async function a2(t,e){return t.post(`/api/v1/claims/${e}/submit`,{})}async function c2(t,e){return t.post(`/api/v1/claims/${e}/approve`,{})}async function l2(t,e,r){return t.post(`/api/v1/claims/${e}/reject`,{rejectionReason:r})}async function u2(t,e,r){return t.post(`/api/v1/claims/${e}/cancel`,{cancellationReason:r})}async function d2(t,e){return t.post(`/api/v1/claims/${e}/unpost`,{})}function GS(t){Ot(t,"resourceIds",500,"claims")}async function f2(t,e){return GS(e),t.post("/api/v1/claims/bulk/submit",{resourceIds:e})}async function p2(t,e){return GS(e),t.post("/api/v1/claims/bulk/approve",{resourceIds:e})}async function h2(t,e){return GS(e),t.post("/api/v1/claims/bulk/delete",{resourceIds:e})}async function m2(t,e,r){return GS(e),t.post("/api/v1/claims/bulk/reject",{resourceIds:e,rejectionReason:r})}async function A2(t,e,r){return GS(e),t.post("/api/v1/claims/bulk/cancel",{resourceIds:e,cancellationReason:r})}async function g2(t){let e=await t.get("/api/v1/claims/tracking-tags");return Array.isArray(e)?e:e?.data??[]}async function y2(t){let e=await t.get("/api/v1/claims/custom-field-values");return Array.isArray(e)?e:e?.data??[]}var CPe,E2=X(()=>{"use strict";En();CPe=["DRAFT","SUBMITTED","APPROVED","CONVERTED","REJECTED","CANCELLED"]});var JS,VS,izt,ozt,WS,ZS,XS,KS,eR,tR,rR,nR,IPe=X(()=>{"use strict";f_();m_();E2();JS={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:CPe},employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Vendor contact resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Approver user resourceId"},reference:{path:"reference",op:"contains",type:"string",description:"Claim reference"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (ISO 4217)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Value date on/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Value date on/before (YYYY-MM-DD)",cliFlag:"--to <date>"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},VS={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20},izt=["RECORDED","COMPLETED","CANCELLED","IN_PROGRESS","ACTION_NEEDED"],ozt=["DIRECT_ENTRY","DISBURSEMENT","REIMBURSEMENT_PAYOUT","ADVANCE"],WS={employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},employeeName:{path:"employeeName",op:"contains",type:"string",description:"Employee name"},reference:{path:"reference",op:"contains",type:"string",description:"Payout reference"},payoutStatus:{path:"payoutStatus",op:"multi",type:"string",description:"Payout status (comma-separated)",enum:izt},payoutType:{path:"payoutType",op:"multi",type:"string",description:"Payout type (comma-separated): DIRECT_ENTRY (books-only DCE), DISBURSEMENT (gateway direct-debit-backed), REIMBURSEMENT_PAYOUT, ADVANCE",enum:ozt}},ZS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20},XS={name:{path:"name",op:"contains",type:"string",description:"Claim type name"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default claim type"},expenseAccountResourceId:{path:"expenseAccountResourceId",op:"eq",type:"string",description:"Default expense account resourceId"},taxProfileResourceId:{path:"taxProfileResourceId",op:"eq",type:"string",description:"Default tax profile resourceId"}},KS={sortBy:"name",sortOrder:"ASC",defaultLimit:100},eR={name:{path:"name",op:"contains",type:"string",description:"Claim profile name"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Default approver user resourceId"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default profile"},minClaimAmount:{path:"minClaimAmount",op:"gte",type:"number",description:"Minimum claim total (>=)"},maxClaimAmount:{path:"maxClaimAmount",op:"lte",type:"number",description:"Maximum claim total (<=)"},maxPerPeriodAmount:{path:"maxPerPeriodAmount",op:"lte",type:"number",description:"Per-period spend cap (<=)"},perPeriod:{path:"perPeriod",op:"eq",type:"string",description:"Per-period window",enum:u_},employeeBalanceAccountResourceId:{path:"employeeBalanceAccountResourceId",op:"eq",type:"string",description:"Employee balance (liability) account resourceId"}},tR={sortBy:"name",sortOrder:"ASC",defaultLimit:100},rR={name:{path:"name",op:"contains",type:"string",description:"Posting rule name"},outerAxis:{path:"outerAxis",op:"eq",type:"string",description:"Outer grouping axis",enum:p_},innerAxis:{path:"innerAxis",op:"eq",type:"string",description:"Inner line-aggregation axis",enum:h_},defaultBankAccountResourceId:{path:"defaultBankAccountResourceId",op:"eq",type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{path:"defaultIncludeReimbursementPayout",op:"boolean",type:"boolean",description:"Creates reimbursement DCE by default"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default rule"}},nR={sortBy:"name",sortOrder:"ASC",defaultLimit:100}});var iR,oR,sR,aR,vPe=X(()=>{"use strict";A_();iR={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},userResourceId:{path:"userResourceId",op:"eq",type:"string",description:"Bound login user resourceId"},managerEmployeeResourceId:{path:"managerEmployeeResourceId",op:"eq",type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"}},oR={sortBy:"name",sortOrder:"ASC",defaultLimit:50},sR={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},employmentType:{path:"employmentType",op:"eq",type:"string",description:"Employment type",enum:xA},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"}},aR={sortBy:"name",sortOrder:"ASC",defaultLimit:50}});var cR,lR,uR,dR,fR,pR,hR,mR,AR,gR,yR,ER,bR,CR,AK,IR,vR,wR,_R,wPe=X(()=>{"use strict";ca();cR={name:{path:"name",op:"contains",type:"string",description:"Account name"},code:{path:"code",op:"contains",type:"string",description:"Account code"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:FFe},accountClass:{path:"accountClass",op:"eq",type:"string",description:"Account class",enum:GFe},accountType:{path:"accountType",op:"eq",type:"string",description:"Account type",enum:jM},controlFlag:{path:"controlFlag",op:"boolean",type:"boolean",description:"Control flag (system accounts)"}},lR={sortBy:"code",sortOrder:"ASC",defaultLimit:100,supportsQuery:!1},uR={query:{path:"tagName",op:"contains",type:"string",description:"Tag name"}},dR={sortBy:"tagName",sortOrder:"ASC",defaultLimit:100},fR={name:{path:"name",op:"contains",type:"string",description:"Tax profile name",cliFlag:"--name <name>"},taxTypeCode:{path:"taxTypeCode",op:"contains",type:"string",description:"Tax type code"},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale profiles"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase profiles"},appliesToSaleCreditNote:{path:"appliesToSaleCreditNote",op:"boolean",type:"boolean",description:"Filter to sale CN profiles"},appliesToPurchaseCreditNote:{path:"appliesToPurchaseCreditNote",op:"boolean",type:"boolean",description:"Filter to purchase CN profiles"}},pR={sortBy:"name",sortOrder:"ASC",defaultLimit:100,supportsQuery:!0},hR={title:{path:"title",op:"contains",type:"string",description:"Capsule title"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:WFe}},mR={sortBy:"title",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},AR={query:{path:"customFieldName",op:"contains",type:"string",description:"Custom field name",cliFlag:"--name <name>"},datatypeCode:{path:"datatypeCode",op:"eq",type:"string",description:"Data type",enum:JFe,cliFlag:"--type <type>"},customFieldName:{path:"customFieldName",op:"contains",type:"string",description:"(alias for query)"}},gR={sortBy:"customFieldName",sortOrder:"ASC",defaultLimit:100},yR={query:{path:"name",op:"contains",type:"string",description:"Group name"}},ER={sortBy:"name",sortOrder:"ASC",defaultLimit:100},bR={firstName:{path:"user.firstName",op:"contains",type:"string",description:"User first name"},lastName:{path:"user.lastName",op:"contains",type:"string",description:"User last name"},email:{path:"user.email",op:"contains",type:"string",description:"Email"},userType:{path:"userType",op:"eq",type:"string",description:"Access tier",enum:VFe},status:{path:"status",op:"multi",type:"string",description:"Status",enum:UM}},CR={sortBy:"user.FirstName",sortOrder:"ASC",defaultLimit:50},AK=t=>({or:{user:{firstName:{contains:t}},or:{user:{lastName:{contains:t}}}}}),IR={query:{path:"name",op:"contains",type:"string",description:"Rule name"},account:{path:"appliesToReconciliationAccount",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"}},vR={sortBy:"name",sortOrder:"ASC",defaultLimit:100},wR={query:{path:"type",op:"contains",type:"string",description:"Classifier type"}},_R={sortBy:"type",sortOrder:"ASC",defaultLimit:100}});var fr=X(()=>{"use strict";ca();YM();uZ();oPe();aPe();lPe();uPe();dPe();fPe();pPe();hPe();mPe();APe();gPe();yPe();EPe();bPe();IPe();vPe();wPe()});async function _Pe(t,e){return t.list("/api/v1/modules",e)}async function DPe(t,e){return t.get(`/api/v1/modules/${encodeURIComponent(e)}`)}var SPe=X(()=>{"use strict"});async function b2(t,e){return t.list("/api/v1/purchase-items",e)}async function C2(t,e){return t.get(`/api/v1/purchase-items/${encodeURIComponent(e)}`)}async function I2(t,e){return t.search("/api/v1/purchase-items/search",e)}var gK=X(()=>{"use strict"});async function v2(t,e){return t.list("/api/v1/invoices",e)}async function Po(t,e){let r=await t.get(`/api/v1/invoices/${e}`);return"data"in r&&typeof r.data=="object"?r:{data:r}}async function $C(t,e){return t.search("/api/v1/invoices/search",e)}async function Eg(t,e){return t.post("/api/v1/invoices",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function w2(t,e,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(fp)}:r,i=await bc(n,()=>Po(t,e));return t.put(`/api/v1/invoices/${e}`,i)}async function _2(t,e,r){return t.delete(`/api/v1/invoices/${e}`,r)}async function DR(t,e,r){return t.post(`/api/v1/invoices/${e}/payments`,{...r,currency:Sr(r.currency),saveAsDraft:r.saveAsDraft??!0})}async function SR(t,e){return t.post("/api/v1/scheduled/invoices",{...e,invoice:{...e.invoice,currency:Sr(e.invoice?.currency)}})}async function D2(t,e,r){return t.post(`/api/v1/invoices/${e}/credits`,{credits:r})}async function RR(t,e,r){let n=await bc({...r,resourceId:e,saveAsDraft:!1},()=>Po(t,e));return t.put(`/api/v1/invoices/${e}`,n)}async function S2(t,e){return t.get(`/api/v1/invoices/${e}/download`)}async function R2(t,e){let r=await t.get(`/api/v1/invoices/${e}/payments`);return{data:Array.isArray(r)?r:r.data??[]}}async function x2(t,e){let r=await t.get(`/api/v1/invoices/${e}/credits`);return{data:Array.isArray(r)?r:r.data??[]}}async function T2(t,e,r){await t.delete(`/api/v1/invoices/${e}/credits/${r}`)}async function B2(t,e){return ho(t,"/api/v1/invoices/bulk-upsert","invoices",e)}async function k2(t,e){return ho(t,"/api/v1/invoices/line-items/bulk-upsert","invoices",cp(e))}var bg=X(()=>{"use strict";Zw();DA();En();hr()});async function RPe(t,e,r){return t.list(`/api/v1/${Pl[e]}`,r)}async function cf(t,e,r){return t.get(`/api/v1/${Pl[e]}/${r}`)}async function N2(t,e,r){return t.search(`/api/v1/${Pl[e]}/search`,r)}async function O2(t,e,r){return t.search(`/api/v1/${Pl[e]}/line-items/search`,r)}async function xR(t,e){return t.post("/api/v1/sale-quotes",{...e,saveAsDraft:e.saveAsDraft??!0})}async function TR(t,e){return t.post("/api/v1/sale-orders",e)}async function F2(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/${r}/convert-to-invoice`,n)}async function Q2(t,e,r,n){return t.put(`/api/v1/${Pl[e]}/${r}`,n)}async function L2(t,e,r){await t.delete(`/api/v1/${Pl[e]}/${r}`)}async function M2(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/${r}/void`,n?{internalNotes:n}:{})}async function P2(t,e){return t.post(`/api/v1/sale-quotes/${e}/accept`,{})}async function U2(t,e){return t.post(`/api/v1/sale-orders/${e}/confirm`,{})}async function xPe(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/${r}/fast-fix`,{attributes:n})}async function TPe(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function BPe(t,e){return t.post("/api/v1/sale-quotes/bulk-accept",{resourceIds:e})}async function kPe(t,e){return t.post("/api/v1/sale-orders/bulk-confirm",{resourceIds:e})}async function NPe(t,e,r){return t.post(`/api/v1/${Pl[e]}/bulk-delete`,{resourceIds:r})}async function OPe(t,e){return t.post("/api/v1/sale-orders/line-items/bulk-upsert",{saleOrders:e})}var Pl,yK=X(()=>{"use strict";Pl={SALE_QUOTE:"sale-quotes",SALE_ORDER:"sale-orders"}});async function FPe(t,e,r){return t.list(`/api/v1/${Ul[e]}`,r)}async function lf(t,e,r){return t.get(`/api/v1/${Ul[e]}/${r}`)}async function $2(t,e,r){return t.search(`/api/v1/${Ul[e]}/search`,r)}async function q2(t,e,r){return t.search(`/api/v1/${Ul[e]}/line-items/search`,r)}async function BR(t,e){return t.post("/api/v1/purchase-requests",{...e,saveAsDraft:e.saveAsDraft??!0})}async function kR(t,e){return t.post("/api/v1/purchase-orders",{...e,saveAsDraft:e.saveAsDraft??!0})}async function j2(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/${r}/convert-to-bill`,n)}async function Y2(t,e,r,n){return t.put(`/api/v1/${Ul[e]}/${r}`,n)}async function H2(t,e,r){await t.delete(`/api/v1/${Ul[e]}/${r}`)}async function z2(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/${r}/void`,n?{internalNotes:n}:{})}async function G2(t,e){return t.post(`/api/v1/purchase-requests/${e}/accept`,{})}async function J2(t,e){return t.post(`/api/v1/purchase-orders/${e}/confirm`,{})}async function QPe(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/${r}/fast-fix`,{attributes:n})}async function LPe(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function MPe(t,e){return t.post("/api/v1/purchase-requests/bulk-accept",{resourceIds:e})}async function PPe(t,e){return t.post("/api/v1/purchase-orders/bulk-confirm",{resourceIds:e})}async function UPe(t,e,r){return t.post(`/api/v1/${Ul[e]}/bulk-delete`,{resourceIds:r})}async function $Pe(t,e){return t.post("/api/v1/purchase-orders/line-items/bulk-upsert",{purchaseOrders:e})}var Ul,EK=X(()=>{"use strict";Ul={PURCHASE_REQUEST:"purchase-requests",PURCHASE_ORDER:"purchase-orders"}});async function V2(t,e){return t.list("/api/v1/journals",e)}async function NR(t,e){return t.search("/api/v1/journals/search",e)}async function Cg(t,e){return t.post("/api/v1/journals",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function W2(t,e,r){return t.delete(`/api/v1/journals/${e}`,r)}async function $l(t,e){return t.get(`/api/v1/journals/${e}`)}async function qC(t,e,r){return t.put(`/api/v1/journals/${e}`,{...r,currency:Sr(r.currency),taxCurrency:Sr(r.taxCurrency)})}async function qPe(t,e,r){return t.put(`/api/v1/journals/${e}`,{...r,resourceId:e,saveAsDraft:!1})}async function OR(t,e){return t.post("/api/v1/scheduled/journals",e)}async function Z2(t,e){return ho(t,"/api/v1/journals/bulk-upsert","journals",e)}async function jPe(t,e){return ls(e,"resourceId","Pass the journal resourceId."),t.get(`/api/v1/journals/${encodeURIComponent(e)}/download`)}var Ig=X(()=>{"use strict";En();hr()});async function X2(t,e){return t.post("/api/v1/generate-reports/trial-balance",e)}async function K2(t,e){return t.post("/api/v1/generate-reports/balance-sheet",e)}async function eU(t,e){return t.post("/api/v1/generate-reports/profit-and-loss",e)}async function tU(t,e){return t.post("/api/v1/generate-reports/cashflow",e)}async function rU(t,e){return t.post("/api/v1/generate-reports/ar-summary-report",e)}async function nU(t,e){return t.post("/api/v1/generate-reports/ap-summary-report",e)}function jC(t,e){let{root:r,rows:n}=szt[e],i=t.data?.[r]??{},o=Array.isArray(i[n])?i[n]:[],s={current:0,lessThanOneMonth:0,oneMonth:0,twoMonths:0,threeMonths:0,older:0,total:0};for(let u of o)s.current+=u.currentIso??0,s.lessThanOneMonth+=u.lessThanOneMonthIso??0,s.oneMonth+=u.oneMonthIso??0,s.twoMonths+=u.twoMonthsIso??0,s.threeMonths+=u.threeMonthsIso??0,s.older+=u.olderIso??0,s.total+=u.balanceIso??0;let a=u=>Math.round(u*100)/100,c=i.startDate;return{reportType:e==="receivables"?"AGED_RECEIVABLES":"AGED_PAYABLES",organizationName:i.organizationName,asAt:typeof c=="number"?new Date(c).toISOString().slice(0,10):void 0,currencyCode:i.currencyCode,currencySymbol:i.currencySymbol,buckets:{current:a(s.current),lessThanOneMonth:a(s.lessThanOneMonth),oneMonth:a(s.oneMonth),twoMonths:a(s.twoMonths),threeMonths:a(s.threeMonths),older:a(s.older)},totalOutstanding:a(s.total),contactCount:o.length}}async function iU(t,e){return t.post("/api/v1/generate-reports/cash-balance",e)}async function oU(t,e){return t.post("/api/v1/generate-reports/general-ledger",e)}async function sU(t,e){return t.post("/api/v1/generate-reports/vat-ledger",e)}async function aU(t,e){return t.post("/api/v1/generate-reports/equity-movement",e)}async function cU(t,e){return t.post("/api/v1/generate-reports/bank-balance-summary",e)}async function lU(t,e){return t.post("/api/v1/generate-reports/bank-reconciliation-summary",e)}async function uU(t,e){return t.post("/api/v1/generate-reports/bank-reconciliation-details",e)}async function dU(t,e){return t.post("/api/v1/generate-reports/fixed-assets-summary",e)}async function fU(t,e){return t.post("/api/v1/generate-reports/fixed-assets-recon-summary",e)}async function pU(t,e){return t.post("/api/v1/generate-reports/ar-report",e)}async function hU(t){return t.get("/api/v1/ledger/highlights")}var szt,bK=X(()=>{"use strict";szt={receivables:{root:"generateAgedReceivablesReportGroupByContact",rows:"customerSummary"},payables:{root:"generateAgedPayablesReportGroupByContact",rows:"supplierSummary"}}});async function mU(t,e){return t.list("/api/v1/catalogs",e)}async function AU(t,e){return t.get(`/api/v1/catalogs/${encodeURIComponent(e)}`)}async function gU(t,e){return t.search("/api/v1/catalogs/search",e)}async function yU(t,e){return t.post("/api/v1/catalogs",e)}async function EU(t,e,r){return t.put(`/api/v1/catalogs/${encodeURIComponent(e)}`,r)}async function bU(t,e){await t.delete(`/api/v1/catalogs/${encodeURIComponent(e)}`)}var CK=X(()=>{"use strict"});async function YPe(t,e){return t.list("/api/v1/organization-report-template",e)}async function HPe(t,e){return t.get(`/api/v1/organization-report-template/${encodeURIComponent(e)}`)}async function zPe(t,e){return t.search("/api/v1/organization-report-template/search",e)}var GPe=X(()=>{"use strict"});async function CU(t,e){return t.list("/api/v1/customer-credit-notes",e)}async function za(t,e){return t.get(`/api/v1/customer-credit-notes/${e}`)}async function FR(t,e){return t.search("/api/v1/customer-credit-notes/search",e)}async function QR(t,e){return t.post("/api/v1/customer-credit-notes",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function IU(t,e,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(fp)}:r,i=await bc(n,()=>za(t,e));return t.put(`/api/v1/customer-credit-notes/${e}`,i)}async function LR(t,e,r){let n=await bc({...r,resourceId:e,saveAsDraft:!1},()=>za(t,e));return t.put(`/api/v1/customer-credit-notes/${e}`,n)}async function vU(t,e,r){return t.delete(`/api/v1/customer-credit-notes/${e}`,r)}async function MR(t,e,r){return t.post(`/api/v1/customer-credit-notes/${e}/refunds`,{...r,currency:Sr(r.currency),saveAsDraft:r.saveAsDraft??!0})}async function wU(t,e){return t.get(`/api/v1/customer-credit-notes/${e}/refunds`)}async function _U(t,e){return t.get(`/api/v1/customer-credit-notes/${e}/download`)}async function DU(t,e){return ho(t,"/api/v1/customer-credit-notes/bulk-upsert","customerCreditNotes",cp(e))}var SU=X(()=>{"use strict";Zw();DA();En();hr()});async function RU(t,e){return t.list("/api/v1/supplier-credit-notes",e)}async function Ga(t,e){return t.get(`/api/v1/supplier-credit-notes/${e}`)}async function PR(t,e){return t.search("/api/v1/supplier-credit-notes/search",e)}async function UR(t,e){return t.post("/api/v1/supplier-credit-notes",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function xU(t,e,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(fp)}:r,i=await bc(n,()=>Ga(t,e));return t.put(`/api/v1/supplier-credit-notes/${e}`,i)}async function $R(t,e,r){let n=await bc({...r,resourceId:e,saveAsDraft:!1},()=>Ga(t,e));return t.put(`/api/v1/supplier-credit-notes/${e}`,n)}async function TU(t,e,r){return t.delete(`/api/v1/supplier-credit-notes/${e}`,r)}async function BU(t,e){return t.get(`/api/v1/supplier-credit-notes/${e}/download`)}async function qR(t,e,r){return t.post(`/api/v1/supplier-credit-notes/${e}/refunds`,{...r,currency:Sr(r.currency),saveAsDraft:r.saveAsDraft??!0})}async function kU(t,e){return t.get(`/api/v1/supplier-credit-notes/${e}/refunds`)}async function NU(t,e){return ho(t,"/api/v1/supplier-credit-notes/bulk-upsert","supplierCreditNotes",cp(e))}var OU=X(()=>{"use strict";Zw();DA();En();hr()});async function jR(t){return t.get("/api/v1/organization/currencies")}async function FU(t,e){return t.post("/api/v1/organization/currencies",{currencies:e})}async function QU(t,e,r){return t.list(`/api/v1/organization/currencies/${e}/rates`,r)}function JPe(t){X9(t.rate,"rate");let e=Z9(t.rateDirection);return{...t,rateDirection:e}}async function LU(t,e,r){return t.post(`/api/v1/organization/currencies/${e}/rates`,JPe(r))}async function MU(t,e,r,n){return t.put(`/api/v1/organization/currencies/${e}/rates/${r}`,JPe(n))}async function PU(t,e){return t.post("/api/v1/organization/currencies/rates/bulk-upsert",{rates:e})}var UU=X(()=>{"use strict";hr()});var VPe=b((IK,vK)=>{(function(t,e){typeof define=="function"&&define.amd?define([],e):typeof vK=="object"&&typeof IK<"u"?vK.exports=e():t.Papa=e()})(IK,function t(){"use strict";var e=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof e<"u"?e:{}})();function r(){var D=e.URL||e.webkitURL||null,B=t.toString();return a.BLOB_URL||(a.BLOB_URL=D.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",B,")();"],{type:"text/javascript"})))}var n=!e.document&&!!e.postMessage,i=e.IS_PAPA_WORKER||!1,o={},s=0,a={};if(a.parse=u,a.unparse=d,a.RECORD_SEP="",a.UNIT_SEP="",a.BYTE_ORDER_MARK="\uFEFF",a.BAD_DELIMITERS=["\r",`
442
+ ... and ${a.toLocaleString()} more (use --format json for full output)`));break}}}function bS(t,e){switch(Xp(e)){case"json":console.log(JSON.stringify(t,null,2));break;case"csv":{let n=Object.keys(t);console.log(n.map(e2).join(",")),console.log(n.map(i=>e2(XMe(t[i]))).join(","));break}case"yaml":console.log((0,cK.stringify)(t).trimEnd());break;case"table":console.log(WMe(t));break}}var cK,yg,dr=X(()=>{"use strict";Oe();sp();cK=sn(GMe(),1);aK();ln();ZMe();yg=class extends No{constructor(e){super(e),this.name="CliValidationError"}}});var tPe={};So(tPe,{displaySlice:()=>lK,paginatedFetch:()=>ot,paginatedJson:()=>uK});async function ot(t,e,r){let n=r.defaultLimit??100;if(t.all&&t.offset!==void 0)throw new Error("--all and --offset cannot be used together");if(t.all){let d=(t.format?.toLowerCase()??(t.json?"json":"table"))==="table"?iQe(r.label):void 0,f=t.maxRows??ePe,p=await Pp((y,C)=>e({limit:C,offset:y}),{pageSize:t.limit??200,maxItems:f,onProgress:d?(y,C)=>d.update(y,C):void 0});d?.clear();let{truncated:h}=p,{data:m}=p;m.length>f&&(m=m.slice(0,f),h=!0),h&&!Ml(t)&&console.error(ke(`Warning: dataset has ${p.totalElements.toLocaleString()} items \u2014 showing ${m.length.toLocaleString()} (max-rows: ${f.toLocaleString()})`));let A=t.limit??n,g=Math.ceil(p.totalElements/A);return{data:m,totalElements:p.totalElements,totalPages:g,truncated:h}}let i=t.limit??n,o=await e({limit:i,offset:t.offset??0}),s=o.data??[],a=(o.totalElements??0)>s.length;return{data:s,totalElements:o.totalElements??0,totalPages:o.totalPages??0,truncated:a}}function lK(t,e=tzt){return t.length<=e?{items:t,overflow:0}:{items:t.slice(0,e),overflow:t.length-e}}function uK(t,e){let{totalElements:r,totalPages:n,truncated:i,data:o,stats:s}=t,a=s?{stats:s}:{};if(i){let c=e.maxRows??ePe;return JSON.stringify({totalElements:r,totalPages:n,truncated:i,_meta:{fetchedRows:o.length,maxRows:c},...a,data:o},null,2)}return JSON.stringify({totalElements:r,totalPages:n,truncated:i,...a,data:o},null,2)}var ePe,tzt,ln=X(()=>{"use strict";Oe();HM();oQe();dr();ePe=1e3,tzt=500});async function rzt(){if(!dK){let[t,e,r,n]=await Promise.all([Promise.resolve().then(()=>(ft(),sPe)),Promise.resolve().then(()=>(ln(),tPe)),Promise.resolve().then(()=>(dr(),KMe)),Promise.resolve().then(()=>(_t(),awe))]);dK=t.apiAction,rPe=e.paginatedFetch,nPe=r.outputList,fK=n.parsePositiveInt,iPe=n.parseNonNegativeInt}}function Ye(t){let e=t.commandName??"search",r=t.positionalArg?` <${t.positionalArg}>`:"",n=t.parent.command(`${e}${r}`).description(`Search ${t.label.replace("Searching ","")}`);n.allowExcessArguments(!1);let i=new Map,o=lZ(t.fields);for(let[a,c,u,d]of o){let f=new Pt(a,c),p=t.fields[d];u&&p?.op!=="multi"&&f.choices(u),n.addOption(f);let h=nzt(a);h!==d&&i.set(h,d)}if(t.defaults.supportsQuery&&n.option("--query <expression>",'Jaz search expression (e.g. "status:unpaid AND $500+", "customer:acme AND date:-30d"). Merged with --filter; --filter fields win on conflict.'),n.option("--filter <json>","Raw API filter JSON (merged with flags; flags win on conflict)").addOption(new Pt("--sort <field>","Sort field name")).addOption(new Pt("--order <direction>","Sort direction").choices(["ASC","DESC"])).option("--limit <n>",`Max results (default ${t.defaults.defaultLimit})`).option("--offset <n>","Page number offset (0-indexed)").option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)").option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON"),t.defaults.supportsView&&n.addOption(new Pt("--view <tier>","Payload tier: 'lean' = summary rows; 'full' (default) = complete records").choices(["lean","full"])),t.pathParam&&t.pathParam!==t.positionalArg){let a=t.pathParam.replace(/([A-Z])/g,"-$1").toLowerCase();n.requiredOption(`--${a} <id>`,t.pathParamDescription??`${t.pathParam} (required)`)}let s=async(...a)=>{let c=t.positionalArg?a[0]:void 0,u=t.positionalArg?a[1]:a[0];c&&t.positionalArg&&(u[t.positionalArg]=c),await rzt(),await dK(async d=>{t.preProcess&&await t.preProcess(d,u),typeof u.limit=="string"&&(u.limit=fK(u.limit)),typeof u.offset=="string"&&(u.offset=iPe(u.offset)),typeof u.maxRows=="string"&&(u.maxRows=fK(u.maxRows));let f={...u};for(let[v,x]of i)f[v]!==void 0&&(f[x]=f[v]);let p;if(typeof u.filter=="string")try{p=JSON.parse(u.filter)}catch{throw new Error(`Invalid --filter JSON: ${u.filter}`)}let h=t.baseFilter?p?{...t.baseFilter,...p}:t.baseFilter:p,m=OD(f,t.fields,h),A;if(c&&t.positionalFilter){let v=t.positionalFilter(c);A=m?{...v,...m}:v}else A=m;let g={sortBy:[u.sort??t.defaults.sortBy],order:u.order??t.defaults.sortOrder},y=t.defaults.supportsQuery?u.query:void 0,C=t.defaults.supportsView?u.view:void 0,E=t.pathParam?({limit:v,offset:x})=>t.fetcher(d,u[t.pathParam],{filter:A,sort:g,limit:v,offset:x,query:y,view:C}):({limit:v,offset:x})=>t.fetcher(d,{filter:A,sort:g,limit:v,offset:x,query:y,view:C}),I=await rPe(u,E,{label:t.label,defaultLimit:t.defaults.defaultLimit});nPe(I,t.columns,u,t.label.replace("Searching ",""))})(u)};return n.action(s),n}function nzt(t){return t.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(r,n)=>n.toUpperCase())}var dK,rPe,nPe,fK,iPe,oPe=X(()=>{"use strict";is();uZ();YM()});var LC,MC,CS,IS,aPe=X(()=>{"use strict";ca();LC={reference:{path:"reference",op:"contains",type:"string",description:"Invoice reference number"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:xFe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact/customer name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:$M},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},MC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},CS=LC,IS=MC});var cPe,vS,wS,PC,_S,Kp,eh,lPe=X(()=>{"use strict";ca();cPe={reference:{path:"reference",op:"contains",type:"string",description:"Order reference number"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},vS={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:HFe},...cPe},wS={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:zFe},...cPe},PC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},_S=PC,Kp={name:{path:"name",op:"contains",type:"string",description:"Line item text/description"},reference:{path:"reference",op:"contains",type:"string",description:"Parent order reference"},orderId:{path:"btResourceId",op:"eq",type:"string",description:"Parent order resourceId"},contactName:{path:"contactName",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},status:{path:"status",op:"eq",type:"string",description:"Line item status"},account:{path:"organizationAccountName",op:"contains",type:"string",description:"Chart-of-account name on the line"},taxProfile:{path:"taxProfileName",op:"contains",type:"string",description:"Tax profile name on the line"},isOpen:{path:"isOpen",op:"boolean",type:"boolean",description:"Only open (unfulfilled) lines"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"totalItemAmount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"totalItemAmount",op:"lte",type:"number",description:"Maximum line amount"}},eh={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var th,UC,DS,uPe=X(()=>{"use strict";ca();th={reference:{path:"reference",op:"contains",type:"string",description:"Credit note reference"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:TFe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:$M},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},UC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},DS=UC});var SS,RS,dPe=X(()=>{"use strict";ca();SS={reference:{path:"reference",op:"contains",type:"string",description:"Journal reference"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:BFe},type:{path:"type",op:"multi",type:"string",description:"Journal type",enum:kFe},templateType:{path:"templateType",op:"multi",type:"string",description:"Template type",enum:NFe},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},internalNotes:{path:"internalNotes",op:"contains",type:"string",description:"Search internal notes"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},RS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var xS,TS,fPe=X(()=>{"use strict";ca();xS={name:{path:"name",op:"contains",type:"string",description:"Contact name"},email:{path:"email",op:"contains",type:"string",description:"Email address"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:UM},isCustomer:{path:"customer",op:"boolean",type:"boolean",description:"Filter to customers only",cliFlag:"--customer"},isSupplier:{path:"supplier",op:"boolean",type:"boolean",description:"Filter to suppliers only",cliFlag:"--supplier"},taxId:{path:"taxId",op:"contains",type:"string",description:"Tax ID"}},TS={sortBy:"name",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var sf,af,pK,BS,kS,pPe=X(()=>{"use strict";ca();sf={type:{path:"businessTransactionType",op:"multi",type:"string",description:"Transaction type",enum:qM},direction:{path:"direction",op:"eq",type:"string",description:"Direction (PAYIN or PAYOUT)",enum:sZ},status:{path:"businessTransactionStatus",op:"multi",type:"string",description:"Status",enum:PFe},reference:{path:"businessTransactionReference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},businessTransactionType:{path:"businessTransactionType",op:"multi",type:"string",description:"(alias for type)"}},af={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0},pK={magicSort:{type:"object",description:"Rank by match quality to a bank entry: {bankStatementEntryResourceId, magicSort:true}."},transactionType:{type:"string",enum:[...MFe],description:"Scope. Default ALL_CASHFLOWS."}},BS={type:{path:"businessTransactionType",op:"multi",type:"string",description:"Transaction type (SALE, PURCHASE, etc.)",enum:qM},direction:{path:"direction",op:"eq",type:"string",description:"Direction",enum:sZ},reference:{path:"businessTransactionReference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},businessTransactionType:{path:"businessTransactionType",op:"multi",type:"string",description:"(alias for type)",enum:qM},fromDate:{path:"valueDate",op:"gte",type:"string",description:"(alias for startDate)"},toDate:{path:"valueDate",op:"lte",type:"string",description:"(alias for endDate)"},accountResourceId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"(alias for accountId)"}},kS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20}});var NS,OS,hPe=X(()=>{"use strict";ca();NS={status:{path:"status",op:"multi",type:"string",description:"Status",enum:LFe},description:{path:"description",op:"contains",type:"string",description:"Description"},payer:{path:"extContactName",op:"contains",type:"string",description:"Payer/payee name"},reference:{path:"extReference",op:"contains",type:"string",description:"Bank reference",cliFlag:"--ref <reference>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"netAmount",op:"gte",type:"number",description:"Minimum net amount"},maxAmount:{path:"netAmount",op:"lte",type:"number",description:"Maximum net amount"}},OS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var FS,QS,mPe=X(()=>{"use strict";ca();FS={status:{path:"status",op:"multi",type:"string",description:"Status",enum:OFe},itemCategory:{path:"itemCategory",op:"eq",type:"string",description:"Category",enum:QFe},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale items only",cliFlag:"--sale"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase items only",cliFlag:"--purchase"}},QS={sortBy:"internalName",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var LS,MS,APe=X(()=>{"use strict";ca();LS={name:{path:"name",op:"contains",type:"string",description:"Asset name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:UFe},category:{path:"category",op:"eq",type:"string",description:"Category",enum:$Fe},tag:{path:"tags",op:"eq",type:"string",description:"Tag name",cliFlag:"--tag <name>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Asset type name"},startDate:{path:"purchaseDate",op:"gte",type:"string",description:"Purchase date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"purchaseDate",op:"lte",type:"string",description:"Purchase date to (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"purchaseAmount",op:"gte",type:"number",description:"Minimum purchase amount"},maxAmount:{path:"purchaseAmount",op:"lte",type:"number",description:"Maximum purchase amount"}},MS={sortBy:"name",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0}});var PS,US,gPe=X(()=>{"use strict";ca();PS={type:{path:"businessTransactionType",op:"eq",type:"string",description:"Transaction type (SALE, PURCHASE, JOURNAL_MANUAL)"},status:{path:"status",op:"multi",type:"string",description:"Scheduler status",enum:qFe},subscriptionStatus:{path:"subscriptionStatus",op:"multi",type:"string",description:"Subscription status",enum:jFe},schedulerType:{path:"schedulerType",op:"eq",type:"string",description:"Scheduler type"},interval:{path:"interval",op:"eq",type:"string",description:"Interval",enum:YFe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"}},US={sortBy:"nextScheduleDate",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0}});var $S,qS,yPe=X(()=>{"use strict";ca();$S={id:{path:"resourceId",op:"eq",type:"string",description:"Job ID (the jobId returned from bulk operations)",cliFlag:"--id"},status:{path:"status",op:"multi",type:"string",description:"Job status",enum:ZFe},type:{path:"jobType",op:"eq",type:"string",description:"Job type (e.g. UPSERT_CONTACTS, UPSERT_ITEMS, PROCESS_BANK_STATEMENT_FILES)",cliFlag:"--type"},fileName:{path:"fileName",op:"contains",type:"string",description:"File name (file-based jobs only)",cliFlag:"--file-name"},from:{path:"createdAt",op:"gte",type:"string",description:"On/after (ISO date)",cliFlag:"--from"},to:{path:"createdAt",op:"lte",type:"string",description:"On/before (ISO date)",cliFlag:"--to"}},qS={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20}});var jS,YS,EPe=X(()=>{"use strict";jS={name:{path:"name",op:"plain",type:"string",description:"Purchase item name"},reference:{path:"reference",op:"plain",type:"string",description:"Reference name"},currencyCode:{path:"currencyCode",op:"plain",type:"string",description:"Currency code (ISO 4217)"}},YS={sortBy:"name",sortOrder:"ASC",defaultLimit:20}});var HS,zS,hK,mK,bPe=X(()=>{"use strict";HS={catalogName:{path:"catalogName",op:"contains",type:"string",description:"Catalog name"},description:{path:"description",op:"contains",type:"string",description:"Catalog item description"},status:{path:"status",op:"multi",type:"string",description:"Record status (e.g. ACTIVE, INACTIVE)"},contactGroupResourceId:{path:"contactGroupResourceId",op:"eq",type:"string",description:"Contact group resourceId"}},zS={sortBy:"catalogName",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},hK={reportType:{path:"reportType",op:"plain",type:"string",description:"Report type"},reportCategory:{path:"reportCategory",op:"eq",type:"string",description:"Report category"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Only default templates",cliFlag:"--default"}},mK={sortBy:"reportType",sortOrder:"ASC",defaultLimit:20}});async function t2(t,e){return t.search("/api/v1/claims/search",e)}async function r2(t,e){return t.get(`/api/v1/claims/${e}`)}async function n2(t,e){return t.post("/api/v1/claims",e)}async function i2(t,e,r){return t.put(`/api/v1/claims/${e}`,r)}async function o2(t,e){return t.delete(`/api/v1/claims/${e}`)}async function s2(t,e,r){return t.delete(`/api/v1/claims/${e}/attachments/${r}`)}async function a2(t,e){return t.post(`/api/v1/claims/${e}/submit`,{})}async function c2(t,e){return t.post(`/api/v1/claims/${e}/approve`,{})}async function l2(t,e,r){return t.post(`/api/v1/claims/${e}/reject`,{rejectionReason:r})}async function u2(t,e,r){return t.post(`/api/v1/claims/${e}/cancel`,{cancellationReason:r})}async function d2(t,e){return t.post(`/api/v1/claims/${e}/unpost`,{})}function GS(t){Ot(t,"resourceIds",500,"claims")}async function f2(t,e){return GS(e),t.post("/api/v1/claims/bulk/submit",{resourceIds:e})}async function p2(t,e){return GS(e),t.post("/api/v1/claims/bulk/approve",{resourceIds:e})}async function h2(t,e){return GS(e),t.post("/api/v1/claims/bulk/delete",{resourceIds:e})}async function m2(t,e,r){return GS(e),t.post("/api/v1/claims/bulk/reject",{resourceIds:e,rejectionReason:r})}async function A2(t,e,r){return GS(e),t.post("/api/v1/claims/bulk/cancel",{resourceIds:e,cancellationReason:r})}async function g2(t){let e=await t.get("/api/v1/claims/tracking-tags");return Array.isArray(e)?e:e?.data??[]}async function y2(t){let e=await t.get("/api/v1/claims/custom-field-values");return Array.isArray(e)?e:e?.data??[]}var CPe,E2=X(()=>{"use strict";En();CPe=["DRAFT","SUBMITTED","APPROVED","CONVERTED","REJECTED","CANCELLED"]});var JS,VS,izt,ozt,WS,ZS,XS,KS,eR,tR,rR,nR,IPe=X(()=>{"use strict";f_();m_();E2();JS={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:CPe},employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Vendor contact resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Approver user resourceId"},reference:{path:"reference",op:"contains",type:"string",description:"Claim reference"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (ISO 4217)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Value date on/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Value date on/before (YYYY-MM-DD)",cliFlag:"--to <date>"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},VS={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20},izt=["RECORDED","COMPLETED","CANCELLED","IN_PROGRESS","ACTION_NEEDED"],ozt=["DIRECT_ENTRY","DISBURSEMENT","REIMBURSEMENT_PAYOUT","ADVANCE"],WS={employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},employeeName:{path:"employeeName",op:"contains",type:"string",description:"Employee name"},reference:{path:"reference",op:"contains",type:"string",description:"Payout reference"},payoutStatus:{path:"payoutStatus",op:"multi",type:"string",description:"Payout status (comma-separated)",enum:izt},payoutType:{path:"payoutType",op:"multi",type:"string",description:"Payout type (comma-separated): DIRECT_ENTRY (books-only DCE), DISBURSEMENT (gateway direct-debit-backed), REIMBURSEMENT_PAYOUT, ADVANCE",enum:ozt}},ZS={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20},XS={name:{path:"name",op:"contains",type:"string",description:"Claim type name"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default claim type"},expenseAccountResourceId:{path:"expenseAccountResourceId",op:"eq",type:"string",description:"Default expense account resourceId"},taxProfileResourceId:{path:"taxProfileResourceId",op:"eq",type:"string",description:"Default tax profile resourceId"}},KS={sortBy:"name",sortOrder:"ASC",defaultLimit:100},eR={name:{path:"name",op:"contains",type:"string",description:"Claim profile name"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Default approver user resourceId"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default profile"},minClaimAmount:{path:"minClaimAmount",op:"gte",type:"number",description:"Minimum claim total (>=)"},maxClaimAmount:{path:"maxClaimAmount",op:"lte",type:"number",description:"Maximum claim total (<=)"},maxPerPeriodAmount:{path:"maxPerPeriodAmount",op:"lte",type:"number",description:"Per-period spend cap (<=)"},perPeriod:{path:"perPeriod",op:"eq",type:"string",description:"Per-period window",enum:u_},employeeBalanceAccountResourceId:{path:"employeeBalanceAccountResourceId",op:"eq",type:"string",description:"Employee balance (liability) account resourceId"}},tR={sortBy:"name",sortOrder:"ASC",defaultLimit:100},rR={name:{path:"name",op:"contains",type:"string",description:"Posting rule name"},outerAxis:{path:"outerAxis",op:"eq",type:"string",description:"Outer grouping axis",enum:p_},innerAxis:{path:"innerAxis",op:"eq",type:"string",description:"Inner line-aggregation axis",enum:h_},defaultBankAccountResourceId:{path:"defaultBankAccountResourceId",op:"eq",type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{path:"defaultIncludeReimbursementPayout",op:"boolean",type:"boolean",description:"Creates reimbursement DCE by default"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default rule"}},nR={sortBy:"name",sortOrder:"ASC",defaultLimit:100}});var iR,oR,sR,aR,vPe=X(()=>{"use strict";A_();iR={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},userResourceId:{path:"userResourceId",op:"eq",type:"string",description:"Bound login user resourceId"},managerEmployeeResourceId:{path:"managerEmployeeResourceId",op:"eq",type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"}},oR={sortBy:"name",sortOrder:"ASC",defaultLimit:50},sR={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},employmentType:{path:"employmentType",op:"eq",type:"string",description:"Employment type",enum:xA},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"}},aR={sortBy:"name",sortOrder:"ASC",defaultLimit:50}});var cR,lR,uR,dR,fR,pR,hR,mR,AR,gR,yR,ER,bR,CR,AK,IR,vR,wR,_R,wPe=X(()=>{"use strict";ca();cR={name:{path:"name",op:"contains",type:"string",description:"Account name"},code:{path:"code",op:"contains",type:"string",description:"Account code"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:FFe},accountClass:{path:"accountClass",op:"eq",type:"string",description:"Account class",enum:GFe},accountType:{path:"accountType",op:"eq",type:"string",description:"Account type",enum:jM},controlFlag:{path:"controlFlag",op:"boolean",type:"boolean",description:"Control flag (system accounts)"}},lR={sortBy:"code",sortOrder:"ASC",defaultLimit:100,supportsQuery:!1},uR={query:{path:"tagName",op:"contains",type:"string",description:"Tag name"}},dR={sortBy:"tagName",sortOrder:"ASC",defaultLimit:100},fR={name:{path:"name",op:"contains",type:"string",description:"Tax profile name",cliFlag:"--name <name>"},taxTypeCode:{path:"taxTypeCode",op:"contains",type:"string",description:"Tax type code"},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale profiles"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase profiles"},appliesToSaleCreditNote:{path:"appliesToSaleCreditNote",op:"boolean",type:"boolean",description:"Filter to sale CN profiles"},appliesToPurchaseCreditNote:{path:"appliesToPurchaseCreditNote",op:"boolean",type:"boolean",description:"Filter to purchase CN profiles"}},pR={sortBy:"name",sortOrder:"ASC",defaultLimit:100,supportsQuery:!0},hR={title:{path:"title",op:"contains",type:"string",description:"Capsule title"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:WFe}},mR={sortBy:"title",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},AR={query:{path:"customFieldName",op:"contains",type:"string",description:"Custom field name",cliFlag:"--name <name>"},datatypeCode:{path:"datatypeCode",op:"eq",type:"string",description:"Data type",enum:JFe,cliFlag:"--type <type>"},customFieldName:{path:"customFieldName",op:"contains",type:"string",description:"(alias for query)"}},gR={sortBy:"customFieldName",sortOrder:"ASC",defaultLimit:100},yR={query:{path:"name",op:"contains",type:"string",description:"Group name"}},ER={sortBy:"name",sortOrder:"ASC",defaultLimit:100},bR={firstName:{path:"user.firstName",op:"contains",type:"string",description:"User first name"},lastName:{path:"user.lastName",op:"contains",type:"string",description:"User last name"},email:{path:"user.email",op:"contains",type:"string",description:"Email"},userType:{path:"userType",op:"eq",type:"string",description:"Access tier",enum:VFe},status:{path:"status",op:"multi",type:"string",description:"Status",enum:UM}},CR={sortBy:"user.FirstName",sortOrder:"ASC",defaultLimit:50},AK=t=>({or:{user:{firstName:{contains:t}},or:{user:{lastName:{contains:t}}}}}),IR={query:{path:"name",op:"contains",type:"string",description:"Rule name"},account:{path:"appliesToReconciliationAccount",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"}},vR={sortBy:"name",sortOrder:"ASC",defaultLimit:100},wR={query:{path:"type",op:"contains",type:"string",description:"Classifier type"}},_R={sortBy:"type",sortOrder:"ASC",defaultLimit:100}});var fr=X(()=>{"use strict";ca();YM();uZ();oPe();aPe();lPe();uPe();dPe();fPe();pPe();hPe();mPe();APe();gPe();yPe();EPe();bPe();IPe();vPe();wPe()});async function _Pe(t,e){return t.list("/api/v1/modules",e)}async function DPe(t,e){return t.get(`/api/v1/modules/${encodeURIComponent(e)}`)}var SPe=X(()=>{"use strict"});async function b2(t,e){return t.list("/api/v1/purchase-items",e)}async function C2(t,e){return t.get(`/api/v1/purchase-items/${encodeURIComponent(e)}`)}async function I2(t,e){return t.search("/api/v1/purchase-items/search",e)}var gK=X(()=>{"use strict"});async function v2(t,e){return t.list("/api/v1/invoices",e)}async function Po(t,e){let r=await t.get(`/api/v1/invoices/${e}`);return"data"in r&&typeof r.data=="object"?r:{data:r}}async function $C(t,e){return t.search("/api/v1/invoices/search",e)}async function Eg(t,e){return t.post("/api/v1/invoices",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function w2(t,e,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(fp)}:r,i=await bc(n,()=>Po(t,e));return t.put(`/api/v1/invoices/${e}`,i)}async function _2(t,e,r){return t.delete(`/api/v1/invoices/${e}`,r)}async function DR(t,e,r){return t.post(`/api/v1/invoices/${e}/payments`,{...r,currency:Sr(r.currency),saveAsDraft:r.saveAsDraft??!0})}async function SR(t,e){return t.post("/api/v1/scheduled/invoices",{...e,invoice:{...e.invoice,currency:Sr(e.invoice?.currency)}})}async function D2(t,e,r){return t.post(`/api/v1/invoices/${e}/credits`,{credits:r})}async function RR(t,e,r){let n=await bc({...r,resourceId:e,saveAsDraft:!1},()=>Po(t,e));return t.put(`/api/v1/invoices/${e}`,n)}async function S2(t,e){return t.get(`/api/v1/invoices/${e}/download`)}async function R2(t,e){let r=await t.get(`/api/v1/invoices/${e}/payments`);return{data:Array.isArray(r)?r:r.data??[]}}async function x2(t,e){let r=await t.get(`/api/v1/invoices/${e}/credits`);return{data:Array.isArray(r)?r:r.data??[]}}async function T2(t,e,r){await t.delete(`/api/v1/invoices/${e}/credits/${r}`)}async function B2(t,e){return ho(t,"/api/v1/invoices/bulk-upsert","invoices",e)}async function k2(t,e){return ho(t,"/api/v1/invoices/line-items/bulk-upsert","invoices",cp(e))}var bg=X(()=>{"use strict";Zw();DA();En();hr()});async function RPe(t,e,r){return t.list(`/api/v1/${Pl[e]}`,r)}async function cf(t,e,r){return t.get(`/api/v1/${Pl[e]}/${r}`)}async function N2(t,e,r){return t.search(`/api/v1/${Pl[e]}/search`,r)}async function O2(t,e,r){return t.search(`/api/v1/${Pl[e]}/line-items/search`,r)}async function xR(t,e){return t.post("/api/v1/sale-quotes",{...e,saveAsDraft:e.saveAsDraft??!0})}async function TR(t,e){return t.post("/api/v1/sale-orders",e)}async function F2(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/${r}/convert-to-invoice`,n)}async function Q2(t,e,r,n){return t.put(`/api/v1/${Pl[e]}/${r}`,n)}async function L2(t,e,r){await t.delete(`/api/v1/${Pl[e]}/${r}`)}async function M2(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/${r}/void`,n?{internalNotes:n}:{})}async function P2(t,e){return t.post(`/api/v1/sale-quotes/${e}/accept`,{})}async function U2(t,e){return t.post(`/api/v1/sale-orders/${e}/confirm`,{})}async function xPe(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/${r}/fast-fix`,{attributes:n})}async function TPe(t,e,r,n){return t.post(`/api/v1/${Pl[e]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function BPe(t,e){return t.post("/api/v1/sale-quotes/bulk-accept",{resourceIds:e})}async function kPe(t,e){return t.post("/api/v1/sale-orders/bulk-confirm",{resourceIds:e})}async function NPe(t,e,r){return t.post(`/api/v1/${Pl[e]}/bulk-delete`,{resourceIds:r})}async function OPe(t,e){return t.post("/api/v1/sale-orders/line-items/bulk-upsert",{saleOrders:e})}var Pl,yK=X(()=>{"use strict";Pl={SALE_QUOTE:"sale-quotes",SALE_ORDER:"sale-orders"}});async function FPe(t,e,r){return t.list(`/api/v1/${Ul[e]}`,r)}async function lf(t,e,r){return t.get(`/api/v1/${Ul[e]}/${r}`)}async function $2(t,e,r){return t.search(`/api/v1/${Ul[e]}/search`,r)}async function q2(t,e,r){return t.search(`/api/v1/${Ul[e]}/line-items/search`,r)}async function BR(t,e){return t.post("/api/v1/purchase-requests",{...e,saveAsDraft:e.saveAsDraft??!0})}async function kR(t,e){return t.post("/api/v1/purchase-orders",{...e,saveAsDraft:e.saveAsDraft??!0})}async function j2(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/${r}/convert-to-bill`,n)}async function Y2(t,e,r,n){return t.put(`/api/v1/${Ul[e]}/${r}`,n)}async function H2(t,e,r){await t.delete(`/api/v1/${Ul[e]}/${r}`)}async function z2(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/${r}/void`,n?{internalNotes:n}:{})}async function G2(t,e){return t.post(`/api/v1/purchase-requests/${e}/accept`,{})}async function J2(t,e){return t.post(`/api/v1/purchase-orders/${e}/confirm`,{})}async function QPe(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/${r}/fast-fix`,{attributes:n})}async function LPe(t,e,r,n){return t.post(`/api/v1/${Ul[e]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function MPe(t,e){return t.post("/api/v1/purchase-requests/bulk-accept",{resourceIds:e})}async function PPe(t,e){return t.post("/api/v1/purchase-orders/bulk-confirm",{resourceIds:e})}async function UPe(t,e,r){return t.post(`/api/v1/${Ul[e]}/bulk-delete`,{resourceIds:r})}async function $Pe(t,e){return t.post("/api/v1/purchase-orders/line-items/bulk-upsert",{purchaseOrders:e})}var Ul,EK=X(()=>{"use strict";Ul={PURCHASE_REQUEST:"purchase-requests",PURCHASE_ORDER:"purchase-orders"}});async function V2(t,e){return t.list("/api/v1/journals",e)}async function NR(t,e){return t.search("/api/v1/journals/search",e)}async function Cg(t,e){return t.post("/api/v1/journals",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function W2(t,e,r){return t.delete(`/api/v1/journals/${e}`,r)}async function $l(t,e){return t.get(`/api/v1/journals/${e}`)}async function qC(t,e,r){return t.put(`/api/v1/journals/${e}`,{...r,currency:Sr(r.currency),taxCurrency:Sr(r.taxCurrency)})}async function qPe(t,e,r){return t.put(`/api/v1/journals/${e}`,{...r,resourceId:e,saveAsDraft:!1})}async function OR(t,e){return t.post("/api/v1/scheduled/journals",e)}async function Z2(t,e){return ho(t,"/api/v1/journals/bulk-upsert","journals",e)}async function jPe(t,e){return ls(e,"resourceId","Pass the journal resourceId."),t.get(`/api/v1/journals/${encodeURIComponent(e)}/download`)}var Ig=X(()=>{"use strict";En();hr()});async function X2(t,e){return t.post("/api/v1/generate-reports/trial-balance",e)}async function K2(t,e){return t.post("/api/v1/generate-reports/balance-sheet",e)}async function eU(t,e){return t.post("/api/v1/generate-reports/profit-and-loss",e)}async function tU(t,e){return t.post("/api/v1/generate-reports/cashflow",e)}async function rU(t,e){return t.post("/api/v1/generate-reports/ar-summary-report",e)}async function nU(t,e){return t.post("/api/v1/generate-reports/ap-summary-report",e)}function jC(t,e){let{root:r,rows:n}=szt[e],i=t.data?.[r]??{},o=Array.isArray(i[n])?i[n]:[],s={current:0,lessThanOneMonth:0,oneMonth:0,twoMonths:0,threeMonths:0,older:0,total:0};for(let u of o)s.current+=u.currentIso??0,s.lessThanOneMonth+=u.lessThanOneMonthIso??0,s.oneMonth+=u.oneMonthIso??0,s.twoMonths+=u.twoMonthsIso??0,s.threeMonths+=u.threeMonthsIso??0,s.older+=u.olderIso??0,s.total+=u.balanceIso??0;let a=u=>Math.round(u*100)/100,c=i.startDate;return{reportType:e==="receivables"?"AGED_RECEIVABLES":"AGED_PAYABLES",organizationName:i.organizationName,asAt:typeof c=="number"?new Date(c).toISOString().slice(0,10):void 0,currencyCode:i.currencyCode,currencySymbol:i.currencySymbol,buckets:{current:a(s.current),lessThanOneMonth:a(s.lessThanOneMonth),oneMonth:a(s.oneMonth),twoMonths:a(s.twoMonths),threeMonths:a(s.threeMonths),older:a(s.older)},totalOutstanding:a(s.total),contactCount:o.length}}async function iU(t,e){return t.post("/api/v1/generate-reports/cash-balance",e)}async function oU(t,e){return t.post("/api/v1/generate-reports/general-ledger",e)}async function sU(t,e){return t.post("/api/v1/generate-reports/vat-ledger",e)}async function aU(t,e){return t.post("/api/v1/generate-reports/equity-movement",e)}async function cU(t,e){return t.post("/api/v1/generate-reports/bank-balance-summary",e)}async function lU(t,e){return t.post("/api/v1/generate-reports/bank-reconciliation-summary",e)}async function uU(t,e){return t.post("/api/v1/generate-reports/bank-reconciliation-details",e)}async function dU(t,e){return t.post("/api/v1/generate-reports/fixed-assets-summary",e)}async function fU(t,e){return t.post("/api/v1/generate-reports/fixed-assets-recon-summary",e)}async function pU(t,e){return t.post("/api/v1/generate-reports/ar-report",e)}async function hU(t){return t.get("/api/v1/ledger/highlights")}var szt,bK=X(()=>{"use strict";szt={receivables:{root:"generateAgedReceivablesReportGroupByContact",rows:"customerSummary"},payables:{root:"generateAgedPayablesReportGroupByContact",rows:"supplierSummary"}}});async function mU(t,e){return t.list("/api/v1/catalogs",e)}async function AU(t,e){return t.get(`/api/v1/catalogs/${encodeURIComponent(e)}`)}async function gU(t,e){return t.search("/api/v1/catalogs/search",e)}async function yU(t,e){return t.post("/api/v1/catalogs",e)}async function EU(t,e,r){return t.put(`/api/v1/catalogs/${encodeURIComponent(e)}`,r)}async function bU(t,e){await t.delete(`/api/v1/catalogs/${encodeURIComponent(e)}`)}var CK=X(()=>{"use strict"});async function YPe(t,e){return t.list("/api/v1/organization-report-template",e)}async function HPe(t,e){return t.get(`/api/v1/organization-report-template/${encodeURIComponent(e)}`)}async function zPe(t,e){return t.search("/api/v1/organization-report-template/search",e)}var GPe=X(()=>{"use strict"});async function CU(t,e){return t.list("/api/v1/customer-credit-notes",e)}async function za(t,e){return t.get(`/api/v1/customer-credit-notes/${e}`)}async function FR(t,e){return t.search("/api/v1/customer-credit-notes/search",e)}async function QR(t,e){return t.post("/api/v1/customer-credit-notes",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function IU(t,e,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(fp)}:r,i=await bc(n,()=>za(t,e));return t.put(`/api/v1/customer-credit-notes/${e}`,i)}async function LR(t,e,r){let n=await bc({...r,resourceId:e,saveAsDraft:!1},()=>za(t,e));return t.put(`/api/v1/customer-credit-notes/${e}`,n)}async function vU(t,e,r){return t.delete(`/api/v1/customer-credit-notes/${e}`,r)}async function MR(t,e,r){return t.post(`/api/v1/customer-credit-notes/${e}/refunds`,{...r,currency:Sr(r.currency),saveAsDraft:r.saveAsDraft??!0})}async function wU(t,e){return t.get(`/api/v1/customer-credit-notes/${e}/refunds`)}async function _U(t,e){return t.get(`/api/v1/customer-credit-notes/${e}/download`)}async function DU(t,e){return ho(t,"/api/v1/customer-credit-notes/bulk-upsert","customerCreditNotes",cp(e))}var SU=X(()=>{"use strict";Zw();DA();En();hr()});async function RU(t,e){return t.list("/api/v1/supplier-credit-notes",e)}async function Ga(t,e){return t.get(`/api/v1/supplier-credit-notes/${e}`)}async function PR(t,e){return t.search("/api/v1/supplier-credit-notes/search",e)}async function UR(t,e){return t.post("/api/v1/supplier-credit-notes",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency),saveAsDraft:e.saveAsDraft??!0})}async function xU(t,e,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(fp)}:r,i=await bc(n,()=>Ga(t,e));return t.put(`/api/v1/supplier-credit-notes/${e}`,i)}async function $R(t,e,r){let n=await bc({...r,resourceId:e,saveAsDraft:!1},()=>Ga(t,e));return t.put(`/api/v1/supplier-credit-notes/${e}`,n)}async function TU(t,e,r){return t.delete(`/api/v1/supplier-credit-notes/${e}`,r)}async function BU(t,e){return t.get(`/api/v1/supplier-credit-notes/${e}/download`)}async function qR(t,e,r){return t.post(`/api/v1/supplier-credit-notes/${e}/refunds`,{...r,currency:Sr(r.currency),saveAsDraft:r.saveAsDraft??!0})}async function kU(t,e){return t.get(`/api/v1/supplier-credit-notes/${e}/refunds`)}async function NU(t,e){return ho(t,"/api/v1/supplier-credit-notes/bulk-upsert","supplierCreditNotes",cp(e))}var OU=X(()=>{"use strict";Zw();DA();En();hr()});async function jR(t){return t.get("/api/v1/organization/currencies")}async function FU(t,e){return t.post("/api/v1/organization/currencies",{currencies:e})}async function QU(t,e,r){return t.list(`/api/v1/organization/currencies/${e}/rates`,r)}function JPe(t){X9(t.rate,"rate");let e=Z9(t.rateDirection);return{...t,rateDirection:e}}async function LU(t,e,r){return t.post(`/api/v1/organization/currencies/${e}/rates`,JPe(r))}async function MU(t,e,r,n){return t.put(`/api/v1/organization/currencies/${e}/rates/${r}`,JPe(n))}async function PU(t,e){return t.post("/api/v1/organization/currencies/rates/bulk-upsert",{rates:e})}var UU=X(()=>{"use strict";hr()});var VPe=b((IK,vK)=>{(function(t,e){typeof define=="function"&&define.amd?define([],e):typeof vK=="object"&&typeof IK<"u"?vK.exports=e():t.Papa=e()})(IK,function t(){"use strict";var e=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof e<"u"?e:{}})();function r(){var D=e.URL||e.webkitURL||null,B=t.toString();return a.BLOB_URL||(a.BLOB_URL=D.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",B,")();"],{type:"text/javascript"})))}var n=!e.document&&!!e.postMessage,i=e.IS_PAPA_WORKER||!1,o={},s=0,a={};if(a.parse=u,a.unparse=d,a.RECORD_SEP="",a.UNIT_SEP="",a.BYTE_ORDER_MARK="\uFEFF",a.BAD_DELIMITERS=["\r",`
443
443
  `,'"',a.BYTE_ORDER_MARK],a.WORKERS_SUPPORTED=!n&&!!e.Worker,a.NODE_STREAM_INPUT=1,a.LocalChunkSize=1024*1024*10,a.RemoteChunkSize=1024*1024*5,a.DefaultDelimiter=",",a.Parser=E,a.ParserHandle=y,a.NetworkStreamer=p,a.FileStreamer=h,a.StringStreamer=m,a.ReadableStreamStreamer=A,typeof PAPA_BROWSER_CONTEXT>"u"&&(a.DuplexStreamStreamer=g),e.jQuery){var c=e.jQuery;c.fn.parse=function(D){var B=D.config||{},L=[];return this.each(function(J){var W=c(this).prop("tagName").toUpperCase()==="INPUT"&&c(this).attr("type").toLowerCase()==="file"&&e.FileReader;if(!W||!this.files||this.files.length===0)return!0;for(var oe=0;oe<this.files.length;oe++)L.push({file:this.files[oe],inputElem:this,instanceConfig:c.extend({},B)})}),V(),this;function V(){if(L.length===0){j(D.complete)&&D.complete();return}var J=L[0];if(j(D.before)){var W=D.before(J.file,J.inputElem);if(typeof W=="object")if(W.action==="abort"){k("AbortError",J.file,J.inputElem,W.reason);return}else if(W.action==="skip"){U();return}else typeof W.config=="object"&&(J.instanceConfig=c.extend(J.instanceConfig,W.config));else if(W==="skip"){U();return}}var oe=J.instanceConfig.complete;J.instanceConfig.complete=function(me){j(oe)&&oe(me,J.file,J.inputElem),U()},a.parse(J.file,J.instanceConfig)}function k(J,W,oe,me){j(D.error)&&D.error({name:J},W,oe,me)}function U(){L.splice(0,1),V()}}}i&&(e.onmessage=O);function u(D,B){B=B||{};var L=B.dynamicTyping||!1;if(j(L)&&(B.dynamicTypingFunction=L,L={}),B.dynamicTyping=L,B.transform=j(B.transform)?B.transform:!1,B.worker&&a.WORKERS_SUPPORTED){var V=I();V.userStep=B.step,V.userChunk=B.chunk,V.userComplete=B.complete,V.userError=B.error,B.step=j(B.step),B.chunk=j(B.chunk),B.complete=j(B.complete),B.error=j(B.error),delete B.worker,V.postMessage({input:D,config:B,workerId:V.id});return}var k=null;if(D===a.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u")return k=new g(B),k.getStream();return typeof D=="string"?(D=U(D),B.download?k=new p(B):k=new m(B)):D.readable===!0&&j(D.read)&&j(D.on)?k=new A(B):(e.File&&D instanceof File||D instanceof Object)&&(k=new h(B)),k.stream(D);function U(J){return J.charCodeAt(0)===65279?J.slice(1):J}}function d(D,B){var L=!1,V=!0,k=",",U=`\r
444
444
  `,J='"',W=J+J,oe=!1,me=null,Re=!1;pt();var we=new RegExp(C(J),"g");if(typeof D=="string"&&(D=JSON.parse(D)),Array.isArray(D)){if(!D.length||Array.isArray(D[0]))return xe(null,D,oe);if(typeof D[0]=="object")return xe(me||Object.keys(D[0]),D,oe)}else if(typeof D=="object")return typeof D.data=="string"&&(D.data=JSON.parse(D.data)),Array.isArray(D.data)&&(D.fields||(D.fields=D.meta&&D.meta.fields||me),D.fields||(D.fields=Array.isArray(D.data[0])?D.fields:typeof D.data[0]=="object"?Object.keys(D.data[0]):[]),!Array.isArray(D.data[0])&&typeof D.data[0]!="object"&&(D.data=[D.data])),xe(D.fields||[],D.data||[],oe);throw new Error("Unable to serialize unrecognized input");function pt(){if(typeof B=="object"){if(typeof B.delimiter=="string"&&!a.BAD_DELIMITERS.filter(function(le){return B.delimiter.indexOf(le)!==-1}).length&&(k=B.delimiter),(typeof B.quotes=="boolean"||typeof B.quotes=="function"||Array.isArray(B.quotes))&&(L=B.quotes),(typeof B.skipEmptyLines=="boolean"||typeof B.skipEmptyLines=="string")&&(oe=B.skipEmptyLines),typeof B.newline=="string"&&(U=B.newline),typeof B.quoteChar=="string"&&(J=B.quoteChar),typeof B.header=="boolean"&&(V=B.header),Array.isArray(B.columns)){if(B.columns.length===0)throw new Error("Option columns is empty");me=B.columns}B.escapeChar!==void 0&&(W=B.escapeChar+J),B.escapeFormulae instanceof RegExp?Re=B.escapeFormulae:typeof B.escapeFormulae=="boolean"&&B.escapeFormulae&&(Re=/^[=+\-@\t\r].*$/)}}function xe(le,Ie,Ne){var He="";typeof le=="string"&&(le=JSON.parse(le)),typeof Ie=="string"&&(Ie=JSON.parse(Ie));var Lt=Array.isArray(le)&&le.length>0,Tt=!Array.isArray(Ie[0]);if(Lt&&V){for(var sr=0;sr<le.length;sr++)sr>0&&(He+=k),He+=Me(le[sr],sr);Ie.length>0&&(He+=U)}for(var Je=0;Je<Ie.length;Je++){var $e=Lt?le.length:Ie[Je].length,Et=!1,Pe=Lt?Object.keys(Ie[Je]).length===0:Ie[Je].length===0;if(Ne&&!Lt&&(Et=Ne==="greedy"?Ie[Je].join("").trim()==="":Ie[Je].length===1&&Ie[Je][0].length===0),Ne==="greedy"&&Lt){for(var Xe=[],tt=0;tt<$e;tt++){var Ke=Tt?le[tt]:tt;Xe.push(Ie[Je][Ke])}Et=Xe.join("").trim()===""}if(!Et){for(var ae=0;ae<$e;ae++){ae>0&&!Pe&&(He+=k);var K=Lt&&Tt?le[ae]:ae;He+=Me(Ie[Je][K],ae)}Je<Ie.length-1&&(!Ne||$e>0&&!Pe)&&(He+=U)}}return He}function Me(le,Ie){if(typeof le>"u"||le===null)return"";if(le.constructor===Date)return JSON.stringify(le).slice(1,25);var Ne=!1;Re&&typeof le=="string"&&Re.test(le)&&(le="'"+le,Ne=!0);var He=le.toString().replace(we,W);return Ne=Ne||L===!0||typeof L=="function"&&L(le,Ie)||Array.isArray(L)&&L[Ie]||fe(He,a.BAD_DELIMITERS)||He.indexOf(k)>-1||He.charAt(0)===" "||He.charAt(He.length-1)===" ",Ne?J+He+J:He}function fe(le,Ie){for(var Ne=0;Ne<Ie.length;Ne++)if(le.indexOf(Ie[Ne])>-1)return!0;return!1}}function f(D){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},B.call(this,D),this.parseChunk=function(L,V){let k=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&k>0){let Re=this._config.newline;if(!Re){let pt=this._config.quoteChar||'"';Re=this._handle.guessLineEndings(L,pt)}L=[...L.split(Re).slice(k)].join(Re)}if(this.isFirstChunk&&j(this._config.beforeFirstChunk)){var U=this._config.beforeFirstChunk(L);U!==void 0&&(L=U)}this.isFirstChunk=!1,this._halted=!1;var J=this._partialLine+L;this._partialLine="";var W=this._handle.parse(J,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var oe=W.meta.cursor;this._finished||(this._partialLine=J.substring(oe-this._baseIndex),this._baseIndex=oe),W&&W.data&&(this._rowCount+=W.data.length);var me=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(i)e.postMessage({results:W,workerId:a.WORKER_ID,finished:me});else if(j(this._config.chunk)&&!V){if(this._config.chunk(W,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}W=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(W.data),this._completeResults.errors=this._completeResults.errors.concat(W.errors),this._completeResults.meta=W.meta),!this._completed&&me&&j(this._config.complete)&&(!W||!W.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!me&&(!W||!W.meta.paused)&&this._nextChunk(),W},this._sendError=function(L){j(this._config.error)?this._config.error(L):i&&this._config.error&&e.postMessage({workerId:a.WORKER_ID,error:L,finished:!1})};function B(L){var V=N(L);V.chunkSize=parseInt(V.chunkSize),!L.step&&!L.chunk&&(V.chunkSize=null),this._handle=new y(V),this._handle.streamer=this,this._config=V}}function p(D){D=D||{},D.chunkSize||(D.chunkSize=a.RemoteChunkSize),f.call(this,D);var B;n?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(V){this._input=V,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(B=new XMLHttpRequest,this._config.withCredentials&&(B.withCredentials=this._config.withCredentials),n||(B.onload=z(this._chunkLoaded,this),B.onerror=z(this._chunkError,this)),B.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var V=this._config.downloadRequestHeaders;for(var k in V)B.setRequestHeader(k,V[k])}if(this._config.chunkSize){var U=this._start+this._config.chunkSize-1;B.setRequestHeader("Range","bytes="+this._start+"-"+U)}try{B.send(this._config.downloadRequestBody)}catch(J){this._chunkError(J.message)}n&&B.status===0&&this._chunkError()},this._chunkLoaded=function(){if(B.readyState===4){if(B.status<200||B.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:B.responseText.length,this._finished=!this._config.chunkSize||this._start>=L(B),this.parseChunk(B.responseText)}},this._chunkError=function(V){var k=B.statusText||V;this._sendError(new Error(k))};function L(V){var k=V.getResponseHeader("Content-Range");return k===null?-1:parseInt(k.substring(k.lastIndexOf("/")+1))}}p.prototype=Object.create(f.prototype),p.prototype.constructor=p;function h(D){D=D||{},D.chunkSize||(D.chunkSize=a.LocalChunkSize),f.call(this,D);var B,L,V=typeof FileReader<"u";this.stream=function(k){this._input=k,L=k.slice||k.webkitSlice||k.mozSlice,V?(B=new FileReader,B.onload=z(this._chunkLoaded,this),B.onerror=z(this._chunkError,this)):B=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){!this._finished&&(!this._config.preview||this._rowCount<this._config.preview)&&this._readChunk()},this._readChunk=function(){var k=this._input;if(this._config.chunkSize){var U=Math.min(this._start+this._config.chunkSize,this._input.size);k=L.call(k,this._start,U)}var J=B.readAsText(k,this._config.encoding);V||this._chunkLoaded({target:{result:J}})},this._chunkLoaded=function(k){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(k.target.result)},this._chunkError=function(){this._sendError(B.error)}}h.prototype=Object.create(f.prototype),h.prototype.constructor=h;function m(D){D=D||{},f.call(this,D);var B;this.stream=function(L){return B=L,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var L=this._config.chunkSize,V;return L?(V=B.substring(0,L),B=B.substring(L)):(V=B,B=""),this._finished=!B,this.parseChunk(V)}}}m.prototype=Object.create(m.prototype),m.prototype.constructor=m;function A(D){D=D||{},f.call(this,D);var B=[],L=!0,V=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(k){this._input=k,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){V&&B.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),B.length?this.parseChunk(B.shift()):L=!0},this._streamData=z(function(k){try{B.push(typeof k=="string"?k:k.toString(this._config.encoding)),L&&(L=!1,this._checkIsFinished(),this.parseChunk(B.shift()))}catch(U){this._streamError(U)}},this),this._streamError=z(function(k){this._streamCleanUp(),this._sendError(k)},this),this._streamEnd=z(function(){this._streamCleanUp(),V=!0,this._streamData("")},this),this._streamCleanUp=z(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}A.prototype=Object.create(f.prototype),A.prototype.constructor=A;function g(D){var B=P("stream").Duplex,L=N(D),V=!0,k=!1,U=[],J=null;this._onCsvData=function(W){var oe=W.data;!J.push(oe)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){J.push(null)},L.step=z(this._onCsvData,this),L.complete=z(this._onCsvComplete,this),f.call(this,L),this._nextChunk=function(){k&&U.length===1&&(this._finished=!0),U.length?U.shift()():V=!0},this._addToParseQueue=function(W,oe){U.push(z(function(){if(this.parseChunk(typeof W=="string"?W:W.toString(L.encoding)),j(oe))return oe()},this)),V&&(V=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(W,oe,me){this._addToParseQueue(W,me)},this._onWriteComplete=function(){k=!0,this._addToParseQueue("")},this.getStream=function(){return J},J=new B({readableObjectMode:!0,decodeStrings:!1,read:z(this._onRead,this),write:z(this._onWrite,this)}),J.once("finish",z(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(g.prototype=Object.create(f.prototype),g.prototype.constructor=g);function y(D){var B=Math.pow(2,53),L=-B,V=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,k=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,U=this,J=0,W=0,oe,me,Re=!1,we=!1,pt,xe=[],Me={data:[],errors:[],meta:{}};if(j(D.step)){var fe=D.step;D.step=function(Pe){if(Me=Pe,He())Ne();else{if(Ne(),Me.data.length===0)return;J+=Pe.data.length,D.preview&&J>D.preview?me.abort():(Me.data=Me.data[0],fe(Me,U))}}}this.parse=function(Pe,Xe,tt){var Ke=D.quoteChar||'"';if(D.newline||(D.newline=this.guessLineEndings(Pe,Ke)),pt=!1,D.delimiter)j(D.delimiter)&&(D.delimiter=D.delimiter(Pe),Me.meta.delimiter=D.delimiter);else{var ae=$e(Pe,D.newline,D.skipEmptyLines,D.comments,D.delimitersToGuess);ae.successful?D.delimiter=ae.bestDelimiter:(pt=!0,D.delimiter=a.DefaultDelimiter),Me.meta.delimiter=D.delimiter}var K=N(D);return D.preview&&D.header&&K.preview++,oe=Pe,me=new E(K),Me=me.parse(oe,Xe,tt),Ne(),Re?{meta:{paused:!0}}:Me||{meta:{paused:!1}}},this.paused=function(){return Re},this.pause=function(){Re=!0,me.abort(),oe=j(D.chunk)?"":oe.substring(me.getCharIndex())},this.resume=function(){U.streamer._halted?(Re=!1,U.streamer.parseChunk(oe,!0)):setTimeout(U.resume,3)},this.aborted=function(){return we},this.abort=function(){we=!0,me.abort(),Me.meta.aborted=!0,j(D.complete)&&D.complete(Me),oe=""},this.guessLineEndings=function(Pe,Xe){Pe=Pe.substring(0,1024*1024);var tt=new RegExp(C(Xe)+"([^]*?)"+C(Xe),"gm");Pe=Pe.replace(tt,"");var Ke=Pe.split("\r"),ae=Pe.split(`
445
445
  `),K=ae.length>1&&ae[0].length<Ke[0].length;if(Ke.length===1||K)return`
@@ -681,7 +681,7 @@ Call with { operation, arguments${o?`, ${nu}`:""}${a.length?", file":""}${t?", o
681
681
  `+r.map(u0).join(`
682
682
  `)+(t?`
683
683
 
684
- Multiple organizations are accessible: pass org_id (from list_organizations) to target one. Confirm the organization with the user before any create/update/delete.`:""),u={operation:{type:"string",enum:n,description:`The ${e.name} operation to run.`},arguments:{type:"object",description:"Parameters for the chosen operation (see the operation list above). Validated by the Jaz API.",additionalProperties:!0}};return o&&(u[nu]={type:"string",description:Hot}),a.length&&(u.file={type:"object",description:`A file from the conversation, when the client supports passing one. Accepted by: ${a.join(", ")}. The content is fetched server-side \u2014 leave source arguments out of \`arguments\`.`,properties:{download_url:{type:"string",description:"URL the file content can be fetched from (may be temporary)."},file_id:{type:"string",description:"Host-side file identifier."},mime_type:{type:"string"},file_name:{type:"string"}},required:["download_url"]}),t&&(u.org_id={type:"string",description:"The organization (resourceId from list_organizations) to run this operation against. Required when more than one organization is accessible."}),{name:e.name,description:c,inputSchema:{type:"object",properties:u,required:["operation"],additionalProperties:!1},...a.length?{_meta:{"openai/fileParams":["file"]}}:{},annotations:{title:`${e.title??Cwr(e.name)} \xB7 ${r.length} operation${r.length===1?"":"s"}`,readOnlyHint:i,destructiveHint:!i&&s,idempotentHint:i,openWorldHint:!1}}})}function Jot(t){return Iwr.has(t)}function Zfe(t,e){let r=xi.find(o=>o.name===t);if(!r)return{error:`Unknown namespace: ${t}.`};let n=Got(r.groups),i=n.find(o=>o.name===e||o.aliases?.includes(e));return i?{tool:i}:{error:`Unknown operation "${e}" for the ${t} tool.`,operations:n.map(o=>o.name)}}var Iwr,nk=X(()=>{"use strict";ud();dd();l0();O3();Iwr=new Set(xi.map(t=>t.name))});var Vot={};So(Vot,{loadAgentSuiteContent:()=>Rwr});import{readFileSync as vwr}from"node:fs";import{dirname as wwr,join as _wr}from"node:path";import{fileURLToPath as Dwr}from"node:url";function Rwr(){return Xfe||(Xfe=JSON.parse(vwr(_wr(Swr,"agent-suite-content.json"),"utf8"))),Xfe}var Swr,Xfe,Wot=X(()=>{"use strict";Swr=wwr(Dwr(import.meta.url)),Xfe=null});var Zot={};So(Zot,{buildCapabilityMap:()=>Twr});async function xwr(){try{let{loadAgentSuiteContent:t}=await Promise.resolve().then(()=>(Wot(),Vot)),e=t().counts;return{cli_command_groups:e.commands,api_rules:e.apiRules,skills:e.skills,ifrs_recipes:e.recipes,calculators:e.calculators,job_playbooks:e.jobs}}catch{return}}async function Twr(t={}){if(t.query&&t.query.trim())return B3(t.query);if(t.namespace){let r=xi.find(i=>i.name===t.namespace);if(!r)return{error:`Unknown namespace "${t.namespace}".`,namespaces:xi.map(i=>i.name),hint:"Call with no arguments for the full map, or pass `query` to rank operations by keyword."};let n=a0(r.groups);return{namespace:r.name,description:r.description,operations:n.length,operation_list:n.map(u0),hint:"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}}let e=Wy(t.surface,t.multiOrg);return{...e,map:t.full?tk().map(r=>({...r,operation_list:a0(xi.find(n=>n.name===r.namespace).groups).map(u0)})):e.map,beyond_mcp:await xwr()}}var Xot=X(()=>{"use strict";ud();nk();l0();R3()});import{randomUUID as Bwr}from"node:crypto";function ust(t,e,r){return{type:"object",description:`The ${t.toLowerCase()} to create. Required.`,properties:{reference:{type:"string",description:`${t} reference`},contactResourceId:{type:"string",description:`${e} UUID`},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:`${t} line items (max 500)`,items:{type:"object",properties:{name:{type:"string",description:"Line description"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:`${r} account UUID`},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}},required:["name"]}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:f0,adjustment:p0}},capsuleResourceId:{type:"string"}},required:["reference","lineItems"]}}function wst(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function Ar(t,e,r,n,i,o){let s={...cpe};return o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:t,description:e,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=wst(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0;return FD((h,m)=>n(a.client,h,m,f),u,d,f==="lean"?50:20)}}}function Ti(t,e,r,n,i,o){return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,a)=>n(s.client,a.resourceId)}}function _st(t,e,r,n){return{[e]:!0,...oZ(t),[r]:n}}function sk(t){return`Deletes a DRAFT ${t}; VOIDs an active one and KEEPS it. force: true hard-deletes either.`}function Xr(t,e,r,n,i,o){let s=o?.verb??"deleted";return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"},...o?.voidable?Mwr:{}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(a,c)=>{let u=c.resourceId;ls(u,"resourceId",`Nothing was deleted. Source a real resourceId from a search_* or list_* result before calling ${t}.`);let d=c.force,f=await n(a.client,u,{force:d,internalNotes:c.internalNotes});return o?.voidable?Oc(f,u,d):_st(f,s,"resourceId",u)}}}function ak(t,e,r,n){return{name:t,description:`Download ${/^[aeiou]/i.test(e)?"an":"a"} ${e} as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).`,params:{resourceId:{type:"string",description:`${e[0].toUpperCase()}${e.slice(1)} resourceId`}},required:["resourceId"],group:r,readOnly:!0,searchHint:`download ${e} as PDF document file`,isConcurrencySafe:!0,execute:async(i,o)=>n(i.client,o.resourceId)}}function ape(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function mst(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function Ywr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e)){if(i==null)continue;let o=tZ.get(n);if(o)r[o]=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else jwr.has(n)&&(r[n]=i)}return r}):t}async function ck(t,e,r,n){let s=(await(e==="invoice"?Po:e==="bill"?Oo:e==="customer_credit_note"?za:Ga)(t,r)).data,a=qwr[e],c={};for(let[p,h]of Object.entries(s))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=mst(c.valueDate)),c.dueDate&&(c.dueDate=mst(c.dueDate)),c.lineItems&&(c.lineItems=Ywr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?il:e==="bill"?Ea:ao,{missingFields:d,ready:f}=Js(c,u);if(!f)throw new Error(`Cannot finalize: missing ${d.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function Ast(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function P3(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function Est(t,e,r){let n=yst[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(yst).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function bst(t,e,r,n,i,o,s){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${s}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function Cst(t,e,r,n,i,o){let s;try{s=(await e(t,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function Ist(t,e,r,n,i){let o;try{o=(await e(t,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${o}; void it instead of deleting.`}}}var kwr,Kfe,rc,vo,iu,wo,fd,ui,pd,Q3,Xy,Kot,Nwr,est,tst,epe,tpe,d0,ik,Owr,Fwr,rpe,rst,nst,npe,cpe,ou,ipe,ist,ost,sst,ast,Qi,cst,ok,Qwr,ope,L3,ba,lst,vst,hd,f0,p0,Lwr,Mwr,dst,fst,pst,Pwr,Uwr,spe,hst,$wr,qwr,jwr,lk,uk,M3,gst,yst,jf,U3=X(()=>{"use strict";BM();EC();rZ();CFe();SFe();sg();kD();ka();fr();hr();vA();Fu();XE();SPe();gK();dp();bg();Ld();yK();EK();Ig();bK();Lp();t1();y1();o_();CK();GPe();SU();OU();UU();hit();a_();w1();f_();uz();m_();E2();Ez();Jde();Vde();Oz();Wde();ofe();lfe();Git();Lp();PB();ffe();pfe();Jz();sot();Cfe();Ife();vfe();lot();Sfe();Rm();Rfe();xD();xfe();Tfe();A_();H7();fot();yot();bot();cZ();Cot();Nfe();N8();Ofe();Ffe();Qfe();Lfe();Mfe();Pfe();Ufe();$fe();dp();bg();qfe();Ig();Oot();Ld();SU();OU();Ig();N8();En();Yfe();zfe();fr();Jfe();$ot();kwr=jM.join(" | "),Kfe=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"],rc={type:"string",description:"Resource ID of the record"},vo={type:"string",description:"Transaction date (YYYY-MM-DD)"},iu={type:"string",description:"Due date (YYYY-MM-DD)"},wo={type:"string",description:"Reference number"},fd={type:"boolean",description:"Use the org's own next number instead of `reference`."},ui={type:"string",description:"Notes or memo text"},pd={type:"string",description:"Tag name for categorization"},Q3={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},Xy={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Kot={recipe:{type:"string",enum:[...zy],description:"Recipe type"},amount:{type:"number",description:"Amount (for amortization, accrued-expense, dividend, ecl, provision, fx-reval)"},principal:{type:"number",description:"Principal (for loan, fixed-deposit)"},startDate:{type:"string",description:"Start date YYYY-MM-DD (REQUIRED for blueprint generation \u2014 default to today if user does not specify)"},currency:{type:"string",description:"Currency code (e.g. SGD, USD)"},periods:{type:"number",description:"Number of periods (for amortization, accrued-expense, leave-accrual)"},frequency:{type:"string",enum:["monthly","quarterly","annual"],description:"Frequency (for depreciation, amortization, accrued-expense)"},annualRate:{type:"number",description:"Annual interest/discount rate %"},termMonths:{type:"number"},monthlyPayment:{type:"number",description:"Monthly lease payment (for lease)"},usefulLifeMonths:{type:"number",description:"Asset useful life in months (hire purchase)"},cost:{type:"number",description:"Asset cost"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"],description:"Depreciation method"},acquisitionDate:{type:"string",description:"Acquisition date YYYY-MM-DD"},disposalDate:{type:"string",description:"Disposal date YYYY-MM-DD"},proceeds:{type:"number",description:"Disposal proceeds"},bookRate:{type:"number",description:"Original booking rate. Declare which way it reads via rateDirection (REQUIRED for fx-reval)."},closingRate:{type:"number",description:"Period-end closing rate. Same direction as bookRate."},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"REQUIRED for fx-reval. FUNCTIONAL_TO_SOURCE = 1 base unit = N foreign, what list_currency_rates returns. SOURCE_TO_FUNCTIONAL = 1 foreign unit = N base, the everyday quote."},position:{type:"string",enum:["ASSET","LIABILITY"],description:"Balance-sheet side: ASSET (receivable/deposit, default) or LIABILITY (payable/provision). A rising base value is a gain on an asset and a loss on a liability."},baseCurrency:{type:"string",description:"Base (functional) currency"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string"},balance:{type:"number"},rate:{type:"number"}},required:["name","balance","rate"]},description:"ECL aging buckets"},existingProvision:{type:"number",description:"Existing ECL provision balance"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number",description:"Leave days per employee per year"},dailyRate:{type:"number",description:"Average daily rate"},declarationDate:{type:"string",description:"Board resolution date YYYY-MM-DD"},paymentDate:{type:"string",description:"Settlement date YYYY-MM-DD"},withholdingRate:{type:"number",description:"Withholding tax rate %"}},Nwr={type:"boolean",description:"Retry-only: set true after the duplicate guard surfaced a candidate and the user confirmed this is a separate document. Never on a first attempt."},est={type:"string",enum:[...aZ],description:"CUSTOM (default) = free text; ALL_* = a picklist of that population. Datatype is derived, not chosen."},tst={type:"object",properties:{address:{type:"string",description:"Street address \u2014 sent as addressLine1"},city:{type:"string"},state:{type:"string"},postalCode:{type:"string"},country:{type:"string"}},required:["address","country"]},epe={type:"string",description:"Contact resourceId (customer or supplier)"},tpe={type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID)"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Draft entity type"}},required:["btResourceId","btType"]}},d0={type:"string",description:"Chart-of-accounts account the line posts to (revenue on a sale, expense on a purchase)"},ik={type:"string",description:"Account the payment posts to. For paymentMethod BANK_TRANSFER/CASH/CHEQUE this MUST be a bank or cash account. Any other method accepts any org account \u2014 that is how a deposit drawdown works (paymentMethod OTHER + the deposit account)."},Owr={type:"number",description:"Payment amount (in bank currency)"},Fwr={type:"string",description:"Period start date (YYYY-MM-DD)"},rpe={type:"string",description:"Period end date (YYYY-MM-DD)"},rst={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report") \u2014 it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},nst={type:"string",description:"Currency code (e.g. SGD, USD)"},npe={type:"string",description:"Display name"},cpe={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},ou={type:"object",required:["sourceCurrency"],properties:{sourceCurrency:{type:"string",description:"Foreign currency code (ISO 4217)."},exchangeRate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N sourceCurrency. Invert ONLY if your quote reads "1 source = X base" (send 1/X), or declare rateDirection and skip the arithmetic. Omit for the org/platform rate.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"How exchangeRate reads. SOURCE_TO_FUNCTIONAL accepts a bank quote verbatim. Default FUNCTIONAL_TO_SOURCE."}}},ipe={type:"string",enum:[...tf],description:"Entity type to export"},ist={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},ost={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},sst={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},ast={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},Qi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},cst={type:"array",description:"Full replacement line-item set \u2014 non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},ok={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},Qwr={type:"array",items:{type:"object",required:["resourceId","type","selectedClasses","printable"],properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",required:["className"],properties:{className:{type:"string"},resourceId:rc}}},printable:{type:"boolean",description:"Show on printed documents."}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},ope={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},L3={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Offset account resourceId"},amount:{type:"number",description:"Amount (positive; direction comes from the endpoint)"},description:{type:"string",description:"Line description"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId"}},required:["accountResourceId","amount"]},description:"Offset lines. No `type` \u2014 cash-in credits these and cash-out debits them, decided by the endpoint."},ba={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:d0,taxProfileResourceId:{type:"string"},classifierConfig:Qwr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},lst={type:"array",items:{type:"object",properties:{itemName:{type:"string",description:"Display name of the catalog item"},itemResourceId:{type:"string",description:"Underlying item resourceId (from search_items)"},price:{type:"number",description:"Default unit price (0-1e9)"},unit:{type:"string",description:"Unit of measure"},quantityDefault:{type:"number",description:"Default quantity when added to a document (0-100)"},discountDefault:{type:"number",description:"Default discount % when added to a document (0-100)"},uiIndex:{type:"number",description:"Display position in the catalog (integer, min 0)"},classifiers:{type:"array",items:{type:"object"},description:"Classifier assignments. Same shape as classifierConfig on invoice/bill line items."}},required:["itemName","itemResourceId","price"]},description:"Catalog item rows. itemName, itemResourceId and price are required on every row."},vst={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},hd={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",enum:["LOAN_AMORTIZATION","ACCRUAL_REVERSAL","PREPAID_AMORTIZATION","DEFERRED_REVENUE","IFRS16_LEASE"],description:"Must match mutation's allowedBaseTransactionTypes (see list_capsule_recipes)."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:vst},required:["recipeName","inputs"]},f0={type:"string",enum:[...XFe],description:"Payment method (default BANK_TRANSFER)"},p0={type:"object",description:"Cash-leg adjustment (overpayment/rounding). Bank leg only, never AR/AP. Not with DEBT_WRITE_OFF/CLEARING_SETTLEMENT/INTER_COMPANY/WITHHOLDING_TAX_CERTIFICATE. See rule 160.",properties:{adjustmentValue:{type:"number",description:"Signed, non-zero, max 2dp"},adjustmentAccountResourceId:{type:"string",description:"Non-controlled account, not bank/cash"},adjustmentDescription:{type:"string",description:"Optional"}},required:["adjustmentValue","adjustmentAccountResourceId"]},Lwr={...p0,description:"Adding or changing an adjustment applies here. REMOVING does not: 0 is rejected and null reads as omitted, so both leave the stored value unchanged. To remove one, delete the payment and record it again. A change is rejected if the payment is reconciled or lock-dated, and amount, account and description are all compared, so resend all three unchanged if you are not editing it. See rule 160."};Mwr={force:{type:"boolean",description:iZ.force},internalNotes:{type:"string",description:iZ.internalNotes}};dst={type:"string",description:"Document family",enum:[...Vy]},fst={type:"string",description:"Document family",enum:[...o0]},pst={type:"string",description:"Why it is sent back. Opens a thread; the only record of the reason."},Pwr=[{name:"approve_documents",description:"Approve one document awaiting approval. Posts its ledger entries and makes it live. One-shot, and the refusal channel differs by entity: invoices/bills THROW 422; credit notes return 200 with isSuccess:false and a STALE approvalStatus of APPROVED. Check isSuccess and catch the throw \u2014 approvalStatus alone cannot tell refusal from success.",params:{entity:dst,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"approvals",readOnly:!1,searchHint:"approve pending invoice bill credit note post ledger",execute:async(t,e)=>c3(t.client,e.entity,e.resourceId)},{name:"bulk_approve_documents",description:"Approve up to 100 documents awaiting approval. Async \u2014 returns a jobId; poll search_background_jobs. Each approval posts a ledger.",params:{entity:dst,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-100)"}},required:["entity","resourceIds"],group:"approvals",readOnly:!1,searchHint:"bulk approve many pending documents at once",execute:async(t,e)=>l3(t.client,e.entity,e.resourceIds)},{name:"request_document_changes",description:"Send one document back for changes instead of approving it. Also covers orders, quotes, requests and claims.",params:{entity:fst,resourceId:{type:"string",description:"Document resourceId"},message:pst},required:["entity","resourceId","message"],group:"approvals",readOnly:!1,searchHint:"request changes reject send back document for revision",execute:async(t,e)=>u3(t.client,e.entity,e.resourceId,e.message)},{name:"bulk_request_document_changes",description:"Send up to 500 documents back for changes with one message. Async \u2014 returns a jobId; poll search_background_jobs.",params:{entity:fst,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-500)"},message:pst},required:["entity","resourceIds","message"],group:"approvals",readOnly:!1,searchHint:"bulk request changes send back many documents",execute:async(t,e)=>d3(t.client,e.entity,e.resourceIds,e.message)}],Uwr=["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"],spe={type:"string",description:"Document family",enum:Uwr},hst={type:"string",description:"Version id from get_document_version_history"},$wr=[{name:"get_document_version_history",description:"The stored versions of a document, newest first. Not paginated. Use before restoring to pick a version id.",params:{entity:spe,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"versions",readOnly:!0,searchHint:"list document version history revisions audit trail",isConcurrencySafe:!0,execute:async(t,e)=>Tot(t.client,e.entity,e.resourceId)},{name:"get_document_version",description:"Read one stored version of a document. An unknown resourceId/version pair returns 422.",params:{entity:spe,resourceId:{type:"string",description:"Document resourceId"},version:hst},required:["entity","resourceId","version"],group:"versions",readOnly:!0,searchHint:"get read one document version snapshot",isConcurrencySafe:!0,execute:async(t,e)=>Bot(t.client,e.entity,e.resourceId,e.version)},{name:"rollback_document_version",description:"Restore a document to a stored version. REPLACES current state \u2014 read the version first with get_document_version. `CREATED` is NOT a restorable version and is refused: upstream DELETES the document for it and still answers 200.",params:{entity:spe,resourceId:{type:"string",description:"Document resourceId"},version:hst},required:["entity","resourceId","version"],group:"versions",readOnly:!1,searchHint:"restore rollback document to previous version undo changes",isDestructive:!0,execute:async(t,e)=>kot(t.client,e.entity,e.resourceId,e.version)},{name:"get_currency_effective_rate",description:"The organization effective rate for a currency on a date: its own custom rate when set, else the platform daily rate. Defaults to today.",params:{currencyCode:{type:"string",description:"ISO 4217 code, e.g. USD (not a resourceId)"},date:{type:"string",description:"YYYY-MM-DD (optional, defaults to today)"}},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"currency effective exchange rate for a date custom or platform",isConcurrencySafe:!0,execute:async(t,e)=>Not(t.client,e.currencyCode,e.date)}];qwr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};jwr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);lk={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},uk={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},M3={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},gst={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},yst={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};jf=[{name:"get_next_reference",description:"Next document number in the org's own series. Same number the web app prefills. Reading does NOT reserve it \u2014 two callers reading at once get the same value. Date embedded is always today. Never invent a reference; use this.",params:{type:{type:"string",description:"Document family whose next number is wanted.",enum:[...W7]}},required:["type"],group:"organization",readOnly:!0,noCache:!0,searchHint:"next reference number document numbering series auto reference",isConcurrencySafe:!0,maxResultSizeChars:5e3,execute:async(t,e)=>Z7(t.client,e.type)},{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>Na(t.client)},{name:"get_my_context",description:"Resolve the CALLER's own context \u2014 identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side \u2014 no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>X0e(t.client)},Ar("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>Md(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),Zt({name:"search_accounts",description:'Search chart of accounts. For OR (name or code), use filter: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:cR,defaults:lR,fetcher:ZE,searchHint:"find accounts chart of accounts CoA by name code type class status OR search"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name \u2014 returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:`Exact API string: ${kwr}. COGS = "Direct Costs". Common variants normalized client-side. "interest expense"/"interest income" is NOT auto-classified \u2014 ask, do not infer: Finance/Financing, Investing or Operating by main business activity.`},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(t,e)=>{let r=e.name,n=await H1(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=KE(e.accountType);return r_(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode,lockDate:e.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(t,e)=>{let r=e.resourceId,n=(await r1(t.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=e.clearLockDate===!0;if(s&&e.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),e.name!==void 0&&(o.name=e.name),e.code!==void 0&&(o.code=e.code),!s&&e.lockDate!==void 0&&(o.lockDate=e.lockDate),Nwe(t.client,r,o)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
684
+ Multiple organizations are accessible: pass org_id (from list_organizations) to target one. Confirm the organization with the user before any create/update/delete.`:""),u={operation:{type:"string",enum:n,description:`The ${e.name} operation to run.`},arguments:{type:"object",description:"Parameters for the chosen operation (see the operation list above). Validated by the Jaz API.",additionalProperties:!0}};return o&&(u[nu]={type:"string",description:Hot}),a.length&&(u.file={type:"object",description:`A file from the conversation, when the client supports passing one. Accepted by: ${a.join(", ")}. The content is fetched server-side \u2014 leave source arguments out of \`arguments\`.`,properties:{download_url:{type:"string",description:"URL the file content can be fetched from (may be temporary)."},file_id:{type:"string",description:"Host-side file identifier."},mime_type:{type:"string"},file_name:{type:"string"}},required:["download_url"]}),t&&(u.org_id={type:"string",description:"The organization (resourceId from list_organizations) to run this operation against. Required when more than one organization is accessible."}),{name:e.name,description:c,inputSchema:{type:"object",properties:u,required:["operation"],additionalProperties:!1},...a.length?{_meta:{"openai/fileParams":["file"]}}:{},annotations:{title:`${e.title??Cwr(e.name)} \xB7 ${r.length} operation${r.length===1?"":"s"}`,readOnlyHint:i,destructiveHint:!i&&s,idempotentHint:i,openWorldHint:!1}}})}function Jot(t){return Iwr.has(t)}function Zfe(t,e){let r=xi.find(o=>o.name===t);if(!r)return{error:`Unknown namespace: ${t}.`};let n=Got(r.groups),i=n.find(o=>o.name===e||o.aliases?.includes(e));return i?{tool:i}:{error:`Unknown operation "${e}" for the ${t} tool.`,operations:n.map(o=>o.name)}}var Iwr,nk=X(()=>{"use strict";ud();dd();l0();O3();Iwr=new Set(xi.map(t=>t.name))});var Vot={};So(Vot,{loadAgentSuiteContent:()=>Rwr});import{readFileSync as vwr}from"node:fs";import{dirname as wwr,join as _wr}from"node:path";import{fileURLToPath as Dwr}from"node:url";function Rwr(){return Xfe||(Xfe=JSON.parse(vwr(_wr(Swr,"agent-suite-content.json"),"utf8"))),Xfe}var Swr,Xfe,Wot=X(()=>{"use strict";Swr=wwr(Dwr(import.meta.url)),Xfe=null});var Zot={};So(Zot,{buildCapabilityMap:()=>Twr});async function xwr(){try{let{loadAgentSuiteContent:t}=await Promise.resolve().then(()=>(Wot(),Vot)),e=t().counts;return{cli_command_groups:e.commands,api_rules:e.apiRules,skills:e.skills,ifrs_recipes:e.recipes,calculators:e.calculators,job_playbooks:e.jobs}}catch{return}}async function Twr(t={}){if(t.query&&t.query.trim())return B3(t.query);if(t.namespace){let r=xi.find(i=>i.name===t.namespace);if(!r)return{error:`Unknown namespace "${t.namespace}".`,namespaces:xi.map(i=>i.name),hint:"Call with no arguments for the full map, or pass `query` to rank operations by keyword."};let n=a0(r.groups);return{namespace:r.name,description:r.description,operations:n.length,operation_list:n.map(u0),hint:"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}}let e=Wy(t.surface,t.multiOrg);return{...e,map:t.full?tk().map(r=>({...r,operation_list:a0(xi.find(n=>n.name===r.namespace).groups).map(u0)})):e.map,beyond_mcp:await xwr()}}var Xot=X(()=>{"use strict";ud();nk();l0();R3()});import{randomUUID as Bwr}from"node:crypto";function ust(t,e,r){return{type:"object",description:`The ${t.toLowerCase()} to create. Required.`,properties:{reference:{type:"string",description:`${t} reference`},contactResourceId:{type:"string",description:`${e} UUID`},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:`${t} line items (max 500)`,items:{type:"object",properties:{name:{type:"string",description:"Line description"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:`${r} account UUID`},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}},required:["name"]}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:f0,adjustment:p0}},capsuleResourceId:{type:"string"}},required:["reference","lineItems"]}}function wst(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function Ar(t,e,r,n,i,o){let s={...cpe};return o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:t,description:e,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=wst(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0;return FD((h,m)=>n(a.client,h,m,f),u,d,f==="lean"?50:20)}}}function Ti(t,e,r,n,i,o){return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,a)=>n(s.client,a.resourceId)}}function _st(t,e,r,n){return{[e]:!0,...oZ(t),[r]:n}}function sk(t){return`Deletes a DRAFT ${t}; VOIDs an active one and KEEPS it. force: true hard-deletes either.`}function Xr(t,e,r,n,i,o){let s=o?.verb??"deleted";return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"},...o?.voidable?Mwr:{}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(a,c)=>{let u=c.resourceId;ls(u,"resourceId",`Nothing was deleted. Source a real resourceId from a search_* or list_* result before calling ${t}.`);let d=c.force,f=await n(a.client,u,{force:d,internalNotes:c.internalNotes});return o?.voidable?Oc(f,u,d):_st(f,s,"resourceId",u)}}}function ak(t,e,r,n){return{name:t,description:`Download ${/^[aeiou]/i.test(e)?"an":"a"} ${e} as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).`,params:{resourceId:{type:"string",description:`${e[0].toUpperCase()}${e.slice(1)} resourceId`}},required:["resourceId"],group:r,readOnly:!0,searchHint:`download ${e} as PDF document file`,isConcurrencySafe:!0,execute:async(i,o)=>n(i.client,o.resourceId)}}function ape(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function mst(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function Ywr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e)){if(i==null)continue;let o=tZ.get(n);if(o)r[o]=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else jwr.has(n)&&(r[n]=i)}return r}):t}async function ck(t,e,r,n){let s=(await(e==="invoice"?Po:e==="bill"?Oo:e==="customer_credit_note"?za:Ga)(t,r)).data,a=qwr[e],c={};for(let[p,h]of Object.entries(s))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=mst(c.valueDate)),c.dueDate&&(c.dueDate=mst(c.dueDate)),c.lineItems&&(c.lineItems=Ywr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?il:e==="bill"?Ea:ao,{missingFields:d,ready:f}=Js(c,u);if(!f)throw new Error(`Cannot finalize: missing ${d.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function Ast(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function P3(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function Est(t,e,r){let n=yst[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(yst).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function bst(t,e,r,n,i,o,s){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${s}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function Cst(t,e,r,n,i,o){let s;try{s=(await e(t,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function Ist(t,e,r,n,i){let o;try{o=(await e(t,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${o}; void it instead of deleting.`}}}var kwr,Kfe,rc,vo,iu,wo,fd,ui,pd,Q3,Xy,Kot,Nwr,est,tst,epe,tpe,d0,ik,Owr,Fwr,rpe,rst,nst,npe,cpe,ou,ipe,ist,ost,sst,ast,Qi,cst,ok,Qwr,ope,L3,ba,lst,vst,hd,f0,p0,Lwr,Mwr,dst,fst,pst,Pwr,Uwr,spe,hst,$wr,qwr,jwr,lk,uk,M3,gst,yst,jf,U3=X(()=>{"use strict";BM();EC();rZ();CFe();SFe();sg();kD();ka();fr();hr();vA();Fu();XE();SPe();gK();dp();bg();Ld();yK();EK();Ig();bK();Lp();t1();y1();o_();CK();GPe();SU();OU();UU();hit();a_();w1();f_();uz();m_();E2();Ez();Jde();Vde();Oz();Wde();ofe();lfe();Git();Lp();PB();ffe();pfe();Jz();sot();Cfe();Ife();vfe();lot();Sfe();Rm();Rfe();xD();xfe();Tfe();A_();H7();fot();yot();bot();cZ();Cot();Nfe();N8();Ofe();Ffe();Qfe();Lfe();Mfe();Pfe();Ufe();$fe();dp();bg();qfe();Ig();Oot();Ld();SU();OU();Ig();N8();En();Yfe();zfe();fr();Jfe();$ot();kwr=jM.join(" | "),Kfe=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"],rc={type:"string",description:"Resource ID of the record"},vo={type:"string",description:"Transaction date (YYYY-MM-DD)"},iu={type:"string",description:"Due date (YYYY-MM-DD)"},wo={type:"string",description:"Reference number"},fd={type:"boolean",description:"Use the org's own next number instead of `reference`."},ui={type:"string",description:"Notes or memo text"},pd={type:"string",description:"Tag name for categorization"},Q3={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},Xy={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Kot={recipe:{type:"string",enum:[...zy],description:"Recipe type"},amount:{type:"number",description:"Amount (for amortization, accrued-expense, dividend, ecl, provision, fx-reval)"},principal:{type:"number",description:"Principal (for loan, fixed-deposit)"},startDate:{type:"string",description:"Start date YYYY-MM-DD (REQUIRED for blueprint generation \u2014 default to today if user does not specify)"},currency:{type:"string",description:"Currency code (e.g. SGD, USD)"},periods:{type:"number",description:"Number of periods (for amortization, accrued-expense, leave-accrual)"},frequency:{type:"string",enum:["monthly","quarterly","annual"],description:"Frequency (for depreciation, amortization, accrued-expense)"},annualRate:{type:"number",description:"Annual interest/discount rate %"},termMonths:{type:"number"},monthlyPayment:{type:"number",description:"Monthly lease payment (for lease)"},usefulLifeMonths:{type:"number",description:"Asset useful life in months (hire purchase)"},cost:{type:"number",description:"Asset cost"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"],description:"Depreciation method"},acquisitionDate:{type:"string",description:"Acquisition date YYYY-MM-DD"},disposalDate:{type:"string",description:"Disposal date YYYY-MM-DD"},proceeds:{type:"number",description:"Disposal proceeds"},bookRate:{type:"number",description:"Original booking rate. Declare which way it reads via rateDirection (REQUIRED for fx-reval)."},closingRate:{type:"number",description:"Period-end closing rate. Same direction as bookRate."},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"REQUIRED for fx-reval. FUNCTIONAL_TO_SOURCE = 1 base unit = N foreign, what list_currency_rates returns. SOURCE_TO_FUNCTIONAL = 1 foreign unit = N base, the everyday quote."},position:{type:"string",enum:["ASSET","LIABILITY"],description:"Balance-sheet side: ASSET (receivable/deposit, default) or LIABILITY (payable/provision). A rising base value is a gain on an asset and a loss on a liability."},baseCurrency:{type:"string",description:"Base (functional) currency"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string"},balance:{type:"number"},rate:{type:"number"}},required:["name","balance","rate"]},description:"ECL aging buckets"},existingProvision:{type:"number",description:"Existing ECL provision balance"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number",description:"Leave days per employee per year"},dailyRate:{type:"number",description:"Average daily rate"},declarationDate:{type:"string",description:"Board resolution date YYYY-MM-DD"},paymentDate:{type:"string",description:"Settlement date YYYY-MM-DD"},withholdingRate:{type:"number",description:"Withholding tax rate %"}},Nwr={type:"boolean",description:"Retry-only: set true after the duplicate guard surfaced a candidate and the user confirmed this is a separate document. Never on a first attempt."},est={type:"string",enum:[...aZ],description:"CUSTOM (default) = free text; ALL_* = a picklist of that population. Datatype is derived, not chosen."},tst={type:"object",properties:{address:{type:"string",description:"Street address \u2014 sent as addressLine1"},city:{type:"string"},state:{type:"string"},postalCode:{type:"string"},country:{type:"string"}},required:["address","country"]},epe={type:"string",description:"Contact resourceId (customer or supplier)"},tpe={type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID)"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Draft entity type"}},required:["btResourceId","btType"]}},d0={type:"string",description:"Chart-of-accounts account the line posts to (revenue on a sale, expense on a purchase)"},ik={type:"string",description:"Account the payment posts to. For paymentMethod BANK_TRANSFER/CASH/CHEQUE this MUST be a bank or cash account. Any other method accepts any org account \u2014 that is how a deposit drawdown works (paymentMethod OTHER + the deposit account)."},Owr={type:"number",description:"Payment amount (in bank currency)"},Fwr={type:"string",description:"Period start date (YYYY-MM-DD)"},rpe={type:"string",description:"Period end date (YYYY-MM-DD)"},rst={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report") \u2014 it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},nst={type:"string",description:"Currency code (e.g. SGD, USD)"},npe={type:"string",description:"Display name"},cpe={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},ou={type:"object",required:["sourceCurrency"],properties:{sourceCurrency:{type:"string",description:"Foreign currency code (ISO 4217)."},exchangeRate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N sourceCurrency. Invert ONLY if your quote reads "1 source = X base" (send 1/X), or declare rateDirection and skip the arithmetic. Omit for the org/platform rate.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"How exchangeRate reads. SOURCE_TO_FUNCTIONAL accepts a bank quote verbatim. Default FUNCTIONAL_TO_SOURCE."}}},ipe={type:"string",enum:[...tf],description:"Entity type to export"},ist={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},ost={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},sst={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},ast={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},Qi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},cst={type:"array",description:"Full replacement line-item set \u2014 non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},ok={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},Qwr={type:"array",items:{type:"object",required:["resourceId","type","selectedClasses","printable"],properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",required:["className"],properties:{className:{type:"string"},resourceId:rc}}},printable:{type:"boolean",description:"Show on printed documents."}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},ope={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},L3={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Offset account resourceId"},amount:{type:"number",description:"Amount (positive; direction comes from the endpoint)"},description:{type:"string",description:"Line description"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId"}},required:["accountResourceId","amount"]},description:"Offset lines. No `type` \u2014 cash-in credits these and cash-out debits them, decided by the endpoint."},ba={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:d0,taxProfileResourceId:{type:"string"},classifierConfig:Qwr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},lst={type:"array",items:{type:"object",properties:{itemName:{type:"string",description:"Display name of the catalog item"},itemResourceId:{type:"string",description:"Underlying item resourceId (from search_items)"},price:{type:"number",description:"Default unit price (0-1e9)"},unit:{type:"string",description:"Unit of measure"},quantityDefault:{type:"number",description:"Default quantity when added to a document (0-100)"},discountDefault:{type:"number",description:"Default discount % when added to a document (0-100)"},uiIndex:{type:"number",description:"Display position in the catalog (integer, min 0)"},classifiers:{type:"array",items:{type:"object"},description:"Classifier assignments. Same shape as classifierConfig on invoice/bill line items."}},required:["itemName","itemResourceId","price"]},description:"Catalog item rows. itemName, itemResourceId and price are required on every row."},vst={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},hd={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",enum:["LOAN_AMORTIZATION","ACCRUAL_REVERSAL","PREPAID_AMORTIZATION","DEFERRED_REVENUE","IFRS16_LEASE"],description:"Must match mutation's allowedBaseTransactionTypes (see list_capsule_recipes)."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:vst},required:["recipeName","inputs"]},f0={type:"string",enum:[...XFe],description:"Payment method (default BANK_TRANSFER)"},p0={type:"object",description:"Cash-leg adjustment (overpayment/rounding). Bank leg only, never AR/AP. Not with DEBT_WRITE_OFF/CLEARING_SETTLEMENT/INTER_COMPANY/WITHHOLDING_TAX_CERTIFICATE. See rule 160.",properties:{adjustmentValue:{type:"number",description:"Signed, non-zero, max 2dp"},adjustmentAccountResourceId:{type:"string",description:"Non-controlled account, not bank/cash"},adjustmentDescription:{type:"string",description:"Optional"}},required:["adjustmentValue","adjustmentAccountResourceId"]},Lwr={...p0,description:"Adding or changing an adjustment applies here. REMOVING does not: 0 is rejected and null reads as omitted, so both leave the stored value unchanged. To remove one, delete the payment and record it again. A change is rejected if the payment is reconciled or lock-dated, and amount, account and description are all compared, so resend all three unchanged if you are not editing it. See rule 160."};Mwr={force:{type:"boolean",description:iZ.force},internalNotes:{type:"string",description:iZ.internalNotes}};dst={type:"string",description:"Document family",enum:[...Vy]},fst={type:"string",description:"Document family",enum:[...o0]},pst={type:"string",description:"Why it is sent back. Opens a thread; the only record of the reason."},Pwr=[{name:"approve_documents",description:"Approve one document awaiting approval. Posts its ledger entries and makes it live. One-shot, and the refusal channel differs by entity: invoices/bills THROW 422; credit notes return 200 with isSuccess:false and a STALE approvalStatus of APPROVED. Check isSuccess and catch the throw \u2014 approvalStatus alone cannot tell refusal from success.",params:{entity:dst,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"approvals",readOnly:!1,searchHint:"approve pending invoice bill credit note post ledger",execute:async(t,e)=>c3(t.client,e.entity,e.resourceId)},{name:"bulk_approve_documents",description:"Approve up to 100 documents awaiting approval. Async \u2014 returns a jobId; poll search_background_jobs. Each approval posts a ledger.",params:{entity:dst,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-100)"}},required:["entity","resourceIds"],group:"approvals",readOnly:!1,searchHint:"bulk approve many pending documents at once",execute:async(t,e)=>l3(t.client,e.entity,e.resourceIds)},{name:"request_document_changes",description:"Send one document back for changes instead of approving it. Also covers orders, quotes, requests and claims.",params:{entity:fst,resourceId:{type:"string",description:"Document resourceId"},message:pst},required:["entity","resourceId","message"],group:"approvals",readOnly:!1,searchHint:"request changes reject send back document for revision",execute:async(t,e)=>u3(t.client,e.entity,e.resourceId,e.message)},{name:"bulk_request_document_changes",description:"Send up to 500 documents back for changes with one message. Async \u2014 returns a jobId; poll search_background_jobs.",params:{entity:fst,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-500)"},message:pst},required:["entity","resourceIds","message"],group:"approvals",readOnly:!1,searchHint:"bulk request changes send back many documents",execute:async(t,e)=>d3(t.client,e.entity,e.resourceIds,e.message)}],Uwr=["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"],spe={type:"string",description:"Document family",enum:Uwr},hst={type:"string",description:"Version id from get_document_version_history"},$wr=[{name:"get_document_version_history",description:"The stored versions of a document, OLDEST first (last entry = current). Not paginated. Use before restoring to pick a version id.",params:{entity:spe,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"versions",readOnly:!0,searchHint:"list document version history revisions audit trail",isConcurrencySafe:!0,execute:async(t,e)=>Tot(t.client,e.entity,e.resourceId)},{name:"get_document_version",description:"Read one stored version of a document. An unknown resourceId/version pair returns 422.",params:{entity:spe,resourceId:{type:"string",description:"Document resourceId"},version:hst},required:["entity","resourceId","version"],group:"versions",readOnly:!0,searchHint:"get read one document version snapshot",isConcurrencySafe:!0,execute:async(t,e)=>Bot(t.client,e.entity,e.resourceId,e.version)},{name:"rollback_document_version",description:"Restore a document to a stored version. REPLACES current state \u2014 read the version first with get_document_version. `CREATED` is NOT a restorable version and is refused: upstream DELETES the document for it and still answers 200.",params:{entity:spe,resourceId:{type:"string",description:"Document resourceId"},version:hst},required:["entity","resourceId","version"],group:"versions",readOnly:!1,searchHint:"restore rollback document to previous version undo changes",isDestructive:!0,execute:async(t,e)=>kot(t.client,e.entity,e.resourceId,e.version)},{name:"get_currency_effective_rate",description:"The organization effective rate for a currency on a date: its own custom rate when set, else the platform daily rate. Defaults to today.",params:{currencyCode:{type:"string",description:"ISO 4217 code, e.g. USD (not a resourceId)"},date:{type:"string",description:"YYYY-MM-DD (optional, defaults to today)"}},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"currency effective exchange rate for a date custom or platform",isConcurrencySafe:!0,execute:async(t,e)=>Not(t.client,e.currencyCode,e.date)}];qwr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};jwr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);lk={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},uk={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},M3={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},gst={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},yst={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};jf=[{name:"get_next_reference",description:"Next document number in the org's own series. Same number the web app prefills. Reading does NOT reserve it \u2014 two callers reading at once get the same value. Date embedded is always today. Never invent a reference; use this.",params:{type:{type:"string",description:"Document family whose next number is wanted.",enum:[...W7]}},required:["type"],group:"organization",readOnly:!0,noCache:!0,searchHint:"next reference number document numbering series auto reference",isConcurrencySafe:!0,maxResultSizeChars:5e3,execute:async(t,e)=>Z7(t.client,e.type)},{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>Na(t.client)},{name:"get_my_context",description:"Resolve the CALLER's own context \u2014 identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side \u2014 no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>X0e(t.client)},Ar("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>Md(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),Zt({name:"search_accounts",description:'Search chart of accounts. For OR (name or code), use filter: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:cR,defaults:lR,fetcher:ZE,searchHint:"find accounts chart of accounts CoA by name code type class status OR search"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name \u2014 returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:`Exact API string: ${kwr}. COGS = "Direct Costs". Common variants normalized client-side. "interest expense"/"interest income" is NOT auto-classified \u2014 ask, do not infer: Finance/Financing, Investing or Operating by main business activity.`},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(t,e)=>{let r=e.name,n=await H1(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=KE(e.accountType);return r_(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode,lockDate:e.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(t,e)=>{let r=e.resourceId,n=(await r1(t.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=e.clearLockDate===!0;if(s&&e.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),e.name!==void 0&&(o.name=e.name),e.code!==void 0&&(o.code=e.code),!s&&e.lockDate!==void 0&&(o.lockDate=e.lockDate),Nwe(t.client,r,o)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
685
685
 
686
686
  resourceId per row \u2192 update; omit \u2192 create. Note: dedup is by NAME (not code) \u2014 duplicate name surfaces ORGANIZATION_CHART_OF_ACCOUNT_DUPLICATED per row. Accepts all 23 accountType values (see create_account); common variants normalized via normalizeAccountType.
687
687
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jaz-clio",
3
- "version": "5.52.0",
3
+ "version": "5.52.2",
4
4
  "description": "Clio: Command Line Interface Operator for Jaz AI.",
5
5
  "type": "module",
6
6
  "bin": {