@apito-io/js-admin-sdk 2.7.0 → 3.1.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/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  // @apito-io/js-admin-sdk - Admin SDK for Apito GraphQL API
2
- import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);this.code=n;this.statusCode=r;this.details=a;this.name="ApitoError"}},g=class extends u{constructor(t,n,r){super(t,"GRAPHQL_ERROR");this.graphQLErrors=n;this.response=r;this.name="GraphQLError"}get partialData(){return this.response?.data}},o=class extends u{constructor(t,n){super(t,"VALIDATION_ERROR");this.field=n;this.name="ValidationError"}};var l=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey,this.tenantId=e.tenantId,this.httpClient=y.create({timeout:e.timeout||3e4,headers:{"Content-Type":"application/json",...this.apiKey.startsWith("cli-")||this.apiKey.startsWith("sdk-")?{"X-Apito-Sync-Key":this.apiKey}:{"X-Apito-Key":this.apiKey}},...e.httpClient}),this.tenantId&&(this.httpClient.defaults.headers["X-Apito-Tenant-ID"]=this.tenantId)}async executeGraphQL(e,t,n){try{let r={query:e,variables:t||{}},a={"Content-Type":"application/json",...this.apiKey.startsWith("cli-")||this.apiKey.startsWith("sdk-")?{"X-Apito-Sync-Key":this.apiKey}:{"X-Apito-Key":this.apiKey}};(n?.tenantId||this.tenantId)&&(a["X-Apito-Tenant-ID"]=n?.tenantId||this.tenantId);let s=await this.httpClient.post(this.baseURL,r,{headers:a});if(s.data.errors&&s.data.errors.length>0)throw new g("GraphQL query failed",s.data.errors,s.data);return s.data}catch(r){throw y.isAxiosError(r)?new u(r.response?.data?.message||r.message,"HTTP_ERROR",r.response?.status,r.response?.data):r}}async generateTenantToken(e,t,n){let r=(t??"").trim();if(!r){let p=new Date;r=`${p.getUTCFullYear()+1}-${String(p.getUTCMonth()+1).padStart(2,"0")}-${String(p.getUTCDate()).padStart(2,"0")}`}let a=`
2
+ import m from"axios";var u=class extends Error{constructor(t,r,n,s){super(t);this.code=r;this.statusCode=n;this.details=s;this.name="ApitoError"}},g=class extends u{constructor(t,r,n){super(t,"GRAPHQL_ERROR");this.graphQLErrors=r;this.response=n;this.name="GraphQLError"}get partialData(){return this.response?.data}},i=class extends u{constructor(t,r){super(t,"VALIDATION_ERROR");this.field=r;this.name="ValidationError"}};function _(c){let e=c.trim().replace(/\/$/,"");return e.endsWith("/graphql")?e.slice(0,-8):e}var p=class{constructor(e){this.baseURL=e.baseURL,this.restBaseURL=(e.restBaseURL??"").trim()||_(e.baseURL),this.apiKey=e.apiKey,this.tenantId=e.tenantId,this.httpClient=m.create({timeout:e.timeout||3e4,headers:{"Content-Type":"application/json",...this.apiKey.startsWith("cli-")||this.apiKey.startsWith("sdk-")?{"X-Apito-Sync-Key":this.apiKey}:{"X-Apito-Key":this.apiKey}},...e.httpClient}),this.tenantId&&(this.httpClient.defaults.headers["X-Apito-Tenant-ID"]=this.tenantId)}async executeGraphQL(e,t,r){try{let n={query:e,variables:t||{}},s={"Content-Type":"application/json",...this.apiKey.startsWith("cli-")||this.apiKey.startsWith("sdk-")?{"X-Apito-Sync-Key":this.apiKey}:{"X-Apito-Key":this.apiKey}};(r?.tenantId||this.tenantId)&&(s["X-Apito-Tenant-ID"]=r?.tenantId||this.tenantId);let a=await this.httpClient.post(this.baseURL,n,{headers:s});if(a.data.errors&&a.data.errors.length>0)throw new g("GraphQL query failed",a.data.errors,a.data);return a.data}catch(n){throw m.isAxiosError(n)?new u(n.response?.data?.message||n.message,"HTTP_ERROR",n.response?.status,n.response?.data):n}}async generateTenantToken(e,t,r){let n=(t??"").trim();if(!n){let l=new Date;n=`${l.getUTCFullYear()+1}-${String(l.getUTCMonth()+1).padStart(2,"0")}-${String(l.getUTCDate()).padStart(2,"0")}`}let s=`
3
3
  mutation GenerateTenantToken($tenantId: String!, $duration: String!, $role: String) {
4
4
  generateTenantToken(tenant_id: $tenantId, duration: $duration, role: $role) {
5
5
  token
6
6
  }
7
7
  }
8
- `,s={tenantId:e,duration:r,role:n!==void 0&&n.trim()!==""?n.trim():null},d=(await this.executeGraphQL(a,s,{tenantId:e})).data?.generateTenantToken;if(!d?.token)throw new o("Invalid response format for tenant token");return d.token}async loginTenantUser(e){let t=(e.authMethod??"general").trim().toLowerCase()||"general",n={project_id:e.projectId};if(t==="google"){n.auth_method="google";let i=(e.code??"").trim(),d=(e.state??"").trim();if(!i||!d)throw new o("code and state are required for Google login");n.code=i,n.state=d}else{let i=(e.password??"").trim();if(!i)throw new o("password is required");n.password=i;let d=(e.email??"").trim(),p=(e.phone??"").trim();if(!d&&!p)throw new o("email or phone is required");d&&(n.email=d),p&&(n.phone=p)}let s=(await this.executeGraphQL(`
9
- query LoginTenantUser($project_id: String!, $password: String, $auth_method: String, $email: String, $phone: String, $code: String, $state: String) {
10
- loginTenantUser(project_id: $project_id, password: $password, auth_method: $auth_method, email: $email, phone: $phone, code: $code, state: $state) {
8
+ `,a={tenantId:e,duration:n,role:r!==void 0&&r.trim()!==""?r.trim():null},d=(await this.executeGraphQL(s,a,{tenantId:e})).data?.generateTenantToken;if(!d?.token)throw new i("Invalid response format for tenant token");return d.token}authHeaders(e){let t={...this.apiKey.startsWith("cli-")||this.apiKey.startsWith("sdk-")?{"X-Apito-Sync-Key":this.apiKey}:{"X-Apito-Key":this.apiKey}},r=e??this.tenantId;return r&&(t["X-Apito-Tenant-ID"]=r),t}async executeREST(e,t,r){let n=new URL(`${this.restBaseURL.replace(/\/$/,"")}${t}`);if(r?.query)for(let[o,d]of Object.entries(r.query))d!==void 0&&d!==""&&n.searchParams.set(o,String(d));let s=this.authHeaders(),a;r?.formData?a=r.formData:r?.jsonBody&&(s["Content-Type"]="application/json",a=r.jsonBody);try{let d=(await this.httpClient.request({method:e,url:n.toString(),headers:s,data:a,maxBodyLength:1/0,maxContentLength:1/0})).data;if(d.success===!1&&!r?.allowFailure)throw new i(String(d.message??"request failed"));return d}catch(o){if(m.isAxiosError(o)){let d=o.response?.data?.message??o.message;throw new u(d,"HTTP_ERROR",o.response?.status,o.response?.data)}throw o}}async loginUser(e){let t=(e.authMethod??"general").trim().toLowerCase()||"general",r={project_id:e.projectId};if(t==="google"){r.auth_method="google";let o=(e.code??"").trim(),d=(e.state??"").trim();if(!o||!d)throw new i("code and state are required for Google login");r.code=o,r.state=d}else{let o=(e.password??"").trim();if(!o)throw new i("password is required");r.password=o;let d=(e.email??"").trim(),l=(e.phone??"").trim();if(!d&&!l)throw new i("email or phone is required");d&&(r.email=d),l&&(r.phone=l)}let a=(await this.executeGraphQL(`
9
+ query LoginUser($project_id: String!, $password: String, $auth_method: String, $email: String, $phone: String, $code: String, $state: String) {
10
+ loginUser(project_id: $project_id, password: $password, auth_method: $auth_method, email: $email, phone: $phone, code: $code, state: $state) {
11
11
  token
12
12
  user {
13
13
  id
@@ -22,15 +22,15 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
22
22
  }
23
23
  }
24
24
  }
25
- `,n)).data?.loginTenantUser;if(!s?.token)throw new o("Invalid response format for loginTenantUser");return{token:s.token,user:s.user}}async tenantGoogleOAuthState(e){let t=`
26
- query TenantGoogleOAuthState($project_id: String!) {
27
- tenantGoogleOAuthState(project_id: $project_id) {
25
+ `,r)).data?.loginUser;if(!a?.token)throw new i("Invalid response format for loginUser");return{token:a.token,user:a.user}}async googleOAuthState(e){let t=`
26
+ query GoogleOAuthState($project_id: String!) {
27
+ googleOAuthState(project_id: $project_id) {
28
28
  state
29
29
  }
30
30
  }
31
- `,n={project_id:e},a=(await this.executeGraphQL(t,n)).data?.tenantGoogleOAuthState,s=typeof a?.state=="string"?a.state.trim():"";if(!s)throw new o("Invalid response format for tenantGoogleOAuthState");return{state:s}}async searchTenantUsers(e,t,n){let r=`
32
- query SearchTenantUsers($project_id: String!, $limit: Int, $offset: Int) {
33
- searchTenantUsers(project_id: $project_id, limit: $limit, offset: $offset) {
31
+ `,r={project_id:e},s=(await this.executeGraphQL(t,r)).data?.googleOAuthState,a=typeof s?.state=="string"?s.state.trim():"";if(!a)throw new i("Invalid response format for googleOAuthState");return{state:a}}async searchUsers(e,t,r){let n=`
32
+ query SearchUsers($project_id: String!, $limit: Int, $offset: Int) {
33
+ searchUsers(project_id: $project_id, limit: $limit, offset: $offset) {
34
34
  count
35
35
  users {
36
36
  id
@@ -45,7 +45,7 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
45
45
  }
46
46
  }
47
47
  }
48
- `,a={project_id:e};t!==void 0&&(a.limit=t),n!==void 0&&(a.offset=n);let i=(await this.executeGraphQL(r,a)).data?.searchTenantUsers;if(!i)throw new o("Invalid response format for searchTenantUsers");let d=0;return typeof i.count=="number"&&(d=i.count),{users:i.users??[],count:d}}async searchTenantsByDomain(e,t){let n=`
48
+ `,s={project_id:e};t!==void 0&&(s.limit=t),r!==void 0&&(s.offset=r);let o=(await this.executeGraphQL(n,s)).data?.searchUsers;if(!o)throw new i("Invalid response format for searchUsers");let d=0;return typeof o.count=="number"&&(d=o.count),{users:o.users??[],count:d}}async searchTenantsByDomain(e,t){let r=`
49
49
  query SearchTenantsByDomain($project_id: String!, $domain: String!) {
50
50
  searchTenantsByDomain(project_id: $project_id, domain: $domain) {
51
51
  tenant {
@@ -57,9 +57,9 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
57
57
  }
58
58
  }
59
59
  }
60
- `,r={project_id:e,domain:t},s=(await this.executeGraphQL(n,r)).data?.searchTenantsByDomain;if(!s)throw new o("Invalid response format for searchTenantsByDomain");return{tenant:s.tenant??null}}async createTenantUser(e,t){let n=(t.password??"").trim();if(!n)throw new o("password is required");let r=`
61
- mutation CreateTenantUser($project_id: String!, $password: String!, $role: String, $email: String, $phone: String) {
62
- createTenantUser(project_id: $project_id, password: $password, role: $role, email: $email, phone: $phone) {
60
+ `,n={project_id:e,domain:t},a=(await this.executeGraphQL(r,n)).data?.searchTenantsByDomain;if(!a)throw new i("Invalid response format for searchTenantsByDomain");return{tenant:a.tenant??null}}async createUser(e,t){let r=(t.password??"").trim();if(!r)throw new i("password is required");let n=`
61
+ mutation CreateUser($project_id: String!, $password: String!, $role: String, $email: String, $phone: String) {
62
+ createUser(project_id: $project_id, password: $password, role: $role, email: $email, phone: $phone) {
63
63
  id
64
64
  email
65
65
  phone
@@ -71,9 +71,9 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
71
71
  updated_at
72
72
  }
73
73
  }
74
- `,a={project_id:e,password:n},s=(t.role??"").trim();s&&(a.role=s);let i=(t.email??"").trim();i&&(a.email=i);let d=(t.phone??"").trim();d&&(a.phone=d);let h=(await this.executeGraphQL(r,a)).data?.createTenantUser;if(!h?.id)throw new o("Invalid response format for createTenantUser");return h}async updateTenantUser(e,t){let n=(e??"").trim();if(!n)throw new o("userId is required");if(t.email===void 0&&t.phone===void 0&&t.password===void 0&&t.role===void 0)throw new o("at least one field must be provided");let r=`
75
- mutation UpdateTenantUser($user_id: String!, $email: String, $phone: String, $password: String, $role: String) {
76
- updateTenantUser(user_id: $user_id, email: $email, phone: $phone, password: $password, role: $role) {
74
+ `,s={project_id:e,password:r},a=(t.role??"").trim();a&&(s.role=a);let o=(t.email??"").trim();o&&(s.email=o);let d=(t.phone??"").trim();d&&(s.phone=d);let f=(await this.executeGraphQL(n,s)).data?.createUser;if(!f?.id)throw new i("Invalid response format for createUser");return f}async updateUser(e,t){let r=(e??"").trim();if(!r)throw new i("userId is required");if(t.email===void 0&&t.phone===void 0&&t.role===void 0)throw new i("at least one field must be provided");let n=`
75
+ mutation UpdateUser($user_id: String!, $email: String, $phone: String, $role: String) {
76
+ updateUser(user_id: $user_id, email: $email, phone: $phone, role: $role) {
77
77
  id
78
78
  email
79
79
  phone
@@ -85,11 +85,15 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
85
85
  updated_at
86
86
  }
87
87
  }
88
- `,a={user_id:n};t.email!==void 0&&(a.email=t.email),t.phone!==void 0&&(a.phone=t.phone),t.password!==void 0&&(a.password=t.password),t.role!==void 0&&(a.role=t.role);let i=(await this.executeGraphQL(r,a)).data?.updateTenantUser;if(!i?.id)throw new o("Invalid response format for updateTenantUser");return i}async deleteTenantUser(e){let t=(e??"").trim();if(!t)throw new o("userId is required");let a=(await this.executeGraphQL(`
89
- mutation DeleteTenantUser($user_id: String!) {
90
- deleteTenantUser(user_id: $user_id)
88
+ `,s={user_id:r};t.email!==void 0&&(s.email=t.email),t.phone!==void 0&&(s.phone=t.phone),t.role!==void 0&&(s.role=t.role);let o=(await this.executeGraphQL(n,s)).data?.updateUser;if(!o?.id)throw new i("Invalid response format for updateUser");return o}async resetUserPassword(e,t){let r=(e??"").trim();if(!r)throw new i("userId is required");if(!(t??"").trim())throw new i("password is required");let a=(await this.executeGraphQL(`
89
+ mutation ResetUserPassword($user_id: String!, $password: String!) {
90
+ resetUserPassword(user_id: $user_id, password: $password)
91
91
  }
92
- `,{user_id:t})).data?.deleteTenantUser;if(typeof a!="boolean")throw new o("Invalid response format for deleteTenantUser");return a}async getSingleResource(e,t,n=!1){let r=`
92
+ `,{user_id:r,password:t})).data?.resetUserPassword;if(typeof a!="boolean")throw new i("Invalid response format for resetUserPassword");return a}async deleteUser(e){let t=(e??"").trim();if(!t)throw new i("userId is required");let s=(await this.executeGraphQL(`
93
+ mutation DeleteUser($user_id: String!) {
94
+ deleteUser(user_id: $user_id)
95
+ }
96
+ `,{user_id:t})).data?.deleteUser;if(typeof s!="boolean")throw new i("Invalid response format for deleteUser");return s}async uploadFile(e){let t=(e.content instanceof ArrayBuffer,e.content.byteLength);if(!e.content||t===0)throw new i("file content is required");let r=(e.fileName??"").trim()||"upload",n=new FormData,s=e.content instanceof ArrayBuffer?new Uint8Array(e.content):e.content,a=new Blob([s]);n.append("file",a,r),e.fileType?.trim()&&n.append("file_type",e.fileType.trim());let o=await this.executeREST("POST","/files/upload",{formData:n});if(!o.file?.id)throw new i("Invalid response format for uploadFile");return o.file}async listFiles(e,t,r){let n=await this.executeREST("GET","/files/list",{query:{file_type:e,limit:t,offset:r}});return{files:n.files??[],total:n.total??0}}async deleteFiles(e){if(!e?.length)throw new i("ids are required");let t=await this.executeREST("POST","/files/delete",{jsonBody:{ids:e},allowFailure:!0}),r={success:!!t.success,deleted_ids:t.deleted_ids??[],storage_failed:t.storage_failed,message:t.message};if(!r.success&&r.message)throw new i(r.message);return r}async getSingleResource(e,t,r=!1){let n=`
93
97
  query GetSingleData($model: String, $_id: String!, $single_page_data: Boolean) {
94
98
  getSingleData(model: $model, _id: $_id, single_page_data: $single_page_data) {
95
99
  _key
@@ -107,7 +111,7 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
107
111
  type
108
112
  }
109
113
  }
110
- `,a={model:e,_id:t,single_page_data:n},s=await this.executeGraphQL(r,a);if(!s.data?.getSingleData)throw new o("Resource not found");return s.data.getSingleData}async searchResources(e,t={},n=!1){let r=`
114
+ `,s={model:e,_id:t,single_page_data:r},a=await this.executeGraphQL(n,s);if(!a.data?.getSingleData)throw new i("Resource not found");return a.data.getSingleData}async searchResources(e,t={},r=!1){let n=`
111
115
  query GetModelData(
112
116
  $model: String!
113
117
  $page: Int
@@ -140,7 +144,7 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
140
144
  count
141
145
  }
142
146
  }
143
- `,a={model:e};t&&typeof t=="object"&&(t._key!==void 0&&(a._key=t._key),t.page!==void 0&&(a.page=t.page),t.limit!==void 0&&(a.limit=t.limit),t.where!==void 0&&(a.where=t.where),t.search!==void 0&&(a.search=t.search));let s=await this.executeGraphQL(r,a);if(!s.data?.getModelData)throw new o("Invalid search response format");return s.data.getModelData}async getRelationDocuments(e,t){let n=`
147
+ `,s={model:e};t&&typeof t=="object"&&(t._key!==void 0&&(s._key=t._key),t.page!==void 0&&(s.page=t.page),t.limit!==void 0&&(s.limit=t.limit),t.where!==void 0&&(s.where=t.where),t.search!==void 0&&(s.search=t.search));let a=await this.executeGraphQL(n,s);if(!a.data?.getModelData)throw new i("Invalid search response format");return a.data.getModelData}async getRelationDocuments(e,t){let r=`
144
148
  query GetModelData($model: String!, $page: Int, $limit: Int, $where: JSON, $search: String, $connection : ListAllDataDetailedOfAModelConnectionPayload) {
145
149
  getModelData(model: $model, page: $page, limit: $limit, where: $where, search: $search, connection: $connection) {
146
150
  results {
@@ -159,7 +163,7 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
159
163
  count
160
164
  }
161
165
  }
162
- `,r={connection:t};if(t.model)r.model=t.model;else throw new o("model is required in connection parameters");if(t.filter){let s=t.filter;s.page!==void 0&&(r.page=s.page),s.limit!==void 0&&(r.limit=s.limit),s.where!==void 0&&(r.where=s.where),s.search!==void 0&&(r.search=s.search)}let a=await this.executeGraphQL(n,r);if(!a.data?.getModelData)throw new o("Invalid relation documents response format");return a.data.getModelData}async createNewResource(e){if(!e.model)throw new o("model is required");if(!e.payload)throw new o("payload is required");let t=`
166
+ `,n={connection:t};if(t.model)n.model=t.model;else throw new i("model is required in connection parameters");if(t.filter){let a=t.filter;a.page!==void 0&&(n.page=a.page),a.limit!==void 0&&(n.limit=a.limit),a.where!==void 0&&(n.where=a.where),a.search!==void 0&&(n.search=a.search)}let s=await this.executeGraphQL(r,n);if(!s.data?.getModelData)throw new i("Invalid relation documents response format");return s.data.getModelData}async createNewResource(e){if(!e.model)throw new i("model is required");if(!e.payload)throw new i("payload is required");let t=`
163
167
  mutation CreateNewData($model: String!, $single_page_data: Boolean, $payload: JSON!, $connect: JSON) {
164
168
  upsertModelData(
165
169
  connect: $connect
@@ -179,7 +183,7 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
179
183
  }
180
184
  }
181
185
  }
182
- `,n={model:e.model,payload:e.payload,single_page_data:e.singlePageData||!1};e.connect&&(n.connect=e.connect);let r=await this.executeGraphQL(t,n);if(!r.data?.upsertModelData)throw new o("Invalid create response format");return r.data.upsertModelData}async updateResource(e){if(!e.id)throw new o("id is required");if(!e.model)throw new o("model is required");if(!e.payload)throw new o("payload is required");let t=`
186
+ `,r={model:e.model,payload:e.payload,single_page_data:e.singlePageData||!1};e.connect&&(r.connect=e.connect);let n=await this.executeGraphQL(t,r);if(!n.data?.upsertModelData)throw new i("Invalid create response format");return n.data.upsertModelData}async updateResource(e){if(!e.id)throw new i("id is required");if(!e.model)throw new i("model is required");if(!e.payload)throw new i("payload is required");let t=`
183
187
  mutation UpdateModelData($_id: String!, $model: String!, $single_page_data: Boolean, $force_update: Boolean, $payload: JSON!, $connect: JSON, $disconnect: JSON) {
184
188
  upsertModelData(
185
189
  connect: $connect
@@ -202,18 +206,18 @@ import y from"axios";var u=class extends Error{constructor(t,n,r,a){super(t);thi
202
206
  }
203
207
  }
204
208
  }
205
- `,n={_id:e.id,model:e.model,payload:e.payload,single_page_data:e.singlePageData||!1,force_update:e.forceUpdate||!1};e.connect&&(n.connect=e.connect),e.disconnect&&(n.disconnect=e.disconnect);let r=await this.executeGraphQL(t,n);if(!r.data?.upsertModelData)throw new o("Invalid update response format");return r.data.upsertModelData}async deleteResource(e,t){let n=`
209
+ `,r={_id:e.id,model:e.model,payload:e.payload,single_page_data:e.singlePageData||!1,force_update:e.forceUpdate||!1};e.connect&&(r.connect=e.connect),e.disconnect&&(r.disconnect=e.disconnect);let n=await this.executeGraphQL(t,r);if(!n.data?.upsertModelData)throw new i("Invalid update response format");return n.data.upsertModelData}async deleteResource(e,t){let r=`
206
210
  mutation DeleteData($model: String!, $_id: String!) {
207
211
  deleteModelData(model_name: $model, _id: $_id) {
208
212
  id
209
213
  }
210
214
  }
211
- `,r={model:e,_id:t};await this.executeGraphQL(n,r)}async debug(e,...t){let n=`
215
+ `,n={model:e,_id:t};await this.executeGraphQL(r,n)}async debug(e,...t){let r=`
212
216
  mutation Debug($stage: String!, $data: JSON) {
213
217
  debug(stage: $stage, data: $data) {
214
218
  message
215
219
  data
216
220
  }
217
221
  }
218
- `,r={stage:e,data:t};return(await this.executeGraphQL(n,r)).data?.debug}};function T(c){return new l(c)}var m=class c{constructor(e){this.client=e}static toTypedDocument(e){let t=JSON.parse(JSON.stringify(e.data));return{_key:e._key,_id:e._id,data:t,meta:e.meta,id:e.id,expire_at:e.expire_at,relation_doc_id:e.relation_doc_id,last_revision_doc_id:e.last_revision_doc_id,type:e.type,tenant_id:e.tenant_id,tenant_model:e.tenant_model}}async getSingleResourceTyped(e,t,n=!1){let r=await this.client.getSingleResource(e,t,n);return c.toTypedDocument(r)}async searchResourcesTyped(e,t={},n=!1){let r=await this.client.searchResources(e,t,n);return{results:r.results.map(a=>c.toTypedDocument(a)),count:r.count}}async getRelationDocumentsTyped(e,t){let n=await this.client.getRelationDocuments(e,t);return{results:n.results.map(r=>c.toTypedDocument(r)),count:n.count}}async createNewResourceTyped(e){let t=await this.client.createNewResource(e);return c.toTypedDocument(t)}async updateResourceTyped(e){let t=await this.client.updateResource(e);return c.toTypedDocument(t)}};var f="2.7.0";function _(){return f}export{l as ApitoClient,u as ApitoError,g as GraphQLError,m as TypedOperations,o as ValidationError,f as Version,T as createClient,l as default,_ as getVersion};
222
+ `,n={stage:e,data:t};return(await this.executeGraphQL(r,n)).data?.debug}};function R(c){return new p(c)}var h=class c{constructor(e){this.client=e}static toTypedDocument(e){let t=JSON.parse(JSON.stringify(e.data));return{_key:e._key,_id:e._id,data:t,meta:e.meta,id:e.id,expire_at:e.expire_at,relation_doc_id:e.relation_doc_id,last_revision_doc_id:e.last_revision_doc_id,type:e.type,tenant_id:e.tenant_id,tenant_model:e.tenant_model}}async getSingleResourceTyped(e,t,r=!1){let n=await this.client.getSingleResource(e,t,r);return c.toTypedDocument(n)}async searchResourcesTyped(e,t={},r=!1){let n=await this.client.searchResources(e,t,r);return{results:n.results.map(s=>c.toTypedDocument(s)),count:n.count}}async getRelationDocumentsTyped(e,t){let r=await this.client.getRelationDocuments(e,t);return{results:r.results.map(n=>c.toTypedDocument(n)),count:r.count}}async createNewResourceTyped(e){let t=await this.client.createNewResource(e);return c.toTypedDocument(t)}async updateResourceTyped(e){let t=await this.client.updateResource(e);return c.toTypedDocument(t)}};var y="3.1.0";function w(){return y}export{p as ApitoClient,u as ApitoError,g as GraphQLError,h as TypedOperations,i as ValidationError,y as Version,R as createClient,p as default,w as getVersion};
219
223
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/types.ts","../src/typed-operations.ts","../src/version.ts"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\nimport {\n ClientConfig,\n DefaultDocumentStructure,\n SearchResult,\n TypedDocumentStructure,\n TypedSearchResult,\n CreateAndUpdateRequest,\n GraphQLResponse,\n GraphQLError as SDKGraphQLError,\n ApitoError,\n ValidationError,\n InjectedDBOperationInterface,\n TenantLoginResponse,\n TenantUser,\n TenantUsersResponse,\n TenantByDomainResponse,\n TenantCatalogSearchRow,\n TenantLoginParams,\n CreateTenantUserParams,\n UpdateTenantUserParams,\n} from './types';\n\n/**\n * Apito SDK Client - JavaScript implementation matching the Go SDK\n */\nexport class ApitoClient implements InjectedDBOperationInterface {\n private httpClient: AxiosInstance;\n private baseURL: string;\n private apiKey: string;\n private tenantId?: string;\n\n constructor(config: ClientConfig) {\n this.baseURL = config.baseURL;\n this.apiKey = config.apiKey;\n this.tenantId = config.tenantId;\n\n // Create axios instance with default configuration\n this.httpClient = axios.create({\n timeout: config.timeout || 30000,\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey.startsWith('cli-') || this.apiKey.startsWith('sdk-')\n ? { 'X-Apito-Sync-Key': this.apiKey }\n : { 'X-Apito-Key': this.apiKey }),\n },\n ...config.httpClient,\n });\n\n // Add tenant ID to headers if provided\n if (this.tenantId) {\n this.httpClient.defaults.headers['X-Apito-Tenant-ID'] = this.tenantId;\n }\n }\n\n /**\n * Execute an arbitrary GraphQL query or mutation against the Apito admin (system) endpoint.\n * Use for plugin-registered operations (e.g. processLedger, plg_closeOrder) when not wrapped by dedicated SDK methods.\n */\n async executeGraphQL(\n query: string,\n variables?: Record<string, any>,\n options?: { tenantId?: string }\n ): Promise<GraphQLResponse> {\n try {\n const payload = {\n query,\n variables: variables || {},\n };\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(this.apiKey.startsWith('cli-') || this.apiKey.startsWith('sdk-')\n ? { 'X-Apito-Sync-Key': this.apiKey }\n : { 'X-Apito-Key': this.apiKey }),\n };\n\n if (options?.tenantId || this.tenantId) {\n headers['X-Apito-Tenant-ID'] = options?.tenantId || this.tenantId!;\n }\n\n const response = await this.httpClient.post<GraphQLResponse>(\n this.baseURL,\n payload,\n { headers }\n );\n\n if (response.data.errors && response.data.errors.length > 0) {\n throw new SDKGraphQLError(\n 'GraphQL query failed',\n response.data.errors,\n response.data\n );\n }\n\n return response.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n throw new ApitoError(\n error.response?.data?.message || error.message,\n 'HTTP_ERROR',\n error.response?.status,\n error.response?.data\n );\n }\n throw error;\n }\n }\n\n /**\n * Generate a tenant-scoped API key. Matches engine `generateTenantToken`: `tenant_id`, `duration`, optional `role`.\n * Auth uses `X-Apito-Key` (client `apiKey`).\n *\n * @param tenantId Catalog tenant id (`tenant_id` in the mutation).\n * @param duration Expiry calendar day `YYYY-MM-DD`. If omitted/empty, defaults to one year ahead in UTC.\n * @param role Optional token role; if omitted/empty, the engine defaults to `admin`.\n */\n async generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string> {\n let dur = (duration ?? '').trim();\n if (!dur) {\n const d = new Date();\n dur = `${d.getUTCFullYear() + 1}-${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(\n d.getUTCDate()\n ).padStart(2, '0')}`;\n }\n\n const query = `\n mutation GenerateTenantToken($tenantId: String!, $duration: String!, $role: String) {\n generateTenantToken(tenant_id: $tenantId, duration: $duration, role: $role) {\n token\n }\n }\n `;\n\n const variables: Record<string, any> = {\n tenantId,\n duration: dur,\n role: role !== undefined && role.trim() !== '' ? role.trim() : null,\n };\n const response = await this.executeGraphQL(query, variables, { tenantId });\n\n const data = response.data?.generateTenantToken;\n if (!data?.token) {\n throw new ValidationError('Invalid response format for tenant token');\n }\n\n return data.token;\n }\n\n /**\n * Tenant catalog login (system GraphQL `loginTenantUser`). Password path: pass `password` and `email` or `phone` per project Authentication settings. Google OAuth path: `authMethod: 'google'` with `code` and `state` from the redirect; call `tenantGoogleOAuthState(projectId)` before opening Google to obtain `state`.\n */\n async loginTenantUser(params: TenantLoginParams): Promise<TenantLoginResponse> {\n const authMethod = (params.authMethod ?? 'general').trim().toLowerCase() || 'general';\n const variables: Record<string, any> = {\n project_id: params.projectId,\n };\n\n if (authMethod === 'google') {\n variables.auth_method = 'google';\n const code = (params.code ?? '').trim();\n const state = (params.state ?? '').trim();\n if (!code || !state) {\n throw new ValidationError('code and state are required for Google login');\n }\n variables.code = code;\n variables.state = state;\n } else {\n const password = (params.password ?? '').trim();\n if (!password) {\n throw new ValidationError('password is required');\n }\n variables.password = password;\n const email = (params.email ?? '').trim();\n const phone = (params.phone ?? '').trim();\n if (!email && !phone) {\n throw new ValidationError('email or phone is required');\n }\n if (email) variables.email = email;\n if (phone) variables.phone = phone;\n }\n\n const query = `\n query LoginTenantUser($project_id: String!, $password: String, $auth_method: String, $email: String, $phone: String, $code: String, $state: String) {\n loginTenantUser(project_id: $project_id, password: $password, auth_method: $auth_method, email: $email, phone: $phone, code: $code, state: $state) {\n token\n user {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n }\n `;\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.loginTenantUser;\n if (!raw?.token) {\n throw new ValidationError('Invalid response format for loginTenantUser');\n }\n return {\n token: raw.token as string,\n user: raw.user as TenantUser | undefined,\n };\n }\n\n /**\n * Signed OAuth state for tenant Google login (system query `tenantGoogleOAuthState`). Use in the authorize URL together with project `google_client_id` and the configured redirect URI.\n */\n async tenantGoogleOAuthState(projectId: string): Promise<{ state: string }> {\n const query = `\n query TenantGoogleOAuthState($project_id: String!) {\n tenantGoogleOAuthState(project_id: $project_id) {\n state\n }\n }\n `;\n const variables = { project_id: projectId };\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.tenantGoogleOAuthState;\n const state = typeof raw?.state === 'string' ? raw.state.trim() : '';\n if (!state) {\n throw new ValidationError('Invalid response format for tenantGoogleOAuthState');\n }\n return { state };\n }\n\n /**\n * Search tenant users for a project.\n */\n async searchTenantUsers(\n projectId: string,\n limit?: number,\n offset?: number\n ): Promise<TenantUsersResponse> {\n const query = `\n query SearchTenantUsers($project_id: String!, $limit: Int, $offset: Int) {\n searchTenantUsers(project_id: $project_id, limit: $limit, offset: $offset) {\n count\n users {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n }\n `;\n const variables: Record<string, any> = { project_id: projectId };\n if (limit !== undefined) variables.limit = limit;\n if (offset !== undefined) variables.offset = offset;\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.searchTenantUsers;\n if (!raw) {\n throw new ValidationError('Invalid response format for searchTenantUsers');\n }\n let count = 0;\n if (typeof raw.count === 'number') {\n count = raw.count;\n }\n const users = (raw.users ?? []) as TenantUser[];\n return { users, count };\n }\n\n /**\n * Resolve the single SaaS catalog tenant for an exact domain match in the project (`tenant` null if none).\n */\n async searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse> {\n const query = `\n query SearchTenantsByDomain($project_id: String!, $domain: String!) {\n searchTenantsByDomain(project_id: $project_id, domain: $domain) {\n tenant {\n id\n name\n status\n domain\n data\n }\n }\n }\n `;\n const variables: Record<string, any> = {\n project_id: projectId,\n domain,\n };\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.searchTenantsByDomain;\n if (!raw) {\n throw new ValidationError('Invalid response format for searchTenantsByDomain');\n }\n const tenant = (raw.tenant ?? null) as TenantCatalogSearchRow | null;\n return { tenant };\n }\n\n /**\n * Create a tenant catalog user (local password). Use `email` and/or `phone` per engine validation for the project identifier mode.\n */\n async createTenantUser(\n projectId: string,\n params: CreateTenantUserParams\n ): Promise<TenantUser> {\n const password = (params.password ?? '').trim();\n if (!password) {\n throw new ValidationError('password is required');\n }\n const query = `\n mutation CreateTenantUser($project_id: String!, $password: String!, $role: String, $email: String, $phone: String) {\n createTenantUser(project_id: $project_id, password: $password, role: $role, email: $email, phone: $phone) {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n `;\n const variables: Record<string, any> = {\n project_id: projectId,\n password,\n };\n const role = (params.role ?? '').trim();\n if (role) variables.role = role;\n const email = (params.email ?? '').trim();\n if (email) variables.email = email;\n const phone = (params.phone ?? '').trim();\n if (phone) variables.phone = phone;\n const response = await this.executeGraphQL(query, variables);\n const u = response.data?.createTenantUser;\n if (!u?.id) {\n throw new ValidationError('Invalid response format for createTenantUser');\n }\n return u as TenantUser;\n }\n\n /**\n * Update a tenant catalog user. Project scope is implied by the API key. Only include fields to change.\n */\n async updateTenantUser(userId: string, params: UpdateTenantUserParams): Promise<TenantUser> {\n const uid = (userId ?? '').trim();\n if (!uid) {\n throw new ValidationError('userId is required');\n }\n if (\n params.email === undefined &&\n params.phone === undefined &&\n params.password === undefined &&\n params.role === undefined\n ) {\n throw new ValidationError('at least one field must be provided');\n }\n const query = `\n mutation UpdateTenantUser($user_id: String!, $email: String, $phone: String, $password: String, $role: String) {\n updateTenantUser(user_id: $user_id, email: $email, phone: $phone, password: $password, role: $role) {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n `;\n const variables: Record<string, any> = { user_id: uid };\n if (params.email !== undefined) variables.email = params.email;\n if (params.phone !== undefined) variables.phone = params.phone;\n if (params.password !== undefined) variables.password = params.password;\n if (params.role !== undefined) variables.role = params.role;\n const response = await this.executeGraphQL(query, variables);\n const u = response.data?.updateTenantUser;\n if (!u?.id) {\n throw new ValidationError('Invalid response format for updateTenantUser');\n }\n return u as TenantUser;\n }\n\n /**\n * Delete a tenant catalog user by id. Project scope is implied by the API key.\n */\n async deleteTenantUser(userId: string): Promise<boolean> {\n const uid = (userId ?? '').trim();\n if (!uid) {\n throw new ValidationError('userId is required');\n }\n const query = `\n mutation DeleteTenantUser($user_id: String!) {\n deleteTenantUser(user_id: $user_id)\n }\n `;\n const response = await this.executeGraphQL(query, { user_id: uid });\n const ok = response.data?.deleteTenantUser;\n if (typeof ok !== 'boolean') {\n throw new ValidationError('Invalid response format for deleteTenantUser');\n }\n return ok;\n }\n\n /**\n * Get a single resource by model and ID\n */\n async getSingleResource(\n model: string,\n id: string,\n singlePageData: boolean = false\n ): Promise<DefaultDocumentStructure> {\n const query = `\n query GetSingleData($model: String, $_id: String!, $single_page_data: Boolean) {\n getSingleData(model: $model, _id: $_id, single_page_data: $single_page_data) {\n _key\n data\n meta {\n created_at\n updated_at\n status\n revision\n revision_at\n }\n id\n expire_at\n relation_doc_id\n type\n }\n }\n `;\n\n const variables = {\n model,\n _id: id,\n single_page_data: singlePageData,\n };\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.getSingleData) {\n throw new ValidationError('Resource not found');\n }\n\n return response.data.getSingleData;\n }\n\n /**\n * Search resources in a model\n */\n async searchResources(\n model: string,\n filter: Record<string, any> = {},\n aggregate: boolean = false\n ): Promise<SearchResult> {\n const query = `\n query GetModelData(\n $model: String!\n $page: Int\n $limit: Int\n $_key: JSON\n $where: JSON\n $search: String\n ) {\n getModelData(\n model: $model\n page: $page\n limit: $limit\n _key: $_key\n where: $where\n search: $search\n ) {\n results {\n id\n relation_doc_id\n data\n type\n expire_at\n meta {\n created_at\n updated_at\n status\n root_revision_id\n }\n }\n count\n }\n }\n `;\n\n // Only forward keys declared on the GraphQL operation (matches go-internal-sdk)\n const variables: Record<string, any> = { model };\n if (filter && typeof filter === 'object') {\n if (filter._key !== undefined) {\n variables._key = filter._key;\n }\n if (filter.page !== undefined) {\n variables.page = filter.page;\n }\n if (filter.limit !== undefined) {\n variables.limit = filter.limit;\n }\n if (filter.where !== undefined) {\n variables.where = filter.where;\n }\n if (filter.search !== undefined) {\n variables.search = filter.search;\n }\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.getModelData) {\n throw new ValidationError('Invalid search response format');\n }\n\n return response.data.getModelData;\n }\n\n /**\n * Get related documents\n */\n async getRelationDocuments(\n id: string,\n connection: Record<string, any>\n ): Promise<SearchResult> {\n const query = `\n query GetModelData($model: String!, $page: Int, $limit: Int, $where: JSON, $search: String, $connection : ListAllDataDetailedOfAModelConnectionPayload) {\n getModelData(model: $model, page: $page, limit: $limit, where: $where, search: $search, connection: $connection) {\n results {\n id\n relation_doc_id\n data\n type\n expire_at\n meta {\n created_at\n updated_at\n status\n root_revision_id\n }\n }\n count\n }\n }\n `;\n\n const variables: Record<string, any> = {\n connection,\n };\n\n // Extract model from connection if available\n if (connection.model) {\n variables.model = connection.model;\n } else {\n throw new ValidationError('model is required in connection parameters');\n }\n\n // Add filter parameters if provided in connection\n if (connection.filter) {\n const filter = connection.filter;\n if (filter.page !== undefined) {\n variables.page = filter.page;\n }\n if (filter.limit !== undefined) {\n variables.limit = filter.limit;\n }\n if (filter.where !== undefined) {\n variables.where = filter.where;\n }\n if (filter.search !== undefined) {\n variables.search = filter.search;\n }\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.getModelData) {\n throw new ValidationError('Invalid relation documents response format');\n }\n\n return response.data.getModelData;\n }\n\n /**\n * Create a new resource\n */\n async createNewResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure> {\n if (!request.model) {\n throw new ValidationError('model is required');\n }\n\n if (!request.payload) {\n throw new ValidationError('payload is required');\n }\n\n const query = `\n mutation CreateNewData($model: String!, $single_page_data: Boolean, $payload: JSON!, $connect: JSON) {\n upsertModelData(\n connect: $connect\n model_name: $model\n single_page_data: $single_page_data\n payload: $payload\n ) {\n id\n type\n data\n meta {\n created_at\n updated_at\n status\n revision\n revision_at\n }\n }\n }\n `;\n\n const variables: Record<string, any> = {\n model: request.model,\n payload: request.payload,\n single_page_data: request.singlePageData || false,\n };\n\n if (request.connect) {\n variables.connect = request.connect;\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.upsertModelData) {\n throw new ValidationError('Invalid create response format');\n }\n\n return response.data.upsertModelData;\n }\n\n /**\n * Update an existing resource\n */\n async updateResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure> {\n if (!request.id) {\n throw new ValidationError('id is required');\n }\n\n if (!request.model) {\n throw new ValidationError('model is required');\n }\n\n if (!request.payload) {\n throw new ValidationError('payload is required');\n }\n\n const query = `\n mutation UpdateModelData($_id: String!, $model: String!, $single_page_data: Boolean, $force_update: Boolean, $payload: JSON!, $connect: JSON, $disconnect: JSON) {\n upsertModelData(\n connect: $connect\n model_name: $model\n single_page_data: $single_page_data\n force_update: $force_update\n disconnect: $disconnect\n _id: $_id\n payload: $payload\n ) {\n id\n type\n data\n meta {\n created_at\n updated_at\n status\n revision\n revision_at\n }\n }\n }\n `;\n\n const variables: Record<string, any> = {\n _id: request.id,\n model: request.model,\n payload: request.payload,\n single_page_data: request.singlePageData || false,\n force_update: request.forceUpdate || false,\n };\n\n if (request.connect) {\n variables.connect = request.connect;\n }\n if (request.disconnect) {\n variables.disconnect = request.disconnect;\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.upsertModelData) {\n throw new ValidationError('Invalid update response format');\n }\n\n return response.data.upsertModelData;\n }\n\n /**\n * Delete a resource by model and ID\n */\n async deleteResource(model: string, id: string): Promise<void> {\n const query = `\n mutation DeleteData($model: String!, $_id: String!) {\n deleteModelData(model_name: $model, _id: $_id) {\n id\n }\n }\n `;\n\n const variables = {\n model,\n _id: id,\n };\n\n await this.executeGraphQL(query, variables);\n }\n\n /**\n * Debug is used to debug the plugin, you can pass data here to debug the plugin\n */\n async debug(stage: string, ...data: any[]): Promise<any> {\n const query = `\n mutation Debug($stage: String!, $data: JSON) {\n debug(stage: $stage, data: $data) {\n message\n data\n }\n }\n `;\n\n const variables = {\n stage,\n data,\n };\n\n const response = await this.executeGraphQL(query, variables);\n\n return response.data?.debug;\n }\n}\n\n/**\n * Factory function to create a new Apito client\n */\nexport function createClient(config: ClientConfig): ApitoClient {\n return new ApitoClient(config);\n}\n","/**\n * Type definitions for the Apito JavaScript SDK\n */\n\nexport interface MetaField {\n created_at: string;\n updated_at: string;\n status: string;\n revision?: string;\n revision_at?: string;\n root_revision_id?: string;\n}\n\nexport interface DefaultDocumentStructure {\n _key?: string;\n _id?: string;\n data: any;\n meta?: MetaField;\n id: string;\n expire_at?: string | number;\n relation_doc_id?: string;\n last_revision_doc_id?: string;\n type?: string;\n tenant_id?: string;\n tenant_model?: string;\n}\n\nexport interface SearchResult {\n results: DefaultDocumentStructure[];\n count: number;\n}\n\nexport interface TypedDocumentStructure<T> {\n _key?: string;\n _id?: string;\n data: T;\n meta?: MetaField;\n id: string;\n expire_at?: string | number;\n relation_doc_id?: string;\n last_revision_doc_id?: string;\n type?: string;\n tenant_id?: string;\n tenant_model?: string;\n}\n\nexport interface TypedSearchResult<T> {\n results: TypedDocumentStructure<T>[];\n count: number;\n}\n\nexport interface Filter {\n page?: number;\n offset?: number;\n limit?: number;\n order?: string;\n min?: number;\n max?: number;\n category?: string;\n}\n\nexport interface GraphQLErrorLocation {\n line: number;\n column: number;\n}\n\nexport interface GraphQLError {\n message: string;\n locations?: GraphQLErrorLocation[];\n path?: (string | number)[];\n extensions?: Record<string, any>;\n}\n\nexport interface GraphQLResponse {\n data?: any;\n errors?: GraphQLError[];\n}\n\nexport interface CreateAndUpdateRequest {\n id?: string;\n model: string;\n payload: any;\n connect?: Record<string, any>;\n disconnect?: Record<string, any>;\n singlePageData?: boolean;\n forceUpdate?: boolean;\n}\n\n/** Tenant catalog user from engine system DB (pro_tenant_users). */\nexport interface TenantUser {\n id: string;\n email?: string;\n phone?: string;\n role: string;\n tenant_id: string;\n provider?: string;\n status?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Login via system GraphQL `loginTenantUser`. Password path: use `email` or `phone` per project settings. Google OAuth code path: `authMethod: 'google'`, `code`, `state` from redirect (get `state` first via `tenantGoogleOAuthState`). */\nexport interface TenantLoginParams {\n projectId: string;\n /** Required for general (password) login. */\n password?: string;\n email?: string;\n phone?: string;\n /** `general` (default) or `google`. */\n authMethod?: string;\n /** Google authorization code (with `authMethod: 'google'`). */\n code?: string;\n /** OAuth state from `tenantGoogleOAuthState` or callback (with `authMethod: 'google'`). */\n state?: string;\n}\n\nexport interface TenantGoogleOAuthStateResponse {\n state: string;\n}\n\nexport interface CreateTenantUserParams {\n password: string;\n role?: string;\n email?: string;\n phone?: string;\n}\n\n/** Optional fields for `updateTenantUser`; omitted keys are not sent. */\nexport interface UpdateTenantUserParams {\n email?: string;\n phone?: string;\n password?: string;\n role?: string;\n}\n\nexport interface TenantLoginResponse {\n token: string;\n user?: TenantUser;\n}\n\nexport interface TenantUsersResponse {\n users: TenantUser[];\n count: number;\n}\n\n/** One SaaS catalog tenant row from searchTenantsByDomain. */\nexport interface TenantCatalogSearchRow {\n id: string;\n name: string;\n status?: string;\n domain?: string;\n data?: string;\n}\n\nexport interface TenantByDomainResponse {\n tenant: TenantCatalogSearchRow | null;\n}\n\nexport interface ClientConfig {\n baseURL: string;\n apiKey: string;\n timeout?: number;\n httpClient?: any;\n tenantId?: string;\n}\n\nexport interface RequestOptions {\n headers?: Record<string, string>;\n timeout?: number;\n}\n\nexport interface SearchOptions {\n limit?: number;\n page?: number;\n offset?: number;\n where?: Record<string, any>;\n search?: string;\n sort?: Record<string, 1 | -1>;\n}\n\nexport interface ConnectionOptions {\n model: string;\n filter?: SearchOptions;\n}\n\n// Plugin interface matching the Go SDK\nexport interface InjectedDBOperationInterface {\n executeGraphQL(\n query: string,\n variables?: Record<string, any>,\n options?: { tenantId?: string }\n ): Promise<GraphQLResponse>;\n /** @param token Legacy; ignored. Auth uses client API key. */\n generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string>;\n loginTenantUser(params: TenantLoginParams): Promise<TenantLoginResponse>;\n tenantGoogleOAuthState(projectId: string): Promise<TenantGoogleOAuthStateResponse>;\n searchTenantUsers(projectId: string, limit?: number, offset?: number): Promise<TenantUsersResponse>;\n searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse>;\n createTenantUser(projectId: string, params: CreateTenantUserParams): Promise<TenantUser>;\n updateTenantUser(userId: string, params: UpdateTenantUserParams): Promise<TenantUser>;\n deleteTenantUser(userId: string): Promise<boolean>;\n getSingleResource(model: string, id: string, singlePageData?: boolean): Promise<DefaultDocumentStructure>;\n searchResources(model: string, filter?: Record<string, any>, aggregate?: boolean): Promise<SearchResult>;\n getRelationDocuments(id: string, connection: Record<string, any>): Promise<SearchResult>;\n createNewResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure>;\n updateResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure>;\n deleteResource(model: string, id: string): Promise<void>;\n debug(stage: string, ...data: any[]): Promise<any>;\n}\n\n// Typed operations interface\nexport interface TypedOperations {\n getSingleResourceTyped<T>(model: string, id: string, singlePageData?: boolean): Promise<TypedDocumentStructure<T>>;\n searchResourcesTyped<T>(model: string, filter?: Record<string, any>, aggregate?: boolean): Promise<TypedSearchResult<T>>;\n getRelationDocumentsTyped<T>(id: string, connection: Record<string, any>): Promise<TypedSearchResult<T>>;\n createNewResourceTyped<T>(request: CreateAndUpdateRequest): Promise<TypedDocumentStructure<T>>;\n updateResourceTyped<T>(request: CreateAndUpdateRequest): Promise<TypedDocumentStructure<T>>;\n}\n\n// Error classes\nexport class ApitoError extends Error {\n constructor(\n message: string,\n public code?: string,\n public statusCode?: number,\n public details?: any\n ) {\n super(message);\n this.name = 'ApitoError';\n }\n}\n\nexport class GraphQLError extends ApitoError {\n constructor(\n message: string,\n public graphQLErrors: GraphQLError[],\n public response?: any\n ) {\n super(message, 'GRAPHQL_ERROR');\n this.name = 'GraphQLError';\n }\n\n get partialData(): any {\n return this.response?.data;\n }\n}\n\nexport class ValidationError extends ApitoError {\n constructor(message: string, public field?: string) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n","import {\n DefaultDocumentStructure,\n TypedDocumentStructure,\n TypedSearchResult,\n CreateAndUpdateRequest,\n} from './types';\nimport { ApitoClient } from './client';\n\n/**\n * Typed operations wrapper for the Apito SDK\n * Provides type-safe methods for working with typed data\n */\nexport class TypedOperations {\n constructor(private client: ApitoClient) {}\n\n private static toTypedDocument<T>(raw: DefaultDocumentStructure): TypedDocumentStructure<T> {\n const data = JSON.parse(JSON.stringify(raw.data)) as T;\n return {\n _key: raw._key,\n _id: raw._id,\n data,\n meta: raw.meta,\n id: raw.id,\n expire_at: raw.expire_at,\n relation_doc_id: raw.relation_doc_id,\n last_revision_doc_id: raw.last_revision_doc_id,\n type: raw.type,\n tenant_id: raw.tenant_id,\n tenant_model: raw.tenant_model,\n };\n }\n\n /**\n * Get a single resource with type safety\n */\n async getSingleResourceTyped<T>(\n model: string,\n id: string,\n singlePageData: boolean = false\n ): Promise<TypedDocumentStructure<T>> {\n const result = await this.client.getSingleResource(model, id, singlePageData);\n return TypedOperations.toTypedDocument<T>(result);\n }\n\n /**\n * Search resources with type safety\n */\n async searchResourcesTyped<T>(\n model: string,\n filter: Record<string, any> = {},\n aggregate: boolean = false\n ): Promise<TypedSearchResult<T>> {\n const result = await this.client.searchResources(model, filter, aggregate);\n return {\n results: result.results.map((doc) => TypedOperations.toTypedDocument<T>(doc)),\n count: result.count,\n };\n }\n\n /**\n * Get related documents with type safety\n */\n async getRelationDocumentsTyped<T>(\n id: string,\n connection: Record<string, any>\n ): Promise<TypedSearchResult<T>> {\n const result = await this.client.getRelationDocuments(id, connection);\n return {\n results: result.results.map((doc) => TypedOperations.toTypedDocument<T>(doc)),\n count: result.count,\n };\n }\n\n /**\n * Create a new resource with type safety\n */\n async createNewResourceTyped<T>(\n request: CreateAndUpdateRequest\n ): Promise<TypedDocumentStructure<T>> {\n const result = await this.client.createNewResource(request);\n return TypedOperations.toTypedDocument<T>(result);\n }\n\n /**\n * Update a resource with type safety\n */\n async updateResourceTyped<T>(\n request: CreateAndUpdateRequest\n ): Promise<TypedDocumentStructure<T>> {\n const result = await this.client.updateResource(request);\n return TypedOperations.toTypedDocument<T>(result);\n }\n}\n","/**\n * Apito JavaScript internal SDK version (kept in sync with package.json for releases)\n */\nexport const Version = '2.7.0';\n\n/**\n * GetVersion returns the current version of the SDK\n */\nexport function getVersion(): string {\n return Version;\n}\n"],"mappings":";AAAA,OAAOA,MAA8B,QC4N9B,IAAMC,EAAN,cAAyB,KAAM,CACpC,YACEC,EACOC,EACAC,EACAC,EACP,CACA,MAAMH,CAAO,EAJN,UAAAC,EACA,gBAAAC,EACA,aAAAC,EAGP,KAAK,KAAO,YACd,CACF,EAEaC,EAAN,cAA2BL,CAAW,CAC3C,YACEC,EACOK,EACAC,EACP,CACA,MAAMN,EAAS,eAAe,EAHvB,mBAAAK,EACA,cAAAC,EAGP,KAAK,KAAO,cACd,CAEA,IAAI,aAAmB,CACrB,OAAO,KAAK,UAAU,IACxB,CACF,EAEaC,EAAN,cAA8BR,CAAW,CAC9C,YAAYC,EAAwBQ,EAAgB,CAClD,MAAMR,EAAS,kBAAkB,EADC,WAAAQ,EAElC,KAAK,KAAO,iBACd,CACF,EDlOO,IAAMC,EAAN,KAA0D,CAM/D,YAAYC,EAAsB,CAChC,KAAK,QAAUA,EAAO,QACtB,KAAK,OAASA,EAAO,OACrB,KAAK,SAAWA,EAAO,SAGvB,KAAK,WAAaC,EAAM,OAAO,CAC7B,QAASD,EAAO,SAAW,IAC3B,QAAS,CACP,eAAgB,mBAChB,GAAI,KAAK,OAAO,WAAW,MAAM,GAAK,KAAK,OAAO,WAAW,MAAM,EAC/D,CAAE,mBAAoB,KAAK,MAAO,EAClC,CAAE,cAAe,KAAK,MAAO,CACnC,EACA,GAAGA,EAAO,UACZ,CAAC,EAGG,KAAK,WACP,KAAK,WAAW,SAAS,QAAQ,mBAAmB,EAAI,KAAK,SAEjE,C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AmBU,CAAG,CAAC,EAC5E,MAAOH,EAAO,KAChB,CACF,CAKA,MAAM,uBACJK,EACoC,CACpC,IAAML,EAAS,MAAM,KAAK,OAAO,kBAAkBK,CAAO,EAC1D,OAAOZ,EAAgB,gBAAmBO,CAAM,CAClD,CAKA,MAAM,oBACJK,EACoC,CACpC,IAAML,EAAS,MAAM,KAAK,OAAO,eAAeK,CAAO,EACvD,OAAOZ,EAAgB,gBAAmBO,CAAM,CAClD,CACF,ECzFO,IAAMM,EAAU,QAKhB,SAASC,GAAqB,CACjC,OAAOD,CACX","names":["axios","ApitoError","message","code","statusCode","details","GraphQLError","graphQLErrors","response","ValidationError","field","ApitoClient","config","axios","query","variables","options","payload","headers","response","GraphQLError","error","ApitoError","tenantId","duration","role","dur","d","data","ValidationError","params","authMethod","code","state","password","email","phone","raw","projectId","limit","offset","count","domain","u","userId","uid","ok","model","id","singlePageData","filter","aggregate","connection","request","stage","createClient","TypedOperations","_TypedOperations","client","raw","data","model","id","singlePageData","result","filter","aggregate","doc","connection","request","Version","getVersion"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/types.ts","../src/typed-operations.ts","../src/version.ts"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\nimport {\n ClientConfig,\n DefaultDocumentStructure,\n SearchResult,\n TypedDocumentStructure,\n TypedSearchResult,\n CreateAndUpdateRequest,\n GraphQLResponse,\n GraphQLError as SDKGraphQLError,\n ApitoError,\n ValidationError,\n InjectedDBOperationInterface,\n LoginUserResponse,\n User,\n UsersResponse,\n TenantByDomainResponse,\n TenantCatalogSearchRow,\n LoginUserParams,\n CreateUserParams,\n UpdateUserParams,\n GoogleOAuthStateResponse,\n File,\n FilesListResponse,\n UploadFileParams,\n DeleteFilesResponse,\n} from './types';\n\nfunction deriveRestBaseURL(graphqlURL: string): string {\n const u = graphqlURL.trim().replace(/\\/$/, '');\n if (u.endsWith('/graphql')) {\n return u.slice(0, -'/graphql'.length);\n }\n return u;\n}\n\n/**\n * Apito SDK Client - JavaScript implementation matching the Go SDK\n */\nexport class ApitoClient implements InjectedDBOperationInterface {\n private httpClient: AxiosInstance;\n private baseURL: string;\n private restBaseURL: string;\n private apiKey: string;\n private tenantId?: string;\n\n constructor(config: ClientConfig) {\n this.baseURL = config.baseURL;\n this.restBaseURL = (config.restBaseURL ?? '').trim() || deriveRestBaseURL(config.baseURL);\n this.apiKey = config.apiKey;\n this.tenantId = config.tenantId;\n\n // Create axios instance with default configuration\n this.httpClient = axios.create({\n timeout: config.timeout || 30000,\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey.startsWith('cli-') || this.apiKey.startsWith('sdk-')\n ? { 'X-Apito-Sync-Key': this.apiKey }\n : { 'X-Apito-Key': this.apiKey }),\n },\n ...config.httpClient,\n });\n\n // Add tenant ID to headers if provided\n if (this.tenantId) {\n this.httpClient.defaults.headers['X-Apito-Tenant-ID'] = this.tenantId;\n }\n }\n\n /**\n * Execute an arbitrary GraphQL query or mutation against the Apito admin (system) endpoint.\n * Use for plugin-registered operations (e.g. processLedger, plg_closeOrder) when not wrapped by dedicated SDK methods.\n */\n async executeGraphQL(\n query: string,\n variables?: Record<string, any>,\n options?: { tenantId?: string }\n ): Promise<GraphQLResponse> {\n try {\n const payload = {\n query,\n variables: variables || {},\n };\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(this.apiKey.startsWith('cli-') || this.apiKey.startsWith('sdk-')\n ? { 'X-Apito-Sync-Key': this.apiKey }\n : { 'X-Apito-Key': this.apiKey }),\n };\n\n if (options?.tenantId || this.tenantId) {\n headers['X-Apito-Tenant-ID'] = options?.tenantId || this.tenantId!;\n }\n\n const response = await this.httpClient.post<GraphQLResponse>(\n this.baseURL,\n payload,\n { headers }\n );\n\n if (response.data.errors && response.data.errors.length > 0) {\n throw new SDKGraphQLError(\n 'GraphQL query failed',\n response.data.errors,\n response.data\n );\n }\n\n return response.data;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n throw new ApitoError(\n error.response?.data?.message || error.message,\n 'HTTP_ERROR',\n error.response?.status,\n error.response?.data\n );\n }\n throw error;\n }\n }\n\n /**\n * Generate a tenant-scoped API key. Matches engine `generateTenantToken`: `tenant_id`, `duration`, optional `role`.\n * Auth uses `X-Apito-Key` (client `apiKey`).\n *\n * @param tenantId Catalog tenant id (`tenant_id` in the mutation).\n * @param duration Expiry calendar day `YYYY-MM-DD`. If omitted/empty, defaults to one year ahead in UTC.\n * @param role Optional token role; if omitted/empty, the engine defaults to `admin`.\n */\n async generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string> {\n let dur = (duration ?? '').trim();\n if (!dur) {\n const d = new Date();\n dur = `${d.getUTCFullYear() + 1}-${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(\n d.getUTCDate()\n ).padStart(2, '0')}`;\n }\n\n const query = `\n mutation GenerateTenantToken($tenantId: String!, $duration: String!, $role: String) {\n generateTenantToken(tenant_id: $tenantId, duration: $duration, role: $role) {\n token\n }\n }\n `;\n\n const variables: Record<string, any> = {\n tenantId,\n duration: dur,\n role: role !== undefined && role.trim() !== '' ? role.trim() : null,\n };\n const response = await this.executeGraphQL(query, variables, { tenantId });\n\n const data = response.data?.generateTenantToken;\n if (!data?.token) {\n throw new ValidationError('Invalid response format for tenant token');\n }\n\n return data.token;\n }\n\n private authHeaders(tenantId?: string): Record<string, string> {\n const headers: Record<string, string> = {\n ...(this.apiKey.startsWith('cli-') || this.apiKey.startsWith('sdk-')\n ? { 'X-Apito-Sync-Key': this.apiKey }\n : { 'X-Apito-Key': this.apiKey }),\n };\n const tid = tenantId ?? this.tenantId;\n if (tid) {\n headers['X-Apito-Tenant-ID'] = tid;\n }\n return headers;\n }\n\n private async executeREST<T>(\n method: 'GET' | 'POST',\n path: string,\n options?: {\n query?: Record<string, string | number | undefined>;\n jsonBody?: Record<string, unknown>;\n formData?: FormData;\n allowFailure?: boolean;\n }\n ): Promise<T> {\n const url = new URL(`${this.restBaseURL.replace(/\\/$/, '')}${path}`);\n if (options?.query) {\n for (const [k, v] of Object.entries(options.query)) {\n if (v !== undefined && v !== '') {\n url.searchParams.set(k, String(v));\n }\n }\n }\n const headers = this.authHeaders();\n let data: FormData | Record<string, unknown> | undefined;\n if (options?.formData) {\n data = options.formData;\n } else if (options?.jsonBody) {\n headers['Content-Type'] = 'application/json';\n data = options.jsonBody;\n }\n try {\n const response = await this.httpClient.request({\n method,\n url: url.toString(),\n headers,\n data,\n maxBodyLength: Infinity,\n maxContentLength: Infinity,\n });\n const body = response.data as Record<string, unknown>;\n if (body.success === false && !options?.allowFailure) {\n throw new ValidationError(String(body.message ?? 'request failed'));\n }\n return body as T;\n } catch (error) {\n if (axios.isAxiosError(error)) {\n const msg =\n (error.response?.data as { message?: string })?.message ?? error.message;\n throw new ApitoError(msg, 'HTTP_ERROR', error.response?.status, error.response?.data);\n }\n throw error;\n }\n }\n\n /**\n * Project user login (system GraphQL `loginUser`). Password path: pass `password` and `email` or `phone` per project Authentication settings. Google OAuth path: `authMethod: 'google'` with `code` and `state` from the redirect; call `googleOAuthState(projectId)` before opening Google to obtain `state`.\n */\n async loginUser(params: LoginUserParams): Promise<LoginUserResponse> {\n const authMethod = (params.authMethod ?? 'general').trim().toLowerCase() || 'general';\n const variables: Record<string, any> = {\n project_id: params.projectId,\n };\n\n if (authMethod === 'google') {\n variables.auth_method = 'google';\n const code = (params.code ?? '').trim();\n const state = (params.state ?? '').trim();\n if (!code || !state) {\n throw new ValidationError('code and state are required for Google login');\n }\n variables.code = code;\n variables.state = state;\n } else {\n const password = (params.password ?? '').trim();\n if (!password) {\n throw new ValidationError('password is required');\n }\n variables.password = password;\n const email = (params.email ?? '').trim();\n const phone = (params.phone ?? '').trim();\n if (!email && !phone) {\n throw new ValidationError('email or phone is required');\n }\n if (email) variables.email = email;\n if (phone) variables.phone = phone;\n }\n\n const query = `\n query LoginUser($project_id: String!, $password: String, $auth_method: String, $email: String, $phone: String, $code: String, $state: String) {\n loginUser(project_id: $project_id, password: $password, auth_method: $auth_method, email: $email, phone: $phone, code: $code, state: $state) {\n token\n user {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n }\n `;\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.loginUser;\n if (!raw?.token) {\n throw new ValidationError('Invalid response format for loginUser');\n }\n return {\n token: raw.token as string,\n user: raw.user as User | undefined,\n };\n }\n\n /**\n * Signed OAuth state for Google login (system query `googleOAuthState`). Use in the authorize URL together with project `google_client_id` and the configured redirect URI.\n */\n async googleOAuthState(projectId: string): Promise<GoogleOAuthStateResponse> {\n const query = `\n query GoogleOAuthState($project_id: String!) {\n googleOAuthState(project_id: $project_id) {\n state\n }\n }\n `;\n const variables = { project_id: projectId };\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.googleOAuthState;\n const state = typeof raw?.state === 'string' ? raw.state.trim() : '';\n if (!state) {\n throw new ValidationError('Invalid response format for googleOAuthState');\n }\n return { state };\n }\n\n /**\n * Search project end-users.\n */\n async searchUsers(\n projectId: string,\n limit?: number,\n offset?: number\n ): Promise<UsersResponse> {\n const query = `\n query SearchUsers($project_id: String!, $limit: Int, $offset: Int) {\n searchUsers(project_id: $project_id, limit: $limit, offset: $offset) {\n count\n users {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n }\n `;\n const variables: Record<string, any> = { project_id: projectId };\n if (limit !== undefined) variables.limit = limit;\n if (offset !== undefined) variables.offset = offset;\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.searchUsers;\n if (!raw) {\n throw new ValidationError('Invalid response format for searchUsers');\n }\n let count = 0;\n if (typeof raw.count === 'number') {\n count = raw.count;\n }\n const users = (raw.users ?? []) as User[];\n return { users, count };\n }\n\n /**\n * Resolve the single SaaS catalog tenant for an exact domain match in the project (`tenant` null if none).\n */\n async searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse> {\n const query = `\n query SearchTenantsByDomain($project_id: String!, $domain: String!) {\n searchTenantsByDomain(project_id: $project_id, domain: $domain) {\n tenant {\n id\n name\n status\n domain\n data\n }\n }\n }\n `;\n const variables: Record<string, any> = {\n project_id: projectId,\n domain,\n };\n const response = await this.executeGraphQL(query, variables);\n const raw = response.data?.searchTenantsByDomain;\n if (!raw) {\n throw new ValidationError('Invalid response format for searchTenantsByDomain');\n }\n const tenant = (raw.tenant ?? null) as TenantCatalogSearchRow | null;\n return { tenant };\n }\n\n /**\n * Create a project user (local password). Use `email` and/or `phone` per engine validation for the project identifier mode.\n */\n async createUser(projectId: string, params: CreateUserParams): Promise<User> {\n const password = (params.password ?? '').trim();\n if (!password) {\n throw new ValidationError('password is required');\n }\n const query = `\n mutation CreateUser($project_id: String!, $password: String!, $role: String, $email: String, $phone: String) {\n createUser(project_id: $project_id, password: $password, role: $role, email: $email, phone: $phone) {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n `;\n const variables: Record<string, any> = {\n project_id: projectId,\n password,\n };\n const role = (params.role ?? '').trim();\n if (role) variables.role = role;\n const email = (params.email ?? '').trim();\n if (email) variables.email = email;\n const phone = (params.phone ?? '').trim();\n if (phone) variables.phone = phone;\n const response = await this.executeGraphQL(query, variables);\n const u = response.data?.createUser;\n if (!u?.id) {\n throw new ValidationError('Invalid response format for createUser');\n }\n return u as User;\n }\n\n /**\n * Update a project user. Project scope is implied by the API key. Only include fields to change.\n */\n async updateUser(userId: string, params: UpdateUserParams): Promise<User> {\n const uid = (userId ?? '').trim();\n if (!uid) {\n throw new ValidationError('userId is required');\n }\n if (params.email === undefined && params.phone === undefined && params.role === undefined) {\n throw new ValidationError('at least one field must be provided');\n }\n const query = `\n mutation UpdateUser($user_id: String!, $email: String, $phone: String, $role: String) {\n updateUser(user_id: $user_id, email: $email, phone: $phone, role: $role) {\n id\n email\n phone\n role\n provider\n tenant_id\n status\n created_at\n updated_at\n }\n }\n `;\n const variables: Record<string, any> = { user_id: uid };\n if (params.email !== undefined) variables.email = params.email;\n if (params.phone !== undefined) variables.phone = params.phone;\n if (params.role !== undefined) variables.role = params.role;\n const response = await this.executeGraphQL(query, variables);\n const u = response.data?.updateUser;\n if (!u?.id) {\n throw new ValidationError('Invalid response format for updateUser');\n }\n return u as User;\n }\n\n /** Set a new password for a project user (admin mutation resetUserPassword). */\n async resetUserPassword(userId: string, password: string): Promise<boolean> {\n const uid = (userId ?? '').trim();\n if (!uid) {\n throw new ValidationError('userId is required');\n }\n if (!(password ?? '').trim()) {\n throw new ValidationError('password is required');\n }\n const query = `\n mutation ResetUserPassword($user_id: String!, $password: String!) {\n resetUserPassword(user_id: $user_id, password: $password)\n }\n `;\n const response = await this.executeGraphQL(query, { user_id: uid, password });\n const ok = response.data?.resetUserPassword;\n if (typeof ok !== 'boolean') {\n throw new ValidationError('Invalid response format for resetUserPassword');\n }\n return ok;\n }\n\n /**\n * Delete a project user by id. Project scope is implied by the API key.\n */\n async deleteUser(userId: string): Promise<boolean> {\n const uid = (userId ?? '').trim();\n if (!uid) {\n throw new ValidationError('userId is required');\n }\n const query = `\n mutation DeleteUser($user_id: String!) {\n deleteUser(user_id: $user_id)\n }\n `;\n const response = await this.executeGraphQL(query, { user_id: uid });\n const ok = response.data?.deleteUser;\n if (typeof ok !== 'boolean') {\n throw new ValidationError('Invalid response format for deleteUser');\n }\n return ok;\n }\n\n /** Upload a file via POST /system/files/upload. */\n async uploadFile(params: UploadFileParams): Promise<File> {\n const size =\n params.content instanceof ArrayBuffer\n ? params.content.byteLength\n : params.content.byteLength;\n if (!params.content || size === 0) {\n throw new ValidationError('file content is required');\n }\n const fileName = (params.fileName ?? '').trim() || 'upload';\n const form = new FormData();\n const bytes =\n params.content instanceof ArrayBuffer ? new Uint8Array(params.content) : params.content;\n const blob = new Blob([bytes as BlobPart]);\n form.append('file', blob, fileName);\n if (params.fileType?.trim()) {\n form.append('file_type', params.fileType.trim());\n }\n const body = await this.executeREST<{ file: File }>('POST', '/files/upload', {\n formData: form,\n });\n if (!body.file?.id) {\n throw new ValidationError('Invalid response format for uploadFile');\n }\n return body.file;\n }\n\n /** List files via GET /system/files/list. */\n async listFiles(\n fileType?: string,\n limit?: number,\n offset?: number\n ): Promise<FilesListResponse> {\n const body = await this.executeREST<{\n files: File[];\n total: number;\n }>('GET', '/files/list', {\n query: {\n file_type: fileType,\n limit,\n offset,\n },\n });\n return {\n files: body.files ?? [],\n total: body.total ?? 0,\n };\n }\n\n /** Delete files via POST /system/files/delete. */\n async deleteFiles(ids: string[]): Promise<DeleteFilesResponse> {\n if (!ids?.length) {\n throw new ValidationError('ids are required');\n }\n const body = await this.executeREST<DeleteFilesResponse>('POST', '/files/delete', {\n jsonBody: { ids },\n allowFailure: true,\n });\n const result: DeleteFilesResponse = {\n success: !!body.success,\n deleted_ids: body.deleted_ids ?? [],\n storage_failed: body.storage_failed,\n message: body.message,\n };\n if (!result.success && result.message) {\n throw new ValidationError(result.message);\n }\n return result;\n }\n\n /**\n * Get a single resource by model and ID\n */\n async getSingleResource(\n model: string,\n id: string,\n singlePageData: boolean = false\n ): Promise<DefaultDocumentStructure> {\n const query = `\n query GetSingleData($model: String, $_id: String!, $single_page_data: Boolean) {\n getSingleData(model: $model, _id: $_id, single_page_data: $single_page_data) {\n _key\n data\n meta {\n created_at\n updated_at\n status\n revision\n revision_at\n }\n id\n expire_at\n relation_doc_id\n type\n }\n }\n `;\n\n const variables = {\n model,\n _id: id,\n single_page_data: singlePageData,\n };\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.getSingleData) {\n throw new ValidationError('Resource not found');\n }\n\n return response.data.getSingleData;\n }\n\n /**\n * Search resources in a model\n */\n async searchResources(\n model: string,\n filter: Record<string, any> = {},\n aggregate: boolean = false\n ): Promise<SearchResult> {\n const query = `\n query GetModelData(\n $model: String!\n $page: Int\n $limit: Int\n $_key: JSON\n $where: JSON\n $search: String\n ) {\n getModelData(\n model: $model\n page: $page\n limit: $limit\n _key: $_key\n where: $where\n search: $search\n ) {\n results {\n id\n relation_doc_id\n data\n type\n expire_at\n meta {\n created_at\n updated_at\n status\n root_revision_id\n }\n }\n count\n }\n }\n `;\n\n // Only forward keys declared on the GraphQL operation (matches go-internal-sdk)\n const variables: Record<string, any> = { model };\n if (filter && typeof filter === 'object') {\n if (filter._key !== undefined) {\n variables._key = filter._key;\n }\n if (filter.page !== undefined) {\n variables.page = filter.page;\n }\n if (filter.limit !== undefined) {\n variables.limit = filter.limit;\n }\n if (filter.where !== undefined) {\n variables.where = filter.where;\n }\n if (filter.search !== undefined) {\n variables.search = filter.search;\n }\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.getModelData) {\n throw new ValidationError('Invalid search response format');\n }\n\n return response.data.getModelData;\n }\n\n /**\n * Get related documents\n */\n async getRelationDocuments(\n id: string,\n connection: Record<string, any>\n ): Promise<SearchResult> {\n const query = `\n query GetModelData($model: String!, $page: Int, $limit: Int, $where: JSON, $search: String, $connection : ListAllDataDetailedOfAModelConnectionPayload) {\n getModelData(model: $model, page: $page, limit: $limit, where: $where, search: $search, connection: $connection) {\n results {\n id\n relation_doc_id\n data\n type\n expire_at\n meta {\n created_at\n updated_at\n status\n root_revision_id\n }\n }\n count\n }\n }\n `;\n\n const variables: Record<string, any> = {\n connection,\n };\n\n // Extract model from connection if available\n if (connection.model) {\n variables.model = connection.model;\n } else {\n throw new ValidationError('model is required in connection parameters');\n }\n\n // Add filter parameters if provided in connection\n if (connection.filter) {\n const filter = connection.filter;\n if (filter.page !== undefined) {\n variables.page = filter.page;\n }\n if (filter.limit !== undefined) {\n variables.limit = filter.limit;\n }\n if (filter.where !== undefined) {\n variables.where = filter.where;\n }\n if (filter.search !== undefined) {\n variables.search = filter.search;\n }\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.getModelData) {\n throw new ValidationError('Invalid relation documents response format');\n }\n\n return response.data.getModelData;\n }\n\n /**\n * Create a new resource\n */\n async createNewResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure> {\n if (!request.model) {\n throw new ValidationError('model is required');\n }\n\n if (!request.payload) {\n throw new ValidationError('payload is required');\n }\n\n const query = `\n mutation CreateNewData($model: String!, $single_page_data: Boolean, $payload: JSON!, $connect: JSON) {\n upsertModelData(\n connect: $connect\n model_name: $model\n single_page_data: $single_page_data\n payload: $payload\n ) {\n id\n type\n data\n meta {\n created_at\n updated_at\n status\n revision\n revision_at\n }\n }\n }\n `;\n\n const variables: Record<string, any> = {\n model: request.model,\n payload: request.payload,\n single_page_data: request.singlePageData || false,\n };\n\n if (request.connect) {\n variables.connect = request.connect;\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.upsertModelData) {\n throw new ValidationError('Invalid create response format');\n }\n\n return response.data.upsertModelData;\n }\n\n /**\n * Update an existing resource\n */\n async updateResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure> {\n if (!request.id) {\n throw new ValidationError('id is required');\n }\n\n if (!request.model) {\n throw new ValidationError('model is required');\n }\n\n if (!request.payload) {\n throw new ValidationError('payload is required');\n }\n\n const query = `\n mutation UpdateModelData($_id: String!, $model: String!, $single_page_data: Boolean, $force_update: Boolean, $payload: JSON!, $connect: JSON, $disconnect: JSON) {\n upsertModelData(\n connect: $connect\n model_name: $model\n single_page_data: $single_page_data\n force_update: $force_update\n disconnect: $disconnect\n _id: $_id\n payload: $payload\n ) {\n id\n type\n data\n meta {\n created_at\n updated_at\n status\n revision\n revision_at\n }\n }\n }\n `;\n\n const variables: Record<string, any> = {\n _id: request.id,\n model: request.model,\n payload: request.payload,\n single_page_data: request.singlePageData || false,\n force_update: request.forceUpdate || false,\n };\n\n if (request.connect) {\n variables.connect = request.connect;\n }\n if (request.disconnect) {\n variables.disconnect = request.disconnect;\n }\n\n const response = await this.executeGraphQL(query, variables);\n\n if (!response.data?.upsertModelData) {\n throw new ValidationError('Invalid update response format');\n }\n\n return response.data.upsertModelData;\n }\n\n /**\n * Delete a resource by model and ID\n */\n async deleteResource(model: string, id: string): Promise<void> {\n const query = `\n mutation DeleteData($model: String!, $_id: String!) {\n deleteModelData(model_name: $model, _id: $_id) {\n id\n }\n }\n `;\n\n const variables = {\n model,\n _id: id,\n };\n\n await this.executeGraphQL(query, variables);\n }\n\n /**\n * Debug is used to debug the plugin, you can pass data here to debug the plugin\n */\n async debug(stage: string, ...data: any[]): Promise<any> {\n const query = `\n mutation Debug($stage: String!, $data: JSON) {\n debug(stage: $stage, data: $data) {\n message\n data\n }\n }\n `;\n\n const variables = {\n stage,\n data,\n };\n\n const response = await this.executeGraphQL(query, variables);\n\n return response.data?.debug;\n }\n}\n\n/**\n * Factory function to create a new Apito client\n */\nexport function createClient(config: ClientConfig): ApitoClient {\n return new ApitoClient(config);\n}\n","/**\n * Type definitions for the Apito JavaScript SDK\n */\n\nexport interface MetaField {\n created_at: string;\n updated_at: string;\n status: string;\n revision?: string;\n revision_at?: string;\n root_revision_id?: string;\n}\n\nexport interface DefaultDocumentStructure {\n _key?: string;\n _id?: string;\n data: any;\n meta?: MetaField;\n id: string;\n expire_at?: string | number;\n relation_doc_id?: string;\n last_revision_doc_id?: string;\n type?: string;\n tenant_id?: string;\n tenant_model?: string;\n}\n\nexport interface SearchResult {\n results: DefaultDocumentStructure[];\n count: number;\n}\n\nexport interface TypedDocumentStructure<T> {\n _key?: string;\n _id?: string;\n data: T;\n meta?: MetaField;\n id: string;\n expire_at?: string | number;\n relation_doc_id?: string;\n last_revision_doc_id?: string;\n type?: string;\n tenant_id?: string;\n tenant_model?: string;\n}\n\nexport interface TypedSearchResult<T> {\n results: TypedDocumentStructure<T>[];\n count: number;\n}\n\nexport interface Filter {\n page?: number;\n offset?: number;\n limit?: number;\n order?: string;\n min?: number;\n max?: number;\n category?: string;\n}\n\nexport interface GraphQLErrorLocation {\n line: number;\n column: number;\n}\n\nexport interface GraphQLError {\n message: string;\n locations?: GraphQLErrorLocation[];\n path?: (string | number)[];\n extensions?: Record<string, any>;\n}\n\nexport interface GraphQLResponse {\n data?: any;\n errors?: GraphQLError[];\n}\n\nexport interface CreateAndUpdateRequest {\n id?: string;\n model: string;\n payload: any;\n connect?: Record<string, any>;\n disconnect?: Record<string, any>;\n singlePageData?: boolean;\n forceUpdate?: boolean;\n}\n\n/** Project end-user from engine system DB (table project_users). */\nexport interface User {\n id: string;\n email?: string;\n phone?: string;\n role: string;\n tenant_id?: string;\n provider?: string;\n status?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Login via system GraphQL `loginUser`. Password path: use `email` or `phone` per project settings. Google OAuth code path: `authMethod: 'google'`, `code`, `state` from redirect (get `state` first via `googleOAuthState`). */\nexport interface LoginUserParams {\n projectId: string;\n password?: string;\n email?: string;\n phone?: string;\n authMethod?: string;\n code?: string;\n state?: string;\n}\n\nexport interface GoogleOAuthStateResponse {\n state: string;\n}\n\nexport interface CreateUserParams {\n password: string;\n role?: string;\n email?: string;\n phone?: string;\n}\n\n/** Optional fields for `updateUser`; omitted keys are not sent. */\nexport interface UpdateUserParams {\n email?: string;\n phone?: string;\n role?: string;\n}\n\nexport interface LoginUserResponse {\n token: string;\n user?: User;\n}\n\nexport interface UsersResponse {\n users: User[];\n count: number;\n}\n\nexport interface File {\n id: string;\n file_type: string;\n file_name: string;\n file_extension?: string;\n content_type?: string;\n size: number;\n url: string;\n created_by?: string;\n created_at?: string;\n}\n\nexport interface FilesListResponse {\n files: File[];\n total: number;\n}\n\nexport interface UploadFileParams {\n fileName: string;\n content: Uint8Array | ArrayBuffer;\n fileType?: string;\n}\n\nexport interface DeleteFilesResponse {\n success: boolean;\n deleted_ids: string[];\n storage_failed?: string[];\n message?: string;\n}\n\n/** One SaaS catalog tenant row from searchTenantsByDomain. */\nexport interface TenantCatalogSearchRow {\n id: string;\n name: string;\n status?: string;\n domain?: string;\n data?: string;\n}\n\nexport interface TenantByDomainResponse {\n tenant: TenantCatalogSearchRow | null;\n}\n\nexport interface ClientConfig {\n baseURL: string;\n /** REST base (e.g. http://host:5050/system); derived from baseURL when omitted */\n restBaseURL?: string;\n apiKey: string;\n timeout?: number;\n httpClient?: any;\n tenantId?: string;\n}\n\nexport interface RequestOptions {\n headers?: Record<string, string>;\n timeout?: number;\n}\n\nexport interface SearchOptions {\n limit?: number;\n page?: number;\n offset?: number;\n where?: Record<string, any>;\n search?: string;\n sort?: Record<string, 1 | -1>;\n}\n\nexport interface ConnectionOptions {\n model: string;\n filter?: SearchOptions;\n}\n\n// Plugin interface matching the Go SDK\nexport interface InjectedDBOperationInterface {\n executeGraphQL(\n query: string,\n variables?: Record<string, any>,\n options?: { tenantId?: string }\n ): Promise<GraphQLResponse>;\n /** @param token Legacy; ignored. Auth uses client API key. */\n generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string>;\n loginUser(params: LoginUserParams): Promise<LoginUserResponse>;\n googleOAuthState(projectId: string): Promise<GoogleOAuthStateResponse>;\n searchUsers(projectId: string, limit?: number, offset?: number): Promise<UsersResponse>;\n searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse>;\n createUser(projectId: string, params: CreateUserParams): Promise<User>;\n updateUser(userId: string, params: UpdateUserParams): Promise<User>;\n resetUserPassword(userId: string, password: string): Promise<boolean>;\n deleteUser(userId: string): Promise<boolean>;\n uploadFile(params: UploadFileParams): Promise<File>;\n listFiles(fileType?: string, limit?: number, offset?: number): Promise<FilesListResponse>;\n deleteFiles(ids: string[]): Promise<DeleteFilesResponse>;\n getSingleResource(model: string, id: string, singlePageData?: boolean): Promise<DefaultDocumentStructure>;\n searchResources(model: string, filter?: Record<string, any>, aggregate?: boolean): Promise<SearchResult>;\n getRelationDocuments(id: string, connection: Record<string, any>): Promise<SearchResult>;\n createNewResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure>;\n updateResource(request: CreateAndUpdateRequest): Promise<DefaultDocumentStructure>;\n deleteResource(model: string, id: string): Promise<void>;\n debug(stage: string, ...data: any[]): Promise<any>;\n}\n\n// Typed operations interface\nexport interface TypedOperations {\n getSingleResourceTyped<T>(model: string, id: string, singlePageData?: boolean): Promise<TypedDocumentStructure<T>>;\n searchResourcesTyped<T>(model: string, filter?: Record<string, any>, aggregate?: boolean): Promise<TypedSearchResult<T>>;\n getRelationDocumentsTyped<T>(id: string, connection: Record<string, any>): Promise<TypedSearchResult<T>>;\n createNewResourceTyped<T>(request: CreateAndUpdateRequest): Promise<TypedDocumentStructure<T>>;\n updateResourceTyped<T>(request: CreateAndUpdateRequest): Promise<TypedDocumentStructure<T>>;\n}\n\n// Error classes\nexport class ApitoError extends Error {\n constructor(\n message: string,\n public code?: string,\n public statusCode?: number,\n public details?: any\n ) {\n super(message);\n this.name = 'ApitoError';\n }\n}\n\nexport class GraphQLError extends ApitoError {\n constructor(\n message: string,\n public graphQLErrors: GraphQLError[],\n public response?: any\n ) {\n super(message, 'GRAPHQL_ERROR');\n this.name = 'GraphQLError';\n }\n\n get partialData(): any {\n return this.response?.data;\n }\n}\n\nexport class ValidationError extends ApitoError {\n constructor(message: string, public field?: string) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n","import {\n DefaultDocumentStructure,\n TypedDocumentStructure,\n TypedSearchResult,\n CreateAndUpdateRequest,\n} from './types';\nimport { ApitoClient } from './client';\n\n/**\n * Typed operations wrapper for the Apito SDK\n * Provides type-safe methods for working with typed data\n */\nexport class TypedOperations {\n constructor(private client: ApitoClient) {}\n\n private static toTypedDocument<T>(raw: DefaultDocumentStructure): TypedDocumentStructure<T> {\n const data = JSON.parse(JSON.stringify(raw.data)) as T;\n return {\n _key: raw._key,\n _id: raw._id,\n data,\n meta: raw.meta,\n id: raw.id,\n expire_at: raw.expire_at,\n relation_doc_id: raw.relation_doc_id,\n last_revision_doc_id: raw.last_revision_doc_id,\n type: raw.type,\n tenant_id: raw.tenant_id,\n tenant_model: raw.tenant_model,\n };\n }\n\n /**\n * Get a single resource with type safety\n */\n async getSingleResourceTyped<T>(\n model: string,\n id: string,\n singlePageData: boolean = false\n ): Promise<TypedDocumentStructure<T>> {\n const result = await this.client.getSingleResource(model, id, singlePageData);\n return TypedOperations.toTypedDocument<T>(result);\n }\n\n /**\n * Search resources with type safety\n */\n async searchResourcesTyped<T>(\n model: string,\n filter: Record<string, any> = {},\n aggregate: boolean = false\n ): Promise<TypedSearchResult<T>> {\n const result = await this.client.searchResources(model, filter, aggregate);\n return {\n results: result.results.map((doc) => TypedOperations.toTypedDocument<T>(doc)),\n count: result.count,\n };\n }\n\n /**\n * Get related documents with type safety\n */\n async getRelationDocumentsTyped<T>(\n id: string,\n connection: Record<string, any>\n ): Promise<TypedSearchResult<T>> {\n const result = await this.client.getRelationDocuments(id, connection);\n return {\n results: result.results.map((doc) => TypedOperations.toTypedDocument<T>(doc)),\n count: result.count,\n };\n }\n\n /**\n * Create a new resource with type safety\n */\n async createNewResourceTyped<T>(\n request: CreateAndUpdateRequest\n ): Promise<TypedDocumentStructure<T>> {\n const result = await this.client.createNewResource(request);\n return TypedOperations.toTypedDocument<T>(result);\n }\n\n /**\n * Update a resource with type safety\n */\n async updateResourceTyped<T>(\n request: CreateAndUpdateRequest\n ): Promise<TypedDocumentStructure<T>> {\n const result = await this.client.updateResource(request);\n return TypedOperations.toTypedDocument<T>(result);\n }\n}\n","/**\n * Apito JavaScript internal SDK version (kept in sync with package.json for releases)\n */\nexport const Version = '3.1.0';\n\n/**\n * GetVersion returns the current version of the SDK\n */\nexport function getVersion(): string {\n return Version;\n}\n"],"mappings":";AAAA,OAAOA,MAA8B,QC2P9B,IAAMC,EAAN,cAAyB,KAAM,CACpC,YACEC,EACOC,EACAC,EACAC,EACP,CACA,MAAMH,CAAO,EAJN,UAAAC,EACA,gBAAAC,EACA,aAAAC,EAGP,KAAK,KAAO,YACd,CACF,EAEaC,EAAN,cAA2BL,CAAW,CAC3C,YACEC,EACOK,EACAC,EACP,CACA,MAAMN,EAAS,eAAe,EAHvB,mBAAAK,EACA,cAAAC,EAGP,KAAK,KAAO,cACd,CAEA,IAAI,aAAmB,CACrB,OAAO,KAAK,UAAU,IACxB,CACF,EAEaC,EAAN,cAA8BR,CAAW,CAC9C,YAAYC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,EACoC,CACpC,IAAML,EAAS,MAAM,KAAK,OAAO,kBAAkBK,CAAO,EAC1D,OAAOZ,EAAgB,gBAAmBO,CAAM,CAClD,CAKA,MAAM,oBACJK,EACoC,CACpC,IAAML,EAAS,MAAM,KAAK,OAAO,eAAeK,CAAO,EACvD,OAAOZ,EAAgB,gBAAmBO,CAAM,CAClD,CACF,ECzFO,IAAMM,EAAU,QAKhB,SAASC,GAAqB,CACjC,OAAOD,CACX","names":["axios","ApitoError","message","code","statusCode","details","GraphQLError","graphQLErrors","response","ValidationError","field","deriveRestBaseURL","graphqlURL","u","ApitoClient","config","axios","query","variables","options","payload","headers","response","GraphQLError","error","ApitoError","tenantId","duration","role","dur","d","data","ValidationError","tid","method","path","url","k","v","body","msg","params","authMethod","code","state","password","email","phone","raw","projectId","limit","offset","count","domain","userId","uid","ok","size","fileName","form","bytes","blob","fileType","ids","result","model","id","singlePageData","filter","aggregate","connection","request","stage","createClient","TypedOperations","_TypedOperations","client","raw","data","model","id","singlePageData","result","filter","aggregate","doc","connection","request","Version","getVersion"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apito-io/js-admin-sdk",
3
- "version": "2.7.0",
3
+ "version": "3.1.0",
4
4
  "description": "Admin JavaScript SDK for Apito GraphQL API (mirrors go-internal-sdk)",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -39,8 +39,8 @@ interface Product {
39
39
  created_at: string;
40
40
  }
41
41
 
42
- // User interface for testing typed operations
43
- interface User {
42
+ // Sample document shape for typed operation tests (not engine User type)
43
+ interface ExampleProfileUser {
44
44
  email: string;
45
45
  first_name: string;
46
46
  last_name: string;
@@ -251,11 +251,11 @@ describe('ApitoClient', () => {
251
251
  }
252
252
  const client = getTestClient();
253
253
  try {
254
- const { count, users } = await client.searchTenantUsers(projectId, 10, 0);
254
+ const { count, users } = await client.searchUsers(projectId, 10, 0);
255
255
  expect(count).toBeGreaterThanOrEqual(0);
256
- console.log('✅ searchTenantUsers:', count, users?.length);
256
+ console.log('✅ searchUsers:', count, users?.length);
257
257
  } catch (error) {
258
- console.log('searchTenantUsers failed (may be expected):', error);
258
+ console.log('searchUsers failed (may be expected):', error);
259
259
  }
260
260
  }, 30000);
261
261
 
@@ -282,13 +282,13 @@ describe('ApitoClient', () => {
282
282
  const password = process.env.APITO_TENANT_PASSWORD;
283
283
  if (!projectId || !(email.trim() || phone.trim()) || !password) {
284
284
  console.log(
285
- 'loginTenantUser skipped — set APITO_PROJECT_ID, APITO_TENANT_PASSWORD, and APITO_TENANT_EMAIL and/or APITO_TENANT_PHONE'
285
+ 'loginUser skipped — set APITO_PROJECT_ID, APITO_TENANT_PASSWORD, and APITO_TENANT_EMAIL and/or APITO_TENANT_PHONE'
286
286
  );
287
287
  return;
288
288
  }
289
289
  const client = getTestClient();
290
290
  try {
291
- const login = await client.loginTenantUser({
291
+ const login = await client.loginUser({
292
292
  projectId,
293
293
  password,
294
294
  ...(email.trim() ? { email: email.trim() } : {}),
@@ -296,9 +296,9 @@ describe('ApitoClient', () => {
296
296
  });
297
297
  expect(login.token).toBeDefined();
298
298
  expect(login.token.length).toBeGreaterThan(0);
299
- console.log('✅ loginTenantUser token length:', login.token.length);
299
+ console.log('✅ loginUser token length:', login.token.length);
300
300
  } catch (error) {
301
- console.log('loginTenantUser failed (may be expected):', error);
301
+ console.log('loginUser failed (may be expected):', error);
302
302
  }
303
303
  }, 30000);
304
304
  });