UNPKG

@rushdb/javascript-sdk

Version:

RushDB Javascript SDK

2 lines (1 loc) 29.2 kB
var De=Object.defineProperty,be=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(n,e,t)=>e in n?De(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(n,t,e[t]);if(M)for(var t of M(e))re.call(e,t)&&ee(n,t,e[t]);return n},y=(n,e)=>be(n,we(e));var $=(n,e)=>{var t={};for(var r in n)te.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&M)for(var r of M(n))e.indexOf(r)<0&&re.call(n,r)&&(t[r]=n[r]);return t};var h=(n,e,t)=>new Promise((r,s)=>{var o=c=>{try{a(t.next(c))}catch(d){s(d)}},i=c=>{try{a(t.throw(c))}catch(d){s(d)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,i);a((t=t.apply(n,e)).next())});var Ie="string",xe="datetime",Oe="boolean",Pe="number",Ee="null",Ae="vector",se=[Ie,xe,Oe,Pe,Ee,Ae];var P=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:i}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};P.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];P.TIMEOUT_ERROR_CODE="ETIMEDOUT";var L=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},Q=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var W=class n extends P{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=n.makeFetchWithAbortTimeout(e):this._fetchFn=n.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,s)=>{let o,i=new Promise((c,d)=>{o=setTimeout(()=>{o=null,d(P.makeTimeoutError())},s)}),a=e(t,r);return Promise.race([a,i]).finally(()=>{o&&clearTimeout(o)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>h(this,null,function*(){let o=new AbortController,i=setTimeout(()=>{i=null,o.abort(P.makeTimeoutError())},s);try{return yield e(t,y(p({},r),{signal:o.signal}))}catch(a){throw a.name==="AbortError"?P.makeTimeoutError():a}finally{i&&clearTimeout(i)}})}makeRequest(a,c){return h(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:o,timeout:i}){let d=r=="POST"||r=="PUT"||r=="PATCH",l=JSON.stringify(o)||(d?"":void 0),u=yield this._fetchFn(e,{body:l,headers:t,method:r},i!=null?i:8e4);return new z(u)})}},z=class n extends L{constructor(e){super(e.status,n._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var b=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,w=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",k=n=>w(n)&&Object.keys(n).length===0,ae=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function Be(n,e){let t=p({},n);return e.forEach(r=>{delete t[r]}),t}var N=n=>w(n)?Be(n,["__label","__id","__proptypes"]):n,j=n=>b(n)?n.map(j):w(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,j(t)])):n,J=n=>b(n)?n.every(ae):ae(n),K=n=>w(n)&&Object.values(n).every(J),C=n=>typeof n=="string",I=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return b(n)&&n.length===0||w(n)&&Object.keys(n).length===0?!1:!!n};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],oe={initial:"in",extended:"ex",fullFeatured:"ff"};var _=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},E=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},V=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var Y=(n,e)=>h(void 0,null,function*(){let t=Object.entries(n).map(a=>h(void 0,[a],function*([o,i]){return i.default&&typeof i.default!="undefined"&&typeof e[o]=="undefined"?{key:o,value:typeof i.default=="function"?yield i.default():i.default}:{key:o,value:void 0}})),s=(yield Promise.all(t)).reduce((o,{key:i,value:a})=>(a!==void 0&&(o[i]=a),o),{});return p(p({},s),e)}),Z=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.uniq}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),ie=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,o])=>o.uniq).reduce((o,[i])=>(o[i]=!0,o),{});return n.forEach(o=>{Object.entries(o).forEach(([i,a])=>{if(i in s)if(r[i]){if(r[i].includes(a))throw new _(t,{[i]:a});r[i]=[...r[i],a]}else r[i]=[a]})}),r},ce=n=>{if(!n)return{};if(!w(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return n};function de(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function X(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function pe(n){return new Date(X(n))}function le(n){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=n.match(e);if(!t)return[null,n];let[,r,s,o]=t,a=Object.entries(oe).find(([g,m])=>m===r)[0],[c,d,l]=s.split("");return[p({},{customDB:c==="1",managedDB:d==="1",selfHosted:l==="1",planType:a}),o]}var D=class{constructor(e={}){this.data=e}exists(){return I(this.data.__id)&&I(this.data.__label)}id(){if(!I(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!I(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!I(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return pe(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return X(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield x.init().records.deleteById(this.id(),e)})}update(e,t){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return x.init().records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return x.init().records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return x.init().records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return x.init().records.detach({source:this.id(),target:e,options:t},r)})}},A=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var Ce={"Content-Type":"application/json"},he=({httpClient:n,token:e,url:t})=>(r,i)=>h(void 0,null,function*(){var a=i,{headers:s}=a,o=$(a,["headers"]);let c=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},Ce),s),typeof e!="undefined"?{token:e}:{})},o));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var q=class{constructor(e){this.id=e}rollback(){return h(this,null,function*(){return yield x.init().tx.rollback(this.id)})}commit(){return h(this,null,function*(){return yield x.init().tx.commit(this.id)})}};var ue="api.rushdb.com";var ye="https",ge="/api/v1";var T=n=>n?{"x-transaction-id":n}:void 0,qe=n=>C(n)||n instanceof q,R=n=>qe(n)?n instanceof q?n.id:n:void 0,me=n=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(n),O=n=>{if(C(n)&&me(n))return n;if(n instanceof D&&n.data)return n.data.__id;if(w(n)&&"__id"in n&&me(n.__id))return n.__id},U=n=>!(!w(n)||w(n)&&"name"in n&&!C(n.name)||w(n)&&"type"in n&&(!C(n.type)||!se.includes(n.type))||!("value"in n)||!J(n.value)||"metadata"in n&&!C(n.metadata)||"valueSeparator"in n&&!C(n.valueSeparator)),fe=n=>{let e=ye,t=ue,r=443,s=ge;if("url"in n){let i=new URL(n.url);e=i.protocol.replace(":",""),t=i.hostname,r=parseInt(i.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let o="";return e==="http"&&r===80||e==="https"&&r===443||(o=":"+r),`${e}://${t}${o}${s}`},S=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var H=class{constructor(e,t){this.records={attach:(o,i)=>h(this,[o,i],function*({source:e,target:t,options:r},s){var m,f;let a=R(s),d=`/relationships/${O(e)}`,l={headers:Object.assign({},T(a)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:u,path:d},l));let g=yield this.fetcher(d,l);return(f=this.logger)==null||f.call(this,y(p({requestId:u,path:d},l),{responseData:g.data})),g}),detach:(o,i)=>h(this,[o,i],function*({source:e,target:t,options:r},s){var m,f;let a=R(s),d=`/relationships/${O(e)}`,l={headers:Object.assign({},T(a)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:u,path:d},l));let g=yield this.fetcher(d,l);return(f=this.logger)==null||f.call(this,y(p({requestId:u,path:d},l),{responseData:g.data})),g}),create:(o,i)=>h(this,[o,i],function*({label:e,data:t,options:r},s){var m,f;let a=R(s),c="/records",d={headers:Object.assign({},T(a)),method:"POST",requestData:{}},l=typeof this.logger=="function"?S():"",u=N(j(t));if(b(u)&&u.every(U))d.requestData={label:e,properties:u};else if(K(u))d.requestData={label:e,data:u,options:r};else throw w(u)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(m=this.logger)==null||m.call(this,p({requestId:l,path:c},d));let g=yield this.fetcher(c,d);return(f=this.logger)==null||f.call(this,y(p({requestId:l,path:c},d),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new D(g.data):new D}),createMany:(e,t)=>h(this,null,function*(){var c,d,l;let r=R(t),s="/records/import/json",o={headers:Object.assign({},T(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a!=null&&a.success&&(a!=null&&a.data)){let u=b(a.data)?(l=a.data)==null?void 0:l.map(g=>new D(g)):[];return new A(u,a.total)}return new A([])}),importCsv:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s="/records/import/csv",o={headers:Object.assign({},T(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a!=null&&a.success&&(a!=null&&a.data)){let l=b(a.data)?a.data.map(u=>new D(u)):[];return new A(l,a.total)}return new A([])}),delete:(e,t)=>h(this,null,function*(){var c,d,l;if(k(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new E("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=R(t),s="/records/delete",o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(l=this.logger)==null||l.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a}),deleteById:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),s=b(e),o=s?"/records/delete":`/records/${e}`,i={headers:Object.assign({},T(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},a=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:a,path:o},i));let c=yield this.fetcher(o,i);return(l=this.logger)==null||l.call(this,y(p({requestId:a,path:o},i),{responseData:c.data})),c}),export:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s="/records/export/csv",o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a}),find:(e,t)=>h(this,null,function*(){var g,m;let u=e,{id:r}=u,s=$(u,["id"]),o=R(t),i=r?`/records/${r}/search`:"/records/search",a={headers:Object.assign({},T(o)),method:"POST",requestData:s!=null?s:{}},c=typeof this.logger=="function"?S():"";(g=this.logger)==null||g.call(this,p({requestId:c,path:i},a));let d=yield this.fetcher(i,a);(m=this.logger)==null||m.call(this,y(p({requestId:c,path:i},a),{responseData:d.data}));let l=d.data.map(f=>new D(f));return new A(l,d.total,e)}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s=b(e)?"/records":`/records/${e}`,o={headers:Object.assign({},T(r)),method:b(e)?"POST":"GET",requestData:b(e)?{ids:e}:void 0},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),b(e)){let l=a.data.map(u=>new D(u));return new A(l,a.total)}else return new D(a.data)}),findOne:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),s="/records/search",o={headers:Object.assign({},T(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);(l=this.logger)==null||l.call(this,y(p({requestId:i,path:s},o),{responseData:a.data}));let[c]=a.data;return new D(c)}),findUniq:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),s="/records/search",o={headers:Object.assign({},T(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);if((l=this.logger)==null||l.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),typeof a.total!="undefined"&&a.total>1)throw new V(a.total,e);let[c]=a.data;return new D(c)}),set:(i,a)=>h(this,[i,a],function*({target:e,label:t,data:r,options:s},o){var F,v;let c=R(o),l=`/records/${O(e)}`,u={headers:Object.assign({},T(c)),method:"PUT",requestData:{}},g=typeof this.logger=="function"?S():"",m=N(j(r));if(b(m)&&m.every(U))u.requestData={label:t,properties:m};else if(K(m))u.requestData={label:t,data:m,options:s};else throw w(m)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:g,path:l},u));let f=yield this.fetcher(l,u);return(v=this.logger)==null||v.call(this,y(p({requestId:g,path:l},u),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D}),update:(i,a)=>h(this,[i,a],function*({target:e,label:t,data:r,options:s},o){var F,v;let c=R(o),l=`/records/${O(e)}`,u={headers:Object.assign({},T(c)),method:"PATCH",requestData:{}},g=typeof this.logger=="function"?S():"",m=N(j(r));if(b(m)&&m.every(U))u.requestData={label:t,properties:m};else if(K(m))u.requestData={label:t,data:m,options:s};else throw w(m)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:g,path:l},u));let f=yield this.fetcher(l,u);return(v=this.logger)==null||v.call(this,y(p({requestId:g,path:l},u),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D})};this.relationships={createMany:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s="/relationships/create-many",o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a}),deleteMany:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s="/relationships/delete-many",o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a}),find:(e,t)=>h(this,null,function*(){var l,u;let r=R(t),s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&s.append("skip",e.skip.toString());let i=`/relationships/search${s.toString()?"?"+s.toString():""}`,a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?S():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:i},a));let d=yield this.fetcher(i,a);return(u=this.logger)==null||u.call(this,y(p({requestId:c,path:i},a),{responseData:d.data})),d})};this.properties={delete:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s=`/properties/${e}`,o={headers:Object.assign({},T(r)),method:"DELETE"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a}),find:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s="/properties/search",o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s=`/properties/${e}`,o={headers:Object.assign({},T(r)),method:"GET"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a}),values:(e,t,r)=>h(this,null,function*(){var d,l;let s=R(r),o=`/properties/${e}/values`,i={headers:Object.assign({},T(s)),method:"POST",requestData:t!=null?t:{}},a=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:a,path:o},i));let c=yield this.fetcher(o,i);return(l=this.logger)==null||l.call(this,y(p({requestId:a,path:o},i),{responseData:c.data})),c})};this.labels={find:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),s="/labels/search",o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},o));let a=yield this.fetcher(s,o);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:s},o),{responseData:a.data})),a})};this.tx={begin:e=>h(this,null,function*(){var i,a;let t="/tx",r={method:"POST",requestData:w(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:s,path:t},r));let o=yield this.fetcher(t,r);return(a=this.logger)==null||a.call(this,y(p({requestId:s,path:t},r),{responseData:o.data})),new q(o.data.id)}),commit:e=>h(this,null,function*(){var a,c;let r=`/tx/${R(e)}/commit`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:o,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,y(p({requestId:o,path:r},s),{responseData:i.data})),i}),get:e=>h(this,null,function*(){var a,c;let r=`/tx/${R(e)}`,s={method:"GET"},o=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:o,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,y(p({requestId:o,path:r},s),{responseData:i.data})),new q(i.data.id)}),rollback:e=>h(this,null,function*(){var a,c;let r=`/tx/${R(e)}/rollback`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:o,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,y(p({requestId:o,path:r},s),{responseData:i.data})),i})};this.settings={get:()=>h(this,null,function*(){var o,i;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:r,path:e},t));let s=yield this.fetcher(e,t);return(i=this.logger)==null||i.call(this,y(p({requestId:r,path:e},t),{responseData:s.data})),s})};this.query={raw:(s,o)=>h(this,[s,o],function*({query:e,params:t},r){var u,g;let i=R(r),a="/query/raw",c={headers:Object.assign({},T(i)),method:"POST",requestData:{query:e,params:t}},d=typeof this.logger=="function"?S():"";(u=this.logger)==null||u.call(this,p({requestId:d,path:a},c));let l=yield this.fetcher(a,c);return(g=this.logger)==null||g.call(this,y(p({requestId:d,path:a},c),{responseData:l.data})),l})};if(this.fetcher=null,t!=null&&t.httpClient){let r=fe(t);this.fetcher=he({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof D){let s=O(e);if(!s)throw new E(`${t} error: Target id is empty`);return[s]}if(b(e)&&e.every(s=>s instanceof D)){let s=e.map(O).filter(I);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}if(e instanceof A){let s=(r=e.data)==null?void 0:r.map(O).filter(I);if(!(s!=null&&s.length))throw new E(`${t} error: Target ids are empty`);return s}if(w(e)&&"__id"in e)return[e.__id];if(b(e)&&e.every(s=>w(s)&&"__id"in s)){let s=e.map(O).filter(I);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}return b(e)?e:C(e)?[e]:[]}};var Se,B=class B extends H{constructor(e,t){var o;let r=ce(t);super(e,y(p({},r),{httpClient:(o=r.httpClient)!=null?o:Se})),B.instance=this;let[s]=le(e!=null?e:"");this.initializeSync(s,e,r)}initializeSync(e,t,r){let s=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;B.state=p({initialized:!0,debug:!1,timeout:de("timeout",r==null?void 0:r.timeout,8e4),token:t},s&&{serverSettings:s})}static init(){if(B.instance)return B.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return B.instance}static isInitialized(){return B.instance!==null}toDBRecordInstance(e){return new D(e)}};B.instance=null,B.state={initialized:!1,debug:!1,timeout:8e4};var x=B,Re=n=>{Se=n};var Te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}getRushDBInstance(){return h(this,null,function*(){if(x.getInstance())return x.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')})}toDBRecordInstance(e){return h(this,null,function*(){try{return(yield this.getRushDBInstance()).toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.find(y(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findOne(y(p({},r),{labels:[this.label]}),t)})}findById(e,t){return h(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findUniq(y(p({},r),{labels:[this.label]}),t)})}create(e,t){return h(this,null,function*(){var a;let r=yield Y(this.schema,e),s=Z(this.schema,r),o=I(s),i=yield this.getRushDBInstance();if(o){let c=t!=null?t:yield i.tx.begin(),d=yield this.find({where:s},c),l=typeof t!="undefined";if(!((a=d==null?void 0:d.data)!=null&&a.length)){let g=yield i.records.create({label:this.label,data:r},c);return l||(yield c.commit()),g}else throw l||(yield c.commit()),new _(this.label,s)}return yield i.records.create({label:this.label,data:r},t)})}attach(o,i){return h(this,arguments,function*({source:e,target:t,options:r},s){return yield(yield this.getRushDBInstance()).records.attach({source:e,target:t,options:r},s)})}detach(o,i){return h(this,arguments,function*({source:e,target:t,options:r},s){return yield(yield this.getRushDBInstance()).records.detach({source:e,target:t,options:r},s)})}handleSetOrUpdate(e,t,r,s){return h(this,null,function*(){var c,d;if(b(t)&&t.every(U))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let o=yield this.getRushDBInstance(),i=yield Y(this.schema,t),a=Z(this.schema,i);if(!k(a)){let l=s!=null?s:yield o.tx.begin(),u=yield this.find({where:a},l),g=typeof s!="undefined";if(!((c=u==null?void 0:u.data)!=null&&c.length)||u.data.length===1&&((d=u.data[0])==null?void 0:d.id())===O(e)){let f=yield o.records[r]({target:e,label:this.label,data:i},l);return g||(yield l.commit()),f}else throw g||(yield l.commit()),new _(this.label,a)}return yield o.records[r]({label:this.label,target:e,data:i},s)})}set(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return h(this,null,function*(){var i;let r=yield this.getRushDBInstance(),s=typeof t!="undefined",o=t!=null?t:yield r.tx.begin();try{let a=yield Promise.all(e.map(l=>h(this,null,function*(){return yield Y(this.schema,l)}))),c=ie(a,this.schema,this.label);if(!k(c)){let l=Object.entries(c).map(([g,m])=>({[g]:{$in:m}})),u=yield this.find({where:{$or:l}},o);if((i=u==null?void 0:u.data)!=null&&i.length)throw new _(this.label,Object.keys(c))}let d=yield r.records.createMany({label:this.label,data:a},o);return s||(yield o.commit()),d}catch(a){throw s||(yield o.rollback()),a}})}delete(e,t){return h(this,null,function*(){if(k(e.where))throw new E(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield(yield this.getRushDBInstance()).records.delete(y(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return h(this,null,function*(){return yield(yield this.getRushDBInstance()).records.deleteById(e,t)})}};Re(new W);var Ft=x;export{D as DBRecordInstance,A as DBRecordsArrayInstance,E as EmptyTargetError,P as HttpClient,Q as HttpClientResponse,Te as Model,V as NonUniqueResultError,H as RestAPI,x as RushDB,q as Transaction,_ as UniquenessError,Ft as default,le as extractMixedPropertiesFromToken,pe as idToDate,X as idToTimestamp,Re as initSDK,Y as mergeDefaultsWithPayload,ce as parseConfig,Z as pickUniqFieldsFromRecord,ie as pickUniqFieldsFromRecords,de as validateInteger};