@allanfsouza/aether-sdk 1.0.0 → 2.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/src/index.ts CHANGED
@@ -4,27 +4,32 @@ import { createHttpClient } from "./http-client.js";
4
4
  import { AuthModule } from "./auth.js";
5
5
  import { DatabaseModule } from "./database.js";
6
6
  import { StorageModule } from "./storage.js";
7
+ import { FunctionsModule } from "./functions.js";
7
8
 
8
- type ClientConfig = {
9
+ /**
10
+ * Configuração usada para criar o cliente principal da plataforma.
11
+ */
12
+ export type ClientConfig = {
9
13
  apiUrl: string;
10
14
  projectId: string;
11
15
  };
12
16
 
13
17
  /**
14
- * O cliente principal da Plataforma API.
15
- * Ponto de entrada para todos os módulos (Auth, DB, Storage).
18
+ * O cliente principal da Plataforma API (Aether).
19
+ * Ponto de entrada para todos os módulos (Auth, DB, Storage, Functions).
16
20
  */
17
21
  export class PlataformaClient {
18
- // Propriedades públicas (os "módulos")
22
+ // Módulos públicos disponíveis para o usuário do SDK
19
23
  public auth: AuthModule;
20
24
  public db: DatabaseModule;
21
25
  public storage: StorageModule;
26
+ public functions: FunctionsModule;
22
27
 
23
- // Propriedades de configuração
28
+ // Configurações imutáveis da instância
24
29
  public apiUrl: string;
25
30
  public projectId: string;
26
31
 
27
- // Propriedades internas
32
+ // Infra interna
28
33
  private http: AxiosInstance;
29
34
  private _token: string | null = null;
30
35
 
@@ -32,23 +37,26 @@ export class PlataformaClient {
32
37
  if (!config.apiUrl || !config.projectId) {
33
38
  throw new Error("apiUrl e projectId são obrigatórios.");
34
39
  }
35
- this.apiUrl = config.apiUrl.replace(/\/$/, ""); // Remove barra final
40
+
41
+ // Normaliza apiUrl removendo barra final, se houver
42
+ this.apiUrl = config.apiUrl.replace(/\/$/, "");
36
43
  this.projectId = config.projectId;
37
44
 
38
- // Inicializa o cliente HTTP (passando 'this', a própria instância)
45
+ // Inicializa o cliente HTTP (passando a própria instância)
39
46
  this.http = createHttpClient(this);
40
47
 
41
- // Inicializa os módulos
48
+ // Inicializa os módulos de alto nível
42
49
  this.auth = new AuthModule(this, this.http);
43
50
  this.db = new DatabaseModule(this, this.http);
44
51
  this.storage = new StorageModule(this, this.http);
52
+ this.functions = new FunctionsModule(this, this.http);
45
53
  }
46
54
 
47
55
  // --- Gerenciamento de Token ---
48
56
 
49
57
  /**
50
58
  * Armazena o token de autenticação em memória.
51
- * @param token O JWT (ou null para logout)
59
+ * Chamado automaticamente pelo AuthModule após login/registro.
52
60
  */
53
61
  setToken(token: string | null) {
54
62
  this._token = token;
@@ -56,9 +64,14 @@ export class PlataformaClient {
56
64
 
57
65
  /**
58
66
  * Recupera o token de autenticação atual.
59
- * @returns O JWT ou null
67
+ * Usado pelo http-client para injetar o header Authorization.
60
68
  */
61
69
  getToken(): string | null {
62
70
  return this._token;
63
71
  }
64
72
  }
73
+
74
+ // Re-exports convenientes para quem consome o SDK
75
+ export { AetherError } from "./errors.js";
76
+ export type { ListOptions } from "./database.js";
77
+
package/src/storage.ts CHANGED
@@ -1,12 +1,8 @@
1
1
  // src/storage.ts
2
2
  import type { AxiosInstance } from "axios";
3
3
  import type { PlataformaClient } from "./index.js";
4
- import axios from "axios"; // [A CORREÇÃO ESTÁ AQUI]
4
+ import axios from "axios";
5
5
 
6
- /**
7
- * Módulo de Storage
8
- * Lida com upload e download de arquivos.
9
- */
10
6
  export class StorageModule {
11
7
  private client: PlataformaClient;
12
8
  private http: AxiosInstance;
@@ -17,36 +13,68 @@ export class StorageModule {
17
13
  }
18
14
 
19
15
  /**
20
- * Faz o upload de um arquivo para o Storage do projeto.
21
- * Isso lida com o fluxo de "presign" (URL assinada) automaticamente.
22
- * @param file O objeto 'File' (do navegador) ou um Buffer (do Node.js)
23
- * @param fileName O nome do arquivo (ex: "imagem.png")
24
- * @param contentType O tipo (ex: "image/png")
25
- * @returns O objeto do arquivo criado no banco
16
+ * Faz o upload de um arquivo.
17
+ * @param file Arquivo (Browser: File, Node: Buffer)
18
+ * @param fileName Nome do arquivo (ex: 'foto.jpg')
19
+ * @param contentType MIME Type (ex: 'image/jpeg')
20
+ * @param folder (Opcional) Pasta de destino (ex: 'usuarios/123/')
26
21
  */
27
- async upload(file: File | Buffer, fileName: string, contentType: string) {
28
- const size = (file as File).size || (file as Buffer).length;
22
+ async upload(
23
+ file: File | Buffer | Blob,
24
+ fileName: string,
25
+ contentType: string,
26
+ folder?: string // [NOVO]
27
+ ) {
28
+ // Calcula tamanho de forma segura para Browser e Node
29
+ let size = 0;
30
+ if (typeof File !== "undefined" && file instanceof File) {
31
+ size = file.size;
32
+ } else if (typeof Blob !== "undefined" && file instanceof Blob) {
33
+ size = file.size;
34
+ } else if (file instanceof Buffer) {
35
+ // Node.js
36
+ size = file.length;
37
+ }
29
38
 
30
- // 1. Pedir a URL de upload para nossa API
39
+ // 1. Pedir URL assinada
31
40
  const { data: presignData } = await this.http.post("/storage/presign", {
32
- fileName: fileName,
33
- contentType: contentType,
34
- size: size,
41
+ fileName,
42
+ contentType,
43
+ size,
44
+ prefix: folder || "", // [NOVO] Envia o prefixo para o backend
35
45
  });
36
46
 
37
- // O 'presign' vem dentro de 'data'
38
47
  const presign = presignData.data;
39
- if (!presign?.url) {
40
- throw new Error("API não retornou uma URL de upload assinada.");
41
- }
48
+ if (!presign?.url) throw new Error("Falha ao obter URL de upload.");
42
49
 
43
- // 2. Enviar o arquivo diretamente para o Minio/S3 (sem auth)
44
- // Usamos o 'axios' global aqui, não o 'this.http' (que adicionaria auth)
50
+ // 2. Upload direto para S3
45
51
  await axios.put(presign.url, file, {
46
52
  headers: { "Content-Type": contentType },
47
53
  });
48
54
 
49
- // 3. Retorna os detalhes do objeto (downloadUrl, objectId, etc.)
50
- return presign;
55
+ return {
56
+ id: presign.objectId,
57
+ key: presign.key,
58
+ downloadUrl: presign.downloadUrl,
59
+ url: presign.downloadUrl, // Alias amigável
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Lista arquivos de uma pasta.
65
+ */
66
+ async list(folder = "") {
67
+ const { data } = await this.http.get("/storage/list", {
68
+ params: { projectId: this.client.projectId, prefix: folder },
69
+ });
70
+ return data.data; // Retorna { files: [], folders: [] }
71
+ }
72
+
73
+ /**
74
+ * Deleta um arquivo pelo ID.
75
+ */
76
+ async delete(fileId: string) {
77
+ await this.http.delete("/storage/delete", { data: { objectId: fileId } });
78
+ return true;
51
79
  }
52
80
  }
package/tsconfig.json CHANGED
@@ -1,14 +1,21 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "ES2020", // Moderno, mas compatível
4
- "module": "NodeNext", // Suporta tanto 'require' (CJS) quanto 'import' (ESM)
5
- "declaration": true, // [IMPORTANTE] Gera arquivos .d.ts (para autocompletar)
6
- "outDir": "./dist", // Onde o JavaScript compilado irá
7
- "rootDir": "./src", // Onde nosso código TypeScript está
8
- "strict": true, // Força boas práticas
3
+ "target": "ES2020",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "declaration": true,
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "strict": true,
9
10
  "skipLibCheck": true,
10
11
  "forceConsistentCasingInFileNames": true,
11
- "moduleResolution": "NodeNext"
12
+ // Adicionado DOM para reconhecer 'File', 'Blob' e 'WebSocket' nativos
13
+ "lib": [
14
+ "ES2020",
15
+ "DOM"
16
+ ]
12
17
  },
13
- "include": ["src"] // Só compila o que está na pasta 'src'
14
- }
18
+ "include": [
19
+ "src"
20
+ ]
21
+ }