UNPKG

@rushdb/javascript-sdk

Version:

RushDB Javascript SDK

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