@apito-io/js-admin-sdk 2.1.2 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -145,6 +145,44 @@ const relatedUsers = await client.getRelationDocuments('todo-123', {
145
145
  });
146
146
  ```
147
147
 
148
+ ### Pro: tenant catalog users (Apito Pro)
149
+
150
+ These calls use the same admin client and system GraphQL endpoint as the rest of the SDK. They mirror the Go SDK and require a **Pro** Apito engine. Pass `projectId`; each returned user includes `tenant_id`.
151
+
152
+ | Method | Description |
153
+ |--------|-------------|
154
+ | `searchTenantUsers(projectId, limit?, offset?)` | List users registered for a project (each row has `email`, `phone`, `tenant_id`). |
155
+ | `searchTenantsByDomain(projectId, domain)` | Exact domain lookup in project scope; returns `{ tenant }` (null if no match). |
156
+ | `createTenantUser(projectId, params)` | Create a local-password user; `params`: `{ password, role?, email?, phone? }` (engine validates required identifier per project). |
157
+ | `loginTenantUser(params)` | General: `{ projectId, password, email? or phone? }`. Google OAuth **code** flow: **`tenantGoogleOAuthState(projectId)`** then redirect; on callback **`loginTenantUser({ projectId, authMethod: 'google', code, state })`**. |
158
+ | `tenantGoogleOAuthState(projectId)` | Returns **`{ state }`** for the Google authorize URL (project must have client id, secret, redirect URI configured). |
159
+ | `updateTenantUser(userId, params)` | Mutate `email`, `phone`, `password`, and/or `role` (omit fields you do not want to send). |
160
+ | `deleteTenantUser(userId)` | Remove a tenant catalog user. |
161
+
162
+ On the engine system GraphQL API, `createTenant` accepts an optional `domain`; when set, the domain must be unused in the project (otherwise the mutation fails). `updateTenant` enforces the same when setting `domain` to a non-empty value. Call those mutations via `executeGraphQL` if needed.
163
+
164
+ ```javascript
165
+ const projectId = 'your-project-id';
166
+
167
+ const { users, count } = await client.searchTenantUsers(projectId, 50, 0);
168
+ console.log(
169
+ 'users:',
170
+ count,
171
+ users.map((u) => u.email || u.phone || u.id),
172
+ );
173
+
174
+ const login = await client.loginTenantUser({
175
+ projectId,
176
+ password: 'your-password',
177
+ email: 'user@example.com', // use phone: '+15551234567' when project is phone mode
178
+ });
179
+ if (login.token) {
180
+ console.log('tenant-scoped token:', login.token);
181
+ }
182
+ ```
183
+
184
+ Runnable sample: `examples/tenant_users` (set `APITO_BASE_URL`, `APITO_API_KEY`, `APITO_PROJECT_ID`).
185
+
148
186
  ### Typed Operations
149
187
 
150
188
  For type-safe operations, use the `TypedOperations` class:
@@ -302,7 +340,8 @@ const createdTodos = await Promise.all(
302
340
 
303
341
  This client mirrors the Go `go-internal-sdk` package and the `InternalSDKOperation` interface from `github.com/apito-io/types`.
304
342
 
305
- - **Tenant header:** In Go, set `context.WithValue(ctx, "tenant_id", id)` before calls. In JavaScript, set `tenantId` on `ClientConfig`, or rely on `generateTenantToken`, which sends `X-Apito-Tenant-ID` for that mutation.
343
+ - **Tenant header:** In Go, set `context.WithValue(ctx, "tenant_id", id)` before calls. In JavaScript, set `tenantId` on `ClientConfig`, or pass `{ tenantId }` to `executeGraphQL` options where relevant.
344
+ - **`generateTenantToken(tenantId, duration?, role?)`:** Matches engine `generateTenantToken` — `tenant_id`, `duration` (`YYYY-MM-DD`; omit for default one year ahead in UTC), optional `role` (omit for engine default `admin`). Sends `X-Apito-Tenant-ID` for the mutation. Auth uses the client `apiKey`.
306
345
  - **GraphQL errors:** The Go client returns `(response, err)` when the response includes `errors`. This SDK throws `GraphQLError` with `graphQLErrors` and the full payload on `response`; use `error.partialData` to read `data` when the server returns partial success.
307
346
  - **`searchResources` filter:** Only `_key`, `page`, `limit`, `where`, and `search` are forwarded. Extra keys are ignored so unknown GraphQL variables cannot break the request.
308
347
  - **`TypedOperations`:** `data` is deep-cloned via `JSON.parse(JSON.stringify(...))`, matching the Go SDK’s marshal/unmarshal approach for typed document `data`.
@@ -332,6 +371,14 @@ npm install
332
371
  npm start
333
372
  ```
334
373
 
374
+ Pro tenant-user listing (optional `APITO_TENANT_EMAIL` / `APITO_TENANT_PHONE` + `APITO_TENANT_PASSWORD` for login):
375
+
376
+ ```bash
377
+ cd examples/tenant_users
378
+ npm install
379
+ APITO_BASE_URL=http://localhost:5050/system/graphql APITO_API_KEY=... APITO_PROJECT_ID=... npm start
380
+ ```
381
+
335
382
  ## 📄 License
336
383
 
337
384
  This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
package/dist/index.d.mts CHANGED
@@ -69,6 +69,67 @@ interface CreateAndUpdateRequest {
69
69
  singlePageData?: boolean;
70
70
  forceUpdate?: boolean;
71
71
  }
72
+ /** Tenant catalog user from engine system DB (pro_tenant_users). */
73
+ interface TenantUser {
74
+ id: string;
75
+ email?: string;
76
+ phone?: string;
77
+ role: string;
78
+ tenant_id: string;
79
+ provider?: string;
80
+ status?: string;
81
+ created_at?: string;
82
+ updated_at?: string;
83
+ }
84
+ /** 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`). */
85
+ interface TenantLoginParams {
86
+ projectId: string;
87
+ /** Required for general (password) login. */
88
+ password?: string;
89
+ email?: string;
90
+ phone?: string;
91
+ /** `general` (default) or `google`. */
92
+ authMethod?: string;
93
+ /** Google authorization code (with `authMethod: 'google'`). */
94
+ code?: string;
95
+ /** OAuth state from `tenantGoogleOAuthState` or callback (with `authMethod: 'google'`). */
96
+ state?: string;
97
+ }
98
+ interface TenantGoogleOAuthStateResponse {
99
+ state: string;
100
+ }
101
+ interface CreateTenantUserParams {
102
+ password: string;
103
+ role?: string;
104
+ email?: string;
105
+ phone?: string;
106
+ }
107
+ /** Optional fields for `updateTenantUser`; omitted keys are not sent. */
108
+ interface UpdateTenantUserParams {
109
+ email?: string;
110
+ phone?: string;
111
+ password?: string;
112
+ role?: string;
113
+ }
114
+ interface TenantLoginResponse {
115
+ token: string;
116
+ user?: TenantUser;
117
+ }
118
+ interface TenantUsersResponse {
119
+ users: TenantUser[];
120
+ count: number;
121
+ }
122
+ /** One SaaS catalog tenant row from searchTenantsByDomain. */
123
+ interface TenantCatalogSearchRow {
124
+ id: string;
125
+ name: string;
126
+ status?: string;
127
+ domain?: string;
128
+ data?: string;
129
+ }
130
+ interface TenantByDomainResponse {
131
+ tenant: TenantCatalogSearchRow | null;
132
+ }
72
133
  interface ClientConfig {
73
134
  baseURL: string;
74
135
  apiKey: string;
@@ -97,7 +158,14 @@ interface InjectedDBOperationInterface {
97
158
  tenantId?: string;
98
159
  }): Promise<GraphQLResponse>;
99
160
  /** @param token Legacy; ignored. Auth uses client API key. */
100
- generateTenantToken(token: string, tenantId: string): Promise<string>;
161
+ generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string>;
162
+ loginTenantUser(params: TenantLoginParams): Promise<TenantLoginResponse>;
163
+ tenantGoogleOAuthState(projectId: string): Promise<TenantGoogleOAuthStateResponse>;
164
+ searchTenantUsers(projectId: string, limit?: number, offset?: number): Promise<TenantUsersResponse>;
165
+ searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse>;
166
+ createTenantUser(projectId: string, params: CreateTenantUserParams): Promise<TenantUser>;
167
+ updateTenantUser(userId: string, params: UpdateTenantUserParams): Promise<TenantUser>;
168
+ deleteTenantUser(userId: string): Promise<boolean>;
101
169
  getSingleResource(model: string, id: string, singlePageData?: boolean): Promise<DefaultDocumentStructure>;
102
170
  searchResources(model: string, filter?: Record<string, any>, aggregate?: boolean): Promise<SearchResult>;
103
171
  getRelationDocuments(id: string, connection: Record<string, any>): Promise<SearchResult>;
@@ -146,12 +214,44 @@ declare class ApitoClient implements InjectedDBOperationInterface {
146
214
  tenantId?: string;
147
215
  }): Promise<GraphQLResponse>;
148
216
  /**
149
- * Generate a tenant-scoped API key for {@link tenantId}.
217
+ * Generate a tenant-scoped API key. Matches engine `generateTenantToken`: `tenant_id`, `duration`, optional `role`.
218
+ * Auth uses `X-Apito-Key` (client `apiKey`).
150
219
  *
151
- * `token` is legacy and ignored; the engine authenticates via `X-Apito-Key` (client `apiKey`).
152
- * Expiry is sent as a calendar day `YYYY-MM-DD`; defaults to one year ahead in UTC (same default as Go admin/internal SDK).
220
+ * @param tenantId Catalog tenant id (`tenant_id` in the mutation).
221
+ * @param duration Expiry calendar day `YYYY-MM-DD`. If omitted/empty, defaults to one year ahead in UTC.
222
+ * @param role Optional token role; if omitted/empty, the engine defaults to `admin`.
223
+ */
224
+ generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string>;
225
+ /**
226
+ * 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`.
227
+ */
228
+ loginTenantUser(params: TenantLoginParams): Promise<TenantLoginResponse>;
229
+ /**
230
+ * 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.
231
+ */
232
+ tenantGoogleOAuthState(projectId: string): Promise<{
233
+ state: string;
234
+ }>;
235
+ /**
236
+ * Search tenant users for a project.
237
+ */
238
+ searchTenantUsers(projectId: string, limit?: number, offset?: number): Promise<TenantUsersResponse>;
239
+ /**
240
+ * Resolve the single SaaS catalog tenant for an exact domain match in the project (`tenant` null if none).
241
+ */
242
+ searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse>;
243
+ /**
244
+ * Create a tenant catalog user (local password). Use `email` and/or `phone` per engine validation for the project identifier mode.
245
+ */
246
+ createTenantUser(projectId: string, params: CreateTenantUserParams): Promise<TenantUser>;
247
+ /**
248
+ * Update a tenant catalog user. Project scope is implied by the API key. Only include fields to change.
249
+ */
250
+ updateTenantUser(userId: string, params: UpdateTenantUserParams): Promise<TenantUser>;
251
+ /**
252
+ * Delete a tenant catalog user by id. Project scope is implied by the API key.
153
253
  */
154
- generateTenantToken(token: string, tenantId: string): Promise<string>;
254
+ deleteTenantUser(userId: string): Promise<boolean>;
155
255
  /**
156
256
  * Get a single resource by model and ID
157
257
  */
@@ -219,10 +319,10 @@ declare class TypedOperations {
219
319
  /**
220
320
  * Apito JavaScript internal SDK version (kept in sync with package.json for releases)
221
321
  */
222
- declare const Version = "2.1.1";
322
+ declare const Version = "2.7.0";
223
323
  /**
224
324
  * GetVersion returns the current version of the SDK
225
325
  */
226
326
  declare function getVersion(): string;
227
327
 
228
- export { ApitoClient, ApitoError, type ClientConfig, type ConnectionOptions, type CreateAndUpdateRequest, type DefaultDocumentStructure, type Filter, GraphQLError, type GraphQLErrorLocation, type GraphQLResponse, type InjectedDBOperationInterface, type MetaField, type RequestOptions, type SearchOptions, type SearchResult, type TypedDocumentStructure, TypedOperations, type TypedSearchResult, ValidationError, Version, createClient, ApitoClient as default, getVersion };
328
+ export { ApitoClient, ApitoError, type ClientConfig, type ConnectionOptions, type CreateAndUpdateRequest, type CreateTenantUserParams, type DefaultDocumentStructure, type Filter, GraphQLError, type GraphQLErrorLocation, type GraphQLResponse, type InjectedDBOperationInterface, type MetaField, type RequestOptions, type SearchOptions, type SearchResult, type TenantByDomainResponse, type TenantCatalogSearchRow, type TenantGoogleOAuthStateResponse, type TenantLoginParams, type TenantLoginResponse, type TenantUser, type TenantUsersResponse, type TypedDocumentStructure, TypedOperations, type TypedSearchResult, type UpdateTenantUserParams, ValidationError, Version, createClient, ApitoClient as default, getVersion };
package/dist/index.d.ts CHANGED
@@ -69,6 +69,67 @@ interface CreateAndUpdateRequest {
69
69
  singlePageData?: boolean;
70
70
  forceUpdate?: boolean;
71
71
  }
72
+ /** Tenant catalog user from engine system DB (pro_tenant_users). */
73
+ interface TenantUser {
74
+ id: string;
75
+ email?: string;
76
+ phone?: string;
77
+ role: string;
78
+ tenant_id: string;
79
+ provider?: string;
80
+ status?: string;
81
+ created_at?: string;
82
+ updated_at?: string;
83
+ }
84
+ /** 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`). */
85
+ interface TenantLoginParams {
86
+ projectId: string;
87
+ /** Required for general (password) login. */
88
+ password?: string;
89
+ email?: string;
90
+ phone?: string;
91
+ /** `general` (default) or `google`. */
92
+ authMethod?: string;
93
+ /** Google authorization code (with `authMethod: 'google'`). */
94
+ code?: string;
95
+ /** OAuth state from `tenantGoogleOAuthState` or callback (with `authMethod: 'google'`). */
96
+ state?: string;
97
+ }
98
+ interface TenantGoogleOAuthStateResponse {
99
+ state: string;
100
+ }
101
+ interface CreateTenantUserParams {
102
+ password: string;
103
+ role?: string;
104
+ email?: string;
105
+ phone?: string;
106
+ }
107
+ /** Optional fields for `updateTenantUser`; omitted keys are not sent. */
108
+ interface UpdateTenantUserParams {
109
+ email?: string;
110
+ phone?: string;
111
+ password?: string;
112
+ role?: string;
113
+ }
114
+ interface TenantLoginResponse {
115
+ token: string;
116
+ user?: TenantUser;
117
+ }
118
+ interface TenantUsersResponse {
119
+ users: TenantUser[];
120
+ count: number;
121
+ }
122
+ /** One SaaS catalog tenant row from searchTenantsByDomain. */
123
+ interface TenantCatalogSearchRow {
124
+ id: string;
125
+ name: string;
126
+ status?: string;
127
+ domain?: string;
128
+ data?: string;
129
+ }
130
+ interface TenantByDomainResponse {
131
+ tenant: TenantCatalogSearchRow | null;
132
+ }
72
133
  interface ClientConfig {
73
134
  baseURL: string;
74
135
  apiKey: string;
@@ -97,7 +158,14 @@ interface InjectedDBOperationInterface {
97
158
  tenantId?: string;
98
159
  }): Promise<GraphQLResponse>;
99
160
  /** @param token Legacy; ignored. Auth uses client API key. */
100
- generateTenantToken(token: string, tenantId: string): Promise<string>;
161
+ generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string>;
162
+ loginTenantUser(params: TenantLoginParams): Promise<TenantLoginResponse>;
163
+ tenantGoogleOAuthState(projectId: string): Promise<TenantGoogleOAuthStateResponse>;
164
+ searchTenantUsers(projectId: string, limit?: number, offset?: number): Promise<TenantUsersResponse>;
165
+ searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse>;
166
+ createTenantUser(projectId: string, params: CreateTenantUserParams): Promise<TenantUser>;
167
+ updateTenantUser(userId: string, params: UpdateTenantUserParams): Promise<TenantUser>;
168
+ deleteTenantUser(userId: string): Promise<boolean>;
101
169
  getSingleResource(model: string, id: string, singlePageData?: boolean): Promise<DefaultDocumentStructure>;
102
170
  searchResources(model: string, filter?: Record<string, any>, aggregate?: boolean): Promise<SearchResult>;
103
171
  getRelationDocuments(id: string, connection: Record<string, any>): Promise<SearchResult>;
@@ -146,12 +214,44 @@ declare class ApitoClient implements InjectedDBOperationInterface {
146
214
  tenantId?: string;
147
215
  }): Promise<GraphQLResponse>;
148
216
  /**
149
- * Generate a tenant-scoped API key for {@link tenantId}.
217
+ * Generate a tenant-scoped API key. Matches engine `generateTenantToken`: `tenant_id`, `duration`, optional `role`.
218
+ * Auth uses `X-Apito-Key` (client `apiKey`).
150
219
  *
151
- * `token` is legacy and ignored; the engine authenticates via `X-Apito-Key` (client `apiKey`).
152
- * Expiry is sent as a calendar day `YYYY-MM-DD`; defaults to one year ahead in UTC (same default as Go admin/internal SDK).
220
+ * @param tenantId Catalog tenant id (`tenant_id` in the mutation).
221
+ * @param duration Expiry calendar day `YYYY-MM-DD`. If omitted/empty, defaults to one year ahead in UTC.
222
+ * @param role Optional token role; if omitted/empty, the engine defaults to `admin`.
223
+ */
224
+ generateTenantToken(tenantId: string, duration?: string, role?: string): Promise<string>;
225
+ /**
226
+ * 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`.
227
+ */
228
+ loginTenantUser(params: TenantLoginParams): Promise<TenantLoginResponse>;
229
+ /**
230
+ * 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.
231
+ */
232
+ tenantGoogleOAuthState(projectId: string): Promise<{
233
+ state: string;
234
+ }>;
235
+ /**
236
+ * Search tenant users for a project.
237
+ */
238
+ searchTenantUsers(projectId: string, limit?: number, offset?: number): Promise<TenantUsersResponse>;
239
+ /**
240
+ * Resolve the single SaaS catalog tenant for an exact domain match in the project (`tenant` null if none).
241
+ */
242
+ searchTenantsByDomain(projectId: string, domain: string): Promise<TenantByDomainResponse>;
243
+ /**
244
+ * Create a tenant catalog user (local password). Use `email` and/or `phone` per engine validation for the project identifier mode.
245
+ */
246
+ createTenantUser(projectId: string, params: CreateTenantUserParams): Promise<TenantUser>;
247
+ /**
248
+ * Update a tenant catalog user. Project scope is implied by the API key. Only include fields to change.
249
+ */
250
+ updateTenantUser(userId: string, params: UpdateTenantUserParams): Promise<TenantUser>;
251
+ /**
252
+ * Delete a tenant catalog user by id. Project scope is implied by the API key.
153
253
  */
154
- generateTenantToken(token: string, tenantId: string): Promise<string>;
254
+ deleteTenantUser(userId: string): Promise<boolean>;
155
255
  /**
156
256
  * Get a single resource by model and ID
157
257
  */
@@ -219,10 +319,10 @@ declare class TypedOperations {
219
319
  /**
220
320
  * Apito JavaScript internal SDK version (kept in sync with package.json for releases)
221
321
  */
222
- declare const Version = "2.1.1";
322
+ declare const Version = "2.7.0";
223
323
  /**
224
324
  * GetVersion returns the current version of the SDK
225
325
  */
226
326
  declare function getVersion(): string;
227
327
 
228
- export { ApitoClient, ApitoError, type ClientConfig, type ConnectionOptions, type CreateAndUpdateRequest, type DefaultDocumentStructure, type Filter, GraphQLError, type GraphQLErrorLocation, type GraphQLResponse, type InjectedDBOperationInterface, type MetaField, type RequestOptions, type SearchOptions, type SearchResult, type TypedDocumentStructure, TypedOperations, type TypedSearchResult, ValidationError, Version, createClient, ApitoClient as default, getVersion };
328
+ export { ApitoClient, ApitoError, type ClientConfig, type ConnectionOptions, type CreateAndUpdateRequest, type CreateTenantUserParams, type DefaultDocumentStructure, type Filter, GraphQLError, type GraphQLErrorLocation, type GraphQLResponse, type InjectedDBOperationInterface, type MetaField, type RequestOptions, type SearchOptions, type SearchResult, type TenantByDomainResponse, type TenantCatalogSearchRow, type TenantGoogleOAuthStateResponse, type TenantLoginParams, type TenantLoginResponse, type TenantUser, type TenantUsersResponse, type TypedDocumentStructure, TypedOperations, type TypedSearchResult, type UpdateTenantUserParams, ValidationError, Version, createClient, ApitoClient as default, getVersion };
package/dist/index.js CHANGED
@@ -1,11 +1,95 @@
1
1
  // @apito-io/js-admin-sdk - Admin SDK for Apito GraphQL API
2
- var R=Object.create;var p=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var S=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var x=(n,e)=>{for(var t in e)p(n,t,{get:e[t],enumerable:!0})},h=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of T(e))!$.call(n,a)&&a!==t&&p(n,a,{get:()=>e[a],enumerable:!(r=D(e,a))||r.enumerable});return n};var b=(n,e,t)=>(t=n!=null?R(S(n)):{},h(e||!n||!n.__esModule?p(t,"default",{value:n,enumerable:!0}):t,n)),w=n=>h(p({},"__esModule",{value:!0}),n);var C={};x(C,{ApitoClient:()=>c,ApitoError:()=>d,GraphQLError:()=>u,TypedOperations:()=>l,ValidationError:()=>s,Version:()=>m,createClient:()=>_,default:()=>c,getVersion:()=>f});module.exports=w(C);var g=b(require("axios"));var d=class extends Error{constructor(t,r,a,o){super(t);this.code=r;this.statusCode=a;this.details=o;this.name="ApitoError"}},u=class extends d{constructor(t,r,a){super(t,"GRAPHQL_ERROR");this.graphQLErrors=r;this.response=a;this.name="GraphQLError"}get partialData(){return this.response?.data}},s=class extends d{constructor(t,r){super(t,"VALIDATION_ERROR");this.field=r;this.name="ValidationError"}};var c=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey,this.tenantId=e.tenantId,this.httpClient=g.default.create({timeout:e.timeout||3e4,headers:{"Content-Type":"application/json","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 a={query:e,variables:t||{}},o={"Content-Type":"application/json","X-Apito-Key":this.apiKey};(r?.tenantId||this.tenantId)&&(o["X-Apito-Tenant-ID"]=r?.tenantId||this.tenantId);let i=await this.httpClient.post(this.baseURL,a,{headers:o});if(i.data.errors&&i.data.errors.length>0)throw new u("GraphQL query failed",i.data.errors,i.data);return i.data}catch(a){throw g.default.isAxiosError(a)?new d(a.response?.data?.message||a.message,"HTTP_ERROR",a.response?.status,a.response?.data):a}}async generateTenantToken(e,t){let r=new Date,a=`${r.getUTCFullYear()+1}-${String(r.getUTCMonth()+1).padStart(2,"0")}-${String(r.getUTCDate()).padStart(2,"0")}`,o=`
3
- mutation GenerateTenantToken($tenantId: String!, $duration: String!) {
4
- generateTenantToken(tenant_id: $tenantId, duration: $duration) {
2
+ var S=Object.create;var m=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,x=Object.prototype.hasOwnProperty;var b=(i,e)=>{for(var t in e)m(i,t,{get:e[t],enumerable:!0})},_=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of D(e))!x.call(i,n)&&n!==t&&m(i,n,{get:()=>e[n],enumerable:!(r=$(e,n))||r.enumerable});return i};var P=(i,e,t)=>(t=i!=null?S(U(i)):{},_(e||!i||!i.__esModule?m(t,"default",{value:i,enumerable:!0}):t,i)),v=i=>_(m({},"__esModule",{value:!0}),i);var I={};b(I,{ApitoClient:()=>l,ApitoError:()=>u,GraphQLError:()=>g,TypedOperations:()=>h,ValidationError:()=>o,Version:()=>f,createClient:()=>R,default:()=>l,getVersion:()=>w});module.exports=v(I);var y=P(require("axios"));var u=class extends Error{constructor(t,r,n,a){super(t);this.code=r;this.statusCode=n;this.details=a;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}},o=class extends u{constructor(t,r){super(t,"VALIDATION_ERROR");this.field=r;this.name="ValidationError"}};var l=class{constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey,this.tenantId=e.tenantId,this.httpClient=y.default.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||{}},a={"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)&&(a["X-Apito-Tenant-ID"]=r?.tenantId||this.tenantId);let s=await this.httpClient.post(this.baseURL,n,{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(n){throw y.default.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 p=new Date;n=`${p.getUTCFullYear()+1}-${String(p.getUTCMonth()+1).padStart(2,"0")}-${String(p.getUTCDate()).padStart(2,"0")}`}let a=`
3
+ mutation GenerateTenantToken($tenantId: String!, $duration: String!, $role: String) {
4
+ generateTenantToken(tenant_id: $tenantId, duration: $duration, role: $role) {
5
5
  token
6
6
  }
7
7
  }
8
- `,i={tenantId:t,duration:a},y=(await this.executeGraphQL(o,i,{tenantId:t})).data?.generateTenantToken;if(!y?.token)throw new s("Invalid response format for tenant token");return y.token}async getSingleResource(e,t,r=!1){let a=`
8
+ `,s={tenantId:e,duration:n,role:r!==void 0&&r.trim()!==""?r.trim():null},c=(await this.executeGraphQL(a,s,{tenantId:e})).data?.generateTenantToken;if(!c?.token)throw new o("Invalid response format for tenant token");return c.token}async loginTenantUser(e){let t=(e.authMethod??"general").trim().toLowerCase()||"general",r={project_id:e.projectId};if(t==="google"){r.auth_method="google";let d=(e.code??"").trim(),c=(e.state??"").trim();if(!d||!c)throw new o("code and state are required for Google login");r.code=d,r.state=c}else{let d=(e.password??"").trim();if(!d)throw new o("password is required");r.password=d;let c=(e.email??"").trim(),p=(e.phone??"").trim();if(!c&&!p)throw new o("email or phone is required");c&&(r.email=c),p&&(r.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) {
11
+ token
12
+ user {
13
+ id
14
+ email
15
+ phone
16
+ role
17
+ provider
18
+ tenant_id
19
+ status
20
+ created_at
21
+ updated_at
22
+ }
23
+ }
24
+ }
25
+ `,r)).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) {
28
+ state
29
+ }
30
+ }
31
+ `,r={project_id:e},a=(await this.executeGraphQL(t,r)).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,r){let n=`
32
+ query SearchTenantUsers($project_id: String!, $limit: Int, $offset: Int) {
33
+ searchTenantUsers(project_id: $project_id, limit: $limit, offset: $offset) {
34
+ count
35
+ users {
36
+ id
37
+ email
38
+ phone
39
+ role
40
+ provider
41
+ tenant_id
42
+ status
43
+ created_at
44
+ updated_at
45
+ }
46
+ }
47
+ }
48
+ `,a={project_id:e};t!==void 0&&(a.limit=t),r!==void 0&&(a.offset=r);let d=(await this.executeGraphQL(n,a)).data?.searchTenantUsers;if(!d)throw new o("Invalid response format for searchTenantUsers");let c=0;return typeof d.count=="number"&&(c=d.count),{users:d.users??[],count:c}}async searchTenantsByDomain(e,t){let r=`
49
+ query SearchTenantsByDomain($project_id: String!, $domain: String!) {
50
+ searchTenantsByDomain(project_id: $project_id, domain: $domain) {
51
+ tenant {
52
+ id
53
+ name
54
+ status
55
+ domain
56
+ data
57
+ }
58
+ }
59
+ }
60
+ `,n={project_id:e,domain:t},s=(await this.executeGraphQL(r,n)).data?.searchTenantsByDomain;if(!s)throw new o("Invalid response format for searchTenantsByDomain");return{tenant:s.tenant??null}}async createTenantUser(e,t){let r=(t.password??"").trim();if(!r)throw new o("password is required");let n=`
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) {
63
+ id
64
+ email
65
+ phone
66
+ role
67
+ provider
68
+ tenant_id
69
+ status
70
+ created_at
71
+ updated_at
72
+ }
73
+ }
74
+ `,a={project_id:e,password:r},s=(t.role??"").trim();s&&(a.role=s);let d=(t.email??"").trim();d&&(a.email=d);let c=(t.phone??"").trim();c&&(a.phone=c);let T=(await this.executeGraphQL(n,a)).data?.createTenantUser;if(!T?.id)throw new o("Invalid response format for createTenantUser");return T}async updateTenantUser(e,t){let r=(e??"").trim();if(!r)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 n=`
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) {
77
+ id
78
+ email
79
+ phone
80
+ role
81
+ provider
82
+ tenant_id
83
+ status
84
+ created_at
85
+ updated_at
86
+ }
87
+ }
88
+ `,a={user_id:r};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 d=(await this.executeGraphQL(n,a)).data?.updateTenantUser;if(!d?.id)throw new o("Invalid response format for updateTenantUser");return d}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)
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,r=!1){let n=`
9
93
  query GetSingleData($model: String, $_id: String!, $single_page_data: Boolean) {
10
94
  getSingleData(model: $model, _id: $_id, single_page_data: $single_page_data) {
11
95
  _key
@@ -23,7 +107,7 @@ var R=Object.create;var p=Object.defineProperty;var D=Object.getOwnPropertyDescr
23
107
  type
24
108
  }
25
109
  }
26
- `,o={model:e,_id:t,single_page_data:r},i=await this.executeGraphQL(a,o);if(!i.data?.getSingleData)throw new s("Resource not found");return i.data.getSingleData}async searchResources(e,t={},r=!1){let a=`
110
+ `,a={model:e,_id:t,single_page_data:r},s=await this.executeGraphQL(n,a);if(!s.data?.getSingleData)throw new o("Resource not found");return s.data.getSingleData}async searchResources(e,t={},r=!1){let n=`
27
111
  query GetModelData(
28
112
  $model: String!
29
113
  $page: Int
@@ -56,7 +140,7 @@ var R=Object.create;var p=Object.defineProperty;var D=Object.getOwnPropertyDescr
56
140
  count
57
141
  }
58
142
  }
59
- `,o={model:e};t&&typeof t=="object"&&(t._key!==void 0&&(o._key=t._key),t.page!==void 0&&(o.page=t.page),t.limit!==void 0&&(o.limit=t.limit),t.where!==void 0&&(o.where=t.where),t.search!==void 0&&(o.search=t.search));let i=await this.executeGraphQL(a,o);if(!i.data?.getModelData)throw new s("Invalid search response format");return i.data.getModelData}async getRelationDocuments(e,t){let r=`
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(n,a);if(!s.data?.getModelData)throw new o("Invalid search response format");return s.data.getModelData}async getRelationDocuments(e,t){let r=`
60
144
  query GetModelData($model: String!, $page: Int, $limit: Int, $where: JSON, $search: String, $connection : ListAllDataDetailedOfAModelConnectionPayload) {
61
145
  getModelData(model: $model, page: $page, limit: $limit, where: $where, search: $search, connection: $connection) {
62
146
  results {
@@ -75,7 +159,7 @@ var R=Object.create;var p=Object.defineProperty;var D=Object.getOwnPropertyDescr
75
159
  count
76
160
  }
77
161
  }
78
- `,a={connection:t};if(t.model)a.model=t.model;else throw new s("model is required in connection parameters");if(t.filter){let i=t.filter;i.page!==void 0&&(a.page=i.page),i.limit!==void 0&&(a.limit=i.limit),i.where!==void 0&&(a.where=i.where),i.search!==void 0&&(a.search=i.search)}let o=await this.executeGraphQL(r,a);if(!o.data?.getModelData)throw new s("Invalid relation documents response format");return o.data.getModelData}async createNewResource(e){if(!e.model)throw new s("model is required");if(!e.payload)throw new s("payload is required");let t=`
162
+ `,n={connection:t};if(t.model)n.model=t.model;else throw new o("model is required in connection parameters");if(t.filter){let s=t.filter;s.page!==void 0&&(n.page=s.page),s.limit!==void 0&&(n.limit=s.limit),s.where!==void 0&&(n.where=s.where),s.search!==void 0&&(n.search=s.search)}let a=await this.executeGraphQL(r,n);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=`
79
163
  mutation CreateNewData($model: String!, $single_page_data: Boolean, $payload: JSON!, $connect: JSON) {
80
164
  upsertModelData(
81
165
  connect: $connect
@@ -95,7 +179,7 @@ var R=Object.create;var p=Object.defineProperty;var D=Object.getOwnPropertyDescr
95
179
  }
96
180
  }
97
181
  }
98
- `,r={model:e.model,payload:e.payload,single_page_data:e.singlePageData||!1};e.connect&&(r.connect=e.connect);let a=await this.executeGraphQL(t,r);if(!a.data?.upsertModelData)throw new s("Invalid create response format");return a.data.upsertModelData}async updateResource(e){if(!e.id)throw new s("id is required");if(!e.model)throw new s("model is required");if(!e.payload)throw new s("payload is required");let t=`
182
+ `,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 o("Invalid create response format");return n.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=`
99
183
  mutation UpdateModelData($_id: String!, $model: String!, $single_page_data: Boolean, $force_update: Boolean, $payload: JSON!, $connect: JSON, $disconnect: JSON) {
100
184
  upsertModelData(
101
185
  connect: $connect
@@ -118,18 +202,18 @@ var R=Object.create;var p=Object.defineProperty;var D=Object.getOwnPropertyDescr
118
202
  }
119
203
  }
120
204
  }
121
- `,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 a=await this.executeGraphQL(t,r);if(!a.data?.upsertModelData)throw new s("Invalid update response format");return a.data.upsertModelData}async deleteResource(e,t){let r=`
205
+ `,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 o("Invalid update response format");return n.data.upsertModelData}async deleteResource(e,t){let r=`
122
206
  mutation DeleteData($model: String!, $_id: String!) {
123
207
  deleteModelData(model_name: $model, _id: $_id) {
124
208
  id
125
209
  }
126
210
  }
127
- `,a={model:e,_id:t};await this.executeGraphQL(r,a)}async debug(e,...t){let r=`
211
+ `,n={model:e,_id:t};await this.executeGraphQL(r,n)}async debug(e,...t){let r=`
128
212
  mutation Debug($stage: String!, $data: JSON) {
129
213
  debug(stage: $stage, data: $data) {
130
214
  message
131
215
  data
132
216
  }
133
217
  }
134
- `,a={stage:e,data:t};return(await this.executeGraphQL(r,a)).data?.debug}};function _(n){return new c(n)}var l=class n{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 a=await this.client.getSingleResource(e,t,r);return n.toTypedDocument(a)}async searchResourcesTyped(e,t={},r=!1){let a=await this.client.searchResources(e,t,r);return{results:a.results.map(o=>n.toTypedDocument(o)),count:a.count}}async getRelationDocumentsTyped(e,t){let r=await this.client.getRelationDocuments(e,t);return{results:r.results.map(a=>n.toTypedDocument(a)),count:r.count}}async createNewResourceTyped(e){let t=await this.client.createNewResource(e);return n.toTypedDocument(t)}async updateResourceTyped(e){let t=await this.client.updateResource(e);return n.toTypedDocument(t)}};var m="2.1.1";function f(){return m}0&&(module.exports={ApitoClient,ApitoError,GraphQLError,TypedOperations,ValidationError,Version,createClient,getVersion});
218
+ `,n={stage:e,data:t};return(await this.executeGraphQL(r,n)).data?.debug}};function R(i){return new l(i)}var h=class i{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 i.toTypedDocument(n)}async searchResourcesTyped(e,t={},r=!1){let n=await this.client.searchResources(e,t,r);return{results:n.results.map(a=>i.toTypedDocument(a)),count:n.count}}async getRelationDocumentsTyped(e,t){let r=await this.client.getRelationDocuments(e,t);return{results:r.results.map(n=>i.toTypedDocument(n)),count:r.count}}async createNewResourceTyped(e){let t=await this.client.createNewResource(e);return i.toTypedDocument(t)}async updateResourceTyped(e){let t=await this.client.updateResource(e);return i.toTypedDocument(t)}};var f="2.7.0";function w(){return f}0&&(module.exports={ApitoClient,ApitoError,GraphQLError,TypedOperations,ValidationError,Version,createClient,getVersion});
135
219
  //# sourceMappingURL=index.js.map