mitra-interactions-sdk 1.0.68 → 1.0.70
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 +19 -5
- package/dist/index.d.mts +55 -26
- package/dist/index.d.ts +55 -26
- package/dist/index.js +146 -28
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +146 -28
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -132,6 +132,18 @@ await loginMitra('mitra', {
|
|
|
132
132
|
|
|
133
133
|
Quando qualquer requisição retorna **403**, o SDK tenta renovar o token automaticamente via iframe invisível (usa o cookie de sessão do provider). Se o refresh funcionar, a requisição é retentada com o novo token — transparente para o desenvolvedor.
|
|
134
134
|
|
|
135
|
+
**Sessão com duração limitada.** Quando o ambiente limita a duração da sessão, o token vale poucos minutos e traz a claim `authTime`. Nesse caso a SDK renova sozinha **antes** do vencimento (e ao voltar para a aba), sem esperar o 403. Se a sessão acabou de vez, a SDK chama `onSessionExpired`: limpe a sessão guardada e leve o usuário ao login. Para os demais tokens nada muda.
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
configureSdkMitra({
|
|
139
|
+
...session,
|
|
140
|
+
onSessionExpired: () => {
|
|
141
|
+
localStorage.removeItem('minha_sessao');
|
|
142
|
+
window.location.reload();
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
```
|
|
146
|
+
|
|
135
147
|
O callback `onTokenRefresh` é chamado após renovação bem-sucedida:
|
|
136
148
|
|
|
137
149
|
```typescript
|
|
@@ -514,19 +526,21 @@ const profiles = await listProfilesMitra({ projectId: 123 });
|
|
|
514
526
|
// { status, projectId, result: [{ id, name, color, homeScreenId }] }
|
|
515
527
|
|
|
516
528
|
// Criar perfil
|
|
517
|
-
const created = await createProfileMitra({ projectId: 123, name: 'Vendedores'
|
|
518
|
-
// { status, result: {
|
|
529
|
+
const created = await createProfileMitra({ projectId: 123, name: 'Vendedores' });
|
|
530
|
+
// { status, result: { profileId, message } } (mitraapi ≥ #8735 também devolve id e name)
|
|
531
|
+
// A cor passada na criação ainda não é gravada pelo servidor: defina com updateProfileMitra.
|
|
519
532
|
|
|
520
533
|
// Detalhes do perfil
|
|
521
534
|
const details = await getProfileDetailsMitra({ projectId: 123, profileId: 1 });
|
|
522
|
-
// { status, projectId, result: { id, name, users,
|
|
535
|
+
// { status, projectId, result: { id, name, color, homeScreenId, users?: [{ id, name, email }], selectTables: [{ tableName, jdbcConnectionConfigId, onlineTable }],
|
|
536
|
+
// dmlTables, actions: [{ actionId, actionName }], screens: [{ screenId, screenName }], serverFunctions: [{ serverFunctionId, serverFunctionName }] } }
|
|
523
537
|
```
|
|
524
538
|
|
|
525
539
|
#### Permissões de Perfil
|
|
526
540
|
|
|
527
|
-
Define quais recursos cada perfil pode acessar. Todas substituem a lista atual (não
|
|
541
|
+
Define quais recursos cada perfil pode acessar. Todas substituem a lista atual, **menos `setProfileUsersMitra`, que só acrescenta** (não tira quem já está no perfil).
|
|
528
542
|
|
|
529
|
-
- `setProfileUsersMitra({ projectId?, profileId, userIds })` -
|
|
543
|
+
- `setProfileUsersMitra({ projectId?, profileId, userIds?, emails? })` - Acrescenta usuários ao perfil (ao menos um de userIds ou emails; os não encontrados voltam em `userIdsNotFound`/`emailsNotFound`)
|
|
530
544
|
- `setProfileSelectTablesMitra({ projectId?, profileId, jdbcConnectionConfigId?, tables })` - Define tabelas SELECT permitidas
|
|
531
545
|
- `setProfileDmlTablesMitra({ projectId?, profileId, jdbcConnectionConfigId?, tables })` - Define tabelas DML permitidas
|
|
532
546
|
- `setProfileActionsMitra({ projectId?, profileId, actionIds })` - Define actions permitidas
|
package/dist/index.d.mts
CHANGED
|
@@ -472,36 +472,43 @@ interface GetProfileDetailsOptions {
|
|
|
472
472
|
projectId?: number;
|
|
473
473
|
profileId: number;
|
|
474
474
|
}
|
|
475
|
+
interface ProfileUserItem {
|
|
476
|
+
id: number;
|
|
477
|
+
userId: number;
|
|
478
|
+
name: string;
|
|
479
|
+
email: string;
|
|
480
|
+
/** Login (= email), mantido por compatibilidade. */
|
|
481
|
+
username: string;
|
|
482
|
+
}
|
|
483
|
+
interface ProfileTableItem {
|
|
484
|
+
tableName: string;
|
|
485
|
+
jdbcConnectionConfigId?: number | null;
|
|
486
|
+
onlineTable?: boolean | null;
|
|
487
|
+
}
|
|
488
|
+
/** Formato conferido no mitraapi (getProfileDetails). */
|
|
475
489
|
interface GetProfileDetailsResponse {
|
|
476
490
|
status: string;
|
|
477
491
|
projectId: number;
|
|
478
492
|
result: {
|
|
479
493
|
id: number;
|
|
480
494
|
name: string;
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
tableName: string;
|
|
488
|
-
jdbcConnectionConfigId?: number;
|
|
489
|
-
}[];
|
|
490
|
-
dmlTables: {
|
|
491
|
-
tableName: string;
|
|
492
|
-
jdbcConnectionConfigId?: number;
|
|
493
|
-
}[];
|
|
495
|
+
color?: string | null;
|
|
496
|
+
homeScreenId?: number | null;
|
|
497
|
+
/** Usuários ativos do perfil (mitraapi ≥ #8735; antes o campo não vinha). */
|
|
498
|
+
users?: ProfileUserItem[];
|
|
499
|
+
selectTables: ProfileTableItem[];
|
|
500
|
+
dmlTables: ProfileTableItem[];
|
|
494
501
|
actions: {
|
|
495
|
-
|
|
496
|
-
|
|
502
|
+
actionId: number;
|
|
503
|
+
actionName: string | null;
|
|
497
504
|
}[];
|
|
498
505
|
screens: {
|
|
499
|
-
|
|
500
|
-
|
|
506
|
+
screenId: number;
|
|
507
|
+
screenName: string | null;
|
|
501
508
|
}[];
|
|
502
509
|
serverFunctions: {
|
|
503
|
-
|
|
504
|
-
|
|
510
|
+
serverFunctionId: number;
|
|
511
|
+
serverFunctionName: string | null;
|
|
505
512
|
}[];
|
|
506
513
|
};
|
|
507
514
|
}
|
|
@@ -514,8 +521,12 @@ interface CreateProfileOptions {
|
|
|
514
521
|
interface CreateProfileResponse {
|
|
515
522
|
status: string;
|
|
516
523
|
result: {
|
|
517
|
-
|
|
518
|
-
|
|
524
|
+
/** Id do novo perfil: use este campo. */
|
|
525
|
+
profileId: number;
|
|
526
|
+
/** Igual a profileId (mitraapi ≥ #8735). */
|
|
527
|
+
id?: number;
|
|
528
|
+
/** mitraapi ≥ #8735 */
|
|
529
|
+
name?: string;
|
|
519
530
|
message: string;
|
|
520
531
|
};
|
|
521
532
|
}
|
|
@@ -529,8 +540,7 @@ interface UpdateProfileOptions {
|
|
|
529
540
|
interface UpdateProfileResponse {
|
|
530
541
|
status: string;
|
|
531
542
|
result: {
|
|
532
|
-
|
|
533
|
-
name: string;
|
|
543
|
+
profileId: number;
|
|
534
544
|
message: string;
|
|
535
545
|
};
|
|
536
546
|
}
|
|
@@ -547,10 +557,15 @@ interface DeleteProfileResponse {
|
|
|
547
557
|
interface SetProfileUsersOptions {
|
|
548
558
|
projectId?: number;
|
|
549
559
|
profileId: number;
|
|
550
|
-
userIds
|
|
560
|
+
/** IDs dos usuários no tenant (INT_USERS.ID) — ao menos um de userIds ou emails deve ser informado */
|
|
561
|
+
userIds?: number[];
|
|
562
|
+
/** Emails dos usuários (resolvidos para userId no tenant) — ao menos um de userIds ou emails deve ser informado */
|
|
563
|
+
emails?: string[];
|
|
551
564
|
}
|
|
552
565
|
interface ProfileTableRef {
|
|
553
566
|
tableName: string;
|
|
567
|
+
/** true = online table (query alias), sem conexão JDBC */
|
|
568
|
+
onlineTable?: boolean;
|
|
554
569
|
}
|
|
555
570
|
interface SetProfileSelectTablesOptions {
|
|
556
571
|
projectId?: number;
|
|
@@ -1027,6 +1042,13 @@ interface MitraConfig {
|
|
|
1027
1042
|
projectId?: number;
|
|
1028
1043
|
/** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
|
|
1029
1044
|
onTokenRefresh?: (session: LoginResponse) => void;
|
|
1045
|
+
/**
|
|
1046
|
+
* Callback chamado quando a sessão acabou e não há mais como renovar: o token
|
|
1047
|
+
* de uma sessão com duração limitada venceu e a renovação foi recusada. O app
|
|
1048
|
+
* deve limpar a sessão guardada e levar o usuário ao login. Nunca é chamado
|
|
1049
|
+
* para token de validade longa nem em erro de permissão (403 comum).
|
|
1050
|
+
*/
|
|
1051
|
+
onSessionExpired?: () => void;
|
|
1030
1052
|
}
|
|
1031
1053
|
/**
|
|
1032
1054
|
* Configura o SDK globalmente e retorna uma instância configurada.
|
|
@@ -1087,8 +1109,15 @@ declare function loginMitra(method: 'email' | 'google' | 'microsoft' | 'mitra',
|
|
|
1087
1109
|
/**
|
|
1088
1110
|
* Renova o token silenciosamente via iframe invisível.
|
|
1089
1111
|
* Se já houver um refresh em andamento, reaproveita a mesma promise.
|
|
1112
|
+
*
|
|
1113
|
+
* `currentToken` é o token que o app tem agora. Quando a página de auth pede
|
|
1114
|
+
* (aperto de mão `mitra-auth-ready`), ele é entregue ao iframe por postMessage.
|
|
1115
|
+
* Sem isso, app em domínio próprio não renova: o navegador particiona o
|
|
1116
|
+
* localStorage do iframe de outro site e a página de auth não acha o token que
|
|
1117
|
+
* gravou no login. Página de auth antiga ignora o pedido e renova pelo token
|
|
1118
|
+
* guardado, como sempre.
|
|
1090
1119
|
*/
|
|
1091
|
-
declare function refreshTokenSilently(authUrl: string, projectId: number): Promise<LoginResponse>;
|
|
1120
|
+
declare function refreshTokenSilently(authUrl: string, projectId: number, currentToken?: string): Promise<LoginResponse>;
|
|
1092
1121
|
/**
|
|
1093
1122
|
* Cria conta via email usando iframe silencioso.
|
|
1094
1123
|
* Após sucesso, o usuário recebe um código de verificação por email.
|
|
@@ -1436,4 +1465,4 @@ type EnvLike = Record<string, string | undefined> | undefined;
|
|
|
1436
1465
|
*/
|
|
1437
1466
|
declare function readServerFunctionProof(env?: EnvLike, hasWindow?: boolean): string | null;
|
|
1438
1467
|
|
|
1439
|
-
export { type AgentApiKeyTarget, type AgentAttachment, type AgentAttachmentType, type AgentAuthMeta, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentModelGroup, type AgentModelOption, type AgentProviderListItem, type AgentQueueChangeEvent, type AgentStatusChangeEvent, type AgentSubscriptionAccount, type AgentSubscriptionTarget, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AuthAgentCredentialOptions, type AuthAgentCredentialResult, type AuthClaudeResult, type AuthCodexResult, type AuthMethod, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialOptions, type ConnectAgentSubscriptionResult, type ConnectableSubscriptionTarget, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAccessType, type CredentialAction, type CredentialTarget, type DeleteAgentChatResult, type DeleteFileOptions, type DeleteFileResponse, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type DownloadFileOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type FileLinkOptions, type FileLinkResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type ManageAgentCredentialResult, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableRef, type QueuedItem, type RenameAgentChatResult, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, SF_EXECUTION_TOKEN_ENV, SF_EXECUTION_TOKEN_HEADER, type SendOptions, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteFileMitra, deleteProfileMitra, deleteRecordMitra, downloadFilePrivateMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getFileLinkMitra, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, manageAgentChatMitra, manageAgentCredentialMitra, openChatMitra, patchRecordMitra, readServerFunctionProof, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePrivateMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
|
|
1468
|
+
export { type AgentApiKeyTarget, type AgentAttachment, type AgentAttachmentType, type AgentAuthMeta, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentModelGroup, type AgentModelOption, type AgentProviderListItem, type AgentQueueChangeEvent, type AgentStatusChangeEvent, type AgentSubscriptionAccount, type AgentSubscriptionTarget, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AuthAgentCredentialOptions, type AuthAgentCredentialResult, type AuthClaudeResult, type AuthCodexResult, type AuthMethod, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialOptions, type ConnectAgentSubscriptionResult, type ConnectableSubscriptionTarget, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAccessType, type CredentialAction, type CredentialTarget, type DeleteAgentChatResult, type DeleteFileOptions, type DeleteFileResponse, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type DownloadFileOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type FileLinkOptions, type FileLinkResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type ManageAgentCredentialResult, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableItem, type ProfileTableRef, type ProfileUserItem, type QueuedItem, type RenameAgentChatResult, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, SF_EXECUTION_TOKEN_ENV, SF_EXECUTION_TOKEN_HEADER, type SendOptions, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteFileMitra, deleteProfileMitra, deleteRecordMitra, downloadFilePrivateMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getFileLinkMitra, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, manageAgentChatMitra, manageAgentCredentialMitra, openChatMitra, patchRecordMitra, readServerFunctionProof, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePrivateMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
|
package/dist/index.d.ts
CHANGED
|
@@ -472,36 +472,43 @@ interface GetProfileDetailsOptions {
|
|
|
472
472
|
projectId?: number;
|
|
473
473
|
profileId: number;
|
|
474
474
|
}
|
|
475
|
+
interface ProfileUserItem {
|
|
476
|
+
id: number;
|
|
477
|
+
userId: number;
|
|
478
|
+
name: string;
|
|
479
|
+
email: string;
|
|
480
|
+
/** Login (= email), mantido por compatibilidade. */
|
|
481
|
+
username: string;
|
|
482
|
+
}
|
|
483
|
+
interface ProfileTableItem {
|
|
484
|
+
tableName: string;
|
|
485
|
+
jdbcConnectionConfigId?: number | null;
|
|
486
|
+
onlineTable?: boolean | null;
|
|
487
|
+
}
|
|
488
|
+
/** Formato conferido no mitraapi (getProfileDetails). */
|
|
475
489
|
interface GetProfileDetailsResponse {
|
|
476
490
|
status: string;
|
|
477
491
|
projectId: number;
|
|
478
492
|
result: {
|
|
479
493
|
id: number;
|
|
480
494
|
name: string;
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
tableName: string;
|
|
488
|
-
jdbcConnectionConfigId?: number;
|
|
489
|
-
}[];
|
|
490
|
-
dmlTables: {
|
|
491
|
-
tableName: string;
|
|
492
|
-
jdbcConnectionConfigId?: number;
|
|
493
|
-
}[];
|
|
495
|
+
color?: string | null;
|
|
496
|
+
homeScreenId?: number | null;
|
|
497
|
+
/** Usuários ativos do perfil (mitraapi ≥ #8735; antes o campo não vinha). */
|
|
498
|
+
users?: ProfileUserItem[];
|
|
499
|
+
selectTables: ProfileTableItem[];
|
|
500
|
+
dmlTables: ProfileTableItem[];
|
|
494
501
|
actions: {
|
|
495
|
-
|
|
496
|
-
|
|
502
|
+
actionId: number;
|
|
503
|
+
actionName: string | null;
|
|
497
504
|
}[];
|
|
498
505
|
screens: {
|
|
499
|
-
|
|
500
|
-
|
|
506
|
+
screenId: number;
|
|
507
|
+
screenName: string | null;
|
|
501
508
|
}[];
|
|
502
509
|
serverFunctions: {
|
|
503
|
-
|
|
504
|
-
|
|
510
|
+
serverFunctionId: number;
|
|
511
|
+
serverFunctionName: string | null;
|
|
505
512
|
}[];
|
|
506
513
|
};
|
|
507
514
|
}
|
|
@@ -514,8 +521,12 @@ interface CreateProfileOptions {
|
|
|
514
521
|
interface CreateProfileResponse {
|
|
515
522
|
status: string;
|
|
516
523
|
result: {
|
|
517
|
-
|
|
518
|
-
|
|
524
|
+
/** Id do novo perfil: use este campo. */
|
|
525
|
+
profileId: number;
|
|
526
|
+
/** Igual a profileId (mitraapi ≥ #8735). */
|
|
527
|
+
id?: number;
|
|
528
|
+
/** mitraapi ≥ #8735 */
|
|
529
|
+
name?: string;
|
|
519
530
|
message: string;
|
|
520
531
|
};
|
|
521
532
|
}
|
|
@@ -529,8 +540,7 @@ interface UpdateProfileOptions {
|
|
|
529
540
|
interface UpdateProfileResponse {
|
|
530
541
|
status: string;
|
|
531
542
|
result: {
|
|
532
|
-
|
|
533
|
-
name: string;
|
|
543
|
+
profileId: number;
|
|
534
544
|
message: string;
|
|
535
545
|
};
|
|
536
546
|
}
|
|
@@ -547,10 +557,15 @@ interface DeleteProfileResponse {
|
|
|
547
557
|
interface SetProfileUsersOptions {
|
|
548
558
|
projectId?: number;
|
|
549
559
|
profileId: number;
|
|
550
|
-
userIds
|
|
560
|
+
/** IDs dos usuários no tenant (INT_USERS.ID) — ao menos um de userIds ou emails deve ser informado */
|
|
561
|
+
userIds?: number[];
|
|
562
|
+
/** Emails dos usuários (resolvidos para userId no tenant) — ao menos um de userIds ou emails deve ser informado */
|
|
563
|
+
emails?: string[];
|
|
551
564
|
}
|
|
552
565
|
interface ProfileTableRef {
|
|
553
566
|
tableName: string;
|
|
567
|
+
/** true = online table (query alias), sem conexão JDBC */
|
|
568
|
+
onlineTable?: boolean;
|
|
554
569
|
}
|
|
555
570
|
interface SetProfileSelectTablesOptions {
|
|
556
571
|
projectId?: number;
|
|
@@ -1027,6 +1042,13 @@ interface MitraConfig {
|
|
|
1027
1042
|
projectId?: number;
|
|
1028
1043
|
/** Callback chamado quando o token é renovado automaticamente (após 401/403). Recebe a nova sessão. */
|
|
1029
1044
|
onTokenRefresh?: (session: LoginResponse) => void;
|
|
1045
|
+
/**
|
|
1046
|
+
* Callback chamado quando a sessão acabou e não há mais como renovar: o token
|
|
1047
|
+
* de uma sessão com duração limitada venceu e a renovação foi recusada. O app
|
|
1048
|
+
* deve limpar a sessão guardada e levar o usuário ao login. Nunca é chamado
|
|
1049
|
+
* para token de validade longa nem em erro de permissão (403 comum).
|
|
1050
|
+
*/
|
|
1051
|
+
onSessionExpired?: () => void;
|
|
1030
1052
|
}
|
|
1031
1053
|
/**
|
|
1032
1054
|
* Configura o SDK globalmente e retorna uma instância configurada.
|
|
@@ -1087,8 +1109,15 @@ declare function loginMitra(method: 'email' | 'google' | 'microsoft' | 'mitra',
|
|
|
1087
1109
|
/**
|
|
1088
1110
|
* Renova o token silenciosamente via iframe invisível.
|
|
1089
1111
|
* Se já houver um refresh em andamento, reaproveita a mesma promise.
|
|
1112
|
+
*
|
|
1113
|
+
* `currentToken` é o token que o app tem agora. Quando a página de auth pede
|
|
1114
|
+
* (aperto de mão `mitra-auth-ready`), ele é entregue ao iframe por postMessage.
|
|
1115
|
+
* Sem isso, app em domínio próprio não renova: o navegador particiona o
|
|
1116
|
+
* localStorage do iframe de outro site e a página de auth não acha o token que
|
|
1117
|
+
* gravou no login. Página de auth antiga ignora o pedido e renova pelo token
|
|
1118
|
+
* guardado, como sempre.
|
|
1090
1119
|
*/
|
|
1091
|
-
declare function refreshTokenSilently(authUrl: string, projectId: number): Promise<LoginResponse>;
|
|
1120
|
+
declare function refreshTokenSilently(authUrl: string, projectId: number, currentToken?: string): Promise<LoginResponse>;
|
|
1092
1121
|
/**
|
|
1093
1122
|
* Cria conta via email usando iframe silencioso.
|
|
1094
1123
|
* Após sucesso, o usuário recebe um código de verificação por email.
|
|
@@ -1436,4 +1465,4 @@ type EnvLike = Record<string, string | undefined> | undefined;
|
|
|
1436
1465
|
*/
|
|
1437
1466
|
declare function readServerFunctionProof(env?: EnvLike, hasWindow?: boolean): string | null;
|
|
1438
1467
|
|
|
1439
|
-
export { type AgentApiKeyTarget, type AgentAttachment, type AgentAttachmentType, type AgentAuthMeta, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentModelGroup, type AgentModelOption, type AgentProviderListItem, type AgentQueueChangeEvent, type AgentStatusChangeEvent, type AgentSubscriptionAccount, type AgentSubscriptionTarget, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AuthAgentCredentialOptions, type AuthAgentCredentialResult, type AuthClaudeResult, type AuthCodexResult, type AuthMethod, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialOptions, type ConnectAgentSubscriptionResult, type ConnectableSubscriptionTarget, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAccessType, type CredentialAction, type CredentialTarget, type DeleteAgentChatResult, type DeleteFileOptions, type DeleteFileResponse, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type DownloadFileOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type FileLinkOptions, type FileLinkResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type ManageAgentCredentialResult, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableRef, type QueuedItem, type RenameAgentChatResult, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, SF_EXECUTION_TOKEN_ENV, SF_EXECUTION_TOKEN_HEADER, type SendOptions, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteFileMitra, deleteProfileMitra, deleteRecordMitra, downloadFilePrivateMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getFileLinkMitra, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, manageAgentChatMitra, manageAgentCredentialMitra, openChatMitra, patchRecordMitra, readServerFunctionProof, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePrivateMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
|
|
1468
|
+
export { type AgentApiKeyTarget, type AgentAttachment, type AgentAttachmentType, type AgentAuthMeta, type AgentChat, type AgentDeltaEvent, type AgentErrorEvent, type AgentMessage, type AgentModelGroup, type AgentModelOption, type AgentProviderListItem, type AgentQueueChangeEvent, type AgentStatusChangeEvent, type AgentSubscriptionAccount, type AgentSubscriptionTarget, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AuthAgentCredentialOptions, type AuthAgentCredentialResult, type AuthClaudeResult, type AuthCodexResult, type AuthMethod, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialOptions, type ConnectAgentSubscriptionResult, type ConnectableSubscriptionTarget, type CreateProfileOptions, type CreateProfileResponse, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAccessType, type CredentialAction, type CredentialTarget, type DeleteAgentChatResult, type DeleteFileOptions, type DeleteFileResponse, type DeleteProfileOptions, type DeleteProfileResponse, type DeleteRecordOptions, type DownloadFileOptions, type EmailLoginOptions, type EmailResendCodeOptions, type EmailSignupOptions, type EmailVerifyCodeOptions, type ExecuteDataLoaderOptions, type ExecuteDataLoaderResponse, type ExecuteDbActionOptions, type ExecuteDbActionResponse, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type FileLinkOptions, type FileLinkResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetProfileDetailsOptions, type GetProfileDetailsResponse, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GetVariableOptions, type GetVariableResponse, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListProfilesOptions, type ListProfilesResponse, type ListRecordsOptions, type ListRecordsResponse, type ListVariablesOptions, type ListVariablesResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type ManageAgentCredentialResult, type MitraConfig, type MitraInstance, type PatchRecordOptions, type ProfileTableItem, type ProfileTableRef, type ProfileUserItem, type QueuedItem, type RenameAgentChatResult, type ResetPasswordOptions, type RunActionOptions, type RunActionResponse, SF_EXECUTION_TOKEN_ENV, SF_EXECUTION_TOKEN_HEADER, type SendOptions, type SendPasswordResetCodeOptions, type SetFileStatusOptions, type SetFileStatusResponse, type SetProfileActionsOptions, type SetProfileDmlTablesOptions, type SetProfilePermissionResponse, type SetProfileScreensOptions, type SetProfileSelectTablesOptions, type SetProfileServerFunctionsOptions, type SetProfileUsersOptions, type SetVariableOptions, type SetVariableResponse, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateProfileOptions, type UpdateProfileResponse, type UpdateRecordOptions, type UploadFileOptions, type UploadFileResponse, type ValidatePasswordResetCodeOptions, callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteFileMitra, deleteProfileMitra, deleteRecordMitra, downloadFilePrivateMitra, emailLoginMitra, emailResendCodeMitra, emailSignupMitra, emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getFileLinkMitra, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra, loginWithEmailMitra, loginWithGoogleMitra, loginWithMicrosoftMitra, manageAgentChatMitra, manageAgentCredentialMitra, openChatMitra, patchRecordMitra, readServerFunctionProof, refreshTokenSilently, resetPasswordMitra, resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePrivateMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
|
package/dist/index.js
CHANGED
|
@@ -120,19 +120,28 @@ async function loginMitra(method, options) {
|
|
|
120
120
|
return doLogin(method, options);
|
|
121
121
|
}
|
|
122
122
|
var REFRESH_TIMEOUT_MS = 15e3;
|
|
123
|
+
var AUTH_HANDOFF_READY_TYPE = "mitra-auth-ready";
|
|
124
|
+
var AUTH_HANDOFF_TOKEN_TYPE = "mitra-auth-refresh-token";
|
|
123
125
|
var _refreshPromise = null;
|
|
124
|
-
function openAuthIframe(url, expectedOrigin) {
|
|
126
|
+
function openAuthIframe(url, expectedOrigin, handoffToken) {
|
|
125
127
|
return new Promise((resolve, reject) => {
|
|
126
128
|
const iframe = document.createElement("iframe");
|
|
127
129
|
iframe.style.display = "none";
|
|
128
130
|
iframe.src = url;
|
|
129
|
-
const
|
|
131
|
+
const timer2 = setTimeout(() => {
|
|
130
132
|
cleanup();
|
|
131
133
|
reject(new Error("Token refresh timeout"));
|
|
132
134
|
}, REFRESH_TIMEOUT_MS);
|
|
133
135
|
function onMessage(event) {
|
|
134
136
|
if (event.origin !== expectedOrigin) return;
|
|
135
|
-
if (!event.data
|
|
137
|
+
if (!event.data) return;
|
|
138
|
+
if (event.data.type === AUTH_HANDOFF_READY_TYPE) {
|
|
139
|
+
if (handoffToken && iframe.contentWindow && event.source === iframe.contentWindow) {
|
|
140
|
+
iframe.contentWindow.postMessage({ type: AUTH_HANDOFF_TOKEN_TYPE, token: handoffToken }, expectedOrigin);
|
|
141
|
+
}
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (event.data.type !== AUTH_MESSAGE_TYPE) return;
|
|
136
145
|
cleanup();
|
|
137
146
|
if (event.data.success) {
|
|
138
147
|
resolve(event.data.data);
|
|
@@ -142,20 +151,20 @@ function openAuthIframe(url, expectedOrigin) {
|
|
|
142
151
|
}
|
|
143
152
|
function cleanup() {
|
|
144
153
|
window.removeEventListener("message", onMessage);
|
|
145
|
-
clearTimeout(
|
|
154
|
+
clearTimeout(timer2);
|
|
146
155
|
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
|
|
147
156
|
}
|
|
148
157
|
window.addEventListener("message", onMessage);
|
|
149
158
|
document.body.appendChild(iframe);
|
|
150
159
|
});
|
|
151
160
|
}
|
|
152
|
-
async function refreshTokenSilently(authUrl, projectId) {
|
|
161
|
+
async function refreshTokenSilently(authUrl, projectId, currentToken) {
|
|
153
162
|
if (_refreshPromise) return _refreshPromise;
|
|
154
163
|
_refreshPromise = (async () => {
|
|
155
164
|
try {
|
|
156
165
|
const origin = getOriginFromUrl(authUrl);
|
|
157
|
-
const url = buildAuthUrl(authUrl, "refresh", projectId);
|
|
158
|
-
const response = await openAuthIframe(url, origin);
|
|
166
|
+
const url = buildAuthUrl(authUrl, "refresh", projectId) + (currentToken ? "&handoff=1" : "");
|
|
167
|
+
const response = await openAuthIframe(url, origin, currentToken);
|
|
159
168
|
return response;
|
|
160
169
|
} finally {
|
|
161
170
|
_refreshPromise = null;
|
|
@@ -177,7 +186,7 @@ function openSilentAuthIframe(authUrl, projectId, credentials) {
|
|
|
177
186
|
}
|
|
178
187
|
const iframe = document.createElement("iframe");
|
|
179
188
|
iframe.style.display = "none";
|
|
180
|
-
const
|
|
189
|
+
const timer2 = setTimeout(() => {
|
|
181
190
|
cleanup();
|
|
182
191
|
reject(new Error("Timeout na autentica\xE7\xE3o silenciosa"));
|
|
183
192
|
}, SILENT_TIMEOUT_MS);
|
|
@@ -201,7 +210,7 @@ function openSilentAuthIframe(authUrl, projectId, credentials) {
|
|
|
201
210
|
}
|
|
202
211
|
function cleanup() {
|
|
203
212
|
window.removeEventListener("message", onMessage);
|
|
204
|
-
clearTimeout(
|
|
213
|
+
clearTimeout(timer2);
|
|
205
214
|
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
|
|
206
215
|
}
|
|
207
216
|
window.addEventListener("message", onMessage);
|
|
@@ -383,6 +392,105 @@ function withServerFunctionProof(headers, proof = readServerFunctionProof()) {
|
|
|
383
392
|
return { ...headers, [SF_EXECUTION_TOKEN_HEADER]: proof };
|
|
384
393
|
}
|
|
385
394
|
|
|
395
|
+
// src/session-watch.ts
|
|
396
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
397
|
+
var RETRY_MS = 1e4;
|
|
398
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
399
|
+
var refresher = null;
|
|
400
|
+
var timer = null;
|
|
401
|
+
var listening = false;
|
|
402
|
+
var expiryAtLastAttempt = null;
|
|
403
|
+
var notifiedFor = null;
|
|
404
|
+
function registerSessionRefresher(fn) {
|
|
405
|
+
refresher = fn;
|
|
406
|
+
}
|
|
407
|
+
function limitedSessionExpiry(token) {
|
|
408
|
+
if (!token) return null;
|
|
409
|
+
const payload = decodeJwtPayload(token);
|
|
410
|
+
if (!payload || typeof payload.authTime !== "number" || typeof payload.exp !== "number") return null;
|
|
411
|
+
return payload.exp * 1e3;
|
|
412
|
+
}
|
|
413
|
+
function currentExpiry() {
|
|
414
|
+
if (typeof window === "undefined" || !isConfigured()) return null;
|
|
415
|
+
const config = getConfig();
|
|
416
|
+
if (!config.token || !config.authUrl || config.projectId == null) return null;
|
|
417
|
+
return limitedSessionExpiry(config.token);
|
|
418
|
+
}
|
|
419
|
+
function clearTimer() {
|
|
420
|
+
if (timer) {
|
|
421
|
+
clearTimeout(timer);
|
|
422
|
+
timer = null;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function startSessionWatch() {
|
|
426
|
+
expiryAtLastAttempt = null;
|
|
427
|
+
notifiedFor = null;
|
|
428
|
+
watchSession();
|
|
429
|
+
}
|
|
430
|
+
function watchSession() {
|
|
431
|
+
clearTimer();
|
|
432
|
+
const expiry = currentExpiry();
|
|
433
|
+
if (expiry == null) return;
|
|
434
|
+
listenForReturn();
|
|
435
|
+
let delay = Math.max(expiry - Date.now() - RENEW_BEFORE_MS, 0);
|
|
436
|
+
if (expiryAtLastAttempt != null && expiry <= expiryAtLastAttempt + 1e3) {
|
|
437
|
+
delay = Math.max(expiry - Date.now() + 1e3, RETRY_MS);
|
|
438
|
+
}
|
|
439
|
+
if (delay > MAX_TIMEOUT_MS) return;
|
|
440
|
+
timer = setTimeout(() => {
|
|
441
|
+
void renewNow();
|
|
442
|
+
}, delay);
|
|
443
|
+
}
|
|
444
|
+
async function renewNow() {
|
|
445
|
+
clearTimer();
|
|
446
|
+
const before = currentExpiry();
|
|
447
|
+
if (before == null || !refresher) return;
|
|
448
|
+
expiryAtLastAttempt = before;
|
|
449
|
+
const renewed = await refresher().catch(() => false);
|
|
450
|
+
if (renewed) return;
|
|
451
|
+
const expiry = currentExpiry();
|
|
452
|
+
if (expiry != null && Date.now() < expiry) {
|
|
453
|
+
timer = setTimeout(() => {
|
|
454
|
+
void renewNow();
|
|
455
|
+
}, RETRY_MS);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function onReturn() {
|
|
459
|
+
const expiry = currentExpiry();
|
|
460
|
+
if (expiry == null) return;
|
|
461
|
+
const atSessionEnd = expiryAtLastAttempt != null && expiry <= expiryAtLastAttempt + 1e3;
|
|
462
|
+
if (expiry - Date.now() <= RENEW_BEFORE_MS && (!atSessionEnd || Date.now() >= expiry)) {
|
|
463
|
+
void renewNow();
|
|
464
|
+
} else {
|
|
465
|
+
watchSession();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
function listenForReturn() {
|
|
469
|
+
if (listening || typeof window === "undefined") return;
|
|
470
|
+
listening = true;
|
|
471
|
+
if (typeof document !== "undefined" && typeof document.addEventListener === "function") {
|
|
472
|
+
document.addEventListener("visibilitychange", () => {
|
|
473
|
+
if (document.visibilityState === "visible") onReturn();
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
if (typeof window.addEventListener === "function") {
|
|
477
|
+
window.addEventListener("online", onReturn);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function reportRefreshFailure() {
|
|
481
|
+
var _a, _b;
|
|
482
|
+
const expiry = currentExpiry();
|
|
483
|
+
if (expiry == null || Date.now() < expiry) return;
|
|
484
|
+
const config = getConfig();
|
|
485
|
+
if (notifiedFor === config.token) return;
|
|
486
|
+
notifiedFor = (_a = config.token) != null ? _a : null;
|
|
487
|
+
clearTimer();
|
|
488
|
+
try {
|
|
489
|
+
(_b = config.onSessionExpired) == null ? void 0 : _b.call(config);
|
|
490
|
+
} catch (e) {
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
386
494
|
// src/client.ts
|
|
387
495
|
function getFetch2() {
|
|
388
496
|
if (typeof globalThis.fetch === "function") {
|
|
@@ -417,14 +525,18 @@ function tryRefreshToken() {
|
|
|
417
525
|
if (refreshInFlight === attempt) refreshInFlight = null;
|
|
418
526
|
};
|
|
419
527
|
attempt.then(clear, clear);
|
|
528
|
+
attempt.then((renewed) => {
|
|
529
|
+
if (!renewed) reportRefreshFailure();
|
|
530
|
+
}, () => void 0);
|
|
420
531
|
return attempt;
|
|
421
532
|
}
|
|
533
|
+
registerSessionRefresher(tryRefreshToken);
|
|
422
534
|
async function doRefreshToken() {
|
|
423
535
|
const config = getConfig();
|
|
424
536
|
if (!config.token || config.projectId == null || !config.baseURL) return false;
|
|
425
537
|
if (!config.authUrl || typeof window === "undefined") return false;
|
|
426
538
|
try {
|
|
427
|
-
const session = await refreshTokenSilently(config.authUrl, config.projectId);
|
|
539
|
+
const session = await refreshTokenSilently(config.authUrl, config.projectId, config.token);
|
|
428
540
|
updateGlobalToken(session.token);
|
|
429
541
|
if (config.onTokenRefresh) config.onTokenRefresh(session);
|
|
430
542
|
return true;
|
|
@@ -826,11 +938,13 @@ async function deleteProfileMitra(options) {
|
|
|
826
938
|
});
|
|
827
939
|
}
|
|
828
940
|
async function setProfileUsersMitra(options) {
|
|
829
|
-
|
|
941
|
+
const body = {
|
|
830
942
|
projectId: resolveProjectId2(options.projectId),
|
|
831
|
-
profileId: options.profileId
|
|
832
|
-
|
|
833
|
-
|
|
943
|
+
profileId: options.profileId
|
|
944
|
+
};
|
|
945
|
+
if (options.userIds !== void 0) body.userIds = options.userIds;
|
|
946
|
+
if (options.emails !== void 0) body.emails = options.emails;
|
|
947
|
+
return http.post("/interactions/profiles/users", body);
|
|
834
948
|
}
|
|
835
949
|
async function setProfileSelectTablesMitra(options) {
|
|
836
950
|
const body = {
|
|
@@ -1498,7 +1612,7 @@ function openSocket() {
|
|
|
1498
1612
|
return new Promise((resolve, reject) => {
|
|
1499
1613
|
const socket = new WebSocket(url);
|
|
1500
1614
|
let opened = false;
|
|
1501
|
-
const
|
|
1615
|
+
const timer2 = setTimeout(() => {
|
|
1502
1616
|
if (!opened) {
|
|
1503
1617
|
try {
|
|
1504
1618
|
socket.close();
|
|
@@ -1509,13 +1623,13 @@ function openSocket() {
|
|
|
1509
1623
|
}, 15e3);
|
|
1510
1624
|
socket.onopen = () => {
|
|
1511
1625
|
opened = true;
|
|
1512
|
-
clearTimeout(
|
|
1626
|
+
clearTimeout(timer2);
|
|
1513
1627
|
ws = socket;
|
|
1514
1628
|
resolve(socket);
|
|
1515
1629
|
};
|
|
1516
1630
|
socket.onerror = () => {
|
|
1517
1631
|
if (!opened) {
|
|
1518
|
-
clearTimeout(
|
|
1632
|
+
clearTimeout(timer2);
|
|
1519
1633
|
reject(new Error("Agent Chat: erro ao conectar no WebSocket"));
|
|
1520
1634
|
}
|
|
1521
1635
|
};
|
|
@@ -1523,7 +1637,7 @@ function openSocket() {
|
|
|
1523
1637
|
if (ws === socket) ws = null;
|
|
1524
1638
|
const detalhe = closeDetail(event);
|
|
1525
1639
|
if (!opened) {
|
|
1526
|
-
clearTimeout(
|
|
1640
|
+
clearTimeout(timer2);
|
|
1527
1641
|
reject(new Error(`Agent Chat: conex\xE3o fechada${detalhe}`));
|
|
1528
1642
|
}
|
|
1529
1643
|
for (const [id, pending] of pendingRequests) {
|
|
@@ -1898,7 +2012,7 @@ function createMitraInstance(initialConfig) {
|
|
|
1898
2012
|
if (!_config.token || _config.projectId == null || !_config.baseURL) return false;
|
|
1899
2013
|
if (!_config.authUrl || typeof window === "undefined") return false;
|
|
1900
2014
|
try {
|
|
1901
|
-
const session = await refreshTokenSilently(_config.authUrl, _config.projectId);
|
|
2015
|
+
const session = await refreshTokenSilently(_config.authUrl, _config.projectId, _config.token);
|
|
1902
2016
|
_config = { ..._config, token: stripBearer(session.token) };
|
|
1903
2017
|
updateGlobalToken(session.token);
|
|
1904
2018
|
if (_config.onTokenRefresh) _config.onTokenRefresh(session);
|
|
@@ -2188,19 +2302,21 @@ function createMitraInstance(initialConfig) {
|
|
|
2188
2302
|
return request("DELETE", "/interactions/profiles", { body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId } });
|
|
2189
2303
|
},
|
|
2190
2304
|
async setProfileUsers(options) {
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2305
|
+
const body = { projectId: resolveProjectId4(options.projectId), profileId: options.profileId };
|
|
2306
|
+
if (options.userIds !== void 0) body.userIds = options.userIds;
|
|
2307
|
+
if (options.emails !== void 0) body.emails = options.emails;
|
|
2308
|
+
return request("POST", "/interactions/profiles/users", { body });
|
|
2194
2309
|
},
|
|
2310
|
+
// jdbcConnectionConfigId era descartado nos dois abaixo (as funções soltas repassavam).
|
|
2195
2311
|
async setProfileSelectTables(options) {
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
});
|
|
2312
|
+
const body = { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, tables: options.tables };
|
|
2313
|
+
if (options.jdbcConnectionConfigId !== void 0) body.jdbcConnectionConfigId = options.jdbcConnectionConfigId;
|
|
2314
|
+
return request("POST", "/interactions/profiles/selectTables", { body });
|
|
2199
2315
|
},
|
|
2200
2316
|
async setProfileDmlTables(options) {
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
});
|
|
2317
|
+
const body = { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, tables: options.tables };
|
|
2318
|
+
if (options.jdbcConnectionConfigId !== void 0) body.jdbcConnectionConfigId = options.jdbcConnectionConfigId;
|
|
2319
|
+
return request("POST", "/interactions/profiles/dmlTables", { body });
|
|
2204
2320
|
},
|
|
2205
2321
|
async setProfileActions(options) {
|
|
2206
2322
|
return request("POST", "/interactions/profiles/actions", {
|
|
@@ -2306,6 +2422,7 @@ function configureSdkMitra(config = {}) {
|
|
|
2306
2422
|
const chat = window.__mitraChat;
|
|
2307
2423
|
if (chat) chat.init(merged.token);
|
|
2308
2424
|
}
|
|
2425
|
+
startSessionWatch();
|
|
2309
2426
|
return createMitraInstance(globalConfig);
|
|
2310
2427
|
}
|
|
2311
2428
|
function getConfig() {
|
|
@@ -2320,6 +2437,7 @@ function isConfigured() {
|
|
|
2320
2437
|
function updateGlobalToken(token) {
|
|
2321
2438
|
if (globalConfig) {
|
|
2322
2439
|
globalConfig = { ...globalConfig, token: stripBearer(token) };
|
|
2440
|
+
watchSession();
|
|
2323
2441
|
}
|
|
2324
2442
|
}
|
|
2325
2443
|
function inferProjectId(projectId) {
|