@rushdb/javascript-sdk
Version:
RushDB Javascript SDK
2 lines (1 loc) • 29.1 kB
JavaScript
;var Te=Object.create;var L=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var xe=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:!0})},ae=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!Ie.call(n,s)&&s!==t&&L(n,s,{get:()=>e[s],enumerable:!(r=De(e,s))||r.enumerable});return n};var oe=(n,e,t)=>(t=n!=null?Te(be(n)):{},ae(e||!n||!n.__esModule?L(t,"default",{value:n,enumerable:!0}):t,n)),Oe=n=>ae(L({},"__esModule",{value:!0}),n);var He={};xe(He,{DBRecordInstance:()=>m,DBRecordsArrayInstance:()=>b,EmptyTargetError:()=>I,HttpClient:()=>O,HttpClientResponse:()=>N,Model:()=>ne,NonUniqueResultError:()=>v,RestAPI:()=>C,RushDB:()=>f,Transaction:()=>A,UniquenessError:()=>E,default:()=>Fe,extractMixedPropertiesFromToken:()=>re,idToDate:()=>te,idToTimestamp:()=>V,initSDK:()=>se,mergeDefaultsWithPayload:()=>M,parseConfig:()=>Z,pickUniqFieldsFromRecord:()=>K,pickUniqFieldsFromRecords:()=>X,validateInteger:()=>ee});module.exports=Oe(He);var O=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};O.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];O.TIMEOUT_ERROR_CODE="ETIMEDOUT";var $=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.")}},N=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 Y=oe(require("http"),1),Q=oe(require("https"),1);var Pe="string",Ee="datetime",Ae="boolean",Be="number",_e="null",qe="vector",ie=[Pe,Ee,Ae,Be,_e,qe];var de=Y.default||Y,pe=Q.default||Q,Ce=new de.Agent({keepAlive:!0}),je=new pe.Agent({keepAlive:!0}),W=class extends O{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){let i=new URL(e),d=s==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Ce:je),new Promise((p,l)=>{let h=(d?de:pe).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:r,path:i.pathname+i.search,port:i.port});h.setTimeout(o!=null?o:8e4,()=>{h.destroy(O.makeTimeoutError())}),h.on("response",y=>{p(new J(y))}),h.on("error",y=>{l(y)}),h.once("socket",y=>{let w=a?JSON.stringify(a):"";y.connecting?y.once(d?"connect":"secureConnect",()=>{h.write(w),h.end()}):(h.write(w),h.end())})})}},J=class extends ${constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,t)=>{let r="";this._res.setEncoding("utf8"),this._res.on("data",s=>{r+=s}),this._res.once("end",()=>{try{e(JSON.parse(r))}catch(s){t(s)}})})}};var R=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,T=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",j=n=>T(n)&&Object.keys(n).length===0,le=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function ke(n,e){let t={...n};return e.forEach(r=>{delete t[r]}),t}var k=n=>T(n)?ke(n,["__label","__id","__proptypes"]):n,_=n=>R(n)?n.map(_):T(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,_(t)])):n,z=n=>R(n)?n.every(le):le(n),U=n=>T(n)&&Object.values(n).every(z),P=n=>typeof n=="string",D=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return R(n)&&n.length===0||T(n)&&Object.keys(n).length===0?!1:!!n};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],he={initial:"in",extended:"ex",fullFeatured:"ff"};var E=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)}},I=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 M=async(n,e)=>{let t=Object.entries(n).map(async([a,o])=>o.default&&typeof o.default<"u"&&typeof e[a]>"u"?{key:a,value:typeof o.default=="function"?await o.default():o.default}:{key:a,value:void 0});return{...(await Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},K=(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),{}),X=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[o])=>(a[o]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in s)if(r[o]){if(r[o].includes(i))throw new E(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},Z=n=>{if(!n)return{};if(!T(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 ee(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function V(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function te(n){return new Date(V(n))}function re(n){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=n.match(e);if(!t)return[null,n];let[,r,s,a]=t,i=Object.entries(he).find(([h,y])=>y===r)[0],[d,c,p]=s.split("");return[{...{customDB:d==="1",managedDB:c==="1",selfHosted:p==="1",planType:i}},a]}var m=class{constructor(e={}){this.data=e}exists(){return D(this.data.__id)&&D(this.data.__label)}id(){if(!D(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(!D(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(!D(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 te(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return V(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!D(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await f.getInstance().records.deleteById(this.id(),e)}async update(e,t){if(!D(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return f.getInstance().records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!D(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return f.getInstance().records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!D(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return f.getInstance().records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!D(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return f.getInstance().records.detach({source:this.id(),target:e,options:t},r)}},b=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var Ue={"Content-Type":"application/json"},ge=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...a})=>{let o=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ue,...s},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var A=class{constructor(e){this.id=e}async rollback(){return await f.getInstance().tx.rollback(this.id)}async commit(){return await f.getInstance().tx.commit(this.id)}};var ye="api.rushdb.com";var ue="https",fe="/api/v1";var S=n=>n?{"x-transaction-id":n}:void 0,Me=n=>P(n)||n instanceof A,u=n=>Me(n)?n instanceof A?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),x=n=>{if(P(n)&&me(n))return n;if(n instanceof m&&n.data)return n.data.__id;if(T(n)&&"__id"in n&&me(n.__id))return n.__id},q=n=>!(!T(n)||T(n)&&"name"in n&&!P(n.name)||T(n)&&"type"in n&&(!P(n.type)||!ie.includes(n.type))||!("value"in n)||!z(n.value)||"metadata"in n&&!P(n.metadata)||"valueSeparator"in n&&!P(n.valueSeparator)),Se=n=>{let e=ue,t=ye,r=443,s=fe;if("url"in n){let o=new URL(n.url);e=o.protocol.replace(":",""),t=o.hostname,r=parseInt(o.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}`},g=(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 C=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:r},s)=>{var l,h;let a=u(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},S(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},detach:async({source:e,target:t,options:r},s)=>{var l,h;let a=u(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},S(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},create:async({label:e,data:t,options:r},s)=>{var l,h;let a=u(s),o="/records",i={headers:Object.assign({},S(a)),method:"POST",requestData:{}},d=typeof this.logger=="function"?g():"",c=k(_(t));if(R(c)&&c.every(q))i.requestData={label:e,properties:c,options:r};else if(U(c))i.requestData={label:e,data:c,options:r};else throw T(c)?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.");(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i});let p=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new m(p.data):new m},createMany:async(e,t)=>{var p,l,h;let r=R(e.data)?e.data:[e.data];if(!r.every(y=>U(y)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=u(t),o="/records/import/json",i={headers:Object.assign({},S(a)),method:"POST",requestData:{...e,data:r}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);if((l=this.logger)==null||l.call(this,{requestId:d,path:o,...i,responseData:c.data}),c!=null&&c.success&&(c!=null&&c.data)){let y=R(c.data)?(h=c.data)==null?void 0:h.map(w=>new m(w)):[];return new b(y,c.total)}return new b([])},importJson:async(e,t)=>{var h,y,w;let{data:r,options:s}=e,{label:a}=e,o=r;if(!a)if(T(r)&&!R(r)){let F=k(r),H=Object.keys(F);if(H.length===1)a=H[0],o=F[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 i=u(t),d="/records/import/json",c={headers:Object.assign({},S(i)),method:"POST",requestData:{label:a,data:o,options:s}},p=typeof this.logger=="function"?g():"";(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((y=this.logger)==null||y.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let F=R(l.data)?(w=l.data)==null?void 0:w.map(H=>new m(H)):[];return new b(F,l.total)}return new b([])},importCsv:async(e,t)=>{var d,c;let r=u(t),s="/records/import/csv",a={headers:Object.assign({},S(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=R(i.data)?i.data.map(l=>new m(l)):[];return new b(p,i.total)}return new b([])},delete:async(e,t)=>{var d,c,p;if(j(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new I("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=u(t),s="/records/delete",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},deleteById:async(e,t)=>{var c,p;let r=u(t),s=R(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},S(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d},export:async(e,t)=>{var d,c;let r=u(t),s="/records/export/csv",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var l,h;let{id:r,...s}=e,a=u(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},S(a)),method:"POST",requestData:s!=null?s:{}},d=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:c.data});let p=c.data.map(y=>new m(y));return new b(p,c.total,e)},findById:async(e,t)=>{var d,c;let r=u(t),s=R(e)?"/records":`/records/${e}`,a={headers:Object.assign({},S(r)),method:R(e)?"POST":"GET",requestData:R(e)?{ids:e}:void 0},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),R(e)){let p=i.data.map(l=>new m(l));return new b(p,i.total)}else return new m(i.data)},findOne:async(e,t)=>{var c,p;let r=u(t),s="/records/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);(p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data});let[d]=i.data;return new m(d)},findUniq:async(e,t)=>{var c,p;let r=u(t),s="/records/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new v(i.total,e);let[d]=i.data;return new m(d)},set:async({target:e,label:t,data:r,options:s},a)=>{var y,w;let o=u(a),d=`/records/${x(e)}`,c={headers:Object.assign({},S(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?g():"",l=k(_(r));if(R(l)&&l.every(q))c.requestData={label:t,properties:l};else if(U(l))c.requestData={label:t,data:l,options:s};else throw T(l)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:p,path:d,...c});let h=await this.fetcher(d,c);return(w=this.logger)==null||w.call(this,{requestId:p,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new m(h.data):new m},update:async({target:e,label:t,data:r,options:s},a)=>{var y,w;let o=u(a),d=`/records/${x(e)}`,c={headers:Object.assign({},S(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?g():"",l=k(_(r));if(R(l)&&l.every(q))c.requestData={label:t,properties:l};else if(U(l))c.requestData={label:t,data:l,options:s};else throw T(l)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:p,path:d,...c});let h=await this.fetcher(d,c);return(w=this.logger)==null||w.call(this,{requestId:p,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new m(h.data):new m},upsert:async({label:e,data:t,options:r},s)=>{var h,y,w;let a=u(s),o="/records",i={headers:Object.assign({},S(a)),method:"POST",requestData:{}},d=typeof this.logger=="function"?g():"",c=k(_(t)),p={...r,mergeBy:(h=r==null?void 0:r.mergeBy)!=null?h:[]};if(R(c)&&c.every(q))i.requestData={label:e,properties:c,options:p};else if(U(c))i.requestData={label:e,data:c,options:p};else throw T(c)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:d,path:o,...i});let l=await this.fetcher(o,i);return(w=this.logger)==null||w.call(this,{requestId:d,path:o,...i,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new m(l.data):new m}};this.relationships={createMany:async(e,t)=>{var d,c;let r=u(t),s="/relationships/create-many",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},deleteMany:async(e,t)=>{var d,c;let r=u(t),s="/relationships/delete-many",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var p,l;let r=u(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 o=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i,responseData:c.data}),c}};this.properties={delete:async(e,t)=>{var d,c;let r=u(t),s=`/properties/${e}`,a={headers:Object.assign({},S(r)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var d,c;let r=u(t),s="/properties/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},findById:async(e,t)=>{var d,c;let r=u(t),s=`/properties/${e}`,a={headers:Object.assign({},S(r)),method:"GET"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},values:async(e,t,r)=>{var c,p;let s=u(r),a=`/properties/${e}/values`,o={headers:Object.assign({},S(s)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.labels={find:async(e,t)=>{var d,c;let r=u(t),s="/labels/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let t="/tx",r={method:"POST",requestData:T(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:s,path:t,...r});let a=await this.fetcher(t,r);return(i=this.logger)==null||i.call(this,{requestId:s,path:t,...r,responseData:a.data}),new A(a.data.id)},commit:async e=>{var i,d;let r=`/tx/${u(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...s,responseData:o.data}),o},get:async e=>{var i,d;let r=`/tx/${u(e)}`,s={method:"GET"},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...s,responseData:o.data}),new A(o.data.id)},rollback:async e=>{var i,d;let r=`/tx/${u(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...s,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:r,path:e,...t});let s=await this.fetcher(e,t);return(o=this.logger)==null||o.call(this,{requestId:r,path:e,...t,responseData:s.data}),s}};this.query={raw:async({query:e,params:t},r)=>{var c,p;let s=u(r),a="/query/raw",o={headers:Object.assign({},S(s)),method:"POST",requestData:{query:e,params:t}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};if(this.fetcher=null,t!=null&&t.httpClient){let r=Se(t);this.fetcher=ge({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 m){let s=x(e);if(!s)throw new I(`${t} error: Target id is empty`);return[s]}if(R(e)&&e.every(s=>s instanceof m)){let s=e.map(x).filter(D);if(!s.length)throw new I(`${t} error: Target ids are empty`);return s}if(e instanceof b){let s=(r=e.data)==null?void 0:r.map(x).filter(D);if(!(s!=null&&s.length))throw new I(`${t} error: Target ids are empty`);return s}if(T(e)&&"__id"in e)return[e.__id];if(R(e)&&e.every(s=>T(s)&&"__id"in s)){let s=e.map(x).filter(D);if(!s.length)throw new I(`${t} error: Target ids are empty`);return s}return R(e)?e:P(e)?[e]:[]}};var Re,B=class B extends C{constructor(e,t){var a;let r=Z(t);super(e,{...r,httpClient:(a=r.httpClient)!=null?a:Re}),B.instance=this;let[s]=re(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={initialized:!0,debug:!1,timeout:ee("timeout",r==null?void 0:r.timeout,8e4),token:t,...s&&{serverSettings:s}}}static getInstance(){if(B.instance)return B.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return D(B.instance)}toDBRecordInstance(e){return new m(e)}};B.instance=null,B.state={initialized:!1,debug:!1,timeout:8e4};var f=B,se=n=>{Re=n};var ne=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async toDBRecordInstance(e){try{return f.getInstance().toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let r=e!=null?e:{};return f.getInstance().records.find({...r,labels:[this.label]},t)}async findOne(e,t){let r=e!=null?e:{};return f.getInstance().records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){let r=e!=null?e:{};return f.getInstance().records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var i;let r=await M(this.schema,e),s=K(this.schema,r),a=D(s),o=f.getInstance();if(a){let d=t!=null?t:await o.tx.begin(),c=await this.find({where:s},d),p=typeof t<"u";if(!((i=c==null?void 0:c.data)!=null&&i.length)){let h=await o.records.create({label:this.label,data:r},d);return p||await d.commit(),h}else throw p||await d.commit(),new E(this.label,s)}return await o.records.create({label:this.label,data:r},t)}async attach({source:e,target:t,options:r},s){return await f.getInstance().records.attach({source:e,target:t,options:r},s)}async detach({source:e,target:t,options:r},s){return await f.getInstance().records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var d,c;if(R(t)&&t.every(q))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=f.getInstance(),o=await M(this.schema,t),i=K(this.schema,o);if(!j(i)){let p=s!=null?s:await a.tx.begin(),l=await this.find({where:i},p),h=typeof s<"u";if(!((d=l==null?void 0:l.data)!=null&&d.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===x(e)){let w=await a.records[r]({target:e,label:this.label,data:o},p);return h||await p.commit(),w}else throw h||await p.commit(),new E(this.label,i)}return await a.records[r]({label:this.label,target:e,data:o},s)}async set(e,t,r){return await this.handleSetOrUpdate(e,t,"set",r)}async update(e,t,r){return await this.handleSetOrUpdate(e,t,"update",r)}async createMany(e,t){var o;let r=f.getInstance(),s=typeof t<"u",a=t!=null?t:await r.tx.begin();try{let i=await Promise.all(e.map(async p=>await M(this.schema,p))),d=X(i,this.schema,this.label);if(!j(d)){let p=Object.entries(d).map(([h,y])=>({[h]:{$in:y}})),l=await this.find({where:{$or:p}},a);if((o=l==null?void 0:l.data)!=null&&o.length)throw new E(this.label,Object.keys(d))}let c=await r.records.createMany({label:this.label,data:i},a);return s||await a.commit(),c}catch(i){throw s||await a.rollback(),i}}async delete(e,t){if(j(e.where))throw new I(`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 await f.getInstance().records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await f.getInstance().records.deleteById(e,t)}};se(new W);var Fe=f;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,extractMixedPropertiesFromToken,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});