UNPKG

@rushdb/javascript-sdk

Version:

RushDB Javascript SDK

2 lines (1 loc) 31 kB
var be=Object.defineProperty,De=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(n,e,t)=>e in n?be(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(W)for(var t of W(e))re.call(e,t)&&ee(n,t,e[t]);return n},g=(n,e)=>De(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&&W)for(var r of W(n))e.indexOf(r)<0&&re.call(n,r)&&(t[r]=n[r]);return t};var y=(n,e,t)=>new Promise((r,s)=>{var a=d=>{try{o(t.next(d))}catch(c){s(c)}},i=d=>{try{o(t.throw(d))}catch(c){s(c)}},o=d=>d.done?r(d.value):Promise.resolve(d.value).then(a,i);o((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 B=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,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}};B.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];B.TIMEOUT_ERROR_CODE="ETIMEDOUT";var N=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.")}},Y=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 K=class n extends B{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 a,i=new Promise((d,c)=>{a=setTimeout(()=>{a=null,c(B.makeTimeoutError())},s)}),o=e(t,r);return Promise.race([o,i]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>y(this,null,function*(){let a=new AbortController,i=setTimeout(()=>{i=null,a.abort(B.makeTimeoutError())},s);try{return yield e(t,g(p({},r),{signal:a.signal}))}catch(o){throw o.name==="AbortError"?B.makeTimeoutError():o}finally{i&&clearTimeout(i)}})}makeRequest(o,d){return y(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:i}){let c=r=="POST"||r=="PUT"||r=="PATCH",h=JSON.stringify(a)||(c?"":void 0),l=yield this._fetchFn(e,{body:h,headers:t,method:r},i!=null?i:8e4);return new Q(l)})}},Q=class n extends N{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 w=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,I=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",F=n=>I(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 H=n=>I(n)?Be(n,["__label","__id","__proptypes"]):n,v=n=>w(n)?n.map(v):I(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,v(t)])):n,z=n=>w(n)?n.every(ae):ae(n),M=n=>I(n)&&Object.values(n).every(z),C=n=>typeof n=="string",x=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return w(n)&&n.length===0||I(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 j=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)}},q=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 J=(n,e)=>y(void 0,null,function*(){let t=Object.entries(n).map(o=>y(void 0,[o],function*([a,i]){return i.default&&typeof i.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof i.default=="function"?yield i.default():i.default}:{key:a,value:void 0}})),s=(yield Promise.all(t)).reduce((a,{key:i,value:o})=>(o!==void 0&&(a[i]=o),a),{});return p(p({},s),e)}),Z=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.unique}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),ie=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[i])=>(a[i]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([i,o])=>{if(i in s)if(r[i]){if(r[i].includes(o))throw new j(t,{[i]:o});r[i]=[...r[i],o]}else r[i]=[o]})}),r},ce=n=>{if(!n)return{};if(!I(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,a]=t,o=Object.entries(oe).find(([m,u])=>u===r)[0],[d,c,h]=s.split("");return[p({},{customDB:d==="1",managedDB:c==="1",selfHosted:h==="1",planType:o}),a]}var D=class{constructor(e={}){this.data=e}exists(){return x(this.data.__id)&&x(this.data.__label)}id(){if(!x(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(!x(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(!x(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 y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield b.getInstance().records.deleteById(this.id(),e)})}update(e,t){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return b.getInstance().records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return b.getInstance().records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return b.getInstance().records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return b.getInstance().records.detach({source:this.id(),target:e,options:t},r)})}},E=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var qe={"Content-Type":"application/json"},he=({httpClient:n,token:e,url:t})=>(r,i)=>y(void 0,null,function*(){var o=i,{headers:s}=o,a=$(o,["headers"]);let d=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},qe),s),typeof e!="undefined"?{token:e}:{})},a));if(d.getStatusCode()>=200&&d.getStatusCode()<300)return yield d.toJSON();throw new Error(`${d.getStatusCode()}`)});var k=class{constructor(e){this.id=e}rollback(){return y(this,null,function*(){return yield b.getInstance().tx.rollback(this.id)})}commit(){return y(this,null,function*(){return yield b.getInstance().tx.commit(this.id)})}};var ye="api.rushdb.com";var ue="https",ge="/api/v1";var T=n=>n?{"x-transaction-id":n}:void 0,_e=n=>C(n)||n instanceof k,R=n=>_e(n)?n instanceof k?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),A=n=>{if(C(n)&&me(n))return n;if(n instanceof D&&n.data)return n.data.__id;if(I(n)&&"__id"in n&&me(n.__id))return n.__id},U=n=>!(!I(n)||I(n)&&"name"in n&&!C(n.name)||I(n)&&"type"in n&&(!C(n.type)||!se.includes(n.type))||!("value"in n)||!z(n.value)||"metadata"in n&&!C(n.metadata)||"valueSeparator"in n&&!C(n.valueSeparator)),fe=n=>{let e=ue,t=ye,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 a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${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 L=class{constructor(e,t){this.records={attach:(a,i)=>y(this,[a,i],function*({source:e,target:t,options:r},s){var u,f;let o=R(s),c=`/relationships/${A(e)}`,h={headers:Object.assign({},T(o)),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})},l=typeof this.logger=="function"?S():"";(u=this.logger)==null||u.call(this,p({requestId:l,path:c},h));let m=yield this.fetcher(c,h);return(f=this.logger)==null||f.call(this,g(p({requestId:l,path:c},h),{responseData:m.data})),m}),detach:(a,i)=>y(this,[a,i],function*({source:e,target:t,options:r},s){var u,f;let o=R(s),c=`/relationships/${A(e)}`,h={headers:Object.assign({},T(o)),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})},l=typeof this.logger=="function"?S():"";(u=this.logger)==null||u.call(this,p({requestId:l,path:c},h));let m=yield this.fetcher(c,h);return(f=this.logger)==null||f.call(this,g(p({requestId:l,path:c},h),{responseData:m.data})),m}),create:(a,i)=>y(this,[a,i],function*({label:e,data:t,options:r},s){var u,f;let o=R(s),d="/records",c={headers:Object.assign({},T(o)),method:"POST",requestData:{}},h=typeof this.logger=="function"?S():"",l=H(v(t));if(w(l)&&l.every(U))c.requestData={label:e,properties:l,options:r};else if(M(l))c.requestData={label:e,data:l,options:r};else throw I(l)?new Error("Provided data is not a flat object. Consider using the `importJson` method for nested objects or arrays of nested objects, or use `createMany` for arrays of flat objects."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,p({requestId:h,path:d},c));let m=yield this.fetcher(d,c);return(f=this.logger)==null||f.call(this,g(p({requestId:h,path:d},c),{responseData:m.data})),m!=null&&m.success&&(m!=null&&m.data)?new D(m.data):new D}),createMany:(e,t)=>y(this,null,function*(){var h,l,m;let r=w(e.data)?e.data:[e.data];if(!r.every(u=>M(u)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=R(t),i="/records/import/json",o={headers:Object.assign({},T(a)),method:"POST",requestData:g(p({},e),{data:r})},d=typeof this.logger=="function"?S():"";(h=this.logger)==null||h.call(this,p({requestId:d,path:i},o));let c=yield this.fetcher(i,o);if((l=this.logger)==null||l.call(this,g(p({requestId:d,path:i},o),{responseData:c.data})),c!=null&&c.success&&(c!=null&&c.data)){let u=w(c.data)?(m=c.data)==null?void 0:m.map(f=>new D(f)):[];return new E(u,c.total)}return new E([])}),importJson:(e,t)=>y(this,null,function*(){var m,u,f;let{data:r,options:s}=e,{label:a}=e,i=r;if(!a)if(I(r)&&!w(r)){let O=H(r),P=Object.keys(O);if(P.length===1)a=P[0],i=O[a];else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }")}else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }");let o=R(t),d="/records/import/json",c={headers:Object.assign({},T(o)),method:"POST",requestData:{label:a,data:i,options:s}},h=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:h,path:d},c));let l=yield this.fetcher(d,c);if((u=this.logger)==null||u.call(this,g(p({requestId:h,path:d},c),{responseData:l.data})),l!=null&&l.success&&(l!=null&&l.data)){let O=w(l.data)?(f=l.data)==null?void 0:f.map(P=>new D(P)):[];return new E(O,l.total)}return new E([])}),importCsv:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/records/import/csv",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o!=null&&o.success&&(o!=null&&o.data)){let h=w(o.data)?o.data.map(l=>new D(l)):[];return new E(h,o.total)}return new E([])}),delete:(e,t)=>y(this,null,function*(){var d,c,h;if(F(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new q("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",a={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},a));let o=yield this.fetcher(s,a);return(h=this.logger)==null||h.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),deleteById:(e,t)=>y(this,null,function*(){var c,h;let r=R(t),s=w(e),a=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},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:a},i));let d=yield this.fetcher(a,i);return(h=this.logger)==null||h.call(this,g(p({requestId:o,path:a},i),{responseData:d.data})),d}),export:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/records/export/csv",a={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},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var m,u;let l=e,{id:r}=l,s=$(l,["id"]),a=R(t),i=r?`/records/${r}/search`:"/records/search",o={headers:Object.assign({},T(a)),method:"POST",requestData:s!=null?s:{}},d=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:d,path:i},o));let c=yield this.fetcher(i,o);(u=this.logger)==null||u.call(this,g(p({requestId:d,path:i},o),{responseData:c.data}));let h=c.data.map(f=>new D(f));return new E(h,c.total,e)}),findById:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s=w(e)?"/records":`/records/${e}`,a={headers:Object.assign({},T(r)),method:w(e)?"POST":"GET",requestData:w(e)?{ids:e}:void 0},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),w(e)){let h=o.data.map(l=>new D(l));return new E(h,o.total)}else return new D(o.data)}),findOne:(e,t)=>y(this,null,function*(){var c,h;let r=R(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:g(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);(h=this.logger)==null||h.call(this,g(p({requestId:i,path:s},a),{responseData:o.data}));let[d]=o.data;return new D(d)}),findUniq:(e,t)=>y(this,null,function*(){var c,h;let r=R(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:g(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((h=this.logger)==null||h.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),typeof o.total!="undefined"&&o.total>1)throw new V(o.total,e);let[d]=o.data;return new D(d)}),set:(i,o)=>y(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var O,P;let d=R(a),h=`/records/${A(e)}`,l={headers:Object.assign({},T(d)),method:"PUT",requestData:{}},m=typeof this.logger=="function"?S():"",u=H(v(r));if(w(u)&&u.every(U))l.requestData={label:t,properties:u};else if(M(u))l.requestData={label:t,data:u,options:s};else throw I(u)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(O=this.logger)==null||O.call(this,p({requestId:m,path:h},l));let f=yield this.fetcher(h,l);return(P=this.logger)==null||P.call(this,g(p({requestId:m,path:h},l),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D}),update:(i,o)=>y(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var O,P;let d=R(a),h=`/records/${A(e)}`,l={headers:Object.assign({},T(d)),method:"PATCH",requestData:{}},m=typeof this.logger=="function"?S():"",u=H(v(r));if(w(u)&&u.every(U))l.requestData={label:t,properties:u};else if(M(u))l.requestData={label:t,data:u,options:s};else throw I(u)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(O=this.logger)==null||O.call(this,p({requestId:m,path:h},l));let f=yield this.fetcher(h,l);return(P=this.logger)==null||P.call(this,g(p({requestId:m,path:h},l),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D}),upsert:(a,i)=>y(this,[a,i],function*({label:e,data:t,options:r},s){var f,O,P;let o=R(s),d="/records",c={headers:Object.assign({},T(o)),method:"POST",requestData:{}},h=typeof this.logger=="function"?S():"",l=H(v(t)),m=g(p({},r),{mergeBy:(f=r==null?void 0:r.mergeBy)!=null?f:[]});if(w(l)&&l.every(U))c.requestData={label:e,properties:l,options:m};else if(M(l))c.requestData={label:e,data:l,options:m};else throw I(l)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(O=this.logger)==null||O.call(this,p({requestId:h,path:d},c));let u=yield this.fetcher(d,c);return(P=this.logger)==null||P.call(this,g(p({requestId:h,path:d},c),{responseData:u.data})),u!=null&&u.success&&(u!=null&&u.data)?new D(u.data):new D})};this.relationships={createMany:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/relationships/create-many",a={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},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),deleteMany:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/relationships/delete-many",a={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},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var h,l;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():""}`,o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},d=typeof this.logger=="function"?S():"";(h=this.logger)==null||h.call(this,p({requestId:d,path:i},o));let c=yield this.fetcher(i,o);return(l=this.logger)==null||l.call(this,g(p({requestId:d,path:i},o),{responseData:c.data})),c})};this.properties={delete:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"DELETE"},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/properties/search",a={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},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),findById:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"GET"},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),values:(e,t,r)=>y(this,null,function*(){var c,h;let s=R(r),a=`/properties/${e}/values`,i={headers:Object.assign({},T(s)),method:"POST",requestData:t!=null?t:{}},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:a},i));let d=yield this.fetcher(a,i);return(h=this.logger)==null||h.call(this,g(p({requestId:o,path:a},i),{responseData:d.data})),d})};this.labels={find:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/labels/search",a={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},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o})};this.tx={begin:e=>y(this,null,function*(){var i,o;let t="/tx",r={method:"POST",requestData:I(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 a=yield this.fetcher(t,r);return(o=this.logger)==null||o.call(this,g(p({requestId:s,path:t},r),{responseData:a.data})),new k(a.data.id)}),commit:e=>y(this,null,function*(){var o,d;let r=`/tx/${R(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(d=this.logger)==null||d.call(this,g(p({requestId:a,path:r},s),{responseData:i.data})),i}),get:e=>y(this,null,function*(){var o,d;let r=`/tx/${R(e)}`,s={method:"GET"},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(d=this.logger)==null||d.call(this,g(p({requestId:a,path:r},s),{responseData:i.data})),new k(i.data.id)}),rollback:e=>y(this,null,function*(){var o,d;let r=`/tx/${R(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(d=this.logger)==null||d.call(this,g(p({requestId:a,path:r},s),{responseData:i.data})),i})};this.settings={get:()=>y(this,null,function*(){var a,i;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:r,path:e},t));let s=yield this.fetcher(e,t);return(i=this.logger)==null||i.call(this,g(p({requestId:r,path:e},t),{responseData:s.data})),s})};this.query={raw:(s,a)=>y(this,[s,a],function*({query:e,params:t},r){var l,m;let i=R(r),o="/query/raw",d={headers:Object.assign({},T(i)),method:"POST",requestData:{query:e,params:t}},c=typeof this.logger=="function"?S():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:o},d));let h=yield this.fetcher(o,d);return(m=this.logger)==null||m.call(this,g(p({requestId:c,path:o},d),{responseData:h.data})),h})};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=A(e);if(!s)throw new q(`${t} error: Target id is empty`);return[s]}if(w(e)&&e.every(s=>s instanceof D)){let s=e.map(A).filter(x);if(!s.length)throw new q(`${t} error: Target ids are empty`);return s}if(e instanceof E){let s=(r=e.data)==null?void 0:r.map(A).filter(x);if(!(s!=null&&s.length))throw new q(`${t} error: Target ids are empty`);return s}if(I(e)&&"__id"in e)return[e.__id];if(w(e)&&e.every(s=>I(s)&&"__id"in s)){let s=e.map(A).filter(x);if(!s.length)throw new q(`${t} error: Target ids are empty`);return s}return w(e)?e:C(e)?[e]:[]}};var Se,_=class _ extends L{constructor(e,t){var a;let r=ce(t);super(e,g(p({},r),{httpClient:(a=r.httpClient)!=null?a:Se})),_.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;_.state=p({initialized:!0,debug:!1,timeout:de("timeout",r==null?void 0:r.timeout,8e4),token:t},s&&{serverSettings:s})}static getInstance(){if(_.instance)return _.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return x(_.instance)}toDBRecordInstance(e){return new D(e)}};_.instance=null,_.state={initialized:!1,debug:!1,timeout:8e4};var b=_,Re=n=>{Se=n};var Te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}toDBRecordInstance(e){return y(this,null,function*(){try{return b.getInstance().toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return y(this,null,function*(){let r=e!=null?e:{};return b.getInstance().records.find(g(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return y(this,null,function*(){let r=e!=null?e:{};return b.getInstance().records.findOne(g(p({},r),{labels:[this.label]}),t)})}findById(e,t){return y(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return y(this,null,function*(){let r=e!=null?e:{};return b.getInstance().records.findUniq(g(p({},r),{labels:[this.label]}),t)})}create(e,t){return y(this,null,function*(){var o;let r=yield J(this.schema,e),s=Z(this.schema,r),a=x(s),i=b.getInstance();if(a){let d=t!=null?t:yield i.tx.begin(),c=yield this.find({where:s},d),h=typeof t!="undefined";if(!((o=c==null?void 0:c.data)!=null&&o.length)){let m=yield i.records.create({label:this.label,data:r},d);return h||(yield d.commit()),m}else throw h||(yield d.commit()),new j(this.label,s)}return yield i.records.create({label:this.label,data:r},t)})}attach(a,i){return y(this,arguments,function*({source:e,target:t,options:r},s){return yield b.getInstance().records.attach({source:e,target:t,options:r},s)})}detach(a,i){return y(this,arguments,function*({source:e,target:t,options:r},s){return yield b.getInstance().records.detach({source:e,target:t,options:r},s)})}handleSetOrUpdate(e,t,r,s){return y(this,null,function*(){var d,c;if(w(t)&&t.every(U))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=b.getInstance(),i=yield J(this.schema,t),o=Z(this.schema,i);if(!F(o)){let h=s!=null?s:yield a.tx.begin(),l=yield this.find({where:o},h),m=typeof s!="undefined";if(!((d=l==null?void 0:l.data)!=null&&d.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===A(e)){let f=yield a.records[r]({target:e,label:this.label,data:i},h);return m||(yield h.commit()),f}else throw m||(yield h.commit()),new j(this.label,o)}return yield a.records[r]({label:this.label,target:e,data:i},s)})}set(e,t,r){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return y(this,null,function*(){var i;let r=b.getInstance(),s=typeof t!="undefined",a=t!=null?t:yield r.tx.begin();try{let o=yield Promise.all(e.map(h=>y(this,null,function*(){return yield J(this.schema,h)}))),d=ie(o,this.schema,this.label);if(!F(d)){let h=Object.entries(d).map(([m,u])=>({[m]:{$in:u}})),l=yield this.find({where:{$or:h}},a);if((i=l==null?void 0:l.data)!=null&&i.length)throw new j(this.label,Object.keys(d))}let c=yield r.records.createMany({label:this.label,data:o},a);return s||(yield a.commit()),c}catch(o){throw s||(yield a.rollback()),o}})}delete(e,t){return y(this,null,function*(){if(F(e.where))throw new q(`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 b.getInstance().records.delete(g(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return y(this,null,function*(){return yield b.getInstance().records.deleteById(e,t)})}};Re(new K);var Ht=b;export{D as DBRecordInstance,E as DBRecordsArrayInstance,q as EmptyTargetError,B as HttpClient,Y as HttpClientResponse,Te as Model,V as NonUniqueResultError,L as RestAPI,b as RushDB,k as Transaction,j as UniquenessError,Ht as default,le as extractMixedPropertiesFromToken,pe as idToDate,X as idToTimestamp,Re as initSDK,J as mergeDefaultsWithPayload,ce as parseConfig,Z as pickUniqFieldsFromRecord,ie as pickUniqFieldsFromRecords,de as validateInteger};