@rushdb/javascript-sdk 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -179,6 +179,22 @@ const relationships = await db.relationships.find({
179
179
  })
180
180
  ```
181
181
 
182
+ `db.relationships.update()` changes the properties of existing relationships: `set` writes values, `unset` removes them.
183
+ `types` marks a value whose type JSON can't carry: `{ since: 'datetime' }` stores an ISO string as a datetime.
184
+ Relationships read back with their datetime values as ISO strings and a `propertyTypes` map.
185
+ It needs RushDB 3.0.4 or newer.
186
+
187
+ ```typescript
188
+ await db.relationships.update({
189
+ source: user,
190
+ target: order,
191
+ type: 'ORDERED',
192
+ set: { confidence: 0.95, reviewedAt: '2026-11-06T10:00:00.000Z' },
193
+ unset: ['legacyCode'],
194
+ types: { reviewedAt: 'datetime' }
195
+ })
196
+ ```
197
+
182
198
  ---
183
199
 
184
200
  ## RushDB Cloud or a self-hosted engine
@@ -211,7 +227,7 @@ What each offers:
211
227
  | Feature | Cloud | Self-hosted engine |
212
228
  | --- | :---: | :---: |
213
229
  | Records: create, read, update, set, upsert, delete, `find` with `where`, `orderBy`, `select`, `groupBy` | ✓ | ✓ |
214
- | Relationships: `attach`/`detach`, `relationships.createMany`/`deleteMany`/`find` | ✓ | ✓ |
230
+ | Relationships: `attach`/`detach`, `relationships.createMany`/`deleteMany`/`find`/`update` | ✓ | ✓ |
215
231
  | Labels, properties, property values | ✓ | ✓ |
216
232
  | Import JSON and CSV, export CSV | ✓ | ✓ |
217
233
  | Text indexes and keyword search (`records.textSearch`) | ✓ | ✓ |
package/dist/api/api.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { HttpClient } from '../network/HttpClient.js';
2
2
  import { DirectEngine } from '../direct/engine.js';
3
- import type { DBRecordCreationOptions, DBRecordTarget, Relation, RelationDetachOptions, RelationDirection, RelationOptions, RelationTarget } from '../sdk/record.js';
3
+ import type { DBRecordCreationOptions, DBRecordTarget, Relation, RelationDetachOptions, RelationDirection, RelationOptions, RelationPropertyType, RelationTarget } from '../sdk/record.js';
4
4
  import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
5
5
  import type { SDKConfig } from '../sdk/types.js';
6
6
  import type { FlatObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, JoinCandidate, NameSuggestion, PropertyValuesData, PropertyValuesSearch, Schema, SchemaSummaryLabel, SearchValuesParams, ValueMatchesData, RelationshipSearchQuery, SearchQuery, Where } from '../types/index.js';
@@ -371,6 +371,33 @@ export declare class RestAPI {
371
371
  }, transaction?: Transaction | string) => Promise<ApiResponse<{
372
372
  message: string;
373
373
  }>>;
374
+ /**
375
+ * Updates the properties of existing relationships of one type, from `source` to each
376
+ * `target` (or the reverse with `direction: 'in'`). `set` writes values (`null` stores an
377
+ * explicit null); `unset` removes properties; `types` names a `set` value's type where JSON
378
+ * can't (`datetime` stores an ISO string as a datetime). Pairs without such a relationship are
379
+ * skipped; `updated` counts the relationships changed. Not available inside a transaction.
380
+ * @param source - The source record
381
+ * @param target - The target record(s)
382
+ * @param type - The relationship type to update
383
+ * @param direction - `out` (default) or `in`
384
+ * @param set - Properties to write
385
+ * @param unset - Property names to remove
386
+ * @param types - Type of `set` properties, e.g. `{ since: 'datetime' }`
387
+ * @returns Promise with the number of relationships updated
388
+ */
389
+ update: ({ source, target, type, direction, set, unset, types }: {
390
+ source: DBRecordTarget;
391
+ target: RelationTarget;
392
+ type: string;
393
+ direction?: RelationDirection;
394
+ set?: Record<string, unknown>;
395
+ unset?: Array<string>;
396
+ types?: Record<string, RelationPropertyType>;
397
+ }) => Promise<ApiResponse<{
398
+ message: string;
399
+ updated: number;
400
+ }>>;
374
401
  /**
375
402
  * Searches for relations matching the query criteria.
376
403
  * Pagination (`limit`/`skip`) is part of the search query body, same as records search.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var kt=Object.create;var ue=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,Bt=Object.prototype.hasOwnProperty;var vt=(t,e)=>{for(var r in e)ue(t,r,{get:e[r],enumerable:!0})},ze=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _t(e))!Bt.call(t,n)&&n!==r&&ue(t,n,{get:()=>e[n],enumerable:!(s=$t(e,n))||s.enumerable});return t};var Xe=(t,e,r)=>(r=t!=null?kt(Ct(t)):{},ze(e||!t||!t.__esModule?ue(r,"default",{value:t,enumerable:!0}):r,t)),Lt=t=>ze(ue({},"__esModule",{value:!0}),t);var ar={};vt(ar,{CLOUD_ONLY_FORMS:()=>pe,CLOUD_ONLY_METHODS:()=>le,CloudOnlyError:()=>K,DBRecordInstance:()=>T,DBRecordsArrayInstance:()=>k,DirectModeError:()=>ee,EmptyTargetError:()=>_,HttpClient:()=>B,HttpClientResponse:()=>ge,Model:()=>He,NonUniqueResultError:()=>ce,RestAPI:()=>J,RushDB:()=>w,Transaction:()=>U,UniquenessError:()=>L,default:()=>sr,idToDate:()=>Be,idToTimestamp:()=>Se,initSDK:()=>Fe,isCloudOnlyMethod:()=>st,mergeDefaultsWithPayload:()=>de,parseConfig:()=>_e,pickUniqFieldsFromRecord:()=>fe,pickUniqFieldsFromRecords:()=>$e,validateInteger:()=>Ce});module.exports=Lt(ar);var B=class t{makeRequest(e,{headers:r,method:s,protocol:n,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(t.TIMEOUT_ERROR_CODE);return e.code=t.TIMEOUT_ERROR_CODE,e}};B.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];B.TIMEOUT_ERROR_CODE="ETIMEDOUT";var me=class{constructor(e,r){this._statusCode=e,this._headers=r}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.")}},ge=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 Ee=Xe(require("http"),1),Oe=Xe(require("https"),1);var jt="string",Ut="datetime",Mt="boolean",Vt="number",Ze=[jt,Ut,Mt,Vt];var tt=Ee.default||Ee,rt=Oe.default||Oe,Nt=new tt.Agent({keepAlive:!0}),Ft=new rt.Agent({keepAlive:!0}),ye=class extends B{constructor(e){super(),this._agent=e}makeRequest(e,{headers:r,method:s,protocol:n,requestData:a,timeout:o}){let i=new URL(e),d=n==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Nt:Ft),new Promise((l,p)=>{let h=(d?tt:rt).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:r,host:i.hostname,method:s,path:i.pathname+i.search,port:i.port});h.setTimeout(o!=null?o:8e4,()=>{h.destroy(B.makeTimeoutError())}),h.on("response",u=>{l(new Pe(u))}),h.on("error",u=>{p(u)}),h.once("socket",u=>{let y=a?JSON.stringify(a):"";u.connecting?u.once(d?"connect":"secureConnect",()=>{h.write(y),h.end()}):(h.write(y),h.end())})})}},Pe=class extends me{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,r)=>{let s="";this._res.setEncoding("utf8"),this._res.on("data",n=>{s+=n}),this._res.once("end",()=>{try{e(JSON.parse(s))}catch(n){r(n)}})})}};var I=t=>typeof t=="object"&&Array.isArray(t)&&t!==null,P=t=>t!==null&&Object.prototype.toString.call(t)==="[object Object]",z=t=>P(t)&&Object.keys(t).length===0,Ae=t=>typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null;function Ht(t,e){let r={...t};return e.forEach(s=>{delete r[s]}),r}var X=t=>P(t)?Ht(t,["__label","__id","__proptypes"]):t,Q=t=>I(t)?t.map(Q):P(t)?Object.fromEntries(Object.entries(t).filter(([e,r])=>r!==void 0).map(([e,r])=>[e,Q(r)])):t,qe=t=>I(t)?t.every(Ae):Ae(t),Z=t=>P(t)&&Object.values(t).every(qe),Qt=t=>P(t)||I(t)&&!t.every(Ae),nt=t=>{if(I(t)||!P(t))return!0;let e=Object.values(t);return e.length===0?!0:e.some(r=>!Qt(r))},v=t=>typeof t=="string",O=t=>{if(typeof t=="string"){if(t.toLowerCase()==="true")return!0;if(t.toLowerCase()==="false")return!1}return I(t)&&t.length===0||P(t)&&Object.keys(t).length===0?!1:!!t};var ke=["httpClient","timeout","host","port","protocol","url","logger","options","direct","engineUrl","scope"];var L=class t extends Error{constructor(e,r){super(`Record with label "${e}" and properties ${JSON.stringify(r)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,t.prototype)}},_=class t extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,t.prototype)}},ce=class t extends Error{constructor(e,r){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(r)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,t.prototype)}},K=class t extends Error{constructor(r,s){super(`${r} requires RushDB Cloud: ${s}. It is not available in direct mode.`);this.method=r;this.reason=s;this.code="CLOUD_ONLY";this.name="CloudOnlyError",Object.setPrototypeOf(this,t.prototype)}},ee=class t extends Error{constructor(r){super(r);this.code="DIRECT_MODE_UNSUPPORTED";this.name="DirectModeError",Object.setPrototypeOf(this,t.prototype)}};var de=async(t,e)=>{let r=Object.entries(t).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(r)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},fe=(t,e)=>Object.entries(e).filter(([r])=>{var s;return(s=t[r])==null?void 0:s.unique}).reduce((r,[s,n])=>(s in t&&(r[s]=n),r),{}),$e=(t,e,r)=>{let s={},n=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[o])=>(a[o]=!0,a),{});return t.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in n)if(s[o]){if(s[o].includes(i))throw new L(r,{[o]:i});s[o]=[...s[o],i]}else s[o]=[i]})}),s},_e=t=>{if(!t)return{};if(!P(t))throw new Error("Config must be an object");if(Object.keys(t).filter(r=>!ke.includes(r)).length>0)throw new Error(`Config object may only contain the following: ${ke.join(", ")}`);return t};function Ce(t,e,r){if(!Number.isInteger(e)){if(r!==void 0)return r;throw new Error(`${t} must be an integer`)}return e}function Se(t){let e=t.split("-"),r=e[0]+e[1].slice(0,4);return parseInt(r,16)}function Be(t){return new Date(Se(t))}var T=class{constructor(e={}){this.data=e}get exists(){return O(this.data.__id)&&O(this.data.__label)}get id(){if(!O(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}get label(){if(!O(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}get proptypes(){if(!O(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}get date(){try{return Be(this.id)}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}get timestamp(){try{return Se(this.id)}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or invalid.")}}get score(){return this.data.__score}async delete(e){if(!O(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await w.getInstance().records.deleteById(this.id,e)}async update(e,r){if(!O(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return w.getInstance().records.update({label:this.label,target:this.id,data:e},r)}async set(e,r){if(!O(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return w.getInstance().records.set({label:this.label,target:this.id,data:e},r)}async attach(e,r,s){if(!O(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return w.getInstance().records.attach({source:this.id,target:e,options:r},s)}async detach(e,r,s){if(!O(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return w.getInstance().records.detach({source:this.id,target:e,options:r},s)}},k=class{constructor(e=[],r=0,s,n){this.data=e,this.total=r,this.searchQuery=s,this.warnings=n}async deleteAll(e){let r=this.data.map(n=>n.id);return r.length?await w.getInstance().records.deleteById(r,e):{success:!0}}async next(e){var i,d,c;if(this.sql){let{skip:l,limit:p}=(i=this.sqlPage)!=null?i:{skip:0,limit:100},h={skip:l+p,limit:p},u=await w.getInstance().ai.runSql(this.sql,h);return e!=null&&e.preserveData?(this.data=[...this.data,...u.data],this.total=u.total,this.sqlPage=h,this):(u.name=this.name,u)}if(!this.searchQuery)throw new Error("DBRecordsArrayInstance: Cannot paginate \u2014 no searchQuery was provided.");let r=(d=this.searchQuery.skip)!=null?d:0,s=(c=this.searchQuery.limit)!=null?c:100,n={...this.searchQuery,skip:r+s},o=await w.getInstance().records.find(n,void 0);return e!=null&&e.preserveData?(this.data=[...this.data,...o.data],this.total=o.total,this.searchQuery=n,this):o}exportCsv(){if(!this.data.length)return"";let e=new Set(["__id","__label","__proptypes"]),r=Object.keys(this.data[0].data).filter(a=>!e.has(a)),s=a=>{let o=a==null?"":String(a);return o.includes(",")||o.includes('"')||o.includes(`
1
+ "use strict";var $t=Object.create;var me=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var _t=Object.getPrototypeOf,Bt=Object.prototype.hasOwnProperty;var vt=(t,e)=>{for(var r in e)me(t,r,{get:e[r],enumerable:!0})},ze=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ct(e))!Bt.call(t,n)&&n!==r&&me(t,n,{get:()=>e[n],enumerable:!(s=kt(e,n))||s.enumerable});return t};var Xe=(t,e,r)=>(r=t!=null?$t(_t(t)):{},ze(e||!t||!t.__esModule?me(r,"default",{value:t,enumerable:!0}):r,t)),Lt=t=>ze(me({},"__esModule",{value:!0}),t);var ar={};vt(ar,{CLOUD_ONLY_FORMS:()=>pe,CLOUD_ONLY_METHODS:()=>le,CloudOnlyError:()=>K,DBRecordInstance:()=>T,DBRecordsArrayInstance:()=>$,DirectModeError:()=>ee,EmptyTargetError:()=>C,HttpClient:()=>B,HttpClientResponse:()=>ye,Model:()=>He,NonUniqueResultError:()=>ce,RestAPI:()=>J,RushDB:()=>w,Transaction:()=>M,UniquenessError:()=>L,default:()=>sr,idToDate:()=>Be,idToTimestamp:()=>Re,initSDK:()=>Fe,isCloudOnlyMethod:()=>st,mergeDefaultsWithPayload:()=>de,parseConfig:()=>Ce,pickUniqFieldsFromRecord:()=>Se,pickUniqFieldsFromRecords:()=>ke,validateInteger:()=>_e});module.exports=Lt(ar);var B=class t{makeRequest(e,{headers:r,method:s,protocol:n,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(t.TIMEOUT_ERROR_CODE);return e.code=t.TIMEOUT_ERROR_CODE,e}};B.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];B.TIMEOUT_ERROR_CODE="ETIMEDOUT";var ge=class{constructor(e,r){this._statusCode=e,this._headers=r}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.")}},ye=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 Ee=Xe(require("http"),1),Oe=Xe(require("https"),1);var jt="string",Ut="datetime",Mt="boolean",Vt="number",Ze=[jt,Ut,Mt,Vt];var tt=Ee.default||Ee,rt=Oe.default||Oe,Nt=new tt.Agent({keepAlive:!0}),Ft=new rt.Agent({keepAlive:!0}),fe=class extends B{constructor(e){super(),this._agent=e}makeRequest(e,{headers:r,method:s,protocol:n,requestData:a,timeout:o}){let i=new URL(e),d=n==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Nt:Ft),new Promise((l,p)=>{let h=(d?tt:rt).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:r,host:i.hostname,method:s,path:i.pathname+i.search,port:i.port});h.setTimeout(o!=null?o:8e4,()=>{h.destroy(B.makeTimeoutError())}),h.on("response",u=>{l(new Pe(u))}),h.on("error",u=>{p(u)}),h.once("socket",u=>{let g=a?JSON.stringify(a):"";u.connecting?u.once(d?"connect":"secureConnect",()=>{h.write(g),h.end()}):(h.write(g),h.end())})})}},Pe=class extends ge{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,r)=>{let s="";this._res.setEncoding("utf8"),this._res.on("data",n=>{s+=n}),this._res.once("end",()=>{try{e(JSON.parse(s))}catch(n){r(n)}})})}};var I=t=>typeof t=="object"&&Array.isArray(t)&&t!==null,P=t=>t!==null&&Object.prototype.toString.call(t)==="[object Object]",z=t=>P(t)&&Object.keys(t).length===0,Ae=t=>typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null;function Ht(t,e){let r={...t};return e.forEach(s=>{delete r[s]}),r}var X=t=>P(t)?Ht(t,["__label","__id","__proptypes"]):t,Q=t=>I(t)?t.map(Q):P(t)?Object.fromEntries(Object.entries(t).filter(([e,r])=>r!==void 0).map(([e,r])=>[e,Q(r)])):t,qe=t=>I(t)?t.every(Ae):Ae(t),Z=t=>P(t)&&Object.values(t).every(qe),Qt=t=>P(t)||I(t)&&!t.every(Ae),nt=t=>{if(I(t)||!P(t))return!0;let e=Object.values(t);return e.length===0?!0:e.some(r=>!Qt(r))},v=t=>typeof t=="string",O=t=>{if(typeof t=="string"){if(t.toLowerCase()==="true")return!0;if(t.toLowerCase()==="false")return!1}return I(t)&&t.length===0||P(t)&&Object.keys(t).length===0?!1:!!t};var $e=["httpClient","timeout","host","port","protocol","url","logger","options","direct","engineUrl","scope"];var L=class t extends Error{constructor(e,r){super(`Record with label "${e}" and properties ${JSON.stringify(r)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,t.prototype)}},C=class t extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,t.prototype)}},ce=class t extends Error{constructor(e,r){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(r)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,t.prototype)}},K=class t extends Error{constructor(r,s){super(`${r} requires RushDB Cloud: ${s}. It is not available in direct mode.`);this.method=r;this.reason=s;this.code="CLOUD_ONLY";this.name="CloudOnlyError",Object.setPrototypeOf(this,t.prototype)}},ee=class t extends Error{constructor(r){super(r);this.code="DIRECT_MODE_UNSUPPORTED";this.name="DirectModeError",Object.setPrototypeOf(this,t.prototype)}};var de=async(t,e)=>{let r=Object.entries(t).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(r)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},Se=(t,e)=>Object.entries(e).filter(([r])=>{var s;return(s=t[r])==null?void 0:s.unique}).reduce((r,[s,n])=>(s in t&&(r[s]=n),r),{}),ke=(t,e,r)=>{let s={},n=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[o])=>(a[o]=!0,a),{});return t.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in n)if(s[o]){if(s[o].includes(i))throw new L(r,{[o]:i});s[o]=[...s[o],i]}else s[o]=[i]})}),s},Ce=t=>{if(!t)return{};if(!P(t))throw new Error("Config must be an object");if(Object.keys(t).filter(r=>!$e.includes(r)).length>0)throw new Error(`Config object may only contain the following: ${$e.join(", ")}`);return t};function _e(t,e,r){if(!Number.isInteger(e)){if(r!==void 0)return r;throw new Error(`${t} must be an integer`)}return e}function Re(t){let e=t.split("-"),r=e[0]+e[1].slice(0,4);return parseInt(r,16)}function Be(t){return new Date(Re(t))}var T=class{constructor(e={}){this.data=e}get exists(){return O(this.data.__id)&&O(this.data.__label)}get id(){if(!O(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}get label(){if(!O(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}get proptypes(){if(!O(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}get date(){try{return Be(this.id)}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}get timestamp(){try{return Re(this.id)}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or invalid.")}}get score(){return this.data.__score}async delete(e){if(!O(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await w.getInstance().records.deleteById(this.id,e)}async update(e,r){if(!O(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return w.getInstance().records.update({label:this.label,target:this.id,data:e},r)}async set(e,r){if(!O(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return w.getInstance().records.set({label:this.label,target:this.id,data:e},r)}async attach(e,r,s){if(!O(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return w.getInstance().records.attach({source:this.id,target:e,options:r},s)}async detach(e,r,s){if(!O(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return w.getInstance().records.detach({source:this.id,target:e,options:r},s)}},$=class{constructor(e=[],r=0,s,n){this.data=e,this.total=r,this.searchQuery=s,this.warnings=n}async deleteAll(e){let r=this.data.map(n=>n.id);return r.length?await w.getInstance().records.deleteById(r,e):{success:!0}}async next(e){var i,d,c;if(this.sql){let{skip:l,limit:p}=(i=this.sqlPage)!=null?i:{skip:0,limit:100},h={skip:l+p,limit:p},u=await w.getInstance().ai.runSql(this.sql,h);return e!=null&&e.preserveData?(this.data=[...this.data,...u.data],this.total=u.total,this.sqlPage=h,this):(u.name=this.name,u)}if(!this.searchQuery)throw new Error("DBRecordsArrayInstance: Cannot paginate \u2014 no searchQuery was provided.");let r=(d=this.searchQuery.skip)!=null?d:0,s=(c=this.searchQuery.limit)!=null?c:100,n={...this.searchQuery,skip:r+s},o=await w.getInstance().records.find(n,void 0);return e!=null&&e.preserveData?(this.data=[...this.data,...o.data],this.total=o.total,this.searchQuery=n,this):o}exportCsv(){if(!this.data.length)return"";let e=new Set(["__id","__label","__proptypes"]),r=Object.keys(this.data[0].data).filter(a=>!e.has(a)),s=a=>{let o=a==null?"":String(a);return o.includes(",")||o.includes('"')||o.includes(`
2
2
  `)?`"${o.replace(/"/g,'""')}"`:o},n=this.data.map(a=>r.map(o=>s(a.data[o])).join(","));return[r.join(","),...n].join(`
3
- `)}async setProperties(e,r){let n=w.getInstance();for(let a=0;a<this.data.length;a+=100){let o=this.data.slice(a,a+100);await Promise.all(o.map(i=>n.records.update({target:i.id,label:i.data.__label,data:e},r)))}}};var Re=class{constructor(e){this.baseUrl=e.engineUrl.replace(/\/$/,""),this.token=e.token,this.httpClient=e.httpClient,this.scope=e.scope}async execute(e){var i,d;let r={protocolVersion:1,...this.scope?{context:{scope:this.scope}}:{},operation:e},s={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`};this.scope&&(s["X-RushDB-Tenant"]=this.scope);let n=await this.httpClient.makeRequest(`${this.baseUrl}/protocol/v1/execute`,{method:"POST",headers:s,requestData:r}),a=n.getStatusCode(),o=await n.toJSON().catch(()=>{});if(a>=400||o!=null&&o.error||!(o!=null&&o.response)){let c=(d=(i=o==null?void 0:o.error)==null?void 0:i.message)!=null?d:"engine request failed",l=new Error(`${a} ${c}`);throw l.status=a,l.body=o,l}return o.response}};var le={"ai.search":"natural-language search turns the prompt into a SQL statement with an LLM","ai.runSql":"Smart search SQL runs on the platform, which loads the full records the statement selects","ai.getJoinCandidates":"join suggestions are computed by the platform (its heuristics over the engine's value overlap)","relationships.patterns.list":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.analyze":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.approve":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.ignore":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.delete":"relationship-pattern suggestions are produced and stored by the platform","settings.get":"project settings belong to the platform"},pe={"records.vectorSearch":"a text `query` is embedded with the managed embedding model; in direct mode pass `queryVector`","ai.indexes.create":"a managed index is filled by the managed embedding model; in direct mode create an external index (`external: true`) and supply vectors"},st=t=>Object.prototype.hasOwnProperty.call(le,t);var ve=async(t,e,r)=>{var p,h,u,y,S,q,C,ne,se,ae,oe,V,N,H,ie,Qe,Ke,We,Ye,Je;let[s,n]=await Promise.all([t.execute({kind:"describe",describe:{kind:"schema",query:{labels:[],predicate:{},offset:0}}}),t.execute({kind:"describe",describe:{kind:"vectorIndexes"}})]),a=(p=s.schema)!=null?p:{labels:[],properties:[],relationships:[]},o=new Map;for(let m of(h=a.properties)!=null?h:[]){let D=(u=m.label)!=null?u:"";if(!D)continue;let b={id:String(m.id),name:String(m.name),type:String((y=m.type)!=null?y:"string"),recordsCount:Number((S=m.recordsCount)!=null?S:0),isArray:(q=m.isArray)!=null?q:void 0};if(b.type==="boolean")b.values=["true","false"];else if(b.type==="string"){let qt=((C=m.sampleValues)!=null?C:[]).filter(Ge=>Ge!=null).map(String);b.values=[...new Set(qt)].slice(0,10)}m.min!==void 0&&m.min!==null&&(b.min=b.type==="number"?Number(m.min):String(m.min)),m.max!==void 0&&m.max!==null&&(b.max=b.type==="number"?Number(m.max):String(m.max));let G=(ne=o.get(D))!=null?ne:[];G.push(b),o.set(D,G)}let i=((se=a.labels)!=null?se:[]).map(m=>{var D,b;return{label:m.name,count:Number((D=m.recordsCount)!=null?D:0),properties:(b=o.get(m.name))!=null?b:[],relationships:[]}}),d=new Map(i.map(m=>[m.label,m])),c=(m,D)=>{let b=d.get(m);b&&!b.relationships.some(G=>G.direction===D.direction&&G.label===D.label&&G.type===D.type)&&b.relationships.push(D)};for(let m of(ae=a.relationships)!=null?ae:[]){let D=(oe=m.properties)!=null&&oe.length?m.properties:void 0;c(m.sourceLabel,{label:m.targetLabel,type:m.type,direction:"out",count:m.count,properties:D}),m.sourceLabel!==m.targetLabel&&c(m.targetLabel,{label:m.sourceLabel,type:m.type,direction:"in",count:m.count,properties:D})}let l=new Map;for(let m of((V=n.indexes)!=null?V:[]).map(r)){let D=`${m.label}|${m.propertyName}`,b=(N=l.get(D))!=null?N:[];b.push({id:String((H=m.id)!=null?H:""),name:String((ie=m.name)!=null?ie:""),sourceType:String((Qe=m.sourceType)!=null?Qe:"external"),similarityFunction:String((Ke=m.similarityFunction)!=null?Ke:"cosine"),dimensions:Number((We=m.dimensions)!=null?We:0),status:String((Ye=m.status)!=null?Ye:"pending"),modelKey:String((Je=m.modelKey)!=null?Je:"")}),l.set(D,b)}for(let m of i){m.relationships.sort((D,b)=>`${D.direction}|${D.label}|${D.type}`.localeCompare(`${b.direction}|${b.label}|${b.type}`));for(let D of m.properties){let b=l.get(`${m.label}|${D.name}`);b!=null&&b.length&&(D.vectorIndexes=b)}}return i.sort((m,D)=>D.count-m.count),e!=null&&e.length?i.filter(m=>e.includes(m.label)):i},at=t=>{var i,d;let e=c=>String(c).replace(/\|/g,"\\|").replace(/`/g,"\\`"),n=c=>c.length>48?c.slice(0,48)+"\u2026":c,a=c=>{let l=(c.type||"").toLowerCase();if(l==="number"||l==="datetime")return c.min!==void 0&&c.max!==void 0?`\`${c.min}\`..\`${c.max}\``:"\u2014";if(Array.isArray(c.values)&&c.values.length>0){let p=c.values.slice(0,5),h=c.values.length>5?` (+${c.values.length-5} more)`:"";return p.map(u=>`\`${e(n(String(u)))}\``).join(", ")+h}return"\u2014"},o=`# Graph Schema
3
+ `)}async setProperties(e,r){let n=w.getInstance();for(let a=0;a<this.data.length;a+=100){let o=this.data.slice(a,a+100);await Promise.all(o.map(i=>n.records.update({target:i.id,label:i.data.__label,data:e},r)))}}};var we=class{constructor(e){this.baseUrl=e.engineUrl.replace(/\/$/,""),this.token=e.token,this.httpClient=e.httpClient,this.scope=e.scope}async execute(e){var i,d;let r={protocolVersion:1,...this.scope?{context:{scope:this.scope}}:{},operation:e},s={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`};this.scope&&(s["X-RushDB-Tenant"]=this.scope);let n=await this.httpClient.makeRequest(`${this.baseUrl}/protocol/v1/execute`,{method:"POST",headers:s,requestData:r}),a=n.getStatusCode(),o=await n.toJSON().catch(()=>{});if(a>=400||o!=null&&o.error||!(o!=null&&o.response)){let c=(d=(i=o==null?void 0:o.error)==null?void 0:i.message)!=null?d:"engine request failed",l=new Error(`${a} ${c}`);throw l.status=a,l.body=o,l}return o.response}};var le={"ai.search":"natural-language search turns the prompt into a SQL statement with an LLM","ai.runSql":"Smart search SQL runs on the platform, which loads the full records the statement selects","ai.getJoinCandidates":"join suggestions are computed by the platform (its heuristics over the engine's value overlap)","relationships.patterns.list":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.analyze":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.approve":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.ignore":"relationship-pattern suggestions are produced and stored by the platform","relationships.patterns.delete":"relationship-pattern suggestions are produced and stored by the platform","settings.get":"project settings belong to the platform"},pe={"records.vectorSearch":"a text `query` is embedded with the managed embedding model; in direct mode pass `queryVector`","ai.indexes.create":"a managed index is filled by the managed embedding model; in direct mode create an external index (`external: true`) and supply vectors"},st=t=>Object.prototype.hasOwnProperty.call(le,t);var ve=async(t,e,r)=>{var p,h,u,g,S,q,_,ne,se,ae,oe,N,F,H,ie,Qe,Ke,We,Ye,Je;let[s,n]=await Promise.all([t.execute({kind:"describe",describe:{kind:"schema",query:{labels:[],predicate:{},offset:0}}}),t.execute({kind:"describe",describe:{kind:"vectorIndexes"}})]),a=(p=s.schema)!=null?p:{labels:[],properties:[],relationships:[]},o=new Map;for(let m of(h=a.properties)!=null?h:[]){let D=(u=m.label)!=null?u:"";if(!D)continue;let b={id:String(m.id),name:String(m.name),type:String((g=m.type)!=null?g:"string"),recordsCount:Number((S=m.recordsCount)!=null?S:0),isArray:(q=m.isArray)!=null?q:void 0};if(b.type==="boolean")b.values=["true","false"];else if(b.type==="string"){let qt=((_=m.sampleValues)!=null?_:[]).filter(Ge=>Ge!=null).map(String);b.values=[...new Set(qt)].slice(0,10)}m.min!==void 0&&m.min!==null&&(b.min=b.type==="number"?Number(m.min):String(m.min)),m.max!==void 0&&m.max!==null&&(b.max=b.type==="number"?Number(m.max):String(m.max));let G=(ne=o.get(D))!=null?ne:[];G.push(b),o.set(D,G)}let i=((se=a.labels)!=null?se:[]).map(m=>{var D,b;return{label:m.name,count:Number((D=m.recordsCount)!=null?D:0),properties:(b=o.get(m.name))!=null?b:[],relationships:[]}}),d=new Map(i.map(m=>[m.label,m])),c=(m,D)=>{let b=d.get(m);b&&!b.relationships.some(G=>G.direction===D.direction&&G.label===D.label&&G.type===D.type)&&b.relationships.push(D)};for(let m of(ae=a.relationships)!=null?ae:[]){let D=(oe=m.properties)!=null&&oe.length?m.properties:void 0;c(m.sourceLabel,{label:m.targetLabel,type:m.type,direction:"out",count:m.count,properties:D}),m.sourceLabel!==m.targetLabel&&c(m.targetLabel,{label:m.sourceLabel,type:m.type,direction:"in",count:m.count,properties:D})}let l=new Map;for(let m of((N=n.indexes)!=null?N:[]).map(r)){let D=`${m.label}|${m.propertyName}`,b=(F=l.get(D))!=null?F:[];b.push({id:String((H=m.id)!=null?H:""),name:String((ie=m.name)!=null?ie:""),sourceType:String((Qe=m.sourceType)!=null?Qe:"external"),similarityFunction:String((Ke=m.similarityFunction)!=null?Ke:"cosine"),dimensions:Number((We=m.dimensions)!=null?We:0),status:String((Ye=m.status)!=null?Ye:"pending"),modelKey:String((Je=m.modelKey)!=null?Je:"")}),l.set(D,b)}for(let m of i){m.relationships.sort((D,b)=>`${D.direction}|${D.label}|${D.type}`.localeCompare(`${b.direction}|${b.label}|${b.type}`));for(let D of m.properties){let b=l.get(`${m.label}|${D.name}`);b!=null&&b.length&&(D.vectorIndexes=b)}}return i.sort((m,D)=>D.count-m.count),e!=null&&e.length?i.filter(m=>e.includes(m.label)):i},at=t=>{var i,d;let e=c=>String(c).replace(/\|/g,"\\|").replace(/`/g,"\\`"),n=c=>c.length>48?c.slice(0,48)+"\u2026":c,a=c=>{let l=(c.type||"").toLowerCase();if(l==="number"||l==="datetime")return c.min!==void 0&&c.max!==void 0?`\`${c.min}\`..\`${c.max}\``:"\u2014";if(Array.isArray(c.values)&&c.values.length>0){let p=c.values.slice(0,5),h=c.values.length>5?` (+${c.values.length-5} more)`:"";return p.map(u=>`\`${e(n(String(u)))}\``).join(", ")+h}return"\u2014"},o=`# Graph Schema
4
4
 
5
5
  ## Labels
6
6
 
@@ -16,12 +16,12 @@
16
16
 
17
17
  `,o+=`| Property | Type | Values / Range | Semantic Search |
18
18
  |----------|------|----------------|-----------------|
19
- `;for(let p of c.properties){let h=(i=p.vectorIndexes)!=null&&i.length?p.vectorIndexes.map(y=>`\`${y.name}\` (${y.sourceType}, ${y.similarityFunction}, ${y.dimensions}d) [${y.status}]`).join(", "):"\u2014",u=p.isArray?`${p.type}[]`:p.type;o+=`| \`${e(p.name)}\` | ${e(u)} | ${a(p)} | ${h} |
19
+ `;for(let p of c.properties){let h=(i=p.vectorIndexes)!=null&&i.length?p.vectorIndexes.map(g=>`\`${g.name}\` (${g.sourceType}, ${g.similarityFunction}, ${g.dimensions}d) [${g.status}]`).join(", "):"\u2014",u=p.isArray?`${p.type}[]`:p.type;o+=`| \`${e(p.name)}\` | ${e(u)} | ${a(p)} | ${h} |
20
20
  `}o+=`
21
21
  `}if(c.relationships.length>0){o+=`### Relationships
22
22
 
23
23
  `,o+=`| Traversal | Count | Edge Properties |
24
24
  |-----------|------:|-----------------|
25
- `;for(let p of c.relationships){let h=(d=p.properties)!=null&&d.length?p.properties.map(S=>`\`${e(S.name)}:${e(S.type)}\``).join(", "):"\u2014",u=p.direction==="out"?`(${c.label})-[:${p.type}]->(${p.label})`:`(${c.label})<-[:${p.type}]-(${p.label})`,y=typeof p.count=="number"?String(p.count):"\u2014";o+=`| \`${e(u)}\` | ${y} | ${h} |
25
+ `;for(let p of c.relationships){let h=(d=p.properties)!=null&&d.length?p.properties.map(S=>`\`${e(S.name)}:${e(S.type)}\``).join(", "):"\u2014",u=p.direction==="out"?`(${c.label})-[:${p.type}]->(${p.label})`:`(${c.label})<-[:${p.type}]-(${p.label})`,g=typeof p.count=="number"?String(p.count):"\u2014";o+=`| \`${e(u)}\` | ${g} | ${h} |
26
26
  `}o+=`
27
- `}}return o.trim()};var f=(t,e={})=>({success:!0,data:t,...e}),A=(t,e)=>{let r=new Error(`${t} ${e}`);return r.status=t,r.body={statusCode:t,message:e},r},j=t=>async()=>{throw new K(t,le[t])},F=(t,e)=>{if(t)throw new ee(`${e} inside a transaction is not supported in direct mode: the engine stages record creates, updates, deletes, links and imports. Run it outside the transaction.`)},ut="__RUSHDB__RELATION__DEFAULT__",W=(t,e,r)=>t.execute({kind:"transaction",transaction:{kind:"stage",transactionId:e,mutation:r}}),je=async(t,e,r)=>{var n;let{record:s}=await W(t,e,{kind:"getRecord",record:{id:r}});return{...(n=s==null?void 0:s.properties)!=null?n:{},__id:r,__label:s==null?void 0:s.__label,__proptypes:{}}},mt=(t,e)=>{t&&Array.isArray(e)&&e.length>0&&F(t,"A write with inline vectors")},be=t=>{var r,s;if(!t)return t;let e={...(r=t.properties)!=null?r:{}};return e.__id=t.id,e.__label=t.label,e.__proptypes=(s=t.propertyTypes)!=null?s:{},t.score!==void 0&&(e.__score=t.score),e},De=t=>(t!=null?t:[]).map(e=>be(e)),Ue=t=>t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:Array.isArray(t.properties)?Object.fromEntries(t.properties.map(e=>[e.name,e.value])):t.properties&&typeof t.properties=="object"?t.properties:{},Kt=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?"desc":typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).map(([e,r])=>[e==="__id"?"id":e,r])),te=(t={})=>{var s,n,a,o,i,d;let e=(s=t.pagination)!=null?s:{},r={labels:(n=t.labels)!=null?n:[],predicate:(a=t.where)!=null?a:{},select:t.select,order:Kt(t.orderBy),offset:(i=(o=t.skip)!=null?o:e.skip)!=null?i:0,limit:(d=t.limit)!=null?d:e.limit};return Array.isArray(t.groupBy)&&t.groupBy.length>0&&(r.groupBy=t.groupBy),r},xe=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0,Ne=async(t,e)=>(await t.execute({kind:"query",query:{kind:"record",id:e}})).record,gt=async(t,e)=>{var s,n,a;let r=await t.execute({kind:"query",query:{kind:"records",query:te(e)}});return r.kind==="rows"?{data:(s=r.rows)!=null?s:[],total:(n=r.total)!=null?n:0}:{data:De(r.records),total:(a=r.total)!=null?a:0}},re=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"vectorIndexes"}})).indexes)!=null?e:[]},Me=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"indexes"}})).indexes)!=null?e:[]},he=t=>{var r;let e=Number((r=t.dimensions)!=null?r:0);return{id:t.name,name:t.name,label:t.label,propertyName:t.property,vectorPropertyName:`_emb_external_${t.similarity}_${e}`,similarityFunction:t.similarity,dimensions:e,sourceType:"external",status:t.status}},yt=t=>{var e,r;return{name:t.name,label:t.label,property:t.property,consistency:(e=t.consistency)!=null?e:"eventual",status:t.state,pending:(r=t.pending)!=null?r:0}},Ve=async t=>(await Me(t)).filter(e=>e.kind==="text").map(yt),ft=64,St=t=>t.join(".").slice(0,ft).replace(/[.:-]+$/,""),Te=t=>t.replace(/[^A-Za-z0-9_-]/g,"-"),Le=(t,e)=>{if(!e.has(t))return t;for(let r=2;;r++){let s=`-${r}`,n=t.slice(0,ft-s.length)+s;if(!e.has(n))return n}},ot=({label:t,property:e})=>St([Te(t),e==="*"?"all":Te(e),"text"]),Wt=(t,e,r)=>St([Te(t.label),Te(t.propertyName),"external",String(e),r]).replace(/^emb__/,"emb_"),Ie=async(t,e,r,s)=>{if(!Array.isArray(e)||e.length===0)return[];let n=s!=null?s:await re(t);return e.map(a=>{if(typeof(a==null?void 0:a.index)=="string")return a;if(!r)throw A(422,"inline vectors require a record label to select their index");let o=Array.isArray(a.vector)?a.vector.length:void 0,i=n.filter(d=>d.label===r&&d.property===a.propertyName&&(a.similarityFunction===void 0||d.similarity===a.similarityFunction)&&(o===void 0||Number(d.dimensions)===o));if(i.length!==1)throw A(i.length===0?404:422,i.length===0?`No vector index matches label "${r}", property "${a.propertyName}"`:`${i.length} vector indexes match label "${r}", property "${a.propertyName}"; name one with \`index\``);return{...a,index:i[0].name}})},Yt=async(t,e,r)=>{let s=Array.isArray(e)?e:[e],n=i=>Array.isArray(i==null?void 0:i.$vectors)&&i.$vectors.length>0;if(!s.some(n))return e;let a=await re(t),o=await Promise.all(s.map(async i=>n(i)?{...i,$vectors:await Ie(t,i.$vectors,r,a)}:i));return Array.isArray(e)?o:o[0]},Jt=()=>{var s;let t=new Uint8Array(16);if(typeof((s=globalThis.crypto)==null?void 0:s.getRandomValues)=="function")globalThis.crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);let e=Date.now();for(let n=0;n<6;n++)t[n]=Math.floor(e/2**(8*(5-n)))&255;t[6]=t[6]&15|112,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},Gt=async({body:t,engine:e,txId:r})=>{var i,d,c,l,p,h;let s=!!((i=t.options)!=null&&i.mergeStrategy)||Array.isArray((d=t.options)==null?void 0:d.mergeBy),n=Ue(t);if(r){s&&F(r,"An upsert"),mt(r,t.vectors);let u=Jt();return await W(e,r,{kind:"createRecord",label:t.label,id:u,properties:n,options:(c=t.options)!=null?c:{}}),f(await je(e,r,u))}let a=s?{...t.options,mergeBy:(p=(l=t.options)==null?void 0:l.mergeBy)!=null?p:[]}:(h=t.options)!=null?h:{},o=await e.execute({kind:"mutate",mutation:{kind:"putRecord",mode:"create",label:t.label,properties:n,vectors:await Ie(e,t.vectors,t.label),options:a}});return f(be(o.record))},it=t=>async({body:e,params:[r],engine:s,txId:n})=>{var d,c;let a=typeof e.label=="string"&&e.label?e.label:void 0;if(n){if(mt(n,e.vectors),a){let l=await je(s,n,r);l.__label&&l.__label!==a&&await W(s,n,{kind:"retypeRecord",record:{id:r},fromLabel:l.__label,toLabel:a})}return await W(s,n,{kind:"updateRecord",record:{id:r},properties:Ue(e),replace:t==="replace"}),f(await je(s,n,r))}let o=a;if(a||(d=e.vectors)!=null&&d.length){let l=await Ne(s,r);a&&(l!=null&&l.label)&&l.label!==a&&await s.execute({kind:"mutate",mutation:{kind:"retypeRecord",id:r,fromLabel:l.label,toLabel:a}}),o=a!=null?a:l==null?void 0:l.label}let i=await s.execute({kind:"mutate",mutation:{kind:"putRecord",mode:t,id:r,properties:Ue(e),vectors:await Ie(s,e.vectors,o),options:(c=e.options)!=null?c:{}}});return f(be(i.record))},zt=async(t,e,r)=>{var o;if(!e)return r;let s;try{s=(o=await Ne(t,e))==null?void 0:o.label}catch(i){if((i==null?void 0:i.status)===404)return;throw i}let n={[s]:{$id:e}},a=r.where;return{...r,where:xe(a)?n:{$and:[a,n]}}},ct=async({body:t,params:[e],engine:r})=>{let s=await zt(r,e,t);if(!s)return f([],{total:0});let{data:n,total:a}=await gt(r,s);return f(n,{total:a})},dt=(t,e,r)=>e?W(t,e,{kind:"ingest",ingest:r}):t.execute({kind:"ingest",ingest:r}),lt=(t,e)=>{var r,s;return e&&((r=t.records)!=null&&r.length)?f(De(t.records)):f({message:"Records have been successfully imported",count:Number((s=t.count)!=null?s:0)})},Xt=["delimiter","header","skipEmptyLines","dynamicTyping","quoteChar","escapeChar","newline"],pt=t=>{var e,r,s,n,a,o,i,d,c,l,p,h;return{relationType:(e=t.type)!=null?e:ut,direction:String((r=t.direction)!=null?r:"").toLowerCase()==="in"?"in":"out",allowCartesian:(s=t.manyToMany)!=null?s:!1,properties:(n=t.properties)!=null?n:{},source:{label:(a=t.source)==null?void 0:a.label,property:(o=t.source)==null?void 0:o.key,predicate:(d=(i=t.source)==null?void 0:i.where)!=null?d:{}},target:{label:(c=t.target)==null?void 0:c.label,property:(l=t.target)==null?void 0:l.key,predicate:(h=(p=t.target)==null?void 0:p.where)!=null?h:{}}}},we=t=>Array.isArray(t)?t:[t],Zt=t=>{var r,s;let e=new Map;for(let n of t){let a=e.get(n.id);if(a){a.recordsCount+=Number((r=n.recordsCount)!=null?r:0),a.isArray||(a.isArray=n.isArray===!0);continue}e.set(n.id,{id:n.id,name:n.name,type:n.type,recordsCount:Number((s=n.recordsCount)!=null?s:0),isArray:n.isArray===!0})}return Array.from(e.values(),({isArray:n,...a})=>({...a,metadata:JSON.stringify({cardinality:n?"OrderedMany":"Single",nullability:"Nullable"})}))},Rt=async(t,e={})=>{var s;let r=await t.execute({kind:"describe",describe:{kind:"properties",query:te(e),...xe(e.where)?{detail:"catalog"}:{}}});return Zt((s=r.properties)!=null?s:[])},ht=async(t,e)=>{var s;let r=(await Rt(t)).find(n=>n.name===e||n.id===e);return r&&{...r,id:(s=r.id)!=null?s:r.name}},wt=async(t,e,r)=>{var a,o;if(typeof e.query!="string"||e.query.trim()==="")throw A(422,"text.query is required");let s=await Ve(t),n;if(e.index!==void 0){if(n=s.find(i=>i.name===e.index),!n)throw A(404,`No text index named "${e.index}"`)}else{let i=r[0];if(!i)throw A(422,"Name a text index with `index`, or give `labels`");let d=s.filter(c=>c.label===i&&c.status==="ready"&&(e.property===void 0||c.property===e.property));if(d.length===0)throw A(404,`No ready text index on label "${i}"`);if(d.length>1)throw A(422,`Label "${i}" has several text indexes (${d.map(c=>c.name).join(", ")}); name one with \`index\``);n=d[0]}return{index:n.name,label:n.label,query:e.query,allTerms:(a=e.allTerms)!=null?a:!1,phrase:(o=e.phrase)!=null?o:!1}},er=async({body:t,engine:e})=>{var p,h,u,y,S,q,C,ne,se,ae,oe;let r=(p=t.queryVector)!=null?p:[];if(r.length===0)throw new K("records.vectorSearch",pe["records.vectorSearch"]);let s=await re(e),n;if(typeof t.index=="string"){if(n=s.find(V=>V.name===t.index),!n)throw A(404,`No vector index named "${t.index}"`)}else{let V=((h=t.labels)!=null?h:[])[0],N=s.filter(H=>{var ie;return H.label===V&&H.property===t.propertyName&&(t.similarityFunction===void 0||H.similarity===t.similarityFunction)&&Number(H.dimensions)===((ie=t.dimensions)!=null?ie:r.length)});if(N.length!==1)throw A(N.length===0?404:422,N.length===0?`No vector index matches label "${V}", property "${t.propertyName}"`:`${N.length} vector indexes match label "${V}", property "${t.propertyName}"; name one with \`index\``);n=N[0]}let a=(u=t.labels)!=null&&u.length?t.labels:[n.label],o={property:n.property,vector:r,similarity:(y=n.similarity)!=null?y:"cosine",index:n.name,mode:t.mode,ef:t.ef,scoreThreshold:t.scoreThreshold},i=t.text?await wt(e,{...t.text,query:(S=t.text.query)!=null?S:t.query},a):void 0,d=i?{kind:"hybrid",query:{labels:a,predicate:(q=t.where)!=null?q:{},vector:{...o,weight:t.weight,prefetchLimit:t.prefetchLimit},text:{index:i.index,query:i.query,allTerms:i.allTerms,phrase:i.phrase,weight:t.text.weight,prefetchLimit:t.text.prefetchLimit},fusion:t.fusion,rrfK:t.rrfK,offset:(C=t.skip)!=null?C:0,limit:(ne=t.limit)!=null?ne:10}}:{kind:"vector",query:{...o,labels:a,predicate:(se=t.where)!=null?se:{},offset:(ae=t.skip)!=null?ae:0,limit:(oe=t.limit)!=null?oe:10}},c=await e.execute({kind:"query",query:d}),l=De(c.records);return f(l,{total:l.length,meta:{vectorSearch:c.vectorSearch,textSearch:c.textSearch,fusion:c.fusion}})},E="([^/]+)",xt=[{method:"GET",pattern:new RegExp(`^/records/${E}$`),handle:async({params:[t],engine:e})=>f(be(await Ne(e,t)))},{method:"POST",pattern:/^\/records$/,handle:Gt},{method:"PATCH",pattern:new RegExp(`^/records/${E}$`),handle:it("merge")},{method:"PUT",pattern:new RegExp(`^/records/${E}$`),handle:it("replace")},{method:"DELETE",pattern:new RegExp(`^/records/${E}$`),handle:async({params:[t],engine:e,txId:r})=>(r?await W(e,r,{kind:"deleteRecord",record:{id:t}}):await e.execute({kind:"mutate",mutation:{kind:"deleteRecord",id:t}}),f({message:"Record deleted"}))},{method:"POST",pattern:/^\/records\/delete$/,handle:async({body:t,engine:e,txId:r})=>{var n;F(r,"records.delete");let s=await e.execute({kind:"mutate",mutation:{kind:"deleteRecords",query:te(t)}});return f({message:`${(n=s.affected)!=null?n:0} records deleted`})}},{method:"POST",pattern:/^\/records\/search$/,handle:ct},{method:"POST",pattern:new RegExp(`^/records/${E}/search$`),handle:ct},{method:"POST",pattern:/^\/records\/import\/json$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;let s=await dt(e,r,{kind:"documents",label:t.label,documents:await Yt(e,t.data,t.label),options:(n=t.options)!=null?n:{}});return lt(s,(a=t.options)==null?void 0:a.returnResult)}},{method:"POST",pattern:/^\/records\/import\/csv$/,handle:async({body:t,engine:e,txId:r})=>{var i,d,c,l,p,h,u;let s=(i=t.vectors)!=null&&i.length?await re(e):[],n=await Promise.all(((d=t.vectors)!=null?d:[]).map(y=>Ie(e,y,t.label,s))),a=Object.fromEntries(Object.entries((c=t.parseConfig)!=null?c:{}).filter(([y])=>Xt.includes(y))),o=await dt(e,r,{kind:"csv",label:t.label,data:(l=t.data)!=null?l:"",parseConfig:a,options:(p=t.options)!=null?p:{},vectors:n});return Number((h=o.count)!=null?h:0)===0?f(!0):lt(o,(u=t.options)==null?void 0:u.returnResult)}},{method:"POST",pattern:/^\/records\/export\/csv$/,handle:async({body:t,engine:e})=>{let r=await e.execute({kind:"query",query:{kind:"exportCsv",query:te({labels:t.labels,where:t.where,orderBy:t.orderBy,skip:typeof t.skip=="number"?t.skip:0,limit:typeof t.limit=="number"?t.limit:100})}});return f({fileContent:r.content,dateTime:new Date().toISOString()})}},{method:"POST",pattern:new RegExp(`^/relationships/${E}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var o,i,d,c;let n=(o=t.type)!=null?o:ut,a=String((i=t.direction)!=null?i:"").toLowerCase()==="in";if(s)for(let l of we(t.targetIds))await W(r,s,{kind:"createRelationship",relationType:n,source:{id:a?l:e},target:{id:a?e:l},properties:(d=t.properties)!=null?d:{}});else await r.execute({kind:"mutate",mutation:{kind:"linkRecordsById",command:{relationType:n,direction:a?"in":"out",sourceIds:[e],targetIds:we(t.targetIds),properties:(c=t.properties)!=null?c:{}}}});return f({message:`Relations to Record ${e} have been successfully created`})}},{method:"PUT",pattern:new RegExp(`^/relationships/${E}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var a;F(s,"records.detach");let n=String((a=t.direction)!=null?a:"").toLowerCase();return await r.execute({kind:"mutate",mutation:{kind:"unlinkRecordsById",command:{relationTypes:we(t.typeOrTypes).filter(Boolean),...n==="in"||n==="out"?{direction:n}:{},sourceIds:[e],targetIds:we(t.targetIds)}}}),f({message:`Relations to Record ${e} have been successfully deleted`})}},{method:"POST",pattern:/^\/relationships\/create-many$/,handle:async({body:t,engine:e,txId:r})=>(F(r,"relationships.createMany"),await e.execute({kind:"mutate",mutation:{kind:"linkRecords",command:pt(t)}}),f({message:"Relations have been successfully created"}))},{method:"POST",pattern:/^\/relationships\/delete-many$/,handle:async({body:t,engine:e,txId:r})=>(F(r,"relationships.deleteMany"),await e.execute({kind:"mutate",mutation:{kind:"unlinkRecords",command:pt(t)}}),f({message:"Relations have been successfully deleted"}))},{method:"POST",pattern:/^\/relationships\/search$/,handle:async({body:t,engine:e})=>{var s,n,a,o,i,d,c,l,p,h,u;let r=await e.execute({kind:"query",query:{kind:"relationships",query:{sourceLabels:(n=(s=t.source)==null?void 0:s.labels)!=null?n:[],targetLabels:(o=(a=t.target)==null?void 0:a.labels)!=null?o:[],relationType:(i=t.where)==null?void 0:i.type,predicate:Object.fromEntries(Object.entries((d=t.where)!=null?d:{}).filter(([y])=>y!=="type")),sourcePredicate:xe((c=t.source)==null?void 0:c.where)?void 0:t.source.where,targetPredicate:xe((l=t.target)==null?void 0:l.where)?void 0:t.target.where,offset:(p=t.skip)!=null?p:0,limit:t.limit}}});return f((h=r.relationships)!=null?h:[],{total:(u=r.total)!=null?u:0})}},{method:"GET",pattern:/^\/relationships\/patterns$/,handle:j("relationships.patterns.list")},{method:"POST",pattern:/^\/relationships\/patterns\/analyze$/,handle:j("relationships.patterns.analyze")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${E}/approve$`),handle:j("relationships.patterns.approve")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${E}/ignore$`),handle:j("relationships.patterns.ignore")},{method:"DELETE",pattern:new RegExp(`^/relationships/patterns/${E}$`),handle:j("relationships.patterns.delete")},{method:"POST",pattern:/^\/properties\/search$/,handle:async({body:t,engine:e})=>{var r,s;return f(await Rt(e,{labels:(r=t.labels)!=null?r:[],where:(s=t.where)!=null?s:{}}))}},{method:"GET",pattern:new RegExp(`^/properties/${E}$`),handle:async({params:[t],engine:e})=>{let r=await ht(e,t);if(!r)throw A(404,`property \`${t}\` does not exist`);return f(r)}},{method:"DELETE",pattern:new RegExp(`^/properties/${E}$`),handle:async({params:[t],engine:e,txId:r})=>{F(r,"properties.delete");let s=await ht(e,t);if(!s)throw A(404,`property \`${t}\` does not exist`);return await e.execute({kind:"mutate",mutation:{kind:"deleteProperty",name:s.name}}),f({message:`Property (${t}) has been successfully deleted.`})}},{method:"POST",pattern:new RegExp(`^/properties/${E}/values$`),handle:async({body:t,params:[e],engine:r})=>{var a,o,i,d,c,l;let s=!!t.query||!!t.limit,n=await r.execute({kind:"query",query:{kind:"propertyValues",property:e,query:te({labels:(a=t.labels)!=null?a:[],where:(o=t.where)!=null?o:{}}),...s?{mode:"topK",limit:(i=t.limit)!=null?i:100}:{},...t.query?{search:{text:t.query,match:(d=t.match)!=null?d:"contains",...t.domainOnMiss?{domainOnMiss:t.domainOnMiss}:{},...t.minSimilarity!==void 0?{minSimilarity:t.minSimilarity}:{}}}:{}}});return f({values:(c=n.values)!=null?c:[],...(l=n.counts)!=null&&l.length?{counts:n.counts}:{},...s&&n.distinctCount!==void 0?{distinctCount:n.distinctCount}:{},...n.searchMissed?{searchMissed:!0}:{}})}},{method:"POST",pattern:/^\/labels\/search$/,handle:async({body:t,engine:e})=>{var n;let r=await e.execute({kind:"describe",describe:{kind:"labels",query:te(t)}}),s={};for(let a of(n=r.labels)!=null?n:[])s[a]=(await gt(e,{...t,labels:[a],skip:0,limit:1})).total;return f(s)}},{method:"POST",pattern:/^\/tx$/,handle:async({body:t,engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"begin",ttlMs:t.ttl,autocommit:(s=t.autocommit)!=null?s:!1}});return f({id:r.transactionId})}},{method:"GET",pattern:new RegExp(`^/tx/${E}$`),handle:async({params:[t]})=>f({id:t})},{method:"POST",pattern:new RegExp(`^/tx/${E}/commit$`),handle:async({params:[t],engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"commit",transactionId:t}});if(r.status!=="committed")throw A(409,`Transaction commit failed: ${(s=r.reason)!=null?s:r.status}`);return f({message:`Transaction (${t}) has been successfully committed.`})}},{method:"POST",pattern:new RegExp(`^/tx/${E}/rollback$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"transaction",transaction:{kind:"rollback",transactionId:t}}),f({message:`Transaction (${t}) has been rolled back.`}))},{method:"POST",pattern:/^\/query\/raw$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;F(r,"query.raw");let s=await e.execute({kind:"query",query:{kind:"statement",language:"cypher",statement:t.query,parameters:(n=t.params)!=null?n:null}});return f({records:(a=s.rows)!=null?a:[]})}},{method:"GET",pattern:/^\/text-indexes$/,handle:async({engine:t})=>f(await Ve(t))},{method:"POST",pattern:/^\/text-indexes$/,handle:async({body:t,engine:e})=>{var n,a;let r=new Set((await Me(e)).map(o=>String(o.name)));if(t.name!==void 0&&r.has(t.name))throw A(409,`An index named "${t.name}" already exists`);let s=await e.execute({kind:"index",index:{kind:"create",definition:{name:(n=t.name)!=null?n:Le(ot(t),r),label:t.label,property:t.property,kind:"text",consistency:(a=t.consistency)!=null?a:"eventual"}}});return f(yt(s.index))}},{method:"POST",pattern:/^\/text-indexes\/name-suggestion$/,handle:async({body:t,engine:e})=>{let r=new Set((await Me(e)).map(s=>String(s.name)));return f({name:Le(ot(t),r)})}},{method:"DELETE",pattern:new RegExp(`^/text-indexes/${E}$`),handle:async({params:[t],engine:e})=>{let r=decodeURIComponent(t);if(!(await Ve(e)).some(s=>s.name===r))throw A(404,`No text index named "${r}"`);return await e.execute({kind:"index",index:{kind:"drop",name:r}}),f({deleted:!0})}},{method:"POST",pattern:/^\/search\/text$/,handle:async({body:t,engine:e})=>{var a,o,i,d,c,l,p;if(typeof t.query!="string"||t.query.trim()==="")throw A(422,"query is required");let r=await wt(e,t,(a=t.labels)!=null?a:[]),s=await e.execute({kind:"query",query:{kind:"hybrid",query:{labels:(o=t.labels)!=null&&o.length?t.labels:[r.label],predicate:(i=t.where)!=null?i:{},text:{index:r.index,query:r.query,allTerms:r.allTerms,phrase:r.phrase},offset:(d=t.skip)!=null?d:0,limit:(c=t.limit)!=null?c:10}}}),n=De(s.records);return f(n,{total:(p=(l=s.textSearch)==null?void 0:l.matches)!=null?p:n.length,meta:{textSearch:s.textSearch}})}},{method:"POST",pattern:/^\/ai\/schema$/,handle:async({body:t,engine:e})=>f(await ve(e,t.labels,he))},{method:"POST",pattern:/^\/ai\/schema\/md$/,handle:async({body:t,engine:e})=>f(at(await ve(e,t.labels,he)))},{method:"POST",pattern:/^\/ai\/sql-search$/,handle:j("ai.search")},{method:"POST",pattern:/^\/records\/sql-search$/,handle:j("ai.runSql")},{method:"POST",pattern:/^\/ai\/search$/,handle:er},{method:"GET",pattern:/^\/ai\/indexes$/,handle:async({engine:t})=>f((await re(t)).map(he))},{method:"POST",pattern:/^\/ai\/indexes$/,handle:async({body:t,engine:e})=>{var d,c;if(t.sourceType!=="external")throw new K("ai.indexes.create",pe["ai.indexes.create"]);let r=Number(t.dimensions);if(!Number.isInteger(r)||r<1||r>4096)throw A(422,"dimensions must be an integer between 1 and 4096");let s=(d=t.similarityFunction)!=null?d:"cosine",n=await re(e),a=n.find(l=>l.label===t.label&&l.property===t.propertyName&&l.similarity===s&&Number(l.dimensions)===r);if(a)throw A(409,`An embedding index for label "${t.label}", property "${t.propertyName}", sourceType "external", similarityFunction "${s}", and dimensions ${r} already exists ("${a.name}")`);let o=new Set(n.map(l=>String(l.name)));if(t.name!==void 0&&o.has(t.name))throw A(409,`An embedding index named "${t.name}" already exists`);let i=await e.execute({kind:"index",index:{kind:"createVector",definition:{label:t.label,property:t.propertyName,dimensions:r,similarity:s,name:(c=t.name)!=null?c:Le(Wt(t,r,s),o)}}});return f(he(i.index))}},{method:"DELETE",pattern:new RegExp(`^/ai/indexes/${E}$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"index",index:{kind:"dropVector",name:decodeURIComponent(t)}}),f({deleted:!0,queued:!1}))},{method:"GET",pattern:new RegExp(`^/ai/indexes/${E}/stats$`),handle:async({params:[t],engine:e})=>{var s,n;let r=await e.execute({kind:"describe",describe:{kind:"vectorIndex",name:decodeURIComponent(t)}});return f({...r.stats,index:he((n=(s=r.stats)==null?void 0:s.index)!=null?n:{})})}},{method:"POST",pattern:new RegExp(`^/ai/indexes/${E}/vectors/upsert$`),handle:async({body:t,params:[e],engine:r})=>{var n;let s=await r.execute({kind:"index",index:{kind:"upsertVectors",name:decodeURIComponent(e),items:(n=t.items)!=null?n:[]}});return f({updated:s.updated,requested:s.requested})}},{method:"POST",pattern:/^\/ai\/values\/search$/,handle:async({body:t,engine:e})=>{var s,n,a,o;let r=await e.execute({kind:"query",query:{kind:"searchValues",search:{text:t.text,match:(s=t.match)!=null?s:"contains",...t.caseSensitive?{caseSensitive:!0}:{},...t.minSimilarity!==void 0?{minSimilarity:t.minSimilarity}:{}},...(n=t.labels)!=null&&n.length?{labels:t.labels}:{},...t.limit?{limit:t.limit}:{}}});return f({matches:(a=r.matches)!=null?a:[],total:(o=r.total)!=null?o:0,...r.skipped?{skipped:r.skipped}:{}})}},{method:"POST",pattern:/^\/ai\/schema\/summary$/,handle:async({body:t,engine:e})=>{var s,n;let r=await e.execute({kind:"describe",describe:{kind:"schemaSummary",...(s=t.labels)!=null&&s.length?{labels:t.labels}:{},...t.fewValues!==void 0?{fewValues:t.fewValues}:{}}});return f((n=r.labels)!=null?n:[])}},{method:"POST",pattern:/^\/ai\/schema\/names$/,handle:async({body:t,engine:e})=>{var s;let r=await e.execute({kind:"describe",describe:{kind:"names",text:t.text,...t.limit?{limit:t.limit}:{}}});return f((s=r.names)!=null?s:[])}},{method:"POST",pattern:/^\/ai\/schema\/join-candidates$/,handle:j("ai.getJoinCandidates")},{method:"GET",pattern:/^\/sdk\/settings$/,handle:j("settings.get")}],Or=xt.map(t=>`${t.method} ${t.pattern.source}`),Tt=t=>async(e,{method:r="GET",headers:s,requestData:n})=>{var c;let a=new URL(String(e),"http://direct"),o=xt.filter(l=>l.method===r&&l.pattern.test(a.pathname)).sort((l,p)=>l.pattern.source.split("(").length-p.pattern.source.split("(").length)[0];if(!o)throw new ee(`${r} ${a.pathname} has no direct-mode mapping`);let i=((c=o.pattern.exec(a.pathname))!=null?c:[]).slice(1),d=s==null?void 0:s["x-transaction-id"];return await o.handle({body:n!=null?n:{},params:i,query:a.searchParams,txId:d,engine:t})};var tr={"Content-Type":"application/json"},bt=({httpClient:t,token:e,url:r})=>async(s,{headers:n,...a})=>{var l;let o=await t.makeRequest(`${r}${s}`,{credentials:"omit",headers:Object.assign({...tr,...n},typeof e<"u"?{Authorization:`Bearer ${e}`}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();let i="",d;try{let p=await o.toJSON();d=p;let h=(l=p==null?void 0:p.message)!=null?l:p==null?void 0:p.error;Array.isArray(h)?i=h.join("; "):typeof h=="string"&&(i=h)}catch{}let c=new Error(i?`${o.getStatusCode()} ${i}`:`${o.getStatusCode()}`);throw c.status=o.getStatusCode(),c.body=d,c};var U=class{constructor(e){this.id=e}async rollback(){return await w.getInstance().tx.rollback(this.id)}async commit(){return await w.getInstance().tx.commit(this.id)}};var Dt="api.rushdb.com";var It="https",Pt="/api/v1";var x=t=>t?{"x-transaction-id":t}:void 0,nr=t=>v(t)||t instanceof U,R=t=>nr(t)?t instanceof U?t.id:t:void 0,Et=t=>/^[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(t),$=t=>{if(v(t)&&Et(t))return t;if(t instanceof T&&t.data)return t.data.__id;if(P(t)&&"__id"in t&&Et(t.__id))return t.__id},Y=t=>!(!P(t)||P(t)&&"name"in t&&!v(t.name)||P(t)&&"type"in t&&(!v(t.type)||!Ze.includes(t.type))||!("value"in t)||!qe(t.value)||"metadata"in t&&!v(t.metadata)||"valueSeparator"in t&&!v(t.valueSeparator)),Ot=t=>{let e=It,r=Dt,s=443,n=Pt;if("url"in t){let o=new URL(t.url);e=o.protocol.replace(":",""),r=o.hostname,s=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in t&&"port"in t&&"protocol"in t&&(e=t.protocol.replace(":",""),r=t.host,s=t.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&s===80||e==="https"&&s===443||(a=":"+s),`${e}://${r}${a}${n}`},g=(t=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="";for(let s=0;s<t;s++){let n=Math.floor(Math.random()*e.length);r+=e[n]}return r};var J=class{constructor(e,r){this.records={attach:async({source:e,target:r,options:s},n)=>{var p,h;let a=R(n),i=`/relationships/${$(e)}`,d={headers:Object.assign({},x(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(r,"Attach"),...(s==null?void 0:s.type)&&{type:s.type},...(s==null?void 0:s.direction)&&{direction:s.direction},...(s==null?void 0:s.properties)&&{properties:s.properties}}},c=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:c,path:i,...d});let l=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:l.data}),l},detach:async({source:e,target:r,options:s},n)=>{var p,h;let a=R(n),i=`/relationships/${$(e)}`,d={headers:Object.assign({},x(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(r,"Detach"),...(s==null?void 0:s.typeOrTypes)&&{typeOrTypes:s.typeOrTypes},...(s==null?void 0:s.direction)&&{direction:s.direction}}},c=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:c,path:i,...d});let l=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:l.data}),l},create:async({label:e,data:r,options:s,vectors:n},a)=>{var h,u;let o=R(a),i="/records",d={headers:Object.assign({},x(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?g():"",l=X(Q(r));if(I(l)&&l.every(Y))d.requestData={label:e,properties:l,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else if(Z(l))d.requestData={label:e,data:l,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else throw P(l)?new Error("Provided data is not a flat object. Consider using the `importJson` method for nested objects or arrays of nested objects, or use `createMany` for arrays of flat objects."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(u=this.logger)==null||u.call(this,{requestId:c,path:i,...d,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new T(p.data):new T},createMany:async(e,r)=>{var h,u,y;let s=I(e.data)?e.data:[e.data];if(!s.every(S=>Z(S)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=e.vectors?I(e.vectors[0])?e.vectors:[e.vectors]:void 0;if(a&&a.length>s.length)throw new Error(`records.createMany: vectors length (${a.length}) exceeds the number of data rows (${s.length}).`);let o=a!=null&&a.length?s.map((S,q)=>{var C;return(C=a[q])!=null&&C.length?{...S,$vectors:a[q]}:S}):s,i=R(r),d="/records/import/json",c={headers:Object.assign({},x(i)),method:"POST",requestData:{label:e.label,data:o,options:e.options}},l=typeof this.logger=="function"?g():"";(h=this.logger)==null||h.call(this,{requestId:l,path:d,...c});let p=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:l,path:d,...c,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)){let S=I(p.data)?(y=p.data)==null?void 0:y.map(q=>new T(q)):[];return new k(S,p.total)}return new k([])},importJson:async(e,r)=>{var h,u,y;let{data:s,options:n}=e,{label:a}=e,o=s;if(!a){let S=P(s)&&!I(s)?X(s):s;if(nt(S))throw new Error("records.importJson: Missing `label`. Provide `label` for top-level arrays or objects with primitive top-level properties, or pass a container object whose top-level values are objects or arrays, e.g. { ITEM: [...], USER: [...] }.")}let i=R(r),d="/records/import/json",c={headers:Object.assign({},x(i)),method:"POST",requestData:{label:a,data:o,options:n}},l=typeof this.logger=="function"?g():"";(h=this.logger)==null||h.call(this,{requestId:l,path:d,...c});let p=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:l,path:d,...c,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)){let S=I(p.data)?(y=p.data)==null?void 0:y.map(q=>new T(q)):[];return new k(S,p.total)}return new k([])},importCsv:async(e,r)=>{var d,c;let s=R(r),n="/records/import/csv",a={headers:Object.assign({},x(s)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let l=I(i.data)?i.data.map(p=>new T(p)):[];return new k(l,i.total)}return new k([])},delete:async(e,r)=>{var d,c,l;if(z(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new _("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let s=R(r),n="/records/delete",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteById:async(e,r)=>{var c,l;let s=R(r),n=I(e),a=n?"/records/delete":`/records/${e}`,o={headers:Object.assign({},x(s)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d},export:async(e,r)=>{var d,c;let s=R(r),n="/records/export/csv",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var p,h;let{id:s,...n}=e,a=R(r),o=s?`/records/${s}/search`:"/records/search",i={headers:Object.assign({},x(a)),method:"POST",requestData:n!=null?n:{}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:c.data});let l=c.data.map(u=>new T(u));return new k(l,c.total,e)},vectorSearch:async(e,r)=>{var l,p,h,u,y,S,q;let s=R(r),n="/ai/search",a={method:"POST",headers:Object.assign({},x(s)),requestData:e},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map(C=>new T(C)),c=new k(d,(u=i.total)!=null?u:0);return c.vectorSearch=(y=i.meta)==null?void 0:y.vectorSearch,c.textSearch=(S=i.meta)==null?void 0:S.textSearch,c.fusion=(q=i.meta)==null?void 0:q.fusion,c},textSearch:async(e,r)=>{var l,p,h,u,y;let s=R(r),n="/search/text",a={method:"POST",headers:Object.assign({},x(s)),requestData:e},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map(S=>new T(S)),c=new k(d,(u=i.total)!=null?u:0);return c.textSearch=(y=i.meta)==null?void 0:y.textSearch,c},findById:async(e,r)=>{var d,c;let s=R(r),n=I(e)?"/records/search":`/records/${e}`,a={headers:Object.assign({},x(s)),method:I(e)?"POST":"GET",requestData:I(e)?{where:{$id:{$in:e}},limit:e.length}:void 0},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),I(e)){let l=i.data.map(p=>new T(p));return new k(l,i.total)}else return new T(i.data)},findOne:async(e,r)=>{var c,l;let s=R(r),n="/records/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data});let[d]=i.data;return new T(d)},findUniq:async(e,r)=>{var c,l;let s=R(r),n="/records/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new ce(i.total,e);let[d]=i.data;return new T(d)},set:async({target:e,label:r,data:s,options:n,vectors:a},o)=>{var y,S;let i=R(o),c=`/records/${$(e)}`,l={headers:Object.assign({},x(i)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?g():"",h=X(Q(s));if(I(h)&&h.every(Y))l.requestData={label:r,properties:h,...(a==null?void 0:a.length)&&{vectors:a}};else if(Z(h))l.requestData={label:r,data:h,options:n,...(a==null?void 0:a.length)&&{vectors:a}};else throw P(h)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:p,path:c,...l});let u=await this.fetcher(c,l);return(S=this.logger)==null||S.call(this,{requestId:p,path:c,...l,responseData:u.data}),u!=null&&u.success&&(u!=null&&u.data)?new T(u.data):new T},update:async({target:e,label:r,data:s,options:n},a)=>{var u,y;let o=$(e),i=R(a),d=`/records/${o}`,c={headers:Object.assign({},x(i)),method:"PATCH",requestData:{}},l=typeof this.logger=="function"?g():"",p=X(Q(s));if(I(p)&&p.every(Y))c.requestData={label:r,properties:p};else if(Z(p))c.requestData={label:r,data:p,options:n};else throw P(p)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,{requestId:l,path:d,...c});let h=await this.fetcher(d,c);return(y=this.logger)==null||y.call(this,{requestId:l,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T},upsert:async({label:e,data:r,options:s,vectors:n},a)=>{var u,y,S;let o=R(a),i="/records",d={headers:Object.assign({},x(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?g():"",l=X(Q(r)),p={...s,mergeBy:(u=s==null?void 0:s.mergeBy)!=null?u:[]};if(I(l)&&l.every(Y))d.requestData={label:e,properties:l,options:p,...(n==null?void 0:n.length)&&{vectors:n}};else if(Z(l))d.requestData={label:e,data:l,options:p,...(n==null?void 0:n.length)&&{vectors:n}};else throw P(l)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:c,path:i,...d});let h=await this.fetcher(i,d);return(S=this.logger)==null||S.call(this,{requestId:c,path:i,...d,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T}};this.relationships={patterns:{list:async()=>{var a,o;let e="/relationships/patterns",r={method:"GET",headers:{}},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},analyze:async()=>{var a,o;let e="/relationships/patterns/analyze",r={method:"POST",headers:{},requestData:{}},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},approve:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/approve`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},ignore:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/ignore`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},delete:async(e,r)=>{var d,c;let s=r!=null&&r.deleteExisting?"?deleteExisting=true":"",n=`/relationships/patterns/${encodeURIComponent(e)}${s}`,a={method:"DELETE",headers:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}},createMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/create-many",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/delete-many",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e={},r)=>{var d,c;let s=R(r),n="/relationships/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.properties={delete:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},x(s)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var d,c;let s=R(r),n="/properties/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},findById:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},x(s)),method:"GET"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},values:async(e,r,s)=>{var c,l;let n=R(s),a=`/properties/${e}/values`,o={headers:Object.assign({},x(n)),method:"POST",requestData:r!=null?r:{}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.labels={find:async(e,r)=>{var d,c;let s=R(r),n="/labels/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let r="/tx",s={method:"POST",requestData:P(e)?e:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),new U(a.data.id)},commit:async e=>{var i,d;let s=`/tx/${R(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},get:async e=>{var i,d;let s=`/tx/${R(e)}`,n={method:"GET"},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),new U(o.data.id)},rollback:async e=>{var i,d;let s=`/tx/${R(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",r={method:"GET"},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n}};this.query={raw:async({query:e,params:r},s)=>{var c,l;let n=R(s),a="/query/raw",o={headers:Object.assign({},x(n)),method:"POST",requestData:{query:e,params:r}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.textIndexes={find:async()=>this.textIndexRequest("/text-indexes","GET"),create:async e=>this.textIndexRequest("/text-indexes","POST",e),suggestName:async e=>this.textIndexRequest("/text-indexes/name-suggestion","POST",e),delete:async e=>this.textIndexRequest(`/text-indexes/${encodeURIComponent(e)}`,"DELETE")};this.ai={searchValues:async e=>{var o,i;let r="/ai/values/search",s={headers:{},method:"POST",requestData:e},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getSchemaSummary:async e=>{var o,i;let r="/ai/schema/summary",s={headers:{},method:"POST",requestData:e!=null?e:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},resolveNames:async e=>{var o,i;let r="/ai/schema/names",s={headers:{},method:"POST",requestData:e},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getJoinCandidates:async e=>{var o,i;let r="/ai/schema/join-candidates",s={headers:{},method:"POST",requestData:e!=null?e:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getSchema:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},getSchemaMarkdown:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema/md",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},indexes:{find:async()=>{var a,o;let e="/ai/indexes",r={method:"GET",headers:{}},s=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},create:async e=>{var c,l;let r="/ai/indexes",{external:s,...n}=e,a=s===!0?{...n,sourceType:"external"}:n,o={method:"POST",headers:{},requestData:a},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:r,...o});let d=await this.fetcher(r,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:r,...o,responseData:d.data}),d},upsertVectors:async(e,r)=>{var i,d;let s=`/ai/indexes/${e}/vectors/upsert`,n={method:"POST",headers:{},requestData:r},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},delete:async e=>{var o,i;let r=`/ai/indexes/${e}`,s={method:"DELETE",headers:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},stats:async e=>{var o,i;let r=`/ai/indexes/${e}/stats`,s={method:"GET",headers:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a}},search:async(e,r)=>{var d,c;let s="/ai/sql-search",n={method:"POST",headers:{},requestData:{prompt:e}},a=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);(c=this.logger)==null||c.call(this,{requestId:a,path:s,...n,responseData:o.data});let i=await this.ai.runSql(o.data.sql,r);return i.name=o.data.name,i.warnings=o.data.warnings,i},runSql:async(e,r)=>{var c,l,p,h,u,y;let s={skip:(c=r==null?void 0:r.skip)!=null?c:0,limit:(l=r==null?void 0:r.limit)!=null?l:100},n="/records/sql-search",a={method:"POST",headers:{},requestData:{sql:e,...s}},o=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(h=this.logger)==null||h.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=new k(((u=i.data)!=null?u:[]).map(S=>new T(S)),(y=i.total)!=null?y:0);return d.sql=e,d.sqlPage=s,d}};if(this.fetcher=null,r!=null&&r.direct){if(!r.engineUrl)throw new Error("Direct mode requires `engineUrl`, the standalone engine base URL.");if(!r.httpClient)throw new Error("Direct mode requires an HTTP client; import the SDK from its Node or browser entry.");this.direct=new Re({engineUrl:r.engineUrl,token:e!=null?e:"",httpClient:r.httpClient,scope:r.scope}),this.fetcher=Tt(this.direct)}else if(r!=null&&r.httpClient){let s=Ot(r);this.fetcher=bt({httpClient:r.httpClient,token:e,url:s})}r!=null&&r.options&&(this.options=r==null?void 0:r.options),r!=null&&r.logger&&(this.logger=r==null?void 0:r.logger)}_extractTargetIds(e,r){var s;if(e instanceof T){let n=$(e);if(!n)throw new _(`${r} error: Target id is empty`);return[n]}if(I(e)&&e.every(n=>n instanceof T)){let n=e.map($).filter(O);if(!n.length)throw new _(`${r} error: Target ids are empty`);return n}if(e instanceof k){let n=(s=e.data)==null?void 0:s.map($).filter(O);if(!(n!=null&&n.length))throw new _(`${r} error: Target ids are empty`);return n}if(P(e)&&"__id"in e)return[e.__id];if(I(e)&&e.every(n=>P(n)&&"__id"in n)){let n=e.map($).filter(O);if(!n.length)throw new _(`${r} error: Target ids are empty`);return n}return I(e)?e:v(e)?[e]:[]}async textIndexRequest(e,r,s){var i,d;let n={method:r,headers:{},...s===void 0?{}:{requestData:s}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:e,...n});let o=await this.fetcher(e,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:e,...n,responseData:o.data}),o}};var At,M=class M extends J{constructor(e,r){var a,o;let s=e!=null?e:typeof process<"u"?(a=process.env)==null?void 0:a.RUSHDB_API_KEY:void 0,n=_e(r);super(s,{...n,httpClient:(o=n.httpClient)!=null?o:At}),M.instance=this,this.initializeSync(s,n)}initializeSync(e,r){M.state={initialized:!0,debug:!1,timeout:Ce("timeout",r==null?void 0:r.timeout,8e4),token:e,direct:(r==null?void 0:r.direct)===!0,engineUrl:r==null?void 0:r.engineUrl}}static getInstance(){if(M.instance)return M.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return O(M.instance)}toDBRecordInstance(e){return new T(e)}};M.instance=null,M.state={initialized:!1,debug:!1,timeout:8e4};var w=M,Fe=t=>{At=t};var He=class{constructor(e,r,s){this.label=e,this.schema=r,this.config=s!=null?s:{}}getLabel(){return this.label}async toDBRecordInstance(e){try{return w.getInstance().toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,r){let s=e!=null?e:{};return w.getInstance().records.find({...s,labels:[this.label]},r)}async findOne(e,r){let s=e!=null?e:{};return w.getInstance().records.findOne({...s,labels:[this.label]},r)}async findById(e,r){return this.findOne({where:{$id:e}},r)}async findUniq(e,r){let s=e!=null?e:{};return w.getInstance().records.findUniq({...s,labels:[this.label]},r)}async create(e,r,s){var d,c;let n=await de(this.schema,e),a=fe(this.schema,n),o=O(a),i=w.getInstance();if(o){let l=r!=null?r:await i.tx.begin(),p=await this.find({where:a},l),h=typeof r<"u";if(!((d=p==null?void 0:p.data)!=null&&d.length)){let y=await i.records.create({label:this.label,data:n},l);return h||await l.commit(),y}else switch((c=s==null?void 0:s.onConflict)!=null?c:"throw"){case"upsert":{let S=p.data[0],q=await i.records.set({target:S.id,label:this.label,data:n},l);return h||await l.commit(),q}case"skip":return h||await l.commit(),null;default:throw h||await l.commit(),new L(this.label,a)}}return await i.records.create({label:this.label,data:n},r)}async attach({source:e,target:r,options:s},n){return await w.getInstance().records.attach({source:e,target:r,options:s},n)}async detach({source:e,target:r,options:s},n){return await w.getInstance().records.detach({source:e,target:r,options:s},n)}async validateTargetLabel(e,r){let s=$(e);if(!s)return;let a=await w.getInstance().records.findById(s,r);if(!a)throw new Error(`Record with id "${s}" not found.`);if(a.data.__label!==this.label)throw new TypeError(`Target record label "${a.data.__label}" does not match model label "${this.label}".`)}async handleSetOrUpdate(e,r,s,n){var d,c;if(this.config.validateTargetLabel&&await this.validateTargetLabel(e,n),I(r)&&r.every(Y))return await w.getInstance().records[s]({label:this.label,target:e,data:r},n);let a=w.getInstance(),o=await de(this.schema,r),i=fe(this.schema,o);if(!z(i)){let l=n!=null?n:await a.tx.begin(),p=await this.find({where:i},l),h=typeof n<"u";if(!((d=p==null?void 0:p.data)!=null&&d.length)||p.data.length===1&&((c=p.data[0])==null?void 0:c.id)===$(e)){let y=await a.records[s]({target:e,label:this.label,data:o},l);return h||await l.commit(),y}else throw h||await l.commit(),new L(this.label,i)}return await a.records[s]({label:this.label,target:e,data:o},n)}async set(e,r,s){return await this.handleSetOrUpdate(e,r,"set",s)}async update(e,r,s){return await this.handleSetOrUpdate(e,r,"update",s)}async createMany(e,r){var o;let s=w.getInstance(),n=typeof r<"u",a=r!=null?r:await s.tx.begin();try{let i=await Promise.all(e.map(async l=>await de(this.schema,l))),d=$e(i,this.schema,this.label);if(!z(d)){let l=Object.entries(d).map(([h,u])=>({[h]:{$in:u}})),p=await this.find({where:{$or:l}},a);if((o=p==null?void 0:p.data)!=null&&o.length)throw new L(this.label,Object.keys(d))}let c=await s.records.createMany({label:this.label,data:i},a);return n||await a.commit(),c}catch(i){throw n||await a.rollback(),i}}async delete(e,r){if(z(e.where))throw new _(`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 w.getInstance().records.delete({...e,labels:[this.label]},r)}async deleteById(e,r){return await w.getInstance().records.deleteById(e,r)}};Fe(new ye);var sr=w;0&&(module.exports={CLOUD_ONLY_FORMS,CLOUD_ONLY_METHODS,CloudOnlyError,DBRecordInstance,DBRecordsArrayInstance,DirectModeError,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,isCloudOnlyMethod,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
27
+ `}}return o.trim()};var f=(t,e={})=>({success:!0,data:t,...e}),A=(t,e)=>{let r=new Error(`${t} ${e}`);return r.status=t,r.body={statusCode:t,message:e},r},j=t=>async()=>{throw new K(t,le[t])},U=(t,e)=>{if(t)throw new ee(`${e} inside a transaction is not supported in direct mode: the engine stages record creates, updates, deletes, links and imports. Run it outside the transaction.`)},ut="__RUSHDB__RELATION__DEFAULT__",W=(t,e,r)=>t.execute({kind:"transaction",transaction:{kind:"stage",transactionId:e,mutation:r}}),je=async(t,e,r)=>{var n;let{record:s}=await W(t,e,{kind:"getRecord",record:{id:r}});return{...(n=s==null?void 0:s.properties)!=null?n:{},__id:r,__label:s==null?void 0:s.__label,__proptypes:{}}},mt=(t,e)=>{t&&Array.isArray(e)&&e.length>0&&U(t,"A write with inline vectors")},be=t=>{var r,s;if(!t)return t;let e={...(r=t.properties)!=null?r:{}};return e.__id=t.id,e.__label=t.label,e.__proptypes=(s=t.propertyTypes)!=null?s:{},t.score!==void 0&&(e.__score=t.score),e},De=t=>(t!=null?t:[]).map(e=>be(e)),Ue=t=>t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:Array.isArray(t.properties)?Object.fromEntries(t.properties.map(e=>[e.name,e.value])):t.properties&&typeof t.properties=="object"?t.properties:{},Kt=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?"desc":typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).map(([e,r])=>[e==="__id"?"id":e,r])),te=(t={})=>{var s,n,a,o,i,d;let e=(s=t.pagination)!=null?s:{},r={labels:(n=t.labels)!=null?n:[],predicate:(a=t.where)!=null?a:{},select:t.select,order:Kt(t.orderBy),offset:(i=(o=t.skip)!=null?o:e.skip)!=null?i:0,limit:(d=t.limit)!=null?d:e.limit};return Array.isArray(t.groupBy)&&t.groupBy.length>0&&(r.groupBy=t.groupBy),r},xe=t=>t==null||typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0,Ne=async(t,e)=>(await t.execute({kind:"query",query:{kind:"record",id:e}})).record,gt=async(t,e)=>{var s,n,a;let r=await t.execute({kind:"query",query:{kind:"records",query:te(e)}});return r.kind==="rows"?{data:(s=r.rows)!=null?s:[],total:(n=r.total)!=null?n:0}:{data:De(r.records),total:(a=r.total)!=null?a:0}},re=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"vectorIndexes"}})).indexes)!=null?e:[]},Me=async t=>{var e;return(e=(await t.execute({kind:"describe",describe:{kind:"indexes"}})).indexes)!=null?e:[]},he=t=>{var r;let e=Number((r=t.dimensions)!=null?r:0);return{id:t.name,name:t.name,label:t.label,propertyName:t.property,vectorPropertyName:`_emb_external_${t.similarity}_${e}`,similarityFunction:t.similarity,dimensions:e,sourceType:"external",status:t.status}},yt=t=>{var e,r;return{name:t.name,label:t.label,property:t.property,consistency:(e=t.consistency)!=null?e:"eventual",status:t.state,pending:(r=t.pending)!=null?r:0}},Ve=async t=>(await Me(t)).filter(e=>e.kind==="text").map(yt),ft=64,St=t=>t.join(".").slice(0,ft).replace(/[.:-]+$/,""),Te=t=>t.replace(/[^A-Za-z0-9_-]/g,"-"),Le=(t,e)=>{if(!e.has(t))return t;for(let r=2;;r++){let s=`-${r}`,n=t.slice(0,ft-s.length)+s;if(!e.has(n))return n}},ot=({label:t,property:e})=>St([Te(t),e==="*"?"all":Te(e),"text"]),Wt=(t,e,r)=>St([Te(t.label),Te(t.propertyName),"external",String(e),r]).replace(/^emb__/,"emb_"),Ie=async(t,e,r,s)=>{if(!Array.isArray(e)||e.length===0)return[];let n=s!=null?s:await re(t);return e.map(a=>{if(typeof(a==null?void 0:a.index)=="string")return a;if(!r)throw A(422,"inline vectors require a record label to select their index");let o=Array.isArray(a.vector)?a.vector.length:void 0,i=n.filter(d=>d.label===r&&d.property===a.propertyName&&(a.similarityFunction===void 0||d.similarity===a.similarityFunction)&&(o===void 0||Number(d.dimensions)===o));if(i.length!==1)throw A(i.length===0?404:422,i.length===0?`No vector index matches label "${r}", property "${a.propertyName}"`:`${i.length} vector indexes match label "${r}", property "${a.propertyName}"; name one with \`index\``);return{...a,index:i[0].name}})},Yt=async(t,e,r)=>{let s=Array.isArray(e)?e:[e],n=i=>Array.isArray(i==null?void 0:i.$vectors)&&i.$vectors.length>0;if(!s.some(n))return e;let a=await re(t),o=await Promise.all(s.map(async i=>n(i)?{...i,$vectors:await Ie(t,i.$vectors,r,a)}:i));return Array.isArray(e)?o:o[0]},Jt=()=>{var s;let t=new Uint8Array(16);if(typeof((s=globalThis.crypto)==null?void 0:s.getRandomValues)=="function")globalThis.crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);let e=Date.now();for(let n=0;n<6;n++)t[n]=Math.floor(e/2**(8*(5-n)))&255;t[6]=t[6]&15|112,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},Gt=async({body:t,engine:e,txId:r})=>{var i,d,c,l,p,h;let s=!!((i=t.options)!=null&&i.mergeStrategy)||Array.isArray((d=t.options)==null?void 0:d.mergeBy),n=Ue(t);if(r){s&&U(r,"An upsert"),mt(r,t.vectors);let u=Jt();return await W(e,r,{kind:"createRecord",label:t.label,id:u,properties:n,options:(c=t.options)!=null?c:{}}),f(await je(e,r,u))}let a=s?{...t.options,mergeBy:(p=(l=t.options)==null?void 0:l.mergeBy)!=null?p:[]}:(h=t.options)!=null?h:{},o=await e.execute({kind:"mutate",mutation:{kind:"putRecord",mode:"create",label:t.label,properties:n,vectors:await Ie(e,t.vectors,t.label),options:a}});return f(be(o.record))},it=t=>async({body:e,params:[r],engine:s,txId:n})=>{var d,c;let a=typeof e.label=="string"&&e.label?e.label:void 0;if(n){if(mt(n,e.vectors),a){let l=await je(s,n,r);l.__label&&l.__label!==a&&await W(s,n,{kind:"retypeRecord",record:{id:r},fromLabel:l.__label,toLabel:a})}return await W(s,n,{kind:"updateRecord",record:{id:r},properties:Ue(e),replace:t==="replace"}),f(await je(s,n,r))}let o=a;if(a||(d=e.vectors)!=null&&d.length){let l=await Ne(s,r);a&&(l!=null&&l.label)&&l.label!==a&&await s.execute({kind:"mutate",mutation:{kind:"retypeRecord",id:r,fromLabel:l.label,toLabel:a}}),o=a!=null?a:l==null?void 0:l.label}let i=await s.execute({kind:"mutate",mutation:{kind:"putRecord",mode:t,id:r,properties:Ue(e),vectors:await Ie(s,e.vectors,o),options:(c=e.options)!=null?c:{}}});return f(be(i.record))},zt=async(t,e,r)=>{var o;if(!e)return r;let s;try{s=(o=await Ne(t,e))==null?void 0:o.label}catch(i){if((i==null?void 0:i.status)===404)return;throw i}let n={[s]:{$id:e}},a=r.where;return{...r,where:xe(a)?n:{$and:[a,n]}}},ct=async({body:t,params:[e],engine:r})=>{let s=await zt(r,e,t);if(!s)return f([],{total:0});let{data:n,total:a}=await gt(r,s);return f(n,{total:a})},dt=(t,e,r)=>e?W(t,e,{kind:"ingest",ingest:r}):t.execute({kind:"ingest",ingest:r}),lt=(t,e)=>{var r,s;return e&&((r=t.records)!=null&&r.length)?f(De(t.records)):f({message:"Records have been successfully imported",count:Number((s=t.count)!=null?s:0)})},Xt=["delimiter","header","skipEmptyLines","dynamicTyping","quoteChar","escapeChar","newline"],pt=t=>{var e,r,s,n,a,o,i,d,c,l,p,h;return{relationType:(e=t.type)!=null?e:ut,direction:String((r=t.direction)!=null?r:"").toLowerCase()==="in"?"in":"out",allowCartesian:(s=t.manyToMany)!=null?s:!1,properties:(n=t.properties)!=null?n:{},source:{label:(a=t.source)==null?void 0:a.label,property:(o=t.source)==null?void 0:o.key,predicate:(d=(i=t.source)==null?void 0:i.where)!=null?d:{}},target:{label:(c=t.target)==null?void 0:c.label,property:(l=t.target)==null?void 0:l.key,predicate:(h=(p=t.target)==null?void 0:p.where)!=null?h:{}}}},ue=t=>Array.isArray(t)?t:[t],Zt=t=>{var r,s;let e=new Map;for(let n of t){let a=e.get(n.id);if(a){a.recordsCount+=Number((r=n.recordsCount)!=null?r:0),a.isArray||(a.isArray=n.isArray===!0);continue}e.set(n.id,{id:n.id,name:n.name,type:n.type,recordsCount:Number((s=n.recordsCount)!=null?s:0),isArray:n.isArray===!0})}return Array.from(e.values(),({isArray:n,...a})=>({...a,metadata:JSON.stringify({cardinality:n?"OrderedMany":"Single",nullability:"Nullable"})}))},Rt=async(t,e={})=>{var s;let r=await t.execute({kind:"describe",describe:{kind:"properties",query:te(e),...xe(e.where)?{detail:"catalog"}:{}}});return Zt((s=r.properties)!=null?s:[])},ht=async(t,e)=>{var s;let r=(await Rt(t)).find(n=>n.name===e||n.id===e);return r&&{...r,id:(s=r.id)!=null?s:r.name}},wt=async(t,e,r)=>{var a,o;if(typeof e.query!="string"||e.query.trim()==="")throw A(422,"text.query is required");let s=await Ve(t),n;if(e.index!==void 0){if(n=s.find(i=>i.name===e.index),!n)throw A(404,`No text index named "${e.index}"`)}else{let i=r[0];if(!i)throw A(422,"Name a text index with `index`, or give `labels`");let d=s.filter(c=>c.label===i&&c.status==="ready"&&(e.property===void 0||c.property===e.property));if(d.length===0)throw A(404,`No ready text index on label "${i}"`);if(d.length>1)throw A(422,`Label "${i}" has several text indexes (${d.map(c=>c.name).join(", ")}); name one with \`index\``);n=d[0]}return{index:n.name,label:n.label,query:e.query,allTerms:(a=e.allTerms)!=null?a:!1,phrase:(o=e.phrase)!=null?o:!1}},er=async({body:t,engine:e})=>{var p,h,u,g,S,q,_,ne,se,ae,oe;let r=(p=t.queryVector)!=null?p:[];if(r.length===0)throw new K("records.vectorSearch",pe["records.vectorSearch"]);let s=await re(e),n;if(typeof t.index=="string"){if(n=s.find(N=>N.name===t.index),!n)throw A(404,`No vector index named "${t.index}"`)}else{let N=((h=t.labels)!=null?h:[])[0],F=s.filter(H=>{var ie;return H.label===N&&H.property===t.propertyName&&(t.similarityFunction===void 0||H.similarity===t.similarityFunction)&&Number(H.dimensions)===((ie=t.dimensions)!=null?ie:r.length)});if(F.length!==1)throw A(F.length===0?404:422,F.length===0?`No vector index matches label "${N}", property "${t.propertyName}"`:`${F.length} vector indexes match label "${N}", property "${t.propertyName}"; name one with \`index\``);n=F[0]}let a=(u=t.labels)!=null&&u.length?t.labels:[n.label],o={property:n.property,vector:r,similarity:(g=n.similarity)!=null?g:"cosine",index:n.name,mode:t.mode,ef:t.ef,scoreThreshold:t.scoreThreshold},i=t.text?await wt(e,{...t.text,query:(S=t.text.query)!=null?S:t.query},a):void 0,d=i?{kind:"hybrid",query:{labels:a,predicate:(q=t.where)!=null?q:{},vector:{...o,weight:t.weight,prefetchLimit:t.prefetchLimit},text:{index:i.index,query:i.query,allTerms:i.allTerms,phrase:i.phrase,weight:t.text.weight,prefetchLimit:t.text.prefetchLimit},fusion:t.fusion,rrfK:t.rrfK,offset:(_=t.skip)!=null?_:0,limit:(ne=t.limit)!=null?ne:10}}:{kind:"vector",query:{...o,labels:a,predicate:(se=t.where)!=null?se:{},offset:(ae=t.skip)!=null?ae:0,limit:(oe=t.limit)!=null?oe:10}},c=await e.execute({kind:"query",query:d}),l=De(c.records);return f(l,{total:l.length,meta:{vectorSearch:c.vectorSearch,textSearch:c.textSearch,fusion:c.fusion}})},E="([^/]+)",xt=[{method:"GET",pattern:new RegExp(`^/records/${E}$`),handle:async({params:[t],engine:e})=>f(be(await Ne(e,t)))},{method:"POST",pattern:/^\/records$/,handle:Gt},{method:"PATCH",pattern:new RegExp(`^/records/${E}$`),handle:it("merge")},{method:"PUT",pattern:new RegExp(`^/records/${E}$`),handle:it("replace")},{method:"DELETE",pattern:new RegExp(`^/records/${E}$`),handle:async({params:[t],engine:e,txId:r})=>(r?await W(e,r,{kind:"deleteRecord",record:{id:t}}):await e.execute({kind:"mutate",mutation:{kind:"deleteRecord",id:t}}),f({message:"Record deleted"}))},{method:"POST",pattern:/^\/records\/delete$/,handle:async({body:t,engine:e,txId:r})=>{var n;U(r,"records.delete");let s=await e.execute({kind:"mutate",mutation:{kind:"deleteRecords",query:te(t)}});return f({message:`${(n=s.affected)!=null?n:0} records deleted`})}},{method:"POST",pattern:/^\/records\/search$/,handle:ct},{method:"POST",pattern:new RegExp(`^/records/${E}/search$`),handle:ct},{method:"POST",pattern:/^\/records\/import\/json$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;let s=await dt(e,r,{kind:"documents",label:t.label,documents:await Yt(e,t.data,t.label),options:(n=t.options)!=null?n:{}});return lt(s,(a=t.options)==null?void 0:a.returnResult)}},{method:"POST",pattern:/^\/records\/import\/csv$/,handle:async({body:t,engine:e,txId:r})=>{var i,d,c,l,p,h,u;let s=(i=t.vectors)!=null&&i.length?await re(e):[],n=await Promise.all(((d=t.vectors)!=null?d:[]).map(g=>Ie(e,g,t.label,s))),a=Object.fromEntries(Object.entries((c=t.parseConfig)!=null?c:{}).filter(([g])=>Xt.includes(g))),o=await dt(e,r,{kind:"csv",label:t.label,data:(l=t.data)!=null?l:"",parseConfig:a,options:(p=t.options)!=null?p:{},vectors:n});return Number((h=o.count)!=null?h:0)===0?f(!0):lt(o,(u=t.options)==null?void 0:u.returnResult)}},{method:"POST",pattern:/^\/records\/export\/csv$/,handle:async({body:t,engine:e})=>{let r=await e.execute({kind:"query",query:{kind:"exportCsv",query:te({labels:t.labels,where:t.where,orderBy:t.orderBy,skip:typeof t.skip=="number"?t.skip:0,limit:typeof t.limit=="number"?t.limit:100})}});return f({fileContent:r.content,dateTime:new Date().toISOString()})}},{method:"POST",pattern:new RegExp(`^/relationships/${E}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var o,i,d,c;let n=(o=t.type)!=null?o:ut,a=String((i=t.direction)!=null?i:"").toLowerCase()==="in";if(s)for(let l of ue(t.targetIds))await W(r,s,{kind:"createRelationship",relationType:n,source:{id:a?l:e},target:{id:a?e:l},properties:(d=t.properties)!=null?d:{}});else await r.execute({kind:"mutate",mutation:{kind:"linkRecordsById",command:{relationType:n,direction:a?"in":"out",sourceIds:[e],targetIds:ue(t.targetIds),properties:(c=t.properties)!=null?c:{}}}});return f({message:`Relations to Record ${e} have been successfully created`})}},{method:"PUT",pattern:new RegExp(`^/relationships/${E}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var a;U(s,"records.detach");let n=String((a=t.direction)!=null?a:"").toLowerCase();return await r.execute({kind:"mutate",mutation:{kind:"unlinkRecordsById",command:{relationTypes:ue(t.typeOrTypes).filter(Boolean),...n==="in"||n==="out"?{direction:n}:{},sourceIds:[e],targetIds:ue(t.targetIds)}}}),f({message:`Relations to Record ${e} have been successfully deleted`})}},{method:"PATCH",pattern:new RegExp(`^/relationships/${E}$`),handle:async({body:t,params:[e],engine:r,txId:s})=>{var o,i,d,c;U(s,"relationships.update");let n=await r.execute({kind:"mutate",mutation:{kind:"updateRelationshipsById",command:{relationType:t.type,direction:String((o=t.direction)!=null?o:"").toLowerCase()==="in"?"in":"out",sourceIds:[e],targetIds:ue(t.targetIds),set:(i=t.set)!=null?i:{},unset:(d=t.unset)!=null?d:[],...t.types&&Object.keys(t.types).length>0&&{types:t.types}}}}),a=Number((c=n==null?void 0:n.affected)!=null?c:0);return f({message:`${a} relationship${a===1?"":"s"} of Record ${e} updated`,updated:a})}},{method:"POST",pattern:/^\/relationships\/create-many$/,handle:async({body:t,engine:e,txId:r})=>(U(r,"relationships.createMany"),await e.execute({kind:"mutate",mutation:{kind:"linkRecords",command:pt(t)}}),f({message:"Relations have been successfully created"}))},{method:"POST",pattern:/^\/relationships\/delete-many$/,handle:async({body:t,engine:e,txId:r})=>(U(r,"relationships.deleteMany"),await e.execute({kind:"mutate",mutation:{kind:"unlinkRecords",command:pt(t)}}),f({message:"Relations have been successfully deleted"}))},{method:"POST",pattern:/^\/relationships\/search$/,handle:async({body:t,engine:e})=>{var s,n,a,o,i,d,c,l,p,h,u;let r=await e.execute({kind:"query",query:{kind:"relationships",query:{sourceLabels:(n=(s=t.source)==null?void 0:s.labels)!=null?n:[],targetLabels:(o=(a=t.target)==null?void 0:a.labels)!=null?o:[],relationType:(i=t.where)==null?void 0:i.type,predicate:Object.fromEntries(Object.entries((d=t.where)!=null?d:{}).filter(([g])=>g!=="type")),sourcePredicate:xe((c=t.source)==null?void 0:c.where)?void 0:t.source.where,targetPredicate:xe((l=t.target)==null?void 0:l.where)?void 0:t.target.where,offset:(p=t.skip)!=null?p:0,limit:t.limit}}});return f((h=r.relationships)!=null?h:[],{total:(u=r.total)!=null?u:0})}},{method:"GET",pattern:/^\/relationships\/patterns$/,handle:j("relationships.patterns.list")},{method:"POST",pattern:/^\/relationships\/patterns\/analyze$/,handle:j("relationships.patterns.analyze")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${E}/approve$`),handle:j("relationships.patterns.approve")},{method:"POST",pattern:new RegExp(`^/relationships/patterns/${E}/ignore$`),handle:j("relationships.patterns.ignore")},{method:"DELETE",pattern:new RegExp(`^/relationships/patterns/${E}$`),handle:j("relationships.patterns.delete")},{method:"POST",pattern:/^\/properties\/search$/,handle:async({body:t,engine:e})=>{var r,s;return f(await Rt(e,{labels:(r=t.labels)!=null?r:[],where:(s=t.where)!=null?s:{}}))}},{method:"GET",pattern:new RegExp(`^/properties/${E}$`),handle:async({params:[t],engine:e})=>{let r=await ht(e,t);if(!r)throw A(404,`property \`${t}\` does not exist`);return f(r)}},{method:"DELETE",pattern:new RegExp(`^/properties/${E}$`),handle:async({params:[t],engine:e,txId:r})=>{U(r,"properties.delete");let s=await ht(e,t);if(!s)throw A(404,`property \`${t}\` does not exist`);return await e.execute({kind:"mutate",mutation:{kind:"deleteProperty",name:s.name}}),f({message:`Property (${t}) has been successfully deleted.`})}},{method:"POST",pattern:new RegExp(`^/properties/${E}/values$`),handle:async({body:t,params:[e],engine:r})=>{var a,o,i,d,c,l;let s=!!t.query||!!t.limit,n=await r.execute({kind:"query",query:{kind:"propertyValues",property:e,query:te({labels:(a=t.labels)!=null?a:[],where:(o=t.where)!=null?o:{}}),...s?{mode:"topK",limit:(i=t.limit)!=null?i:100}:{},...t.query?{search:{text:t.query,match:(d=t.match)!=null?d:"contains",...t.domainOnMiss?{domainOnMiss:t.domainOnMiss}:{},...t.minSimilarity!==void 0?{minSimilarity:t.minSimilarity}:{}}}:{}}});return f({values:(c=n.values)!=null?c:[],...(l=n.counts)!=null&&l.length?{counts:n.counts}:{},...s&&n.distinctCount!==void 0?{distinctCount:n.distinctCount}:{},...n.searchMissed?{searchMissed:!0}:{}})}},{method:"POST",pattern:/^\/labels\/search$/,handle:async({body:t,engine:e})=>{var n;let r=await e.execute({kind:"describe",describe:{kind:"labels",query:te(t)}}),s={};for(let a of(n=r.labels)!=null?n:[])s[a]=(await gt(e,{...t,labels:[a],skip:0,limit:1})).total;return f(s)}},{method:"POST",pattern:/^\/tx$/,handle:async({body:t,engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"begin",ttlMs:t.ttl,autocommit:(s=t.autocommit)!=null?s:!1}});return f({id:r.transactionId})}},{method:"GET",pattern:new RegExp(`^/tx/${E}$`),handle:async({params:[t]})=>f({id:t})},{method:"POST",pattern:new RegExp(`^/tx/${E}/commit$`),handle:async({params:[t],engine:e})=>{var s;let r=await e.execute({kind:"transaction",transaction:{kind:"commit",transactionId:t}});if(r.status!=="committed")throw A(409,`Transaction commit failed: ${(s=r.reason)!=null?s:r.status}`);return f({message:`Transaction (${t}) has been successfully committed.`})}},{method:"POST",pattern:new RegExp(`^/tx/${E}/rollback$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"transaction",transaction:{kind:"rollback",transactionId:t}}),f({message:`Transaction (${t}) has been rolled back.`}))},{method:"POST",pattern:/^\/query\/raw$/,handle:async({body:t,engine:e,txId:r})=>{var n,a;U(r,"query.raw");let s=await e.execute({kind:"query",query:{kind:"statement",language:"cypher",statement:t.query,parameters:(n=t.params)!=null?n:null}});return f({records:(a=s.rows)!=null?a:[]})}},{method:"GET",pattern:/^\/text-indexes$/,handle:async({engine:t})=>f(await Ve(t))},{method:"POST",pattern:/^\/text-indexes$/,handle:async({body:t,engine:e})=>{var n,a;let r=new Set((await Me(e)).map(o=>String(o.name)));if(t.name!==void 0&&r.has(t.name))throw A(409,`An index named "${t.name}" already exists`);let s=await e.execute({kind:"index",index:{kind:"create",definition:{name:(n=t.name)!=null?n:Le(ot(t),r),label:t.label,property:t.property,kind:"text",consistency:(a=t.consistency)!=null?a:"eventual"}}});return f(yt(s.index))}},{method:"POST",pattern:/^\/text-indexes\/name-suggestion$/,handle:async({body:t,engine:e})=>{let r=new Set((await Me(e)).map(s=>String(s.name)));return f({name:Le(ot(t),r)})}},{method:"DELETE",pattern:new RegExp(`^/text-indexes/${E}$`),handle:async({params:[t],engine:e})=>{let r=decodeURIComponent(t);if(!(await Ve(e)).some(s=>s.name===r))throw A(404,`No text index named "${r}"`);return await e.execute({kind:"index",index:{kind:"drop",name:r}}),f({deleted:!0})}},{method:"POST",pattern:/^\/search\/text$/,handle:async({body:t,engine:e})=>{var a,o,i,d,c,l,p;if(typeof t.query!="string"||t.query.trim()==="")throw A(422,"query is required");let r=await wt(e,t,(a=t.labels)!=null?a:[]),s=await e.execute({kind:"query",query:{kind:"hybrid",query:{labels:(o=t.labels)!=null&&o.length?t.labels:[r.label],predicate:(i=t.where)!=null?i:{},text:{index:r.index,query:r.query,allTerms:r.allTerms,phrase:r.phrase},offset:(d=t.skip)!=null?d:0,limit:(c=t.limit)!=null?c:10}}}),n=De(s.records);return f(n,{total:(p=(l=s.textSearch)==null?void 0:l.matches)!=null?p:n.length,meta:{textSearch:s.textSearch}})}},{method:"POST",pattern:/^\/ai\/schema$/,handle:async({body:t,engine:e})=>f(await ve(e,t.labels,he))},{method:"POST",pattern:/^\/ai\/schema\/md$/,handle:async({body:t,engine:e})=>f(at(await ve(e,t.labels,he)))},{method:"POST",pattern:/^\/ai\/sql-search$/,handle:j("ai.search")},{method:"POST",pattern:/^\/records\/sql-search$/,handle:j("ai.runSql")},{method:"POST",pattern:/^\/ai\/search$/,handle:er},{method:"GET",pattern:/^\/ai\/indexes$/,handle:async({engine:t})=>f((await re(t)).map(he))},{method:"POST",pattern:/^\/ai\/indexes$/,handle:async({body:t,engine:e})=>{var d,c;if(t.sourceType!=="external")throw new K("ai.indexes.create",pe["ai.indexes.create"]);let r=Number(t.dimensions);if(!Number.isInteger(r)||r<1||r>4096)throw A(422,"dimensions must be an integer between 1 and 4096");let s=(d=t.similarityFunction)!=null?d:"cosine",n=await re(e),a=n.find(l=>l.label===t.label&&l.property===t.propertyName&&l.similarity===s&&Number(l.dimensions)===r);if(a)throw A(409,`An embedding index for label "${t.label}", property "${t.propertyName}", sourceType "external", similarityFunction "${s}", and dimensions ${r} already exists ("${a.name}")`);let o=new Set(n.map(l=>String(l.name)));if(t.name!==void 0&&o.has(t.name))throw A(409,`An embedding index named "${t.name}" already exists`);let i=await e.execute({kind:"index",index:{kind:"createVector",definition:{label:t.label,property:t.propertyName,dimensions:r,similarity:s,name:(c=t.name)!=null?c:Le(Wt(t,r,s),o)}}});return f(he(i.index))}},{method:"DELETE",pattern:new RegExp(`^/ai/indexes/${E}$`),handle:async({params:[t],engine:e})=>(await e.execute({kind:"index",index:{kind:"dropVector",name:decodeURIComponent(t)}}),f({deleted:!0,queued:!1}))},{method:"GET",pattern:new RegExp(`^/ai/indexes/${E}/stats$`),handle:async({params:[t],engine:e})=>{var s,n;let r=await e.execute({kind:"describe",describe:{kind:"vectorIndex",name:decodeURIComponent(t)}});return f({...r.stats,index:he((n=(s=r.stats)==null?void 0:s.index)!=null?n:{})})}},{method:"POST",pattern:new RegExp(`^/ai/indexes/${E}/vectors/upsert$`),handle:async({body:t,params:[e],engine:r})=>{var n;let s=await r.execute({kind:"index",index:{kind:"upsertVectors",name:decodeURIComponent(e),items:(n=t.items)!=null?n:[]}});return f({updated:s.updated,requested:s.requested})}},{method:"POST",pattern:/^\/ai\/values\/search$/,handle:async({body:t,engine:e})=>{var s,n,a,o;let r=await e.execute({kind:"query",query:{kind:"searchValues",search:{text:t.text,match:(s=t.match)!=null?s:"contains",...t.caseSensitive?{caseSensitive:!0}:{},...t.minSimilarity!==void 0?{minSimilarity:t.minSimilarity}:{}},...(n=t.labels)!=null&&n.length?{labels:t.labels}:{},...t.limit?{limit:t.limit}:{}}});return f({matches:(a=r.matches)!=null?a:[],total:(o=r.total)!=null?o:0,...r.skipped?{skipped:r.skipped}:{}})}},{method:"POST",pattern:/^\/ai\/schema\/summary$/,handle:async({body:t,engine:e})=>{var s,n;let r=await e.execute({kind:"describe",describe:{kind:"schemaSummary",...(s=t.labels)!=null&&s.length?{labels:t.labels}:{},...t.fewValues!==void 0?{fewValues:t.fewValues}:{}}});return f((n=r.labels)!=null?n:[])}},{method:"POST",pattern:/^\/ai\/schema\/names$/,handle:async({body:t,engine:e})=>{var s;let r=await e.execute({kind:"describe",describe:{kind:"names",text:t.text,...t.limit?{limit:t.limit}:{}}});return f((s=r.names)!=null?s:[])}},{method:"POST",pattern:/^\/ai\/schema\/join-candidates$/,handle:j("ai.getJoinCandidates")},{method:"GET",pattern:/^\/sdk\/settings$/,handle:j("settings.get")}],Or=xt.map(t=>`${t.method} ${t.pattern.source}`),Tt=t=>async(e,{method:r="GET",headers:s,requestData:n})=>{var c;let a=new URL(String(e),"http://direct"),o=xt.filter(l=>l.method===r&&l.pattern.test(a.pathname)).sort((l,p)=>l.pattern.source.split("(").length-p.pattern.source.split("(").length)[0];if(!o)throw new ee(`${r} ${a.pathname} has no direct-mode mapping`);let i=((c=o.pattern.exec(a.pathname))!=null?c:[]).slice(1),d=s==null?void 0:s["x-transaction-id"];return await o.handle({body:n!=null?n:{},params:i,query:a.searchParams,txId:d,engine:t})};var tr={"Content-Type":"application/json"},bt=({httpClient:t,token:e,url:r})=>async(s,{headers:n,...a})=>{var l;let o=await t.makeRequest(`${r}${s}`,{credentials:"omit",headers:Object.assign({...tr,...n},typeof e<"u"?{Authorization:`Bearer ${e}`}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();let i="",d;try{let p=await o.toJSON();d=p;let h=(l=p==null?void 0:p.message)!=null?l:p==null?void 0:p.error;Array.isArray(h)?i=h.join("; "):typeof h=="string"&&(i=h)}catch{}let c=new Error(i?`${o.getStatusCode()} ${i}`:`${o.getStatusCode()}`);throw c.status=o.getStatusCode(),c.body=d,c};var M=class{constructor(e){this.id=e}async rollback(){return await w.getInstance().tx.rollback(this.id)}async commit(){return await w.getInstance().tx.commit(this.id)}};var Dt="api.rushdb.com";var It="https",Pt="/api/v1";var x=t=>t?{"x-transaction-id":t}:void 0,nr=t=>v(t)||t instanceof M,R=t=>nr(t)?t instanceof M?t.id:t:void 0,Et=t=>/^[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(t),k=t=>{if(v(t)&&Et(t))return t;if(t instanceof T&&t.data)return t.data.__id;if(P(t)&&"__id"in t&&Et(t.__id))return t.__id},Y=t=>!(!P(t)||P(t)&&"name"in t&&!v(t.name)||P(t)&&"type"in t&&(!v(t.type)||!Ze.includes(t.type))||!("value"in t)||!qe(t.value)||"metadata"in t&&!v(t.metadata)||"valueSeparator"in t&&!v(t.valueSeparator)),Ot=t=>{let e=It,r=Dt,s=443,n=Pt;if("url"in t){let o=new URL(t.url);e=o.protocol.replace(":",""),r=o.hostname,s=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in t&&"port"in t&&"protocol"in t&&(e=t.protocol.replace(":",""),r=t.host,s=t.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&s===80||e==="https"&&s===443||(a=":"+s),`${e}://${r}${a}${n}`},y=(t=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="";for(let s=0;s<t;s++){let n=Math.floor(Math.random()*e.length);r+=e[n]}return r};var J=class{constructor(e,r){this.records={attach:async({source:e,target:r,options:s},n)=>{var p,h;let a=R(n),i=`/relationships/${k(e)}`,d={headers:Object.assign({},x(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(r,"Attach"),...(s==null?void 0:s.type)&&{type:s.type},...(s==null?void 0:s.direction)&&{direction:s.direction},...(s==null?void 0:s.properties)&&{properties:s.properties}}},c=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:c,path:i,...d});let l=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:l.data}),l},detach:async({source:e,target:r,options:s},n)=>{var p,h;let a=R(n),i=`/relationships/${k(e)}`,d={headers:Object.assign({},x(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(r,"Detach"),...(s==null?void 0:s.typeOrTypes)&&{typeOrTypes:s.typeOrTypes},...(s==null?void 0:s.direction)&&{direction:s.direction}}},c=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:c,path:i,...d});let l=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:l.data}),l},create:async({label:e,data:r,options:s,vectors:n},a)=>{var h,u;let o=R(a),i="/records",d={headers:Object.assign({},x(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?y():"",l=X(Q(r));if(I(l)&&l.every(Y))d.requestData={label:e,properties:l,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else if(Z(l))d.requestData={label:e,data:l,options:s,...(n==null?void 0:n.length)&&{vectors:n}};else throw P(l)?new Error("Provided data is not a flat object. Consider using the `importJson` method for nested objects or arrays of nested objects, or use `createMany` for arrays of flat objects."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(u=this.logger)==null||u.call(this,{requestId:c,path:i,...d,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new T(p.data):new T},createMany:async(e,r)=>{var h,u,g;let s=I(e.data)?e.data:[e.data];if(!s.every(S=>Z(S)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=e.vectors?I(e.vectors[0])?e.vectors:[e.vectors]:void 0;if(a&&a.length>s.length)throw new Error(`records.createMany: vectors length (${a.length}) exceeds the number of data rows (${s.length}).`);let o=a!=null&&a.length?s.map((S,q)=>{var _;return(_=a[q])!=null&&_.length?{...S,$vectors:a[q]}:S}):s,i=R(r),d="/records/import/json",c={headers:Object.assign({},x(i)),method:"POST",requestData:{label:e.label,data:o,options:e.options}},l=typeof this.logger=="function"?y():"";(h=this.logger)==null||h.call(this,{requestId:l,path:d,...c});let p=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:l,path:d,...c,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)){let S=I(p.data)?(g=p.data)==null?void 0:g.map(q=>new T(q)):[];return new $(S,p.total)}return new $([])},importJson:async(e,r)=>{var h,u,g;let{data:s,options:n}=e,{label:a}=e,o=s;if(!a){let S=P(s)&&!I(s)?X(s):s;if(nt(S))throw new Error("records.importJson: Missing `label`. Provide `label` for top-level arrays or objects with primitive top-level properties, or pass a container object whose top-level values are objects or arrays, e.g. { ITEM: [...], USER: [...] }.")}let i=R(r),d="/records/import/json",c={headers:Object.assign({},x(i)),method:"POST",requestData:{label:a,data:o,options:n}},l=typeof this.logger=="function"?y():"";(h=this.logger)==null||h.call(this,{requestId:l,path:d,...c});let p=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:l,path:d,...c,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)){let S=I(p.data)?(g=p.data)==null?void 0:g.map(q=>new T(q)):[];return new $(S,p.total)}return new $([])},importCsv:async(e,r)=>{var d,c;let s=R(r),n="/records/import/csv",a={headers:Object.assign({},x(s)),method:"POST",requestData:e},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let l=I(i.data)?i.data.map(p=>new T(p)):[];return new $(l,i.total)}return new $([])},delete:async(e,r)=>{var d,c,l;if(z(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new C("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let s=R(r),n="/records/delete",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteById:async(e,r)=>{var c,l;let s=R(r),n=I(e),a=n?"/records/delete":`/records/${e}`,o={headers:Object.assign({},x(s)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d},export:async(e,r)=>{var d,c;let s=R(r),n="/records/export/csv",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var p,h;let{id:s,...n}=e,a=R(r),o=s?`/records/${s}/search`:"/records/search",i={headers:Object.assign({},x(a)),method:"POST",requestData:n!=null?n:{}},d=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:c.data});let l=c.data.map(u=>new T(u));return new $(l,c.total,e)},vectorSearch:async(e,r)=>{var l,p,h,u,g,S,q;let s=R(r),n="/ai/search",a={method:"POST",headers:Object.assign({},x(s)),requestData:e},o=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map(_=>new T(_)),c=new $(d,(u=i.total)!=null?u:0);return c.vectorSearch=(g=i.meta)==null?void 0:g.vectorSearch,c.textSearch=(S=i.meta)==null?void 0:S.textSearch,c.fusion=(q=i.meta)==null?void 0:q.fusion,c},textSearch:async(e,r)=>{var l,p,h,u,g;let s=R(r),n="/search/text",a={method:"POST",headers:Object.assign({},x(s)),requestData:e},o=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=((h=i.data)!=null?h:[]).map(S=>new T(S)),c=new $(d,(u=i.total)!=null?u:0);return c.textSearch=(g=i.meta)==null?void 0:g.textSearch,c},findById:async(e,r)=>{var d,c;let s=R(r),n=I(e)?"/records/search":`/records/${e}`,a={headers:Object.assign({},x(s)),method:I(e)?"POST":"GET",requestData:I(e)?{where:{$id:{$in:e}},limit:e.length}:void 0},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),I(e)){let l=i.data.map(p=>new T(p));return new $(l,i.total)}else return new T(i.data)},findOne:async(e,r)=>{var c,l;let s=R(r),n="/records/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data});let[d]=i.data;return new T(d)},findUniq:async(e,r)=>{var c,l;let s=R(r),n="/records/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((l=this.logger)==null||l.call(this,{requestId:o,path:n,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new ce(i.total,e);let[d]=i.data;return new T(d)},set:async({target:e,label:r,data:s,options:n,vectors:a},o)=>{var g,S;let i=R(o),c=`/records/${k(e)}`,l={headers:Object.assign({},x(i)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?y():"",h=X(Q(s));if(I(h)&&h.every(Y))l.requestData={label:r,properties:h,...(a==null?void 0:a.length)&&{vectors:a}};else if(Z(h))l.requestData={label:r,data:h,options:n,...(a==null?void 0:a.length)&&{vectors:a}};else throw P(h)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(g=this.logger)==null||g.call(this,{requestId:p,path:c,...l});let u=await this.fetcher(c,l);return(S=this.logger)==null||S.call(this,{requestId:p,path:c,...l,responseData:u.data}),u!=null&&u.success&&(u!=null&&u.data)?new T(u.data):new T},update:async({target:e,label:r,data:s,options:n},a)=>{var u,g;let o=k(e),i=R(a),d=`/records/${o}`,c={headers:Object.assign({},x(i)),method:"PATCH",requestData:{}},l=typeof this.logger=="function"?y():"",p=X(Q(s));if(I(p)&&p.every(Y))c.requestData={label:r,properties:p};else if(Z(p))c.requestData={label:r,data:p,options:n};else throw P(p)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,{requestId:l,path:d,...c});let h=await this.fetcher(d,c);return(g=this.logger)==null||g.call(this,{requestId:l,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T},upsert:async({label:e,data:r,options:s,vectors:n},a)=>{var u,g,S;let o=R(a),i="/records",d={headers:Object.assign({},x(o)),method:"POST",requestData:{}},c=typeof this.logger=="function"?y():"",l=X(Q(r)),p={...s,mergeBy:(u=s==null?void 0:s.mergeBy)!=null?u:[]};if(I(l)&&l.every(Y))d.requestData={label:e,properties:l,options:p,...(n==null?void 0:n.length)&&{vectors:n}};else if(Z(l))d.requestData={label:e,data:l,options:p,...(n==null?void 0:n.length)&&{vectors:n}};else throw P(l)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(g=this.logger)==null||g.call(this,{requestId:c,path:i,...d});let h=await this.fetcher(i,d);return(S=this.logger)==null||S.call(this,{requestId:c,path:i,...d,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new T(h.data):new T}};this.relationships={patterns:{list:async()=>{var a,o;let e="/relationships/patterns",r={method:"GET",headers:{}},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},analyze:async()=>{var a,o;let e="/relationships/patterns/analyze",r={method:"POST",headers:{},requestData:{}},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},approve:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/approve`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},ignore:async e=>{var o,i;let r=`/relationships/patterns/${encodeURIComponent(e)}/ignore`,s={method:"POST",headers:{},requestData:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},delete:async(e,r)=>{var d,c;let s=r!=null&&r.deleteExisting?"?deleteExisting=true":"",n=`/relationships/patterns/${encodeURIComponent(e)}${s}`,a={method:"DELETE",headers:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}},createMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/create-many",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteMany:async(e,r)=>{var d,c;let s=R(r),n="/relationships/delete-many",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},update:async({source:e,target:r,type:s,direction:n,set:a,unset:o,types:i})=>{var u,g;let c=`/relationships/${k(e)}`,l={headers:{},method:"PATCH",requestData:{targetIds:this._extractTargetIds(r,"Update"),type:s,...n&&{direction:n},...a&&{set:a},...o&&{unset:o},...i&&Object.keys(i).length>0&&{types:i}}},p=typeof this.logger=="function"?y():"";(u=this.logger)==null||u.call(this,{requestId:p,path:c,...l});let h=await this.fetcher(c,l);return(g=this.logger)==null||g.call(this,{requestId:p,path:c,...l,responseData:h.data}),h},find:async(e={},r)=>{var d,c;let s=R(r),n="/relationships/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.properties={delete:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},x(s)),method:"DELETE"},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,r)=>{var d,c;let s=R(r),n="/properties/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},findById:async(e,r)=>{var d,c;let s=R(r),n=`/properties/${e}`,a={headers:Object.assign({},x(s)),method:"GET"},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},values:async(e,r,s)=>{var c,l;let n=R(s),a=`/properties/${e}/values`,o={headers:Object.assign({},x(n)),method:"POST",requestData:r!=null?r:{}},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.labels={find:async(e,r)=>{var d,c;let s=R(r),n="/labels/search",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let r="/tx",s={method:"POST",requestData:P(e)?e:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),new M(a.data.id)},commit:async e=>{var i,d;let s=`/tx/${R(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},get:async e=>{var i,d;let s=`/tx/${R(e)}`,n={method:"GET"},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),new M(o.data.id)},rollback:async e=>{var i,d;let s=`/tx/${R(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",r={method:"GET"},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n}};this.query={raw:async({query:e,params:r},s)=>{var c,l;let n=R(s),a="/query/raw",o={headers:Object.assign({},x(n)),method:"POST",requestData:{query:e,params:r}},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.textIndexes={find:async()=>this.textIndexRequest("/text-indexes","GET"),create:async e=>this.textIndexRequest("/text-indexes","POST",e),suggestName:async e=>this.textIndexRequest("/text-indexes/name-suggestion","POST",e),delete:async e=>this.textIndexRequest(`/text-indexes/${encodeURIComponent(e)}`,"DELETE")};this.ai={searchValues:async e=>{var o,i;let r="/ai/values/search",s={headers:{},method:"POST",requestData:e},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getSchemaSummary:async e=>{var o,i;let r="/ai/schema/summary",s={headers:{},method:"POST",requestData:e!=null?e:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},resolveNames:async e=>{var o,i;let r="/ai/schema/names",s={headers:{},method:"POST",requestData:e},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getJoinCandidates:async e=>{var o,i;let r="/ai/schema/join-candidates",s={headers:{},method:"POST",requestData:e!=null?e:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},getSchema:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},getSchemaMarkdown:async(e,r)=>{var d,c;let s=R(r),n="/ai/schema/md",a={headers:Object.assign({},x(s)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},indexes:{find:async()=>{var a,o;let e="/ai/indexes",r={method:"GET",headers:{}},s=typeof this.logger=="function"?y():"";(a=this.logger)==null||a.call(this,{requestId:s,path:e,...r});let n=await this.fetcher(e,r);return(o=this.logger)==null||o.call(this,{requestId:s,path:e,...r,responseData:n.data}),n},create:async e=>{var c,l;let r="/ai/indexes",{external:s,...n}=e,a=s===!0?{...n,sourceType:"external"}:n,o={method:"POST",headers:{},requestData:a},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:r,...o});let d=await this.fetcher(r,o);return(l=this.logger)==null||l.call(this,{requestId:i,path:r,...o,responseData:d.data}),d},upsertVectors:async(e,r)=>{var i,d;let s=`/ai/indexes/${e}/vectors/upsert`,n={method:"POST",headers:{},requestData:r},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n,responseData:o.data}),o},delete:async e=>{var o,i;let r=`/ai/indexes/${e}`,s={method:"DELETE",headers:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a},stats:async e=>{var o,i;let r=`/ai/indexes/${e}/stats`,s={method:"GET",headers:{}},n=typeof this.logger=="function"?y():"";(o=this.logger)==null||o.call(this,{requestId:n,path:r,...s});let a=await this.fetcher(r,s);return(i=this.logger)==null||i.call(this,{requestId:n,path:r,...s,responseData:a.data}),a}},search:async(e,r)=>{var d,c;let s="/ai/sql-search",n={method:"POST",headers:{},requestData:{prompt:e}},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...n});let o=await this.fetcher(s,n);(c=this.logger)==null||c.call(this,{requestId:a,path:s,...n,responseData:o.data});let i=await this.ai.runSql(o.data.sql,r);return i.name=o.data.name,i.warnings=o.data.warnings,i},runSql:async(e,r)=>{var c,l,p,h,u,g;let s={skip:(c=r==null?void 0:r.skip)!=null?c:0,limit:(l=r==null?void 0:r.limit)!=null?l:100},n="/records/sql-search",a={method:"POST",headers:{},requestData:{sql:e,...s}},o=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(h=this.logger)==null||h.call(this,{requestId:o,path:n,...a,responseData:i.data});let d=new $(((u=i.data)!=null?u:[]).map(S=>new T(S)),(g=i.total)!=null?g:0);return d.sql=e,d.sqlPage=s,d}};if(this.fetcher=null,r!=null&&r.direct){if(!r.engineUrl)throw new Error("Direct mode requires `engineUrl`, the standalone engine base URL.");if(!r.httpClient)throw new Error("Direct mode requires an HTTP client; import the SDK from its Node or browser entry.");this.direct=new we({engineUrl:r.engineUrl,token:e!=null?e:"",httpClient:r.httpClient,scope:r.scope}),this.fetcher=Tt(this.direct)}else if(r!=null&&r.httpClient){let s=Ot(r);this.fetcher=bt({httpClient:r.httpClient,token:e,url:s})}r!=null&&r.options&&(this.options=r==null?void 0:r.options),r!=null&&r.logger&&(this.logger=r==null?void 0:r.logger)}_extractTargetIds(e,r){var s;if(e instanceof T){let n=k(e);if(!n)throw new C(`${r} error: Target id is empty`);return[n]}if(I(e)&&e.every(n=>n instanceof T)){let n=e.map(k).filter(O);if(!n.length)throw new C(`${r} error: Target ids are empty`);return n}if(e instanceof $){let n=(s=e.data)==null?void 0:s.map(k).filter(O);if(!(n!=null&&n.length))throw new C(`${r} error: Target ids are empty`);return n}if(P(e)&&"__id"in e)return[e.__id];if(I(e)&&e.every(n=>P(n)&&"__id"in n)){let n=e.map(k).filter(O);if(!n.length)throw new C(`${r} error: Target ids are empty`);return n}return I(e)?e:v(e)?[e]:[]}async textIndexRequest(e,r,s){var i,d;let n={method:r,headers:{},...s===void 0?{}:{requestData:s}},a=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:a,path:e,...n});let o=await this.fetcher(e,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:e,...n,responseData:o.data}),o}};var At,V=class V extends J{constructor(e,r){var a,o;let s=e!=null?e:typeof process<"u"?(a=process.env)==null?void 0:a.RUSHDB_API_KEY:void 0,n=Ce(r);super(s,{...n,httpClient:(o=n.httpClient)!=null?o:At}),V.instance=this,this.initializeSync(s,n)}initializeSync(e,r){V.state={initialized:!0,debug:!1,timeout:_e("timeout",r==null?void 0:r.timeout,8e4),token:e,direct:(r==null?void 0:r.direct)===!0,engineUrl:r==null?void 0:r.engineUrl}}static getInstance(){if(V.instance)return V.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return O(V.instance)}toDBRecordInstance(e){return new T(e)}};V.instance=null,V.state={initialized:!1,debug:!1,timeout:8e4};var w=V,Fe=t=>{At=t};var He=class{constructor(e,r,s){this.label=e,this.schema=r,this.config=s!=null?s:{}}getLabel(){return this.label}async toDBRecordInstance(e){try{return w.getInstance().toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,r){let s=e!=null?e:{};return w.getInstance().records.find({...s,labels:[this.label]},r)}async findOne(e,r){let s=e!=null?e:{};return w.getInstance().records.findOne({...s,labels:[this.label]},r)}async findById(e,r){return this.findOne({where:{$id:e}},r)}async findUniq(e,r){let s=e!=null?e:{};return w.getInstance().records.findUniq({...s,labels:[this.label]},r)}async create(e,r,s){var d,c;let n=await de(this.schema,e),a=Se(this.schema,n),o=O(a),i=w.getInstance();if(o){let l=r!=null?r:await i.tx.begin(),p=await this.find({where:a},l),h=typeof r<"u";if(!((d=p==null?void 0:p.data)!=null&&d.length)){let g=await i.records.create({label:this.label,data:n},l);return h||await l.commit(),g}else switch((c=s==null?void 0:s.onConflict)!=null?c:"throw"){case"upsert":{let S=p.data[0],q=await i.records.set({target:S.id,label:this.label,data:n},l);return h||await l.commit(),q}case"skip":return h||await l.commit(),null;default:throw h||await l.commit(),new L(this.label,a)}}return await i.records.create({label:this.label,data:n},r)}async attach({source:e,target:r,options:s},n){return await w.getInstance().records.attach({source:e,target:r,options:s},n)}async detach({source:e,target:r,options:s},n){return await w.getInstance().records.detach({source:e,target:r,options:s},n)}async validateTargetLabel(e,r){let s=k(e);if(!s)return;let a=await w.getInstance().records.findById(s,r);if(!a)throw new Error(`Record with id "${s}" not found.`);if(a.data.__label!==this.label)throw new TypeError(`Target record label "${a.data.__label}" does not match model label "${this.label}".`)}async handleSetOrUpdate(e,r,s,n){var d,c;if(this.config.validateTargetLabel&&await this.validateTargetLabel(e,n),I(r)&&r.every(Y))return await w.getInstance().records[s]({label:this.label,target:e,data:r},n);let a=w.getInstance(),o=await de(this.schema,r),i=Se(this.schema,o);if(!z(i)){let l=n!=null?n:await a.tx.begin(),p=await this.find({where:i},l),h=typeof n<"u";if(!((d=p==null?void 0:p.data)!=null&&d.length)||p.data.length===1&&((c=p.data[0])==null?void 0:c.id)===k(e)){let g=await a.records[s]({target:e,label:this.label,data:o},l);return h||await l.commit(),g}else throw h||await l.commit(),new L(this.label,i)}return await a.records[s]({label:this.label,target:e,data:o},n)}async set(e,r,s){return await this.handleSetOrUpdate(e,r,"set",s)}async update(e,r,s){return await this.handleSetOrUpdate(e,r,"update",s)}async createMany(e,r){var o;let s=w.getInstance(),n=typeof r<"u",a=r!=null?r:await s.tx.begin();try{let i=await Promise.all(e.map(async l=>await de(this.schema,l))),d=ke(i,this.schema,this.label);if(!z(d)){let l=Object.entries(d).map(([h,u])=>({[h]:{$in:u}})),p=await this.find({where:{$or:l}},a);if((o=p==null?void 0:p.data)!=null&&o.length)throw new L(this.label,Object.keys(d))}let c=await s.records.createMany({label:this.label,data:i},a);return n||await a.commit(),c}catch(i){throw n||await a.rollback(),i}}async delete(e,r){if(z(e.where))throw new C(`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 w.getInstance().records.delete({...e,labels:[this.label]},r)}async deleteById(e,r){return await w.getInstance().records.deleteById(e,r)}};Fe(new fe);var sr=w;0&&(module.exports={CLOUD_ONLY_FORMS,CLOUD_ONLY_METHODS,CloudOnlyError,DBRecordInstance,DBRecordsArrayInstance,DirectModeError,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,isCloudOnlyMethod,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});