@rushdb/javascript-sdk 1.3.2 → 1.5.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 +2 -2
- package/dist/api/api.d.ts +15 -6
- package/dist/common/utils.d.ts +3 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.node.d.ts +1 -563
- package/dist/index.worker.d.ts +1 -563
- package/dist/sdk/model.d.ts +29 -13
- package/dist/sdk/record.d.ts +149 -6
- package/dist/sdk/sdk.d.ts +31 -566
- package/dist/sdk/transaction.d.ts +30 -2
- package/dist/sdk/types.d.ts +8 -0
- package/dist/types/schema.d.ts +2 -2
- package/dist/types/utils.d.ts +0 -1
- package/package.json +1 -1
- package/dist/api/rest-api-proxy.d.ts +0 -6
package/README.md
CHANGED
|
@@ -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("
|
|
57
|
+
const db = new RushDB("RUSHDB_API_TOKEN");
|
|
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('
|
|
124
|
+
const db = new RushDB('RUSHDB_API_TOKEN', {
|
|
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/api/api.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { HttpClient } from '../network/HttpClient.js';
|
|
2
|
-
import type { DBRecordTarget, RelationDetachOptions, RelationOptions, RelationTarget
|
|
2
|
+
import type { DBRecordCreationOptions, DBRecordTarget, Relation, RelationDetachOptions, RelationOptions, RelationTarget } from '../sdk/record.js';
|
|
3
|
+
import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
|
|
3
4
|
import type { SDKConfig } from '../sdk/types.js';
|
|
4
|
-
import type {
|
|
5
|
+
import type { AnyObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, PropertyValuesData, Schema, SearchQuery } from '../types/index.js';
|
|
5
6
|
import type { ApiResponse } from './types.js';
|
|
6
7
|
import { createFetcher } from '../network/index.js';
|
|
7
|
-
import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
|
|
8
8
|
import { Transaction } from '../sdk/transaction.js';
|
|
9
9
|
export declare class RestAPI {
|
|
10
10
|
fetcher: ReturnType<typeof createFetcher>;
|
|
@@ -61,7 +61,7 @@ export declare class RestAPI {
|
|
|
61
61
|
* @returns Promise resolving to the created DBRecordInstance
|
|
62
62
|
* @throws Error if data is not a flat object and createMany should be used instead
|
|
63
63
|
*/
|
|
64
|
-
create: <S extends Schema = any>({ label, data, options }: {
|
|
64
|
+
create: <S extends Schema = any>({ label, data: rawData, options }: {
|
|
65
65
|
label: string;
|
|
66
66
|
data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
|
|
67
67
|
options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType">;
|
|
@@ -150,7 +150,7 @@ export declare class RestAPI {
|
|
|
150
150
|
* @returns Promise resolving to updated DBRecordInstance
|
|
151
151
|
* @throws Error if data is not a flat object
|
|
152
152
|
*/
|
|
153
|
-
set: <S extends Schema = any>({ target, label, data, options }: {
|
|
153
|
+
set: <S extends Schema = any>({ target, label, data: rawData, options }: {
|
|
154
154
|
target: DBRecordTarget;
|
|
155
155
|
label: string;
|
|
156
156
|
data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
|
|
@@ -166,7 +166,7 @@ export declare class RestAPI {
|
|
|
166
166
|
* @returns Promise resolving to updated DBRecordInstance
|
|
167
167
|
* @throws Error if data is not a flat object
|
|
168
168
|
*/
|
|
169
|
-
update: <S extends Schema = any>({ target, label, data, options }: {
|
|
169
|
+
update: <S extends Schema = any>({ target, label, data: rawData, options }: {
|
|
170
170
|
target: DBRecordTarget;
|
|
171
171
|
label: string;
|
|
172
172
|
data: Partial<InferSchemaTypesWrite<S>> | Array<PropertyDraft>;
|
|
@@ -281,4 +281,13 @@ export declare class RestAPI {
|
|
|
281
281
|
message: string;
|
|
282
282
|
}>>;
|
|
283
283
|
};
|
|
284
|
+
settings: {
|
|
285
|
+
get: () => Promise<ApiResponse<{
|
|
286
|
+
selfHosted: boolean;
|
|
287
|
+
dashboardUrl: string;
|
|
288
|
+
googleOAuthEnabled: boolean;
|
|
289
|
+
githubOAuthEnabled: boolean;
|
|
290
|
+
customDB?: boolean;
|
|
291
|
+
} | undefined>>;
|
|
292
|
+
};
|
|
284
293
|
}
|
package/dist/common/utils.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ export declare const isArray: (item: any) => item is Array<any>;
|
|
|
3
3
|
export declare const isObject: (input: unknown) => input is object;
|
|
4
4
|
export declare const isEmptyObject: (input: unknown) => boolean;
|
|
5
5
|
export declare const isPrimitive: (value: unknown) => value is string | number | boolean | null;
|
|
6
|
+
export declare function omit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
|
|
7
|
+
export declare const getOwnProperties: <T>(input: T) => T | Omit<T & object, keyof T>;
|
|
8
|
+
export declare const removeUndefinedDeep: <T>(input: T) => T;
|
|
6
9
|
export declare const isPropertyValue: (value: any) => value is PropertyValue;
|
|
7
10
|
export declare const isFlatObject: (input: any) => input is Record<string, PropertyValue>;
|
|
8
11
|
export declare const isString: (input: any) => input is string;
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ye=Object.create;var j=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty;var Se=(n,e)=>{for(var t in e)j(n,t,{get:e[t],enumerable:!0})},ee=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ge(e))!fe.call(n,s)&&s!==t&&j(n,s,{get:()=>e[s],enumerable:!(r=ue(e,s))||r.enumerable});return n};var te=(n,e,t)=>(t=n!=null?ye(me(n)):{},ee(e||!n||!n.__esModule?j(t,"default",{value:n,enumerable:!0}):t,n)),Re=n=>ee(j({},"__esModule",{value:!0}),n);var qe={};Se(qe,{DBRecordInstance:()=>m,DBRecordsArrayInstance:()=>O,EmptyTargetError:()=>T,HttpClient:()=>w,HttpClientResponse:()=>k,Model:()=>X,NonUniqueResultError:()=>B,RestAPI:()=>_,RushDB:()=>he,Transaction:()=>A,UniquenessError:()=>I,default:()=>Be,idToDate:()=>z,idToTimestamp:()=>Q,initSDK:()=>G,mergeDefaultsWithPayload:()=>q,parseConfig:()=>V,pickUniqFieldsFromRecord:()=>H,pickUniqFieldsFromRecords:()=>Y,validateInteger:()=>J});module.exports=Re(qe);var w=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};w.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];w.TIMEOUT_ERROR_CODE="ETIMEDOUT";var M=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.")}},k=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 $=te(require("http"),1),N=te(require("https"),1);var Te="string",De="datetime",xe="boolean",we="number",be="null",Ie="vector",re=[Te,De,xe,we,be,Ie];var se=$.default||$,ne=N.default||N,Oe=new se.Agent({keepAlive:!0}),Ae=new ne.Agent({keepAlive:!0}),U=class extends w{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){let i=new URL(e),d=s==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Oe:Ae),new Promise((p,l)=>{let h=(d?se:ne).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:r,path:i.pathname+i.search,port:i.port});h.setTimeout(a!=null?a:8e4,()=>{h.destroy(w.makeTimeoutError())}),h.on("response",u=>{p(new v(u))}),h.on("error",u=>{l(u)}),h.once("socket",u=>{let x=o?JSON.stringify(o):"";u.connecting?u.once(d?"connect":"secureConnect",()=>{h.write(x),h.end()}):(h.write(x),h.end())})})}},v=class extends M{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 S=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,R=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",E=n=>R(n)&&Object.keys(n).length===0,ae=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,W=n=>S(n)?n.every(ae):ae(n),L=n=>R(n)&&Object.values(n).every(W),b=n=>typeof n=="string",F=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return S(n)&&n.length===0||R(n)&&Object.keys(n).length===0?!1:!!n};var Ee={"Content-Type":"application/json"},oe=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...o})=>{let a=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ee,...s},typeof e<"u"?{token:e}:{}),...o});if(a.getStatusCode()>=200&&a.getStatusCode()<300)return await a.toJSON();throw new Error(`${a.getStatusCode()}`)};var I=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)}},T=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},B=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 P=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var K=["httpClient","timeout","host","port","protocol","url","logger","options"];var q=async(n,e)=>{let t=Object.entries(n).map(async([o,a])=>a.default&&typeof a.default<"u"&&typeof e[o]>"u"?{key:o,value:typeof a.default=="function"?await a.default():a.default}:{key:o,value:void 0});return{...(await Promise.all(t)).reduce((o,{key:a,value:i})=>(i!==void 0&&(o[a]=i),o),{}),...e}},H=(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),{}),Y=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,o])=>o.uniq).reduce((o,[a])=>(o[a]=!0,o),{});return n.forEach(o=>{Object.entries(o).forEach(([a,i])=>{if(a in s)if(r[a]){if(r[a].includes(i))throw new I(t,{[a]:i});r[a]=[...r[a],i]}else r[a]=[i]})}),r},V=n=>{if(!n)return{};if(!R(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!K.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${K.join(", ")}`);return n};function J(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function Q(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function z(n){return new Date(Q(n))}var m=class extends P{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch{throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch{throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch{throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}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 Q(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await this.apiProxy.records.deleteById(this.id(),e)}async update(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)}},O=class extends P{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var A=class extends P{constructor(e){super(),this.id=e}async rollback(){return await this.apiProxy.tx.rollback(this.id)}async commit(){return await this.apiProxy.tx.commit(this.id)}};var ie="api.rushdb.com";var ce="https",de="/api/v1";var f=n=>n?{"x-transaction-id":n}:void 0,Ce=n=>b(n)||n instanceof A,g=n=>Ce(n)?n instanceof A?n.id:n:void 0,pe=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),D=n=>{if(b(n)&&pe(n))return n;if(n instanceof m&&n.data)return n.data.__id;if(R(n)&&"__id"in n&&pe(n.__id))return n.__id},C=n=>!(!R(n)||R(n)&&"name"in n&&!b(n.name)||R(n)&&"type"in n&&(!b(n.type)||!re.includes(n.type))||!("value"in n)||!W(n.value)||"metadata"in n&&!b(n.metadata)||"valueSeparator"in n&&!b(n.valueSeparator)),le=n=>{let e=ce,t=ie,r=443,s=de;if("url"in n){let a=new URL(n.url);e=a.protocol.replace(":",""),t=a.hostname,r=parseInt(a.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 o="";return e==="http"&&r===80||e==="https"&&r===443||(o=":"+r),`${e}://${t}${o}${s}`},y=(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 l,h;let o=g(s),i=`/relationships/${D(e)}`,d={headers:Object.assign({},f(o)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},detach:async({source:e,target:t,options:r},s)=>{var l,h;let o=g(s),i=`/relationships/${D(e)}`,d={headers:Object.assign({},f(o)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},create:async({label:e,data:t,options:r},s)=>{var p,l;let o=g(s),a="/records",i={headers:Object.assign({},f(o)),method:"POST",requestData:{}},d=typeof this.logger=="function"?y():"";if(S(t)&&t.every(C))i.requestData={label:e,properties:t};else if(L(t))i.requestData={label:e,data:t,options:r};else if(R(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);if((l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c!=null&&c.success&&(c!=null&&c.data)){let h=new m(c.data);return h.init(this),h}return new m},createMany:async(e,t)=>{var d,c;let r=g(t),s="/records/import/json",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=i.data.map(h=>{let u=new m(h);return u.init(this),u}),l=new O(p,i.total);return l.init(this),l}return new O([])},delete:async(e,t)=>{var d,c,p;if(E(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new T("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=g(t),s="/records/delete",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},deleteById:async(e,t)=>{var c,p;let r=g(t),s=S(e),o=s?"/records/delete":`/records/${e}`,a={headers:Object.assign({},f(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:o,...a});let d=await this.fetcher(o,a);return(p=this.logger)==null||p.call(this,{requestId:i,path:o,...a,responseData:d.data}),d},export:async(e,t)=>{var d,c;let r=g(t),s="/records/export/csv",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var h,u;let{id:r,...s}=e,o=g(t),a=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},f(o)),method:"POST",requestData:s},d=typeof this.logger=="function"?y():"";(h=this.logger)==null||h.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);(u=this.logger)==null||u.call(this,{requestId:d,path:a,...i,responseData:c.data});let p=c.data.map(x=>{let Z=new m(x);return Z.init(this),Z}),l=new O(p,c.total,e);return l.init(this),l},findById:async(e,t)=>{var d,c;let r=g(t),s=S(e)?"/records":`/records/${e}`,o={headers:Object.assign({},f(r)),method:S(e)?"POST":"GET",requestData:S(e)?{ids:e}:void 0},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),S(e)){let p=i.data.map(h=>{let u=new m(h);return u.init(this),u}),l=new O(p,i.total);return l.init(this),l}else{let p=new m(i.data);return p.init(this),p}},findOne:async(e,t)=>{var p,l;let r=g(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);(l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data});let[d]=i.data,c=new m(d);return c.init(this),c},findUniq:async(e,t)=>{var p,l;let r=g(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new B(i.total,e);let[d]=i.data,c=new m(d);return c.init(this),c},set:async({target:e,label:t,data:r,options:s},o)=>{var h,u;let a=g(o),d=`/records/${D(e)}`,c={headers:Object.assign({},f(a)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?y():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(L(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let x=new m(l.data);return x.init(this),x}return new m},update:async({target:e,label:t,data:r,options:s},o)=>{var h,u;let a=g(o),d=`/records/${D(e)}`,c={headers:Object.assign({},f(a)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?y():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(L(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let x=new m(l.data);return x.init(this),x}return new m}};this.relationships={find:async(e,t)=>{var p,l;let r=g(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 a=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},f(r)),method:"POST",requestData:e},d=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);return(l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c}};this.properties={delete:async(e,t)=>{var d,c;let r=g(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"DELETE"},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var d,c;let r=g(t),s="/properties/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},findById:async(e,t)=>{var d,c;let r=g(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"GET"},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},values:async(e,t,r)=>{var c,p;let s=g(r),o=`/properties/${e}/values`,a={headers:Object.assign({},f(s)),method:"POST",requestData:t},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:o,...a});let d=await this.fetcher(o,a);return(p=this.logger)==null||p.call(this,{requestId:i,path:o,...a,responseData:d.data}),d}};this.labels={find:async(e,t)=>{var d,c;let r=g(t),s="/labels/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i}};this.tx={begin:async e=>{var i,d;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:s,path:t,...r});let o=await this.fetcher(t,r);(d=this.logger)==null||d.call(this,{requestId:s,path:t,...r,responseData:o.data});let a=new A(o.data.id);return a.init(this),a},commit:async e=>{var i,d;let r=`/tx/${g(e)}/commit`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a},get:async e=>{var d,c;let r=`/tx/${g(e)}`,s={method:"GET"},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);(c=this.logger)==null||c.call(this,{requestId:o,path:r,...s,responseData:a.data});let i=new A(a.data.id);return i.init(this),i},rollback:async e=>{var i,d;let r=`/tx/${g(e)}/rollback`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a}};if(this.fetcher=null,t!=null&&t.httpClient){let r=le(t);this.fetcher=oe({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof m){let s=D(e);if(!s)throw new T(`${t} error: Target id is empty`);return[s]}if(S(e)&&e.every(s=>s instanceof m)){let s=e.map(D).filter(F);if(!s.length)throw new T(`${t} error: Target ids are empty`);return s}if(e instanceof O){let s=(r=e.data)==null?void 0:r.map(D).filter(F);if(!(s!=null&&s.length))throw new T(`${t} error: Target ids are empty`);return s}if(R(e)&&"__id"in e)return[e.__id];if(S(e)&&e.every(s=>R(s)&&"__id"in s)){let s=e.map(D).filter(F);if(!s.length)throw new T(`${t} error: Target ids are empty`);return s}return S(e)?e:b(e)?[e]:[]}};var G=n=>{class e extends _{constructor(r,s){var a;let o=V(s);super(r,{...o,httpClient:(a=o.httpClient)!=null?a:n}),this.state={debug:!1,timeout:J("timeout",o.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new m(r);return s.init(this),s}}return e};var X=class extends P{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}async find(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find({...r,labels:[this.label]},t)}async findOne(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var o;let r=await q(this.schema,e),s=H(this.schema,r);if(!E(s)){let a=t!=null?t:await this.apiProxy.tx.begin(),i=await this.find({where:s},a),d=typeof t<"u";if(!((o=i==null?void 0:i.data)!=null&&o.length)){let p=await this.apiProxy.records.create({label:this.label,data:r},a);return d||await a.commit(),p}else throw d||await a.commit(),new I(this.label,s)}return await this.apiProxy.records.create({label:this.label,data:r},t)}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var i,d;if(S(t)&&t.every(C))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let o=await q(this.schema,t),a=H(this.schema,o);if(!E(a)){let c=s!=null?s:await this.apiProxy.tx.begin(),p=await this.find({where:a},c),l=typeof s<"u";if(!((i=p==null?void 0:p.data)!=null&&i.length)||p.data.length===1&&((d=p.data[0])==null?void 0:d.id())===D(e)){let u=await this.apiProxy.records[r]({target:e,label:this.label,data:o},c);return l||await c.commit(),u}else throw l||await c.commit(),new I(this.label,a)}return await this.apiProxy.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=typeof t<"u",s=t!=null?t:await this.apiProxy.tx.begin();try{let a=await Promise.all(e.map(async c=>await q(this.schema,c))),i=Y(a,this.schema,this.label);if(!E(i)){let c=Object.entries(i).map(([l,h])=>({[l]:{$in:h}})),p=await this.find({where:{$or:c}},s);if((o=p==null?void 0:p.data)!=null&&o.length)throw new I(this.label,Object.keys(i))}let d=await this.apiProxy.records.createMany({label:this.label,data:a},s);return r||await s.commit(),d}catch(a){throw r||await s.rollback(),a}}async delete(e,t){if(E(e.where))throw new T(`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 this.apiProxy.records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await this.apiProxy.records.deleteById(e,t)}};var he=G(new U);var Be=he;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),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",R=>{p(new W(R))}),l.on("error",R=>{h(R)}),l.once("socket",R=>{let x=a?JSON.stringify(a):"";R.connecting?R.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,S=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",q=n=>S(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=>S(n)?_e(n,["__label","__id","__proptypes"]):n,C=n=>T(n)?n.map(C):S(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=>S(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||S(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(!S(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(S(n)&&"__id"in n&&ue(n.__id))return n.__id},j=n=>!(!S(n)||S(n)&&"name"in n&&!P(n.name)||S(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 S(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;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 p=i.data.map(h=>new g(h));return new A(p,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(R=>new g(R));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 R,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 S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(R=this.logger)==null||R.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 R,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 S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(R=this.logger)==null||R.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:S(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(S(e)&&"__id"in e)return[e.__id];if(T(e)&&e.every(s=>S(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,R])=>({[l]:{$in:R}})),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 ue=Object.defineProperty,me=Object.defineProperties;var fe=Object.getOwnPropertyDescriptors;var U=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable;var G=(n,e,t)=>e in n?ue(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))Z.call(e,t)&&G(n,t,e[t]);if(U)for(var t of U(e))X.call(e,t)&&G(n,t,e[t]);return n},m=(n,e)=>me(n,fe(e));var F=(n,e)=>{var t={};for(var r in n)Z.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&U)for(var r of U(n))e.indexOf(r)<0&&X.call(n,r)&&(t[r]=n[r]);return t};var h=(n,e,t)=>new Promise((r,s)=>{var a=c=>{try{i(t.next(c))}catch(d){s(d)}},o=c=>{try{i(t.throw(c))}catch(d){s(d)}},i=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,o);i((t=t.apply(n,e)).next())});var ge="string",Se="datetime",Re="boolean",Te="number",be="null",De="vector",ee=[ge,Se,Re,Te,be,De];var I=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}};I.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];I.TIMEOUT_ERROR_CODE="ETIMEDOUT";var H=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},N=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var v=class n extends I{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=n.makeFetchWithAbortTimeout(e):this._fetchFn=n.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,s)=>{let a,o=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(I.makeTimeoutError())},s)}),i=e(t,r);return Promise.race([i,o]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>h(this,null,function*(){let a=new AbortController,o=setTimeout(()=>{o=null,a.abort(I.makeTimeoutError())},s);try{return yield e(t,m(p({},r),{signal:a.signal}))}catch(i){throw i.name==="AbortError"?I.makeTimeoutError():i}finally{o&&clearTimeout(o)}})}makeRequest(i,c){return h(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){let d=r=="POST"||r=="PUT"||r=="PATCH",l=JSON.stringify(a)||(d?"":void 0),y=yield this._fetchFn(e,{body:l,headers:t,method:r},o!=null?o:8e4);return new K(y)})}},K=class n extends H{constructor(e){super(e.status,n._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var D=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,x=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",j=n=>x(n)&&Object.keys(n).length===0,te=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,Y=n=>D(n)?n.every(te):te(n),L=n=>x(n)&&Object.values(n).every(Y),O=n=>typeof n=="string",Q=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return D(n)&&n.length===0||x(n)&&Object.keys(n).length===0?!1:!!n};var we={"Content-Type":"application/json"},re=({httpClient:n,token:e,url:t})=>(r,o)=>h(void 0,null,function*(){var i=o,{headers:s}=i,a=F(i,["headers"]);let c=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},we),s),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var C=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)}},P=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},$=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 E=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var V=["httpClient","timeout","host","port","protocol","url","logger","options"];var W=(n,e)=>h(void 0,null,function*(){let t=Object.entries(n).map(i=>h(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}})),s=(yield Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{});return p(p({},s),e)}),J=(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),{}),se=(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 C(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},ne=n=>{if(!n)return{};if(!x(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 ae(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function z(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function oe(n){return new Date(z(n))}var R=class extends E{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch(e){throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch(e){throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch(e){throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}date(){try{return oe(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return z(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield this.apiProxy.records.deleteById(this.id(),e)})}update(e,t){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)})}},B=class extends E{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var q=class extends E{constructor(e){super(),this.id=e}rollback(){return h(this,null,function*(){return yield this.apiProxy.tx.rollback(this.id)})}commit(){return h(this,null,function*(){return yield this.apiProxy.tx.commit(this.id)})}};var ie="api.rushdb.com";var ce="https",de="/api/v1";var T=n=>n?{"x-transaction-id":n}:void 0,Pe=n=>O(n)||n instanceof q,S=n=>Pe(n)?n instanceof q?n.id:n:void 0,pe=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),w=n=>{if(O(n)&&pe(n))return n;if(n instanceof R&&n.data)return n.data.__id;if(x(n)&&"__id"in n&&pe(n.__id))return n.__id},k=n=>!(!x(n)||x(n)&&"name"in n&&!O(n.name)||x(n)&&"type"in n&&(!O(n.type)||!ee.includes(n.type))||!("value"in n)||!Y(n.value)||"metadata"in n&&!O(n.metadata)||"valueSeparator"in n&&!O(n.valueSeparator)),le=n=>{let e=ce,t=ie,r=443,s=de;if("url"in n){let o=new URL(n.url);e=o.protocol.replace(":",""),t=o.hostname,r=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${s}`},g=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var M=class{constructor(e,t){this.records={attach:(a,o)=>h(this,[a,o],function*({source:e,target:t,options:r},s){var u,b;let i=S(s),d=`/relationships/${w(e)}`,l={headers:Object.assign({},T(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})},y=typeof this.logger=="function"?g():"";(u=this.logger)==null||u.call(this,p({requestId:y,path:d},l));let f=yield this.fetcher(d,l);return(b=this.logger)==null||b.call(this,m(p({requestId:y,path:d},l),{responseData:f.data})),f}),detach:(a,o)=>h(this,[a,o],function*({source:e,target:t,options:r},s){var u,b;let i=S(s),d=`/relationships/${w(e)}`,l={headers:Object.assign({},T(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})},y=typeof this.logger=="function"?g():"";(u=this.logger)==null||u.call(this,p({requestId:y,path:d},l));let f=yield this.fetcher(d,l);return(b=this.logger)==null||b.call(this,m(p({requestId:y,path:d},l),{responseData:f.data})),f}),create:(a,o)=>h(this,[a,o],function*({label:e,data:t,options:r},s){var f,u;let i=S(s),c="/records",d={headers:Object.assign({},T(i)),method:"POST",requestData:{}},l=typeof this.logger=="function"?g():"";if(D(t)&&t.every(k))d.requestData={label:e,properties:t};else if(L(t))d.requestData={label:e,data:t,options:r};else if(x(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(f=this.logger)==null||f.call(this,p({requestId:l,path:c},d));let y=yield this.fetcher(c,d);if((u=this.logger)==null||u.call(this,m(p({requestId:l,path:c},d),{responseData:y.data})),y!=null&&y.success&&(y!=null&&y.data)){let b=new R(y.data);return b.init(this),b}return new R}),createMany:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/records/import/json",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i!=null&&i.success&&(i!=null&&i.data)){let l=i.data.map(f=>{let u=new R(f);return u.init(this),u}),y=new B(l,i.total);return y.init(this),y}return new B([])}),delete:(e,t)=>h(this,null,function*(){var c,d,l;if(j(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new P("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=S(t),s="/records/delete",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(l=this.logger)==null||l.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),deleteById:(e,t)=>h(this,null,function*(){var d,l;let r=S(t),s=D(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},T(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(l=this.logger)==null||l.call(this,m(p({requestId:i,path:a},o),{responseData:c.data})),c}),export:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/records/export/csv",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>h(this,null,function*(){var u,b;let f=e,{id:r}=f,s=F(f,["id"]),a=S(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},T(a)),method:"POST",requestData:s},c=typeof this.logger=="function"?g():"";(u=this.logger)==null||u.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);(b=this.logger)==null||b.call(this,m(p({requestId:c,path:o},i),{responseData:d.data}));let l=d.data.map(_=>{let A=new R(_);return A.init(this),A}),y=new B(l,d.total,e);return y.init(this),y}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s=D(e)?"/records":`/records/${e}`,a={headers:Object.assign({},T(r)),method:D(e)?"POST":"GET",requestData:D(e)?{ids:e}:void 0},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),D(e)){let l=i.data.map(f=>{let u=new R(f);return u.init(this),u}),y=new B(l,i.total);return y.init(this),y}else{let l=new R(i.data);return l.init(this),l}}),findOne:(e,t)=>h(this,null,function*(){var l,y;let r=S(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);(y=this.logger)==null||y.call(this,m(p({requestId:o,path:s},a),{responseData:i.data}));let[c]=i.data,d=new R(c);return d.init(this),d}),findUniq:(e,t)=>h(this,null,function*(){var l,y;let r=S(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((y=this.logger)==null||y.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),typeof i.total!="undefined"&&i.total>1)throw new $(i.total,e);let[c]=i.data,d=new R(c);return d.init(this),d}),set:(o,i)=>h(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var b,_;let c=S(a),l=`/records/${w(e)}`,y={headers:Object.assign({},T(c)),method:"PUT",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))y.requestData={label:t,properties:r};else if(L(r))y.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(b=this.logger)==null||b.call(this,p({requestId:f,path:l},y));let u=yield this.fetcher(l,y);if((_=this.logger)==null||_.call(this,m(p({requestId:f,path:l},y),{responseData:u.data})),u!=null&&u.success&&(u!=null&&u.data)){let A=new R(u.data);return A.init(this),A}return new R}),update:(o,i)=>h(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var b,_;let c=S(a),l=`/records/${w(e)}`,y={headers:Object.assign({},T(c)),method:"PATCH",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))y.requestData={label:t,properties:r};else if(L(r))y.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(b=this.logger)==null||b.call(this,p({requestId:f,path:l},y));let u=yield this.fetcher(l,y);if((_=this.logger)==null||_.call(this,m(p({requestId:f,path:l},y),{responseData:u.data})),u!=null&&u.success&&(u!=null&&u.data)){let A=new R(u.data);return A.init(this),A}return new R})};this.relationships={find:(e,t)=>h(this,null,function*(){var l,y;let r=S(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({},T(r)),method:"POST",requestData:e},c=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);return(y=this.logger)==null||y.call(this,m(p({requestId:c,path:o},i),{responseData:d.data})),d})};this.properties={delete:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/properties/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"GET"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),values:(e,t,r)=>h(this,null,function*(){var d,l;let s=S(r),a=`/properties/${e}/values`,o={headers:Object.assign({},T(s)),method:"POST",requestData:t},i=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(l=this.logger)==null||l.call(this,m(p({requestId:i,path:a},o),{responseData:c.data})),c})};this.labels={find:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/labels/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i})};this.tx={begin:e=>h(this,null,function*(){var i,c;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:s,path:t},r));let a=yield this.fetcher(t,r);(c=this.logger)==null||c.call(this,m(p({requestId:s,path:t},r),{responseData:a.data}));let o=new q(a.data.id);return o.init(this),o}),commit:e=>h(this,null,function*(){var i,c;let r=`/tx/${S(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o}),get:e=>h(this,null,function*(){var c,d;let r=`/tx/${S(e)}`,s={method:"GET"},a=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);(d=this.logger)==null||d.call(this,m(p({requestId:a,path:r},s),{responseData:o.data}));let i=new q(o.data.id);return i.init(this),i}),rollback:e=>h(this,null,function*(){var i,c;let r=`/tx/${S(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o})};if(this.fetcher=null,t!=null&&t.httpClient){let r=le(t);this.fetcher=re({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 R){let s=w(e);if(!s)throw new P(`${t} error: Target id is empty`);return[s]}if(D(e)&&e.every(s=>s instanceof R)){let s=e.map(w).filter(Q);if(!s.length)throw new P(`${t} error: Target ids are empty`);return s}if(e instanceof B){let s=(r=e.data)==null?void 0:r.map(w).filter(Q);if(!(s!=null&&s.length))throw new P(`${t} error: Target ids are empty`);return s}if(x(e)&&"__id"in e)return[e.__id];if(D(e)&&e.every(s=>x(s)&&"__id"in s)){let s=e.map(w).filter(Q);if(!s.length)throw new P(`${t} error: Target ids are empty`);return s}return D(e)?e:O(e)?[e]:[]}};var he=n=>{class e extends M{constructor(r,s){var o;let a=ne(s);super(r,m(p({},a),{httpClient:(o=a.httpClient)!=null?o:n})),this.state={debug:!1,timeout:ae("timeout",a.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new R(r);return s.init(this),s}}return e};var ye=class extends E{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}find(e,t){return h(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find(m(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return h(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne(m(p({},r),{labels:[this.label]}),t)})}findById(e,t){return h(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return h(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq(m(p({},r),{labels:[this.label]}),t)})}create(e,t){return h(this,null,function*(){var a;let r=yield W(this.schema,e),s=J(this.schema,r);if(!j(s)){let o=t!=null?t:yield this.apiProxy.tx.begin(),i=yield this.find({where:s},o),c=typeof t!="undefined";if(!((a=i==null?void 0:i.data)!=null&&a.length)){let l=yield this.apiProxy.records.create({label:this.label,data:r},o);return c||(yield o.commit()),l}else throw c||(yield o.commit()),new C(this.label,s)}return yield this.apiProxy.records.create({label:this.label,data:r},t)})}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}handleSetOrUpdate(e,t,r,s){return h(this,null,function*(){var i,c;if(D(t)&&t.every(k))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield W(this.schema,t),o=J(this.schema,a);if(!j(o)){let d=s!=null?s:yield this.apiProxy.tx.begin(),l=yield this.find({where:o},d),y=typeof s!="undefined";if(!((i=l==null?void 0:l.data)!=null&&i.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===w(e)){let u=yield this.apiProxy.records[r]({target:e,label:this.label,data:a},d);return y||(yield d.commit()),u}else throw y||(yield d.commit()),new C(this.label,o)}return yield this.apiProxy.records[r]({label:this.label,target:e,data:a},s)})}set(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return h(this,null,function*(){var a;let r=typeof t!="undefined",s=t!=null?t:yield this.apiProxy.tx.begin();try{let o=yield Promise.all(e.map(d=>h(this,null,function*(){return yield W(this.schema,d)}))),i=se(o,this.schema,this.label);if(!j(i)){let d=Object.entries(i).map(([y,f])=>({[y]:{$in:f}})),l=yield this.find({where:{$or:d}},s);if((a=l==null?void 0:l.data)!=null&&a.length)throw new C(this.label,Object.keys(i))}let c=yield this.apiProxy.records.createMany({label:this.label,data:o},s);return r||(yield s.commit()),c}catch(o){throw r||(yield s.rollback()),o}})}delete(e,t){return h(this,null,function*(){if(j(e.where))throw new P(`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 this.apiProxy.records.delete(m(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return h(this,null,function*(){return yield this.apiProxy.records.deleteById(e,t)})}};var Oe=he(new v);var Bt=Oe;export{R as DBRecordInstance,B as DBRecordsArrayInstance,P as EmptyTargetError,I as HttpClient,N as HttpClientResponse,ye as Model,$ as NonUniqueResultError,M as RestAPI,Oe as RushDB,q as Transaction,C as UniquenessError,Bt as default,oe as idToDate,z as idToTimestamp,he as initSDK,W as mergeDefaultsWithPayload,ne as parseConfig,J as pickUniqFieldsFromRecord,se as pickUniqFieldsFromRecords,ae 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)}},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 g,f;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():"";(g=this.logger)==null||g.call(this,p({requestId:u,path:d},h));let m=yield this.fetcher(d,h);return(f=this.logger)==null||f.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 g,f;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():"";(g=this.logger)==null||g.call(this,p({requestId:u,path:d},h));let m=yield this.fetcher(d,h);return(f=this.logger)==null||f.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 g,f;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.");(g=this.logger)==null||g.call(this,p({requestId:h,path:c},d));let m=yield this.fetcher(c,d);return(f=this.logger)==null||f.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;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 h=i.data.map(u=>new T(u));return new q(h,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,g;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);(g=this.logger)==null||g.call(this,y(p({requestId:c,path:o},i),{responseData:d.data}));let h=d.data.map(f=>new T(f));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():"",g=W(j(r));if(I(g)&&g.every(U))u.requestData={label:t,properties:g};else if(K(g))u.requestData={label:t,data:g,options:n};else throw b(g)?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 f=yield this.fetcher(h,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:h},u),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new T(f.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():"",g=W(j(r));if(I(g)&&g.every(U))u.requestData={label:t,properties:g};else if(K(g))u.requestData={label:t,data:g,options:n};else throw b(g)?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 f=yield this.fetcher(h,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:h},u),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new T(f.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 f=yield a.records[r]({target:e,label:this.label,data:o},h);return m||(yield h.commit()),f}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,g])=>({[m]:{$in:g}})),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};
|