swiftbase-admin-sdk 1.0.0 → 1.0.2

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.d.cts CHANGED
@@ -163,6 +163,14 @@ interface User {
163
163
  approved?: boolean;
164
164
  attributes?: any;
165
165
  }
166
+ interface UserInput {
167
+ email: string;
168
+ password?: string;
169
+ projectId: string;
170
+ firstName?: string;
171
+ lastName?: string;
172
+ approved?: boolean;
173
+ }
166
174
 
167
175
  /**
168
176
  * Verify a service's access token
@@ -194,6 +202,7 @@ declare const deleteService: (id: string) => Promise<string>;
194
202
  declare const getUsers: (projectId: string) => Promise<User[]>;
195
203
  declare const assignRole: (userId: string, roleName: string) => Promise<User>;
196
204
  declare const unassignRole: (userId: string, roleName: string) => Promise<User>;
205
+ declare const createUser: (input: UserInput) => Promise<User>;
197
206
 
198
207
  interface Profile {
199
208
  id: string;
@@ -273,6 +282,7 @@ interface Configuration {
273
282
  brand_name: string;
274
283
  brand_logo_url?: string;
275
284
  primary_color: string;
285
+ redirect_uris?: string[];
276
286
  created_at: string;
277
287
  updated_at: string;
278
288
  }
@@ -306,7 +316,18 @@ declare class QueryBuilder implements PromiseLike<any> {
306
316
  }>;
307
317
  then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
308
318
  }
309
- declare function db(dbName: string): (tableName: string) => QueryBuilder;
319
+ interface TableDefinition {
320
+ dbname: string;
321
+ name: string;
322
+ ddl: string;
323
+ }
324
+ declare function db(dbName: string): {
325
+ (tableName: string): QueryBuilder;
326
+ initializeDatabase(tables: TableDefinition[]): Promise<void>;
327
+ executeSQL(sql: string): Promise<any>;
328
+ };
329
+
330
+ declare function search(indexId: string, query: string): Promise<any[]>;
310
331
 
311
332
  interface StorageOptions {
312
333
  bucket: string;
@@ -357,4 +378,31 @@ declare class Storage {
357
378
  deleteObject(key: string): Promise<void>;
358
379
  }
359
380
 
360
- export { type BucketInfo, type ChangePasswordInput, type Configuration, type ConfigurationInput, type User as IdentityUser, type ListObjectsResult, PaginatedResponse, type Profile, type ProfileInput, type Role, type RoleInput, type RoleUpdateInput, type S3Object, type Service, type ServiceInput, type ServiceUpdateInput, Storage, type StorageOptions, type User$1 as User, app, assignRole, changePassword, createRole, createService, db, deleteRole, deleteService, getAccessToken, getConfiguration, getProfile, getRoles, getServices, getUsers, initializeSdk, isLoggedIn, login, logout, setAccessToken, unassignRole, updateConfiguration, updateProfile, updateRole, updateService, updateUser, verifyServiceToken, verifyToken };
381
+ interface AIChatMessage {
382
+ role: "system" | "user" | "assistant";
383
+ content: string;
384
+ }
385
+ interface AIChatCompletionOptions {
386
+ model?: string;
387
+ messages: AIChatMessage[];
388
+ }
389
+ interface AIChatCompletionResponse {
390
+ choices: Array<{
391
+ message: {
392
+ role: string;
393
+ content: string;
394
+ };
395
+ }>;
396
+ }
397
+ /**
398
+ * Generate completion using the AI service.
399
+ */
400
+ declare const ai: {
401
+ chat: {
402
+ completions: {
403
+ create: (options: AIChatCompletionOptions) => Promise<AIChatCompletionResponse>;
404
+ };
405
+ };
406
+ };
407
+
408
+ export { type AIChatCompletionOptions, type AIChatCompletionResponse, type AIChatMessage, type BucketInfo, type ChangePasswordInput, type Configuration, type ConfigurationInput, type User as IdentityUser, type ListObjectsResult, PaginatedResponse, type Profile, type ProfileInput, type Role, type RoleInput, type RoleUpdateInput, type S3Object, type Service, type ServiceInput, type ServiceUpdateInput, Storage, type StorageOptions, type TableDefinition, type User$1 as User, type UserInput, ai, app, assignRole, changePassword, createRole, createService, createUser, db, deleteRole, deleteService, getAccessToken, getConfiguration, getProfile, getRoles, getServices, getUsers, initializeSdk, isLoggedIn, login, logout, search, setAccessToken, unassignRole, updateConfiguration, updateProfile, updateRole, updateService, updateUser, verifyServiceToken, verifyToken };
package/dist/index.d.ts CHANGED
@@ -163,6 +163,14 @@ interface User {
163
163
  approved?: boolean;
164
164
  attributes?: any;
165
165
  }
166
+ interface UserInput {
167
+ email: string;
168
+ password?: string;
169
+ projectId: string;
170
+ firstName?: string;
171
+ lastName?: string;
172
+ approved?: boolean;
173
+ }
166
174
 
167
175
  /**
168
176
  * Verify a service's access token
@@ -194,6 +202,7 @@ declare const deleteService: (id: string) => Promise<string>;
194
202
  declare const getUsers: (projectId: string) => Promise<User[]>;
195
203
  declare const assignRole: (userId: string, roleName: string) => Promise<User>;
196
204
  declare const unassignRole: (userId: string, roleName: string) => Promise<User>;
205
+ declare const createUser: (input: UserInput) => Promise<User>;
197
206
 
198
207
  interface Profile {
199
208
  id: string;
@@ -273,6 +282,7 @@ interface Configuration {
273
282
  brand_name: string;
274
283
  brand_logo_url?: string;
275
284
  primary_color: string;
285
+ redirect_uris?: string[];
276
286
  created_at: string;
277
287
  updated_at: string;
278
288
  }
@@ -306,7 +316,18 @@ declare class QueryBuilder implements PromiseLike<any> {
306
316
  }>;
307
317
  then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
308
318
  }
309
- declare function db(dbName: string): (tableName: string) => QueryBuilder;
319
+ interface TableDefinition {
320
+ dbname: string;
321
+ name: string;
322
+ ddl: string;
323
+ }
324
+ declare function db(dbName: string): {
325
+ (tableName: string): QueryBuilder;
326
+ initializeDatabase(tables: TableDefinition[]): Promise<void>;
327
+ executeSQL(sql: string): Promise<any>;
328
+ };
329
+
330
+ declare function search(indexId: string, query: string): Promise<any[]>;
310
331
 
311
332
  interface StorageOptions {
312
333
  bucket: string;
@@ -357,4 +378,31 @@ declare class Storage {
357
378
  deleteObject(key: string): Promise<void>;
358
379
  }
359
380
 
360
- export { type BucketInfo, type ChangePasswordInput, type Configuration, type ConfigurationInput, type User as IdentityUser, type ListObjectsResult, PaginatedResponse, type Profile, type ProfileInput, type Role, type RoleInput, type RoleUpdateInput, type S3Object, type Service, type ServiceInput, type ServiceUpdateInput, Storage, type StorageOptions, type User$1 as User, app, assignRole, changePassword, createRole, createService, db, deleteRole, deleteService, getAccessToken, getConfiguration, getProfile, getRoles, getServices, getUsers, initializeSdk, isLoggedIn, login, logout, setAccessToken, unassignRole, updateConfiguration, updateProfile, updateRole, updateService, updateUser, verifyServiceToken, verifyToken };
381
+ interface AIChatMessage {
382
+ role: "system" | "user" | "assistant";
383
+ content: string;
384
+ }
385
+ interface AIChatCompletionOptions {
386
+ model?: string;
387
+ messages: AIChatMessage[];
388
+ }
389
+ interface AIChatCompletionResponse {
390
+ choices: Array<{
391
+ message: {
392
+ role: string;
393
+ content: string;
394
+ };
395
+ }>;
396
+ }
397
+ /**
398
+ * Generate completion using the AI service.
399
+ */
400
+ declare const ai: {
401
+ chat: {
402
+ completions: {
403
+ create: (options: AIChatCompletionOptions) => Promise<AIChatCompletionResponse>;
404
+ };
405
+ };
406
+ };
407
+
408
+ export { type AIChatCompletionOptions, type AIChatCompletionResponse, type AIChatMessage, type BucketInfo, type ChangePasswordInput, type Configuration, type ConfigurationInput, type User as IdentityUser, type ListObjectsResult, PaginatedResponse, type Profile, type ProfileInput, type Role, type RoleInput, type RoleUpdateInput, type S3Object, type Service, type ServiceInput, type ServiceUpdateInput, Storage, type StorageOptions, type TableDefinition, type User$1 as User, type UserInput, ai, app, assignRole, changePassword, createRole, createService, createUser, db, deleteRole, deleteService, getAccessToken, getConfiguration, getProfile, getRoles, getServices, getUsers, initializeSdk, isLoggedIn, login, logout, search, setAccessToken, unassignRole, updateConfiguration, updateProfile, updateRole, updateService, updateUser, verifyServiceToken, verifyToken };
package/dist/index.js CHANGED
@@ -133,6 +133,9 @@ var init_token = __esm({
133
133
  * @returns {boolean} True if the API key is valid, false otherwise
134
134
  */
135
135
  isValid() {
136
+ if (__privateGet(this, _expiration) === 0) {
137
+ return true;
138
+ }
136
139
  return __privateGet(this, _expiration) > Date.now();
137
140
  }
138
141
  /**
@@ -221,7 +224,11 @@ var init_login = __esm({
221
224
  body.append("client_id", serviceId);
222
225
  body.append("client_secret", secretKey);
223
226
  body.append("scope", "openid profile email");
224
- const url = `${app.baseUrl}/oauth2/token`;
227
+ let base = app.baseUrl || "https://api.swiftbase.io";
228
+ if (!base.includes("localhost") && !base.includes("127.0.0.1")) {
229
+ base = base.replace("api.swiftbase", "identity.swiftbase");
230
+ }
231
+ const url = `${base}/oauth2/token`;
225
232
  const response = yield fetch(url, {
226
233
  method: "POST",
227
234
  headers: {
@@ -3807,19 +3814,6 @@ var TooManyRequests = class _TooManyRequests extends Error {
3807
3814
  Object.setPrototypeOf(this, _TooManyRequests.prototype);
3808
3815
  }
3809
3816
  };
3810
- var handleRequestError = (status) => {
3811
- if (status === 401) {
3812
- throw new Unauthorized("Unauthorized");
3813
- } else if (status === 403) {
3814
- throw new Forbidden("Forbidden");
3815
- } else if (status === 400) {
3816
- throw new BadRequest("Bad Request");
3817
- } else if (status === 429) {
3818
- throw new TooManyRequests("Too Many Requests");
3819
- } else {
3820
- throw new Error("Unexpected error");
3821
- }
3822
- };
3823
3817
  var _data, _meta;
3824
3818
  var PaginatedResponse = class {
3825
3819
  constructor(response) {
@@ -3874,7 +3868,17 @@ var makeRequest = (method, path, params, body) => __async(null, null, function*
3874
3868
  } else if (app.accessToken && app.accessToken.isValid()) {
3875
3869
  headers["Authorization"] = `Bearer ${app.accessToken.value()}`;
3876
3870
  }
3877
- let url = path.startsWith("http") ? path : `${app.baseUrl}${!path.startsWith("/") ? "/" : ""}${path}`;
3871
+ let base = app.baseUrl || "https://api.swiftbase.io";
3872
+ if (!base.includes("localhost") && !base.includes("127.0.0.1")) {
3873
+ if (path.includes("/db/") || path.includes("/database") || path.includes("/tables") || path.includes("/sql") || path.includes("/queries")) {
3874
+ base = base.replace("api.swiftbase", "database.swiftbase");
3875
+ } else if (path.includes("/oauth2") || path.includes("/login") || path.includes("/api/roles") || path.includes("/api/services") || path.includes("/api/users") || path.includes("/api/me")) {
3876
+ base = base.replace("api.swiftbase", "identity.swiftbase");
3877
+ } else {
3878
+ base = base.replace("api.swiftbase", "app.swiftbase");
3879
+ }
3880
+ }
3881
+ let url = path.startsWith("http") ? path : `${base}${!path.startsWith("/") ? "/" : ""}${path}`;
3878
3882
  if (params) {
3879
3883
  const query = new URLSearchParams();
3880
3884
  for (const [key, value] of Object.entries(params)) {
@@ -3895,7 +3899,30 @@ var makeRequest = (method, path, params, body) => __async(null, null, function*
3895
3899
  try {
3896
3900
  const response = yield fetch(url, options);
3897
3901
  if (!response.ok) {
3898
- handleRequestError(response.status);
3902
+ let message = "";
3903
+ try {
3904
+ const bodyText = yield response.text();
3905
+ try {
3906
+ const parsed = JSON.parse(bodyText);
3907
+ message = parsed.message || parsed.error || bodyText;
3908
+ } catch (e) {
3909
+ message = bodyText;
3910
+ }
3911
+ } catch (_) {
3912
+ }
3913
+ const errorMsg = message ? `HTTP ${response.status}: ${message}` : `HTTP error ${response.status}`;
3914
+ console.error(errorMsg);
3915
+ if (response.status === 401) {
3916
+ throw new Unauthorized(errorMsg);
3917
+ } else if (response.status === 403) {
3918
+ throw new Forbidden(errorMsg);
3919
+ } else if (response.status === 400) {
3920
+ throw new BadRequest(errorMsg);
3921
+ } else if (response.status === 429) {
3922
+ throw new TooManyRequests(errorMsg);
3923
+ } else {
3924
+ throw new Error(errorMsg);
3925
+ }
3899
3926
  }
3900
3927
  const data = yield response.json();
3901
3928
  if (data.data !== void 0 && data.meta !== void 0) {
@@ -3919,7 +3946,11 @@ var verifyToken = (token) => __async(null, null, function* () {
3919
3946
  const headers = {
3920
3947
  "Authorization": `Bearer ${token}`
3921
3948
  };
3922
- const response = yield fetch(`${app.baseUrl}/api/me`, { headers });
3949
+ let base = app.baseUrl || "https://api.swiftbase.io";
3950
+ if (!base.includes("localhost") && !base.includes("127.0.0.1")) {
3951
+ base = base.replace("api.swiftbase", "identity.swiftbase");
3952
+ }
3953
+ const response = yield fetch(`${base}/api/me`, { headers });
3923
3954
  if (!response.ok) {
3924
3955
  throw new Error(`Token verification failed: ${response.status}`);
3925
3956
  }
@@ -3929,7 +3960,11 @@ var verifyToken = (token) => __async(null, null, function* () {
3929
3960
  // src/auth/verifyservicetoken.ts
3930
3961
  init_app();
3931
3962
  var verifyServiceToken = (token, scope) => __async(null, null, function* () {
3932
- const url = `${app.baseUrl}/api/verify-service-token`;
3963
+ let base = app.baseUrl || "https://api.swiftbase.io";
3964
+ if (!base.includes("localhost") && !base.includes("127.0.0.1")) {
3965
+ base = base.replace("api.swiftbase", "identity.swiftbase");
3966
+ }
3967
+ const url = `${base}/api/verify-service-token`;
3933
3968
  const response = yield fetch(url, {
3934
3969
  method: "POST",
3935
3970
  headers: {
@@ -4000,6 +4035,9 @@ var unassignRole = (userId, roleName) => __async(null, null, function* () {
4000
4035
  const roles = (user.roles || []).filter((r) => r !== roleName);
4001
4036
  return yield makeRequest("put" /* PUT */, `/api/users/${userId}`, void 0, { roles });
4002
4037
  });
4038
+ var createUser = (input) => __async(null, null, function* () {
4039
+ return yield makeRequest("post" /* POST */, "/api/users", void 0, input);
4040
+ });
4003
4041
 
4004
4042
  // src/profile/getprofile.ts
4005
4043
  var getProfile = () => __async(null, null, function* () {
@@ -4047,7 +4085,7 @@ var _DatabaseSocketManager = class _DatabaseSocketManager {
4047
4085
  return _DatabaseSocketManager.instance;
4048
4086
  }
4049
4087
  isWebSocketAvailable() {
4050
- return this.socket !== null && (this.socket.readyState === 0 || this.socket.readyState === 1);
4088
+ return this.socket !== null && this.socket.readyState === 1;
4051
4089
  }
4052
4090
  getWebSocketUrl(baseUrl, token) {
4053
4091
  let wsUrl = baseUrl.replace(/^http/, "ws");
@@ -4308,14 +4346,6 @@ var QueryBuilder = class {
4308
4346
  }
4309
4347
  execute() {
4310
4348
  return __async(this, null, function* () {
4311
- const socketManager = DatabaseSocketManager.getInstance();
4312
- if (socketManager.isWebSocketAvailable()) {
4313
- try {
4314
- return yield socketManager.executeQuery(this.payload);
4315
- } catch (err) {
4316
- console.warn("[QueryBuilder] WebSocket execution failed, falling back to REST:", err);
4317
- }
4318
- }
4319
4349
  return yield makeRequest("post" /* POST */, "/api/db/query", void 0, this.payload);
4320
4350
  });
4321
4351
  }
@@ -4324,9 +4354,115 @@ var QueryBuilder = class {
4324
4354
  }
4325
4355
  };
4326
4356
  function db(dbName) {
4327
- return function(tableName) {
4357
+ const dbClient = function(tableName) {
4328
4358
  return new QueryBuilder(dbName, tableName);
4329
4359
  };
4360
+ dbClient.initializeDatabase = function(tables) {
4361
+ return __async(this, null, function* () {
4362
+ const projectId = app.projectId;
4363
+ let dbs = [];
4364
+ try {
4365
+ dbs = yield makeRequest("get" /* GET */, "/api/databases", { projectId });
4366
+ } catch (err) {
4367
+ console.error("[DatabaseInit] Failed to list databases:", err.message);
4368
+ throw err;
4369
+ }
4370
+ let myDb = dbs.find((d) => d.name === dbName);
4371
+ if (!myDb) {
4372
+ console.log(`[DatabaseInit] Database '${dbName}' not found. Creating...`);
4373
+ try {
4374
+ myDb = yield makeRequest("post" /* POST */, "/api/databases", void 0, {
4375
+ name: dbName,
4376
+ projectId,
4377
+ engine: "oltp",
4378
+ enableGraphQL: true
4379
+ });
4380
+ } catch (err) {
4381
+ console.error("[DatabaseInit] Failed to create database:", err.message);
4382
+ throw err;
4383
+ }
4384
+ }
4385
+ const databaseId = myDb.id;
4386
+ const schemaName = dbName.toLowerCase().replace(/[^a-z0-9_]/g, "_");
4387
+ let existingTables = [];
4388
+ try {
4389
+ existingTables = yield makeRequest("get" /* GET */, "/api/tables", { databaseId });
4390
+ } catch (err) {
4391
+ console.error("[DatabaseInit] Failed to list tables:", err.message);
4392
+ throw err;
4393
+ }
4394
+ for (const t of tables) {
4395
+ try {
4396
+ yield makeRequest("post" /* POST */, "/api/sql", void 0, {
4397
+ databaseId,
4398
+ sql: t.ddl
4399
+ });
4400
+ } catch (err) {
4401
+ console.error(`[DatabaseInit] Failed to execute DDL for table ${t.dbname}:`, err.message);
4402
+ throw err;
4403
+ }
4404
+ const metaExists = existingTables.some((meta) => meta.dbname === t.dbname);
4405
+ if (!metaExists) {
4406
+ try {
4407
+ yield makeRequest("post" /* POST */, "/api/tables", void 0, {
4408
+ databaseId,
4409
+ dbname: t.dbname,
4410
+ name: t.name,
4411
+ docName: t.dbname,
4412
+ rules: "true"
4413
+ });
4414
+ } catch (err) {
4415
+ console.error(`[DatabaseInit] Failed to register metadata for table ${t.dbname}:`, err.message);
4416
+ throw err;
4417
+ }
4418
+ }
4419
+ }
4420
+ });
4421
+ };
4422
+ dbClient.executeSQL = function(sql) {
4423
+ return __async(this, null, function* () {
4424
+ const projectId = app.projectId;
4425
+ let dbs = [];
4426
+ try {
4427
+ dbs = yield makeRequest("get" /* GET */, "/api/databases", { projectId });
4428
+ } catch (err) {
4429
+ console.error("[DatabaseSQL] Failed to list databases:", err.message);
4430
+ throw err;
4431
+ }
4432
+ const myDb = dbs.find((d) => d.name === dbName);
4433
+ if (!myDb) throw new Error(`Database ${dbName} not found`);
4434
+ return yield makeRequest("post" /* POST */, "/api/sql", void 0, {
4435
+ databaseId: myDb.id,
4436
+ sql
4437
+ });
4438
+ });
4439
+ };
4440
+ return dbClient;
4441
+ }
4442
+
4443
+ // src/database/search.ts
4444
+ init_app();
4445
+ function search(indexId, query) {
4446
+ return __async(this, null, function* () {
4447
+ if (!indexId || !query) {
4448
+ throw new Error("indexId and query are required to perform a search");
4449
+ }
4450
+ const baseUrl = app.baseUrl || "https://api.swiftbase.io";
4451
+ const token = app.accessToken || "";
4452
+ const res = yield fetch(`${baseUrl}/api/search/query`, {
4453
+ method: "POST",
4454
+ headers: {
4455
+ "Content-Type": "application/json",
4456
+ "Authorization": token ? `Bearer ${token}` : ""
4457
+ },
4458
+ body: JSON.stringify({ indexId, query })
4459
+ });
4460
+ if (!res.ok) {
4461
+ throw new Error("Failed to execute search query against Swiftbase indexes");
4462
+ }
4463
+ const data = yield res.json();
4464
+ return data || [];
4465
+ });
4330
4466
  }
4331
4467
 
4332
4468
  // src/storage/storage.ts
@@ -4654,14 +4790,30 @@ var Storage = class {
4654
4790
  });
4655
4791
  }
4656
4792
  };
4793
+
4794
+ // src/ai/index.ts
4795
+ var ai = {
4796
+ chat: {
4797
+ completions: {
4798
+ create: (options) => __async(null, null, function* () {
4799
+ return yield makeRequest("post" /* POST */, "/api/ai/chat/completions", void 0, {
4800
+ model: options.model || "gemini-3.5-flash",
4801
+ messages: options.messages
4802
+ });
4803
+ })
4804
+ }
4805
+ }
4806
+ };
4657
4807
  export {
4658
4808
  PaginatedResponse,
4659
4809
  Storage,
4810
+ ai,
4660
4811
  app,
4661
4812
  assignRole,
4662
4813
  changePassword,
4663
4814
  createRole,
4664
4815
  createService,
4816
+ createUser,
4665
4817
  db,
4666
4818
  deleteRole,
4667
4819
  deleteService,
@@ -4675,6 +4827,7 @@ export {
4675
4827
  isLoggedIn,
4676
4828
  login,
4677
4829
  logout,
4830
+ search,
4678
4831
  setAccessToken,
4679
4832
  unassignRole,
4680
4833
  updateConfiguration,