@mitralab.io/platform-sdk 1.5.0-beta.0 → 1.5.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/CHANGELOG.md +16 -0
- package/README.md +57 -531
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## 1.5.0
|
|
6
|
+
|
|
7
|
+
Stable release of the 1.5.0-beta line, already on the `beta` tag.
|
|
8
|
+
|
|
9
|
+
- `auth.allTokens` for apps enabled server-side, as in 1.5.0-beta.0.
|
|
10
|
+
- Depend on `@mitralab.io/sdk-core@0.2.12`, the stable release of the 0.2.12-beta.1 surface: a
|
|
11
|
+
`cancel()` pressed before the agent turn starts waits for the box to admit the prompt and goes out
|
|
12
|
+
right after it.
|
|
13
|
+
|
|
14
|
+
## 1.5.0-beta.1
|
|
15
|
+
|
|
16
|
+
- Depend on `@mitralab.io/sdk-core@0.2.12-beta.1`: a `cancel()` pressed before the agent turn starts
|
|
17
|
+
waits for the box to admit the prompt and goes out right after it, instead of being dropped while
|
|
18
|
+
the answer kept coming. `cancelled` is only emitted once the stop was delivered, and a stop pressed
|
|
19
|
+
for a prompt the box refuses never goes out, so it cannot stop a later turn.
|
|
20
|
+
|
|
5
21
|
## 1.5.0-beta.0
|
|
6
22
|
|
|
7
23
|
- Expose `auth.allTokens` for apps enabled server-side, with the three families IAM returns at
|
package/README.md
CHANGED
|
@@ -3,19 +3,17 @@
|
|
|
3
3
|
[](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
|
|
4
4
|
[](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
|
|
5
5
|
|
|
6
|
-
JavaScript
|
|
6
|
+
SDK JavaScript e TypeScript para apps de browser feitos na Mitra: login da pessoa, dados do app, Server Functions, queries, integrações e chats de agente. Para código que roda dentro de uma Server Function, use [`@mitralab.io/functions-sdk`](https://www.npmjs.com/package/@mitralab.io/functions-sdk).
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
## Installation
|
|
8
|
+
## Instalação
|
|
11
9
|
|
|
12
10
|
```bash
|
|
13
11
|
npm install @mitralab.io/platform-sdk
|
|
14
12
|
```
|
|
15
13
|
|
|
16
|
-
|
|
14
|
+
Roda no browser, com as APIs dele (`fetch`, `WebSocket`, `localStorage`). Para desenvolver, Node 18 ou mais novo. Publicado em ESM e CommonJS, com tipos.
|
|
17
15
|
|
|
18
|
-
##
|
|
16
|
+
## Início rápido
|
|
19
17
|
|
|
20
18
|
```typescript
|
|
21
19
|
import { createClient } from "@mitralab.io/platform-sdk"
|
|
@@ -23,564 +21,92 @@ import { createClient } from "@mitralab.io/platform-sdk"
|
|
|
23
21
|
export const mitra = createClient({
|
|
24
22
|
appId: import.meta.env.VITE_MITRA_APP_ID,
|
|
25
23
|
apiUrl: import.meta.env.VITE_MITRA_API_URL,
|
|
26
|
-
onError: (error) => console.error(error.status, error.code, error.message),
|
|
27
24
|
})
|
|
28
25
|
|
|
29
26
|
await mitra.init()
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
`init()` resolves the application's public Code Studio configuration, including nullable
|
|
33
|
-
`dataSourceId`, `allowSignup`, and `emailLoginEnabled`. It also reads the application's brand, which
|
|
34
|
-
does not become a public property: it is what `requestEmailCode()` sends so IAM writes the
|
|
35
|
-
message as the application. The Data Source value remains part of the
|
|
36
|
-
Platform 1.x compatibility flow; native Entities and Custom Queries resolve the current app through
|
|
37
|
-
the authenticated request. Call `init()` during application startup before the compatibility
|
|
38
|
-
sign-up method needs `allowSignup` or the login screen needs `emailLoginEnabled`.
|
|
39
|
-
|
|
40
|
-
## Configuration
|
|
41
|
-
|
|
42
|
-
| Field | Required | Description |
|
|
43
|
-
|---|---|---|
|
|
44
|
-
| `appId` | yes | ID of the published Code Studio application. |
|
|
45
|
-
| `apiUrl` | yes | Base URL of the Mitra API gateway. |
|
|
46
|
-
| `authPageUrl` | no | Absolute URL of `sdk-auth.html`. Falls back to `window.__mitraEnv.authPageUrl`, then `/sdk-auth.html` on the `apiUrl` origin. |
|
|
47
|
-
| `onError` | no | Global callback for API errors. |
|
|
48
|
-
|
|
49
|
-
The client derives service endpoints from `apiUrl`: `/iam`, `/data-manager`, `/functions`, `/integration`, `/copilot`, and `/code-studio`.
|
|
50
|
-
|
|
51
|
-
## Boundary
|
|
52
|
-
|
|
53
|
-
The Platform SDK owns:
|
|
54
|
-
|
|
55
|
-
- browser Google and Microsoft SSO, browser email sign-in, logout, and session refresh
|
|
56
|
-
- trusted session adoption for the embedded app preview
|
|
57
|
-
- session persistence in `localStorage`
|
|
58
|
-
- auth-state listeners
|
|
59
|
-
- proactive token refresh before authenticated native requests
|
|
60
|
-
- one retry after reactive `401` recovery with the current session
|
|
61
|
-
- browser HTTP transport and public application initialization
|
|
62
|
-
- the Copilot WebSocket and HTTP/SSE streams an Agent chat falls back to, and the offline outbox for its prompts
|
|
63
|
-
|
|
64
|
-
`@mitralab.io/sdk-core` owns the shared entities, custom queries, Functions, integrations, Agent task lifecycle and the direct channel to the chat's box, `auth.me`, safe paths, and structural response validation. Server Function code should use `@mitralab.io/functions-sdk` instead of this browser SDK.
|
|
65
|
-
|
|
66
|
-
## Authentication
|
|
67
|
-
|
|
68
|
-
```typescript
|
|
69
|
-
const user = await mitra.auth.signInWithGoogle({ mode: "popup" })
|
|
70
|
-
|
|
71
|
-
const unsubscribe = mitra.auth.onAuthStateChange((currentUser) => {
|
|
72
|
-
console.log(currentUser?.email)
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
mitra.auth.signOut("/login")
|
|
76
|
-
unsubscribe()
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
Authentication state is stored under `mitra_auth_{appId}`. Before each authenticated native request, the SDK checks a JWT's `exp` claim with a 30-second safety window and refreshes directly through IAM when needed. Opaque tokens, malformed JWTs, and JWTs without a numeric `exp` remain server-authoritative and proceed to the request. A `401` still triggers reactive recovery and at most one retry. If another login or bridged session replaced the token while the request was in flight, the retry uses that current token without refreshing its session. If sign-out cleared the token, the old `401` neither refreshes nor retries.
|
|
80
|
-
|
|
81
|
-
A generated application signs people in with Google SSO, Microsoft SSO, or email. The old native `signIn` and `signUp` names fail locally with `UNSUPPORTED_AUTH_METHOD` because IAM has no email/password endpoints; `signInWithEmail()` is the email flow that replaced them. Deprecated login bindings remain available only through the legacy reexports.
|
|
82
|
-
|
|
83
|
-
### Signing in as a process
|
|
84
|
-
|
|
85
|
-
Google and Microsoft SSO both need a person to complete a redirect. A process that runs on its own -
|
|
86
|
-
a cron, a background collector, another service - signs in with an api key created in
|
|
87
|
-
**Settings -> API keys**:
|
|
88
|
-
|
|
89
|
-
```typescript
|
|
90
|
-
const mitra = createClient({ appId, apiUrl, apiKey: process.env.MITRA_API_KEY })
|
|
91
|
-
|
|
92
|
-
await mitra.auth.signInWithApiKey()
|
|
93
|
-
```
|
|
94
27
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
key adds authoring. An **Administrator** key belongs to a workspace rather than a product; the SDK
|
|
98
|
-
issues this app's token from it, and the platform decides on that call what the key's owner
|
|
99
|
-
actually reaches here, so the key never widens anyone's access.
|
|
100
|
-
|
|
101
|
-
This session is not written to storage and carries no refresh token. The key does not expire and is
|
|
102
|
-
revoked by deleting it, so renewing means signing in again rather than holding a second secret.
|
|
103
|
-
|
|
104
|
-
**Server runtimes only.** In a browser the key would be served to every visitor inside the bundle,
|
|
105
|
-
so the method refuses to run when a `window` exists.
|
|
106
|
-
|
|
107
|
-
An embedded preview can adopt the app-scoped session it receives from the platform without exchanging it:
|
|
108
|
-
|
|
109
|
-
```typescript
|
|
110
|
-
mitra.auth.setSession({ accessToken, refreshToken })
|
|
111
|
-
await mitra.auth.checkAuth()
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
Proactive and reactive callers share one in-flight refresh. Successful refresh rotates and persists both tokens and updates the legacy session bridge without calling `auth.me()` or notifying public auth-state listeners. A refresh response that arrives after sign-out or after another login/session replacement is discarded and cannot restore or overwrite that newer state. Network failures, `408`, `429`, and `5xx` responses preserve the current session; the original HTTP request proceeds with the current token so a later `401` can use the reactive fallback. `auth.me()` also preserves that retained session when the fallback refresh is transient. Other IAM `4xx` responses are definitive and clear the session.
|
|
115
|
-
|
|
116
|
-
JWT decoding is not user authentication. It schedules refresh and prevents cross-app session adoption. Every decodable access and refresh token must contain `app_id` exactly equal to the client's configured `appId`; opaque tokens are kept for rollout compatibility and remain validated by the server.
|
|
117
|
-
|
|
118
|
-
Custom WebSocket or Server-Sent Events boundaries can refresh explicitly before connecting:
|
|
119
|
-
|
|
120
|
-
```typescript
|
|
121
|
-
const fresh = await mitra.auth.ensureFreshSession(30_000)
|
|
122
|
-
|
|
123
|
-
if (!fresh) {
|
|
124
|
-
// A required refresh failed. The SDK may still retain the session after a
|
|
125
|
-
// transient failure, but this boundary can choose whether to connect.
|
|
28
|
+
if (!mitra.auth.isAuthenticated) {
|
|
29
|
+
await mitra.auth.signInWithGoogle({ mode: "popup" })
|
|
126
30
|
}
|
|
127
|
-
```
|
|
128
31
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
Google SSO uses a popup by default. The SDK opens `sdk-auth.html`, validates the popup source, origin, and one-time state, exchanges the returned code directly with IAM, stores both tokens, and fetches the current user:
|
|
132
|
-
|
|
133
|
-
```typescript
|
|
134
|
-
const user = await mitra.auth.signInWithGoogle({ mode: "popup" })
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
The public Google options contain only `mode`. Account creation and locale are producer concerns, so the SDK does not send `create` or `language` to IAM. During rollout, the popup also accepts the older auth page token response.
|
|
138
|
-
|
|
139
|
-
Deprecated `LoginOptions` still preserve `returnTo` and `title` for source compatibility. They are not copied into the new Google API: the legacy runtime never read `title`, did not pass caller `returnTo` into popup login, and hardcoded the current URL for redirect login.
|
|
140
|
-
|
|
141
|
-
Redirect mode stores the one-time state and options in `sessionStorage`. Complete it during application startup before rendering authenticated routes:
|
|
142
|
-
|
|
143
|
-
```typescript
|
|
144
|
-
const redirectedUser = await mitra.auth.completeGoogleSignInRedirect()
|
|
145
|
-
|
|
146
|
-
if (!redirectedUser) {
|
|
147
|
-
await mitra.auth.signInWithGoogle({ mode: "redirect" })
|
|
148
|
-
}
|
|
32
|
+
const { data: tasks } = await mitra.entities.Task.list({ sort: "-created_at", limit: 10 })
|
|
149
33
|
```
|
|
150
34
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
Configure the auth page explicitly when it is hosted outside the API gateway origin:
|
|
35
|
+
No app gerado pelo Code Studio, `VITE_MITRA_APP_ID` e `VITE_MITRA_API_URL` já vêm preenchidos no build.
|
|
154
36
|
|
|
155
|
-
|
|
156
|
-
const mitra = createClient({
|
|
157
|
-
appId,
|
|
158
|
-
apiUrl,
|
|
159
|
-
authPageUrl: "https://app.example.com/sdk-auth.html",
|
|
160
|
-
})
|
|
161
|
-
```
|
|
37
|
+
## O que dá para fazer
|
|
162
38
|
|
|
163
|
-
|
|
39
|
+
- `auth`: login com Google (`signInWithGoogle`), Microsoft (`signInWithMicrosoft`) ou código por e-mail, mais `currentUser`, `onAuthStateChange` e `signOut`.
|
|
40
|
+
- `entities.<Tabela>`: `list`, `filter`, `get`, `create`, `bulkCreate`, `update`, `delete` e `deleteMany` nas tabelas do app.
|
|
41
|
+
- `queries.execute(id, params)`: roda uma query salva no app.
|
|
42
|
+
- `functions`: `execute` espera o resultado da Server Function; `executeAsync` devolve a execução para acompanhar com `getExecution` ou parar com `cancelExecution`. `publicFunctions` chama as Functions publicadas como públicas, sem login.
|
|
43
|
+
- `integration.executeByAlias(alias, request)`: chama uma API externa configurada no app. A credencial do provedor fica na Mitra e não passa pelo browser.
|
|
44
|
+
- `agentTasks.session(...)`: chat com agente, com `send`, `sendAndWait`, `cancel` e eventos como `delta`, `turnEnd` e `error`.
|
|
45
|
+
- `agentCredentials`: credenciais de provedor de IA e modelos disponíveis.
|
|
164
46
|
|
|
165
|
-
|
|
47
|
+
Login por código no e-mail, para quem monta a própria tela:
|
|
166
48
|
|
|
167
49
|
```typescript
|
|
168
|
-
const
|
|
169
|
-
const
|
|
170
|
-
const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken
|
|
50
|
+
const { receipt } = await mitra.auth.requestEmailCode({ email })
|
|
51
|
+
const user = await mitra.auth.verifyEmailCode({ receipt, code })
|
|
171
52
|
```
|
|
172
53
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
- `platform`: an IAM session pair (`accessToken`, `refreshToken`, `tokenType`) in the workspace IAM chose for the person.
|
|
176
|
-
- `mitraSpace`: a mitraSpace token (`token`, `tokenType`). It lasts for decades and has no refresh flow.
|
|
177
|
-
- `b2bToken`: an IAM session pair for the same person in the IAM of another environment, with the same shape as `platform`.
|
|
178
|
-
|
|
179
|
-
`platform` and `b2bToken` are sessions of one hour. The SDK refreshes only the app token: each app refresh brings a new `platform`, while `b2bToken` comes from login alone, so the app renews it itself with `POST {iam of that environment}/api/v1/auth/refresh-token`, sending only its `refreshToken`. The SDK does not store what that call returns. On an app refresh, `platform` is replaced by what IAM sent, `null` included; `mitraSpace` and `b2bToken`, which IAM sends as `null` there on purpose, keep the values issued at login; a refresh without the field clears it, because IAM omits it whenever the app is not entitled to these tokens and a stored one-hour pair would expire unnoticed. A new login, `setSession`, `setToken`, or a legacy login replaces the session and resets the field; the silent token refresh of the legacy SDK keeps it when the renewed token belongs to the same person, and resets it otherwise. Auth-state listeners are not notified when only these tokens change, so read them right before use. The returned objects are frozen: keep a renewed `b2bToken` in your own state instead of writing it back. After a reload, the `b2bToken` pair available is the one issued at login: the SDK neither renews nor expires it, so a `401` from the peer means the person has to sign in again. `platform` is renewed only by this SDK's app refresh; the silent rotation through the legacy bridge keeps whatever was stored when the renewed token belongs to the same person.
|
|
180
|
-
|
|
181
|
-
These tokens are not checked against `appId`: they are issued for other scopes and stay validated by the server that receives them.
|
|
182
|
-
|
|
183
|
-
**Security note.** These tokens reach more than the app session: `platform` and `b2bToken` act as the person on IAM endpoints the app token cannot reach, and the mitraSpace token lives for decades. `b2bToken` carries the widest exposure: it is the person's session in another environment, the production of the Mitra brand, kept on the origin of an app that runs in a different environment. All three are stored with the rest of the session in `localStorage` under `mitra_auth_{appId}`, so any script running on the application origin can read them. They are persisted, instead of held in memory, because IAM issues `mitraSpace` and `b2bToken` only at login, and `platform` only at login and on refresh: without persistence, a reload would leave `platform` `null` until the next refresh and the other two until the next sign-in. The SDK only carries what IAM sent: the flag is turned on per app in IAM, so whoever enables it there decides which app origins hold these sessions. `signOut()` removes them.
|
|
184
|
-
|
|
185
|
-
### Signing in with email
|
|
186
|
-
|
|
187
|
-
Email sign-in needs neither a password nor an SSO account, and the application
|
|
188
|
-
never has to send anyone to a platform screen. It renders its own address and
|
|
189
|
-
code fields, IAM sends a message branded as the app, and the link in that
|
|
190
|
-
message comes back to the application's own origin:
|
|
54
|
+
Chat com agente:
|
|
191
55
|
|
|
192
56
|
```typescript
|
|
193
|
-
const
|
|
194
|
-
|
|
57
|
+
const chat = mitra.agentTasks.session({ taskId })
|
|
58
|
+
chat.on("delta", ({ delta, kind }) => {
|
|
59
|
+
if (kind === "text") render(delta)
|
|
195
60
|
})
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
```
|
|
199
|
-
|
|
200
|
-
`requestEmailCode()` answers the same way whatever the address is, so nothing in
|
|
201
|
-
it says whether that person already exists. The `receipt` names the request when
|
|
202
|
-
the code comes back; it is not a credential and authorizes nothing on its own.
|
|
203
|
-
Resending is calling `requestEmailCode()` again, which replaces the request in
|
|
204
|
-
flight; `resendAfterSeconds` is how long to wait before offering that.
|
|
205
|
-
|
|
206
|
-
The message is written in `pt-BR` or `en`. Pass `language` to choose; without it
|
|
207
|
-
the SDK reads the browser's language and falls back to `pt-BR`.
|
|
208
|
-
|
|
209
|
-
`requestEmailCode()` needs `init()` to have run, because the message is branded
|
|
210
|
-
with the app's own brand, read from `/info`. Calling it before that fails with
|
|
211
|
-
`INVALID_CONFIGURATION` rather than sending a message branded at random.
|
|
212
|
-
`mitra.emailLoginEnabled`, read from the same `/info`, is this app's own verdict
|
|
213
|
-
about the rollout, and it is what a login screen should offer the option on:
|
|
214
|
-
|
|
215
|
-
```typescript
|
|
216
|
-
await mitra.init()
|
|
217
|
-
|
|
218
|
-
if (mitra.emailLoginEnabled) {
|
|
219
|
-
// render the email field
|
|
220
|
-
}
|
|
61
|
+
const { content } = await chat.sendAndWait("Resuma os pedidos de hoje")
|
|
62
|
+
chat.close()
|
|
221
63
|
```
|
|
222
64
|
|
|
223
|
-
|
|
224
|
-
field or with something that is not a boolean, and `false` is the safe answer:
|
|
225
|
-
the app is outside the rollout, IAM answers a request neutrally without sending
|
|
226
|
-
anything, and the person would wait for a message that never arrives. Calling
|
|
227
|
-
the email methods anyway is not blocked by the SDK; the verdict is there so the
|
|
228
|
-
application does not offer a door that does not open.
|
|
229
|
-
|
|
230
|
-
#### The link in the message
|
|
65
|
+
## Configuração
|
|
231
66
|
|
|
232
|
-
|
|
233
|
-
`#emailToken=<token>`. Complete it during application startup, before rendering
|
|
234
|
-
authenticated routes:
|
|
235
|
-
|
|
236
|
-
```typescript
|
|
237
|
-
const emailUser = await mitra.auth.completeEmailSignInRedirect()
|
|
238
|
-
```
|
|
239
|
-
|
|
240
|
-
The token travels in the fragment, so it never reaches a server other than the
|
|
241
|
-
one this SDK sends it to. The SDK inspects the link first, without consuming it,
|
|
242
|
-
and spends it only when IAM reports the origin the page is on and the one-time
|
|
243
|
-
state of the request pending in this browser. That pending request is written by
|
|
244
|
-
`requestEmailCode()` to `localStorage` under `mitra_email_redirect_{appId}`, for
|
|
245
|
-
10 minutes:
|
|
246
|
-
|
|
247
|
-
```json
|
|
248
|
-
{ "state": "email.<random>", "redirectUri": "https://app.example.com", "createdAt": 0 }
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
**No token is written there.** What is persisted is only the record of a request
|
|
252
|
-
already in flight, which is the smallest thing that lets the tab the link opens
|
|
253
|
-
finish it, and it expires on its own. Writing it is best effort: without
|
|
254
|
-
`localStorage` the code typed into the application still signs in and only the
|
|
255
|
-
completion from the link is lost.
|
|
256
|
-
|
|
257
|
-
**The link has to be opened in the same browser that asked for the message.**
|
|
258
|
-
Another browser or device has no pending request, so the SDK consumes nothing,
|
|
259
|
-
returns `null`, and the link stays valid for the person who asked. The same
|
|
260
|
-
answer protects against a scanner that opens links on their way to a mailbox. On
|
|
261
|
-
another device, type the six-digit code instead.
|
|
262
|
-
|
|
263
|
-
Only `emailToken` is taken out of the URL. The rest of the fragment is left
|
|
264
|
-
exactly as it was found, so an application that routes on it keeps its route.
|
|
265
|
-
|
|
266
|
-
`completeEmailSignInRedirect()` returns `null` when the URL carries no sign-in
|
|
267
|
-
result, when it carries one belonging to another method's flow, and when it
|
|
268
|
-
carries a link this browser cannot claim. A link that does belong here but
|
|
269
|
-
cannot be used is reported as a `MitraApiError`:
|
|
270
|
-
|
|
271
|
-
| Code | Status | What happened |
|
|
67
|
+
| Campo | Obrigatório | Uso |
|
|
272
68
|
|---|---|---|
|
|
273
|
-
| `
|
|
274
|
-
| `
|
|
275
|
-
| `
|
|
276
|
-
|
|
277
|
-
`
|
|
278
|
-
and the same `MAGIC_LINK_EXPIRED` and `MAGIC_LINK_USED` when the request is
|
|
279
|
-
over. Both methods report `RATE_LIMITED` (429) when IAM asks the person to slow
|
|
280
|
-
down, and `SIGNUP_NOT_ALLOWED`, `APP_ACCESS_REQUIRED`, `APP_ACCESS_REVOKED`
|
|
281
|
-
(403) or `APP_ACCESS_LIMIT_REACHED` (409) when this app does not admit that
|
|
282
|
-
address. A `429` carries `error.retryAfterSeconds` when the gateway exposes
|
|
283
|
-
`Retry-After`, and `null` when it does not.
|
|
284
|
-
|
|
285
|
-
`requestEmailCode()` also reports `INVALID_ORIGIN` (400) when the page asking
|
|
286
|
-
for the message is not on one of the origins published for this application, and
|
|
287
|
-
both methods report `VALIDATION_FAILED` (400) for a field IAM refuses to read,
|
|
288
|
-
such as a malformed address or a code that is not six digits.
|
|
69
|
+
| `appId` | sim | ID do app no Code Studio |
|
|
70
|
+
| `apiUrl` | sim | URL do API gateway da Mitra |
|
|
71
|
+
| `onError` | não | callback com o `MitraApiError` das falhas de `entities`, `queries`, `functions`, `integration`, `agentTasks` e `agentCredentials`; `init()`, login, `publicFunctions` e falha de rede não passam por ele e são tratados no `catch` de cada chamada |
|
|
72
|
+
| `authPageUrl` | não | URL da página de login da Mitra; sem ela, o SDK descobre sozinho |
|
|
73
|
+
| `apiKey` | não | chave padrão de `auth.signInWithApiKey()`; só em código de servidor, nunca no bundle do browser |
|
|
289
74
|
|
|
290
|
-
|
|
75
|
+
## Erros
|
|
291
76
|
|
|
292
|
-
`
|
|
293
|
-
SSO opens collects the address and the code, and the single-use exchange code it
|
|
294
|
-
returns is redeemed at `/iam/api/v1/auth/magic-link/exchange` for the same app
|
|
295
|
-
session:
|
|
77
|
+
Falhas de API lançam `MitraApiError`, com `status`, `code`, `details` e `retryAfterSeconds`. O SDK mascara o token da sessão, credenciais `Bearer` e campos com nome sensível, como `password` ou `apiKey`, em `details`. Texto livre fora disso, como `password=...` dentro de uma mensagem, passa como veio: não trate mensagem e detalhes como saneados antes de mandar para log.
|
|
296
78
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
Both come back as `#codeMitra` and `#stateMitra`, and are completed by the same
|
|
309
|
-
`completeEmailSignInRedirect()` at startup. The message that page sends carries a
|
|
310
|
-
link too, which opens a **new tab** that never saw the popup, so the pending
|
|
311
|
-
request is written before the popup opens, for the same 10 minutes and under the
|
|
312
|
-
same key. `sessionStorage`, which the SSO redirect uses, is scoped to a single
|
|
313
|
-
tab and cannot answer for another one. Writing the request is best effort for a
|
|
314
|
-
popup: without `localStorage` the popup still signs in and only the completion
|
|
315
|
-
from the link is lost, while redirect mode, which has nowhere else to keep it,
|
|
316
|
-
fails at the start.
|
|
317
|
-
|
|
318
|
-
When the person finishes in the tab the link opened, the `signInWithEmail()`
|
|
319
|
-
call still waiting in the original tab eventually times out. Treat that
|
|
320
|
-
rejection as a cancelled popup: the session is already established wherever the
|
|
321
|
-
application called `completeEmailSignInRedirect()`.
|
|
322
|
-
|
|
323
|
-
#### One fragment, one flow
|
|
324
|
-
|
|
325
|
-
An application that offers more than one method can call every completion at
|
|
326
|
-
startup, in any order:
|
|
327
|
-
|
|
328
|
-
```typescript
|
|
329
|
-
const user =
|
|
330
|
-
(await mitra.auth.completeEmailSignInRedirect()) ??
|
|
331
|
-
(await mitra.auth.completeGoogleSignInRedirect()) ??
|
|
332
|
-
(await mitra.auth.completeMicrosoftSignInRedirect())
|
|
333
|
-
```
|
|
334
|
-
|
|
335
|
-
A chain like that propagates a rejection: an expired request or a forged
|
|
336
|
-
fragment on the first completion keeps the others from running. Wrap each call
|
|
337
|
-
in `try`/`catch` when the application should still try the remaining methods
|
|
338
|
-
after one of them refuses a fragment.
|
|
339
|
-
|
|
340
|
-
The one-time state each flow generates names that flow, as in `google.<random>`
|
|
341
|
-
or `email.<random>`, and the auth page echoes it verbatim, so a completion
|
|
342
|
-
recognizes its own fragment. A fragment from another method returns `null` and
|
|
343
|
-
leaves the fragment and that other flow's pending request untouched, whatever
|
|
344
|
-
this browser has pending. A fragment that does name this flow but does not match
|
|
345
|
-
its pending request is rejected as forged, and the fragment is removed from the
|
|
346
|
-
URL on the way out, so the rejection is reported once instead of on every
|
|
347
|
-
reload.
|
|
348
|
-
|
|
349
|
-
## Entities
|
|
350
|
-
|
|
351
|
-
```typescript
|
|
352
|
-
type Task = {
|
|
353
|
-
id: string
|
|
354
|
-
title: string
|
|
355
|
-
status: "pending" | "done"
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
const { data: tasks } = await mitra.entities.getTable<Task>("Task").list({
|
|
359
|
-
sort: "-created_at",
|
|
360
|
-
limit: 10,
|
|
361
|
-
fields: ["id", "title", "status"],
|
|
362
|
-
})
|
|
363
|
-
|
|
364
|
-
const pending = await mitra.entities.Task.filter({ status: "pending" })
|
|
365
|
-
const created = await mitra.entities.Task.create({ title: "New task" })
|
|
366
|
-
await mitra.entities.Task.update(created.id, { status: "done" })
|
|
367
|
-
await mitra.entities.Task.delete(created.id)
|
|
368
|
-
```
|
|
369
|
-
|
|
370
|
-
Table names are case-sensitive and must match the Data Manager table name. Record operations use `/api/v1/tables/{table}/records`. Application and tenant scope come from the authenticated context, not from a data source in the path.
|
|
371
|
-
|
|
372
|
-
The native producer does not accept `jdbcConnectionConfigId` or `dataSourceId` on public record requests. The deprecated record helpers still expose their legacy arguments, but there is no native equivalent until Data Manager defines an app-safe backend contract. The SDK does not translate those arguments into query parameters or SQL.
|
|
373
|
-
|
|
374
|
-
`update(id, fields)` sends the Data Manager PUT contract, which applies the supplied fields as a partial record update and preserves omitted fields. A separate `patch` alias would duplicate that producer behavior, so the native surface keeps one method.
|
|
375
|
-
|
|
376
|
-
## Server Functions
|
|
377
|
-
|
|
378
|
-
```typescript
|
|
379
|
-
const execution = await mitra.functions.execute("function-id", {
|
|
380
|
-
orderId: "order-123",
|
|
381
|
-
})
|
|
382
|
-
|
|
383
|
-
console.log(execution.id, execution.status)
|
|
384
|
-
```
|
|
385
|
-
|
|
386
|
-
`execute` sends `X-Invocation-Type: sync` and waits for the terminal result. `executeAsync` sends `async` and returns the initial execution for polling or cancellation.
|
|
387
|
-
|
|
388
|
-
The complete native lifecycle is also available. `getExecution` is kept because the Functions producer exposes execution polling and Agent consumers use it:
|
|
389
|
-
|
|
390
|
-
```typescript
|
|
391
|
-
const queued = await mitra.functions.executeAsync("function-id", { orderId: "order-123" })
|
|
392
|
-
const current = await mitra.functions.getExecution(queued.id)
|
|
393
|
-
await mitra.functions.cancelExecution(current.id)
|
|
394
|
-
```
|
|
395
|
-
|
|
396
|
-
Public Functions use a separate anonymous transport. It never adds `Authorization` or `X-App-Id`:
|
|
397
|
-
|
|
398
|
-
```typescript
|
|
399
|
-
const result = await mitra.publicFunctions.execute("public-function-id", { sku: "A-1" })
|
|
400
|
-
const queuedPublic = await mitra.publicFunctions.executeAsync("public-function-id", { sku: "A-1" })
|
|
401
|
-
```
|
|
402
|
-
|
|
403
|
-
Public async execution is fire-and-forget. The public API does not expose anonymous polling or
|
|
404
|
-
cancellation. Use synchronous `publicFunctions.execute` when the screen needs the result, or the
|
|
405
|
-
authenticated `functions.executeAsync` plus `functions.getExecution` flow after login.
|
|
406
|
-
|
|
407
|
-
## Agent tasks and credentials
|
|
408
|
-
|
|
409
|
-
The browser-safe Copilot modules call the native service directly. `agentTasks` provides list, read, create, rename, archive, HTTP input, history, and live sessions. These direct primitives match the Copilot producer and MCP contract. Core owns session state, queueing, recovery, reconciliation, and the direct channel to the chat's box; Platform supplies the authenticated Copilot WebSocket/SSE streams a chat falls back to and the offline outbox. `agentCredentials` provides safe credential status, model discovery, API key, OAuth, and device authorization flows. Raw credentials are write-only.
|
|
410
|
-
|
|
411
|
-
```typescript
|
|
412
|
-
const credentials = await mitra.agentCredentials.list()
|
|
413
|
-
const models = await mitra.agentCredentials.listModels()
|
|
414
|
-
const chats = await mitra.agentTasks.list({ archived: false, size: 20 })
|
|
415
|
-
```
|
|
416
|
-
|
|
417
|
-
Create a live task lazily on the first message. `agentId` names the business agent the chat belongs to; without it the chat is a plain Copilot chat:
|
|
418
|
-
|
|
419
|
-
```typescript
|
|
420
|
-
const session = mitra.agentTasks.session({
|
|
421
|
-
create: true,
|
|
422
|
-
agentId,
|
|
423
|
-
agentType: models[0].agentType,
|
|
424
|
-
reasoningEffort: models[0].reasoningOptions[0],
|
|
425
|
-
})
|
|
426
|
-
|
|
427
|
-
const unsubscribe = session.on("delta", ({ delta, kind }) => {
|
|
428
|
-
console.log(kind, delta)
|
|
429
|
-
})
|
|
430
|
-
|
|
431
|
-
session.send("Analyze this application")
|
|
432
|
-
session.respondApproval(true)
|
|
433
|
-
await session.cancel()
|
|
434
|
-
unsubscribe()
|
|
435
|
-
session.close()
|
|
436
|
-
```
|
|
437
|
-
|
|
438
|
-
A business agent's chat (`create: true` with an `agentId`) is born on the T3 box (`runtime: "T3"` in the create request) whenever the session can reach the box, over any transport, `http` included, so the first open does not wait for the box to adopt it. A chat without `agentId` is created without `runtime` and never asks for the direct channel: the Copilot refuses T3 outside an agent chat (`RUNTIME_REQUIRES_AGENT_APP`). Pass `runtime: "RUNNER"` or `runtime: "T3"` to decide explicitly.
|
|
439
|
-
|
|
440
|
-
`session({ create: true, agentId, scope: "ACCOUNT" })` and `agentTasks.create({ agentType, agentId, scope: "ACCOUNT" })` send `scope` in the create body, so the chat runs on the credential the person connected to their own account, the one the IDE and the builder read, instead of the agent's connection. The Copilot honors `ACCOUNT` only for apps listed by flag and answers `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise; a turn without a credential on the account fails with `ACCOUNT_CREDENTIAL_MISSING`. Through `agentTasks.session(...)` those refusals reach the session `error` event with the message and code the Copilot sends; through `agentTasks.create()` and the `agentCredentials` methods they reject the promise with a `MitraApiError` carrying status and code. No platform session is involved: the app token is used as always. Without `scope` nothing changes.
|
|
441
|
-
|
|
442
|
-
Open an existing task with `session({ taskId })`. A session on a business agent's chat (a task with an `agentId`) asks the Copilot once where the chat is served (`POST /copilot/api/v1/tasks/{taskId}/channel`) and talks to the box that runs the agent when one is offered; any other chat never asks and stays on the Copilot stream described below. This direct channel lives in `@mitralab.io/sdk-core` (0.2.9 and later); this package passes it the API URL and nothing else, so the rules below are Core's. The Copilot holds that request while the box boots and answers only once the box is ready or cannot be had; the SDK does not poll. The choice belongs to the server, never to application configuration, so a Copilot that stops offering the box leaves every application on the Copilot stream without a republish.
|
|
443
|
-
|
|
444
|
-
- **Transport.** `auto`, the default, uses the box socket in the browser. `websocket` uses the box socket. `http` uses the box's HTTP routes next to the socket path (`POST .../api/mitra/chat/messages` to send, `GET .../api/mitra/chat/events` as SSE to read), for browsers or proxies where WebSockets are unavailable; before 1.3.0 it meant the Copilot SSE, which is now only its fallback. A business agent's new chat is created with `runtime: "T3"` so it is born on its box, unless the session names a runtime.
|
|
445
|
-
- **Host rule.** The box is followed only when its address is on the API host (proxy mode, `/__ide/<box>/...`) or on a fleet box host over `wss:` (direct mode, `<port>-<box>.e2b.app` or `<port>-<box>.e2b-<fleet>.mitralab.ai`), the same allowlist the gateway trusts on `/__ide`.
|
|
446
|
-
- **Fallback, always visible.** When the Copilot offers no box (a `202` or an error), the body has no address, the host is outside the rule, the box cannot be reached, or the box has no HTTP routes, the chat follows the Copilot stream (`/copilot/ws/tasks/{taskId}`, falling back to `/copilot/api/v1/tasks/{taskId}/events` for `auto`) and the session first emits a `raw` event of type `channelDeclined` with `reason` `unavailable`, `body`, `host`, `websocket` or `http_unsupported` (and `host` or `error` when known). A channel request that fails is not reported to the client's global `onError`: it is not an error for the application.
|
|
447
|
-
- **Sending.** On the box, the message and the interrupt go to the box itself, as the frames it reads from a client: `{ "type": "message", "content", "agentType"?, "reasoningEffort"? }` and `{ "type": "interrupt" }`. The box asks the Copilot to admit the turn and the Copilot records the history. The session emits `accepted` once the box starts the admitted turn, or once the Copilot accepts a REST send; a message the box refuses surfaces through the `error` event with the box's code, and a box that confirms nothing within 35 seconds fails the send. `POST /copilot/api/v1/tasks/{taskId}/inputs` is the path when there is no box wire: a chat on the Copilot stream, a box wire that is down at the moment of the send (a drop being redialed included), and every approval answer. A message whose wire drops before the box answers is not sent again over REST, because the box may already have admitted the turn; the redial replays the box log.
|
|
448
|
-
- **Drops.** Opening the box never asks it to replay: what an idle chat missed is history, which the application loads over REST. A box wire that drops in the middle of a turn is redialed with a bounded backoff (1, 2, 4, 8 and 16 seconds) and the replay from the last position seen on that box, so the answer keeps streaming; replayed `textChunk` frames reach the `delta` event like live text. While that happens the session emits `raw` events of type `channelReconnecting` (payload `attempt`, `maxAttempts`, `reason`) and `channelConnected` (payload `attempt`); the session `status` stays `streaming`. The disconnect reaches the session, and with it the `error` event, only when the attempts run out or the Copilot no longer offers the box. A drop with no turn in flight, a channel taken over by another tab (close code 4409), and any close of the Copilot socket the session did not ask for are reported at once, so the next send reopens the channel. Recovery through persisted history is unchanged.
|
|
449
|
-
|
|
450
|
-
Messages sent during a turn enter a FIFO queue with a maximum of 10 items; the session also exposes edit, remove, clear, approval, cancel, history, close, and typed events.
|
|
451
|
-
|
|
452
|
-
A prompt sent while the browser says it is offline (`navigator.onLine === false`) does not enter Core at all, because Core opens the channel and reads the turn baseline before the prompt goes out and every one of those requests would fail first: the session keeps the prompt in an outbox, emits a `raw` event of type `inputUnsent` (payload `attempt` 0, `reason`, `waitingForOnline` true) and hands it to Core, in order, when the browser fires `online`; the turn starts then. A prompt whose `POST /inputs` went out but got no response at all is kept the same way: the session sends the same request again when the browser fires `online` or on a bounded backoff (2, 5, 10, 20 and 40 seconds), while the turn stays `streaming`, with `inputUnsent` events (payload `attempt`, `reason`, `waitingForOnline`, `retryInMs` when a timer is armed) and, once it goes through, `inputSent` (payload `attempts`). A response from the server, an error included, is never retried: the prompt fails through the `error` event as before. A session closed with a prompt still waiting emits `error` with code `INPUT_UNSENT` before it goes quiet, and `sendAndWait` rejects. The retry cannot tell a request the server never received from one whose response was lost on the way back, so a prompt may reach the server twice in that case; the Copilot's `/inputs` accepts no client message id yet. The public `agentTasks.sendInput` primitive is not held back: it fails immediately, as it always did.
|
|
453
|
-
|
|
454
|
-
API keys and removal accept `ANTHROPIC` or `OPENAI`. OAuth accepts only `ANTHROPIC`; device authorization accepts only `OPENAI`. The facade enforces those producer-supported pairs in TypeScript and at runtime.
|
|
455
|
-
|
|
456
|
-
Every `agentCredentials` method takes a trailing `options` with `scope: "ACCOUNT"`, sent as the `scope` query parameter, so the credential is read from or written to the person's own account instead of the app: `startOAuth("ANTHROPIC", { scope: "ACCOUNT" })`, `exchangeOAuth("ANTHROPIC", input, { scope: "ACCOUNT" })`, `list({ scope: "ACCOUNT" })`. The Copilot honors `ACCOUNT` only for apps listed by flag and answers `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise. No platform session is involved: the app token is used as always. Without `options` the request is the same as before.
|
|
457
|
-
|
|
458
|
-
A custom provider the person adds by API is a credential like the others, managed on `/api/v1/credentials/custom-providers` with the same trailing `options`: `listCustomProviders({ scope: "ACCOUNT" })` returns the person's OpenAI-compatible providers with the API key masked, `createCustomProvider({ name, baseUrl, apiKey, models }, { scope: "ACCOUNT" })` adds one under a name the person chooses and returns the list after creation, and `deleteCustomProvider(id, { scope: "ACCOUNT" })` removes it for good. The API key is write-only and `models` takes 1 to 32 model ids; each joins the catalog `listModels()` returns as `custom/<providerId>/<model>`, and a chat runs on one of them by sending the `agentType` that catalog row returns, the same way a built-in model is chosen. The Copilot requires `scope: "ACCOUNT"` on an app token. The three methods take no provider argument and no provider guard applies.
|
|
459
|
-
|
|
460
|
-
The subscription usage, the meters behind the bar the IDE shows for a Claude or ChatGPT login, is readable with no chat open: `usage("ANTHROPIC")` (or `"OPENAI"`, with the same trailing `options`) resolves to `{ harness, observedAt, status, windows: [{ kind, usedPercent, resetsAt, windowSeconds }] }`, the last reading a chat on that credential reported, or `null` while none has. `windows` carries every window the provider reports (Claude: `FIVE_HOUR`, `WEEKLY`, `WEEKLY_OPUS` and any other it sends; Codex: primary and secondary, named by duration) and `status` is the provider's own (Claude: `allowed`, `allowed_warning`, `rejected`). Only a turn on the person's own subscription login, or the agent connection's, reports a window; an API key, a custom provider and the included AI never do. During a turn on the box the session emits the same reading live, in the same shape, as `providerUsage`, and the Copilot keeps it for the next `usage()`:
|
|
461
|
-
|
|
462
|
-
```typescript
|
|
463
|
-
session.on("providerUsage", ({ status, windows }) => console.log(status, windows))
|
|
464
|
-
const usage = await mitra.agentCredentials.usage("ANTHROPIC")
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
The browser token roles expose Agent tasks, credential status, and model discovery. Administrative business-Agent CRUD is intentionally not exposed by this adapter because the `USE` app role does not carry `AGENT_*` authority.
|
|
468
|
-
|
|
469
|
-
## Custom queries
|
|
470
|
-
|
|
471
|
-
```typescript
|
|
472
|
-
const result = await mitra.queries.execute("query-id", {
|
|
473
|
-
status: "active",
|
|
474
|
-
})
|
|
475
|
-
|
|
476
|
-
console.log(result.rows, result.affectedRows)
|
|
477
|
-
```
|
|
478
|
-
|
|
479
|
-
Custom Query execution sends only `parameters`. Data Manager resolves its Data Source from the
|
|
480
|
-
authenticated app, so Queries work without a caller-selected `dataSourceId` and do not depend on
|
|
481
|
-
`init()`.
|
|
482
|
-
|
|
483
|
-
## Integrations
|
|
484
|
-
|
|
485
|
-
List the current app's saved configs without exposing the Core admin module:
|
|
486
|
-
|
|
487
|
-
```typescript
|
|
488
|
-
const configs = await mitra.integration.list({ page: 0, size: 20, sort: "alias,asc" })
|
|
489
|
-
```
|
|
490
|
-
|
|
491
|
-
The Integration producer derives the app from the authenticated token, so this list is app-scoped. A listed config carries `templateId: null` when it was created from an inline definition instead of a catalog template.
|
|
492
|
-
|
|
493
|
-
Execute a predefined resource:
|
|
494
|
-
|
|
495
|
-
```typescript
|
|
496
|
-
const result = await mitra.integration.executeResource("resource-id", {
|
|
497
|
-
description: "Notebook",
|
|
498
|
-
limit: 10,
|
|
499
|
-
})
|
|
500
|
-
```
|
|
501
|
-
|
|
502
|
-
Or execute an integration config directly:
|
|
503
|
-
|
|
504
|
-
```typescript
|
|
505
|
-
const result = await mitra.integration.execute("config-id", {
|
|
506
|
-
method: "GET",
|
|
507
|
-
endpoint: "/users",
|
|
508
|
-
queryParams: { limit: "10" },
|
|
509
|
-
})
|
|
510
|
-
|
|
511
|
-
console.log(result.status, result.body)
|
|
512
|
-
```
|
|
513
|
-
|
|
514
|
-
An app can also address a saved config by its app-scoped alias:
|
|
515
|
-
|
|
516
|
-
```typescript
|
|
517
|
-
const result = await mitra.integration.executeByAlias("billing", {
|
|
518
|
-
method: "POST",
|
|
519
|
-
endpoint: "/invoices",
|
|
520
|
-
body: { customerId: "customer-1" },
|
|
521
|
-
})
|
|
522
|
-
```
|
|
523
|
-
|
|
524
|
-
Integration credentials are injected by the Integration service. Do not pass provider credentials through browser input.
|
|
525
|
-
|
|
526
|
-
## Legacy surface
|
|
527
|
-
|
|
528
|
-
The public surface of `mitra-interactions-sdk` is re-exported from this package so an application can replace the legacy dependency without rewriting its call sites. Runtime re-exports are marked `@deprecated` and name their replacement, or state that no replacement exists yet. Every legacy type is an identity-preserving alias marked as a deprecated compatibility type.
|
|
529
|
-
|
|
530
|
-
```typescript
|
|
531
|
-
import { createClient, loginWithGoogleMitra } from "@mitralab.io/platform-sdk"
|
|
532
|
-
|
|
533
|
-
export const mitra = createClient({ appId, apiUrl })
|
|
534
|
-
|
|
535
|
-
await loginWithGoogleMitra()
|
|
536
|
-
console.log(mitra.auth.accessToken)
|
|
537
|
-
```
|
|
538
|
-
|
|
539
|
-
Google, Microsoft and e-mail sign-in have native replacements: `mitra.auth.signInWithGoogle`, `mitra.auth.signInWithMicrosoft` and `mitra.auth.signInWithEmail`, each with its `complete...SignInRedirect` counterpart. Agent tasks, Agent credentials, public Functions, entities, custom queries, Function execution, and integrations also have native replacements. Only `loginMitra('mitra')` still has no native equivalent and remains available through the deprecated re-export surface.
|
|
540
|
-
|
|
541
|
-
`createClient` configures the legacy SDK with both `baseURL` and `authUrl` set to `${apiUrl}/legacy`, after removing trailing slashes, plus `projectId: appId`. This keeps deprecated calls and legacy login routed through the BFF while the new modules call their native APIs directly. Its `authPageUrl` uses the same precedence as native Google SSO: explicit client config, `window.__mitraEnv.authPageUrl`, then `/sdk-auth.html` on the `apiUrl` origin. Existing query parameters are preserved.
|
|
542
|
-
|
|
543
|
-
The bridge shares the session in both directions. A session persisted under `mitra_auth_{appId}` is handed to the legacy SDK at startup; native sign-in, Google SSO, proactive or reactive refresh, manual token changes, and sign-out update its active configuration. Sessions produced by legacy login or refresh are persisted back under the same new storage key. The bridge only propagates sessions the two SDKs produce: it never starts a login and never triggers a refresh of its own.
|
|
544
|
-
|
|
545
|
-
The legacy package exposes no sign-out API for deleting the refresh token stored in its private `mitra-session` entry. Native sign-out safely removes both credentials from the active legacy configuration, so deprecated calls cannot authenticate or refresh. A later direct call to `configureSdkMitra` can restore that private persisted refresh token; applications should keep configuration ownership in `createClient` during the migration.
|
|
546
|
-
|
|
547
|
-
The legacy SDK does not return a user, so `auth.currentUser` stays empty after a legacy login. Call `mitra.auth.me()` to populate it. Calling `configureSdkMitra` directly replaces the legacy configuration and its refresh hook until the next bridged session change, so it should not be mixed with a client-managed migration.
|
|
548
|
-
|
|
549
|
-
## Errors and request behavior
|
|
550
|
-
|
|
551
|
-
API failures throw `MitraApiError`:
|
|
79
|
+
| `status` ou `code` | Quando | O que fazer |
|
|
80
|
+
|---|---|---|
|
|
81
|
+
| `401` | a sessão acabou e não deu para renovar | leve a pessoa ao login de novo |
|
|
82
|
+
| `403` | a pessoa não tem acesso ao recurso | confira as permissões dela no app |
|
|
83
|
+
| `429`, `5xx` | limite de requisições ou falha no servidor | espere `retryAfterSeconds`, quando vier, e repita se a operação puder ser repetida |
|
|
84
|
+
| `INVALID_CONFIGURATION` | argumento inválido, ou `requestEmailCode()` antes de `init()` | corrija o argumento ou chame `init()` no startup |
|
|
85
|
+
| `UNSUPPORTED_AUTH_METHOD` | `signIn` ou `signUp` com senha | use Google, Microsoft ou código por e-mail |
|
|
86
|
+
| `INVALID_CODE` | o código digitado não confere | peça para a pessoa conferir o código |
|
|
87
|
+
| `MAGIC_LINK_EXPIRED`, `MAGIC_LINK_USED`, `MAGIC_LINK_INVALID` | o link do e-mail venceu, já foi usado ou não vale | peça um código novo |
|
|
88
|
+
| `REDIRECT_NOT_ALLOWED` | o servidor respondeu com redirect | confira o `apiUrl` |
|
|
89
|
+
| `INVALID_RESPONSE` | resposta fora do formato esperado | atualize o SDK; se continuar, abra uma issue |
|
|
552
90
|
|
|
553
|
-
|
|
554
|
-
import { MitraApiError } from "@mitralab.io/platform-sdk"
|
|
91
|
+
Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar por `onError`.
|
|
555
92
|
|
|
556
|
-
|
|
557
|
-
await mitra.entities.Task.get("missing-id")
|
|
558
|
-
} catch (error) {
|
|
559
|
-
if (error instanceof MitraApiError) {
|
|
560
|
-
console.error(error.status, error.code, error.message)
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
```
|
|
93
|
+
## Boas práticas
|
|
564
94
|
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
95
|
+
- Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled` e o login por e-mail dependem dele.
|
|
96
|
+
- Com `mode: "redirect"`, chame no startup o `completeGoogleSignInRedirect()`, `completeMicrosoftSignInRedirect()` ou `completeEmailSignInRedirect()` do método que você usa. Cada um devolve `null` quando a URL não é dele. O link do e-mail completa o login no mesmo browser que pediu o código; em outro aparelho, a pessoa digita o código.
|
|
97
|
+
- A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. `signOut()` limpa.
|
|
98
|
+
- O SDK só repete uma requisição depois de renovar o token num `401`. Fora isso, quem decide repetir é o app.
|
|
99
|
+
- Nunca coloque API key em código que vai para o browser, nem passe uma em `createClient({ apiKey })` num app de browser: o bundle entrega a chave a quem abrir o app. O `signInWithApiKey()` recusa rodar no browser, mas isso não tira do bundle uma chave escrita nele. Para processo sem pessoa, como cron ou coletor, use `@mitralab.io/functions-sdk` com `createClientFromApiKey`.
|
|
570
100
|
|
|
571
|
-
|
|
101
|
+
## Migração do `mitra-interactions-sdk`
|
|
572
102
|
|
|
573
|
-
|
|
103
|
+
Os exports do SDK legado continuam neste pacote, marcados `@deprecated`, e dividem a sessão com o cliente novo. Troque a dependência, crie o cliente com `createClient` e substitua as chamadas aos poucos: o aviso de cada export diz o método novo. Não chame `configureSdkMitra` direto, porque o `createClient` já configura o legado.
|
|
574
104
|
|
|
575
|
-
##
|
|
105
|
+
## Desenvolvimento
|
|
576
106
|
|
|
577
107
|
```bash
|
|
578
|
-
npm
|
|
108
|
+
npm ci
|
|
579
109
|
npm run check
|
|
580
110
|
```
|
|
581
111
|
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
The build produces ESM, CommonJS, `.d.ts`, and `.d.cts` artifacts. Package checks inspect the public tarball with Are The Types Wrong, install it into an isolated consumer, and validate ESM, CommonJS, and TypeScript resolution.
|
|
585
|
-
|
|
586
|
-
See [CHANGELOG.md](CHANGELOG.md) for release history and [LICENSE](LICENSE) for license terms.
|
|
112
|
+
O `check` roda lint, typecheck, testes, build e um smoke test do pacote. A publicação no npm sai do workflow Release.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mitralab.io/platform-sdk",
|
|
3
|
-
"version": "1.5.0
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "JavaScript/TypeScript SDK for building apps on the Mitra Platform",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"url": "https://github.com/mitralab-dev/mitra-platform-sdk/issues"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@mitralab.io/sdk-core": "0.2.
|
|
65
|
+
"@mitralab.io/sdk-core": "0.2.12",
|
|
66
66
|
"mitra-interactions-sdk": "1.0.60-beta.48"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|