@dizzlkheinz/ynab-mcpb 0.16.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -57,7 +57,7 @@ Valid formats:
57
57
  - UUID format (versions 1-5, e.g., "123e4567-e89b-12d3-a456-426614174000")
58
58
  - Special keywords: ${this.ALLOWED_KEYWORDS.map(a=>`"${a}"`).join(", ")}
59
59
 
60
- You can use the list_budgets tool to see available budget IDs.`;return nn.createValidationError("Invalid budget ID format",r,["Use a valid UUID format (UUID v1-v5, e.g., 123e4567-e89b-12d3-a456-426614174000; standard UUID v4 format works as well)","Run the list_budgets tool to view available budget IDs",'Use the special keyword "default" for convenience'])}static resolveBudgetIdOrThrow(t,r){let a=this.resolveBudgetId(t,r);if(typeof a=="string")return a;let n=a.content?.[0]?.type==="text"?a.content[0].text:"Budget resolution failed";throw new Error(n)}static validateBudgetIdOrThrow(t){let r=this.validateBudgetId(t);if(typeof r=="string")return r;let a=r.content?.[0]?.type==="text"?r.content[0].text:"Budget validation failed";throw new Error(a)}};qd.UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;qd.ALLOWED_KEYWORDS=["default"];var be=class{constructor(){this.cache=new Map,this.hits=0,this.misses=0,this.evictions=0,this.lastCleanup=null,this.pendingFetches=new Map,this.pendingRefresh=new Set,this.maxEntries=this.parseEnvInt("YNAB_MCP_CACHE_MAX_ENTRIES",1e3),this.defaultStaleWindow=this.parseEnvInt("YNAB_MCP_CACHE_STALE_MS",120*1e3),this.defaultTTL=this.parseEnvInt("YNAB_MCP_CACHE_DEFAULT_TTL_MS",3e5)}get(t){let r=this.cache.get(t);if(!r)return this.misses++,null;let n=Date.now()-r.timestamp;if(n>r.ttl){let i=r.staleWhileRevalidate||0;return i>0&&n<=r.ttl+i?(this.hits++,this.cache.delete(t),this.cache.set(t,r),this.pendingRefresh.add(t),r.data):(this.cache.delete(t),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),this.misses++,null)}return this.hits++,this.cache.delete(t),this.cache.set(t,r),r.data}has(t){let r=this.cache.get(t);if(!r)return!1;let n=Date.now()-r.timestamp;if(n>r.ttl){let i=r.staleWhileRevalidate||0;return i>0&&n<=r.ttl+i?!0:(this.cache.delete(t),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),!1)}return!0}set(t,r,a){if(this.maxEntries<=0)return;let n=this.cache.has(t);n||this.evictIfNeeded();let i,o;if(typeof a=="number")i=Number.isFinite(a)?a:this.defaultTTL,o=void 0;else if(a===void 0)i=this.defaultTTL,o=void 0;else{let d=a?.ttl;i=d!==void 0?d:this.defaultTTL,a&&"staleWhileRevalidate"in a?o=a.staleWhileRevalidate:o=a?.staleWhileRevalidate,o===void 0&&this.defaultStaleWindow>0&&(o=this.defaultStaleWindow)}let s={data:r,timestamp:Date.now(),ttl:i};o!==void 0&&(s.staleWhileRevalidate=o),n&&this.cache.delete(t),this.cache.set(t,s),this.pendingFetches.delete(t),this.pendingRefresh.delete(t)}delete(t){let r=this.cache.delete(t);return r&&(this.pendingFetches.delete(t),this.pendingRefresh.delete(t)),r}deleteMany(t){for(let r of t)this.cache.delete(r),this.pendingFetches.delete(r),this.pendingRefresh.delete(r)}deleteByPrefix(t){if(!t)return 0;let r=t.endsWith(":")?t.slice(0,-1):t,a=`${r}:`,n=0;for(let i of this.cache.keys())(i===r||i.startsWith(a))&&(this.cache.delete(i),this.pendingFetches.delete(i),this.pendingRefresh.delete(i),n++);return n}deleteByBudgetId(t){if(!t)return 0;let r=0;for(let a of this.cache.keys())a.split(":").some(i=>i===t)&&(this.cache.delete(a),this.pendingFetches.delete(a),this.pendingRefresh.delete(a),r++);return r}getKeys(){return Array.from(this.cache.keys())}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.evictions=0,this.lastCleanup=null,this.pendingFetches.clear(),this.pendingRefresh.clear()}getStats(){let t=this.hits+this.misses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),hits:this.hits,misses:this.misses,evictions:this.evictions,lastCleanup:this.lastCleanup,maxEntries:this.maxEntries,hitRate:t>0?this.hits/t:0}}getEntriesForSizeEstimation(){let t=Date.now();return Array.from(this.cache.entries()).filter(([,r])=>t-r.timestamp<=r.ttl)}getCacheMetadata(){let t=Date.now();return Array.from(this.cache.entries()).map(([r,a])=>{let n={key:r,timestamp:a.timestamp,ttl:a.ttl,dataType:typeof a.data,isExpired:t-a.timestamp>a.ttl};return a.staleWhileRevalidate!==void 0&&(n.staleWhileRevalidate=a.staleWhileRevalidate),n})}cleanup(){return this.cleanupDetailed().cleaned}cleanupDetailed(){let t=Date.now(),r=0,a=this.evictions;for(let[n,i]of this.cache.entries())t-i.timestamp>i.ttl&&(this.cache.delete(n),this.pendingFetches.delete(n),this.pendingRefresh.delete(n),r++,this.evictions++);return this.lastCleanup=t,{cleaned:r,evictions:this.evictions-a}}async wrap(t,r){let a=this.cache.get(t),n=this.get(t);if(n!==null){if(this.pendingRefresh.has(t)&&!this.pendingFetches.has(t)){let s=r.loader().then(d=>{let u={},l=r.ttl??a?.ttl;l!==void 0&&(u.ttl=l);let p=r.staleWhileRevalidate??a?.staleWhileRevalidate;return p!==void 0&&(u.staleWhileRevalidate=p),this.set(t,d,u),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),d},d=>{throw this.pendingFetches.delete(t),this.pendingRefresh.delete(t),d});this.pendingFetches.set(t,s)}return n}let i=this.pendingFetches.get(t);if(i)return i;let o=r.loader().then(s=>(this.set(t,s,r),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),s),s=>{throw this.pendingFetches.delete(t),this.pendingRefresh.delete(t),s});return this.pendingFetches.set(t,o),o}evictIfNeeded(){if(!(this.maxEntries<=0))for(;this.cache.size>=this.maxEntries;){let t=this.cache.keys().next().value;if(t)this.cache.delete(t),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),this.evictions++;else break}}parseEnvInt(t,r){let a=process.env[t];if(!a)return r;let n=parseInt(a,10);return isNaN(n)?r:n}static generateKey(t,...r){let a=r.filter(n=>n!==void 0).map(n=>String(n)).join(":");return`${t}:${a}`}},It={BUDGETS:600*1e3,ACCOUNTS:300*1e3,CATEGORIES:300*1e3,PAYEES:600*1e3,TRANSACTIONS:120*1e3,SCHEDULED_TRANSACTIONS:300*1e3,USER_INFO:1800*1e3,MONTHS:300*1e3},ke=new be;var dA=100,Fue={info(e,t){l0.logSuccess("delta-cache",e,t?{...t}:{})},warn(e,t){let r={...t?{...t}:{},severity:"warn"};l0.logSuccess("delta-cache",e,r)},error(e,t){let r=t?{...t}:{},a=r.error,n=typeof a=="string"?a:e;l0.logError("delta-cache",e,r,n)}},Es=class{constructor(t,r,a=Fue){this.cacheManager=t,this.knowledgeStore=r,this.logger=a,this.deltaHits=0,this.deltaMisses=0,this.mergeOperations=0,this.knowledgeGapEvents=0}async fetchWithDelta(t,r,a,n,i){let o=this.assertFiniteTtl("fetchWithDelta",t,i.ttl);if(!this.isDeltaEnabled())return this.fetchWithoutDelta(t,r,a,i);let s=this.cacheManager.get(t);if(i.forceFullRefresh&&s&&!(Date.now()-s.timestamp>s.ttl))return{data:s.snapshot,wasCached:!0,usedDelta:!1,serverKnowledge:s.serverKnowledge};let d=i.forceFullRefresh?void 0:this.knowledgeStore.get(t),u=!!(!i.forceFullRefresh&&s&&d!==void 0),l=u?d:void 0,p=await a(l),_=l!==void 0?p.serverKnowledge-l:0,g=!1;_>dA&&(this.logger.warn("delta-cache.knowledge-gap",{budgetId:r,cacheKey:t,lastKnowledge:l,serverKnowledge:p.serverKnowledge,gap:_,threshold:dA,action:"full-refresh",recommendation:"Consider forcing a full refresh to resync cache."}),g=!0,this.knowledgeGapEvents++,p=await a(void 0));let f=!g&&l!==void 0&&p.serverKnowledge>l,m,h=!1;f&&s?(this.mergeOperations++,m=n(s.snapshot,p.data,i.mergeOptions),h=!0):s&&l!==void 0&&!g?m=s.snapshot:m=this.filterDeleted(p.data);let y={snapshot:m,serverKnowledge:p.serverKnowledge,timestamp:Date.now(),ttl:o};i.staleWhileRevalidate!==void 0&&(y.staleWhileRevalidate=i.staleWhileRevalidate);let b={ttl:o};return i.staleWhileRevalidate!==void 0&&(b.staleWhileRevalidate=i.staleWhileRevalidate),this.cacheManager.set(t,y,b),this.knowledgeStore.update(t,p.serverKnowledge),u?this.deltaHits++:this.deltaMisses++,{data:m,wasCached:!!s,usedDelta:h,serverKnowledge:p.serverKnowledge}}getStats(){return{deltaHits:this.deltaHits,deltaMisses:this.deltaMisses,mergeOperations:this.mergeOperations,knowledgeGapEvents:this.knowledgeGapEvents}}invalidate(t,r){if(t)if(r){let a=`${r}:list:${t}`;this.cacheManager.deleteByPrefix(a)}else this.cacheManager.deleteByBudgetId(t)}forceFullRefresh(t,r){t?this.invalidate(t,r):this.cacheManager.clear(),r&&t?this.knowledgeStore.reset(`${r}:list:${t}`):t?this.knowledgeStore.resetByBudgetId(t):this.knowledgeStore.reset()}async fetchWithoutDelta(t,r,a,n){let i=this.assertFiniteTtl("fetchWithoutDelta",t,n.ttl),o=this.cacheManager.get(t);if(o&&(!(Date.now()-o.timestamp>o.ttl)||!n.forceFullRefresh))return{data:o.snapshot,wasCached:!0,usedDelta:!1,serverKnowledge:o.serverKnowledge};let s=await a(void 0),d=this.filterDeleted(s.data),u={snapshot:d,serverKnowledge:s.serverKnowledge,timestamp:Date.now(),ttl:i};n.staleWhileRevalidate!==void 0&&(u.staleWhileRevalidate=n.staleWhileRevalidate);let l={ttl:i};return n.staleWhileRevalidate!==void 0&&(l.staleWhileRevalidate=n.staleWhileRevalidate),this.cacheManager.set(t,u,l),this.knowledgeStore.update(t,s.serverKnowledge),{data:d,wasCached:!1,usedDelta:!1,serverKnowledge:s.serverKnowledge}}filterDeleted(t){return t.filter(r=>!r.deleted)}assertFiniteTtl(t,r,a){if(!Number.isFinite(a))throw new Error(`DeltaCache.${t} requires a finite ttl for cache key "${r}". Received: ${String(a)}.`);return a}isDeltaEnabled(){return process.env.YNAB_MCP_ENABLE_DELTA==="true"}};var Ps=class{constructor(){this.knowledge=new Map}get(t){return this.knowledge.get(t)}update(t,r){if(r<0)throw new Error(`server_knowledge must be non-negative, got: ${r}`);this.knowledge.set(t,r)}reset(t){if(t===void 0||t===""){this.knowledge.clear();return}let r=[];for(let a of this.knowledge.keys())a.includes(t)&&r.push(a);for(let a of r)this.knowledge.delete(a)}resetByBudgetId(t){this.reset(`:${t}`)}getStats(){let t={};for(let[r,a]of this.knowledge.entries())t[r]=a;return{entryCount:this.knowledge.size,entries:t}}};function Kp(e,t,r){let a=new Map(e.map(n=>[n.id,{...n}]));for(let n of t){if(n.deleted&&!r?.preserveDeleted){a.delete(n.id);continue}let i=a.get(n.id)??{};a.set(n.id,{...i,...n})}return Array.from(a.values())}var lA=(e,t,r)=>{let a=!!r?.preserveDeleted,n=new Map(e.map(i=>[i.month,{...i}]));for(let i of t){if(i.deleted&&!a){n.delete(i.month);continue}let o=n.get(i.month)??{};n.set(i.month,{...o,...i})}return Array.from(n.values())},pA=(e,t,r)=>{let a=!!r?.preserveDeleted,n=new Map(e.map(i=>[i.id,cA(i)]));for(let i of t){if(i.deleted&&!a){n.delete(i.id);continue}let o=n.get(i.id);if(!o){n.set(i.id,cA(i));continue}let s={...o,...i,categories:o.categories?o.categories.map(d=>({...d})):o.categories};if(i.categories){let d=new Map((o.categories??[]).map(u=>[u.id,{...u}]));for(let u of i.categories)if(u.deleted&&!a)d.delete(u.id);else{let l=d.get(u.id)??{};d.set(u.id,{...l,...u})}s.categories=Array.from(d.values())}n.set(i.id,s)}return Array.from(n.values())},_v=(e,t,r)=>{let a=!!r?.preserveDeleted,n=new Map(e.map(i=>[i.id,uA(i)]));for(let i of t){if(i.deleted&&!a){n.delete(i.id);continue}let o=n.get(i.id);if(!o){n.set(i.id,uA(i));continue}let s={...o,...i,subtransactions:o.subtransactions?o.subtransactions.map(d=>({...d})):o.subtransactions};if(i.subtransactions){let d=new Map((o.subtransactions??[]).map(u=>[u.id,{...u}]));for(let u of i.subtransactions)if(u.deleted&&!a)d.delete(u.id);else{let l=d.get(u.id)??{};d.set(u.id,{...l,...u})}s.subtransactions=Array.from(d.values())}n.set(i.id,s)}return Array.from(n.values())},cA=e=>({...e,categories:e.categories?e.categories.map(t=>({...t})):e.categories}),uA=e=>({...e,subtransactions:e.subtransactions?e.subtransactions.map(t=>({...t})):e.subtransactions});var Ud=class{constructor(t,r){this.ynabAPI=t,this.deltaCache=r}async fetchAccounts(t,r){let a=be.generateKey("accounts","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.accounts.getAccounts(t,n):await this.ynabAPI.accounts.getAccounts(t);return{data:i.data.accounts,serverKnowledge:i.data.server_knowledge??0}},Kp,this.buildDeltaOptions(It.ACCOUNTS,r))}async fetchCategories(t,r){let a=be.generateKey("categories","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.categories.getCategories(t,n):await this.ynabAPI.categories.getCategories(t);return{data:i.data.category_groups,serverKnowledge:i.data.server_knowledge??0}},pA,this.buildDeltaOptions(It.CATEGORIES,r))}async fetchTransactions(t,r,a,n){let i=r??"all",o=a??"all",s=be.generateKey("transactions","list",t,i,o);return await this.deltaCache.fetchWithDelta(s,t,async d=>{let u=await this.ynabAPI.transactions.getTransactions(t,r,a,d);return{data:u.data.transactions,serverKnowledge:u.data.server_knowledge??0}},_v,this.buildDeltaOptions(It.TRANSACTIONS,n))}async fetchTransactionsByAccount(t,r,a,n){let i=a??"all",o=be.generateKey("transactions","account",t,r,i);return await this.deltaCache.fetchWithDelta(o,t,async s=>{let d=await this.ynabAPI.transactions.getTransactionsByAccount(t,r,a,void 0,s);return{data:d.data.transactions,serverKnowledge:d.data.server_knowledge??0}},_v,this.buildDeltaOptions(It.TRANSACTIONS,n))}async fetchAccountsFull(t){let r=await this.ynabAPI.accounts.getAccounts(t);return{data:r.data.accounts.filter(n=>!n.deleted),wasCached:!1,usedDelta:!1,serverKnowledge:r.data.server_knowledge??0}}async fetchTransactionsByAccountFull(t,r,a){let n=await this.ynabAPI.transactions.getTransactionsByAccount(t,r,a);return{data:n.data.transactions.filter(o=>!o.deleted),wasCached:!1,usedDelta:!1,serverKnowledge:n.data.server_knowledge??0}}async fetchScheduledTransactions(t,r){let a=be.generateKey("scheduled_transactions","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.scheduledTransactions.getScheduledTransactions(t,n):await this.ynabAPI.scheduledTransactions.getScheduledTransactions(t);return{data:i.data.scheduled_transactions,serverKnowledge:i.data.server_knowledge??0}},Kp,this.buildDeltaOptions(It.SCHEDULED_TRANSACTIONS,r))}async fetchPayees(t,r){let a=be.generateKey("payees","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.payees.getPayees(t,n):await this.ynabAPI.payees.getPayees(t);return{data:i.data.payees,serverKnowledge:i.data.server_knowledge??0}},Kp,this.buildDeltaOptions(It.PAYEES,r))}async fetchMonths(t,r){let a=be.generateKey("months","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.months.getBudgetMonths(t,n):await this.ynabAPI.months.getBudgetMonths(t);return{data:i.data.months,serverKnowledge:i.data.server_knowledge??0}},lA,this.buildDeltaOptions(It.MONTHS,r))}async fetchBudgets(t){let r=be.generateKey("budgets","list"),a=await this.deltaCache.fetchWithDelta(r,"global",async()=>{let n=await this.ynabAPI.budgets.getBudgets(),i=n.data.server_knowledge??0;return{data:n.data.budgets,serverKnowledge:i}},Kp,{ttl:t?.ttl??It.BUDGETS,forceFullRefresh:!0});return{...a,data:a.data}}buildDeltaOptions(t,r){return{ttl:r?.ttl??t,...r?.forceFullRefresh!==void 0&&{forceFullRefresh:r.forceFullRefresh}}}};var uo;function zue(e){if(uo&&!uo.manuallyConfigured&&uo.ynabAPI&&uo.ynabAPI!==e&&(uo=void 0),uo?.deltaFetcher)return uo.deltaFetcher;let t=uo?{...uo}:{};t.manuallyConfigured===void 0&&(t.manuallyConfigured=!1),t.deltaCache||(t.knowledgeStore||(t.knowledgeStore=new Ps),t.deltaCache=new Es(ke,t.knowledgeStore));let r=new Ud(e,t.deltaCache);return t.deltaFetcher=r,t.ynabAPI||(t.ynabAPI=e),uo=t,r}function mA(e){return e!==null&&typeof e=="object"&&e instanceof Ud&&typeof e.fetchAccounts=="function"&&typeof e.fetchCategories=="function"}function fA(e){return e!==null&&typeof e=="object"&&e instanceof Es&&typeof e.fetchWithDelta=="function"}function hA(e){return e!==null&&typeof e=="object"&&e instanceof Ps&&typeof e.get=="function"&&typeof e.update=="function"}function Xp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(e.constructor===Object||e.constructor===void 0)}function Cs(e){if(e===null)return"null";if(e===void 0)return"undefined";let t=typeof e;if(t!=="object")return t;let r=e.constructor?.name;return r?`${t} (${r})`:t}function Xr(e,t,r){if(r!==void 0){if(!mA(t))throw new Error(`resolveDeltaFetcherArgs: When providing 3 arguments, the second argument must be a DeltaFetcher instance. Got: ${Cs(t)}`);if(!Xp(r))throw new Error(`resolveDeltaFetcherArgs: When providing 3 arguments, the third argument must be a params object. Got: ${Cs(r)}`);return{deltaFetcher:t,params:r}}if(mA(t))throw new Error("resolveDeltaFetcherArgs: When providing 2 arguments, the second argument must be a params object, not a DeltaFetcher. To use a custom DeltaFetcher, provide all 3 arguments: (ynabAPI, deltaFetcher, params)");if(!Xp(t))throw new Error(`resolveDeltaFetcherArgs: When providing 2 arguments, the second argument must be a params object. Got: ${Cs(t)}`);return{deltaFetcher:zue(e),params:t}}function ki(e,t,r){if(r!==void 0){if(!fA(e))throw new Error(`resolveDeltaWriteArgs: When providing 3 arguments, the first argument must be a DeltaCache instance. Got: ${Cs(e)}`);if(!hA(t))throw new Error(`resolveDeltaWriteArgs: When providing 3 arguments, the second argument must be a ServerKnowledgeStore instance. Got: ${Cs(t)}`);if(!Xp(r))throw new Error(`resolveDeltaWriteArgs: When providing 3 arguments, the third argument must be a params object. Got: ${Cs(r)}`);return{deltaCache:e,knowledgeStore:t,params:r}}if(t!==void 0){let i=hA(t),o=Xp(t);if(!i&&!o)throw new Error(`resolveDeltaWriteArgs: When providing 2 arguments, the second argument must be either a ServerKnowledgeStore or a params object. Got: ${Cs(t)}`);if(o)throw new Error("resolveDeltaWriteArgs: Invalid argument combination. When providing 2 arguments where the second is a params object, this is ambiguous. Either provide 1 argument (params only) or 3 arguments (deltaCache, knowledgeStore, params).");if(i)throw new Error("resolveDeltaWriteArgs: When providing DeltaCache and ServerKnowledgeStore, you must also provide params as the third argument. Got 2 arguments, expected 3: (deltaCache, knowledgeStore, params)")}if(fA(e))throw new Error("resolveDeltaWriteArgs: When providing only 1 argument, it must be a params object, not a DeltaCache. To use a custom DeltaCache, provide all 3 arguments: (deltaCache, knowledgeStore, params)");if(!Xp(e))throw new Error(`resolveDeltaWriteArgs: When providing only 1 argument, it must be a params object. Got: ${Cs(e)}`);let a=new Ps;return{deltaCache:new Es(ke,a),knowledgeStore:a,params:e}}var gA=c.object({budget_id:c.string().min(1,"Budget ID is required")}).strict();async function _A(e,t,r){let{deltaFetcher:a}=Xr(e,t??{},r);return await mt(async()=>{let n=await a.fetchBudgets(),i=n.data,o=n.wasCached;return{content:[{type:"text",text:he.format({budgets:i.map(s=>({id:s.id,name:s.name,last_modified_on:s.last_modified_on,first_month:s.first_month,last_month:s.last_month,date_format:s.date_format,currency_format:s.currency_format})),cached:o,cache_info:o?`Data retrieved from cache for improved performance${n.usedDelta?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API"})}]}},"ynab:list_budgets","listing budgets")}async function yA(e,t){return await mt(async()=>{let a=(await e.budgets.getBudgetById(t.budget_id)).data.budget;return{content:[{type:"text",text:he.format({budget:{id:a.id,name:a.name,last_modified_on:a.last_modified_on,first_month:a.first_month,last_month:a.last_month,date_format:a.date_format,currency_format:a.currency_format,accounts_count:a.accounts?.length??0,categories_count:a.categories?.length??0,payees_count:a.payees?.length??0,months_count:a.months?.length??0,message:"Use list_accounts, list_categories, list_payees, and list_months to get detailed lists"}})}]}},"ynab:get_budget","getting budget details")}function fe(e){return Math.round(e)/1e3}function Qp(e){return Math.round(e*1e3)}var Sr={ACCOUNTS:"accounts",BUDGETS:"budgets",CATEGORIES:"categories",PAYEES:"payees",TRANSACTIONS:"transactions",MONTHS:"months"};var vA=c.object({budget_id:c.string().min(1,"Budget ID is required"),limit:c.number().int().positive().optional()}).strict(),bA=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().min(1,"Account ID is required")}).strict(),wA=c.object({budget_id:c.string().min(1,"Budget ID is required"),name:c.string().min(1,"Account name is required"),type:c.enum(["checking","savings","creditCard","cash","lineOfCredit","otherAsset","otherLiability"]),balance:c.number().optional(),dry_run:c.boolean().optional()}).strict();async function SA(e,t,r){let{deltaFetcher:a,params:n}=Xr(e,t,r);return await mt(async()=>{let i=await a.fetchAccounts(n.budget_id),o=i.data,s=i.wasCached,d=o.length;return n.limit!==void 0&&(o=o.slice(0,n.limit)),{content:[{type:"text",text:he.format({accounts:o.map(u=>({id:u.id,name:u.name,type:u.type,on_budget:u.on_budget,closed:u.closed,note:u.note,balance:fe(u.balance),cleared_balance:fe(u.cleared_balance),uncleared_balance:fe(u.uncleared_balance),transfer_payee_id:u.transfer_payee_id,direct_import_linked:u.direct_import_linked,direct_import_in_error:u.direct_import_in_error})),total_count:d,returned_count:o.length,cached:s,cache_info:s?`Data retrieved from cache for improved performance${i.usedDelta?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API"})}]}},"ynab:list_accounts","listing accounts")}async function TA(e,t){return await mt(async()=>{let r=be.generateKey(Sr.ACCOUNTS,"get",t.budget_id,t.account_id),a=ke.has(r),n=await ke.wrap(r,{ttl:It.ACCOUNTS,loader:async()=>(await e.accounts.getAccountById(t.budget_id,t.account_id)).data.account});return{content:[{type:"text",text:he.format({account:{id:n.id,name:n.name,type:n.type,on_budget:n.on_budget,closed:n.closed,note:n.note,balance:fe(n.balance),cleared_balance:fe(n.cleared_balance),uncleared_balance:fe(n.uncleared_balance),transfer_payee_id:n.transfer_payee_id,direct_import_linked:n.direct_import_linked,direct_import_in_error:n.direct_import_in_error},cached:a,cache_info:a?"Data retrieved from cache for improved performance":"Fresh data retrieved from YNAB API"})}]}},"ynab:get_account","getting account details")}async function $A(e,t,r,a){let{deltaCache:n,params:i}=ki(t,r,a);return await mt(async()=>{if(i.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_account",request:{budget_id:i.budget_id,name:i.name,type:i.type,balance:i.balance??0}})}]};let o={name:i.name,type:i.type,balance:i.balance?i.balance*1e3:0},d=(await e.accounts.createAccount(i.budget_id,{account:o})).data.account,u=be.generateKey(Sr.ACCOUNTS,"list",i.budget_id);return ke.delete(u),n.invalidate(i.budget_id,Sr.ACCOUNTS),{content:[{type:"text",text:he.format({account:{id:d.id,name:d.name,type:d.type,on_budget:d.on_budget,closed:d.closed,note:d.note,balance:fe(d.balance),cleared_balance:fe(d.cleared_balance),uncleared_balance:fe(d.uncleared_balance),transfer_payee_id:d.transfer_payee_id,direct_import_linked:d.direct_import_linked,direct_import_in_error:d.direct_import_in_error}})}]}},"ynab:create_account","creating account")}var NA=require("crypto");function yu(e,t){if(!e)throw new Error(t);return e}var Jo=e=>`${e.slice(0,7)}-01`;function xA(e,t){if(e&&(e.category_id&&t.add(e.category_id),Array.isArray(e.subtransactions)))for(let r of e.subtransactions)r?.category_id&&t.add(r.category_id)}function p0(...e){let t=new Set;for(let r of e)xA(r,t);return t}function Jue(e,t){if(e.size!==t.size)return!1;for(let r of e)if(!t.has(r))return!1;return!0}function rm(e,t,r,a,n,i,o={}){e.invalidate(r,"transactions"),ke.delete(be.generateKey("transactions","list",r));for(let p of n){let _=be.generateKey("transactions","account",r,p);ke.deleteByPrefix(_)}let s=o.accountTotalsChanged??!0;s&&ke.delete(be.generateKey("accounts","list",r));for(let p of n)ke.delete(be.generateKey("account","get",r,p));let d=o.affectedCategoryIds??new Set;if(o.invalidateAllCategories||d.size>0){ke.delete(be.generateKey("categories","list",r));for(let p of d)ke.delete(be.generateKey("category","get",r,p))}let l=o.invalidateMonths??i.size>0;if(l){ke.delete(be.generateKey("months","list",r)),e.invalidate(r,"months");for(let p of i)ke.delete(be.generateKey("month","get",r,p))}if(a!==void 0){let p=be.generateKey("transactions","list",r);if(t.update(p,a),s){let _=be.generateKey("accounts","list",r);t.update(_,a)}if(l&&i.size>0){let _=be.generateKey("months","list",r);t.update(_,a)}}}var DA=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().optional(),category_id:c.string().optional(),since_date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),type:c.enum(["uncategorized","unapproved"]).optional()}).strict(),kA=c.object({budget_id:c.string().min(1,"Budget ID is required"),transaction_id:c.string().min(1,"Transaction ID is required")}).strict(),yv=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().min(1,"Account ID is required"),amount:c.number().int("Amount must be an integer in milliunits"),date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)"),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional(),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),import_id:c.string().min(1,"Import ID cannot be empty").optional(),dry_run:c.boolean().optional(),subtransactions:c.array(c.object({amount:c.number().int("Subtransaction amount must be an integer in milliunits"),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional()}).strict()).min(1,"At least one subtransaction is required when provided").optional()}).strict().superRefine((e,t)=>{e.subtransactions&&e.subtransactions.length>0&&e.subtransactions.reduce((a,n)=>a+n.amount,0)!==e.amount&&t.addIssue({code:c.ZodIssueCode.custom,message:"Amount must equal the sum of subtransaction amounts",path:["amount"]})}),jue=yv.pick({account_id:!0,amount:!0,date:!0,payee_name:!0,payee_id:!0,category_id:!0,memo:!0,cleared:!0,approved:!0,flag_color:!0,import_id:!0}),que=jue.strict(),vv=c.object({budget_id:c.string().min(1,"Budget ID is required"),transactions:c.array(que).min(1,"At least one transaction is required").max(100,"A maximum of 100 transactions may be created at once"),dry_run:c.boolean().optional()}).strict(),RA=64*1024,IA=96*1024,EA=100*1024;function em(e){if(e.import_id)return e.import_id;let r=[`account:${e.account_id??""}`,`date:${e.date??""}`,`amount:${e.amount??0}`,`payee:${e.payee_id??e.payee_name??""}`,`category:${e.category_id??""}`,`memo:${e.memo??""}`,`cleared:${e.cleared??""}`,`approved:${e.approved??!1}`,`flag:${e.flag_color??""}`].join("|");return`hash:${(0,NA.createHash)("sha256").update(r).digest("hex").slice(0,16)}`}function tm(e){let t={};return e.account_id!==void 0&&(t.account_id=e.account_id),e.date!==void 0&&(t.date=e.date),e.amount!==void 0&&(t.amount=e.amount),e.cleared!==void 0&&(t.cleared=e.cleared),e.approved!==void 0&&(t.approved=e.approved),e.flag_color!==void 0&&(t.flag_color=e.flag_color),t.payee_id=e.payee_id??null,t.payee_name=e.payee_name??null,t.category_id=e.category_id??null,t.memo=e.memo??null,t.import_id=e.import_id??null,t}function bv(e,t,r){let a=new Map,n=new Map,i=t.transactions??[],o=(u,l,p)=>{let _=u.get(l);if(_){_.push(p);return}u.set(l,[p])};for(let u of i){if(!u.id)continue;let l=em(u);l.startsWith("hash:")?o(n,l,u.id):o(a,l,u.id)}let s=(u,l)=>{let p=u.get(l);if(!p||p.length===0)return;let[_]=p.splice(0,1);return p.length===0&&u.delete(l),_},d=[];for(let[u,l]of e.entries()){let p=tm(l),_=em(p);if(l.import_id&&r.has(l.import_id)){d.push({request_index:u,status:"duplicate",correlation_key:_});continue}let g;if(_.startsWith("hash:")?g=s(n,_):g=s(a,_),!g&&!_.startsWith("hash:")){let f=em(tm({...l,import_id:void 0}));g=s(n,f)}if(g){let f={request_index:u,status:"created",correlation_key:_};f.transaction_id=g,d.push(f);continue}Di.logError("ynab:create_transactions","correlate_results",{request_index:u,correlation_key:_,request:{account_id:l.account_id,date:l.date,amount:l.amount,import_id:l.import_id}},"correlation_failed"),d.push({request_index:u,status:"failed",correlation_key:_,error_code:"correlation_failed",error:"Unable to correlate request transaction with YNAB response"})}return d}function _u(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Uue(e){let t=(s,d)=>s?s.includes(d)?s:`${s} ${d}`:d;if(_u({...e,mode:"full"})<=RA)return{...e,mode:"full"};let{transactions:a,...n}=e,i={...n,message:t(e.message,"Response downgraded to summary to stay under size limits."),mode:"summary"};if(_u(i)<=IA)return i;let o={...i,results:n.results.map(s=>({request_index:s.request_index,status:s.status,transaction_id:s.transaction_id,correlation_key:s.correlation_key,error:s.error})),message:t(n.message,"Response downgraded to ids_only to meet 100KB limit."),mode:"ids_only"};if(_u(o)<=EA)return o;throw new Ir("RESPONSE_TOO_LARGE: Unable to format bulk create response within 100KB limit",`Batch size: ${e.summary.total_requested} transactions`,["Reduce the batch size and retry","Consider splitting into multiple smaller batches"])}var Bue=c.object({name:c.string().min(1,"Item name is required"),amount:c.number().finite("Item amount must be a finite number").refine(e=>e>=0,"Item amount must be zero or greater"),quantity:c.number().finite("Quantity must be a finite number").positive("Quantity must be greater than zero").optional(),memo:c.string().optional()}).strict(),Vue=c.object({category_id:c.string().min(1,"Category ID is required"),category_name:c.string().optional(),items:c.array(Bue).min(1,"Each category must include at least one item")}).strict(),PA=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().min(1,"Account ID is required"),payee_name:c.string().min(1,"Payee name is required"),date:c.string().regex(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),memo:c.string().optional(),receipt_subtotal:c.number().finite("Receipt subtotal must be a finite number").refine(e=>e>=0,"Receipt subtotal must be zero or greater").optional(),receipt_tax:c.number().finite("Receipt tax must be a finite number").refine(e=>e>=0,"Receipt tax must be zero or greater"),receipt_total:c.number().finite("Receipt total must be a finite number").refine(e=>e>0,"Receipt total must be greater than zero"),categories:c.array(Vue).min(1,"At least one categorized group is required to create a split transaction"),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),dry_run:c.boolean().optional()}).strict().superRefine((e,t)=>{let r=e.categories.flatMap(i=>i.items).reduce((i,o)=>i+o.amount,0);e.receipt_subtotal!==void 0&&Math.abs(e.receipt_subtotal-r)>.01&&t.addIssue({code:c.ZodIssueCode.custom,message:`Receipt subtotal (${e.receipt_subtotal.toFixed(2)}) does not match categorized items total (${r.toFixed(2)})`,path:["receipt_subtotal"]});let a=r+e.receipt_tax;Math.abs(a-e.receipt_total)>.01&&t.addIssue({code:c.ZodIssueCode.custom,message:`Receipt total (${e.receipt_total.toFixed(2)}) does not match subtotal plus tax (${a.toFixed(2)})`,path:["receipt_total"]})}),CA=c.object({budget_id:c.string().min(1,"Budget ID is required"),transaction_id:c.string().min(1,"Transaction ID is required"),account_id:c.string().optional(),amount:c.number().int("Amount must be an integer in milliunits").optional(),date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional(),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),dry_run:c.boolean().optional()}).strict(),Lue=c.object({id:c.string().min(1,"Transaction ID is required"),amount:c.number().int("Amount must be an integer in milliunits").optional(),date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional(),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),original_account_id:c.string().optional(),original_date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional()}).strict(),wv=c.object({budget_id:c.string().min(1,"Budget ID is required"),transactions:c.array(Lue).min(1,"At least one transaction is required").max(100,"A maximum of 100 transactions may be updated at once"),dry_run:c.boolean().optional()}).strict(),AA=c.object({budget_id:c.string().min(1,"Budget ID is required"),transaction_id:c.string().min(1,"Transaction ID is required"),dry_run:c.boolean().optional()}).strict();async function MA(e,t,r){let{deltaFetcher:a,params:n}=Xr(e,t,r);return await mt(async()=>{let i,o=!1,s=!1;if(n.account_id){let l=await a.fetchTransactionsByAccount(n.budget_id,n.account_id,n.since_date);i=l.data,o=l.wasCached,s=l.usedDelta}else if(n.category_id)i=(await e.transactions.getTransactionsByCategory(n.budget_id,n.category_id,n.since_date)).data.transactions;else{let l=await a.fetchTransactions(n.budget_id,n.since_date,n.type);i=l.data,o=l.wasCached,s=l.usedDelta}let d=JSON.stringify(i).length;if(d>9e4){let l=i.slice(0,50);return{content:[{type:"text",text:he.format({message:`Found ${i.length} transactions (${Math.round(d/1024)}KB). Too large to display all.`,suggestion:"Use 'export_transactions' tool to save all transactions to a file.",showing:`First ${l.length} transactions:`,total_count:i.length,estimated_size_kb:Math.round(d/1024),cached:o,cache_info:o?`Data retrieved from cache for improved performance${s?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API",preview_transactions:l.map(p=>({id:p.id,date:p.date,amount:fe(p.amount),memo:p.memo,payee_name:p.payee_name,category_name:p.category_name}))})}]}}return{content:[{type:"text",text:he.format({total_count:i.length,cached:o,cache_info:o?`Data retrieved from cache for improved performance${s?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API",transactions:i.map(l=>({id:l.id,date:l.date,amount:fe(l.amount),memo:l.memo,cleared:l.cleared,approved:l.approved,flag_color:l.flag_color,account_id:l.account_id,payee_id:l.payee_id,category_id:l.category_id,transfer_account_id:l.transfer_account_id,transfer_transaction_id:l.transfer_transaction_id,matched_transaction_id:l.matched_transaction_id,import_id:l.import_id,deleted:l.deleted}))})}]}},"ynab:list_transactions","listing transactions")}async function FA(e,t){try{let r=process.env.NODE_ENV!=="test",a,n=!1;if(r){let i=be.generateKey("transaction","get",t.budget_id,t.transaction_id);n=ke.has(i),a=await ke.wrap(i,{ttl:It.TRANSACTIONS,loader:async()=>{let o=await e.transactions.getTransactionById(t.budget_id,t.transaction_id);return yu(o.data.transaction,"Transaction not found")}})}else{let i=await e.transactions.getTransactionById(t.budget_id,t.transaction_id);a=yu(i.data.transaction,"Transaction not found")}return{content:[{type:"text",text:he.format({transaction:{id:a.id,date:a.date,amount:fe(a.amount),memo:a.memo,cleared:a.cleared,approved:a.approved,flag_color:a.flag_color,account_id:a.account_id,payee_id:a.payee_id,category_id:a.category_id,transfer_account_id:a.transfer_account_id,transfer_transaction_id:a.transfer_transaction_id,matched_transaction_id:a.matched_transaction_id,import_id:a.import_id,deleted:a.deleted,account_name:a.account_name,payee_name:a.payee_name,category_name:a.category_name},cached:n,cache_info:n?"Data retrieved from cache for improved performance":"Fresh data retrieved from YNAB API"})}]}}catch(r){return m0(r,"Failed to get transaction")}}async function Sv(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);try{if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_transaction",request:o})}]};let s={account_id:o.account_id,amount:o.amount,date:o.date,cleared:o.cleared,flag_color:o.flag_color};if(o.payee_name!==void 0&&(s.payee_name=o.payee_name),o.payee_id!==void 0&&(s.payee_id=o.payee_id),o.category_id!==void 0&&(s.category_id=o.category_id),o.memo!==void 0&&(s.memo=o.memo),o.approved!==void 0&&(s.approved=o.approved),o.import_id!==void 0&&(s.import_id=o.import_id),o.subtransactions&&o.subtransactions.length>0){let m=o.subtransactions.map(h=>{let y={amount:h.amount};return h.payee_name!==void 0&&(y.payee_name=h.payee_name),h.payee_id!==void 0&&(y.payee_id=h.payee_id),h.category_id!==void 0&&(y.category_id=h.category_id),h.memo!==void 0&&(y.memo=h.memo),y});s.subtransactions=m}let d=await e.transactions.createTransaction(o.budget_id,{transaction:s}),u=yu(d.data.transaction,"Transaction creation failed"),l=new Set([u.account_id]),p=new Set([Jo(u.date)]),_=p0(u);rm(n,i,o.budget_id,d.data.server_knowledge,l,p,{affectedCategoryIds:_,accountTotalsChanged:!0,invalidateMonths:!0});let f=(await e.accounts.getAccountById(o.budget_id,u.account_id)).data.account;return{content:[{type:"text",text:he.format({transaction:{id:u.id,date:u.date,amount:fe(u.amount),memo:u.memo,cleared:u.cleared,approved:u.approved,flag_color:u.flag_color,account_id:u.account_id,payee_id:u.payee_id,category_id:u.category_id,transfer_account_id:u.transfer_account_id,transfer_transaction_id:u.transfer_transaction_id,matched_transaction_id:u.matched_transaction_id,import_id:u.import_id,deleted:u.deleted,account_balance:f.balance,account_cleared_balance:f.cleared_balance,subtransactions:u.subtransactions?.map(m=>({id:m.id,transaction_id:m.transaction_id,amount:fe(m.amount),memo:m.memo,payee_id:m.payee_id,payee_name:m.payee_name,category_id:m.category_id,category_name:m.category_name,transfer_account_id:m.transfer_account_id,transfer_transaction_id:m.transfer_transaction_id,deleted:m.deleted}))}})}]}}catch(s){return m0(s,"Failed to create transaction")}}function Wue(e){let t=e.quantity?` (x${e.quantity})`:"";return e.memo&&e.memo.trim().length>0?`${e.name}${t} - ${e.memo}`:t?`${e.name}${t}`:e.name}function Yue(e,t,r){if(t===0){for(let n of r)n.tax_milliunits=0;return}if(e<=0)throw new Error("Receipt subtotal must be greater than zero to distribute tax");let a=0;r.forEach((n,i)=>{if(i===r.length-1)n.tax_milliunits=t-a;else{let o=Math.round(t*n.subtotal_milliunits/e);n.tax_milliunits=o,a+=o}})}async function zA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a),s=o.date??new Date().toISOString().slice(0,10),d=o.categories.map(w=>{let R=w.items.map(M=>({name:M.name,amount_milliunits:Qp(M.amount),quantity:M.quantity,memo:M.memo})),N=R.reduce((M,X)=>M+X.amount_milliunits,0);return{category_id:w.category_id,category_name:w.category_name,subtotal_milliunits:N,tax_milliunits:0,items:R}}),u=d.reduce((w,R)=>w+R.subtotal_milliunits,0),l=o.receipt_subtotal!==void 0?Qp(o.receipt_subtotal):void 0;if(l!==void 0&&Math.abs(l-u)>1)throw new Error(`Categorized items subtotal (${fe(u)}) does not match receipt subtotal (${fe(l)})`);let p=Qp(o.receipt_tax),_=Qp(o.receipt_total),g=u+p;if(Math.abs(g-_)>1)throw new Error(`Receipt total (${fe(_)}) does not equal subtotal plus tax (${fe(g)})`);Yue(u,p,d);let f=d.flatMap(w=>{let R=w.items.map(M=>{let X=Wue({name:M.name,quantity:M.quantity,memo:M.memo}),q={amount:-M.amount_milliunits,category_id:w.category_id};return X&&(q.memo=X),q}),N=w.tax_milliunits>0?[{amount:-w.tax_milliunits,category_id:w.category_id,memo:`Tax - ${w.category_name??"Uncategorized"}`}]:[];return[...R,...N]}),m={subtotal:fe(u),tax:fe(p),total:fe(_),categories:d.map(w=>({category_id:w.category_id,category_name:w.category_name,items:w.items.map(R=>({name:R.name,quantity:R.quantity,amount:fe(R.amount_milliunits),memo:R.memo})),subtotal:fe(w.subtotal_milliunits),tax:fe(w.tax_milliunits),total:fe(w.subtotal_milliunits+w.tax_milliunits)}))};if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_receipt_split_transaction",transaction_preview:{account_id:o.account_id,payee_name:o.payee_name,date:s,amount:fe(_),cleared:o.cleared??"uncleared"},receipt_summary:m,subtransactions:f.map(w=>({amount:fe(-w.amount),category_id:w.category_id,memo:w.memo}))})}]};let h={budget_id:o.budget_id,account_id:o.account_id,amount:-_,date:s,payee_name:o.payee_name,memo:o.memo,cleared:o.cleared??"uncleared",flag_color:o.flag_color,subtransactions:f};o.approved!==void 0&&(h.approved=o.approved);let y=await Sv(e,n,i,h),b=y.content?.[0];if(!b||b.type!=="text")return y;try{let w=JSON.parse(b.text);w.receipt_summary=m,b.text=he.format(w)}catch{}return y}async function JA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);try{if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"update_transaction",request:o})}]};let s=await e.transactions.getTransactionById(o.budget_id,o.transaction_id),d=yu(s.data.transaction,"Original transaction not found"),u={};o.account_id!==void 0&&(u.account_id=o.account_id),o.amount!==void 0&&(u.amount=o.amount),o.date!==void 0&&(u.date=o.date),o.payee_name!==void 0&&(u.payee_name=o.payee_name),o.payee_id!==void 0&&(u.payee_id=o.payee_id),o.category_id!==void 0&&(u.category_id=o.category_id),o.memo!==void 0&&(u.memo=o.memo),o.cleared!==void 0&&(u.cleared=o.cleared),o.approved!==void 0&&(u.approved=o.approved),o.flag_color!==void 0&&(u.flag_color=o.flag_color);let l=await e.transactions.updateTransaction(o.budget_id,o.transaction_id,{transaction:u}),p=yu(l.data.transaction,"Transaction update failed"),_=be.generateKey("transaction","get",o.budget_id,o.transaction_id);ke.delete(_);let g=new Set([d.account_id,p.account_id]);d.transfer_account_id&&g.add(d.transfer_account_id),p.transfer_account_id&&g.add(p.transfer_account_id);let f=new Set([Jo(d.date),Jo(p.date)]),m=p0(d),h=p0(p),y=new Set([...m,...h]),b=!Jue(m,h),w=p.amount!==d.amount,R=p.account_id!==d.account_id,N=p.cleared!==d.cleared,M=p.transfer_account_id!==d.transfer_account_id,X=p.transfer_transaction_id!==d.transfer_transaction_id,q=p.date!==d.date;rm(n,i,o.budget_id,l.data.server_knowledge,g,f,{affectedCategoryIds:y,accountTotalsChanged:w||R||N||M||X,invalidateMonths:w||b||q});let oe=(await e.accounts.getAccountById(o.budget_id,p.account_id)).data.account;return{content:[{type:"text",text:he.format({transaction:{id:p.id,date:p.date,amount:fe(p.amount),memo:p.memo,cleared:p.cleared,approved:p.approved,flag_color:p.flag_color,account_id:p.account_id,payee_id:p.payee_id,category_id:p.category_id,transfer_account_id:p.transfer_account_id,transfer_transaction_id:p.transfer_transaction_id,matched_transaction_id:p.matched_transaction_id,import_id:p.import_id,deleted:p.deleted},updated_balance:oe.balance,updated_cleared_balance:oe.cleared_balance})}]}}catch(s){return m0(s,"Failed to update transaction")}}async function jA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);try{if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"delete_transaction",request:o})}]};let s=await e.transactions.deleteTransaction(o.budget_id,o.transaction_id),d=yu(s.data.transaction,"Transaction deletion failed"),u=be.generateKey("transaction","get",o.budget_id,o.transaction_id);ke.delete(u);let l=new Set([d.account_id]);d.transfer_account_id&&l.add(d.transfer_account_id);let p=new Set([Jo(d.date)]),_=p0(d);rm(n,i,o.budget_id,s.data.server_knowledge,l,p,{affectedCategoryIds:_,accountTotalsChanged:!0,invalidateMonths:!0});let f=(await e.accounts.getAccountById(o.budget_id,d.account_id)).data.account;return{content:[{type:"text",text:he.format({message:"Transaction deleted successfully",transaction:{id:d.id,deleted:d.deleted},updated_balance:f.balance,updated_cleared_balance:f.cleared_balance})}]}}catch(s){return m0(s,"Failed to delete transaction")}}async function qA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);return await mt(async()=>{let s=vv.safeParse(o);if(!s.success){let q=new Map,ne=s.error.issues??[];for(let V of ne){let x=V.path.find(U=>typeof U=="number"),S=V.message,D=x!==void 0?x:null,P=q.get(D)??[];P.push(S),q.set(D,P)}let oe=Array.from(q.entries()).map(([V,x])=>({transaction_index:V,errors:x}));throw new Ir("Bulk transaction validation failed",JSON.stringify(oe,null,2),["Ensure each transaction includes required fields","Limit batches to 100 items"])}let{budget_id:d,transactions:u,dry_run:l}=s.data,p=new Map;for(let[q,ne]of u.entries())if(ne.import_id&&ne.import_id.trim().length>0){let oe=p.get(ne.import_id);oe?oe.push(q):p.set(ne.import_id,[q])}let _=Array.from(p.entries()).filter(([,q])=>q.length>1).map(([q,ne])=>({import_id:q,indices:ne}));if(_.length>0){let q=_.map(({import_id:ne,indices:oe})=>({import_id:ne,transaction_indices:oe,count:oe.length}));throw new Ir("Duplicate import_id values detected within batch",JSON.stringify(q,null,2),["Ensure each transaction has a unique import_id within the batch","Remove duplicate import_id values or omit import_id to use hash-based correlation"])}if(l){let q=u.reduce((D,P)=>D+P.amount,0),ne=Array.from(new Set(u.map(D=>D.account_id))),oe=Array.from(new Set(u.map(D=>D.category_id).filter(D=>D!==void 0))),V=[...u.map(D=>D.date)].sort(),x=V.length>0?{earliest:V[0],latest:V[V.length-1]}:void 0,S=u.slice(0,10).map((D,P)=>({request_index:P,account_id:D.account_id,date:D.date,amount:fe(D.amount),memo:D.memo,payee_id:D.payee_id,payee_name:D.payee_name,category_id:D.category_id,import_id:D.import_id}));return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_transactions",validation:"passed",summary:{total_transactions:u.length,total_amount:fe(q),accounts_affected:ne,date_range:x,categories_affected:oe},transactions_preview:S,note:"Dry run complete. No transactions created. No caches invalidated. No server_knowledge updated."})}]}}let g=u.map(q=>{let ne={account_id:q.account_id,amount:q.amount,date:q.date};return q.payee_id!==void 0&&(ne.payee_id=q.payee_id),q.payee_name!==void 0&&(ne.payee_name=q.payee_name),q.category_id!==void 0&&(ne.category_id=q.category_id),q.memo!==void 0&&(ne.memo=q.memo),q.cleared!==void 0&&(ne.cleared=q.cleared),q.approved!==void 0&&(ne.approved=q.approved),q.flag_color!==void 0&&(ne.flag_color=q.flag_color),q.import_id!==void 0&&(ne.import_id=q.import_id),ne}),m=(await e.transactions.createTransactions(d,{transactions:g})).data,h=new Set(m.duplicate_import_ids??[]),y=bv(u,m,h),b={total_requested:u.length,created:m.transaction_ids?.length??0,duplicates:h.size,failed:y.filter(q=>q.status==="failed").length},w={success:b.failed===0,server_knowledge:m.server_knowledge,summary:b,results:y,transactions:m.transactions??[],duplicate_import_ids:m.duplicate_import_ids??[],message:`Processed ${b.total_requested} transactions: ${b.created} created, ${b.duplicates} duplicates, ${b.failed} failed.`},R=new Set(u.map(q=>q.account_id)),N=new Set(u.map(q=>Jo(q.date))),M=new Set;for(let q of m.transactions??[])xA(q,M);rm(n,i,d,m.server_knowledge,R,N,{affectedCategoryIds:M,accountTotalsChanged:!0,invalidateMonths:!0});let X=Uue(w);return{content:[{type:"text",text:he.format(X)}]}},"ynab:create_transactions","bulk transaction creation")}async function OA(e,t,r,a={}){let n=new Map,i=[],o=new Set(a.previewTransactionIds??[]),s=new Map,d=new Set(o);for(let h of r)h.original_account_id&&h.original_date?n.set(h.id,{account_id:h.original_account_id,date:h.original_date}):i.push(h.id);if(o.size===0&&i.length===0)return{metadata:n,unresolvedIds:[],previewDetails:s};let u=new Set(i),l=new Set([...i,...o]);for(let h of l){let y=be.generateKey("transaction","get",t,h),b=ke.get(y);b&&(u.has(h)&&(n.set(h,{account_id:b.account_id,date:b.date}),u.delete(h)),o.has(h)&&!s.has(h)&&(s.set(h,b),d.delete(h)))}let p=Array.from(u);if(p.length===0&&d.size===0)return{metadata:n,unresolvedIds:[],previewDetails:s};let _=5,g=[],f=new Set(p),m=Array.from(new Set([...p,...d]));for(let h=0;h<m.length;h+=_){let b=m.slice(h,h+_).map(async w=>{try{let N=(await e.transactions.getTransactionById(t,w)).data.transaction;N&&(f.has(w)&&(n.set(w,{account_id:N.account_id,date:N.date}),f.delete(w)),d.has(w)&&!s.has(w)&&(s.set(w,N),d.delete(w)))}catch{f.has(w)&&Di.logError("ynab:update_transactions","resolve_metadata",{transaction_id:w},"Failed to resolve transaction metadata")}});g.push(...b)}return await Promise.all(g),{metadata:n,unresolvedIds:Array.from(f),previewDetails:s}}function Zue(e){let t=(s,d)=>s?s.includes(d)?s:`${s} ${d}`:d;if(_u(e)<=RA)return{...e,mode:"full"};let{transactions:a,...n}=e,i={...n,message:t(e.message,"Response downgraded to summary to stay under size limits."),mode:"summary"};if(_u(i)<=IA)return i;let o={...i,results:n.results.map(s=>{let d={request_index:s.request_index,status:s.status,transaction_id:s.transaction_id,correlation_key:s.correlation_key};return s.error&&(d.error=s.error),s.error_code&&(d.error_code=s.error_code),d}),message:t(n.message,"Response downgraded to ids_only to meet 100KB limit."),mode:"ids_only"};if(_u(o)<=EA)return o;throw new Ir("RESPONSE_TOO_LARGE: Unable to format bulk update response within 100KB limit",`Batch size: ${e.summary.total_requested} transactions`,["Reduce the batch size and retry","Consider splitting into multiple smaller batches"])}async function UA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);return await mt(async()=>{let s=wv.safeParse(o);if(!s.success){let D=new Map,P=s.error.issues??[];for(let F of P){let j=F.path.find(C=>typeof C=="number"),J=F.message,ee=j!==void 0?j:null,se=D.get(ee)??[];se.push(J),D.set(ee,se)}let U=Array.from(D.entries()).map(([F,j])=>({transaction_index:F,errors:j}));throw new Ir("Bulk transaction update validation failed",JSON.stringify(U,null,2),["Ensure each transaction includes an id field","Limit batches to 100 items"])}let{budget_id:d,transactions:u,dry_run:l}=s.data;if(l){let D=u.slice(0,10),P=D.map(k=>k.id),{metadata:U,unresolvedIds:F,previewDetails:j}=await OA(e,d,u,{previewTransactionIds:P}),J=[],ee=[];for(let k of D){let O=j.get(k.id);if(!O){ee.push(k.id),J.push({transaction_id:k.id,before:"unavailable",after:k});continue}let te={},A={};k.amount!==void 0&&k.amount!==O.amount&&(te.amount=fe(O.amount),A.amount=fe(k.amount)),k.date!==void 0&&k.date!==O.date&&(te.date=O.date,A.date=k.date),k.memo!==void 0&&k.memo!==O.memo&&(te.memo=O.memo,A.memo=k.memo),k.payee_id!==void 0&&k.payee_id!==O.payee_id&&(te.payee_id=O.payee_id,A.payee_id=k.payee_id),k.payee_name!==void 0&&k.payee_name!==O.payee_name&&(te.payee_name=O.payee_name,A.payee_name=k.payee_name),k.category_id!==void 0&&k.category_id!==O.category_id&&(te.category_id=O.category_id,A.category_id=k.category_id),k.cleared!==void 0&&k.cleared!==O.cleared&&(te.cleared=O.cleared,A.cleared=k.cleared),k.approved!==void 0&&k.approved!==O.approved&&(te.approved=O.approved,A.approved=k.approved),k.flag_color!==void 0&&k.flag_color!==O.flag_color&&(te.flag_color=O.flag_color,A.flag_color=k.flag_color),J.push({transaction_id:k.id,before:te,after:A})}let se=[];if(ee.length>0||F.length>0){let k=Math.max(ee.length,F.length),O=F.length>0?F.slice(0,10):ee.slice(0,10);se.push({code:"metadata_unavailable",count:k,message:`Unable to fetch prior state for ${k} transactions`,sample_ids:O})}let C=Array.from(new Set(Array.from(U.values()).map(k=>k.account_id))),$=new Set;for(let k of u)k.amount!==void 0&&$.add("amount"),k.date!==void 0&&$.add("date"),k.memo!==void 0&&$.add("memo"),k.payee_id!==void 0&&$.add("payee_id"),k.payee_name!==void 0&&$.add("payee_name"),k.category_id!==void 0&&$.add("category_id"),k.cleared!==void 0&&$.add("cleared"),k.approved!==void 0&&$.add("approved"),k.flag_color!==void 0&&$.add("flag_color");let E={dry_run:!0,action:"update_transactions",validation:"passed",summary:{total_transactions:u.length,accounts_affected:C,fields_to_update:Array.from($)},transactions_preview:J,note:"Dry run complete. No transactions updated. No caches invalidated. No server_knowledge updated."};return se.length>0&&(E.warnings=se),{content:[{type:"text",text:he.format(E)}]}}let{metadata:p,unresolvedIds:_}=await OA(e,d,u),g=_.length/u.length,f=.05;if(g>f)throw new Ir(`METADATA_INCOMPLETE: ${(g*100).toFixed(1)}% of transactions have missing metadata (threshold: ${(f*100).toFixed(0)}%)`,JSON.stringify({unresolved_count:_.length,total_transactions:u.length,ratio:(g*100).toFixed(1)+"%",threshold:(f*100).toFixed(0)+"%",sample_unresolved_ids:_.slice(0,5)},null,2),["Provide original_account_id and original_date for all transactions being updated","Ensure transactions exist in YNAB before updating them"]);g>.01&&Di.logRequest("ynab:update_transactions","metadata_resolution_warning",{unresolved_count:_.length,total_transactions:u.length,ratio:g.toFixed(3),sample_ids:_.slice(0,5),message:"Metadata resolution incomplete for some transactions"},!0);let m=u.map(D=>{let P={};return D.amount!==void 0&&(P.amount=D.amount),D.date!==void 0&&(P.date=D.date),D.payee_name!==void 0&&(P.payee_name=D.payee_name),D.payee_id!==void 0&&(P.payee_id=D.payee_id),D.category_id!==void 0&&(P.category_id=D.category_id),D.memo!==void 0&&(P.memo=D.memo),D.cleared!==void 0&&(P.cleared=D.cleared),D.approved!==void 0&&(P.approved=D.approved),D.flag_color!==void 0&&(P.flag_color=D.flag_color),{id:D.id,transaction:P}}),y=(await e.transactions.updateTransactions(d,{transactions:m})).data,b=y.transactions??[],w=[],R=new Set(b.map(D=>D.id));for(let[D,P]of u.entries())R.has(P.id)?w.push({request_index:D,status:"updated",transaction_id:P.id,correlation_key:P.id}):w.push({request_index:D,status:"failed",transaction_id:P.id,correlation_key:P.id,error_code:"update_failed",error:"Transaction was not updated by YNAB API"});let N={total_requested:u.length,updated:b.length,failed:w.filter(D=>D.status==="failed").length},M={success:N.failed===0,server_knowledge:y.server_knowledge,summary:N,results:w,transactions:b,message:`Processed ${N.total_requested} transactions: ${N.updated} updated, ${N.failed} failed.`};for(let D of u)ke.delete(be.generateKey("transaction","get",d,D.id));let X=new Set,q=new Set,ne=new Set,oe=!1,V=!1,x=!1;for(let D of u){let P=p.get(D.id),U=D.amount!==void 0,F=D.cleared!==void 0,j=D.category_id!==void 0,J=D.date!==void 0;(U||F)&&P&&X.add(P.account_id),U&&(x=!0,V=!0,oe=!0,P&&q.add(Jo(P.date))),j&&(x=!0,oe=!0,D.category_id&&ne.add(D.category_id),P&&q.add(Jo(P.date))),J&&P&&(x=!0,q.add(Jo(P.date))),J&&D.date&&q.add(Jo(D.date))}rm(n,i,d,y.server_knowledge,X,q,{affectedCategoryIds:ne,invalidateAllCategories:oe,accountTotalsChanged:V,invalidateMonths:x});let S=Zue(M);return{content:[{type:"text",text:he.format(S)}]}},"ynab:update_transactions","bulk transaction update")}function m0(e,t){let r=t;return e instanceof Error&&(e.message.includes("401")||e.message.includes("Unauthorized")?r="Invalid or expired YNAB access token":e.message.includes("403")||e.message.includes("Forbidden")?r="Insufficient permissions to access YNAB data":e.message.includes("404")||e.message.includes("Not Found")?r="Budget, account, category, or transaction not found":e.message.includes("429")||e.message.includes("Too Many Requests")?r="Rate limit exceeded. Please try again later":(e.message.includes("500")||e.message.includes("Internal Server Error"))&&(r="YNAB service is currently unavailable")),{content:[{type:"text",text:he.format({error:{message:r}})}]}}var om=require("fs");var Hue=Math.pow(10,8)*24*60*60*1e3,p7e=-Hue,f0=6048e5,BA=864e5,VA=6e4,LA=36e5,WA=1e3;var Gue=3600;var YA=Gue*24,m7e=YA*7,Kue=YA*365.2425,Xue=Kue/12,f7e=Xue*3,Tv=Symbol.for("constructDateFrom");function dt(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Tv in e?e[Tv](t):e instanceof Date?new e.constructor(t):new Date(t)}function Be(e,t){return dt(t||e,e)}function h0(e,t,r){let a=Be(e,r?.in);return isNaN(t)?dt(r?.in||e,NaN):(t&&a.setDate(a.getDate()+t),a)}var Que={};function ai(){return Que}function Qr(e,t){let r=ai(),a=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=Be(e,t?.in),i=n.getDay(),o=(i<a?7:0)+i-a;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Ri(e,t){return Qr(e,{...t,weekStartsOn:1})}function g0(e,t){let r=Be(e,t?.in),a=r.getFullYear(),n=dt(r,0);n.setFullYear(a+1,0,4),n.setHours(0,0,0,0);let i=Ri(n),o=dt(r,0);o.setFullYear(a,0,4),o.setHours(0,0,0,0);let s=Ri(o);return r.getTime()>=i.getTime()?a+1:r.getTime()>=s.getTime()?a:a-1}function Bd(e){let t=Be(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function ZA(e,...t){let r=dt.bind(null,e||t.find(a=>typeof a=="object"));return t.map(r)}function $v(e,t){let r=Be(e,t?.in);return r.setHours(0,0,0,0),r}function HA(e,t,r){let[a,n]=ZA(r?.in,e,t),i=$v(a),o=$v(n),s=+i-Bd(i),d=+o-Bd(o);return Math.round((s-d)/BA)}function GA(e,t){let r=g0(e,t),a=dt(t?.in||e,0);return a.setFullYear(r,0,4),a.setHours(0,0,0,0),Ri(a)}function KA(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function XA(e){return!(!KA(e)&&typeof e!="number"||isNaN(+Be(e)))}function QA(e,t){let r=Be(e,t?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}var ele={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},eM=(e,t,r)=>{let a,n=ele[e];return typeof n=="string"?a=n:t===1?a=n.one:a=n.other.replace("{{count}}",t.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+a:a+" ago":a};function _0(e){return(t={})=>{let r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}var tle={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},rle={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},nle={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},tM={date:_0({formats:tle,defaultWidth:"full"}),time:_0({formats:rle,defaultWidth:"full"}),dateTime:_0({formats:nle,defaultWidth:"full"})};var ale={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},rM=(e,t,r,a)=>ale[e];function vu(e){return(t,r)=>{let a=r?.context?String(r.context):"standalone",n;if(a==="formatting"&&e.formattingValues){let o=e.defaultFormattingWidth||e.defaultWidth,s=r?.width?String(r.width):o;n=e.formattingValues[s]||e.formattingValues[o]}else{let o=e.defaultWidth,s=r?.width?String(r.width):e.defaultWidth;n=e.values[s]||e.values[o]}let i=e.argumentCallback?e.argumentCallback(t):t;return n[i]}}var ile={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ole={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},sle={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},dle={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},cle={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},ule={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},lle=(e,t)=>{let r=Number(e),a=r%100;if(a>20||a<10)switch(a%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},nM={ordinalNumber:lle,era:vu({values:ile,defaultWidth:"wide"}),quarter:vu({values:ole,defaultWidth:"wide",argumentCallback:e=>e-1}),month:vu({values:sle,defaultWidth:"wide"}),day:vu({values:dle,defaultWidth:"wide"}),dayPeriod:vu({values:cle,defaultWidth:"wide",formattingValues:ule,defaultFormattingWidth:"wide"})};function bu(e){return(t,r={})=>{let a=r.width,n=a&&e.matchPatterns[a]||e.matchPatterns[e.defaultMatchWidth],i=t.match(n);if(!i)return null;let o=i[0],s=a&&e.parsePatterns[a]||e.parsePatterns[e.defaultParseWidth],d=Array.isArray(s)?mle(s,p=>p.test(o)):ple(s,p=>p.test(o)),u;u=e.valueCallback?e.valueCallback(d):d,u=r.valueCallback?r.valueCallback(u):u;let l=t.slice(o.length);return{value:u,rest:l}}}function ple(e,t){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function mle(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function aM(e){return(t,r={})=>{let a=t.match(e.matchPattern);if(!a)return null;let n=a[0],i=t.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=r.valueCallback?r.valueCallback(o):o;let s=t.slice(n.length);return{value:o,rest:s}}}var fle=/^(\d+)(th|st|nd|rd)?/i,hle=/\d+/i,gle={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},_le={any:[/^b/i,/^(a|c)/i]},yle={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},vle={any:[/1/i,/2/i,/3/i,/4/i]},ble={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},wle={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Sle={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Tle={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},$le={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Ole={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},iM={ordinalNumber:aM({matchPattern:fle,parsePattern:hle,valueCallback:e=>parseInt(e,10)}),era:bu({matchPatterns:gle,defaultMatchWidth:"wide",parsePatterns:_le,defaultParseWidth:"any"}),quarter:bu({matchPatterns:yle,defaultMatchWidth:"wide",parsePatterns:vle,defaultParseWidth:"any",valueCallback:e=>e+1}),month:bu({matchPatterns:ble,defaultMatchWidth:"wide",parsePatterns:wle,defaultParseWidth:"any"}),day:bu({matchPatterns:Sle,defaultMatchWidth:"wide",parsePatterns:Tle,defaultParseWidth:"any"}),dayPeriod:bu({matchPatterns:$le,defaultMatchWidth:"any",parsePatterns:Ole,defaultParseWidth:"any"})};var nm={code:"en-US",formatDistance:eM,formatLong:tM,formatRelative:rM,localize:nM,match:iM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function oM(e,t){let r=Be(e,t?.in);return HA(r,QA(r))+1}function y0(e,t){let r=Be(e,t?.in),a=+Ri(r)-+GA(r);return Math.round(a/f0)+1}function wu(e,t){let r=Be(e,t?.in),a=r.getFullYear(),n=ai(),i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=dt(t?.in||e,0);o.setFullYear(a+1,0,i),o.setHours(0,0,0,0);let s=Qr(o,t),d=dt(t?.in||e,0);d.setFullYear(a,0,i),d.setHours(0,0,0,0);let u=Qr(d,t);return+r>=+s?a+1:+r>=+u?a:a-1}function sM(e,t){let r=ai(),a=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=wu(e,t),i=dt(t?.in||e,0);return i.setFullYear(n,0,a),i.setHours(0,0,0,0),Qr(i,t)}function v0(e,t){let r=Be(e,t?.in),a=+Qr(r,t)-+sM(r,t);return Math.round(a/f0)+1}function lt(e,t){let r=e<0?"-":"",a=Math.abs(e).toString().padStart(t,"0");return r+a}var jo={y(e,t){let r=e.getFullYear(),a=r>0?r:1-r;return lt(t==="yy"?a%100:a,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):lt(r+1,2)},d(e,t){return lt(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return lt(e.getHours()%12||12,t.length)},H(e,t){return lt(e.getHours(),t.length)},m(e,t){return lt(e.getMinutes(),t.length)},s(e,t){return lt(e.getSeconds(),t.length)},S(e,t){let r=t.length,a=e.getMilliseconds(),n=Math.trunc(a*Math.pow(10,r-3));return lt(n,t.length)}};var Su={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ov={G:function(e,t,r){let a=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return r.era(a,{width:"abbreviated"});case"GGGGG":return r.era(a,{width:"narrow"});case"GGGG":default:return r.era(a,{width:"wide"})}},y:function(e,t,r){if(t==="yo"){let a=e.getFullYear(),n=a>0?a:1-a;return r.ordinalNumber(n,{unit:"year"})}return jo.y(e,t)},Y:function(e,t,r,a){let n=wu(e,a),i=n>0?n:1-n;if(t==="YY"){let o=i%100;return lt(o,2)}return t==="Yo"?r.ordinalNumber(i,{unit:"year"}):lt(i,t.length)},R:function(e,t){let r=g0(e);return lt(r,t.length)},u:function(e,t){let r=e.getFullYear();return lt(r,t.length)},Q:function(e,t,r){let a=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(a);case"QQ":return lt(a,2);case"Qo":return r.ordinalNumber(a,{unit:"quarter"});case"QQQ":return r.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(a,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(a,{width:"wide",context:"formatting"})}},q:function(e,t,r){let a=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(a);case"qq":return lt(a,2);case"qo":return r.ordinalNumber(a,{unit:"quarter"});case"qqq":return r.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(a,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(a,{width:"wide",context:"standalone"})}},M:function(e,t,r){let a=e.getMonth();switch(t){case"M":case"MM":return jo.M(e,t);case"Mo":return r.ordinalNumber(a+1,{unit:"month"});case"MMM":return r.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(a,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(a,{width:"wide",context:"formatting"})}},L:function(e,t,r){let a=e.getMonth();switch(t){case"L":return String(a+1);case"LL":return lt(a+1,2);case"Lo":return r.ordinalNumber(a+1,{unit:"month"});case"LLL":return r.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(a,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(a,{width:"wide",context:"standalone"})}},w:function(e,t,r,a){let n=v0(e,a);return t==="wo"?r.ordinalNumber(n,{unit:"week"}):lt(n,t.length)},I:function(e,t,r){let a=y0(e);return t==="Io"?r.ordinalNumber(a,{unit:"week"}):lt(a,t.length)},d:function(e,t,r){return t==="do"?r.ordinalNumber(e.getDate(),{unit:"date"}):jo.d(e,t)},D:function(e,t,r){let a=oM(e);return t==="Do"?r.ordinalNumber(a,{unit:"dayOfYear"}):lt(a,t.length)},E:function(e,t,r){let a=e.getDay();switch(t){case"E":case"EE":case"EEE":return r.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(a,{width:"short",context:"formatting"});case"EEEE":default:return r.day(a,{width:"wide",context:"formatting"})}},e:function(e,t,r,a){let n=e.getDay(),i=(n-a.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return lt(i,2);case"eo":return r.ordinalNumber(i,{unit:"day"});case"eee":return r.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(n,{width:"short",context:"formatting"});case"eeee":default:return r.day(n,{width:"wide",context:"formatting"})}},c:function(e,t,r,a){let n=e.getDay(),i=(n-a.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return lt(i,t.length);case"co":return r.ordinalNumber(i,{unit:"day"});case"ccc":return r.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(n,{width:"narrow",context:"standalone"});case"cccccc":return r.day(n,{width:"short",context:"standalone"});case"cccc":default:return r.day(n,{width:"wide",context:"standalone"})}},i:function(e,t,r){let a=e.getDay(),n=a===0?7:a;switch(t){case"i":return String(n);case"ii":return lt(n,t.length);case"io":return r.ordinalNumber(n,{unit:"day"});case"iii":return r.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(a,{width:"short",context:"formatting"});case"iiii":default:return r.day(a,{width:"wide",context:"formatting"})}},a:function(e,t,r){let n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(e,t,r){let a=e.getHours(),n;switch(a===12?n=Su.noon:a===0?n=Su.midnight:n=a/12>=1?"pm":"am",t){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,t,r){let a=e.getHours(),n;switch(a>=17?n=Su.evening:a>=12?n=Su.afternoon:a>=4?n=Su.morning:n=Su.night,t){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,t,r){if(t==="ho"){let a=e.getHours()%12;return a===0&&(a=12),r.ordinalNumber(a,{unit:"hour"})}return jo.h(e,t)},H:function(e,t,r){return t==="Ho"?r.ordinalNumber(e.getHours(),{unit:"hour"}):jo.H(e,t)},K:function(e,t,r){let a=e.getHours()%12;return t==="Ko"?r.ordinalNumber(a,{unit:"hour"}):lt(a,t.length)},k:function(e,t,r){let a=e.getHours();return a===0&&(a=24),t==="ko"?r.ordinalNumber(a,{unit:"hour"}):lt(a,t.length)},m:function(e,t,r){return t==="mo"?r.ordinalNumber(e.getMinutes(),{unit:"minute"}):jo.m(e,t)},s:function(e,t,r){return t==="so"?r.ordinalNumber(e.getSeconds(),{unit:"second"}):jo.s(e,t)},S:function(e,t){return jo.S(e,t)},X:function(e,t,r){let a=e.getTimezoneOffset();if(a===0)return"Z";switch(t){case"X":return cM(a);case"XXXX":case"XX":return Vd(a);case"XXXXX":case"XXX":default:return Vd(a,":")}},x:function(e,t,r){let a=e.getTimezoneOffset();switch(t){case"x":return cM(a);case"xxxx":case"xx":return Vd(a);case"xxxxx":case"xxx":default:return Vd(a,":")}},O:function(e,t,r){let a=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+dM(a,":");case"OOOO":default:return"GMT"+Vd(a,":")}},z:function(e,t,r){let a=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+dM(a,":");case"zzzz":default:return"GMT"+Vd(a,":")}},t:function(e,t,r){let a=Math.trunc(+e/1e3);return lt(a,t.length)},T:function(e,t,r){return lt(+e,t.length)}};function dM(e,t=""){let r=e>0?"-":"+",a=Math.abs(e),n=Math.trunc(a/60),i=a%60;return i===0?r+String(n):r+String(n)+t+lt(i,2)}function cM(e,t){return e%60===0?(e>0?"-":"+")+lt(Math.abs(e)/60,2):Vd(e,t)}function Vd(e,t=""){let r=e>0?"-":"+",a=Math.abs(e),n=lt(Math.trunc(a/60),2),i=lt(a%60,2);return r+n+t+i}var uM=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},lM=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},Nle=(e,t)=>{let r=e.match(/(P+)(p+)?/)||[],a=r[1],n=r[2];if(!n)return uM(e,t);let i;switch(a){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;case"PPPP":default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",uM(a,t)).replace("{{time}}",lM(n,t))},am={p:lM,P:Nle};var xle=/^D+$/,Dle=/^Y+$/,kle=["D","DD","YY","YYYY"];function b0(e){return xle.test(e)}function w0(e){return Dle.test(e)}function im(e,t,r){let a=Rle(e,t,r);if(console.warn(a),kle.includes(e))throw new RangeError(a)}function Rle(e,t,r){let a=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${a} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var Ile=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Ele=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Ple=/^'([^]*?)'?$/,Cle=/''/g,Ale=/[a-zA-Z]/;function pM(e,t,r){let a=ai(),n=r?.locale??a.locale??nm,i=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,o=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,s=Be(e,r?.in);if(!XA(s))throw new RangeError("Invalid time value");let d=t.match(Ele).map(l=>{let p=l[0];if(p==="p"||p==="P"){let _=am[p];return _(l,n.formatLong)}return l}).join("").match(Ile).map(l=>{if(l==="''")return{isToken:!1,value:"'"};let p=l[0];if(p==="'")return{isToken:!1,value:Mle(l)};if(Ov[p])return{isToken:!0,value:l};if(p.match(Ale))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");return{isToken:!1,value:l}});n.localize.preprocessor&&(d=n.localize.preprocessor(s,d));let u={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return d.map(l=>{if(!l.isToken)return l.value;let p=l.value;(!r?.useAdditionalWeekYearTokens&&w0(p)||!r?.useAdditionalDayOfYearTokens&&b0(p))&&im(p,t,String(e));let _=Ov[p[0]];return _(s,p,n.localize,u)}).join("")}function Mle(e){let t=e.match(Ple);return t?t[1].replace(Cle,"'"):e}function mM(){return Object.assign({},ai())}function fM(e,t){let r=Be(e,t?.in).getDay();return r===0?7:r}function hM(e,t){let r=Fle(t)?new t(0):dt(t,0);return r.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),r.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),r}function Fle(e){return typeof e=="function"&&e.prototype?.constructor===e}var zle=10,S0=class{subPriority=0;validate(t,r){return!0}},T0=class extends S0{constructor(t,r,a,n,i){super(),this.value=t,this.validateValue=r,this.setValue=a,this.priority=n,i&&(this.subPriority=i)}validate(t,r){return this.validateValue(t,this.value,r)}set(t,r,a){return this.setValue(t,r,this.value,a)}},$0=class extends S0{priority=zle;subPriority=-1;constructor(t,r){super(),this.context=t||(a=>dt(r,a))}set(t,r){return r.timestampIsSet?t:dt(t,hM(t,this.context))}};var ue=class{run(t,r,a,n){let i=this.parse(t,r,a,n);return i?{setter:new T0(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,r,a){return!0}};var O0=class extends ue{priority=140;parse(t,r,a){switch(r){case"G":case"GG":case"GGG":return a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"});case"GGGGG":return a.era(t,{width:"narrow"});case"GGGG":default:return a.era(t,{width:"wide"})||a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"})}}set(t,r,a){return r.era=a,t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}incompatibleTokens=["R","u","t","T"]};var et={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},ii={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function ht(e,t){return e&&{value:t(e.value),rest:e.rest}}function Ke(e,t){let r=t.match(e);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function oi(e,t){let r=t.match(e);if(!r)return null;if(r[0]==="Z")return{value:0,rest:t.slice(1)};let a=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,i=r[3]?parseInt(r[3],10):0,o=r[5]?parseInt(r[5],10):0;return{value:a*(n*LA+i*VA+o*WA),rest:t.slice(r[0].length)}}function N0(e){return Ke(et.anyDigitsSigned,e)}function Re(e,t){switch(e){case 1:return Ke(et.singleDigit,t);case 2:return Ke(et.twoDigits,t);case 3:return Ke(et.threeDigits,t);case 4:return Ke(et.fourDigits,t);default:return Ke(new RegExp("^\\d{1,"+e+"}"),t)}}function Tu(e,t){switch(e){case 1:return Ke(et.singleDigitSigned,t);case 2:return Ke(et.twoDigitsSigned,t);case 3:return Ke(et.threeDigitsSigned,t);case 4:return Ke(et.fourDigitsSigned,t);default:return Ke(new RegExp("^-?\\d{1,"+e+"}"),t)}}function $u(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function x0(e,t){let r=t>0,a=r?t:1-t,n;if(a<=50)n=e||100;else{let i=a+50,o=Math.trunc(i/100)*100,s=e>=i%100;n=e+o-(s?100:0)}return r?n:1-n}function D0(e){return e%400===0||e%4===0&&e%100!==0}var k0=class extends ue{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(t,r,a){let n=i=>({year:i,isTwoDigitYear:r==="yy"});switch(r){case"y":return ht(Re(4,t),n);case"yo":return ht(a.ordinalNumber(t,{unit:"year"}),n);default:return ht(Re(r.length,t),n)}}validate(t,r){return r.isTwoDigitYear||r.year>0}set(t,r,a){let n=t.getFullYear();if(a.isTwoDigitYear){let o=x0(a.year,n);return t.setFullYear(o,0,1),t.setHours(0,0,0,0),t}let i=!("era"in r)||r.era===1?a.year:1-a.year;return t.setFullYear(i,0,1),t.setHours(0,0,0,0),t}};var R0=class extends ue{priority=130;parse(t,r,a){let n=i=>({year:i,isTwoDigitYear:r==="YY"});switch(r){case"Y":return ht(Re(4,t),n);case"Yo":return ht(a.ordinalNumber(t,{unit:"year"}),n);default:return ht(Re(r.length,t),n)}}validate(t,r){return r.isTwoDigitYear||r.year>0}set(t,r,a,n){let i=wu(t,n);if(a.isTwoDigitYear){let s=x0(a.year,i);return t.setFullYear(s,0,n.firstWeekContainsDate),t.setHours(0,0,0,0),Qr(t,n)}let o=!("era"in r)||r.era===1?a.year:1-a.year;return t.setFullYear(o,0,n.firstWeekContainsDate),t.setHours(0,0,0,0),Qr(t,n)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};var I0=class extends ue{priority=130;parse(t,r){return r==="R"?Tu(4,t):Tu(r.length,t)}set(t,r,a){let n=dt(t,0);return n.setFullYear(a,0,4),n.setHours(0,0,0,0),Ri(n)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};var E0=class extends ue{priority=130;parse(t,r){return r==="u"?Tu(4,t):Tu(r.length,t)}set(t,r,a){return t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};var P0=class extends ue{priority=120;parse(t,r,a){switch(r){case"Q":case"QQ":return Re(r.length,t);case"Qo":return a.ordinalNumber(t,{unit:"quarter"});case"QQQ":return a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(t,{width:"wide",context:"formatting"})||a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=1&&r<=4}set(t,r,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};var C0=class extends ue{priority=120;parse(t,r,a){switch(r){case"q":case"qq":return Re(r.length,t);case"qo":return a.ordinalNumber(t,{unit:"quarter"});case"qqq":return a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(t,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(t,{width:"wide",context:"standalone"})||a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"})}}validate(t,r){return r>=1&&r<=4}set(t,r,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};var A0=class extends ue{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(t,r,a){let n=i=>i-1;switch(r){case"M":return ht(Ke(et.month,t),n);case"MM":return ht(Re(2,t),n);case"Mo":return ht(a.ordinalNumber(t,{unit:"month"}),n);case"MMM":return a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(t,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(t,{width:"wide",context:"formatting"})||a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=0&&r<=11}set(t,r,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}};var M0=class extends ue{priority=110;parse(t,r,a){let n=i=>i-1;switch(r){case"L":return ht(Ke(et.month,t),n);case"LL":return ht(Re(2,t),n);case"Lo":return ht(a.ordinalNumber(t,{unit:"month"}),n);case"LLL":return a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(t,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(t,{width:"wide",context:"standalone"})||a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"})}}validate(t,r){return r>=0&&r<=11}set(t,r,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};function gM(e,t,r){let a=Be(e,r?.in),n=v0(a,r)-t;return a.setDate(a.getDate()-n*7),Be(a,r?.in)}var F0=class extends ue{priority=100;parse(t,r,a){switch(r){case"w":return Ke(et.week,t);case"wo":return a.ordinalNumber(t,{unit:"week"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=53}set(t,r,a,n){return Qr(gM(t,a,n),n)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};function _M(e,t,r){let a=Be(e,r?.in),n=y0(a,r)-t;return a.setDate(a.getDate()-n*7),a}var z0=class extends ue{priority=100;parse(t,r,a){switch(r){case"I":return Ke(et.week,t);case"Io":return a.ordinalNumber(t,{unit:"week"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=53}set(t,r,a){return Ri(_M(t,a))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};var Jle=[31,28,31,30,31,30,31,31,30,31,30,31],jle=[31,29,31,30,31,30,31,31,30,31,30,31],J0=class extends ue{priority=90;subPriority=1;parse(t,r,a){switch(r){case"d":return Ke(et.date,t);case"do":return a.ordinalNumber(t,{unit:"date"});default:return Re(r.length,t)}}validate(t,r){let a=t.getFullYear(),n=D0(a),i=t.getMonth();return n?r>=1&&r<=jle[i]:r>=1&&r<=Jle[i]}set(t,r,a){return t.setDate(a),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};var j0=class extends ue{priority=90;subpriority=1;parse(t,r,a){switch(r){case"D":case"DD":return Ke(et.dayOfYear,t);case"Do":return a.ordinalNumber(t,{unit:"date"});default:return Re(r.length,t)}}validate(t,r){let a=t.getFullYear();return D0(a)?r>=1&&r<=366:r>=1&&r<=365}set(t,r,a){return t.setMonth(0,a),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};function Ou(e,t,r){let a=ai(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,i=Be(e,r?.in),o=i.getDay(),d=(t%7+7)%7,u=7-n,l=t<0||t>6?t-(o+u)%7:(d+u)%7-(o+u)%7;return h0(i,l,r)}var q0=class extends ue{priority=90;parse(t,r,a){switch(r){case"E":case"EE":case"EEE":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=0&&r<=6}set(t,r,a,n){return t=Ou(t,a,n),t.setHours(0,0,0,0),t}incompatibleTokens=["D","i","e","c","t","T"]};var U0=class extends ue{priority=90;parse(t,r,a,n){let i=o=>{let s=Math.floor((o-1)/7)*7;return(o+n.weekStartsOn+6)%7+s};switch(r){case"e":case"ee":return ht(Re(r.length,t),i);case"eo":return ht(a.ordinalNumber(t,{unit:"day"}),i);case"eee":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeeee":return a.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=0&&r<=6}set(t,r,a,n){return t=Ou(t,a,n),t.setHours(0,0,0,0),t}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};var B0=class extends ue{priority=90;parse(t,r,a,n){let i=o=>{let s=Math.floor((o-1)/7)*7;return(o+n.weekStartsOn+6)%7+s};switch(r){case"c":case"cc":return ht(Re(r.length,t),i);case"co":return ht(a.ordinalNumber(t,{unit:"day"}),i);case"ccc":return a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"ccccc":return a.day(t,{width:"narrow",context:"standalone"});case"cccccc":return a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(t,{width:"wide",context:"standalone"})||a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"})}}validate(t,r){return r>=0&&r<=6}set(t,r,a,n){return t=Ou(t,a,n),t.setHours(0,0,0,0),t}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};function yM(e,t,r){let a=Be(e,r?.in),n=fM(a,r),i=t-n;return h0(a,i,r)}var V0=class extends ue{priority=90;parse(t,r,a){let n=i=>i===0?7:i;switch(r){case"i":case"ii":return Re(r.length,t);case"io":return a.ordinalNumber(t,{unit:"day"});case"iii":return ht(a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),n);case"iiiii":return ht(a.day(t,{width:"narrow",context:"formatting"}),n);case"iiiiii":return ht(a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),n);case"iiii":default:return ht(a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),n)}}validate(t,r){return r>=1&&r<=7}set(t,r,a){return t=yM(t,a),t.setHours(0,0,0,0),t}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};var L0=class extends ue{priority=80;parse(t,r,a){switch(r){case"a":case"aa":case"aaa":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,r,a){return t.setHours($u(a),0,0,0),t}incompatibleTokens=["b","B","H","k","t","T"]};var W0=class extends ue{priority=80;parse(t,r,a){switch(r){case"b":case"bb":case"bbb":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,r,a){return t.setHours($u(a),0,0,0),t}incompatibleTokens=["a","B","H","k","t","T"]};var Y0=class extends ue{priority=80;parse(t,r,a){switch(r){case"B":case"BB":case"BBB":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,r,a){return t.setHours($u(a),0,0,0),t}incompatibleTokens=["a","b","t","T"]};var Z0=class extends ue{priority=70;parse(t,r,a){switch(r){case"h":return Ke(et.hour12h,t);case"ho":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=12}set(t,r,a){let n=t.getHours()>=12;return n&&a<12?t.setHours(a+12,0,0,0):!n&&a===12?t.setHours(0,0,0,0):t.setHours(a,0,0,0),t}incompatibleTokens=["H","K","k","t","T"]};var H0=class extends ue{priority=70;parse(t,r,a){switch(r){case"H":return Ke(et.hour23h,t);case"Ho":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=23}set(t,r,a){return t.setHours(a,0,0,0),t}incompatibleTokens=["a","b","h","K","k","t","T"]};var G0=class extends ue{priority=70;parse(t,r,a){switch(r){case"K":return Ke(et.hour11h,t);case"Ko":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=11}set(t,r,a){return t.getHours()>=12&&a<12?t.setHours(a+12,0,0,0):t.setHours(a,0,0,0),t}incompatibleTokens=["h","H","k","t","T"]};var K0=class extends ue{priority=70;parse(t,r,a){switch(r){case"k":return Ke(et.hour24h,t);case"ko":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=24}set(t,r,a){let n=a<=24?a%24:a;return t.setHours(n,0,0,0),t}incompatibleTokens=["a","b","h","H","K","t","T"]};var X0=class extends ue{priority=60;parse(t,r,a){switch(r){case"m":return Ke(et.minute,t);case"mo":return a.ordinalNumber(t,{unit:"minute"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=59}set(t,r,a){return t.setMinutes(a,0,0),t}incompatibleTokens=["t","T"]};var Q0=class extends ue{priority=50;parse(t,r,a){switch(r){case"s":return Ke(et.second,t);case"so":return a.ordinalNumber(t,{unit:"second"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=59}set(t,r,a){return t.setSeconds(a,0),t}incompatibleTokens=["t","T"]};var e2=class extends ue{priority=30;parse(t,r){let a=n=>Math.trunc(n*Math.pow(10,-r.length+3));return ht(Re(r.length,t),a)}set(t,r,a){return t.setMilliseconds(a),t}incompatibleTokens=["t","T"]};var t2=class extends ue{priority=10;parse(t,r){switch(r){case"X":return oi(ii.basicOptionalMinutes,t);case"XX":return oi(ii.basic,t);case"XXXX":return oi(ii.basicOptionalSeconds,t);case"XXXXX":return oi(ii.extendedOptionalSeconds,t);case"XXX":default:return oi(ii.extended,t)}}set(t,r,a){return r.timestampIsSet?t:dt(t,t.getTime()-Bd(t)-a)}incompatibleTokens=["t","T","x"]};var r2=class extends ue{priority=10;parse(t,r){switch(r){case"x":return oi(ii.basicOptionalMinutes,t);case"xx":return oi(ii.basic,t);case"xxxx":return oi(ii.basicOptionalSeconds,t);case"xxxxx":return oi(ii.extendedOptionalSeconds,t);case"xxx":default:return oi(ii.extended,t)}}set(t,r,a){return r.timestampIsSet?t:dt(t,t.getTime()-Bd(t)-a)}incompatibleTokens=["t","T","X"]};var n2=class extends ue{priority=40;parse(t){return N0(t)}set(t,r,a){return[dt(t,a*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};var a2=class extends ue{priority=20;parse(t){return N0(t)}set(t,r,a){return[dt(t,a),{timestampIsSet:!0}]}incompatibleTokens="*"};var vM={G:new O0,y:new k0,Y:new R0,R:new I0,u:new E0,Q:new P0,q:new C0,M:new A0,L:new M0,w:new F0,I:new z0,d:new J0,D:new j0,E:new q0,e:new U0,c:new B0,i:new V0,a:new L0,b:new W0,B:new Y0,h:new Z0,H:new H0,K:new G0,k:new K0,m:new X0,s:new Q0,S:new e2,X:new t2,x:new r2,t:new n2,T:new a2};var qle=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Ule=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Ble=/^'([^]*?)'?$/,Vle=/''/g,Lle=/\S/,Wle=/[a-zA-Z]/;function bM(e,t,r,a){let n=()=>dt(a?.in||r,NaN),i=mM(),o=a?.locale??i.locale??nm,s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,d=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??i.weekStartsOn??i.locale?.options?.weekStartsOn??0;if(!t)return e?n():Be(r,a?.in);let u={firstWeekContainsDate:s,weekStartsOn:d,locale:o},l=[new $0(a?.in,r)],p=t.match(Ule).map(h=>{let y=h[0];if(y in am){let b=am[y];return b(h,o.formatLong)}return h}).join("").match(qle),_=[];for(let h of p){!a?.useAdditionalWeekYearTokens&&w0(h)&&im(h,t,e),!a?.useAdditionalDayOfYearTokens&&b0(h)&&im(h,t,e);let y=h[0],b=vM[y];if(b){let{incompatibleTokens:w}=b;if(Array.isArray(w)){let N=_.find(M=>w.includes(M.token)||M.token===y);if(N)throw new RangeError(`The format string mustn't contain \`${N.fullToken}\` and \`${h}\` at the same time`)}else if(b.incompatibleTokens==="*"&&_.length>0)throw new RangeError(`The format string mustn't contain \`${h}\` and any other token at the same time`);_.push({token:y,fullToken:h});let R=b.run(e,h,o.match,u);if(!R)return n();l.push(R.setter),e=R.rest}else{if(y.match(Wle))throw new RangeError("Format string contains an unescaped latin alphabet character `"+y+"`");if(h==="''"?h="'":y==="'"&&(h=Yle(h)),e.indexOf(h)===0)e=e.slice(h.length);else return n()}}if(e.length>0&&Lle.test(e))return n();let g=l.map(h=>h.priority).sort((h,y)=>y-h).filter((h,y,b)=>b.indexOf(h)===y).map(h=>l.filter(y=>y.priority===h).sort((y,b)=>b.subPriority-y.subPriority)).map(h=>h[0]),f=Be(r,a?.in);if(isNaN(+f))return n();let m={};for(let h of g){if(!h.validate(f,u))return n();let y=h.set(f,m,u);Array.isArray(y)?(f=y[0],Object.assign(m,y[1])):f=y}return f}function Yle(e){return e.match(Ble)[1].replace(Vle,"'")}var qo=require("path"),Nv=require("os"),SM=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().optional(),category_id:c.string().optional(),since_date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),type:c.enum(["uncategorized","unapproved"]).optional(),filename:c.string().optional(),minimal:c.boolean().optional().default(!0)}).strict();function Zle(e,t){if(e.filename)return e.filename.endsWith(".json")?e.filename:`${e.filename}.json`;let r=pM(new Date,"yyyy-MM-dd_HH-mm-ss"),a="transactions",n=[];return e.since_date&&n.push(`since_${e.since_date}`),e.account_id&&n.push(`account_${e.account_id.substring(0,8)}`),e.category_id&&n.push(`category_${e.category_id.substring(0,8)}`),e.type&&n.push(e.type),e.minimal!==!1&&n.push("minimal"),n.length>0&&(a=n.join("_")),`ynab_${a}_${t}items_${r}.json`}function wM(){let e=process.platform,t=(0,Nv.homedir)();switch(e){case"win32":return(0,qo.join)(t,"Downloads");case"darwin":return(0,qo.join)(t,"Downloads");case"linux":case"freebsd":case"openbsd":case"sunos":case"aix":return process.env.XDG_DOCUMENTS_DIR||(0,qo.join)(t,"Documents");default:return(0,qo.join)(t,"Downloads")}}function Hle(){let e=process.env.YNAB_EXPORT_PATH?.trim(),t;e?e.startsWith("~/")?t=(0,qo.join)((0,Nv.homedir)(),e.slice(2)):t=(0,qo.resolve)(e):t=wM();try{(0,om.mkdirSync)(t,{recursive:!0})}catch(r){console.warn(`Failed to create export directory ${t}, using platform default:`,r);let a=wM();try{return(0,om.mkdirSync)(a,{recursive:!0}),a}catch(n){return console.warn("Failed to create default folder, using current directory:",n),process.cwd()}}return t}async function TM(e,t){return await mt(async()=>{let r;t.account_id?r=await e.transactions.getTransactionsByAccount(t.budget_id,t.account_id,t.since_date):t.category_id?r=await e.transactions.getTransactionsByCategory(t.budget_id,t.category_id,t.since_date):r=await e.transactions.getTransactions(t.budget_id,t.since_date,t.type);let a=r.data.transactions,n=Hle(),i=Zle(t,a.length),o=(0,qo.join)(n,i),s={export_info:{exported_at:new Date().toISOString(),total_transactions:a.length,minimal:t.minimal!==!1,filters:{budget_id:t.budget_id,account_id:t.account_id||null,category_id:t.category_id||null,since_date:t.since_date||null,type:t.type||null}},transactions:a.map(l=>t.minimal!==!1?{id:l.id,date:l.date,amount:l.amount,payee_name:l.payee_name,cleared:l.cleared}:{id:l.id,date:l.date,amount:l.amount,memo:l.memo,cleared:l.cleared,approved:l.approved,flag_color:l.flag_color,account_id:l.account_id,payee_id:l.payee_id,category_id:l.category_id,transfer_account_id:l.transfer_account_id,transfer_transaction_id:l.transfer_transaction_id,matched_transaction_id:l.matched_transaction_id,import_id:l.import_id,deleted:l.deleted,account_name:l.account_name,payee_name:l.payee_name,category_name:l.category_name})};(0,om.writeFileSync)(o,JSON.stringify(s,null,2),"utf-8");let d=Math.min(10,a.length),u=a.slice(0,d);return{content:[{type:"text",text:he.format({message:`Successfully exported ${a.length} transactions${t.minimal!==!1?" (minimal fields)":" (full fields)"}`,filename:i,full_path:o,export_directory:n,export_mode:t.minimal!==!1?"minimal":"full",minimal_fields:t.minimal!==!1?"id, date, amount, payee_name, cleared":null,filename_explanation:"Filename format: ynab_{filters}_{count}items_{timestamp}.json - identifies what data was exported, when, and how many transactions",preview_count:d,total_count:a.length,preview_transactions:u.map(l=>({id:l.id,date:l.date,amount:l.amount,memo:l.memo,payee_name:l.payee_name,category_name:l.category_name}))})}]}},"ynab:export_transactions","exporting transactions")}var tt=class e extends Error{constructor(t,r,a,...n){Array.isArray(r)&&(r=r.join(" ").trim()),super(r),Error.captureStackTrace!==void 0&&Error.captureStackTrace(this,e),this.code=t;for(let i of n)for(let o in i){let s=i[o];this[o]=Buffer.isBuffer(s)?s.toString(a.encoding):s==null?s:JSON.parse(JSON.stringify(s))}}};var $M=function(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)};var i2=function(e){let t=[];for(let r=0,a=e.length;r<a;r++){let n=e[r];if(n==null||n===!1)t[r]={disabled:!0};else if(typeof n=="string")t[r]={name:n};else if($M(n)){if(typeof n.name!="string")throw new tt("CSV_OPTION_COLUMNS_MISSING_NAME",["Option columns missing name:",`property "name" is required at position ${r}`,"when column is an object literal"]);t[r]=n}else throw new tt("CSV_INVALID_COLUMN_DEFINITION",["Invalid column definition:","expect a string or a literal object,",`got ${JSON.stringify(n)} at position ${r}`])}return t};var xv=class{constructor(t=100){this.size=t,this.length=0,this.buf=Buffer.allocUnsafe(t)}prepend(t){if(Buffer.isBuffer(t)){let r=this.length+t.length;if(r>=this.size&&(this.resize(),r>=this.size))throw Error("INVALID_BUFFER_STATE");let a=this.buf;this.buf=Buffer.allocUnsafe(this.size),t.copy(this.buf,0),a.copy(this.buf,t.length),this.length+=t.length}else{let r=this.length++;r===this.size&&this.resize();let a=this.clone();this.buf[0]=t,a.copy(this.buf,1,0,r)}}append(t){let r=this.length++;r===this.size&&this.resize(),this.buf[r]=t}clone(){return Buffer.from(this.buf.slice(0,this.length))}resize(){let t=this.length;this.size=this.size*2;let r=Buffer.allocUnsafe(this.size);this.buf.copy(r,0,0,t),this.buf=r}toString(t){return t?this.buf.slice(0,this.length).toString(t):Uint8Array.prototype.slice.call(this.buf.slice(0,this.length))}toJSON(){return this.toString("utf8")}reset(){this.length=0}},Dv=xv;var Gle=12,Kle=13,Xle=10,Qle=32,epe=9,OM=function(e){return{bomSkipped:!1,bufBytesStart:0,castField:e.cast_function,commenting:!1,error:void 0,enabled:e.from_line===1,escaping:!1,escapeIsQuote:Buffer.isBuffer(e.escape)&&Buffer.isBuffer(e.quote)&&Buffer.compare(e.escape,e.quote)===0,expectedRecordLength:Array.isArray(e.columns)?e.columns.length:void 0,field:new Dv(20),firstLineToHeaders:e.cast_first_line_to_header,needMoreDataSize:Math.max(e.comment!==null?e.comment.length:0,...e.delimiter.map(t=>t.length),e.quote!==null?e.quote.length:0),previousBuf:void 0,quoting:!1,stop:!1,rawBuffer:new Dv(100),record:[],recordHasError:!1,record_length:0,recordDelimiterMaxLength:e.record_delimiter.length===0?0:Math.max(...e.record_delimiter.map(t=>t.length)),trimChars:[Buffer.from(" ",e.encoding)[0],Buffer.from(" ",e.encoding)[0]],wasQuoting:!1,wasRowDelimiter:!1,timchars:[Buffer.from(Buffer.from([Kle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([Xle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([Gle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([Qle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([epe],"utf8").toString(),e.encoding)]}};var NM=function(e){return e.replace(/([A-Z])/g,function(t,r){return"_"+r.toLowerCase()})};var kv=function(e){let t={};for(let a in e)t[NM(a)]=e[a];if(t.encoding===void 0||t.encoding===!0)t.encoding="utf8";else if(t.encoding===null||t.encoding===!1)t.encoding=null;else if(typeof t.encoding!="string"&&t.encoding!==null)throw new tt("CSV_INVALID_OPTION_ENCODING",["Invalid option encoding:","encoding must be a string or null to return a buffer,",`got ${JSON.stringify(t.encoding)}`],t);if(t.bom===void 0||t.bom===null||t.bom===!1)t.bom=!1;else if(t.bom!==!0)throw new tt("CSV_INVALID_OPTION_BOM",["Invalid option bom:","bom must be true,",`got ${JSON.stringify(t.bom)}`],t);if(t.cast_function=null,t.cast===void 0||t.cast===null||t.cast===!1||t.cast==="")t.cast=void 0;else if(typeof t.cast=="function")t.cast_function=t.cast,t.cast=!0;else if(t.cast!==!0)throw new tt("CSV_INVALID_OPTION_CAST",["Invalid option cast:","cast must be true or a function,",`got ${JSON.stringify(t.cast)}`],t);if(t.cast_date===void 0||t.cast_date===null||t.cast_date===!1||t.cast_date==="")t.cast_date=!1;else if(t.cast_date===!0)t.cast_date=function(a){let n=Date.parse(a);return isNaN(n)?a:new Date(n)};else if(typeof t.cast_date!="function")throw new tt("CSV_INVALID_OPTION_CAST_DATE",["Invalid option cast_date:","cast_date must be true or a function,",`got ${JSON.stringify(t.cast_date)}`],t);if(t.cast_first_line_to_header=void 0,t.columns===!0)t.cast_first_line_to_header=void 0;else if(typeof t.columns=="function")t.cast_first_line_to_header=t.columns,t.columns=!0;else if(Array.isArray(t.columns))t.columns=i2(t.columns);else if(t.columns===void 0||t.columns===null||t.columns===!1)t.columns=!1;else throw new tt("CSV_INVALID_OPTION_COLUMNS",["Invalid option columns:","expect an array, a function or true,",`got ${JSON.stringify(t.columns)}`],t);if(t.group_columns_by_name===void 0||t.group_columns_by_name===null||t.group_columns_by_name===!1)t.group_columns_by_name=!1;else{if(t.group_columns_by_name!==!0)throw new tt("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","expect an boolean,",`got ${JSON.stringify(t.group_columns_by_name)}`],t);if(t.columns===!1)throw new tt("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","the `columns` mode must be activated."],t)}if(t.comment===void 0||t.comment===null||t.comment===!1||t.comment==="")t.comment=null;else if(typeof t.comment=="string"&&(t.comment=Buffer.from(t.comment,t.encoding)),!Buffer.isBuffer(t.comment))throw new tt("CSV_INVALID_OPTION_COMMENT",["Invalid option comment:","comment must be a buffer or a string,",`got ${JSON.stringify(t.comment)}`],t);if(t.comment_no_infix===void 0||t.comment_no_infix===null||t.comment_no_infix===!1)t.comment_no_infix=!1;else if(t.comment_no_infix!==!0)throw new tt("CSV_INVALID_OPTION_COMMENT",["Invalid option comment_no_infix:","value must be a boolean,",`got ${JSON.stringify(t.comment_no_infix)}`],t);let r=JSON.stringify(t.delimiter);if(Array.isArray(t.delimiter)||(t.delimiter=[t.delimiter]),t.delimiter.length===0)throw new tt("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);if(t.delimiter=t.delimiter.map(function(a){if(a==null||a===!1)return Buffer.from(",",t.encoding);if(typeof a=="string"&&(a=Buffer.from(a,t.encoding)),!Buffer.isBuffer(a)||a.length===0)throw new tt("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);return a}),t.escape===void 0||t.escape===!0?t.escape=Buffer.from('"',t.encoding):typeof t.escape=="string"?t.escape=Buffer.from(t.escape,t.encoding):(t.escape===null||t.escape===!1)&&(t.escape=null),t.escape!==null&&!Buffer.isBuffer(t.escape))throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(t.escape)}`);if(t.from===void 0||t.from===null)t.from=1;else if(typeof t.from=="string"&&/\d+/.test(t.from)&&(t.from=parseInt(t.from)),Number.isInteger(t.from)){if(t.from<0)throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(e.from)}`)}else throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(t.from)}`);if(t.from_line===void 0||t.from_line===null)t.from_line=1;else if(typeof t.from_line=="string"&&/\d+/.test(t.from_line)&&(t.from_line=parseInt(t.from_line)),Number.isInteger(t.from_line)){if(t.from_line<=0)throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(e.from_line)}`)}else throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(e.from_line)}`);if(t.ignore_last_delimiters===void 0||t.ignore_last_delimiters===null)t.ignore_last_delimiters=!1;else if(typeof t.ignore_last_delimiters=="number")t.ignore_last_delimiters=Math.floor(t.ignore_last_delimiters),t.ignore_last_delimiters===0&&(t.ignore_last_delimiters=!1);else if(typeof t.ignore_last_delimiters!="boolean")throw new tt("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS",["Invalid option `ignore_last_delimiters`:","the value must be a boolean value or an integer,",`got ${JSON.stringify(t.ignore_last_delimiters)}`],t);if(t.ignore_last_delimiters===!0&&t.columns===!1)throw new tt("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS",["The option `ignore_last_delimiters`","requires the activation of the `columns` option"],t);if(t.info===void 0||t.info===null||t.info===!1)t.info=!1;else if(t.info!==!0)throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(t.info)}`);if(t.max_record_size===void 0||t.max_record_size===null||t.max_record_size===!1)t.max_record_size=0;else if(!(Number.isInteger(t.max_record_size)&&t.max_record_size>=0))if(typeof t.max_record_size=="string"&&/\d+/.test(t.max_record_size))t.max_record_size=parseInt(t.max_record_size);else throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(t.max_record_size)}`);if(t.objname===void 0||t.objname===null||t.objname===!1)t.objname=void 0;else if(Buffer.isBuffer(t.objname)){if(t.objname.length===0)throw new Error("Invalid Option: objname must be a non empty buffer");t.encoding===null||(t.objname=t.objname.toString(t.encoding))}else if(typeof t.objname=="string"){if(t.objname.length===0)throw new Error("Invalid Option: objname must be a non empty string")}else if(typeof t.objname!="number")throw new Error(`Invalid Option: objname must be a string or a buffer, got ${t.objname}`);if(t.objname!==void 0){if(typeof t.objname=="number"){if(t.columns!==!1)throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field")}else if(t.columns===!1)throw Error("Invalid Option: objname field must be combined with columns or be defined as an index")}if(t.on_record===void 0||t.on_record===null)t.on_record=void 0;else if(typeof t.on_record!="function")throw new tt("CSV_INVALID_OPTION_ON_RECORD",["Invalid option `on_record`:","expect a function,",`got ${JSON.stringify(t.on_record)}`],t);if(t.on_skip!==void 0&&t.on_skip!==null&&typeof t.on_skip!="function")throw new Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify(t.on_skip)}`);if(t.quote===null||t.quote===!1||t.quote==="")t.quote=null;else if(t.quote===void 0||t.quote===!0?t.quote=Buffer.from('"',t.encoding):typeof t.quote=="string"&&(t.quote=Buffer.from(t.quote,t.encoding)),!Buffer.isBuffer(t.quote))throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(t.quote)}`);if(t.raw===void 0||t.raw===null||t.raw===!1)t.raw=!1;else if(t.raw!==!0)throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(t.raw)}`);if(t.record_delimiter===void 0)t.record_delimiter=[];else if(typeof t.record_delimiter=="string"||Buffer.isBuffer(t.record_delimiter)){if(t.record_delimiter.length===0)throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);t.record_delimiter=[t.record_delimiter]}else if(!Array.isArray(t.record_delimiter))throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);if(t.record_delimiter=t.record_delimiter.map(function(a,n){if(typeof a!="string"&&!Buffer.isBuffer(a))throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer",`at index ${n},`,`got ${JSON.stringify(a)}`],t);if(a.length===0)throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer",`at index ${n},`,`got ${JSON.stringify(a)}`],t);return typeof a=="string"&&(a=Buffer.from(a,t.encoding)),a}),typeof t.relax_column_count!="boolean")if(t.relax_column_count===void 0||t.relax_column_count===null)t.relax_column_count=!1;else throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(t.relax_column_count)}`);if(typeof t.relax_column_count_less!="boolean")if(t.relax_column_count_less===void 0||t.relax_column_count_less===null)t.relax_column_count_less=!1;else throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(t.relax_column_count_less)}`);if(typeof t.relax_column_count_more!="boolean")if(t.relax_column_count_more===void 0||t.relax_column_count_more===null)t.relax_column_count_more=!1;else throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(t.relax_column_count_more)}`);if(typeof t.relax_quotes!="boolean")if(t.relax_quotes===void 0||t.relax_quotes===null)t.relax_quotes=!1;else throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(t.relax_quotes)}`);if(typeof t.skip_empty_lines!="boolean")if(t.skip_empty_lines===void 0||t.skip_empty_lines===null)t.skip_empty_lines=!1;else throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(t.skip_empty_lines)}`);if(typeof t.skip_records_with_empty_values!="boolean")if(t.skip_records_with_empty_values===void 0||t.skip_records_with_empty_values===null)t.skip_records_with_empty_values=!1;else throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(t.skip_records_with_empty_values)}`);if(typeof t.skip_records_with_error!="boolean")if(t.skip_records_with_error===void 0||t.skip_records_with_error===null)t.skip_records_with_error=!1;else throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(t.skip_records_with_error)}`);if(t.rtrim===void 0||t.rtrim===null||t.rtrim===!1)t.rtrim=!1;else if(t.rtrim!==!0)throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(t.rtrim)}`);if(t.ltrim===void 0||t.ltrim===null||t.ltrim===!1)t.ltrim=!1;else if(t.ltrim!==!0)throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(t.ltrim)}`);if(t.trim===void 0||t.trim===null||t.trim===!1)t.trim=!1;else if(t.trim!==!0)throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(t.trim)}`);if(t.trim===!0&&e.ltrim!==!1?t.ltrim=!0:t.ltrim!==!0&&(t.ltrim=!1),t.trim===!0&&e.rtrim!==!1?t.rtrim=!0:t.rtrim!==!0&&(t.rtrim=!1),t.to===void 0||t.to===null)t.to=-1;else if(t.to!==-1)if(typeof t.to=="string"&&/\d+/.test(t.to)&&(t.to=parseInt(t.to)),Number.isInteger(t.to)){if(t.to<=0)throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(e.to)}`)}else throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(e.to)}`);if(t.to_line===void 0||t.to_line===null)t.to_line=-1;else if(t.to_line!==-1)if(typeof t.to_line=="string"&&/\d+/.test(t.to_line)&&(t.to_line=parseInt(t.to_line)),Number.isInteger(t.to_line)){if(t.to_line<=0)throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(e.to_line)}`)}else throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(e.to_line)}`);return t};var xM=function(e){return e.every(t=>t==null||t.toString&&t.toString().trim()==="")},tpe=13,rpe=10,Nu={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},DM=function(e={}){let t={bytes:0,comment_lines:0,empty_lines:0,invalid_field_length:0,lines:1,records:0},r=kv(e);return{info:t,original_options:e,options:r,state:OM(r),__needMoreData:function(a,n,i){if(i)return!1;let{encoding:o,escape:s,quote:d}=this.options,{quoting:u,needMoreDataSize:l,recordDelimiterMaxLength:p}=this.state,_=n-a-1,g=Math.max(l,p===0?Buffer.from(`\r
60
+ You can use the list_budgets tool to see available budget IDs.`;return nn.createValidationError("Invalid budget ID format",r,["Use a valid UUID format (UUID v1-v5, e.g., 123e4567-e89b-12d3-a456-426614174000; standard UUID v4 format works as well)","Run the list_budgets tool to view available budget IDs",'Use the special keyword "default" for convenience'])}static resolveBudgetIdOrThrow(t,r){let a=this.resolveBudgetId(t,r);if(typeof a=="string")return a;let n=a.content?.[0]?.type==="text"?a.content[0].text:"Budget resolution failed";throw new Error(n)}static validateBudgetIdOrThrow(t){let r=this.validateBudgetId(t);if(typeof r=="string")return r;let a=r.content?.[0]?.type==="text"?r.content[0].text:"Budget validation failed";throw new Error(a)}};qd.UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;qd.ALLOWED_KEYWORDS=["default"];var be=class{constructor(){this.cache=new Map,this.hits=0,this.misses=0,this.evictions=0,this.lastCleanup=null,this.pendingFetches=new Map,this.pendingRefresh=new Set,this.maxEntries=this.parseEnvInt("YNAB_MCP_CACHE_MAX_ENTRIES",1e3),this.defaultStaleWindow=this.parseEnvInt("YNAB_MCP_CACHE_STALE_MS",120*1e3),this.defaultTTL=this.parseEnvInt("YNAB_MCP_CACHE_DEFAULT_TTL_MS",3e5)}get(t){let r=this.cache.get(t);if(!r)return this.misses++,null;let n=Date.now()-r.timestamp;if(n>r.ttl){let i=r.staleWhileRevalidate||0;return i>0&&n<=r.ttl+i?(this.hits++,this.cache.delete(t),this.cache.set(t,r),this.pendingRefresh.add(t),r.data):(this.cache.delete(t),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),this.misses++,null)}return this.hits++,this.cache.delete(t),this.cache.set(t,r),r.data}has(t){let r=this.cache.get(t);if(!r)return!1;let n=Date.now()-r.timestamp;if(n>r.ttl){let i=r.staleWhileRevalidate||0;return i>0&&n<=r.ttl+i?!0:(this.cache.delete(t),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),!1)}return!0}set(t,r,a){if(this.maxEntries<=0)return;let n=this.cache.has(t);n||this.evictIfNeeded();let i,o;if(typeof a=="number")i=Number.isFinite(a)?a:this.defaultTTL,o=void 0;else if(a===void 0)i=this.defaultTTL,o=void 0;else{let d=a?.ttl;i=d!==void 0?d:this.defaultTTL,a&&"staleWhileRevalidate"in a?o=a.staleWhileRevalidate:o=a?.staleWhileRevalidate,o===void 0&&this.defaultStaleWindow>0&&(o=this.defaultStaleWindow)}let s={data:r,timestamp:Date.now(),ttl:i};o!==void 0&&(s.staleWhileRevalidate=o),n&&this.cache.delete(t),this.cache.set(t,s),this.pendingFetches.delete(t),this.pendingRefresh.delete(t)}delete(t){let r=this.cache.delete(t);return r&&(this.pendingFetches.delete(t),this.pendingRefresh.delete(t)),r}deleteMany(t){for(let r of t)this.cache.delete(r),this.pendingFetches.delete(r),this.pendingRefresh.delete(r)}deleteByPrefix(t){if(!t)return 0;let r=t.endsWith(":")?t.slice(0,-1):t,a=`${r}:`,n=0;for(let i of this.cache.keys())(i===r||i.startsWith(a))&&(this.cache.delete(i),this.pendingFetches.delete(i),this.pendingRefresh.delete(i),n++);return n}deleteByBudgetId(t){if(!t)return 0;let r=0;for(let a of this.cache.keys())a.split(":").some(i=>i===t)&&(this.cache.delete(a),this.pendingFetches.delete(a),this.pendingRefresh.delete(a),r++);return r}getKeys(){return Array.from(this.cache.keys())}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.evictions=0,this.lastCleanup=null,this.pendingFetches.clear(),this.pendingRefresh.clear()}getStats(){let t=this.hits+this.misses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),hits:this.hits,misses:this.misses,evictions:this.evictions,lastCleanup:this.lastCleanup,maxEntries:this.maxEntries,hitRate:t>0?this.hits/t:0}}getEntriesForSizeEstimation(){let t=Date.now();return Array.from(this.cache.entries()).filter(([,r])=>t-r.timestamp<=r.ttl)}getCacheMetadata(){let t=Date.now();return Array.from(this.cache.entries()).map(([r,a])=>{let n={key:r,timestamp:a.timestamp,ttl:a.ttl,dataType:typeof a.data,isExpired:t-a.timestamp>a.ttl};return a.staleWhileRevalidate!==void 0&&(n.staleWhileRevalidate=a.staleWhileRevalidate),n})}cleanup(){return this.cleanupDetailed().cleaned}cleanupDetailed(){let t=Date.now(),r=0,a=this.evictions;for(let[n,i]of this.cache.entries())t-i.timestamp>i.ttl&&(this.cache.delete(n),this.pendingFetches.delete(n),this.pendingRefresh.delete(n),r++,this.evictions++);return this.lastCleanup=t,{cleaned:r,evictions:this.evictions-a}}async wrap(t,r){let a=this.cache.get(t),n=this.get(t);if(n!==null){if(this.pendingRefresh.has(t)&&!this.pendingFetches.has(t)){let s=r.loader().then(d=>{let u={},l=r.ttl??a?.ttl;l!==void 0&&(u.ttl=l);let p=r.staleWhileRevalidate??a?.staleWhileRevalidate;return p!==void 0&&(u.staleWhileRevalidate=p),this.set(t,d,u),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),d},d=>{throw this.pendingFetches.delete(t),this.pendingRefresh.delete(t),d});this.pendingFetches.set(t,s)}return n}let i=this.pendingFetches.get(t);if(i)return i;let o=r.loader().then(s=>(this.set(t,s,r),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),s),s=>{throw this.pendingFetches.delete(t),this.pendingRefresh.delete(t),s});return this.pendingFetches.set(t,o),o}evictIfNeeded(){if(!(this.maxEntries<=0))for(;this.cache.size>=this.maxEntries;){let t=this.cache.keys().next().value;if(t)this.cache.delete(t),this.pendingFetches.delete(t),this.pendingRefresh.delete(t),this.evictions++;else break}}parseEnvInt(t,r){let a=process.env[t];if(!a)return r;let n=parseInt(a,10);return isNaN(n)?r:n}static generateKey(t,...r){let a=r.filter(n=>n!==void 0).map(n=>String(n)).join(":");return`${t}:${a}`}},It={BUDGETS:600*1e3,ACCOUNTS:300*1e3,CATEGORIES:300*1e3,PAYEES:600*1e3,TRANSACTIONS:120*1e3,SCHEDULED_TRANSACTIONS:300*1e3,USER_INFO:1800*1e3,MONTHS:300*1e3},ke=new be;var dA=100,Fue={info(e,t){l0.logSuccess("delta-cache",e,t?{...t}:{})},warn(e,t){let r={...t?{...t}:{},severity:"warn"};l0.logSuccess("delta-cache",e,r)},error(e,t){let r=t?{...t}:{},a=r.error,n=typeof a=="string"?a:e;l0.logError("delta-cache",e,r,n)}},Es=class{constructor(t,r,a=Fue){this.cacheManager=t,this.knowledgeStore=r,this.logger=a,this.deltaHits=0,this.deltaMisses=0,this.mergeOperations=0,this.knowledgeGapEvents=0}async fetchWithDelta(t,r,a,n,i){let o=this.assertFiniteTtl("fetchWithDelta",t,i.ttl);if(!this.isDeltaEnabled())return this.fetchWithoutDelta(t,r,a,i);let s=this.cacheManager.get(t);if(i.forceFullRefresh&&s&&!(Date.now()-s.timestamp>s.ttl))return{data:s.snapshot,wasCached:!0,usedDelta:!1,serverKnowledge:s.serverKnowledge};let d=i.forceFullRefresh?void 0:this.knowledgeStore.get(t),u=!!(!i.forceFullRefresh&&s&&d!==void 0),l=u?d:void 0,p=await a(l),_=l!==void 0?p.serverKnowledge-l:0,g=!1;_>dA&&(this.logger.warn("delta-cache.knowledge-gap",{budgetId:r,cacheKey:t,lastKnowledge:l,serverKnowledge:p.serverKnowledge,gap:_,threshold:dA,action:"full-refresh",recommendation:"Consider forcing a full refresh to resync cache."}),g=!0,this.knowledgeGapEvents++,p=await a(void 0));let f=!g&&l!==void 0&&p.serverKnowledge>l,m,h=!1;f&&s?(this.mergeOperations++,m=n(s.snapshot,p.data,i.mergeOptions),h=!0):s&&l!==void 0&&!g?m=s.snapshot:m=this.filterDeleted(p.data);let y={snapshot:m,serverKnowledge:p.serverKnowledge,timestamp:Date.now(),ttl:o};i.staleWhileRevalidate!==void 0&&(y.staleWhileRevalidate=i.staleWhileRevalidate);let b={ttl:o};return i.staleWhileRevalidate!==void 0&&(b.staleWhileRevalidate=i.staleWhileRevalidate),this.cacheManager.set(t,y,b),this.knowledgeStore.update(t,p.serverKnowledge),u?this.deltaHits++:this.deltaMisses++,{data:m,wasCached:!!s,usedDelta:h,serverKnowledge:p.serverKnowledge}}getStats(){return{deltaHits:this.deltaHits,deltaMisses:this.deltaMisses,mergeOperations:this.mergeOperations,knowledgeGapEvents:this.knowledgeGapEvents}}invalidate(t,r){if(t)if(r){let a=`${r}:list:${t}`;this.cacheManager.deleteByPrefix(a)}else this.cacheManager.deleteByBudgetId(t)}forceFullRefresh(t,r){t?this.invalidate(t,r):this.cacheManager.clear(),r&&t?this.knowledgeStore.reset(`${r}:list:${t}`):t?this.knowledgeStore.resetByBudgetId(t):this.knowledgeStore.reset()}async fetchWithoutDelta(t,r,a,n){let i=this.assertFiniteTtl("fetchWithoutDelta",t,n.ttl),o=this.cacheManager.get(t);if(o&&(!(Date.now()-o.timestamp>o.ttl)||!n.forceFullRefresh))return{data:o.snapshot,wasCached:!0,usedDelta:!1,serverKnowledge:o.serverKnowledge};let s=await a(void 0),d=this.filterDeleted(s.data),u={snapshot:d,serverKnowledge:s.serverKnowledge,timestamp:Date.now(),ttl:i};n.staleWhileRevalidate!==void 0&&(u.staleWhileRevalidate=n.staleWhileRevalidate);let l={ttl:i};return n.staleWhileRevalidate!==void 0&&(l.staleWhileRevalidate=n.staleWhileRevalidate),this.cacheManager.set(t,u,l),this.knowledgeStore.update(t,s.serverKnowledge),{data:d,wasCached:!1,usedDelta:!1,serverKnowledge:s.serverKnowledge}}filterDeleted(t){return t.filter(r=>!r.deleted)}assertFiniteTtl(t,r,a){if(!Number.isFinite(a))throw new Error(`DeltaCache.${t} requires a finite ttl for cache key "${r}". Received: ${String(a)}.`);return a}isDeltaEnabled(){return process.env.YNAB_MCP_ENABLE_DELTA==="true"}};var Ps=class{constructor(){this.knowledge=new Map}get(t){return this.knowledge.get(t)}update(t,r){if(r<0)throw new Error(`server_knowledge must be non-negative, got: ${r}`);this.knowledge.set(t,r)}reset(t){if(t===void 0||t===""){this.knowledge.clear();return}let r=[];for(let a of this.knowledge.keys())a.includes(t)&&r.push(a);for(let a of r)this.knowledge.delete(a)}resetByBudgetId(t){this.reset(`:${t}`)}getStats(){let t={};for(let[r,a]of this.knowledge.entries())t[r]=a;return{entryCount:this.knowledge.size,entries:t}}};function Kp(e,t,r){let a=new Map(e.map(n=>[n.id,{...n}]));for(let n of t){if(n.deleted&&!r?.preserveDeleted){a.delete(n.id);continue}let i=a.get(n.id)??{};a.set(n.id,{...i,...n})}return Array.from(a.values())}var lA=(e,t,r)=>{let a=!!r?.preserveDeleted,n=new Map(e.map(i=>[i.month,{...i}]));for(let i of t){if(i.deleted&&!a){n.delete(i.month);continue}let o=n.get(i.month)??{};n.set(i.month,{...o,...i})}return Array.from(n.values())},pA=(e,t,r)=>{let a=!!r?.preserveDeleted,n=new Map(e.map(i=>[i.id,cA(i)]));for(let i of t){if(i.deleted&&!a){n.delete(i.id);continue}let o=n.get(i.id);if(!o){n.set(i.id,cA(i));continue}let s={...o,...i,categories:o.categories?o.categories.map(d=>({...d})):o.categories};if(i.categories){let d=new Map((o.categories??[]).map(u=>[u.id,{...u}]));for(let u of i.categories)if(u.deleted&&!a)d.delete(u.id);else{let l=d.get(u.id)??{};d.set(u.id,{...l,...u})}s.categories=Array.from(d.values())}n.set(i.id,s)}return Array.from(n.values())},_v=(e,t,r)=>{let a=!!r?.preserveDeleted,n=new Map(e.map(i=>[i.id,uA(i)]));for(let i of t){if(i.deleted&&!a){n.delete(i.id);continue}let o=n.get(i.id);if(!o){n.set(i.id,uA(i));continue}let s={...o,...i,subtransactions:o.subtransactions?o.subtransactions.map(d=>({...d})):o.subtransactions};if(i.subtransactions){let d=new Map((o.subtransactions??[]).map(u=>[u.id,{...u}]));for(let u of i.subtransactions)if(u.deleted&&!a)d.delete(u.id);else{let l=d.get(u.id)??{};d.set(u.id,{...l,...u})}s.subtransactions=Array.from(d.values())}n.set(i.id,s)}return Array.from(n.values())},cA=e=>({...e,categories:e.categories?e.categories.map(t=>({...t})):e.categories}),uA=e=>({...e,subtransactions:e.subtransactions?e.subtransactions.map(t=>({...t})):e.subtransactions});var Ud=class{constructor(t,r){this.ynabAPI=t,this.deltaCache=r}async fetchAccounts(t,r){let a=be.generateKey("accounts","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.accounts.getAccounts(t,n):await this.ynabAPI.accounts.getAccounts(t);return{data:i.data.accounts,serverKnowledge:i.data.server_knowledge??0}},Kp,this.buildDeltaOptions(It.ACCOUNTS,r))}async fetchCategories(t,r){let a=be.generateKey("categories","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.categories.getCategories(t,n):await this.ynabAPI.categories.getCategories(t);return{data:i.data.category_groups,serverKnowledge:i.data.server_knowledge??0}},pA,this.buildDeltaOptions(It.CATEGORIES,r))}async fetchTransactions(t,r,a,n){let i=r??"all",o=a??"all",s=be.generateKey("transactions","list",t,i,o);return await this.deltaCache.fetchWithDelta(s,t,async d=>{let u=await this.ynabAPI.transactions.getTransactions(t,r,a,d);return{data:u.data.transactions,serverKnowledge:u.data.server_knowledge??0}},_v,this.buildDeltaOptions(It.TRANSACTIONS,n))}async fetchTransactionsByAccount(t,r,a,n){let i=a??"all",o=be.generateKey("transactions","account",t,r,i);return await this.deltaCache.fetchWithDelta(o,t,async s=>{let d=await this.ynabAPI.transactions.getTransactionsByAccount(t,r,a,void 0,s);return{data:d.data.transactions,serverKnowledge:d.data.server_knowledge??0}},_v,this.buildDeltaOptions(It.TRANSACTIONS,n))}async fetchAccountsFull(t){let r=await this.ynabAPI.accounts.getAccounts(t);return{data:r.data.accounts.filter(n=>!n.deleted),wasCached:!1,usedDelta:!1,serverKnowledge:r.data.server_knowledge??0}}async fetchTransactionsByAccountFull(t,r,a){let n=await this.ynabAPI.transactions.getTransactionsByAccount(t,r,a);return{data:n.data.transactions.filter(o=>!o.deleted),wasCached:!1,usedDelta:!1,serverKnowledge:n.data.server_knowledge??0}}async fetchScheduledTransactions(t,r){let a=be.generateKey("scheduled_transactions","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.scheduledTransactions.getScheduledTransactions(t,n):await this.ynabAPI.scheduledTransactions.getScheduledTransactions(t);return{data:i.data.scheduled_transactions,serverKnowledge:i.data.server_knowledge??0}},Kp,this.buildDeltaOptions(It.SCHEDULED_TRANSACTIONS,r))}async fetchPayees(t,r){let a=be.generateKey("payees","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.payees.getPayees(t,n):await this.ynabAPI.payees.getPayees(t);return{data:i.data.payees,serverKnowledge:i.data.server_knowledge??0}},Kp,this.buildDeltaOptions(It.PAYEES,r))}async fetchMonths(t,r){let a=be.generateKey("months","list",t);return await this.deltaCache.fetchWithDelta(a,t,async n=>{let i=n!==void 0?await this.ynabAPI.months.getBudgetMonths(t,n):await this.ynabAPI.months.getBudgetMonths(t);return{data:i.data.months,serverKnowledge:i.data.server_knowledge??0}},lA,this.buildDeltaOptions(It.MONTHS,r))}async fetchBudgets(t){let r=be.generateKey("budgets","list"),a=await this.deltaCache.fetchWithDelta(r,"global",async()=>{let n=await this.ynabAPI.budgets.getBudgets(),i=n.data.server_knowledge??0;return{data:n.data.budgets,serverKnowledge:i}},Kp,{ttl:t?.ttl??It.BUDGETS,forceFullRefresh:!0});return{...a,data:a.data}}buildDeltaOptions(t,r){return{ttl:r?.ttl??t,...r?.forceFullRefresh!==void 0&&{forceFullRefresh:r.forceFullRefresh}}}};var uo;function zue(e){if(uo&&!uo.manuallyConfigured&&uo.ynabAPI&&uo.ynabAPI!==e&&(uo=void 0),uo?.deltaFetcher)return uo.deltaFetcher;let t=uo?{...uo}:{};t.manuallyConfigured===void 0&&(t.manuallyConfigured=!1),t.deltaCache||(t.knowledgeStore||(t.knowledgeStore=new Ps),t.deltaCache=new Es(ke,t.knowledgeStore));let r=new Ud(e,t.deltaCache);return t.deltaFetcher=r,t.ynabAPI||(t.ynabAPI=e),uo=t,r}function mA(e){return e!==null&&typeof e=="object"&&e instanceof Ud&&typeof e.fetchAccounts=="function"&&typeof e.fetchCategories=="function"}function fA(e){return e!==null&&typeof e=="object"&&e instanceof Es&&typeof e.fetchWithDelta=="function"}function hA(e){return e!==null&&typeof e=="object"&&e instanceof Ps&&typeof e.get=="function"&&typeof e.update=="function"}function Xp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(e.constructor===Object||e.constructor===void 0)}function Cs(e){if(e===null)return"null";if(e===void 0)return"undefined";let t=typeof e;if(t!=="object")return t;let r=e.constructor?.name;return r?`${t} (${r})`:t}function Xr(e,t,r){if(r!==void 0){if(!mA(t))throw new Error(`resolveDeltaFetcherArgs: When providing 3 arguments, the second argument must be a DeltaFetcher instance. Got: ${Cs(t)}`);if(!Xp(r))throw new Error(`resolveDeltaFetcherArgs: When providing 3 arguments, the third argument must be a params object. Got: ${Cs(r)}`);return{deltaFetcher:t,params:r}}if(mA(t))throw new Error("resolveDeltaFetcherArgs: When providing 2 arguments, the second argument must be a params object, not a DeltaFetcher. To use a custom DeltaFetcher, provide all 3 arguments: (ynabAPI, deltaFetcher, params)");if(!Xp(t))throw new Error(`resolveDeltaFetcherArgs: When providing 2 arguments, the second argument must be a params object. Got: ${Cs(t)}`);return{deltaFetcher:zue(e),params:t}}function ki(e,t,r){if(r!==void 0){if(!fA(e))throw new Error(`resolveDeltaWriteArgs: When providing 3 arguments, the first argument must be a DeltaCache instance. Got: ${Cs(e)}`);if(!hA(t))throw new Error(`resolveDeltaWriteArgs: When providing 3 arguments, the second argument must be a ServerKnowledgeStore instance. Got: ${Cs(t)}`);if(!Xp(r))throw new Error(`resolveDeltaWriteArgs: When providing 3 arguments, the third argument must be a params object. Got: ${Cs(r)}`);return{deltaCache:e,knowledgeStore:t,params:r}}if(t!==void 0){let i=hA(t),o=Xp(t);if(!i&&!o)throw new Error(`resolveDeltaWriteArgs: When providing 2 arguments, the second argument must be either a ServerKnowledgeStore or a params object. Got: ${Cs(t)}`);if(o)throw new Error("resolveDeltaWriteArgs: Invalid argument combination. When providing 2 arguments where the second is a params object, this is ambiguous. Either provide 1 argument (params only) or 3 arguments (deltaCache, knowledgeStore, params).");if(i)throw new Error("resolveDeltaWriteArgs: When providing DeltaCache and ServerKnowledgeStore, you must also provide params as the third argument. Got 2 arguments, expected 3: (deltaCache, knowledgeStore, params)")}if(fA(e))throw new Error("resolveDeltaWriteArgs: When providing only 1 argument, it must be a params object, not a DeltaCache. To use a custom DeltaCache, provide all 3 arguments: (deltaCache, knowledgeStore, params)");if(!Xp(e))throw new Error(`resolveDeltaWriteArgs: When providing only 1 argument, it must be a params object. Got: ${Cs(e)}`);let a=new Ps;return{deltaCache:new Es(ke,a),knowledgeStore:a,params:e}}var gA=c.object({budget_id:c.string().min(1,"Budget ID is required")}).strict();async function _A(e,t,r){let{deltaFetcher:a}=Xr(e,t??{},r);return await mt(async()=>{let n=await a.fetchBudgets(),i=n.data,o=n.wasCached;return{content:[{type:"text",text:he.format({budgets:i.map(s=>({id:s.id,name:s.name,last_modified_on:s.last_modified_on,first_month:s.first_month,last_month:s.last_month,date_format:s.date_format,currency_format:s.currency_format})),cached:o,cache_info:o?`Data retrieved from cache for improved performance${n.usedDelta?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API"})}]}},"ynab:list_budgets","listing budgets")}async function yA(e,t){return await mt(async()=>{let a=(await e.budgets.getBudgetById(t.budget_id)).data.budget;return{content:[{type:"text",text:he.format({budget:{id:a.id,name:a.name,last_modified_on:a.last_modified_on,first_month:a.first_month,last_month:a.last_month,date_format:a.date_format,currency_format:a.currency_format,accounts_count:a.accounts?.length??0,categories_count:a.categories?.length??0,payees_count:a.payees?.length??0,months_count:a.months?.length??0,message:"Use list_accounts, list_categories, list_payees, and list_months to get detailed lists"}})}]}},"ynab:get_budget","getting budget details")}function fe(e){return Math.round(e)/1e3}function Qp(e){return Math.round(e*1e3)}var Sr={ACCOUNTS:"accounts",BUDGETS:"budgets",CATEGORIES:"categories",PAYEES:"payees",TRANSACTIONS:"transactions",MONTHS:"months"};var vA=c.object({budget_id:c.string().min(1,"Budget ID is required"),limit:c.number().int().positive().optional()}).strict(),bA=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().min(1,"Account ID is required")}).strict(),wA=c.object({budget_id:c.string().min(1,"Budget ID is required"),name:c.string().min(1,"Account name is required"),type:c.enum(["checking","savings","creditCard","cash","lineOfCredit","otherAsset","otherLiability"]),balance:c.number().optional(),dry_run:c.boolean().optional()}).strict();async function SA(e,t,r){let{deltaFetcher:a,params:n}=Xr(e,t,r);return await mt(async()=>{let i=await a.fetchAccounts(n.budget_id),o=i.data,s=i.wasCached,d=o.length;return n.limit!==void 0&&(o=o.slice(0,n.limit)),{content:[{type:"text",text:he.format({accounts:o.map(u=>({id:u.id,name:u.name,type:u.type,on_budget:u.on_budget,closed:u.closed,note:u.note,balance:fe(u.balance),cleared_balance:fe(u.cleared_balance),uncleared_balance:fe(u.uncleared_balance),transfer_payee_id:u.transfer_payee_id,direct_import_linked:u.direct_import_linked,direct_import_in_error:u.direct_import_in_error})),total_count:d,returned_count:o.length,cached:s,cache_info:s?`Data retrieved from cache for improved performance${i.usedDelta?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API"})}]}},"ynab:list_accounts","listing accounts")}async function TA(e,t){return await mt(async()=>{let r=be.generateKey(Sr.ACCOUNTS,"get",t.budget_id,t.account_id),a=ke.has(r),n=await ke.wrap(r,{ttl:It.ACCOUNTS,loader:async()=>(await e.accounts.getAccountById(t.budget_id,t.account_id)).data.account});return{content:[{type:"text",text:he.format({account:{id:n.id,name:n.name,type:n.type,on_budget:n.on_budget,closed:n.closed,note:n.note,balance:fe(n.balance),cleared_balance:fe(n.cleared_balance),uncleared_balance:fe(n.uncleared_balance),transfer_payee_id:n.transfer_payee_id,direct_import_linked:n.direct_import_linked,direct_import_in_error:n.direct_import_in_error},cached:a,cache_info:a?"Data retrieved from cache for improved performance":"Fresh data retrieved from YNAB API"})}]}},"ynab:get_account","getting account details")}async function $A(e,t,r,a){let{deltaCache:n,params:i}=ki(t,r,a);return await mt(async()=>{if(i.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_account",request:{budget_id:i.budget_id,name:i.name,type:i.type,balance:i.balance??0}})}]};let o={name:i.name,type:i.type,balance:i.balance?i.balance*1e3:0},d=(await e.accounts.createAccount(i.budget_id,{account:o})).data.account,u=be.generateKey(Sr.ACCOUNTS,"list",i.budget_id);return ke.delete(u),n.invalidate(i.budget_id,Sr.ACCOUNTS),{content:[{type:"text",text:he.format({account:{id:d.id,name:d.name,type:d.type,on_budget:d.on_budget,closed:d.closed,note:d.note,balance:fe(d.balance),cleared_balance:fe(d.cleared_balance),uncleared_balance:fe(d.uncleared_balance),transfer_payee_id:d.transfer_payee_id,direct_import_linked:d.direct_import_linked,direct_import_in_error:d.direct_import_in_error}})}]}},"ynab:create_account","creating account")}var NA=require("crypto");function yu(e,t){if(!e)throw new Error(t);return e}var Jo=e=>`${e.slice(0,7)}-01`;function xA(e,t){if(e&&(e.category_id&&t.add(e.category_id),Array.isArray(e.subtransactions)))for(let r of e.subtransactions)r?.category_id&&t.add(r.category_id)}function p0(...e){let t=new Set;for(let r of e)xA(r,t);return t}function Jue(e,t){if(e.size!==t.size)return!1;for(let r of e)if(!t.has(r))return!1;return!0}function rm(e,t,r,a,n,i,o={}){e.invalidate(r,"transactions"),ke.delete(be.generateKey("transactions","list",r));for(let p of n){let _=be.generateKey("transactions","account",r,p);ke.deleteByPrefix(_)}let s=o.accountTotalsChanged??!0;s&&ke.delete(be.generateKey("accounts","list",r));for(let p of n)ke.delete(be.generateKey("account","get",r,p));let d=o.affectedCategoryIds??new Set;if(o.invalidateAllCategories||d.size>0){ke.delete(be.generateKey("categories","list",r));for(let p of d)ke.delete(be.generateKey("category","get",r,p))}let l=o.invalidateMonths??i.size>0;if(l){ke.delete(be.generateKey("months","list",r)),e.invalidate(r,"months");for(let p of i)ke.delete(be.generateKey("month","get",r,p))}if(a!==void 0){let p=be.generateKey("transactions","list",r);if(t.update(p,a),s){let _=be.generateKey("accounts","list",r);t.update(_,a)}if(l&&i.size>0){let _=be.generateKey("months","list",r);t.update(_,a)}}}var DA=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().optional(),category_id:c.string().optional(),since_date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),type:c.enum(["uncategorized","unapproved"]).optional()}).strict(),kA=c.object({budget_id:c.string().min(1,"Budget ID is required"),transaction_id:c.string().min(1,"Transaction ID is required")}).strict(),yv=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().min(1,"Account ID is required"),amount:c.number().int("Amount must be an integer in milliunits"),date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)"),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional(),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),import_id:c.string().min(1,"Import ID cannot be empty").optional(),dry_run:c.boolean().optional(),subtransactions:c.array(c.object({amount:c.number().int("Subtransaction amount must be an integer in milliunits"),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional()}).strict()).min(1,"At least one subtransaction is required when provided").optional()}).strict().superRefine((e,t)=>{e.subtransactions&&e.subtransactions.length>0&&e.subtransactions.reduce((a,n)=>a+n.amount,0)!==e.amount&&t.addIssue({code:c.ZodIssueCode.custom,message:"Amount must equal the sum of subtransaction amounts",path:["amount"]})}),jue=yv.pick({account_id:!0,amount:!0,date:!0,payee_name:!0,payee_id:!0,category_id:!0,memo:!0,cleared:!0,approved:!0,flag_color:!0,import_id:!0}),que=jue.strict(),vv=c.object({budget_id:c.string().min(1,"Budget ID is required"),transactions:c.array(que).min(1,"At least one transaction is required").max(100,"A maximum of 100 transactions may be created at once"),dry_run:c.boolean().optional()}).strict(),RA=64*1024,IA=96*1024,EA=100*1024;function em(e){if(e.import_id)return e.import_id;let r=[`account:${e.account_id??""}`,`date:${e.date??""}`,`amount:${e.amount??0}`,`payee:${e.payee_id??e.payee_name??""}`,`category:${e.category_id??""}`,`memo:${e.memo??""}`,`cleared:${e.cleared??""}`,`approved:${e.approved??!1}`,`flag:${e.flag_color??""}`].join("|");return`hash:${(0,NA.createHash)("sha256").update(r).digest("hex").slice(0,16)}`}function tm(e){let t={};return e.account_id!==void 0&&(t.account_id=e.account_id),e.date!==void 0&&(t.date=e.date),e.amount!==void 0&&(t.amount=e.amount),e.cleared!==void 0&&(t.cleared=e.cleared),e.approved!==void 0&&(t.approved=e.approved),e.flag_color!==void 0&&(t.flag_color=e.flag_color),t.payee_id=e.payee_id??null,t.payee_name=e.payee_name??null,t.category_id=e.category_id??null,t.memo=e.memo??null,t.import_id=e.import_id??null,t}function bv(e,t,r){let a=new Map,n=new Map,i=t.transactions??[],o=(u,l,p)=>{let _=u.get(l);if(_){_.push(p);return}u.set(l,[p])};for(let u of i){if(!u.id)continue;let l=em(u);l.startsWith("hash:")?o(n,l,u.id):o(a,l,u.id)}let s=(u,l)=>{let p=u.get(l);if(!p||p.length===0)return;let[_]=p.splice(0,1);return p.length===0&&u.delete(l),_},d=[];for(let[u,l]of e.entries()){let p=tm(l),_=em(p);if(l.import_id&&r.has(l.import_id)){d.push({request_index:u,status:"duplicate",correlation_key:_});continue}let g;if(_.startsWith("hash:")?g=s(n,_):g=s(a,_),!g&&!_.startsWith("hash:")){let f=em(tm({...l,import_id:void 0}));g=s(n,f)}if(g){let f={request_index:u,status:"created",correlation_key:_};f.transaction_id=g,d.push(f);continue}Di.logError("ynab:create_transactions","correlate_results",{request_index:u,correlation_key:_,request:{account_id:l.account_id,date:l.date,amount:l.amount,import_id:l.import_id}},"correlation_failed"),d.push({request_index:u,status:"failed",correlation_key:_,error_code:"correlation_failed",error:"Unable to correlate request transaction with YNAB response"})}return d}function _u(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Uue(e){let t=(s,d)=>s?s.includes(d)?s:`${s} ${d}`:d;if(_u({...e,mode:"full"})<=RA)return{...e,mode:"full"};let{transactions:a,...n}=e,i={...n,message:t(e.message,"Response downgraded to summary to stay under size limits."),mode:"summary"};if(_u(i)<=IA)return i;let o={...i,results:n.results.map(s=>({request_index:s.request_index,status:s.status,transaction_id:s.transaction_id,correlation_key:s.correlation_key,error:s.error})),message:t(n.message,"Response downgraded to ids_only to meet 100KB limit."),mode:"ids_only"};if(_u(o)<=EA)return o;throw new Ir("RESPONSE_TOO_LARGE: Unable to format bulk create response within 100KB limit",`Batch size: ${e.summary.total_requested} transactions`,["Reduce the batch size and retry","Consider splitting into multiple smaller batches"])}var Bue=c.object({name:c.string().min(1,"Item name is required"),amount:c.number().finite("Item amount must be a finite number").refine(e=>e>=0,"Item amount must be zero or greater"),quantity:c.number().finite("Quantity must be a finite number").positive("Quantity must be greater than zero").optional(),memo:c.string().optional()}).strict(),Vue=c.object({category_id:c.string().min(1,"Category ID is required"),category_name:c.string().optional(),items:c.array(Bue).min(1,"Each category must include at least one item")}).strict(),PA=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().min(1,"Account ID is required"),payee_name:c.string().min(1,"Payee name is required"),date:c.string().regex(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),memo:c.string().optional(),receipt_subtotal:c.number().finite("Receipt subtotal must be a finite number").refine(e=>e>=0,"Receipt subtotal must be zero or greater").optional(),receipt_tax:c.number().finite("Receipt tax must be a finite number").refine(e=>e>=0,"Receipt tax must be zero or greater"),receipt_total:c.number().finite("Receipt total must be a finite number").refine(e=>e>0,"Receipt total must be greater than zero"),categories:c.array(Vue).min(1,"At least one categorized group is required to create a split transaction"),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),dry_run:c.boolean().optional()}).strict().superRefine((e,t)=>{let r=e.categories.flatMap(i=>i.items).reduce((i,o)=>i+o.amount,0);e.receipt_subtotal!==void 0&&Math.abs(e.receipt_subtotal-r)>.01&&t.addIssue({code:c.ZodIssueCode.custom,message:`Receipt subtotal (${e.receipt_subtotal.toFixed(2)}) does not match categorized items total (${r.toFixed(2)})`,path:["receipt_subtotal"]});let a=r+e.receipt_tax;Math.abs(a-e.receipt_total)>.01&&t.addIssue({code:c.ZodIssueCode.custom,message:`Receipt total (${e.receipt_total.toFixed(2)}) does not match subtotal plus tax (${a.toFixed(2)})`,path:["receipt_total"]})}),CA=c.object({budget_id:c.string().min(1,"Budget ID is required"),transaction_id:c.string().min(1,"Transaction ID is required"),account_id:c.string().optional(),amount:c.number().int("Amount must be an integer in milliunits").optional(),date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional(),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),dry_run:c.boolean().optional()}).strict(),Lue=c.object({id:c.string().min(1,"Transaction ID is required"),amount:c.number().int("Amount must be an integer in milliunits").optional(),date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),payee_name:c.string().optional(),payee_id:c.string().optional(),category_id:c.string().optional(),memo:c.string().optional(),cleared:c.enum(["cleared","uncleared","reconciled"]).optional(),approved:c.boolean().optional(),flag_color:c.enum(["red","orange","yellow","green","blue","purple"]).optional(),original_account_id:c.string().optional(),original_date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional()}).strict(),wv=c.object({budget_id:c.string().min(1,"Budget ID is required"),transactions:c.array(Lue).min(1,"At least one transaction is required").max(100,"A maximum of 100 transactions may be updated at once"),dry_run:c.boolean().optional()}).strict(),AA=c.object({budget_id:c.string().min(1,"Budget ID is required"),transaction_id:c.string().min(1,"Transaction ID is required"),dry_run:c.boolean().optional()}).strict();async function MA(e,t,r){let{deltaFetcher:a,params:n}=Xr(e,t,r);return await mt(async()=>{let i,o=!1,s=!1;if(n.account_id){if(!(await a.fetchAccounts(n.budget_id)).data.some(g=>g.id===n.account_id))throw new Error(`Account ${n.account_id} not found in budget ${n.budget_id}`);let _=await a.fetchTransactionsByAccount(n.budget_id,n.account_id,n.since_date);i=_.data,o=_.wasCached,s=_.usedDelta}else if(n.category_id)i=(await e.transactions.getTransactionsByCategory(n.budget_id,n.category_id,n.since_date)).data.transactions;else{let l=await a.fetchTransactions(n.budget_id,n.since_date,n.type);i=l.data,o=l.wasCached,s=l.usedDelta}let d=JSON.stringify(i).length;if(d>9e4){let l=i.slice(0,50);return{content:[{type:"text",text:he.format({message:`Found ${i.length} transactions (${Math.round(d/1024)}KB). Too large to display all.`,suggestion:"Use 'export_transactions' tool to save all transactions to a file.",showing:`First ${l.length} transactions:`,total_count:i.length,estimated_size_kb:Math.round(d/1024),cached:o,cache_info:o?`Data retrieved from cache for improved performance${s?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API",preview_transactions:l.map(p=>({id:p.id,date:p.date,amount:fe(p.amount),memo:p.memo,payee_name:p.payee_name,category_name:p.category_name}))})}]}}return{content:[{type:"text",text:he.format({total_count:i.length,cached:o,cache_info:o?`Data retrieved from cache for improved performance${s?" (delta merge applied)":""}`:"Fresh data retrieved from YNAB API",transactions:i.map(l=>({id:l.id,date:l.date,amount:fe(l.amount),memo:l.memo,cleared:l.cleared,approved:l.approved,flag_color:l.flag_color,account_id:l.account_id,payee_id:l.payee_id,category_id:l.category_id,transfer_account_id:l.transfer_account_id,transfer_transaction_id:l.transfer_transaction_id,matched_transaction_id:l.matched_transaction_id,import_id:l.import_id,deleted:l.deleted}))})}]}},"ynab:list_transactions","listing transactions")}async function FA(e,t){try{let r=process.env.NODE_ENV!=="test",a,n=!1;if(r){let i=be.generateKey("transaction","get",t.budget_id,t.transaction_id);n=ke.has(i),a=await ke.wrap(i,{ttl:It.TRANSACTIONS,loader:async()=>{let o=await e.transactions.getTransactionById(t.budget_id,t.transaction_id);return yu(o.data.transaction,"Transaction not found")}})}else{let i=await e.transactions.getTransactionById(t.budget_id,t.transaction_id);a=yu(i.data.transaction,"Transaction not found")}return{content:[{type:"text",text:he.format({transaction:{id:a.id,date:a.date,amount:fe(a.amount),memo:a.memo,cleared:a.cleared,approved:a.approved,flag_color:a.flag_color,account_id:a.account_id,payee_id:a.payee_id,category_id:a.category_id,transfer_account_id:a.transfer_account_id,transfer_transaction_id:a.transfer_transaction_id,matched_transaction_id:a.matched_transaction_id,import_id:a.import_id,deleted:a.deleted,account_name:a.account_name,payee_name:a.payee_name,category_name:a.category_name},cached:n,cache_info:n?"Data retrieved from cache for improved performance":"Fresh data retrieved from YNAB API"})}]}}catch(r){return m0(r,"Failed to get transaction")}}async function Sv(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);try{if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_transaction",request:o})}]};let s={account_id:o.account_id,amount:o.amount,date:o.date,cleared:o.cleared,flag_color:o.flag_color};if(o.payee_name!==void 0&&(s.payee_name=o.payee_name),o.payee_id!==void 0&&(s.payee_id=o.payee_id),o.category_id!==void 0&&(s.category_id=o.category_id),o.memo!==void 0&&(s.memo=o.memo),o.approved!==void 0&&(s.approved=o.approved),o.import_id!==void 0&&(s.import_id=o.import_id),o.subtransactions&&o.subtransactions.length>0){let m=o.subtransactions.map(h=>{let y={amount:h.amount};return h.payee_name!==void 0&&(y.payee_name=h.payee_name),h.payee_id!==void 0&&(y.payee_id=h.payee_id),h.category_id!==void 0&&(y.category_id=h.category_id),h.memo!==void 0&&(y.memo=h.memo),y});s.subtransactions=m}let d=await e.transactions.createTransaction(o.budget_id,{transaction:s}),u=yu(d.data.transaction,"Transaction creation failed"),l=new Set([u.account_id]),p=new Set([Jo(u.date)]),_=p0(u);rm(n,i,o.budget_id,d.data.server_knowledge,l,p,{affectedCategoryIds:_,accountTotalsChanged:!0,invalidateMonths:!0});let f=(await e.accounts.getAccountById(o.budget_id,u.account_id)).data.account;return{content:[{type:"text",text:he.format({transaction:{id:u.id,date:u.date,amount:fe(u.amount),memo:u.memo,cleared:u.cleared,approved:u.approved,flag_color:u.flag_color,account_id:u.account_id,payee_id:u.payee_id,category_id:u.category_id,transfer_account_id:u.transfer_account_id,transfer_transaction_id:u.transfer_transaction_id,matched_transaction_id:u.matched_transaction_id,import_id:u.import_id,deleted:u.deleted,account_balance:f.balance,account_cleared_balance:f.cleared_balance,subtransactions:u.subtransactions?.map(m=>({id:m.id,transaction_id:m.transaction_id,amount:fe(m.amount),memo:m.memo,payee_id:m.payee_id,payee_name:m.payee_name,category_id:m.category_id,category_name:m.category_name,transfer_account_id:m.transfer_account_id,transfer_transaction_id:m.transfer_transaction_id,deleted:m.deleted}))}})}]}}catch(s){return m0(s,"Failed to create transaction")}}function Wue(e){let t=e.quantity?` (x${e.quantity})`:"";return e.memo&&e.memo.trim().length>0?`${e.name}${t} - ${e.memo}`:t?`${e.name}${t}`:e.name}function Yue(e,t,r){if(t===0){for(let n of r)n.tax_milliunits=0;return}if(e<=0)throw new Error("Receipt subtotal must be greater than zero to distribute tax");let a=0;r.forEach((n,i)=>{if(i===r.length-1)n.tax_milliunits=t-a;else{let o=Math.round(t*n.subtotal_milliunits/e);n.tax_milliunits=o,a+=o}})}async function zA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a),s=o.date??new Date().toISOString().slice(0,10),d=o.categories.map(w=>{let R=w.items.map(M=>({name:M.name,amount_milliunits:Qp(M.amount),quantity:M.quantity,memo:M.memo})),N=R.reduce((M,X)=>M+X.amount_milliunits,0);return{category_id:w.category_id,category_name:w.category_name,subtotal_milliunits:N,tax_milliunits:0,items:R}}),u=d.reduce((w,R)=>w+R.subtotal_milliunits,0),l=o.receipt_subtotal!==void 0?Qp(o.receipt_subtotal):void 0;if(l!==void 0&&Math.abs(l-u)>1)throw new Error(`Categorized items subtotal (${fe(u)}) does not match receipt subtotal (${fe(l)})`);let p=Qp(o.receipt_tax),_=Qp(o.receipt_total),g=u+p;if(Math.abs(g-_)>1)throw new Error(`Receipt total (${fe(_)}) does not equal subtotal plus tax (${fe(g)})`);Yue(u,p,d);let f=d.flatMap(w=>{let R=w.items.map(M=>{let X=Wue({name:M.name,quantity:M.quantity,memo:M.memo}),q={amount:-M.amount_milliunits,category_id:w.category_id};return X&&(q.memo=X),q}),N=w.tax_milliunits>0?[{amount:-w.tax_milliunits,category_id:w.category_id,memo:`Tax - ${w.category_name??"Uncategorized"}`}]:[];return[...R,...N]}),m={subtotal:fe(u),tax:fe(p),total:fe(_),categories:d.map(w=>({category_id:w.category_id,category_name:w.category_name,items:w.items.map(R=>({name:R.name,quantity:R.quantity,amount:fe(R.amount_milliunits),memo:R.memo})),subtotal:fe(w.subtotal_milliunits),tax:fe(w.tax_milliunits),total:fe(w.subtotal_milliunits+w.tax_milliunits)}))};if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_receipt_split_transaction",transaction_preview:{account_id:o.account_id,payee_name:o.payee_name,date:s,amount:fe(_),cleared:o.cleared??"uncleared"},receipt_summary:m,subtransactions:f.map(w=>({amount:fe(-w.amount),category_id:w.category_id,memo:w.memo}))})}]};let h={budget_id:o.budget_id,account_id:o.account_id,amount:-_,date:s,payee_name:o.payee_name,memo:o.memo,cleared:o.cleared??"uncleared",flag_color:o.flag_color,subtransactions:f};o.approved!==void 0&&(h.approved=o.approved);let y=await Sv(e,n,i,h),b=y.content?.[0];if(!b||b.type!=="text")return y;try{let w=JSON.parse(b.text);w.receipt_summary=m,b.text=he.format(w)}catch{}return y}async function JA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);try{if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"update_transaction",request:o})}]};let s=await e.transactions.getTransactionById(o.budget_id,o.transaction_id),d=yu(s.data.transaction,"Original transaction not found"),u={};o.account_id!==void 0&&(u.account_id=o.account_id),o.amount!==void 0&&(u.amount=o.amount),o.date!==void 0&&(u.date=o.date),o.payee_name!==void 0&&(u.payee_name=o.payee_name),o.payee_id!==void 0&&(u.payee_id=o.payee_id),o.category_id!==void 0&&(u.category_id=o.category_id),o.memo!==void 0&&(u.memo=o.memo),o.cleared!==void 0&&(u.cleared=o.cleared),o.approved!==void 0&&(u.approved=o.approved),o.flag_color!==void 0&&(u.flag_color=o.flag_color);let l=await e.transactions.updateTransaction(o.budget_id,o.transaction_id,{transaction:u}),p=yu(l.data.transaction,"Transaction update failed"),_=be.generateKey("transaction","get",o.budget_id,o.transaction_id);ke.delete(_);let g=new Set([d.account_id,p.account_id]);d.transfer_account_id&&g.add(d.transfer_account_id),p.transfer_account_id&&g.add(p.transfer_account_id);let f=new Set([Jo(d.date),Jo(p.date)]),m=p0(d),h=p0(p),y=new Set([...m,...h]),b=!Jue(m,h),w=p.amount!==d.amount,R=p.account_id!==d.account_id,N=p.cleared!==d.cleared,M=p.transfer_account_id!==d.transfer_account_id,X=p.transfer_transaction_id!==d.transfer_transaction_id,q=p.date!==d.date;rm(n,i,o.budget_id,l.data.server_knowledge,g,f,{affectedCategoryIds:y,accountTotalsChanged:w||R||N||M||X,invalidateMonths:w||b||q});let oe=(await e.accounts.getAccountById(o.budget_id,p.account_id)).data.account;return{content:[{type:"text",text:he.format({transaction:{id:p.id,date:p.date,amount:fe(p.amount),memo:p.memo,cleared:p.cleared,approved:p.approved,flag_color:p.flag_color,account_id:p.account_id,payee_id:p.payee_id,category_id:p.category_id,transfer_account_id:p.transfer_account_id,transfer_transaction_id:p.transfer_transaction_id,matched_transaction_id:p.matched_transaction_id,import_id:p.import_id,deleted:p.deleted},updated_balance:oe.balance,updated_cleared_balance:oe.cleared_balance})}]}}catch(s){return m0(s,"Failed to update transaction")}}async function jA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);try{if(o.dry_run)return{content:[{type:"text",text:he.format({dry_run:!0,action:"delete_transaction",request:o})}]};let s=await e.transactions.deleteTransaction(o.budget_id,o.transaction_id),d=yu(s.data.transaction,"Transaction deletion failed"),u=be.generateKey("transaction","get",o.budget_id,o.transaction_id);ke.delete(u);let l=new Set([d.account_id]);d.transfer_account_id&&l.add(d.transfer_account_id);let p=new Set([Jo(d.date)]),_=p0(d);rm(n,i,o.budget_id,s.data.server_knowledge,l,p,{affectedCategoryIds:_,accountTotalsChanged:!0,invalidateMonths:!0});let f=(await e.accounts.getAccountById(o.budget_id,d.account_id)).data.account;return{content:[{type:"text",text:he.format({message:"Transaction deleted successfully",transaction:{id:d.id,deleted:d.deleted},updated_balance:f.balance,updated_cleared_balance:f.cleared_balance})}]}}catch(s){return m0(s,"Failed to delete transaction")}}async function qA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);return await mt(async()=>{let s=vv.safeParse(o);if(!s.success){let q=new Map,ne=s.error.issues??[];for(let V of ne){let x=V.path.find(U=>typeof U=="number"),S=V.message,D=x!==void 0?x:null,P=q.get(D)??[];P.push(S),q.set(D,P)}let oe=Array.from(q.entries()).map(([V,x])=>({transaction_index:V,errors:x}));throw new Ir("Bulk transaction validation failed",JSON.stringify(oe,null,2),["Ensure each transaction includes required fields","Limit batches to 100 items"])}let{budget_id:d,transactions:u,dry_run:l}=s.data,p=new Map;for(let[q,ne]of u.entries())if(ne.import_id&&ne.import_id.trim().length>0){let oe=p.get(ne.import_id);oe?oe.push(q):p.set(ne.import_id,[q])}let _=Array.from(p.entries()).filter(([,q])=>q.length>1).map(([q,ne])=>({import_id:q,indices:ne}));if(_.length>0){let q=_.map(({import_id:ne,indices:oe})=>({import_id:ne,transaction_indices:oe,count:oe.length}));throw new Ir("Duplicate import_id values detected within batch",JSON.stringify(q,null,2),["Ensure each transaction has a unique import_id within the batch","Remove duplicate import_id values or omit import_id to use hash-based correlation"])}if(l){let q=u.reduce((D,P)=>D+P.amount,0),ne=Array.from(new Set(u.map(D=>D.account_id))),oe=Array.from(new Set(u.map(D=>D.category_id).filter(D=>D!==void 0))),V=[...u.map(D=>D.date)].sort(),x=V.length>0?{earliest:V[0],latest:V[V.length-1]}:void 0,S=u.slice(0,10).map((D,P)=>({request_index:P,account_id:D.account_id,date:D.date,amount:fe(D.amount),memo:D.memo,payee_id:D.payee_id,payee_name:D.payee_name,category_id:D.category_id,import_id:D.import_id}));return{content:[{type:"text",text:he.format({dry_run:!0,action:"create_transactions",validation:"passed",summary:{total_transactions:u.length,total_amount:fe(q),accounts_affected:ne,date_range:x,categories_affected:oe},transactions_preview:S,note:"Dry run complete. No transactions created. No caches invalidated. No server_knowledge updated."})}]}}let g=u.map(q=>{let ne={account_id:q.account_id,amount:q.amount,date:q.date};return q.payee_id!==void 0&&(ne.payee_id=q.payee_id),q.payee_name!==void 0&&(ne.payee_name=q.payee_name),q.category_id!==void 0&&(ne.category_id=q.category_id),q.memo!==void 0&&(ne.memo=q.memo),q.cleared!==void 0&&(ne.cleared=q.cleared),q.approved!==void 0&&(ne.approved=q.approved),q.flag_color!==void 0&&(ne.flag_color=q.flag_color),q.import_id!==void 0&&(ne.import_id=q.import_id),ne}),m=(await e.transactions.createTransactions(d,{transactions:g})).data,h=new Set(m.duplicate_import_ids??[]),y=bv(u,m,h),b={total_requested:u.length,created:m.transaction_ids?.length??0,duplicates:h.size,failed:y.filter(q=>q.status==="failed").length},w={success:b.failed===0,server_knowledge:m.server_knowledge,summary:b,results:y,transactions:m.transactions??[],duplicate_import_ids:m.duplicate_import_ids??[],message:`Processed ${b.total_requested} transactions: ${b.created} created, ${b.duplicates} duplicates, ${b.failed} failed.`},R=new Set(u.map(q=>q.account_id)),N=new Set(u.map(q=>Jo(q.date))),M=new Set;for(let q of m.transactions??[])xA(q,M);rm(n,i,d,m.server_knowledge,R,N,{affectedCategoryIds:M,accountTotalsChanged:!0,invalidateMonths:!0});let X=Uue(w);return{content:[{type:"text",text:he.format(X)}]}},"ynab:create_transactions","bulk transaction creation")}async function OA(e,t,r,a={}){let n=new Map,i=[],o=new Set(a.previewTransactionIds??[]),s=new Map,d=new Set(o);for(let h of r)h.original_account_id&&h.original_date?n.set(h.id,{account_id:h.original_account_id,date:h.original_date}):i.push(h.id);if(o.size===0&&i.length===0)return{metadata:n,unresolvedIds:[],previewDetails:s};let u=new Set(i),l=new Set([...i,...o]);for(let h of l){let y=be.generateKey("transaction","get",t,h),b=ke.get(y);b&&(u.has(h)&&(n.set(h,{account_id:b.account_id,date:b.date}),u.delete(h)),o.has(h)&&!s.has(h)&&(s.set(h,b),d.delete(h)))}let p=Array.from(u);if(p.length===0&&d.size===0)return{metadata:n,unresolvedIds:[],previewDetails:s};let _=5,g=[],f=new Set(p),m=Array.from(new Set([...p,...d]));for(let h=0;h<m.length;h+=_){let b=m.slice(h,h+_).map(async w=>{try{let N=(await e.transactions.getTransactionById(t,w)).data.transaction;N&&(f.has(w)&&(n.set(w,{account_id:N.account_id,date:N.date}),f.delete(w)),d.has(w)&&!s.has(w)&&(s.set(w,N),d.delete(w)))}catch{f.has(w)&&Di.logError("ynab:update_transactions","resolve_metadata",{transaction_id:w},"Failed to resolve transaction metadata")}});g.push(...b)}return await Promise.all(g),{metadata:n,unresolvedIds:Array.from(f),previewDetails:s}}function Zue(e){let t=(s,d)=>s?s.includes(d)?s:`${s} ${d}`:d;if(_u(e)<=RA)return{...e,mode:"full"};let{transactions:a,...n}=e,i={...n,message:t(e.message,"Response downgraded to summary to stay under size limits."),mode:"summary"};if(_u(i)<=IA)return i;let o={...i,results:n.results.map(s=>{let d={request_index:s.request_index,status:s.status,transaction_id:s.transaction_id,correlation_key:s.correlation_key};return s.error&&(d.error=s.error),s.error_code&&(d.error_code=s.error_code),d}),message:t(n.message,"Response downgraded to ids_only to meet 100KB limit."),mode:"ids_only"};if(_u(o)<=EA)return o;throw new Ir("RESPONSE_TOO_LARGE: Unable to format bulk update response within 100KB limit",`Batch size: ${e.summary.total_requested} transactions`,["Reduce the batch size and retry","Consider splitting into multiple smaller batches"])}async function UA(e,t,r,a){let{deltaCache:n,knowledgeStore:i,params:o}=ki(t,r,a);return await mt(async()=>{let s=wv.safeParse(o);if(!s.success){let D=new Map,P=s.error.issues??[];for(let F of P){let j=F.path.find(C=>typeof C=="number"),J=F.message,ee=j!==void 0?j:null,se=D.get(ee)??[];se.push(J),D.set(ee,se)}let U=Array.from(D.entries()).map(([F,j])=>({transaction_index:F,errors:j}));throw new Ir("Bulk transaction update validation failed",JSON.stringify(U,null,2),["Ensure each transaction includes an id field","Limit batches to 100 items"])}let{budget_id:d,transactions:u,dry_run:l}=s.data;if(l){let D=u.slice(0,10),P=D.map(k=>k.id),{metadata:U,unresolvedIds:F,previewDetails:j}=await OA(e,d,u,{previewTransactionIds:P}),J=[],ee=[];for(let k of D){let O=j.get(k.id);if(!O){ee.push(k.id),J.push({transaction_id:k.id,before:"unavailable",after:k});continue}let te={},A={};k.amount!==void 0&&k.amount!==O.amount&&(te.amount=fe(O.amount),A.amount=fe(k.amount)),k.date!==void 0&&k.date!==O.date&&(te.date=O.date,A.date=k.date),k.memo!==void 0&&k.memo!==O.memo&&(te.memo=O.memo,A.memo=k.memo),k.payee_id!==void 0&&k.payee_id!==O.payee_id&&(te.payee_id=O.payee_id,A.payee_id=k.payee_id),k.payee_name!==void 0&&k.payee_name!==O.payee_name&&(te.payee_name=O.payee_name,A.payee_name=k.payee_name),k.category_id!==void 0&&k.category_id!==O.category_id&&(te.category_id=O.category_id,A.category_id=k.category_id),k.cleared!==void 0&&k.cleared!==O.cleared&&(te.cleared=O.cleared,A.cleared=k.cleared),k.approved!==void 0&&k.approved!==O.approved&&(te.approved=O.approved,A.approved=k.approved),k.flag_color!==void 0&&k.flag_color!==O.flag_color&&(te.flag_color=O.flag_color,A.flag_color=k.flag_color),J.push({transaction_id:k.id,before:te,after:A})}let se=[];if(ee.length>0||F.length>0){let k=Math.max(ee.length,F.length),O=F.length>0?F.slice(0,10):ee.slice(0,10);se.push({code:"metadata_unavailable",count:k,message:`Unable to fetch prior state for ${k} transactions`,sample_ids:O})}let C=Array.from(new Set(Array.from(U.values()).map(k=>k.account_id))),$=new Set;for(let k of u)k.amount!==void 0&&$.add("amount"),k.date!==void 0&&$.add("date"),k.memo!==void 0&&$.add("memo"),k.payee_id!==void 0&&$.add("payee_id"),k.payee_name!==void 0&&$.add("payee_name"),k.category_id!==void 0&&$.add("category_id"),k.cleared!==void 0&&$.add("cleared"),k.approved!==void 0&&$.add("approved"),k.flag_color!==void 0&&$.add("flag_color");let E={dry_run:!0,action:"update_transactions",validation:"passed",summary:{total_transactions:u.length,accounts_affected:C,fields_to_update:Array.from($)},transactions_preview:J,note:"Dry run complete. No transactions updated. No caches invalidated. No server_knowledge updated."};return se.length>0&&(E.warnings=se),{content:[{type:"text",text:he.format(E)}]}}let{metadata:p,unresolvedIds:_}=await OA(e,d,u),g=_.length/u.length,f=.05;if(g>f)throw new Ir(`METADATA_INCOMPLETE: ${(g*100).toFixed(1)}% of transactions have missing metadata (threshold: ${(f*100).toFixed(0)}%)`,JSON.stringify({unresolved_count:_.length,total_transactions:u.length,ratio:(g*100).toFixed(1)+"%",threshold:(f*100).toFixed(0)+"%",sample_unresolved_ids:_.slice(0,5)},null,2),["Provide original_account_id and original_date for all transactions being updated","Ensure transactions exist in YNAB before updating them"]);g>.01&&Di.logRequest("ynab:update_transactions","metadata_resolution_warning",{unresolved_count:_.length,total_transactions:u.length,ratio:g.toFixed(3),sample_ids:_.slice(0,5),message:"Metadata resolution incomplete for some transactions"},!0);let m=u.map(D=>{let P={};return D.amount!==void 0&&(P.amount=D.amount),D.date!==void 0&&(P.date=D.date),D.payee_name!==void 0&&(P.payee_name=D.payee_name),D.payee_id!==void 0&&(P.payee_id=D.payee_id),D.category_id!==void 0&&(P.category_id=D.category_id),D.memo!==void 0&&(P.memo=D.memo),D.cleared!==void 0&&(P.cleared=D.cleared),D.approved!==void 0&&(P.approved=D.approved),D.flag_color!==void 0&&(P.flag_color=D.flag_color),{id:D.id,transaction:P}}),y=(await e.transactions.updateTransactions(d,{transactions:m})).data,b=y.transactions??[],w=[],R=new Set(b.map(D=>D.id));for(let[D,P]of u.entries())R.has(P.id)?w.push({request_index:D,status:"updated",transaction_id:P.id,correlation_key:P.id}):w.push({request_index:D,status:"failed",transaction_id:P.id,correlation_key:P.id,error_code:"update_failed",error:"Transaction was not updated by YNAB API"});let N={total_requested:u.length,updated:b.length,failed:w.filter(D=>D.status==="failed").length},M={success:N.failed===0,server_knowledge:y.server_knowledge,summary:N,results:w,transactions:b,message:`Processed ${N.total_requested} transactions: ${N.updated} updated, ${N.failed} failed.`};for(let D of u)ke.delete(be.generateKey("transaction","get",d,D.id));let X=new Set,q=new Set,ne=new Set,oe=!1,V=!1,x=!1;for(let D of u){let P=p.get(D.id),U=D.amount!==void 0,F=D.cleared!==void 0,j=D.category_id!==void 0,J=D.date!==void 0;(U||F)&&P&&X.add(P.account_id),U&&(x=!0,V=!0,oe=!0,P&&q.add(Jo(P.date))),j&&(x=!0,oe=!0,D.category_id&&ne.add(D.category_id),P&&q.add(Jo(P.date))),J&&P&&(x=!0,q.add(Jo(P.date))),J&&D.date&&q.add(Jo(D.date))}rm(n,i,d,y.server_knowledge,X,q,{affectedCategoryIds:ne,invalidateAllCategories:oe,accountTotalsChanged:V,invalidateMonths:x});let S=Zue(M);return{content:[{type:"text",text:he.format(S)}]}},"ynab:update_transactions","bulk transaction update")}function m0(e,t){let r=t;return e instanceof Error&&(e.message.includes("401")||e.message.includes("Unauthorized")?r="Invalid or expired YNAB access token":e.message.includes("403")||e.message.includes("Forbidden")?r="Insufficient permissions to access YNAB data":e.message.includes("404")||e.message.includes("Not Found")?r="Budget, account, category, or transaction not found":e.message.includes("429")||e.message.includes("Too Many Requests")?r="Rate limit exceeded. Please try again later":(e.message.includes("500")||e.message.includes("Internal Server Error"))&&(r="YNAB service is currently unavailable")),{content:[{type:"text",text:he.format({error:{message:r}})}]}}var om=require("fs");var Hue=Math.pow(10,8)*24*60*60*1e3,p7e=-Hue,f0=6048e5,BA=864e5,VA=6e4,LA=36e5,WA=1e3;var Gue=3600;var YA=Gue*24,m7e=YA*7,Kue=YA*365.2425,Xue=Kue/12,f7e=Xue*3,Tv=Symbol.for("constructDateFrom");function dt(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Tv in e?e[Tv](t):e instanceof Date?new e.constructor(t):new Date(t)}function Be(e,t){return dt(t||e,e)}function h0(e,t,r){let a=Be(e,r?.in);return isNaN(t)?dt(r?.in||e,NaN):(t&&a.setDate(a.getDate()+t),a)}var Que={};function ai(){return Que}function Qr(e,t){let r=ai(),a=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=Be(e,t?.in),i=n.getDay(),o=(i<a?7:0)+i-a;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Ri(e,t){return Qr(e,{...t,weekStartsOn:1})}function g0(e,t){let r=Be(e,t?.in),a=r.getFullYear(),n=dt(r,0);n.setFullYear(a+1,0,4),n.setHours(0,0,0,0);let i=Ri(n),o=dt(r,0);o.setFullYear(a,0,4),o.setHours(0,0,0,0);let s=Ri(o);return r.getTime()>=i.getTime()?a+1:r.getTime()>=s.getTime()?a:a-1}function Bd(e){let t=Be(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function ZA(e,...t){let r=dt.bind(null,e||t.find(a=>typeof a=="object"));return t.map(r)}function $v(e,t){let r=Be(e,t?.in);return r.setHours(0,0,0,0),r}function HA(e,t,r){let[a,n]=ZA(r?.in,e,t),i=$v(a),o=$v(n),s=+i-Bd(i),d=+o-Bd(o);return Math.round((s-d)/BA)}function GA(e,t){let r=g0(e,t),a=dt(t?.in||e,0);return a.setFullYear(r,0,4),a.setHours(0,0,0,0),Ri(a)}function KA(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function XA(e){return!(!KA(e)&&typeof e!="number"||isNaN(+Be(e)))}function QA(e,t){let r=Be(e,t?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}var ele={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},eM=(e,t,r)=>{let a,n=ele[e];return typeof n=="string"?a=n:t===1?a=n.one:a=n.other.replace("{{count}}",t.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+a:a+" ago":a};function _0(e){return(t={})=>{let r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}var tle={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},rle={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},nle={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},tM={date:_0({formats:tle,defaultWidth:"full"}),time:_0({formats:rle,defaultWidth:"full"}),dateTime:_0({formats:nle,defaultWidth:"full"})};var ale={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},rM=(e,t,r,a)=>ale[e];function vu(e){return(t,r)=>{let a=r?.context?String(r.context):"standalone",n;if(a==="formatting"&&e.formattingValues){let o=e.defaultFormattingWidth||e.defaultWidth,s=r?.width?String(r.width):o;n=e.formattingValues[s]||e.formattingValues[o]}else{let o=e.defaultWidth,s=r?.width?String(r.width):e.defaultWidth;n=e.values[s]||e.values[o]}let i=e.argumentCallback?e.argumentCallback(t):t;return n[i]}}var ile={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ole={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},sle={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},dle={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},cle={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},ule={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},lle=(e,t)=>{let r=Number(e),a=r%100;if(a>20||a<10)switch(a%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},nM={ordinalNumber:lle,era:vu({values:ile,defaultWidth:"wide"}),quarter:vu({values:ole,defaultWidth:"wide",argumentCallback:e=>e-1}),month:vu({values:sle,defaultWidth:"wide"}),day:vu({values:dle,defaultWidth:"wide"}),dayPeriod:vu({values:cle,defaultWidth:"wide",formattingValues:ule,defaultFormattingWidth:"wide"})};function bu(e){return(t,r={})=>{let a=r.width,n=a&&e.matchPatterns[a]||e.matchPatterns[e.defaultMatchWidth],i=t.match(n);if(!i)return null;let o=i[0],s=a&&e.parsePatterns[a]||e.parsePatterns[e.defaultParseWidth],d=Array.isArray(s)?mle(s,p=>p.test(o)):ple(s,p=>p.test(o)),u;u=e.valueCallback?e.valueCallback(d):d,u=r.valueCallback?r.valueCallback(u):u;let l=t.slice(o.length);return{value:u,rest:l}}}function ple(e,t){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function mle(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function aM(e){return(t,r={})=>{let a=t.match(e.matchPattern);if(!a)return null;let n=a[0],i=t.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=r.valueCallback?r.valueCallback(o):o;let s=t.slice(n.length);return{value:o,rest:s}}}var fle=/^(\d+)(th|st|nd|rd)?/i,hle=/\d+/i,gle={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},_le={any:[/^b/i,/^(a|c)/i]},yle={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},vle={any:[/1/i,/2/i,/3/i,/4/i]},ble={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},wle={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Sle={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Tle={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},$le={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Ole={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},iM={ordinalNumber:aM({matchPattern:fle,parsePattern:hle,valueCallback:e=>parseInt(e,10)}),era:bu({matchPatterns:gle,defaultMatchWidth:"wide",parsePatterns:_le,defaultParseWidth:"any"}),quarter:bu({matchPatterns:yle,defaultMatchWidth:"wide",parsePatterns:vle,defaultParseWidth:"any",valueCallback:e=>e+1}),month:bu({matchPatterns:ble,defaultMatchWidth:"wide",parsePatterns:wle,defaultParseWidth:"any"}),day:bu({matchPatterns:Sle,defaultMatchWidth:"wide",parsePatterns:Tle,defaultParseWidth:"any"}),dayPeriod:bu({matchPatterns:$le,defaultMatchWidth:"any",parsePatterns:Ole,defaultParseWidth:"any"})};var nm={code:"en-US",formatDistance:eM,formatLong:tM,formatRelative:rM,localize:nM,match:iM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function oM(e,t){let r=Be(e,t?.in);return HA(r,QA(r))+1}function y0(e,t){let r=Be(e,t?.in),a=+Ri(r)-+GA(r);return Math.round(a/f0)+1}function wu(e,t){let r=Be(e,t?.in),a=r.getFullYear(),n=ai(),i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=dt(t?.in||e,0);o.setFullYear(a+1,0,i),o.setHours(0,0,0,0);let s=Qr(o,t),d=dt(t?.in||e,0);d.setFullYear(a,0,i),d.setHours(0,0,0,0);let u=Qr(d,t);return+r>=+s?a+1:+r>=+u?a:a-1}function sM(e,t){let r=ai(),a=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=wu(e,t),i=dt(t?.in||e,0);return i.setFullYear(n,0,a),i.setHours(0,0,0,0),Qr(i,t)}function v0(e,t){let r=Be(e,t?.in),a=+Qr(r,t)-+sM(r,t);return Math.round(a/f0)+1}function lt(e,t){let r=e<0?"-":"",a=Math.abs(e).toString().padStart(t,"0");return r+a}var jo={y(e,t){let r=e.getFullYear(),a=r>0?r:1-r;return lt(t==="yy"?a%100:a,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):lt(r+1,2)},d(e,t){return lt(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return lt(e.getHours()%12||12,t.length)},H(e,t){return lt(e.getHours(),t.length)},m(e,t){return lt(e.getMinutes(),t.length)},s(e,t){return lt(e.getSeconds(),t.length)},S(e,t){let r=t.length,a=e.getMilliseconds(),n=Math.trunc(a*Math.pow(10,r-3));return lt(n,t.length)}};var Su={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ov={G:function(e,t,r){let a=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return r.era(a,{width:"abbreviated"});case"GGGGG":return r.era(a,{width:"narrow"});case"GGGG":default:return r.era(a,{width:"wide"})}},y:function(e,t,r){if(t==="yo"){let a=e.getFullYear(),n=a>0?a:1-a;return r.ordinalNumber(n,{unit:"year"})}return jo.y(e,t)},Y:function(e,t,r,a){let n=wu(e,a),i=n>0?n:1-n;if(t==="YY"){let o=i%100;return lt(o,2)}return t==="Yo"?r.ordinalNumber(i,{unit:"year"}):lt(i,t.length)},R:function(e,t){let r=g0(e);return lt(r,t.length)},u:function(e,t){let r=e.getFullYear();return lt(r,t.length)},Q:function(e,t,r){let a=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(a);case"QQ":return lt(a,2);case"Qo":return r.ordinalNumber(a,{unit:"quarter"});case"QQQ":return r.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(a,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(a,{width:"wide",context:"formatting"})}},q:function(e,t,r){let a=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(a);case"qq":return lt(a,2);case"qo":return r.ordinalNumber(a,{unit:"quarter"});case"qqq":return r.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(a,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(a,{width:"wide",context:"standalone"})}},M:function(e,t,r){let a=e.getMonth();switch(t){case"M":case"MM":return jo.M(e,t);case"Mo":return r.ordinalNumber(a+1,{unit:"month"});case"MMM":return r.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(a,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(a,{width:"wide",context:"formatting"})}},L:function(e,t,r){let a=e.getMonth();switch(t){case"L":return String(a+1);case"LL":return lt(a+1,2);case"Lo":return r.ordinalNumber(a+1,{unit:"month"});case"LLL":return r.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(a,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(a,{width:"wide",context:"standalone"})}},w:function(e,t,r,a){let n=v0(e,a);return t==="wo"?r.ordinalNumber(n,{unit:"week"}):lt(n,t.length)},I:function(e,t,r){let a=y0(e);return t==="Io"?r.ordinalNumber(a,{unit:"week"}):lt(a,t.length)},d:function(e,t,r){return t==="do"?r.ordinalNumber(e.getDate(),{unit:"date"}):jo.d(e,t)},D:function(e,t,r){let a=oM(e);return t==="Do"?r.ordinalNumber(a,{unit:"dayOfYear"}):lt(a,t.length)},E:function(e,t,r){let a=e.getDay();switch(t){case"E":case"EE":case"EEE":return r.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(a,{width:"short",context:"formatting"});case"EEEE":default:return r.day(a,{width:"wide",context:"formatting"})}},e:function(e,t,r,a){let n=e.getDay(),i=(n-a.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return lt(i,2);case"eo":return r.ordinalNumber(i,{unit:"day"});case"eee":return r.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(n,{width:"short",context:"formatting"});case"eeee":default:return r.day(n,{width:"wide",context:"formatting"})}},c:function(e,t,r,a){let n=e.getDay(),i=(n-a.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return lt(i,t.length);case"co":return r.ordinalNumber(i,{unit:"day"});case"ccc":return r.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(n,{width:"narrow",context:"standalone"});case"cccccc":return r.day(n,{width:"short",context:"standalone"});case"cccc":default:return r.day(n,{width:"wide",context:"standalone"})}},i:function(e,t,r){let a=e.getDay(),n=a===0?7:a;switch(t){case"i":return String(n);case"ii":return lt(n,t.length);case"io":return r.ordinalNumber(n,{unit:"day"});case"iii":return r.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(a,{width:"short",context:"formatting"});case"iiii":default:return r.day(a,{width:"wide",context:"formatting"})}},a:function(e,t,r){let n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(e,t,r){let a=e.getHours(),n;switch(a===12?n=Su.noon:a===0?n=Su.midnight:n=a/12>=1?"pm":"am",t){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,t,r){let a=e.getHours(),n;switch(a>=17?n=Su.evening:a>=12?n=Su.afternoon:a>=4?n=Su.morning:n=Su.night,t){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,t,r){if(t==="ho"){let a=e.getHours()%12;return a===0&&(a=12),r.ordinalNumber(a,{unit:"hour"})}return jo.h(e,t)},H:function(e,t,r){return t==="Ho"?r.ordinalNumber(e.getHours(),{unit:"hour"}):jo.H(e,t)},K:function(e,t,r){let a=e.getHours()%12;return t==="Ko"?r.ordinalNumber(a,{unit:"hour"}):lt(a,t.length)},k:function(e,t,r){let a=e.getHours();return a===0&&(a=24),t==="ko"?r.ordinalNumber(a,{unit:"hour"}):lt(a,t.length)},m:function(e,t,r){return t==="mo"?r.ordinalNumber(e.getMinutes(),{unit:"minute"}):jo.m(e,t)},s:function(e,t,r){return t==="so"?r.ordinalNumber(e.getSeconds(),{unit:"second"}):jo.s(e,t)},S:function(e,t){return jo.S(e,t)},X:function(e,t,r){let a=e.getTimezoneOffset();if(a===0)return"Z";switch(t){case"X":return cM(a);case"XXXX":case"XX":return Vd(a);case"XXXXX":case"XXX":default:return Vd(a,":")}},x:function(e,t,r){let a=e.getTimezoneOffset();switch(t){case"x":return cM(a);case"xxxx":case"xx":return Vd(a);case"xxxxx":case"xxx":default:return Vd(a,":")}},O:function(e,t,r){let a=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+dM(a,":");case"OOOO":default:return"GMT"+Vd(a,":")}},z:function(e,t,r){let a=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+dM(a,":");case"zzzz":default:return"GMT"+Vd(a,":")}},t:function(e,t,r){let a=Math.trunc(+e/1e3);return lt(a,t.length)},T:function(e,t,r){return lt(+e,t.length)}};function dM(e,t=""){let r=e>0?"-":"+",a=Math.abs(e),n=Math.trunc(a/60),i=a%60;return i===0?r+String(n):r+String(n)+t+lt(i,2)}function cM(e,t){return e%60===0?(e>0?"-":"+")+lt(Math.abs(e)/60,2):Vd(e,t)}function Vd(e,t=""){let r=e>0?"-":"+",a=Math.abs(e),n=lt(Math.trunc(a/60),2),i=lt(a%60,2);return r+n+t+i}var uM=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},lM=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},Nle=(e,t)=>{let r=e.match(/(P+)(p+)?/)||[],a=r[1],n=r[2];if(!n)return uM(e,t);let i;switch(a){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;case"PPPP":default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",uM(a,t)).replace("{{time}}",lM(n,t))},am={p:lM,P:Nle};var xle=/^D+$/,Dle=/^Y+$/,kle=["D","DD","YY","YYYY"];function b0(e){return xle.test(e)}function w0(e){return Dle.test(e)}function im(e,t,r){let a=Rle(e,t,r);if(console.warn(a),kle.includes(e))throw new RangeError(a)}function Rle(e,t,r){let a=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${a} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var Ile=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Ele=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Ple=/^'([^]*?)'?$/,Cle=/''/g,Ale=/[a-zA-Z]/;function pM(e,t,r){let a=ai(),n=r?.locale??a.locale??nm,i=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,o=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,s=Be(e,r?.in);if(!XA(s))throw new RangeError("Invalid time value");let d=t.match(Ele).map(l=>{let p=l[0];if(p==="p"||p==="P"){let _=am[p];return _(l,n.formatLong)}return l}).join("").match(Ile).map(l=>{if(l==="''")return{isToken:!1,value:"'"};let p=l[0];if(p==="'")return{isToken:!1,value:Mle(l)};if(Ov[p])return{isToken:!0,value:l};if(p.match(Ale))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");return{isToken:!1,value:l}});n.localize.preprocessor&&(d=n.localize.preprocessor(s,d));let u={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return d.map(l=>{if(!l.isToken)return l.value;let p=l.value;(!r?.useAdditionalWeekYearTokens&&w0(p)||!r?.useAdditionalDayOfYearTokens&&b0(p))&&im(p,t,String(e));let _=Ov[p[0]];return _(s,p,n.localize,u)}).join("")}function Mle(e){let t=e.match(Ple);return t?t[1].replace(Cle,"'"):e}function mM(){return Object.assign({},ai())}function fM(e,t){let r=Be(e,t?.in).getDay();return r===0?7:r}function hM(e,t){let r=Fle(t)?new t(0):dt(t,0);return r.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),r.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),r}function Fle(e){return typeof e=="function"&&e.prototype?.constructor===e}var zle=10,S0=class{subPriority=0;validate(t,r){return!0}},T0=class extends S0{constructor(t,r,a,n,i){super(),this.value=t,this.validateValue=r,this.setValue=a,this.priority=n,i&&(this.subPriority=i)}validate(t,r){return this.validateValue(t,this.value,r)}set(t,r,a){return this.setValue(t,r,this.value,a)}},$0=class extends S0{priority=zle;subPriority=-1;constructor(t,r){super(),this.context=t||(a=>dt(r,a))}set(t,r){return r.timestampIsSet?t:dt(t,hM(t,this.context))}};var ue=class{run(t,r,a,n){let i=this.parse(t,r,a,n);return i?{setter:new T0(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,r,a){return!0}};var O0=class extends ue{priority=140;parse(t,r,a){switch(r){case"G":case"GG":case"GGG":return a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"});case"GGGGG":return a.era(t,{width:"narrow"});case"GGGG":default:return a.era(t,{width:"wide"})||a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"})}}set(t,r,a){return r.era=a,t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}incompatibleTokens=["R","u","t","T"]};var et={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},ii={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function ht(e,t){return e&&{value:t(e.value),rest:e.rest}}function Ke(e,t){let r=t.match(e);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function oi(e,t){let r=t.match(e);if(!r)return null;if(r[0]==="Z")return{value:0,rest:t.slice(1)};let a=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,i=r[3]?parseInt(r[3],10):0,o=r[5]?parseInt(r[5],10):0;return{value:a*(n*LA+i*VA+o*WA),rest:t.slice(r[0].length)}}function N0(e){return Ke(et.anyDigitsSigned,e)}function Re(e,t){switch(e){case 1:return Ke(et.singleDigit,t);case 2:return Ke(et.twoDigits,t);case 3:return Ke(et.threeDigits,t);case 4:return Ke(et.fourDigits,t);default:return Ke(new RegExp("^\\d{1,"+e+"}"),t)}}function Tu(e,t){switch(e){case 1:return Ke(et.singleDigitSigned,t);case 2:return Ke(et.twoDigitsSigned,t);case 3:return Ke(et.threeDigitsSigned,t);case 4:return Ke(et.fourDigitsSigned,t);default:return Ke(new RegExp("^-?\\d{1,"+e+"}"),t)}}function $u(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function x0(e,t){let r=t>0,a=r?t:1-t,n;if(a<=50)n=e||100;else{let i=a+50,o=Math.trunc(i/100)*100,s=e>=i%100;n=e+o-(s?100:0)}return r?n:1-n}function D0(e){return e%400===0||e%4===0&&e%100!==0}var k0=class extends ue{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(t,r,a){let n=i=>({year:i,isTwoDigitYear:r==="yy"});switch(r){case"y":return ht(Re(4,t),n);case"yo":return ht(a.ordinalNumber(t,{unit:"year"}),n);default:return ht(Re(r.length,t),n)}}validate(t,r){return r.isTwoDigitYear||r.year>0}set(t,r,a){let n=t.getFullYear();if(a.isTwoDigitYear){let o=x0(a.year,n);return t.setFullYear(o,0,1),t.setHours(0,0,0,0),t}let i=!("era"in r)||r.era===1?a.year:1-a.year;return t.setFullYear(i,0,1),t.setHours(0,0,0,0),t}};var R0=class extends ue{priority=130;parse(t,r,a){let n=i=>({year:i,isTwoDigitYear:r==="YY"});switch(r){case"Y":return ht(Re(4,t),n);case"Yo":return ht(a.ordinalNumber(t,{unit:"year"}),n);default:return ht(Re(r.length,t),n)}}validate(t,r){return r.isTwoDigitYear||r.year>0}set(t,r,a,n){let i=wu(t,n);if(a.isTwoDigitYear){let s=x0(a.year,i);return t.setFullYear(s,0,n.firstWeekContainsDate),t.setHours(0,0,0,0),Qr(t,n)}let o=!("era"in r)||r.era===1?a.year:1-a.year;return t.setFullYear(o,0,n.firstWeekContainsDate),t.setHours(0,0,0,0),Qr(t,n)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};var I0=class extends ue{priority=130;parse(t,r){return r==="R"?Tu(4,t):Tu(r.length,t)}set(t,r,a){let n=dt(t,0);return n.setFullYear(a,0,4),n.setHours(0,0,0,0),Ri(n)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};var E0=class extends ue{priority=130;parse(t,r){return r==="u"?Tu(4,t):Tu(r.length,t)}set(t,r,a){return t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};var P0=class extends ue{priority=120;parse(t,r,a){switch(r){case"Q":case"QQ":return Re(r.length,t);case"Qo":return a.ordinalNumber(t,{unit:"quarter"});case"QQQ":return a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(t,{width:"wide",context:"formatting"})||a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=1&&r<=4}set(t,r,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};var C0=class extends ue{priority=120;parse(t,r,a){switch(r){case"q":case"qq":return Re(r.length,t);case"qo":return a.ordinalNumber(t,{unit:"quarter"});case"qqq":return a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(t,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(t,{width:"wide",context:"standalone"})||a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"})}}validate(t,r){return r>=1&&r<=4}set(t,r,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};var A0=class extends ue{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(t,r,a){let n=i=>i-1;switch(r){case"M":return ht(Ke(et.month,t),n);case"MM":return ht(Re(2,t),n);case"Mo":return ht(a.ordinalNumber(t,{unit:"month"}),n);case"MMM":return a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(t,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(t,{width:"wide",context:"formatting"})||a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=0&&r<=11}set(t,r,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}};var M0=class extends ue{priority=110;parse(t,r,a){let n=i=>i-1;switch(r){case"L":return ht(Ke(et.month,t),n);case"LL":return ht(Re(2,t),n);case"Lo":return ht(a.ordinalNumber(t,{unit:"month"}),n);case"LLL":return a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(t,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(t,{width:"wide",context:"standalone"})||a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"})}}validate(t,r){return r>=0&&r<=11}set(t,r,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};function gM(e,t,r){let a=Be(e,r?.in),n=v0(a,r)-t;return a.setDate(a.getDate()-n*7),Be(a,r?.in)}var F0=class extends ue{priority=100;parse(t,r,a){switch(r){case"w":return Ke(et.week,t);case"wo":return a.ordinalNumber(t,{unit:"week"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=53}set(t,r,a,n){return Qr(gM(t,a,n),n)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};function _M(e,t,r){let a=Be(e,r?.in),n=y0(a,r)-t;return a.setDate(a.getDate()-n*7),a}var z0=class extends ue{priority=100;parse(t,r,a){switch(r){case"I":return Ke(et.week,t);case"Io":return a.ordinalNumber(t,{unit:"week"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=53}set(t,r,a){return Ri(_M(t,a))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};var Jle=[31,28,31,30,31,30,31,31,30,31,30,31],jle=[31,29,31,30,31,30,31,31,30,31,30,31],J0=class extends ue{priority=90;subPriority=1;parse(t,r,a){switch(r){case"d":return Ke(et.date,t);case"do":return a.ordinalNumber(t,{unit:"date"});default:return Re(r.length,t)}}validate(t,r){let a=t.getFullYear(),n=D0(a),i=t.getMonth();return n?r>=1&&r<=jle[i]:r>=1&&r<=Jle[i]}set(t,r,a){return t.setDate(a),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};var j0=class extends ue{priority=90;subpriority=1;parse(t,r,a){switch(r){case"D":case"DD":return Ke(et.dayOfYear,t);case"Do":return a.ordinalNumber(t,{unit:"date"});default:return Re(r.length,t)}}validate(t,r){let a=t.getFullYear();return D0(a)?r>=1&&r<=366:r>=1&&r<=365}set(t,r,a){return t.setMonth(0,a),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};function Ou(e,t,r){let a=ai(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,i=Be(e,r?.in),o=i.getDay(),d=(t%7+7)%7,u=7-n,l=t<0||t>6?t-(o+u)%7:(d+u)%7-(o+u)%7;return h0(i,l,r)}var q0=class extends ue{priority=90;parse(t,r,a){switch(r){case"E":case"EE":case"EEE":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=0&&r<=6}set(t,r,a,n){return t=Ou(t,a,n),t.setHours(0,0,0,0),t}incompatibleTokens=["D","i","e","c","t","T"]};var U0=class extends ue{priority=90;parse(t,r,a,n){let i=o=>{let s=Math.floor((o-1)/7)*7;return(o+n.weekStartsOn+6)%7+s};switch(r){case"e":case"ee":return ht(Re(r.length,t),i);case"eo":return ht(a.ordinalNumber(t,{unit:"day"}),i);case"eee":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeeee":return a.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,r){return r>=0&&r<=6}set(t,r,a,n){return t=Ou(t,a,n),t.setHours(0,0,0,0),t}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};var B0=class extends ue{priority=90;parse(t,r,a,n){let i=o=>{let s=Math.floor((o-1)/7)*7;return(o+n.weekStartsOn+6)%7+s};switch(r){case"c":case"cc":return ht(Re(r.length,t),i);case"co":return ht(a.ordinalNumber(t,{unit:"day"}),i);case"ccc":return a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"ccccc":return a.day(t,{width:"narrow",context:"standalone"});case"cccccc":return a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(t,{width:"wide",context:"standalone"})||a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"})}}validate(t,r){return r>=0&&r<=6}set(t,r,a,n){return t=Ou(t,a,n),t.setHours(0,0,0,0),t}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};function yM(e,t,r){let a=Be(e,r?.in),n=fM(a,r),i=t-n;return h0(a,i,r)}var V0=class extends ue{priority=90;parse(t,r,a){let n=i=>i===0?7:i;switch(r){case"i":case"ii":return Re(r.length,t);case"io":return a.ordinalNumber(t,{unit:"day"});case"iii":return ht(a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),n);case"iiiii":return ht(a.day(t,{width:"narrow",context:"formatting"}),n);case"iiiiii":return ht(a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),n);case"iiii":default:return ht(a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),n)}}validate(t,r){return r>=1&&r<=7}set(t,r,a){return t=yM(t,a),t.setHours(0,0,0,0),t}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};var L0=class extends ue{priority=80;parse(t,r,a){switch(r){case"a":case"aa":case"aaa":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,r,a){return t.setHours($u(a),0,0,0),t}incompatibleTokens=["b","B","H","k","t","T"]};var W0=class extends ue{priority=80;parse(t,r,a){switch(r){case"b":case"bb":case"bbb":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,r,a){return t.setHours($u(a),0,0,0),t}incompatibleTokens=["a","B","H","k","t","T"]};var Y0=class extends ue{priority=80;parse(t,r,a){switch(r){case"B":case"BB":case"BBB":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,r,a){return t.setHours($u(a),0,0,0),t}incompatibleTokens=["a","b","t","T"]};var Z0=class extends ue{priority=70;parse(t,r,a){switch(r){case"h":return Ke(et.hour12h,t);case"ho":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=12}set(t,r,a){let n=t.getHours()>=12;return n&&a<12?t.setHours(a+12,0,0,0):!n&&a===12?t.setHours(0,0,0,0):t.setHours(a,0,0,0),t}incompatibleTokens=["H","K","k","t","T"]};var H0=class extends ue{priority=70;parse(t,r,a){switch(r){case"H":return Ke(et.hour23h,t);case"Ho":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=23}set(t,r,a){return t.setHours(a,0,0,0),t}incompatibleTokens=["a","b","h","K","k","t","T"]};var G0=class extends ue{priority=70;parse(t,r,a){switch(r){case"K":return Ke(et.hour11h,t);case"Ko":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=11}set(t,r,a){return t.getHours()>=12&&a<12?t.setHours(a+12,0,0,0):t.setHours(a,0,0,0),t}incompatibleTokens=["h","H","k","t","T"]};var K0=class extends ue{priority=70;parse(t,r,a){switch(r){case"k":return Ke(et.hour24h,t);case"ko":return a.ordinalNumber(t,{unit:"hour"});default:return Re(r.length,t)}}validate(t,r){return r>=1&&r<=24}set(t,r,a){let n=a<=24?a%24:a;return t.setHours(n,0,0,0),t}incompatibleTokens=["a","b","h","H","K","t","T"]};var X0=class extends ue{priority=60;parse(t,r,a){switch(r){case"m":return Ke(et.minute,t);case"mo":return a.ordinalNumber(t,{unit:"minute"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=59}set(t,r,a){return t.setMinutes(a,0,0),t}incompatibleTokens=["t","T"]};var Q0=class extends ue{priority=50;parse(t,r,a){switch(r){case"s":return Ke(et.second,t);case"so":return a.ordinalNumber(t,{unit:"second"});default:return Re(r.length,t)}}validate(t,r){return r>=0&&r<=59}set(t,r,a){return t.setSeconds(a,0),t}incompatibleTokens=["t","T"]};var e2=class extends ue{priority=30;parse(t,r){let a=n=>Math.trunc(n*Math.pow(10,-r.length+3));return ht(Re(r.length,t),a)}set(t,r,a){return t.setMilliseconds(a),t}incompatibleTokens=["t","T"]};var t2=class extends ue{priority=10;parse(t,r){switch(r){case"X":return oi(ii.basicOptionalMinutes,t);case"XX":return oi(ii.basic,t);case"XXXX":return oi(ii.basicOptionalSeconds,t);case"XXXXX":return oi(ii.extendedOptionalSeconds,t);case"XXX":default:return oi(ii.extended,t)}}set(t,r,a){return r.timestampIsSet?t:dt(t,t.getTime()-Bd(t)-a)}incompatibleTokens=["t","T","x"]};var r2=class extends ue{priority=10;parse(t,r){switch(r){case"x":return oi(ii.basicOptionalMinutes,t);case"xx":return oi(ii.basic,t);case"xxxx":return oi(ii.basicOptionalSeconds,t);case"xxxxx":return oi(ii.extendedOptionalSeconds,t);case"xxx":default:return oi(ii.extended,t)}}set(t,r,a){return r.timestampIsSet?t:dt(t,t.getTime()-Bd(t)-a)}incompatibleTokens=["t","T","X"]};var n2=class extends ue{priority=40;parse(t){return N0(t)}set(t,r,a){return[dt(t,a*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};var a2=class extends ue{priority=20;parse(t){return N0(t)}set(t,r,a){return[dt(t,a),{timestampIsSet:!0}]}incompatibleTokens="*"};var vM={G:new O0,y:new k0,Y:new R0,R:new I0,u:new E0,Q:new P0,q:new C0,M:new A0,L:new M0,w:new F0,I:new z0,d:new J0,D:new j0,E:new q0,e:new U0,c:new B0,i:new V0,a:new L0,b:new W0,B:new Y0,h:new Z0,H:new H0,K:new G0,k:new K0,m:new X0,s:new Q0,S:new e2,X:new t2,x:new r2,t:new n2,T:new a2};var qle=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Ule=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Ble=/^'([^]*?)'?$/,Vle=/''/g,Lle=/\S/,Wle=/[a-zA-Z]/;function bM(e,t,r,a){let n=()=>dt(a?.in||r,NaN),i=mM(),o=a?.locale??i.locale??nm,s=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,d=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??i.weekStartsOn??i.locale?.options?.weekStartsOn??0;if(!t)return e?n():Be(r,a?.in);let u={firstWeekContainsDate:s,weekStartsOn:d,locale:o},l=[new $0(a?.in,r)],p=t.match(Ule).map(h=>{let y=h[0];if(y in am){let b=am[y];return b(h,o.formatLong)}return h}).join("").match(qle),_=[];for(let h of p){!a?.useAdditionalWeekYearTokens&&w0(h)&&im(h,t,e),!a?.useAdditionalDayOfYearTokens&&b0(h)&&im(h,t,e);let y=h[0],b=vM[y];if(b){let{incompatibleTokens:w}=b;if(Array.isArray(w)){let N=_.find(M=>w.includes(M.token)||M.token===y);if(N)throw new RangeError(`The format string mustn't contain \`${N.fullToken}\` and \`${h}\` at the same time`)}else if(b.incompatibleTokens==="*"&&_.length>0)throw new RangeError(`The format string mustn't contain \`${h}\` and any other token at the same time`);_.push({token:y,fullToken:h});let R=b.run(e,h,o.match,u);if(!R)return n();l.push(R.setter),e=R.rest}else{if(y.match(Wle))throw new RangeError("Format string contains an unescaped latin alphabet character `"+y+"`");if(h==="''"?h="'":y==="'"&&(h=Yle(h)),e.indexOf(h)===0)e=e.slice(h.length);else return n()}}if(e.length>0&&Lle.test(e))return n();let g=l.map(h=>h.priority).sort((h,y)=>y-h).filter((h,y,b)=>b.indexOf(h)===y).map(h=>l.filter(y=>y.priority===h).sort((y,b)=>b.subPriority-y.subPriority)).map(h=>h[0]),f=Be(r,a?.in);if(isNaN(+f))return n();let m={};for(let h of g){if(!h.validate(f,u))return n();let y=h.set(f,m,u);Array.isArray(y)?(f=y[0],Object.assign(m,y[1])):f=y}return f}function Yle(e){return e.match(Ble)[1].replace(Vle,"'")}var qo=require("path"),Nv=require("os"),SM=c.object({budget_id:c.string().min(1,"Budget ID is required"),account_id:c.string().optional(),category_id:c.string().optional(),since_date:c.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Date must be in ISO format (YYYY-MM-DD)").optional(),type:c.enum(["uncategorized","unapproved"]).optional(),filename:c.string().optional(),minimal:c.boolean().optional().default(!0)}).strict();function Zle(e,t){if(e.filename)return e.filename.endsWith(".json")?e.filename:`${e.filename}.json`;let r=pM(new Date,"yyyy-MM-dd_HH-mm-ss"),a="transactions",n=[];return e.since_date&&n.push(`since_${e.since_date}`),e.account_id&&n.push(`account_${e.account_id.substring(0,8)}`),e.category_id&&n.push(`category_${e.category_id.substring(0,8)}`),e.type&&n.push(e.type),e.minimal!==!1&&n.push("minimal"),n.length>0&&(a=n.join("_")),`ynab_${a}_${t}items_${r}.json`}function wM(){let e=process.platform,t=(0,Nv.homedir)();switch(e){case"win32":return(0,qo.join)(t,"Downloads");case"darwin":return(0,qo.join)(t,"Downloads");case"linux":case"freebsd":case"openbsd":case"sunos":case"aix":return process.env.XDG_DOCUMENTS_DIR||(0,qo.join)(t,"Documents");default:return(0,qo.join)(t,"Downloads")}}function Hle(){let e=process.env.YNAB_EXPORT_PATH?.trim(),t;e?e.startsWith("~/")?t=(0,qo.join)((0,Nv.homedir)(),e.slice(2)):t=(0,qo.resolve)(e):t=wM();try{(0,om.mkdirSync)(t,{recursive:!0})}catch(r){console.warn(`Failed to create export directory ${t}, using platform default:`,r);let a=wM();try{return(0,om.mkdirSync)(a,{recursive:!0}),a}catch(n){return console.warn("Failed to create default folder, using current directory:",n),process.cwd()}}return t}async function TM(e,t){return await mt(async()=>{let r;t.account_id?r=await e.transactions.getTransactionsByAccount(t.budget_id,t.account_id,t.since_date):t.category_id?r=await e.transactions.getTransactionsByCategory(t.budget_id,t.category_id,t.since_date):r=await e.transactions.getTransactions(t.budget_id,t.since_date,t.type);let a=r.data.transactions,n=Hle(),i=Zle(t,a.length),o=(0,qo.join)(n,i),s={export_info:{exported_at:new Date().toISOString(),total_transactions:a.length,minimal:t.minimal!==!1,filters:{budget_id:t.budget_id,account_id:t.account_id||null,category_id:t.category_id||null,since_date:t.since_date||null,type:t.type||null}},transactions:a.map(l=>t.minimal!==!1?{id:l.id,date:l.date,amount:l.amount,payee_name:l.payee_name,cleared:l.cleared}:{id:l.id,date:l.date,amount:l.amount,memo:l.memo,cleared:l.cleared,approved:l.approved,flag_color:l.flag_color,account_id:l.account_id,payee_id:l.payee_id,category_id:l.category_id,transfer_account_id:l.transfer_account_id,transfer_transaction_id:l.transfer_transaction_id,matched_transaction_id:l.matched_transaction_id,import_id:l.import_id,deleted:l.deleted,account_name:l.account_name,payee_name:l.payee_name,category_name:l.category_name})};(0,om.writeFileSync)(o,JSON.stringify(s,null,2),"utf-8");let d=Math.min(10,a.length),u=a.slice(0,d);return{content:[{type:"text",text:he.format({message:`Successfully exported ${a.length} transactions${t.minimal!==!1?" (minimal fields)":" (full fields)"}`,filename:i,full_path:o,export_directory:n,export_mode:t.minimal!==!1?"minimal":"full",minimal_fields:t.minimal!==!1?"id, date, amount, payee_name, cleared":null,filename_explanation:"Filename format: ynab_{filters}_{count}items_{timestamp}.json - identifies what data was exported, when, and how many transactions",preview_count:d,total_count:a.length,preview_transactions:u.map(l=>({id:l.id,date:l.date,amount:l.amount,memo:l.memo,payee_name:l.payee_name,category_name:l.category_name}))})}]}},"ynab:export_transactions","exporting transactions")}var tt=class e extends Error{constructor(t,r,a,...n){Array.isArray(r)&&(r=r.join(" ").trim()),super(r),Error.captureStackTrace!==void 0&&Error.captureStackTrace(this,e),this.code=t;for(let i of n)for(let o in i){let s=i[o];this[o]=Buffer.isBuffer(s)?s.toString(a.encoding):s==null?s:JSON.parse(JSON.stringify(s))}}};var $M=function(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)};var i2=function(e){let t=[];for(let r=0,a=e.length;r<a;r++){let n=e[r];if(n==null||n===!1)t[r]={disabled:!0};else if(typeof n=="string")t[r]={name:n};else if($M(n)){if(typeof n.name!="string")throw new tt("CSV_OPTION_COLUMNS_MISSING_NAME",["Option columns missing name:",`property "name" is required at position ${r}`,"when column is an object literal"]);t[r]=n}else throw new tt("CSV_INVALID_COLUMN_DEFINITION",["Invalid column definition:","expect a string or a literal object,",`got ${JSON.stringify(n)} at position ${r}`])}return t};var xv=class{constructor(t=100){this.size=t,this.length=0,this.buf=Buffer.allocUnsafe(t)}prepend(t){if(Buffer.isBuffer(t)){let r=this.length+t.length;if(r>=this.size&&(this.resize(),r>=this.size))throw Error("INVALID_BUFFER_STATE");let a=this.buf;this.buf=Buffer.allocUnsafe(this.size),t.copy(this.buf,0),a.copy(this.buf,t.length),this.length+=t.length}else{let r=this.length++;r===this.size&&this.resize();let a=this.clone();this.buf[0]=t,a.copy(this.buf,1,0,r)}}append(t){let r=this.length++;r===this.size&&this.resize(),this.buf[r]=t}clone(){return Buffer.from(this.buf.slice(0,this.length))}resize(){let t=this.length;this.size=this.size*2;let r=Buffer.allocUnsafe(this.size);this.buf.copy(r,0,0,t),this.buf=r}toString(t){return t?this.buf.slice(0,this.length).toString(t):Uint8Array.prototype.slice.call(this.buf.slice(0,this.length))}toJSON(){return this.toString("utf8")}reset(){this.length=0}},Dv=xv;var Gle=12,Kle=13,Xle=10,Qle=32,epe=9,OM=function(e){return{bomSkipped:!1,bufBytesStart:0,castField:e.cast_function,commenting:!1,error:void 0,enabled:e.from_line===1,escaping:!1,escapeIsQuote:Buffer.isBuffer(e.escape)&&Buffer.isBuffer(e.quote)&&Buffer.compare(e.escape,e.quote)===0,expectedRecordLength:Array.isArray(e.columns)?e.columns.length:void 0,field:new Dv(20),firstLineToHeaders:e.cast_first_line_to_header,needMoreDataSize:Math.max(e.comment!==null?e.comment.length:0,...e.delimiter.map(t=>t.length),e.quote!==null?e.quote.length:0),previousBuf:void 0,quoting:!1,stop:!1,rawBuffer:new Dv(100),record:[],recordHasError:!1,record_length:0,recordDelimiterMaxLength:e.record_delimiter.length===0?0:Math.max(...e.record_delimiter.map(t=>t.length)),trimChars:[Buffer.from(" ",e.encoding)[0],Buffer.from(" ",e.encoding)[0]],wasQuoting:!1,wasRowDelimiter:!1,timchars:[Buffer.from(Buffer.from([Kle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([Xle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([Gle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([Qle],"utf8").toString(),e.encoding),Buffer.from(Buffer.from([epe],"utf8").toString(),e.encoding)]}};var NM=function(e){return e.replace(/([A-Z])/g,function(t,r){return"_"+r.toLowerCase()})};var kv=function(e){let t={};for(let a in e)t[NM(a)]=e[a];if(t.encoding===void 0||t.encoding===!0)t.encoding="utf8";else if(t.encoding===null||t.encoding===!1)t.encoding=null;else if(typeof t.encoding!="string"&&t.encoding!==null)throw new tt("CSV_INVALID_OPTION_ENCODING",["Invalid option encoding:","encoding must be a string or null to return a buffer,",`got ${JSON.stringify(t.encoding)}`],t);if(t.bom===void 0||t.bom===null||t.bom===!1)t.bom=!1;else if(t.bom!==!0)throw new tt("CSV_INVALID_OPTION_BOM",["Invalid option bom:","bom must be true,",`got ${JSON.stringify(t.bom)}`],t);if(t.cast_function=null,t.cast===void 0||t.cast===null||t.cast===!1||t.cast==="")t.cast=void 0;else if(typeof t.cast=="function")t.cast_function=t.cast,t.cast=!0;else if(t.cast!==!0)throw new tt("CSV_INVALID_OPTION_CAST",["Invalid option cast:","cast must be true or a function,",`got ${JSON.stringify(t.cast)}`],t);if(t.cast_date===void 0||t.cast_date===null||t.cast_date===!1||t.cast_date==="")t.cast_date=!1;else if(t.cast_date===!0)t.cast_date=function(a){let n=Date.parse(a);return isNaN(n)?a:new Date(n)};else if(typeof t.cast_date!="function")throw new tt("CSV_INVALID_OPTION_CAST_DATE",["Invalid option cast_date:","cast_date must be true or a function,",`got ${JSON.stringify(t.cast_date)}`],t);if(t.cast_first_line_to_header=void 0,t.columns===!0)t.cast_first_line_to_header=void 0;else if(typeof t.columns=="function")t.cast_first_line_to_header=t.columns,t.columns=!0;else if(Array.isArray(t.columns))t.columns=i2(t.columns);else if(t.columns===void 0||t.columns===null||t.columns===!1)t.columns=!1;else throw new tt("CSV_INVALID_OPTION_COLUMNS",["Invalid option columns:","expect an array, a function or true,",`got ${JSON.stringify(t.columns)}`],t);if(t.group_columns_by_name===void 0||t.group_columns_by_name===null||t.group_columns_by_name===!1)t.group_columns_by_name=!1;else{if(t.group_columns_by_name!==!0)throw new tt("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","expect an boolean,",`got ${JSON.stringify(t.group_columns_by_name)}`],t);if(t.columns===!1)throw new tt("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","the `columns` mode must be activated."],t)}if(t.comment===void 0||t.comment===null||t.comment===!1||t.comment==="")t.comment=null;else if(typeof t.comment=="string"&&(t.comment=Buffer.from(t.comment,t.encoding)),!Buffer.isBuffer(t.comment))throw new tt("CSV_INVALID_OPTION_COMMENT",["Invalid option comment:","comment must be a buffer or a string,",`got ${JSON.stringify(t.comment)}`],t);if(t.comment_no_infix===void 0||t.comment_no_infix===null||t.comment_no_infix===!1)t.comment_no_infix=!1;else if(t.comment_no_infix!==!0)throw new tt("CSV_INVALID_OPTION_COMMENT",["Invalid option comment_no_infix:","value must be a boolean,",`got ${JSON.stringify(t.comment_no_infix)}`],t);let r=JSON.stringify(t.delimiter);if(Array.isArray(t.delimiter)||(t.delimiter=[t.delimiter]),t.delimiter.length===0)throw new tt("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);if(t.delimiter=t.delimiter.map(function(a){if(a==null||a===!1)return Buffer.from(",",t.encoding);if(typeof a=="string"&&(a=Buffer.from(a,t.encoding)),!Buffer.isBuffer(a)||a.length===0)throw new tt("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);return a}),t.escape===void 0||t.escape===!0?t.escape=Buffer.from('"',t.encoding):typeof t.escape=="string"?t.escape=Buffer.from(t.escape,t.encoding):(t.escape===null||t.escape===!1)&&(t.escape=null),t.escape!==null&&!Buffer.isBuffer(t.escape))throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(t.escape)}`);if(t.from===void 0||t.from===null)t.from=1;else if(typeof t.from=="string"&&/\d+/.test(t.from)&&(t.from=parseInt(t.from)),Number.isInteger(t.from)){if(t.from<0)throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(e.from)}`)}else throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(t.from)}`);if(t.from_line===void 0||t.from_line===null)t.from_line=1;else if(typeof t.from_line=="string"&&/\d+/.test(t.from_line)&&(t.from_line=parseInt(t.from_line)),Number.isInteger(t.from_line)){if(t.from_line<=0)throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(e.from_line)}`)}else throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(e.from_line)}`);if(t.ignore_last_delimiters===void 0||t.ignore_last_delimiters===null)t.ignore_last_delimiters=!1;else if(typeof t.ignore_last_delimiters=="number")t.ignore_last_delimiters=Math.floor(t.ignore_last_delimiters),t.ignore_last_delimiters===0&&(t.ignore_last_delimiters=!1);else if(typeof t.ignore_last_delimiters!="boolean")throw new tt("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS",["Invalid option `ignore_last_delimiters`:","the value must be a boolean value or an integer,",`got ${JSON.stringify(t.ignore_last_delimiters)}`],t);if(t.ignore_last_delimiters===!0&&t.columns===!1)throw new tt("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS",["The option `ignore_last_delimiters`","requires the activation of the `columns` option"],t);if(t.info===void 0||t.info===null||t.info===!1)t.info=!1;else if(t.info!==!0)throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(t.info)}`);if(t.max_record_size===void 0||t.max_record_size===null||t.max_record_size===!1)t.max_record_size=0;else if(!(Number.isInteger(t.max_record_size)&&t.max_record_size>=0))if(typeof t.max_record_size=="string"&&/\d+/.test(t.max_record_size))t.max_record_size=parseInt(t.max_record_size);else throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(t.max_record_size)}`);if(t.objname===void 0||t.objname===null||t.objname===!1)t.objname=void 0;else if(Buffer.isBuffer(t.objname)){if(t.objname.length===0)throw new Error("Invalid Option: objname must be a non empty buffer");t.encoding===null||(t.objname=t.objname.toString(t.encoding))}else if(typeof t.objname=="string"){if(t.objname.length===0)throw new Error("Invalid Option: objname must be a non empty string")}else if(typeof t.objname!="number")throw new Error(`Invalid Option: objname must be a string or a buffer, got ${t.objname}`);if(t.objname!==void 0){if(typeof t.objname=="number"){if(t.columns!==!1)throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field")}else if(t.columns===!1)throw Error("Invalid Option: objname field must be combined with columns or be defined as an index")}if(t.on_record===void 0||t.on_record===null)t.on_record=void 0;else if(typeof t.on_record!="function")throw new tt("CSV_INVALID_OPTION_ON_RECORD",["Invalid option `on_record`:","expect a function,",`got ${JSON.stringify(t.on_record)}`],t);if(t.on_skip!==void 0&&t.on_skip!==null&&typeof t.on_skip!="function")throw new Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify(t.on_skip)}`);if(t.quote===null||t.quote===!1||t.quote==="")t.quote=null;else if(t.quote===void 0||t.quote===!0?t.quote=Buffer.from('"',t.encoding):typeof t.quote=="string"&&(t.quote=Buffer.from(t.quote,t.encoding)),!Buffer.isBuffer(t.quote))throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(t.quote)}`);if(t.raw===void 0||t.raw===null||t.raw===!1)t.raw=!1;else if(t.raw!==!0)throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(t.raw)}`);if(t.record_delimiter===void 0)t.record_delimiter=[];else if(typeof t.record_delimiter=="string"||Buffer.isBuffer(t.record_delimiter)){if(t.record_delimiter.length===0)throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);t.record_delimiter=[t.record_delimiter]}else if(!Array.isArray(t.record_delimiter))throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);if(t.record_delimiter=t.record_delimiter.map(function(a,n){if(typeof a!="string"&&!Buffer.isBuffer(a))throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer",`at index ${n},`,`got ${JSON.stringify(a)}`],t);if(a.length===0)throw new tt("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer",`at index ${n},`,`got ${JSON.stringify(a)}`],t);return typeof a=="string"&&(a=Buffer.from(a,t.encoding)),a}),typeof t.relax_column_count!="boolean")if(t.relax_column_count===void 0||t.relax_column_count===null)t.relax_column_count=!1;else throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(t.relax_column_count)}`);if(typeof t.relax_column_count_less!="boolean")if(t.relax_column_count_less===void 0||t.relax_column_count_less===null)t.relax_column_count_less=!1;else throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(t.relax_column_count_less)}`);if(typeof t.relax_column_count_more!="boolean")if(t.relax_column_count_more===void 0||t.relax_column_count_more===null)t.relax_column_count_more=!1;else throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(t.relax_column_count_more)}`);if(typeof t.relax_quotes!="boolean")if(t.relax_quotes===void 0||t.relax_quotes===null)t.relax_quotes=!1;else throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(t.relax_quotes)}`);if(typeof t.skip_empty_lines!="boolean")if(t.skip_empty_lines===void 0||t.skip_empty_lines===null)t.skip_empty_lines=!1;else throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(t.skip_empty_lines)}`);if(typeof t.skip_records_with_empty_values!="boolean")if(t.skip_records_with_empty_values===void 0||t.skip_records_with_empty_values===null)t.skip_records_with_empty_values=!1;else throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(t.skip_records_with_empty_values)}`);if(typeof t.skip_records_with_error!="boolean")if(t.skip_records_with_error===void 0||t.skip_records_with_error===null)t.skip_records_with_error=!1;else throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(t.skip_records_with_error)}`);if(t.rtrim===void 0||t.rtrim===null||t.rtrim===!1)t.rtrim=!1;else if(t.rtrim!==!0)throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(t.rtrim)}`);if(t.ltrim===void 0||t.ltrim===null||t.ltrim===!1)t.ltrim=!1;else if(t.ltrim!==!0)throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(t.ltrim)}`);if(t.trim===void 0||t.trim===null||t.trim===!1)t.trim=!1;else if(t.trim!==!0)throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(t.trim)}`);if(t.trim===!0&&e.ltrim!==!1?t.ltrim=!0:t.ltrim!==!0&&(t.ltrim=!1),t.trim===!0&&e.rtrim!==!1?t.rtrim=!0:t.rtrim!==!0&&(t.rtrim=!1),t.to===void 0||t.to===null)t.to=-1;else if(t.to!==-1)if(typeof t.to=="string"&&/\d+/.test(t.to)&&(t.to=parseInt(t.to)),Number.isInteger(t.to)){if(t.to<=0)throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(e.to)}`)}else throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(e.to)}`);if(t.to_line===void 0||t.to_line===null)t.to_line=-1;else if(t.to_line!==-1)if(typeof t.to_line=="string"&&/\d+/.test(t.to_line)&&(t.to_line=parseInt(t.to_line)),Number.isInteger(t.to_line)){if(t.to_line<=0)throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(e.to_line)}`)}else throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(e.to_line)}`);return t};var xM=function(e){return e.every(t=>t==null||t.toString&&t.toString().trim()==="")},tpe=13,rpe=10,Nu={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},DM=function(e={}){let t={bytes:0,comment_lines:0,empty_lines:0,invalid_field_length:0,lines:1,records:0},r=kv(e);return{info:t,original_options:e,options:r,state:OM(r),__needMoreData:function(a,n,i){if(i)return!1;let{encoding:o,escape:s,quote:d}=this.options,{quoting:u,needMoreDataSize:l,recordDelimiterMaxLength:p}=this.state,_=n-a-1,g=Math.max(l,p===0?Buffer.from(`\r
61
61
  `,o).length:p,u?(s===null?0:s.length)+d.length:0,u?d.length+p:0);return _<g},parse:function(a,n,i,o){let{bom:s,comment_no_infix:d,encoding:u,from_line:l,ltrim:p,max_record_size:_,raw:g,relax_quotes:f,rtrim:m,skip_empty_lines:h,to:y,to_line:b}=this.options,{comment:w,escape:R,quote:N,record_delimiter:M}=this.options,{bomSkipped:X,previousBuf:q,rawBuffer:ne,escapeIsQuote:oe}=this.state,V;if(q===void 0)if(a===void 0){o();return}else V=a;else q!==void 0&&a===void 0?V=q:V=Buffer.concat([q,a]);if(X===!1)if(s===!1)this.state.bomSkipped=!0;else if(V.length<3){if(n===!1){this.state.previousBuf=V;return}}else{for(let D in Nu)if(Nu[D].compare(V,0,Nu[D].length)===0){let P=Nu[D].length;this.state.bufBytesStart+=P,V=V.slice(P);let U=kv({...this.original_options,encoding:D});for(let F in U)this.options[F]=U[F];({comment:w,escape:R,quote:N}=this.options);break}this.state.bomSkipped=!0}let x=V.length,S;for(S=0;S<x&&!this.__needMoreData(S,x,n);S++){if(this.state.wasRowDelimiter===!0&&(this.info.lines++,this.state.wasRowDelimiter=!1),b!==-1&&this.info.lines>b){this.state.stop=!0,o();return}this.state.quoting===!1&&M.length===0&&this.__autoDiscoverRecordDelimiter(V,S)&&(M=this.options.record_delimiter);let D=V[S];if(g===!0&&ne.append(D),(D===tpe||D===rpe)&&this.state.wasRowDelimiter===!1&&(this.state.wasRowDelimiter=!0),this.state.escaping===!0)this.state.escaping=!1;else{if(R!==null&&this.state.quoting===!0&&this.__isEscape(V,S,D)&&S+R.length<x)if(oe){if(this.__isQuote(V,S+R.length)){this.state.escaping=!0,S+=R.length-1;continue}}else{this.state.escaping=!0,S+=R.length-1;continue}if(this.state.commenting===!1&&this.__isQuote(V,S))if(this.state.quoting===!0){let F=V[S+N.length],j=m&&this.__isCharTrimable(V,S+N.length),J=w!==null&&this.__compareBytes(w,V,S+N.length,F),ee=this.__isDelimiter(V,S+N.length,F),se=M.length===0?this.__autoDiscoverRecordDelimiter(V,S+N.length):this.__isRecordDelimiter(F,V,S+N.length);if(R!==null&&this.__isEscape(V,S,D)&&this.__isQuote(V,S+R.length))S+=R.length-1;else if(!F||ee||se||J||j){this.state.quoting=!1,this.state.wasQuoting=!0,S+=N.length-1;continue}else if(f===!1){let C=this.__error(new tt("CSV_INVALID_CLOSING_QUOTE",["Invalid Closing Quote:",`got "${String.fromCharCode(F)}"`,`at line ${this.info.lines}`,"instead of delimiter, record delimiter, trimable character","(if activated) or comment"],this.options,this.__infoField()));if(C!==void 0)return C}else this.state.quoting=!1,this.state.wasQuoting=!0,this.state.field.prepend(N),S+=N.length-1}else if(this.state.field.length!==0){if(f===!1){let F=this.__infoField(),j=Object.keys(Nu).map(ee=>Nu[ee].equals(this.state.field.toString())?ee:!1).filter(Boolean)[0],J=this.__error(new tt("INVALID_OPENING_QUOTE",["Invalid Opening Quote:",`a quote is found on field ${JSON.stringify(F.column)} at line ${F.lines}, value is ${JSON.stringify(this.state.field.toString(u))}`,j?`(${j} bom)`:void 0],this.options,F,{field:this.state.field}));if(J!==void 0)return J}}else{this.state.quoting=!0,S+=N.length-1;continue}if(this.state.quoting===!1){let F=this.__isRecordDelimiter(D,V,S);if(F!==0){if(this.state.commenting&&this.state.wasQuoting===!1&&this.state.record.length===0&&this.state.field.length===0)this.info.comment_lines++;else{if(this.state.enabled===!1&&this.info.lines+(this.state.wasRowDelimiter===!0?1:0)>=l){this.state.enabled=!0,this.__resetField(),this.__resetRecord(),S+=F-1;continue}if(h===!0&&this.state.wasQuoting===!1&&this.state.record.length===0&&this.state.field.length===0){this.info.empty_lines++,S+=F-1;continue}this.info.bytes=this.state.bufBytesStart+S;let ee=this.__onField();if(ee!==void 0)return ee;this.info.bytes=this.state.bufBytesStart+S+F;let se=this.__onRecord(i);if(se!==void 0)return se;if(y!==-1&&this.info.records>=y){this.state.stop=!0,o();return}}this.state.commenting=!1,S+=F-1;continue}if(this.state.commenting)continue;if(w!==null&&(d===!1||this.state.record.length===0&&this.state.field.length===0)&&this.__compareBytes(w,V,S,D)!==0){this.state.commenting=!0;continue}let j=this.__isDelimiter(V,S,D);if(j!==0){this.info.bytes=this.state.bufBytesStart+S;let J=this.__onField();if(J!==void 0)return J;S+=j-1;continue}}}if(this.state.commenting===!1&&_!==0&&this.state.record_length+this.state.field.length>_)return this.__error(new tt("CSV_MAX_RECORD_SIZE",["Max Record Size:","record exceed the maximum number of tolerated bytes",`of ${_}`,`at line ${this.info.lines}`],this.options,this.__infoField()));let P=p===!1||this.state.quoting===!0||this.state.field.length!==0||!this.__isCharTrimable(V,S),U=m===!1||this.state.wasQuoting===!1;if(P===!0&&U===!0)this.state.field.append(D);else{if(m===!0&&!this.__isCharTrimable(V,S))return this.__error(new tt("CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE",["Invalid Closing Quote:","found non trimable byte after quote",`at line ${this.info.lines}`],this.options,this.__infoField()));P===!1&&(S+=this.__isCharTrimable(V,S)-1);continue}}if(n===!0)if(this.state.quoting===!0){let D=this.__error(new tt("CSV_QUOTE_NOT_CLOSED",["Quote Not Closed:",`the parsing is finished with an opening quote at line ${this.info.lines}`],this.options,this.__infoField()));if(D!==void 0)return D}else if(this.state.wasQuoting===!0||this.state.record.length!==0||this.state.field.length!==0){this.info.bytes=this.state.bufBytesStart+S;let D=this.__onField();if(D!==void 0)return D;let P=this.__onRecord(i);if(P!==void 0)return P}else this.state.wasRowDelimiter===!0?this.info.empty_lines++:this.state.commenting===!0&&this.info.comment_lines++;else this.state.bufBytesStart+=S,this.state.previousBuf=V.slice(S);this.state.wasRowDelimiter===!0&&(this.info.lines++,this.state.wasRowDelimiter=!1)},__onRecord:function(a){let{columns:n,group_columns_by_name:i,encoding:o,info:s,from:d,relax_column_count:u,relax_column_count_less:l,relax_column_count_more:p,raw:_,skip_records_with_empty_values:g}=this.options,{enabled:f,record:m}=this.state;if(f===!1)return this.__resetRecord();let h=m.length;if(n===!0){if(g===!0&&xM(m)){this.__resetRecord();return}return this.__firstLineToColumns(m)}if(n===!1&&this.info.records===0&&(this.state.expectedRecordLength=h),h!==this.state.expectedRecordLength){let y=n===!1?new tt("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH",["Invalid Record Length:",`expect ${this.state.expectedRecordLength},`,`got ${h} on line ${this.info.lines}`],this.options,this.__infoField(),{record:m}):new tt("CSV_RECORD_INCONSISTENT_COLUMNS",["Invalid Record Length:",`columns length is ${n.length},`,`got ${h} on line ${this.info.lines}`],this.options,this.__infoField(),{record:m});if(u===!0||l===!0&&h<this.state.expectedRecordLength||p===!0&&h>this.state.expectedRecordLength)this.info.invalid_field_length++,this.state.error=y;else{let b=this.__error(y);if(b)return b}}if(g===!0&&xM(m)){this.__resetRecord();return}if(this.state.recordHasError===!0){this.__resetRecord(),this.state.recordHasError=!1;return}if(this.info.records++,d===1||this.info.records>=d){let{objname:y}=this.options;if(n!==!1){let b={};for(let w=0,R=m.length;w<R;w++)n[w]===void 0||n[w].disabled||(i===!0&&b[n[w].name]!==void 0?Array.isArray(b[n[w].name])?b[n[w].name]=b[n[w].name].concat(m[w]):b[n[w].name]=[b[n[w].name],m[w]]:b[n[w].name]=m[w]);if(_===!0||s===!0){let w=Object.assign({record:b},_===!0?{raw:this.state.rawBuffer.toString(o)}:{},s===!0?{info:this.__infoRecord()}:{}),R=this.__push(y===void 0?w:[b[y],w],a);if(R)return R}else{let w=this.__push(y===void 0?b:[b[y],b],a);if(w)return w}}else if(_===!0||s===!0){let b=Object.assign({record:m},_===!0?{raw:this.state.rawBuffer.toString(o)}:{},s===!0?{info:this.__infoRecord()}:{}),w=this.__push(y===void 0?b:[m[y],b],a);if(w)return w}else{let b=this.__push(y===void 0?m:[m[y],m],a);if(b)return b}}this.__resetRecord()},__firstLineToColumns:function(a){let{firstLineToHeaders:n}=this.state;try{let i=n===void 0?a:n.call(null,a);if(!Array.isArray(i))return this.__error(new tt("CSV_INVALID_COLUMN_MAPPING",["Invalid Column Mapping:","expect an array from column function,",`got ${JSON.stringify(i)}`],this.options,this.__infoField(),{headers:i}));let o=i2(i);this.state.expectedRecordLength=o.length,this.options.columns=o,this.__resetRecord();return}catch(i){return i}},__resetRecord:function(){this.options.raw===!0&&this.state.rawBuffer.reset(),this.state.error=void 0,this.state.record=[],this.state.record_length=0},__onField:function(){let{cast:a,encoding:n,rtrim:i,max_record_size:o}=this.options,{enabled:s,wasQuoting:d}=this.state;if(s===!1)return this.__resetField();let u=this.state.field.toString(n);if(i===!0&&d===!1&&(u=u.trimRight()),a===!0){let[l,p]=this.__cast(u);if(l!==void 0)return l;u=p}this.state.record.push(u),o!==0&&typeof u=="string"&&(this.state.record_length+=u.length),this.__resetField()},__resetField:function(){this.state.field.reset(),this.state.wasQuoting=!1},__push:function(a,n){let{on_record:i}=this.options;if(i!==void 0){let o=this.__infoRecord();try{a=i.call(null,a,o)}catch(s){return s}if(a==null)return}n(a)},__cast:function(a){let{columns:n,relax_column_count:i}=this.options;if(Array.isArray(n)===!0&&i&&this.options.columns.length<=this.state.record.length)return[void 0,void 0];if(this.state.castField!==null)try{let s=this.__infoField();return[void 0,this.state.castField.call(null,a,s)]}catch(s){return[s]}if(this.__isFloat(a))return[void 0,parseFloat(a)];if(this.options.cast_date!==!1){let s=this.__infoField();return[void 0,this.options.cast_date.call(null,a,s)]}return[void 0,a]},__isCharTrimable:function(a,n){return((o,s)=>{let{timchars:d}=this.state;e:for(let u=0;u<d.length;u++){let l=d[u];for(let p=0;p<l.length;p++)if(l[p]!==o[s+p])continue e;return l.length}return 0})(a,n)},__isFloat:function(a){return a-parseFloat(a)+1>=0},__compareBytes:function(a,n,i,o){if(a[0]!==o)return 0;let s=a.length;for(let d=1;d<s;d++)if(a[d]!==n[i+d])return 0;return s},__isDelimiter:function(a,n,i){let{delimiter:o,ignore_last_delimiters:s}=this.options;if(s===!0&&this.state.record.length===this.options.columns.length-1)return 0;if(s!==!1&&typeof s=="number"&&this.state.record.length===s-1)return 0;e:for(let d=0;d<o.length;d++){let u=o[d];if(u[0]===i){for(let l=1;l<u.length;l++)if(u[l]!==a[n+l])continue e;return u.length}}return 0},__isRecordDelimiter:function(a,n,i){let{record_delimiter:o}=this.options,s=o.length;e:for(let d=0;d<s;d++){let u=o[d],l=u.length;if(u[0]===a){for(let p=1;p<l;p++)if(u[p]!==n[i+p])continue e;return u.length}}return 0},__isEscape:function(a,n,i){let{escape:o}=this.options;if(o===null)return!1;let s=o.length;if(o[0]===i){for(let d=0;d<s;d++)if(o[d]!==a[n+d])return!1;return!0}return!1},__isQuote:function(a,n){let{quote:i}=this.options;if(i===null)return!1;let o=i.length;for(let s=0;s<o;s++)if(i[s]!==a[n+s])return!1;return!0},__autoDiscoverRecordDelimiter:function(a,n){let{encoding:i}=this.options,o=[Buffer.from(`\r
62
62
  `,i),Buffer.from(`
63
63
  `,i),Buffer.from("\r",i)];e:for(let s=0;s<o.length;s++){let d=o[s].length;for(let u=0;u<d;u++)if(o[s][u]!==a[n+u])continue e;return this.options.record_delimiter.push(o[s]),this.state.recordDelimiterMaxLength=o[s].length,o[s].length}return 0},__error:function(a){let{encoding:n,raw:i,skip_records_with_error:o}=this.options,s=typeof a=="string"?new Error(a):a;if(o){if(this.state.recordHasError=!0,this.options.on_skip!==void 0)try{this.options.on_skip(s,i?this.state.rawBuffer.toString(n):void 0)}catch(d){return d}return}else return s},__infoDataSet:function(){return{...this.info,columns:this.options.columns}},__infoRecord:function(){let{columns:a,raw:n,encoding:i}=this.options;return{...this.__infoDataSet(),error:this.state.error,header:a===!0,index:this.state.record.length,raw:n?this.state.rawBuffer.toString(i):void 0}},__infoField:function(){let{columns:a}=this.options,n=Array.isArray(a);return{...this.__infoRecord(),column:n===!0?a.length>this.state.record.length?a[this.state.record.length].name:null:this.state.record.length,quoting:this.state.wasQuoting}}}};var Rv=function(e,t={}){typeof e=="string"&&(e=Buffer.from(e));let r=t&&t.objname?{}:[],a=DM(t),n=s=>{a.options.objname===void 0?r.push(s):r[s[0]]=s[1]},i=()=>{},o=a.parse(e,!0,n,i);if(o!==void 0)throw o;return r};var kM=Ko(uv(),1),Iv="USD",sm=2;var Ld=e=>{let t=Number(e),r=Math.round(t*1e3);if(!Number.isFinite(t)||!Number.isSafeInteger(r))throw new Error(`Invalid/unsafe amount: ${e}`);return r},o2=(e,t=sm)=>kM.utils.convertMilliUnitsToCurrencyAmount(e,t);var dm=(e,t)=>{let r=e+t;if(!Number.isSafeInteger(r))throw new Error("Milliunit sum overflow");return r};var npe=e=>e===0?"balanced":e>0?"credit":"debit",ape=(e,t=sm)=>new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:t,maximumFractionDigits:t}),ipe=(e,t=Iv,r=sm)=>ape(t,r).format(o2(e,r)),$t=(e,t=Iv,r=sm)=>({value_milliunits:e,value:o2(e,r),value_display:ipe(e,t,r),currency:t,direction:npe(e)}),lo=(e,t=Iv,r=sm)=>$t(Ld(e),t,r);var RM=require("fs");function ope(e,t){let r=e.trim(),n={"MM/DD/YYYY":"MM/dd/yyyy","M/D/YYYY":"M/d/yyyy","DD/MM/YYYY":"dd/MM/yyyy","D/M/YYYY":"d/M/yyyy","YYYY-MM-DD":"yyyy-MM-dd","MM-DD-YYYY":"MM-dd-yyyy","MMM dd, yyyy":"MMM dd, yyyy","MMM d, yyyy":"MMM d, yyyy"}[t];if(n)try{let o=bM(r,n,new Date);if(!isNaN(o.getTime()))return o}catch{}let i=new Date(r);if(isNaN(i.getTime()))throw new Error(`Unable to parse date: ${e} with format: ${t}`);return i}function spe(e){let r=e.replace(/[$,\s]/g,"").trim(),a=!1;r.startsWith("(")&&r.endsWith(")")&&(a=!0,r=r.slice(1,-1)),r.startsWith("+")&&(r=r.slice(1));let n=Number(r);if(isNaN(n)||!isFinite(n))throw new Error(`Invalid amount value: "${e}" (cleaned: "${r}")`);return Ld(a?-n:n)}function dpe(e){return e?[/^\d{1,2}\/\d{1,2}\/\d{4}$/,/^\d{4}-\d{1,2}-\d{1,2}$/,/^\d{1,2}-\d{1,2}-\d{4}$/,/^[A-Za-z]{3}\s+\d{1,2},\s+\d{4}$/].some(r=>r.test(e.trim())):!1}function s2(e){if(!e)return"MM/DD/YYYY";let t=e.trim();return t.includes("/")?"MM/DD/YYYY":t.includes("-")?/^\d{4}-/.test(t)?"YYYY-MM-DD":"MM-DD-YYYY":/^[A-Za-z]{3}\s+\d{1,2},\s+\d{4}$/.test(t)?"MMM dd, yyyy":"MM/DD/YYYY"}function cpe(e){let t=[",",";"," ","|"],r=e.slice(0,3).filter(i=>i.trim());if(r.length===0)return",";let a=",",n=-1;for(let i of t){let o=0,s=[],d=!1;for(let u of r)try{let l=Rv(u,{delimiter:i,quote:'"',escape:'"',skip_empty_lines:!0,trim:!0,relax_column_count:!0});if(l&&l.length>0&&l[0]){let p=Array.isArray(l[0])?l[0]:Object.values(l[0]);s.push(p.length)}else{let p=u.split(i);s.push(p.length)}}catch{d=!0;let l=u.split(i);s.push(l.length)}if(s.length>1){let u=s[0];if(u===void 0)continue;s.every(p=>p===u)&&u>1&&(o=Math.min(u,10),i===","&&(o+=.5),i===";"&&(o+=.3),d||(o+=.2))}o>n&&(n=o,a=i)}return a}function upe(e){let t=/^(date|trans.*date|transaction.*date|post.*date|dt)$/i,r=/^(amount|amt|dollar.*amount|transaction.*amount)$/i,a=/^(description|desc|memo|transaction.*description|payee|merchant)$/i,n=/^(debit|debits|withdrawal|withdrawals|out|outgoing)$/i,i=/^(credit|credits|deposit|deposits|in|incoming)$/i,o=null,s=null,d=null,u=null,l=null;for(let p of e){let _=p.trim();t.test(_)?o=_:r.test(_)?s=_:a.test(_)?d=_:n.test(_)?u=_:i.test(_)&&(l=_)}return{dateColumn:o,amountColumn:s,descriptionColumn:d,debitColumn:u,creditColumn:l}}function IM(e){let t=e.trim().split(`