UNPKG

@rushdb/javascript-sdk

Version:

RushDB Javascript SDK

2 lines (1 loc) 25.9 kB
"use strict";var me=Object.create;var v=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var we=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:!0})},re=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Se(e))!Te.call(n,s)&&s!==t&&v(n,s,{get:()=>e[s],enumerable:!(r=fe(e,s))||r.enumerable});return n};var se=(n,e,t)=>(t=n!=null?me(Re(n)):{},re(e||!n||!n.__esModule?v(t,"default",{value:n,enumerable:!0}):t,n)),De=n=>re(v({},"__esModule",{value:!0}),n);var ke={};we(ke,{DBRecordInstance:()=>g,DBRecordsArrayInstance:()=>A,EmptyTargetError:()=>b,HttpClient:()=>O,HttpClientResponse:()=>H,Model:()=>te,NonUniqueResultError:()=>U,RestAPI:()=>_,RushDB:()=>D,Transaction:()=>B,UniquenessError:()=>E,default:()=>Ue,idToDate:()=>Z,idToTimestamp:()=>K,initSDK:()=>ee,mergeDefaultsWithPayload:()=>k,parseConfig:()=>G,pickUniqFieldsFromRecord:()=>N,pickUniqFieldsFromRecords:()=>J,validateInteger:()=>X});module.exports=De(ke);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 F=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.")}},H=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 z=se(require("http"),1),Y=se(require("https"),1);var be="string",Ie="datetime",xe="boolean",Oe="number",Pe="null",Ee="vector",ne=[be,Ie,xe,Oe,Pe,Ee];var oe=z.default||z,ie=Y.default||Y,Ae=new oe.Agent({keepAlive:!0}),Be=new ie.Agent({keepAlive:!0}),M=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),c=s==="http"||i.protocol==="http:",d=this._agent;return d||(d=c?Ae:Be),new Promise((p,h)=>{let l=(c?oe:ie).request({agent:d,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:r,path:i.pathname+i.search,port:i.port});l.setTimeout(o!=null?o:8e4,()=>{l.destroy(O.makeTimeoutError())}),l.on("response",S=>{p(new W(S))}),l.on("error",S=>{h(S)}),l.once("socket",S=>{let x=a?JSON.stringify(a):"";S.connecting?S.once(c?"connect":"secureConnect",()=>{l.write(x),l.end()}):(l.write(x),l.end())})})}},W=class extends F{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 T=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,R=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",q=n=>R(n)&&Object.keys(n).length===0,ce=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function _e(n,e){let t={...n};return e.forEach(r=>{delete t[r]}),t}var L=n=>R(n)?_e(n,["__label","__id","__proptypes"]):n,C=n=>T(n)?n.map(C):R(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,C(t)])):n,Q=n=>T(n)?n.every(ce):ce(n),$=n=>R(n)&&Object.values(n).every(Q),P=n=>typeof n=="string",w=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return T(n)&&n.length===0||R(n)&&Object.keys(n).length===0?!1:!!n};var V=["httpClient","timeout","host","port","protocol","url","logger","options"];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)}},b=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},U=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 k=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}},N=(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),{}),J=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.uniq).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},G=n=>{if(!n)return{};if(!R(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!V.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${V.join(", ")}`);return n};function X(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function K(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function Z(n){return new Date(K(n))}var g=class{constructor(e={}){this.data=e}exists(){return w(this.data.__id)&&w(this.data.__label)}id(){if(!w(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(!w(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(!w(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 Z(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return K(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!w(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await(await D.init()).records.deleteById(this.id(),e)}async update(e,t){if(!w(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return(await D.init()).records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!w(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return(await D.init()).records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!w(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return(await D.init()).records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!w(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return(await D.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"},de=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...a})=>{let o=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ce,...s},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var B=class{constructor(e){this.id=e}async rollback(){return await(await D.init()).tx.rollback(this.id)}async commit(){return await(await D.init()).tx.commit(this.id)}};var pe="api.rushdb.com";var le="https",he="/api/v1";var f=n=>n?{"x-transaction-id":n}:void 0,je=n=>P(n)||n instanceof B,y=n=>je(n)?n instanceof B?n.id:n:void 0,ue=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),I=n=>{if(P(n)&&ue(n))return n;if(n instanceof g&&n.data)return n.data.__id;if(R(n)&&"__id"in n&&ue(n.__id))return n.__id},j=n=>!(!R(n)||R(n)&&"name"in n&&!P(n.name)||R(n)&&"type"in n&&(!P(n.type)||!ne.includes(n.type))||!("value"in n)||!Q(n.value)||"metadata"in n&&!P(n.metadata)||"valueSeparator"in n&&!P(n.valueSeparator)),ye=n=>{let e=le,t=pe,r=443,s=he;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}`},u=(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 _=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:r},s)=>{var h,l;let a=y(s),i=`/relationships/${I(e)}`,c={headers:Object.assign({},f(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}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},detach:async({source:e,target:t,options:r},s)=>{var h,l;let a=y(s),i=`/relationships/${I(e)}`,c={headers:Object.assign({},f(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}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},create:async({label:e,data:t,options:r},s)=>{var h,l;let a=y(s),o="/records",i={headers:Object.assign({},f(a)),method:"POST",requestData:{}},c=typeof this.logger=="function"?u():"",d=L(C(t));if(T(d)&&d.every(j))i.requestData={label:e,properties:d};else if($(d))i.requestData={label:e,data:d,options:r};else throw R(d)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let p=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new g(p.data):new g},createMany:async(e,t)=>{var c,d,p,h;let r=y(t),s="/records/import/json",a={headers:Object.assign({},f(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let l=(h=(p=i.data)==null?void 0:p.map(S=>new g(S)))!=null?h:[];return new A(l,i.total)}return new A([])},delete:async(e,t)=>{var c,d,p;if(q(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new b("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=y(t),s="/records/delete",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.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 d,p;let r=y(t),s=T(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},f(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c},export:async(e,t)=>{var c,d;let r=y(t),s="/records/export/csv",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var h,l;let{id:r,...s}=e,a=y(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},f(a)),method:"POST",requestData:s!=null?s:{}},c=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:d.data});let p=d.data.map(S=>new g(S));return new A(p,d.total,e)},findById:async(e,t)=>{var c,d;let r=y(t),s=T(e)?"/records":`/records/${e}`,a={headers:Object.assign({},f(r)),method:T(e)?"POST":"GET",requestData:T(e)?{ids:e}:void 0},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),T(e)){let p=i.data.map(h=>new g(h));return new A(p,i.total)}else return new g(i.data)},findOne:async(e,t)=>{var d,p;let r=y(t),s="/records/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.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[c]=i.data;return new g(c)},findUniq:async(e,t)=>{var d,p;let r=y(t),s="/records/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.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 U(i.total,e);let[c]=i.data;return new g(c)},set:async({target:e,label:t,data:r,options:s},a)=>{var S,x;let o=y(a),c=`/records/${I(e)}`,d={headers:Object.assign({},f(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(r));if(T(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:s};else throw R(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(S=this.logger)==null||S.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(x=this.logger)==null||x.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g},update:async({target:e,label:t,data:r,options:s},a)=>{var S,x;let o=y(a),c=`/records/${I(e)}`,d={headers:Object.assign({},f(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(r));if(T(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:s};else throw R(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(S=this.logger)==null||S.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(x=this.logger)==null||x.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g}};this.relationships={find:async(e,t)=>{var p,h;let r=y(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({},f(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i,responseData:d.data}),d}};this.properties={delete:async(e,t)=>{var c,d;let r=y(t),s=`/properties/${e}`,a={headers:Object.assign({},f(r)),method:"DELETE"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var c,d;let r=y(t),s="/properties/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},findById:async(e,t)=>{var c,d;let r=y(t),s=`/properties/${e}`,a={headers:Object.assign({},f(r)),method:"GET"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},values:async(e,t,r)=>{var d,p;let s=y(r),a=`/properties/${e}/values`,o={headers:Object.assign({},f(s)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c}};this.labels={find:async(e,t)=>{var c,d;let r=y(t),s="/labels/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.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:R(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?u():"";(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 B(a.data.id)},commit:async e=>{var i,c;let r=`/tx/${y(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(c=this.logger)==null||c.call(this,{requestId:a,path:r,...s,responseData:o.data}),o},get:async e=>{var i,c;let r=`/tx/${y(e)}`,s={method:"GET"},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(c=this.logger)==null||c.call(this,{requestId:a,path:r,...s,responseData:o.data}),new B(o.data.id)},rollback:async e=>{var i,c;let r=`/tx/${y(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(c=this.logger)==null||c.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"?u():"";(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}};if(this.fetcher=null,t!=null&&t.httpClient){let r=ye(t);this.fetcher=de({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 g){let s=I(e);if(!s)throw new b(`${t} error: Target id is empty`);return[s]}if(T(e)&&e.every(s=>s instanceof g)){let s=e.map(I).filter(w);if(!s.length)throw new b(`${t} error: Target ids are empty`);return s}if(e instanceof A){let s=(r=e.data)==null?void 0:r.map(I).filter(w);if(!(s!=null&&s.length))throw new b(`${t} error: Target ids are empty`);return s}if(R(e)&&"__id"in e)return[e.__id];if(T(e)&&e.every(s=>R(s)&&"__id"in s)){let s=e.map(I).filter(w);if(!s.length)throw new b(`${t} error: Target ids are empty`);return s}return T(e)?e:P(e)?[e]:[]}};var ge,m=class m extends _{constructor(e,t){var s;let r=G(t);super(e,{...r,httpClient:(s=r.httpClient)!=null?s:ge}),m.instance=this,m.initPromise=this.initializeAsync(e,r).catch(a=>{throw console.error("RushDB initialization failed:",a),a})}async waitForInitialization(){return m.initPromise?await m.initPromise:this}async initializeAsync(e,t){try{let{data:r}=await this.settings.get();return m.state={initialized:!0,debug:!1,timeout:X("timeout",t==null?void 0:t.timeout,8e4),token:e,serverSettings:r},this}catch(r){throw console.error("Failed to initialize RushDB:",r),new Error(`RushDB initialization failed: ${r}`)}finally{m.state.initialized=!0}}static async init(){if(m.state.initialized&&m.instance)return m.instance;if(m.initPromise)return await m.initPromise;if(m.instance)return await m.instance.waitForInitialization();throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return m.instance}static isInitialized(){return m.state.initialized&&m.instance!==null}toDBRecordInstance(e){return new g(e)}};m.instance=null,m.initPromise=null,m.state={initialized:!1,debug:!1,timeout:8e4};var D=m,ee=n=>{ge=n};var te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async getRushDBInstance(){if(D.getInstance())return await D.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}async toDBRecordInstance(e){try{return(await this.getRushDBInstance()).toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let r=e!=null?e:{};return(await this.getRushDBInstance()).records.find({...r,labels:[this.label]},t)}async findOne(e,t){let r=e!=null?e:{};return(await this.getRushDBInstance()).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(await this.getRushDBInstance()).records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var i;let r=await k(this.schema,e),s=N(this.schema,r),a=w(s),o=await this.getRushDBInstance();if(a){let c=t!=null?t:await o.tx.begin(),d=await this.find({where:s},c),p=typeof t<"u";if(!((i=d==null?void 0:d.data)!=null&&i.length)){let l=await o.records.create({label:this.label,data:r},c);return p||await c.commit(),l}else throw p||await c.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(await this.getRushDBInstance()).records.attach({source:e,target:t,options:r},s)}async detach({source:e,target:t,options:r},s){return await(await this.getRushDBInstance()).records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var c,d;if(T(t)&&t.every(j))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=await this.getRushDBInstance(),o=await k(this.schema,t),i=N(this.schema,o);if(!q(i)){let p=s!=null?s:await a.tx.begin(),h=await this.find({where:i},p),l=typeof s<"u";if(!((c=h==null?void 0:h.data)!=null&&c.length)||h.data.length===1&&((d=h.data[0])==null?void 0:d.id())===I(e)){let x=await a.records[r]({target:e,label:this.label,data:o},p);return l||await p.commit(),x}else throw l||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=await this.getRushDBInstance(),s=typeof t<"u",a=t!=null?t:await r.tx.begin();try{let i=await Promise.all(e.map(async p=>await k(this.schema,p))),c=J(i,this.schema,this.label);if(!q(c)){let p=Object.entries(c).map(([l,S])=>({[l]:{$in:S}})),h=await this.find({where:{$or:p}},a);if((o=h==null?void 0:h.data)!=null&&o.length)throw new E(this.label,Object.keys(c))}let d=await r.records.createMany({label:this.label,data:i},a);return s||await a.commit(),d}catch(i){throw s||await a.rollback(),i}}async delete(e,t){if(q(e.where))throw new b(`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(await this.getRushDBInstance()).records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await(await this.getRushDBInstance()).records.deleteById(e,t)}};ee(new M);var Ue=D;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});