@rushdb/javascript-sdk 1.7.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,7 +46,7 @@ pnpm add @rushdb/javascript-sdk
46
46
 
47
47
  ---
48
48
 
49
- 1. **Obtain API Token**: Grab one from the [RushDB Cloud Dashboard](https://app.rushdb.com).
49
+ 1. **Obtain API Key**: Grab one from the [RushDB Cloud Dashboard](https://app.rushdb.com).
50
50
  2. **Build anything**: Easily push, search, and manage relationships within your data.
51
51
 
52
52
  ### Quick Example
@@ -54,7 +54,7 @@ pnpm add @rushdb/javascript-sdk
54
54
  import RushDB from '@rushdb/javascript-sdk';
55
55
 
56
56
  // Setup SDK
57
- const db = new RushDB("RUSHDB_API_TOKEN");
57
+ const db = new RushDB("RUSHDB_API_KEY");
58
58
  // Default URL is "https://api.rushdb.com/api/v1". See SDK Configuration for more options.
59
59
 
60
60
  // Push any data, and RushDB will automatically flatten it into Records
@@ -121,7 +121,7 @@ The SDK is designed to be flexible. You can provide configuration options when i
121
121
  import RushDB from '@rushdb/javascript-sdk';
122
122
 
123
123
  // Example: Initialize with a custom URL and timeout
124
- const db = new RushDB('RUSHDB_API_TOKEN', {
124
+ const db = new RushDB('RUSHDB_API_KEY', {
125
125
  url: 'http://your-custom-rushdb-server.com/api/v1', // Default is 'https://api.rushdb.com/api/v1'
126
126
  timeout: 30000 // 30 seconds
127
127
  });
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "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),Q=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=Q.default||Q,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,V=n=>T(n)?n.every(ce):ce(n),$=n=>R(n)&&Object.values(n).every(V),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 Y=["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=>!Y.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${Y.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)||!V(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_TOKEN")')}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_TOKEN")')}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});
1
+ "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});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- 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)}},z=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 Y=(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 z(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_TOKEN")')})}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_TOKEN")')})}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 Y(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 Y(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 Y(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,z 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,Y as mergeDefaultsWithPayload,ie as parseConfig,Z as pickUniqFieldsFromRecord,oe as pickUniqFieldsFromRecords,ce as validateInteger};
1
+ 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};
package/package.json CHANGED
@@ -33,7 +33,7 @@
33
33
  "rushdb"
34
34
  ],
35
35
  "license": "Apache-2.0",
36
- "version": "1.7.1",
36
+ "version": "1.8.0",
37
37
  "type": "module",
38
38
  "files": [
39
39
  "dist"