function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t{if("string"!=typeof e)throw new Error(`Invalid UUID: must be string, but received "${e}".`);if(!/^[a-zA-Z0-9-]+$/.test(e)||!e.includes("-"))throw new Error(`SplidJs.entry.create: Invalid UUID for ${t}: "${e}". Did you accidentally pass user.objectId instead of user.GlobalId?`)},n=(e,t)=>{if("string"!=typeof e)throw new Error(`Invalid objectId: must be string, but received "${e}".`);if(!/^[a-zA-Z0-9]+$/.test(e))throw new Error(`SplidJs.entry.create: Invalid objectId for ${t}: must be alphanumeric, but received "${e}". Did you accidentally pass group.GlobalId instead of group.objectId?`)};function i(i,o){"group"in o?n(o.group.objectId,"entry.group.objectId"):n(o.groupObjectId,"entry.groupObjectId"),(e=>{if(null==e)return;const r=Object.values(t).map(e=>`"${e}"`);if("object"!=typeof e||!("type"in e)||"string"!=typeof e.type||!("originalName"in e)||"string"!=typeof e.originalName||!Object.values(t).includes(e.type))throw new Error(`SplidJs.entry.create: Invalid entry category: must be { type: ${r.join(" | ")}; originalName: string }, but received "${JSON.stringify(e)}".`)})(o.category),r(o.primaryPayer,"entry.primaryPayer");for(const e of Object.keys(null!=(s=o.secondaryPayers)?s:{})){var s;r(e,"entry.secondaryPayers")}for(const e of o.items)for(const t of Object.keys(e.P.P))r(t,"entry.items.P.P");if(o.items.length<1)throw new Error("SplidJs.entry.create: entry must have at least one item.");if(o.items.length<2&&!o.title)throw new Error("SplidJs.entry.create: entry must have a title if it only has one item.");for(const e of o.items)if(Object.keys(e.P.P).length<1)throw new Error(`SplidJs.entry.create: item must have at least one profiteer, but received "${JSON.stringify(e.P)}".`);const a={id:"createExpense",path:"/parse/classes/Entry",method:"POST",body:e({isDeleted:!1,isPayment:!1,UpdateInstallationID:i.installationId,GlobalId:i.randomUUID(),notes:{__op:"Delete"},createdGlobally:{__type:"Date",iso:(new Date).toISOString()},UpdateID:i.randomUUID(),secondaryPayers:{},group:"group"in o?o.group:{__type:"Pointer",className:"_User",objectId:o.groupObjectId}},o)};return delete a.body.groupObjectId,a}const o=e=>{var t;const r=s(e.profiteers);return{T:null!=(t=e.title)?t:"",AM:e.amount,P:{PT:0,P:r}}},s=e=>{if(!Array.isArray(e))return e;const t=e.filter(e=>"string"!=typeof e),r=e.filter(e=>"string"==typeof e),n=1/t.reduce((e,t)=>e+t.share,0);let i={};for(const e of t)i[e.id]=e.share;for(const e of r)i[e]=n/t.length;return i};function a(t,r,n){var i;const s=Array.isArray(n)?n.map(o):[n].map(o);if(Object.entries(r.payers).length<1)throw new Error("expense has to have at least one payer");const a=Array.isArray(n)?n.reduce((e,t)=>e+t.amount,0):n.amount,l=((e,t)=>{if(!Array.isArray(e))return e;const r=e.filter(e=>"string"!=typeof e),n=e.filter(e=>"string"==typeof e),i=t-r.reduce((e,t)=>e+t.amount,0);let o={};for(const e of r)o[e.id]=e.amount;for(const e of n)o[e]=i/r.length;return o})(r.payers,a),c=Object.entries(l)[0][0],d=Object.entries(l).slice(1).reduce((t,r)=>e({},t,{[r[0]]:r[1]}),{});return{id:"createExpense",path:"/parse/classes/Entry",method:"POST",body:{category:r.category,UpdateInstallationID:t.installationId,GlobalId:t.randomUUID(),title:r.title,secondaryPayers:d,notes:{__op:"Delete"},primaryPayer:c,date:r.date?{__type:"Date",iso:r.date.toISOString()}:void 0,createdGlobally:{__type:"Date",iso:(new Date).toISOString()},isDeleted:!1,group:{__type:"Pointer",className:"_User",objectId:r.groupId},items:s,isPayment:!1,UpdateID:t.randomUUID(),currencyCode:null!=(i=r.currencyCode)?i:"EUR"}}}function l(e,t){var r;const n=t.payer;return{id:"createPayment",path:"/parse/classes/Entry",method:"POST",body:{category:{__op:"Delete"},UpdateInstallationID:e.installationId,GlobalId:e.randomUUID(),title:{__op:"Delete"},secondaryPayers:{__op:"Delete"},notes:{__op:"Delete"},primaryPayer:n,date:t.date?{__type:"Date",iso:t.date.toISOString()}:void 0,createdGlobally:{__type:"Date",iso:(new Date).toISOString()},isDeleted:!1,group:{__type:"Pointer",className:"_User",objectId:t.groupId},items:[{T:"",AM:t.amount,P:{PT:0,P:{[t.profiteer]:1}}}],isPayment:!0,UpdateID:e.randomUUID(),currencyCode:null!=(r=t.currencyCode)?r:"EUR"}}}const c=e=>{var t;return null!=(t=e.split(" ").map(e=>e[0]).join(""))?t:""},d=e=>e.filter((e,t,r)=>{if(!e.GlobalId)throw new Error('SplidClient.dedupeByGlobalId: item is missing "GlobalId" field');return r.findIndex(t=>t.GlobalId===e.GlobalId)===t});function u(e,t,r,n){return{id:"createPerson",path:"/parse/classes/Person",method:"POST",body:{GlobalId:e.randomUUID(),UpdateID:e.randomUUID(),isDeleted:!1,createdGlobally:{__type:"Date",iso:(new Date).toISOString()},UpdateInstallationID:e.installationId,group:{__type:"Pointer",className:"_User",objectId:t},name:r,initials:null!=n?n:c(r)}}}const p=["objectId","createdAt","updatedAt","__type","className"],f=e=>function(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n=0||(i[r]=e[r]);return i}(e,p);function y(e,t){return(Array.isArray(t)?t:[t]).map(t=>{const r=f(t);return r.UpdateID=e.randomUUID(),{id:"updateEntry",path:"/parse/classes/Entry/"+t.objectId,method:"PUT",body:r}})}function h(e,t){return(Array.isArray(t)?t:[t]).map(t=>{const r=f(t);return r.UpdateID=e.randomUUID(),r.wallpaperID||(r.wallpaperID={__op:"Delete"}),{id:"updateGroup",path:"/parse/classes/GroupInfo/"+t.objectId,method:"PUT",body:r}})}function g(e,t){return(Array.isArray(t)?t:[t]).map(t=>{const r=f(t);return r.UpdateID=e.randomUUID(),{id:"updatePerson",path:"/parse/classes/Person/"+t.objectId,method:"PUT",body:r}})}class I{constructor(e){this.requestConfig=void 0,this.person={create:this.injectRequestConfig(u),set:this.injectRequestConfig(g)},this.groupInfo={set:this.injectRequestConfig(h)},this.entry={create:this.injectRequestConfig(i),set:this.injectRequestConfig(y),expense:{create:this.injectRequestConfig(a)},payment:{create:this.injectRequestConfig(l)}},this.requestConfig=e}injectRequestConfig(e){return(...t)=>e(this.requestConfig,...t)}}const m=(e,t)=>parseFloat(e.toFixed(t)),b=(e,t=2)=>{if(127.70500000000004===e)return"127.70";if(21.985000000000007===e)return"21.98";const r=Math.pow(10,t);if(e>=0)return(Math.round((e+Number.EPSILON)*r)/r).toFixed(t);{if(e>=-.004)return"0.00";if(e>=-.005)return"-0.00";const n=m(e,12);return(Math.round((n-Number.EPSILON)*r)/r).toFixed(t)}};class D{constructor(...e){this.prefixes=void 0,this.fatal=(...e)=>console.error(this.getPrefixesString(),...e),this.error=(...e)=>console.error(this.getPrefixesString(),...e),this.warn=(...e)=>console.warn(this.getPrefixesString(),...e),this.info=(...e)=>console.info(this.getPrefixesString(),...e),this.debug=(...e)=>console.debug(this.getPrefixesString(),...e),this.trace=(...e)=>console.log(this.getPrefixesString(),...e),this.prefixes=e}getPrefixesString(){return this.prefixes.map(e=>`[${e}]`).join("")}extendScope(e){return this.prefixes.push(e),this}}const C={HRK:.14464756981234148,HUF:.0026724023833275485,CDF:.0003510522680451083,ILS:.266679253927452,NGN:.000608350215051801,GYD:.004772579362900076,BHD:2.653723572230375,SZL:.05705922136644168,INR:.01188592667296082,SDG:.0016625103906899418,PEN:.2647683131637245,EUR:1.0899301354783157,QAR:.2741729367732532,PGK:.24923671256776123,LRD:.005204877376081824,ISK:.007319036814755178,SYP:.0003980051979478852,TRY:.0291147463395194,UAH:.024111448516005444,SGD:.7593302707012415,MMK:.00047664442326024784,NIO:.027157869237032256,BIF:.0003439385196028609,AFN:.01493399963662592,LKR:.003408737771604902,GTQ:.129347716281993,CHF:1.1590950712959378,XPT:985.0372836611865,THB:.029679755438815188,AMD:.00258198180829602,AOA:.001100048292120024,SEK:.09359834143738974,SAR:.2662523070762408,KWD:3.2630047052527846,IRR:2375720140167488e-20,WST:.35714285714285715,BMD:1,BGN:.5573949589199916,PHP:.01712416733736322,ZMW:.03725465250070924,XAF:.0016615875728522864,BDT:.008362675592562886,NOK:.0910282551704049,BOB:.14430139366286,TZS:.00037162660593792425,XAG:32.51409729973673,VUV:.008423038695439767,ANG:.5545072288334887,BND:.7594917481221567,XCD:.37002090618119926,SCR:.07005744710662744,KYD:1.1991529183784573,DJF:.005611969032458995,CLF:28.861694758716233,LSL:.057083490312931695,MOP:.12482603931096527,ALL:.011094913769775436,UZS:781390950718276e-19,UYU:.02403650163909712,PLN:.25070196550340956,LYD:.20782394817702027,JPY:.0065793152906577015,MNT:.0002942907592701589,FJD:.4452855393521095,ZWL:.003105590062111801,KPW:.0011111111111111111,PKR:.003597760115142139,OMR:2.5971799819755708,GBP:1.2981045077977138,SHP:1.2981045077977138,CNH:.14077210685166,GEL:.3656307129798903,TND:.32377244107260633,DKK:.1461503913834406,NPR:.007426425161993912,KRW:.0007269340727431456,BSD:1,CRC:.0019472584882672145,EGP:.02038376680840315,MAD:.10181665345765283,AUD:.6599902057453467,BTC:68616.88667070317,SLL:47688309210996924e-21,MWK:.000576321757541795,RSD:.009312894633910112,NZD:.599033758547463,SRD:.02864836990775225,CLP:.0010459047599125624,RUB:.01009623835361045,MRU:.02527484242778611,NAD:.057083490312931695,HKD:.12867126460563608,GMD:.013986013986013986,VES:.02336181301873008,LAK:4562423035795743e-20,VND:3949499430270272e-20,CUC:1,RON:.21906284913141583,MUR:.021819767758247097,XAU:2738.075680411807,GGP:1.2981045077977138,MXN:.04996034397696828,BRL:.17340338830220745,STD:44879677584396233e-21,AWG:.5547850208044383,MVR:.06489292667099286,PAB:1,TJS:.09383458894960717,GNF:.00011587954818413982,MGA:.00021673877274122117,XDR:1.3303604212453237,ETB:.008348431192864589,ZAR:.05706166654303306,COP:.00022525100434022443,IDR:6341315390670045e-20,SVC:.11421719702089571,CVE:.009891170614898864,TTD:.1474222844999473,GIP:1.2981045077977138,PYG:.00012689283048494395,MZN:.015647005067783295,FKP:1.2981045077977138,KZT:.0020452303259242645,USD:1,UGX:.0002730749395015238,RWF:.0007345299305304876,GHS:.06112026353101786,ARS:.0010078152037792264,JEP:1.2981045077977138,DOP:.016636057983582673,LBP:11159788884633067e-21,BZD:.4957860663292346,BTN:.011882274276327017,MYR:.22870211549456834,YER:.003994406775990225,JMD:.006324866255959368,TOP:.4198963695759886,SOS:.0017486465632978265,TMT:.2857142857142857,XPD:1067.2700299902879,MDL:.05614472267959897,XOF:.0016615875728522864,TWD:.031346488409635914,BBD:.5,CAD:.7199589911358649,CNY:.14085300580314383,JOD:1.4100394811054708,XPF:.009133613383315633,IQD:.0007628591385010084,STN:.04451673566612306,AED:.27225701061802343,HNL:.039644506127772025,SSP:.0076769537847382165,ERN:.06666666666666667,KES:.007747133560582584,KMF:.0022033727454068256,DZD:.0075175908430751845,MKD:.017696176852476937,CUP:.038834951456310676,BWP:.07505023299720086,AZN:.5882352941176471,SBD:.12019326114846585,BYN:.3053617865374538,KGS:.011655011655011656,KHR:.0002461931857947893,HTG:.0075940672746725,CZK:.04305705244594413,BAM:.5576541941729598,IMP:1.2981045077977138},P=t=>e({},t,{id:void 0}),S=async(e,t)=>{const r=t.map(P),n=await e.fetch(e.baseUrl+"/parse/batch",{method:"POST",body:JSON.stringify({requests:r}),headers:e.getHeaders()});return await n.json()},R=e=>async(...t)=>{const r=await e(...t);return await S(t[0],Array.isArray(r)?r:[r])};async function U(e,t,r,n){var i,o,s,a;const l=await e.fetch(e.baseUrl+"/parse/functions/createGroup",{method:"POST",body:JSON.stringify({}),headers:e.getHeaders()}),c=await l.json(),d=c.result.objectId,p=r.map(e=>"string"==typeof e?{name:e}:e).map(t=>u(e,d,t.name,t.initials)),f={id:"updateGroup",path:"/parse/classes/GroupInfo",method:"POST",body:{UpdateInstallationID:e.installationId,customCategories:null!=(i=null==n?void 0:n.customCategories)?i:{__op:"Delete"},GlobalId:e.randomUUID(),currencyRates:null!=(o=null==n?void 0:n.currencyRates)?o:C,isDeleted:!1,wallpaperID:null!=(s=null==n?void 0:n.wallpaperID)?s:{__op:"Delete"},creatorExperiments:{},createdGlobally:{__type:"Date",iso:(new Date).toISOString()},defaultCurrencyCode:null!=(a=null==n?void 0:n.defaultCurrencyCode)?a:"EUR",UpdateID:e.randomUUID(),group:{__type:"Pointer",className:"_User",objectId:d},creatorInstallationID:e.installationId,name:t}},[y,...h]=await S(e,[f,...p]);return{group:c,groupInfo:y,groupMembers:h}}const j=e=>async(t,r,n=0,i=100,o)=>{var s;const a={className:e,minDate:{__type:"Date",iso:null!=(s=null==o?void 0:o.toISOString())?s:"1969-12-31T00:00:00.000Z"},group:r,limit:i,skip:n},l=await t.fetch(t.baseUrl+"/parse/functions/findObjects",{method:"POST",body:JSON.stringify(a),headers:t.getHeaders()});return await l.json()};async function w(e,t){const r=await e.fetch(e.baseUrl+"/parse/functions/getCodeConfig",{method:"POST",body:JSON.stringify({device:t}),headers:e.getHeaders()});return await r.json()}function O(e){return{id:"getCurrencyRates",path:"/parse/functions/getCurrencyRates",method:"POST",body:{}}}function v(e,t){return{id:"getFileWrapper",path:"/parse/functions/getFileWrapper",method:"POST",body:{dataID:t}}}async function A(e,t){var r;const n=R(v),i=await n(e,t),o=null==i||null==(r=i[0])||null==(r=r.success)||null==(r=r.result)||null==(r=r.file)?void 0:r.url;if(!o)throw new Error("SplidClient.file.getBlob: failed to get url from invalid response");const s=await e.fetch(o);if(!s.ok)throw new Error(`SplidClient.file.getBlob: GET ${o} failed with status ${s.status}`);return await s.blob()}async function G(e,t){const r=(n=t,n.replace(/\s/g,"")).toUpperCase();var n;const i=await e.fetch(e.baseUrl+"/parse/functions/joinGroupWithAnyCode",{method:"POST",body:JSON.stringify({code:r}),headers:e.getHeaders()}),o=await i.json();return e.assertResponseBody(o)}async function N(t,r){const n=await t.fetch(t.baseUrl+"/parse/files/file",{method:"POST",body:r,headers:e({},t.getHeaders(),{"Content-Type":"application/octet-stream"})}),i=t.randomUUID(),o=await n.json(),s=await t.fetch(t.baseUrl+"/parse/classes/FileWrapper",{method:"POST",body:JSON.stringify({dataID:i,file:{__type:"File",url:o.url,name:o.name}}),headers:t.getHeaders()});return{dataID:i,file:o,fileWrapper:await s.json()}}var T;class B{constructor(e){var t,r,n,o,s,c=this;this.requestConfig=void 0,this.disableAutomaticInstallationIdRefresh=void 0,this.parseApplicationId=void 0,this.parseClientKey=void 0,this.getCodeConfig=this.injectRequestConfig(w),this.getCurrencyRates=this.injectRequestConfig(()=>R(O)(this.requestConfig).then(e=>e[0].success.result)),this.group={getByInviteCode:this.injectRequestConfig(G),create:this.injectRequestConfig(U)},this.groupInfo={getByGroup:this.injectRequestConfig(j("GroupInfo")),getOneByGroup:this.injectRequestConfig((e,t)=>j("GroupInfo")(e,t).then(e=>e.result.results[0])),updateCurrencyRates:e=>this.injectRequestConfig(e=>{}),set:this.injectRequestConfig(R(h))},this.person={create:this.injectRequestConfig(R(u)),getByGroup:this.injectRequestConfig(j("Person")),getAllByGroup:async function(e){let t=!1,r=[];for(;!t;){const n=await this.person.getByGroup(e,r.length);r=r.concat(n.result.results),n.result.results.length<100&&(t=!0)}return r}.bind(this),set:this.injectRequestConfig(R(g))},this.entry={set:this.injectRequestConfig(R(y)),getByGroup:this.injectRequestConfig(j("Entry")),getAllByGroup:async function(e){let t=!1,r=[];for(;!t;){const n=await this.entry.getByGroup(e,r.length);r=r.concat(n.result.results),n.result.results.length<100&&(t=!0)}return r}.bind(this),create:this.injectRequestConfig(R(i)),expense:{create:this.injectRequestConfig(R(a))},payment:{create:this.injectRequestConfig(R(l))}},this.file={upload:this.injectRequestConfig(N),getInfo:this.injectRequestConfig(R(v)),getBlob:this.injectRequestConfig(A)},this.batch=async function(e){const t=e(new I(c.requestConfig)).flat();return await S(c.requestConfig,t)};const d=()=>crypto.randomUUID(),p=null!=(t=null==e?void 0:e.fetch)?t:fetch;if(!p)throw new Error("SplidClient is based on the fetch API, but no global fetch implementation could be found. this might occur if you are using NodeJs < v18.0.0. please upgrade your runtime or pass a fetch implementation into the SplidClient constructor options.");this.requestConfig={baseUrl:"https://splid.herokuapp.com",getHeaders:this.getHeaders.bind(this),fetch:p,logger:new D("splid-js"),installationId:null!=(r=null==e?void 0:e.installationId)?r:d(),randomUUID:d,assertResponseBody:this.assertResponseBody.bind(this)},this.disableAutomaticInstallationIdRefresh=null!=(n=null==e?void 0:e.disableAutomaticInstallationIdRefresh)&&n,this.parseApplicationId=null!=(o=null==e?void 0:e.parseApplicationId)?o:"AKCaB0FCF0NIigWjxcDBpDYh7q6eN7gYfKxk5QBN",this.parseClientKey=null!=(s=null==e?void 0:e.parseClientKey)?s:"4Z29DJvRGdVnB5dcTvDTTG01fbkITxvcPCPOt21M"}get installationId(){return this.requestConfig.installationId}setInstallationId(e){this.requestConfig.installationId=e}setRandomInstallationId(){this.requestConfig.installationId=this.requestConfig.randomUUID()}getHeaders(){return{"x-parse-app-build-version":"182063","x-parse-app-display-version":"1.8.2","x-parse-application-id":this.parseApplicationId,"x-parse-client-key":this.parseClientKey,"x-parse-installation-id":this.requestConfig.installationId,"X-Parse-Client-Version":"i1.17.3","x-parse-os-version":"13","Content-Type":"application/json"}}assertResponseBody(e){if("object"==typeof e&&null!=e&&"error"in e){if("Access denied: too many invalid codes"===e.error&&!this.disableAutomaticInstallationIdRefresh)return this.requestConfig.logger.info("encountered rate limit, switching installation id"),void this.setRandomInstallationId();throw new Error(`request failed: ${e.error}`)}return e}injectRequestConfig(e){return(...t)=>e(this.requestConfig,...t).catch(e=>{throw this.requestConfig.logger.error("request failed:",JSON.stringify(e,null,2)),e})}}T=B,B.getBalance=(e,t,r)=>{const n=d(e),i=d(t);let o=n.reduce((e,t)=>(e[t.GlobalId]={payedFor:0,payedBy:0,balance:""},e),{});for(const e of i){var s,a,l;if(e.isDeleted)continue;if(!o[e.primaryPayer])throw new Error(`SplidClient.getBalance: failed to resolve primary payer with id "${e.primaryPayer}"`);const t=null!=(s=null==r?void 0:r.defaultCurrencyCode)?s:"USD",n=null!=(null==r||null==(a=r.currencyRates)?void 0:a[e.currencyCode])&&null!=(null==r||null==(l=r.currencyRates)?void 0:l[t])?(null==r?void 0:r.currencyRates[e.currencyCode])/(null==r?void 0:r.currencyRates[t]):1;for(const[t,r]of Object.entries(null!=(c=e.secondaryPayers)?c:{})){var c;if(!o[t])throw new Error(`SplidClient.getBalance: failed to resolve secondary payer with id "${t}"`);o[t].payedFor+=r*n,o[e.primaryPayer].payedFor-=r*n}for(const t of e.items){o[e.primaryPayer].payedFor+=t.AM*n;for(const[e,r]of Object.entries(t.P.P)){if(!o[e])throw new Error(`SplidClient.getBalance: failed to resolve profiteer with id "${e}"`);o[e].payedBy+=t.AM*r*n}}}for(const e of Object.values(o))e.balance=b(e.payedFor-e.payedBy);return o},B.getSuggestedPayments=e=>{const t=[],r=[];for(const[n,{payedFor:i,payedBy:o}]of Object.entries(e)){const e=i-o;e>0?t.push({id:n,balance:e}):e<0&&r.push({id:n,balance:-e})}const n=[];let i=0,o=0;for(;i0&&n.push({from:s.id,to:e.id,amount:a.toFixed(2)}),e.balance-=a,s.balance-=a,0===e.balance&&i++,0===s.balance&&o++}return n},B.dedupeByGlobalId=d,B.getRoundedBalance=b,B.getTotal=e=>T.getRoundedBalance(Object.values(e).reduce((e,t)=>e+(t.payedBy-t.payedFor),0));export{B as SplidClient}; //# sourceMappingURL=index.modern.js.map