mitra-interactions-sdk 1.0.34 → 1.0.36

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
@@ -14,16 +14,17 @@ pnpm add mitra-interactions-sdk
14
14
 
15
15
  ## Configuração
16
16
 
17
- Antes de usar qualquer função, configure o SDK com seu token da plataforma Mitra.
17
+ Antes de usar qualquer função, configure o SDK. O `token` é **opcional** — Server Functions públicas podem ser chamadas sem autenticação.
18
18
 
19
- > **Importante:** O token é um JWT de autenticação da plataforma Mitra. **Nunca deixe o token estático no código.** Utilize variáveis de ambiente para armazená-lo de forma segura.
19
+ > **Importante:** Quando usado, o token é um JWT de autenticação da plataforma Mitra. **Nunca deixe o token estático no código.** Utilize variáveis de ambiente para armazená-lo de forma segura.
20
20
 
21
21
  ```typescript
22
22
  import { configureSdkMitra } from 'mitra-interactions-sdk';
23
23
 
24
+ // Configuração completa (com autenticação)
24
25
  const instance = configureSdkMitra({
25
26
  baseURL: process.env.MITRA_BASE_URL || 'https://api.mitra.com',
26
- token: process.env.MITRA_TOKEN!,
27
+ token: process.env.MITRA_TOKEN!, // Opcional — necessário apenas para endpoints autenticados
27
28
  authUrl: 'https://coder.mitralab.io/sdk-auth/', // Opcional — necessário para login e token refresh
28
29
  projectId: 123, // Opcional — se informado, torna projectId opcional em TODOS os métodos
29
30
  integrationURL: 'https://api0.mitraecp.com:1003', // Opcional — necessário para integrações
@@ -31,6 +32,13 @@ const instance = configureSdkMitra({
31
32
  localStorage.setItem('mitra_session', JSON.stringify(session));
32
33
  }
33
34
  });
35
+
36
+ // Configuração mínima (sem token — apenas para Server Functions públicas)
37
+ const instance = configureSdkMitra({
38
+ baseURL: 'https://api.mitra.com',
39
+ projectId: 123
40
+ });
41
+ await instance.executeServerFunction({ serverFunctionId: 42 }); // OK — sem token
34
42
  ```
35
43
 
36
44
  > **`projectId` global:** Se você passar `projectId` no `configureSdkMitra`, ele será usado como fallback em **todos** os métodos do SDK. Assim, não é necessário passar `projectId` em cada chamada individual — basta configurar uma vez.
@@ -144,6 +152,79 @@ configureSdkMitra({
144
152
  });
145
153
  ```
146
154
 
155
+ ### Login por Email (iframe silencioso)
156
+
157
+ Para quem precisa montar sua **própria tela de login** (sem popup/redirect), o SDK oferece funções que fazem a autenticação via iframe invisível. As credenciais são enviadas ao HTML de auth via `postMessage` — sem CORS, sem expor a API.
158
+
159
+ #### emailSignupMitra
160
+
161
+ Cria conta. Após sucesso, o usuário recebe um código de verificação por email.
162
+
163
+ ```typescript
164
+ import { emailSignupMitra } from 'mitra-interactions-sdk';
165
+
166
+ await emailSignupMitra({
167
+ name: 'João Silva',
168
+ email: 'joao@email.com',
169
+ password: 'minhasenha123'
170
+ });
171
+ // Não retorna token — o próximo passo é verificar o código
172
+ ```
173
+
174
+ #### emailVerifyCodeMitra
175
+
176
+ Verifica o código de 6 dígitos e faz login automático. Retorna `LoginResponse` e auto-configura o SDK.
177
+
178
+ ```typescript
179
+ import { emailVerifyCodeMitra } from 'mitra-interactions-sdk';
180
+
181
+ const session = await emailVerifyCodeMitra({
182
+ email: 'joao@email.com',
183
+ code: '123456',
184
+ password: 'minhasenha123' // Necessário para login automático após verificação
185
+ });
186
+ // session: { token, baseURL, integrationURL? }
187
+ ```
188
+
189
+ #### emailResendCodeMitra
190
+
191
+ Reenvia o código de verificação para o email.
192
+
193
+ ```typescript
194
+ import { emailResendCodeMitra } from 'mitra-interactions-sdk';
195
+
196
+ await emailResendCodeMitra({ email: 'joao@email.com' });
197
+ ```
198
+
199
+ #### emailLoginMitra
200
+
201
+ Login direto com email e senha. Retorna `LoginResponse` e auto-configura o SDK.
202
+
203
+ ```typescript
204
+ import { emailLoginMitra } from 'mitra-interactions-sdk';
205
+
206
+ const session = await emailLoginMitra({
207
+ email: 'joao@email.com',
208
+ password: 'minhasenha123'
209
+ });
210
+ // session: { token, baseURL, integrationURL? }
211
+ ```
212
+
213
+ #### Fluxo completo de signup com email
214
+
215
+ ```typescript
216
+ // 1. Criar conta
217
+ await emailSignupMitra({ name: 'João', email, password });
218
+
219
+ // 2. Usuário recebe código por email e digita na tela
220
+ const session = await emailVerifyCodeMitra({ email, code: '123456', password });
221
+
222
+ // 3. SDK já está configurado — pode chamar qualquer método
223
+ await executeDbActionMitra({ dbActionId: 1 });
224
+ ```
225
+
226
+ > **Nota:** `authUrl` e `projectId` são opcionais em todas as funções de email se já foram configurados via `configureSdkMitra()`.
227
+
147
228
  ## Métodos Disponíveis
148
229
 
149
230
  ### executeDbActionMitra
@@ -397,6 +478,11 @@ import type {
397
478
  // Login
398
479
  LoginOptions,
399
480
  LoginResponse,
481
+ // Email Auth
482
+ EmailSignupOptions,
483
+ EmailLoginOptions,
484
+ EmailVerifyCodeOptions,
485
+ EmailResendCodeOptions,
400
486
  // Options
401
487
  ExecuteDbActionOptions,
402
488
  ExecuteServerFunctionOptions,
package/dist/index.d.mts CHANGED
@@ -23,6 +23,48 @@ interface LoginResponse {
23
23
  /** URL do serviço de integrações (opcional) */
24
24
  integrationURL?: string;
25
25
  }
26
+ interface EmailSignupOptions {
27
+ /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
28
+ authUrl?: string;
29
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
30
+ projectId?: number;
31
+ /** Nome completo do usuário */
32
+ name: string;
33
+ /** Email do usuário */
34
+ email: string;
35
+ /** Senha */
36
+ password: string;
37
+ }
38
+ interface EmailLoginOptions {
39
+ /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
40
+ authUrl?: string;
41
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
42
+ projectId?: number;
43
+ /** Email do usuário */
44
+ email: string;
45
+ /** Senha */
46
+ password: string;
47
+ }
48
+ interface EmailVerifyCodeOptions {
49
+ /** URL da página de auth. Opcional se já configurado via configureSdkMitra. */
50
+ authUrl?: string;
51
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
52
+ projectId?: number;
53
+ /** Email do usuário */
54
+ email: string;
55
+ /** Código de verificação de 6 dígitos */
56
+ code: string;
57
+ /** Senha do usuário (necessário para login automático após verificação) */
58
+ password: string;
59
+ }
60
+ interface EmailResendCodeOptions {
61
+ /** URL da página de auth. Opcional se já configurado via configureSdkMitra. */
62
+ authUrl?: string;
63
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
64
+ projectId?: number;
65
+ /** Email do usuário */
66
+ email: string;
67
+ }
26
68
  interface RunQueryOptions {
27
69
  /** ID do projeto (opcional se já configurado via configureSdkMitra) */
28
70
  projectId?: number;
@@ -316,8 +358,8 @@ declare function createMitraInstance(initialConfig: Partial<MitraConfig>): Mitra
316
358
  interface MitraConfig {
317
359
  /** URL base da API (ex: https://api.mitra.com) */
318
360
  baseURL: string;
319
- /** Token JWT para autenticação */
320
- token: string;
361
+ /** Token JWT para autenticação (opcional para Server Functions públicas) */
362
+ token?: string;
321
363
  /** URL base do serviço de integrações (ex: https://api0.mitraecp.com:1003) */
322
364
  integrationURL?: string;
323
365
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
@@ -381,6 +423,29 @@ declare function handleAuthRedirect(): LoginResponse | null;
381
423
  * Se já houver um refresh em andamento, reaproveita a mesma promise.
382
424
  */
383
425
  declare function refreshTokenSilently(authUrl: string, projectId: number): Promise<LoginResponse>;
426
+ /**
427
+ * Cria conta via email usando iframe silencioso.
428
+ * Após sucesso, o usuário recebe um código de verificação por email.
429
+ * Fluxo: emailSignupMitra → emailVerifyCodeMitra → emailLoginMitra
430
+ */
431
+ declare function emailSignupMitra(options: EmailSignupOptions): Promise<void>;
432
+ /**
433
+ * Verifica o código de 6 dígitos enviado por email após signup.
434
+ * Após verificação, faz login automático e retorna LoginResponse.
435
+ * Auto-configura o SDK após sucesso.
436
+ */
437
+ declare function emailVerifyCodeMitra(options: EmailVerifyCodeOptions): Promise<LoginResponse>;
438
+ /**
439
+ * Reenvia o código de verificação para o email.
440
+ */
441
+ declare function emailResendCodeMitra(options: EmailResendCodeOptions): Promise<void>;
442
+ /**
443
+ * Login via email e senha usando iframe silencioso.
444
+ * O HTML de auth faz a chamada à API e resolve as credenciais do projeto.
445
+ * Retorna LoginResponse com token, baseURL e integrationURL.
446
+ * Auto-configura o SDK após sucesso.
447
+ */
448
+ declare function emailLoginMitra(options: EmailLoginOptions): Promise<LoginResponse>;
384
449
 
385
450
  /**
386
451
  * Mitra Interactions SDK - Services
@@ -465,4 +530,4 @@ declare function patchRecordMitra(options: PatchRecordOptions): Promise<Record<s
465
530
  declare function deleteRecordMitra(options: DeleteRecordOptions): Promise<void>;
466
531
  declare function createRecordsBatchMitra(options: CreateRecordsBatchOptions): Promise<Record<string, any>[]>;
467
532
 
468
- export { type CallIntegrationOptions, type CallIntegrationResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteRecordOptions, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type RunActionOptions, type RunActionResponse, type RunQueryOptions, type RunQueryResponse, type SetFileStatusOptions, type SetFileStatusResponse, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, executeDbActionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getConfig, getRecordMitra, getVariableMitra, handleAuthRedirect, listIntegrationsMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, runActionMitra, runQueryMitra, setFileStatusMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra };
533
+ export { type CallIntegrationOptions, type CallIntegrationResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteRecordOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type RunActionOptions, type RunActionResponse, type RunQueryOptions, type RunQueryResponse, type SetFileStatusOptions, type SetFileStatusResponse, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDbActionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getConfig, getRecordMitra, getVariableMitra, handleAuthRedirect, listIntegrationsMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, runActionMitra, runQueryMitra, setFileStatusMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra };
package/dist/index.d.ts CHANGED
@@ -23,6 +23,48 @@ interface LoginResponse {
23
23
  /** URL do serviço de integrações (opcional) */
24
24
  integrationURL?: string;
25
25
  }
26
+ interface EmailSignupOptions {
27
+ /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
28
+ authUrl?: string;
29
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
30
+ projectId?: number;
31
+ /** Nome completo do usuário */
32
+ name: string;
33
+ /** Email do usuário */
34
+ email: string;
35
+ /** Senha */
36
+ password: string;
37
+ }
38
+ interface EmailLoginOptions {
39
+ /** URL da página de auth (ex: https://validacao.mitralab.io/sdk-auth/). Opcional se já configurado via configureSdkMitra. */
40
+ authUrl?: string;
41
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
42
+ projectId?: number;
43
+ /** Email do usuário */
44
+ email: string;
45
+ /** Senha */
46
+ password: string;
47
+ }
48
+ interface EmailVerifyCodeOptions {
49
+ /** URL da página de auth. Opcional se já configurado via configureSdkMitra. */
50
+ authUrl?: string;
51
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
52
+ projectId?: number;
53
+ /** Email do usuário */
54
+ email: string;
55
+ /** Código de verificação de 6 dígitos */
56
+ code: string;
57
+ /** Senha do usuário (necessário para login automático após verificação) */
58
+ password: string;
59
+ }
60
+ interface EmailResendCodeOptions {
61
+ /** URL da página de auth. Opcional se já configurado via configureSdkMitra. */
62
+ authUrl?: string;
63
+ /** ID do projeto. Opcional se já configurado via configureSdkMitra. */
64
+ projectId?: number;
65
+ /** Email do usuário */
66
+ email: string;
67
+ }
26
68
  interface RunQueryOptions {
27
69
  /** ID do projeto (opcional se já configurado via configureSdkMitra) */
28
70
  projectId?: number;
@@ -316,8 +358,8 @@ declare function createMitraInstance(initialConfig: Partial<MitraConfig>): Mitra
316
358
  interface MitraConfig {
317
359
  /** URL base da API (ex: https://api.mitra.com) */
318
360
  baseURL: string;
319
- /** Token JWT para autenticação */
320
- token: string;
361
+ /** Token JWT para autenticação (opcional para Server Functions públicas) */
362
+ token?: string;
321
363
  /** URL base do serviço de integrações (ex: https://api0.mitraecp.com:1003) */
322
364
  integrationURL?: string;
323
365
  /** URL da página de autenticação Mitra (ex: https://coder.mitralab.io/sdk-auth/) */
@@ -381,6 +423,29 @@ declare function handleAuthRedirect(): LoginResponse | null;
381
423
  * Se já houver um refresh em andamento, reaproveita a mesma promise.
382
424
  */
383
425
  declare function refreshTokenSilently(authUrl: string, projectId: number): Promise<LoginResponse>;
426
+ /**
427
+ * Cria conta via email usando iframe silencioso.
428
+ * Após sucesso, o usuário recebe um código de verificação por email.
429
+ * Fluxo: emailSignupMitra → emailVerifyCodeMitra → emailLoginMitra
430
+ */
431
+ declare function emailSignupMitra(options: EmailSignupOptions): Promise<void>;
432
+ /**
433
+ * Verifica o código de 6 dígitos enviado por email após signup.
434
+ * Após verificação, faz login automático e retorna LoginResponse.
435
+ * Auto-configura o SDK após sucesso.
436
+ */
437
+ declare function emailVerifyCodeMitra(options: EmailVerifyCodeOptions): Promise<LoginResponse>;
438
+ /**
439
+ * Reenvia o código de verificação para o email.
440
+ */
441
+ declare function emailResendCodeMitra(options: EmailResendCodeOptions): Promise<void>;
442
+ /**
443
+ * Login via email e senha usando iframe silencioso.
444
+ * O HTML de auth faz a chamada à API e resolve as credenciais do projeto.
445
+ * Retorna LoginResponse com token, baseURL e integrationURL.
446
+ * Auto-configura o SDK após sucesso.
447
+ */
448
+ declare function emailLoginMitra(options: EmailLoginOptions): Promise<LoginResponse>;
384
449
 
385
450
  /**
386
451
  * Mitra Interactions SDK - Services
@@ -465,4 +530,4 @@ declare function patchRecordMitra(options: PatchRecordOptions): Promise<Record<s
465
530
  declare function deleteRecordMitra(options: DeleteRecordOptions): Promise<void>;
466
531
  declare function createRecordsBatchMitra(options: CreateRecordsBatchOptions): Promise<Record<string, any>[]>;
467
532
 
468
- export { type CallIntegrationOptions, type CallIntegrationResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteRecordOptions, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type RunActionOptions, type RunActionResponse, type RunQueryOptions, type RunQueryResponse, type SetFileStatusOptions, type SetFileStatusResponse, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, executeDbActionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getConfig, getRecordMitra, getVariableMitra, handleAuthRedirect, listIntegrationsMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, runActionMitra, runQueryMitra, setFileStatusMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra };
533
+ export { type CallIntegrationOptions, type CallIntegrationResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type DeleteRecordOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type MitraConfig, type MitraInstance, type PatchRecordOptions, type RunActionOptions, type RunActionResponse, type RunQueryOptions, type RunQueryResponse, type SetFileStatusOptions, type SetFileStatusResponse, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDbActionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getConfig, getRecordMitra, getVariableMitra, handleAuthRedirect, listIntegrationsMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, patchRecordMitra, refreshTokenSilently, resolveProjectId, runActionMitra, runQueryMitra, setFileStatusMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra };
package/dist/index.js CHANGED
@@ -189,6 +189,91 @@ async function refreshTokenSilently(authUrl, projectId) {
189
189
  })();
190
190
  return _refreshPromise;
191
191
  }
192
+ var SILENT_TIMEOUT_MS = 2e4;
193
+ var AUTH_READY_TYPE = "mitra-auth-ready";
194
+ var AUTH_CREDENTIALS_TYPE = "mitra-auth-credentials";
195
+ function openSilentAuthIframe(authUrl, projectId, credentials) {
196
+ return new Promise((resolve, reject) => {
197
+ const origin = getOriginFromUrl(authUrl);
198
+ const base = authUrl.endsWith("/") ? authUrl : authUrl + "/";
199
+ let url = `${base}?mode=silent&projectId=${encodeURIComponent(projectId)}`;
200
+ if (typeof window !== "undefined") {
201
+ url += `&originUrl=${encodeURIComponent(window.location.href)}`;
202
+ }
203
+ const iframe = document.createElement("iframe");
204
+ iframe.style.display = "none";
205
+ const timer = setTimeout(() => {
206
+ cleanup();
207
+ reject(new Error("Timeout na autentica\xE7\xE3o silenciosa"));
208
+ }, SILENT_TIMEOUT_MS);
209
+ function onMessage(event) {
210
+ var _a, _b, _c;
211
+ if (event.origin !== origin) return;
212
+ if (((_a = event.data) == null ? void 0 : _a.type) === AUTH_READY_TYPE) {
213
+ (_b = iframe.contentWindow) == null ? void 0 : _b.postMessage({
214
+ type: AUTH_CREDENTIALS_TYPE,
215
+ ...credentials
216
+ }, origin);
217
+ return;
218
+ }
219
+ if (((_c = event.data) == null ? void 0 : _c.type) !== AUTH_MESSAGE_TYPE) return;
220
+ cleanup();
221
+ if (event.data.success) {
222
+ resolve(event.data.data);
223
+ } else {
224
+ reject(new Error(event.data.error || "Erro na autentica\xE7\xE3o"));
225
+ }
226
+ }
227
+ function cleanup() {
228
+ window.removeEventListener("message", onMessage);
229
+ clearTimeout(timer);
230
+ if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
231
+ }
232
+ window.addEventListener("message", onMessage);
233
+ iframe.src = url;
234
+ document.body.appendChild(iframe);
235
+ });
236
+ }
237
+ async function emailSignupMitra(options) {
238
+ const { authUrl, projectId } = resolveLoginOptions(options);
239
+ const result = await openSilentAuthIframe(authUrl, projectId, {
240
+ action: "signup",
241
+ name: options.name,
242
+ email: options.email,
243
+ password: options.password
244
+ });
245
+ if (!result.needsVerification) {
246
+ throw new Error("Resposta inesperada do signup");
247
+ }
248
+ }
249
+ async function emailVerifyCodeMitra(options) {
250
+ const { authUrl, projectId } = resolveLoginOptions(options);
251
+ const response = await openSilentAuthIframe(authUrl, projectId, {
252
+ action: "verifyCode",
253
+ email: options.email,
254
+ code: options.code,
255
+ password: options.password
256
+ });
257
+ autoConfigureFromLogin(response, authUrl, projectId);
258
+ return response;
259
+ }
260
+ async function emailResendCodeMitra(options) {
261
+ const { authUrl, projectId } = resolveLoginOptions(options);
262
+ await openSilentAuthIframe(authUrl, projectId, {
263
+ action: "resendCode",
264
+ email: options.email
265
+ });
266
+ }
267
+ async function emailLoginMitra(options) {
268
+ const { authUrl, projectId } = resolveLoginOptions(options);
269
+ const response = await openSilentAuthIframe(authUrl, projectId, {
270
+ action: "login",
271
+ email: options.email,
272
+ password: options.password
273
+ });
274
+ autoConfigureFromLogin(response, authUrl, projectId);
275
+ return response;
276
+ }
192
277
 
193
278
  // src/instance.ts
194
279
  function formatToken(token) {
@@ -216,10 +301,9 @@ function createMitraInstance(initialConfig) {
216
301
  throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
217
302
  }
218
303
  function authHeaders() {
219
- return {
220
- "Authorization": formatToken(_config.token),
221
- "Content-Type": "application/json"
222
- };
304
+ const headers = { "Content-Type": "application/json" };
305
+ if (_config.token) headers["Authorization"] = formatToken(_config.token);
306
+ return headers;
223
307
  }
224
308
  async function handleResponse2(response) {
225
309
  const text = await response.text();
@@ -232,8 +316,31 @@ function createMitraInstance(initialConfig) {
232
316
  return data;
233
317
  }
234
318
  async function tryRefreshToken2() {
235
- if (!_config.authUrl || _config.projectId == null) return false;
236
- if (typeof window === "undefined") return false;
319
+ var _a2, _b;
320
+ if (!_config.token || _config.projectId == null) return false;
321
+ try {
322
+ const baseURL = _config.baseURL.replace(/\/+$/, "");
323
+ const resp = await getFetch()(`${baseURL}/mitraspace/project/refreshedToken/${_config.projectId}`, {
324
+ method: "GET",
325
+ headers: { "Authorization": formatToken(_config.token) }
326
+ });
327
+ if (resp.ok) {
328
+ const data = await resp.json();
329
+ if (data.token) {
330
+ const newToken = data.token.startsWith("Bearer ") ? data.token : `Bearer ${data.token}`;
331
+ const session = {
332
+ token: newToken,
333
+ baseURL: ((_a2 = data.merge) == null ? void 0 : _a2.backURL) || _config.baseURL,
334
+ ...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
335
+ };
336
+ _config = { ..._config, token: session.token };
337
+ if (_config.onTokenRefresh) _config.onTokenRefresh(session);
338
+ return true;
339
+ }
340
+ }
341
+ } catch (e) {
342
+ }
343
+ if (!_config.authUrl || typeof window === "undefined") return false;
237
344
  try {
238
345
  const session = await refreshTokenSilently(_config.authUrl, _config.projectId);
239
346
  _config = { ..._config, token: session.token };
@@ -276,9 +383,11 @@ function createMitraInstance(initialConfig) {
276
383
  }
277
384
  async function requestUpload(endpoint, formData) {
278
385
  const url = `${_config.baseURL}${endpoint}`;
386
+ const headers = {};
387
+ if (_config.token) headers["Authorization"] = formatToken(_config.token);
279
388
  return fetchWithRefresh2(url, {
280
389
  method: "POST",
281
- headers: { "Authorization": formatToken(_config.token) },
390
+ headers,
282
391
  body: formData
283
392
  });
284
393
  }
@@ -439,14 +548,11 @@ function configureSdkMitra(config) {
439
548
  if (!config.baseURL) {
440
549
  throw new Error("baseURL \xE9 obrigat\xF3rio");
441
550
  }
442
- if (!config.token) {
443
- throw new Error("token \xE9 obrigat\xF3rio");
444
- }
445
551
  globalConfig = {
446
552
  ...config,
447
553
  baseURL: config.baseURL.replace(/\/+$/, "")
448
554
  };
449
- if (typeof window !== "undefined" && window.__cbTracker) {
555
+ if (config.token && typeof window !== "undefined" && window.__cbTracker) {
450
556
  window.__cbTracker.setToken(config.token);
451
557
  }
452
558
  return createMitraInstance(config);
@@ -483,10 +589,9 @@ function formatToken2(token) {
483
589
  }
484
590
  function buildHeaders() {
485
591
  const config = getConfig();
486
- return {
487
- "Authorization": formatToken2(config.token),
488
- "Content-Type": "application/json"
489
- };
592
+ const headers = { "Content-Type": "application/json" };
593
+ if (config.token) headers["Authorization"] = formatToken2(config.token);
594
+ return headers;
490
595
  }
491
596
  function buildUrl(endpoint, params) {
492
597
  const config = getConfig();
@@ -498,9 +603,32 @@ function buildUrl(endpoint, params) {
498
603
  return url;
499
604
  }
500
605
  async function tryRefreshToken() {
606
+ var _a, _b;
501
607
  const config = getConfig();
502
- if (!config.authUrl || config.projectId == null) return false;
503
- if (typeof window === "undefined") return false;
608
+ if (!config.token || config.projectId == null) return false;
609
+ try {
610
+ const baseURL = config.baseURL.replace(/\/+$/, "");
611
+ const resp = await getFetch2()(`${baseURL}/mitraspace/project/refreshedToken/${config.projectId}`, {
612
+ method: "GET",
613
+ headers: { "Authorization": formatToken2(config.token) }
614
+ });
615
+ if (resp.ok) {
616
+ const data = await resp.json();
617
+ if (data.token) {
618
+ const newToken = data.token.startsWith("Bearer ") ? data.token : `Bearer ${data.token}`;
619
+ const session = {
620
+ token: newToken,
621
+ baseURL: ((_a = data.merge) == null ? void 0 : _a.backURL) || config.baseURL,
622
+ ...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
623
+ };
624
+ updateGlobalToken(session.token);
625
+ if (config.onTokenRefresh) config.onTokenRefresh(session);
626
+ return true;
627
+ }
628
+ }
629
+ } catch (e) {
630
+ }
631
+ if (!config.authUrl || typeof window === "undefined") return false;
504
632
  try {
505
633
  const session = await refreshTokenSilently(config.authUrl, config.projectId);
506
634
  updateGlobalToken(session.token);
@@ -565,9 +693,11 @@ var http = {
565
693
  },
566
694
  async upload(endpoint, formData) {
567
695
  const config = getConfig();
696
+ const headers = {};
697
+ if (config.token) headers["Authorization"] = formatToken2(config.token);
568
698
  return fetchWithRefresh(buildUrl(endpoint), {
569
699
  method: "POST",
570
- headers: { "Authorization": formatToken2(config.token) },
700
+ headers,
571
701
  body: formData
572
702
  });
573
703
  }
@@ -594,12 +724,11 @@ async function requestIntegrations(method, endpoint, options) {
594
724
  const query = Object.entries(options.params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
595
725
  if (query) url += `?${query}`;
596
726
  }
727
+ const headers = { "Content-Type": "application/json" };
728
+ if (config.token) headers["Authorization"] = formatToken2(config.token);
597
729
  return fetchWithRefresh(url, {
598
730
  method,
599
- headers: {
600
- "Authorization": formatToken2(config.token),
601
- "Content-Type": "application/json"
602
- },
731
+ headers,
603
732
  body: (options == null ? void 0 : options.body) !== void 0 ? JSON.stringify(options.body) : void 0
604
733
  });
605
734
  }
@@ -792,6 +921,10 @@ exports.createMitraInstance = createMitraInstance;
792
921
  exports.createRecordMitra = createRecordMitra;
793
922
  exports.createRecordsBatchMitra = createRecordsBatchMitra;
794
923
  exports.deleteRecordMitra = deleteRecordMitra;
924
+ exports.emailLoginMitra = emailLoginMitra;
925
+ exports.emailResendCodeMitra = emailResendCodeMitra;
926
+ exports.emailSignupMitra = emailSignupMitra;
927
+ exports.emailVerifyCodeMitra = emailVerifyCodeMitra;
795
928
  exports.executeDbActionMitra = executeDbActionMitra;
796
929
  exports.executeServerFunctionAsyncMitra = executeServerFunctionAsyncMitra;
797
930
  exports.executeServerFunctionMitra = executeServerFunctionMitra;