@allanfsouza/aether-sdk 2.4.3 → 2.4.5

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/src/database.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  // src/database.ts
2
2
  import type { AxiosInstance } from "axios";
3
3
  import type { PlataformaClient } from "./index.js";
4
- import WebSocket from "ws";
4
+
5
+ // Ajuste para WebSocket funcionar no Browser (Vite) e Node
6
+ const WS = typeof window !== "undefined" ? window.WebSocket : (global as any).WebSocket || null;
5
7
 
6
8
  // Tipo para a mensagem que recebemos do WebSocket
7
9
  type WebSocketMessage<T = any> = {
@@ -10,7 +12,7 @@ type WebSocketMessage<T = any> = {
10
12
  data: T;
11
13
  };
12
14
 
13
- // [NOVO] Opções de Listagem Avançada
15
+ // Opções de Listagem Avançada
14
16
  export type ListOptions<T> = {
15
17
  filter?: Partial<T> | Record<string, any>; // Suporta operadores avançados
16
18
  sort?: {
@@ -35,89 +37,56 @@ export class QueryBuilder<T> {
35
37
  this.collectionRef = collectionRef;
36
38
  }
37
39
 
38
- /**
39
- * Adiciona um filtro de igualdade.
40
- */
41
40
  eq(column: keyof T & string, value: any): this {
42
41
  this.filter[column] = value;
43
42
  return this;
44
43
  }
45
44
 
46
- /**
47
- * Adiciona um filtro de desigualdade ($ne).
48
- */
49
45
  neq(column: keyof T & string, value: any): this {
50
46
  this.filter[column] = { ...this.filter[column], $ne: value };
51
47
  return this;
52
48
  }
53
49
 
54
- /**
55
- * Adiciona um filtro maior que ($gt).
56
- */
57
50
  gt(column: keyof T & string, value: number | string): this {
58
51
  this.filter[column] = { ...this.filter[column], $gt: value };
59
52
  return this;
60
53
  }
61
54
 
62
- /**
63
- * Adiciona um filtro maior ou igual ($gte).
64
- */
65
55
  gte(column: keyof T & string, value: number | string): this {
66
56
  this.filter[column] = { ...this.filter[column], $gte: value };
67
57
  return this;
68
58
  }
69
59
 
70
- /**
71
- * Adiciona um filtro menor que ($lt).
72
- */
73
60
  lt(column: keyof T & string, value: number | string): this {
74
61
  this.filter[column] = { ...this.filter[column], $lt: value };
75
62
  return this;
76
63
  }
77
64
 
78
- /**
79
- * Adiciona um filtro menor ou igual ($lte).
80
- */
81
65
  lte(column: keyof T & string, value: number | string): this {
82
66
  this.filter[column] = { ...this.filter[column], $lte: value };
83
67
  return this;
84
68
  }
85
69
 
86
- /**
87
- * Adiciona um filtro LIKE ($like).
88
- */
89
70
  like(column: keyof T & string, value: string): this {
90
71
  this.filter[column] = { ...this.filter[column], $like: value };
91
72
  return this;
92
73
  }
93
74
 
94
- /**
95
- * Define a ordenação.
96
- */
97
75
  order(column: keyof T & string, direction: "ASC" | "DESC" = "ASC"): this {
98
76
  this.sort = { field: column, order: direction };
99
77
  return this;
100
78
  }
101
79
 
102
- /**
103
- * Define o limite de registros.
104
- */
105
80
  limit(count: number): this {
106
81
  this.limitVal = count;
107
82
  return this;
108
83
  }
109
84
 
110
- /**
111
- * Define o deslocamento (paginação).
112
- */
113
85
  offset(count: number): this {
114
86
  this.offsetVal = count;
115
87
  return this;
116
88
  }
117
89
 
118
- /**
119
- * Executa a query e retorna os resultados.
120
- */
121
90
  async get(): Promise<T[]> {
122
91
  return this.collectionRef.list({
123
92
  filter: this.filter,
@@ -151,15 +120,65 @@ export class DatabaseModule {
151
120
  /**
152
121
  * Seleciona uma coleção de dados.
153
122
  * [PREMIUM] Suporta Generics <T> para tipagem forte.
154
- * * @example client.db.collection<Product>('products')
123
+ * @example client.db.collection<Product>('products')
155
124
  */
156
125
  collection<T = any>(collectionName: string) {
157
126
  return new CollectionReference<T>(this.client, this.http, collectionName);
158
127
  }
159
128
 
129
+ /**
130
+ * [NOVO] Método compatível com estilo 'Supabase/Drizzle'.
131
+ * É um alias para .collection() mas retorna interface compatível com o Showcase.
132
+ * @example client.db.from('posts').select('*')
133
+ */
134
+ from<T = any>(tableName: string) {
135
+ const ref = this.collection<T>(tableName);
136
+
137
+ return {
138
+ // Mapeia .select() para .list()
139
+ select: async (columns = "*") => {
140
+ try {
141
+ // Nota: O parametro 'columns' poderia ser enviado ao backend se suportado
142
+ const data = await ref.list();
143
+ return { data, error: null };
144
+ } catch (err: any) {
145
+ return { data: null, error: err.response?.data || err.message };
146
+ }
147
+ },
148
+
149
+ // Mapeia .insert() para .create()
150
+ insert: async (data: T) => {
151
+ try {
152
+ const res = await ref.create(data);
153
+ return { data: res, error: null };
154
+ } catch (err: any) {
155
+ return { data: null, error: err.response?.data || err.message };
156
+ }
157
+ },
158
+
159
+ // Mapeia .update() para .update() (Requer ID no payload ou logica extra)
160
+ update: async (data: Partial<T> & { id?: string }) => {
161
+ try {
162
+ if (!data.id) throw new Error("ID é obrigatório para update via .from()");
163
+ const { id, ...updates } = data;
164
+ const res = await ref.update(id, updates as any);
165
+ return { data: res, error: null };
166
+ } catch (err: any) {
167
+ return { data: null, error: err.response?.data || err.message };
168
+ }
169
+ },
170
+
171
+ // Mapeia .delete()
172
+ delete: async () => {
173
+ // O showcase não passou argumentos no delete, o que é perigoso.
174
+ // Aqui retornamos erro ou implementamos delete por query se suportado.
175
+ return { data: null, error: "Delete via .from() requer implementação de filtros" };
176
+ }
177
+ };
178
+ }
179
+
160
180
  /**
161
181
  * Executa múltiplas operações em uma única transação.
162
- * Se uma falhar, todas são revertidas.
163
182
  */
164
183
  async batch(operations: BatchOperation[]): Promise<any[]> {
165
184
  const { data } = await this.http.post("/db/batch", { operations });
@@ -169,7 +188,6 @@ export class DatabaseModule {
169
188
 
170
189
  /**
171
190
  * Referência a uma coleção específica.
172
- * O <T> define o formato dos dados (ex: interface User).
173
191
  */
174
192
  export class CollectionReference<T> {
175
193
  private client: PlataformaClient;
@@ -181,56 +199,41 @@ export class CollectionReference<T> {
181
199
  this.client = client;
182
200
  this.http = http;
183
201
  this.collectionName = name;
202
+
184
203
  // Ajusta protocolo para WS/WSS
185
204
  const protocol = client.apiUrl.startsWith("https") ? "wss" : "ws";
186
205
  this.wsUrl = client.apiUrl.replace(/^https?/, protocol);
187
206
  }
188
207
 
189
- /**
190
- * Inicia o QueryBuilder.
191
- * Atalho para .eq()
192
- */
208
+ // --- Atalhos de Query ---
209
+
193
210
  eq(column: keyof T & string, value: any): QueryBuilder<T> {
194
211
  return new QueryBuilder<T>(this).eq(column, value);
195
212
  }
196
213
 
197
- /**
198
- * Inicia o QueryBuilder.
199
- * Atalho para .gt()
200
- */
201
214
  gt(column: keyof T & string, value: number | string): QueryBuilder<T> {
202
215
  return new QueryBuilder<T>(this).gt(column, value);
203
216
  }
204
217
 
205
- // ... Outros atalhos podem ser adicionados conforme necessidade ...
206
-
207
- /**
208
- * Retorna uma nova instância do QueryBuilder.
209
- */
210
218
  query(): QueryBuilder<T> {
211
219
  return new QueryBuilder<T>(this);
212
220
  }
213
221
 
214
- /**
215
- * Lista documentos da coleção com filtros opcionais.
216
- * @param options Filtros e Ordenação
217
- */
222
+ // --- Operações CRUD ---
223
+
218
224
  async list(options?: ListOptions<T>): Promise<T[]> {
219
225
  const params: any = {};
220
226
 
221
- // Converte os objetos do SDK para strings que o Backend entende
222
227
  if (options?.filter) {
223
228
  params.filter = JSON.stringify(options.filter);
224
229
  }
225
230
 
226
231
  if (options?.sort) {
227
- // Backend espera formato array: ["campo", "DESC"]
228
232
  params.sort = JSON.stringify([options.sort.field, options.sort.order]);
229
233
  }
230
234
 
231
- // TODO: Backend precisa implementar limit/offset na rota GET
232
- // if (options?.limit) params.limit = options.limit;
233
- // if (options?.offset) params.offset = options.offset;
235
+ if (options?.limit) params.limit = options.limit;
236
+ if (options?.offset) params.offset = options.offset;
234
237
 
235
238
  const { data } = await this.http.get(`/db/${this.collectionName}`, {
236
239
  params,
@@ -238,18 +241,11 @@ export class CollectionReference<T> {
238
241
  return data.data;
239
242
  }
240
243
 
241
- /**
242
- * Busca um documento pelo ID.
243
- */
244
244
  async get(id: string): Promise<T> {
245
245
  const { data } = await this.http.get(`/db/${this.collectionName}/${id}`);
246
246
  return data.data;
247
247
  }
248
248
 
249
- /**
250
- * Cria um novo documento.
251
- * O Partial<T> permite criar sem passar campos gerados (como id, createdAt).
252
- */
253
249
  async create(newData: Partial<T>): Promise<T> {
254
250
  const { data } = await this.http.post(
255
251
  `/db/${this.collectionName}`,
@@ -258,9 +254,6 @@ export class CollectionReference<T> {
258
254
  return data.data;
259
255
  }
260
256
 
261
- /**
262
- * Atualiza um documento existente.
263
- */
264
257
  async update(id: string, updates: Partial<T>): Promise<T> {
265
258
  const { data } = await this.http.put(
266
259
  `/db/${this.collectionName}/${id}`,
@@ -269,21 +262,21 @@ export class CollectionReference<T> {
269
262
  return data.data;
270
263
  }
271
264
 
272
- /**
273
- * Deleta um documento.
274
- */
275
265
  async delete(id: string): Promise<boolean> {
276
266
  await this.http.delete(`/db/${this.collectionName}/${id}`);
277
267
  return true;
278
268
  }
279
269
 
280
- /**
281
- * Inscreve-se para mudanças em tempo real.
282
- * O callback recebe os dados já tipados como T.
283
- */
270
+ // --- Realtime ---
271
+
284
272
  subscribe(
285
273
  callback: (action: "create" | "update" | "delete", data: T) => void
286
274
  ) {
275
+ if (!WS) {
276
+ console.warn("[SDK] WebSocket não disponível neste ambiente.");
277
+ return () => { };
278
+ }
279
+
287
280
  const token = this.client.getToken();
288
281
  const projectId = this.client.projectId;
289
282
 
@@ -292,12 +285,15 @@ export class CollectionReference<T> {
292
285
  return () => { };
293
286
  }
294
287
 
288
+ // URL correta de subscribe
295
289
  const url = `${this.wsUrl}/v1/db/subscribe/${this.collectionName}?token=${token}&projectId=${projectId}`;
296
290
 
297
291
  let ws: WebSocket | null = null;
298
292
 
299
293
  try {
300
- ws = new WebSocket(url);
294
+ ws = new WS(url);
295
+
296
+ if (!ws) return () => { };
301
297
 
302
298
  ws.onopen = () => {
303
299
  // Conectado
@@ -315,9 +311,12 @@ export class CollectionReference<T> {
315
311
  }
316
312
  };
317
313
 
318
- // Mantém a conexão viva (Heartbeat)
314
+ // Heartbeat
319
315
  const pingInterval = setInterval(() => {
320
- if (ws?.readyState === WebSocket.OPEN) ws.send("ping");
316
+ // [CORREÇÃO] Adicionada verificação explicita 'ws &&' para evitar erro 'possibly null'
317
+ if (ws && ws.readyState === 1) { // 1 = OPEN
318
+ ws.send("ping");
319
+ }
321
320
  }, 30000);
322
321
 
323
322
  return () => {
@@ -329,4 +328,4 @@ export class CollectionReference<T> {
329
328
  return () => { };
330
329
  }
331
330
  }
332
- }
331
+ }
package/src/index.ts CHANGED
@@ -1,26 +1,50 @@
1
1
  // src/index.ts
2
2
  import type { AxiosInstance } from "axios";
3
3
  import { createHttpClient } from "./http-client.js";
4
- import { AuthModule, User } from "./auth.js"; // Importando User
4
+ import { AuthModule, User } from "./auth.js";
5
5
  import { DatabaseModule } from "./database.js";
6
6
  import { StorageModule } from "./storage.js";
7
7
  import { FunctionsModule } from "./functions.js";
8
8
  import { PushModule } from "./push.js";
9
9
 
10
+ // =============================================================================
11
+ // CONSTANTES DE STORAGE
12
+ // Chaves padronizadas para localStorage - evita conflito com outros SDKs
13
+ // =============================================================================
14
+ const STORAGE_KEYS = {
15
+ TOKEN: "aether_token",
16
+ REFRESH_TOKEN: "aether_refresh_token",
17
+ USER: "aether_user",
18
+ } as const;
19
+
10
20
  /**
11
21
  * Configuração usada para criar o cliente principal da plataforma.
12
22
  */
13
23
  export type ClientConfig = {
14
24
  // Suporte duplo para compatibilidade:
15
- // apiUrl (nome original) OU baseUrl (nome novo do App)
16
25
  apiUrl?: string;
17
26
  baseUrl?: string;
18
-
19
- // projectId (nome original) OU apiKey (nome novo do App)
20
27
  projectId?: string;
21
28
  apiKey?: string;
29
+
30
+ /**
31
+ * Habilita persistência automática de sessão no localStorage.
32
+ * Padrão: true em browsers, false em Node.js/SSR.
33
+ */
34
+ persistSession?: boolean;
22
35
  };
23
36
 
37
+ /**
38
+ * Verifica se estamos em ambiente browser com localStorage disponível.
39
+ * Necessário para evitar erros em SSR (Next.js, Nuxt, etc).
40
+ */
41
+ function isBrowser(): boolean {
42
+ return (
43
+ typeof window !== "undefined" &&
44
+ typeof window.localStorage !== "undefined"
45
+ );
46
+ }
47
+
24
48
  export class PlataformaClient {
25
49
  public auth: AuthModule;
26
50
  public db: DatabaseModule;
@@ -35,7 +59,9 @@ export class PlataformaClient {
35
59
  public projectId: string;
36
60
 
37
61
  public http: AxiosInstance;
62
+
38
63
  private _token: string | null = null;
64
+ private _persistSession: boolean;
39
65
 
40
66
  constructor(config: ClientConfig) {
41
67
  // Resolve URL (prioridade para baseUrl se existir, senão apiUrl)
@@ -49,6 +75,13 @@ export class PlataformaClient {
49
75
  this.apiUrl = url.replace(/\/+$/, "");
50
76
  this.projectId = project;
51
77
 
78
+ // Persistência habilitada por padrão apenas em browsers
79
+ this._persistSession = config.persistSession ?? isBrowser();
80
+
81
+ // Restaura sessão salva ANTES de criar o httpClient
82
+ // Isso garante que requisições iniciais já tenham o token
83
+ this._restoreSession();
84
+
52
85
  this.http = createHttpClient(this);
53
86
 
54
87
  // Inicializa módulos
@@ -62,18 +95,141 @@ export class PlataformaClient {
62
95
  this.database = this.db;
63
96
  }
64
97
 
65
- setToken(token: string | null) {
98
+ // ===========================================================================
99
+ // TOKEN DE ACESSO
100
+ // ===========================================================================
101
+
102
+ /**
103
+ * Define o token de acesso (JWT).
104
+ * Se persistSession estiver ativo, salva automaticamente no localStorage.
105
+ */
106
+ setToken(token: string | null): void {
66
107
  this._token = token;
108
+
109
+ if (this._persistSession && isBrowser()) {
110
+ if (token) {
111
+ localStorage.setItem(STORAGE_KEYS.TOKEN, token);
112
+ } else {
113
+ localStorage.removeItem(STORAGE_KEYS.TOKEN);
114
+ }
115
+ }
67
116
  }
68
117
 
118
+ /**
119
+ * Retorna o token de acesso atual.
120
+ */
69
121
  getToken(): string | null {
70
122
  return this._token;
71
123
  }
124
+
125
+ // ===========================================================================
126
+ // REFRESH TOKEN
127
+ // ===========================================================================
128
+
129
+ /**
130
+ * Salva o refresh token.
131
+ * Usado internamente pelo AuthModule após login.
132
+ */
133
+ setRefreshToken(token: string | null): void {
134
+ if (this._persistSession && isBrowser()) {
135
+ if (token) {
136
+ localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token);
137
+ } else {
138
+ localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
139
+ }
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Retorna o refresh token salvo no localStorage.
145
+ */
146
+ getRefreshToken(): string | null {
147
+ if (this._persistSession && isBrowser()) {
148
+ return localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);
149
+ }
150
+ return null;
151
+ }
152
+
153
+ // ===========================================================================
154
+ // DADOS DO USUÁRIO
155
+ // ===========================================================================
156
+
157
+ /**
158
+ * Salva dados do usuário logado no localStorage.
159
+ */
160
+ setUser(user: User | null): void {
161
+ if (this._persistSession && isBrowser()) {
162
+ if (user) {
163
+ localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(user));
164
+ } else {
165
+ localStorage.removeItem(STORAGE_KEYS.USER);
166
+ }
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Retorna dados do usuário salvo no localStorage.
172
+ */
173
+ getUser(): User | null {
174
+ if (this._persistSession && isBrowser()) {
175
+ const saved = localStorage.getItem(STORAGE_KEYS.USER);
176
+ if (saved) {
177
+ try {
178
+ return JSON.parse(saved) as User;
179
+ } catch {
180
+ // JSON corrompido - limpa
181
+ localStorage.removeItem(STORAGE_KEYS.USER);
182
+ return null;
183
+ }
184
+ }
185
+ }
186
+ return null;
187
+ }
188
+
189
+ // ===========================================================================
190
+ // GERENCIAMENTO DE SESSÃO
191
+ // ===========================================================================
192
+
193
+ /**
194
+ * Limpa toda a sessão (token, refresh, user).
195
+ * Chamado automaticamente no logout.
196
+ */
197
+ clearSession(): void {
198
+ this._token = null;
199
+
200
+ if (isBrowser()) {
201
+ localStorage.removeItem(STORAGE_KEYS.TOKEN);
202
+ localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
203
+ localStorage.removeItem(STORAGE_KEYS.USER);
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Verifica se existe uma sessão salva (token presente).
209
+ */
210
+ hasSession(): boolean {
211
+ return this._token !== null;
212
+ }
213
+
214
+ /**
215
+ * Restaura sessão do localStorage ao inicializar o client.
216
+ * Executado automaticamente no constructor.
217
+ */
218
+ private _restoreSession(): void {
219
+ if (!this._persistSession || !isBrowser()) {
220
+ return;
221
+ }
222
+
223
+ const savedToken = localStorage.getItem(STORAGE_KEYS.TOKEN);
224
+ if (savedToken) {
225
+ this._token = savedToken;
226
+ }
227
+ }
72
228
  }
73
229
 
74
230
  // ===== EXPORTS =====
75
231
  export { AetherError } from "./errors.js";
76
- export type { LoginResponse, Session, User } from "./auth.js"; // User exportado!
232
+ export type { LoginResponse, Session, User } from "./auth.js";
77
233
  export type { ListOptions } from "./database.js";
78
234
  export type {
79
235
  PushPlatform,