mitra-interactions-sdk 1.0.60-beta.2 → 1.0.60-beta.21

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/dist/index.mjs CHANGED
@@ -105,9 +105,6 @@ async function doLogin(method, options) {
105
105
  autoConfigureFromLogin(response, authUrl, projectId);
106
106
  return response;
107
107
  }
108
- async function loginWithEmailMitra(options) {
109
- return doLogin("email", options);
110
- }
111
108
  async function loginWithGoogleMitra(options) {
112
109
  return doLogin("google", options);
113
110
  }
@@ -161,102 +158,12 @@ async function refreshTokenSilently(authUrl, projectId) {
161
158
  })();
162
159
  return _refreshPromise;
163
160
  }
164
- var SILENT_TIMEOUT_MS = 2e4;
165
- var AUTH_READY_TYPE = "mitra-auth-ready";
166
- var AUTH_CREDENTIALS_TYPE = "mitra-auth-credentials";
167
- function openSilentAuthIframe(authUrl, projectId, credentials) {
168
- return new Promise((resolve, reject) => {
169
- const origin = getOriginFromUrl(authUrl);
170
- const base = authUrl.endsWith("/") ? authUrl : authUrl + "/";
171
- const separator = base.includes("?") ? "&" : "?";
172
- let url = `${base}${separator}mode=silent&projectId=${encodeURIComponent(projectId)}`;
173
- if (typeof window !== "undefined") {
174
- url += `&originUrl=${encodeURIComponent(window.location.href)}`;
175
- }
176
- const iframe = document.createElement("iframe");
177
- iframe.style.display = "none";
178
- const timer = setTimeout(() => {
179
- cleanup();
180
- reject(new Error("Timeout na autentica\xE7\xE3o silenciosa"));
181
- }, SILENT_TIMEOUT_MS);
182
- function onMessage(event) {
183
- var _a, _b, _c;
184
- if (event.origin !== origin) return;
185
- if (((_a = event.data) == null ? void 0 : _a.type) === AUTH_READY_TYPE) {
186
- (_b = iframe.contentWindow) == null ? void 0 : _b.postMessage({
187
- type: AUTH_CREDENTIALS_TYPE,
188
- ...credentials
189
- }, origin);
190
- return;
191
- }
192
- if (((_c = event.data) == null ? void 0 : _c.type) !== AUTH_MESSAGE_TYPE) return;
193
- cleanup();
194
- if (event.data.success) {
195
- resolve(event.data.data);
196
- } else {
197
- reject(new Error(event.data.error || "Erro na autentica\xE7\xE3o"));
198
- }
199
- }
200
- function cleanup() {
201
- window.removeEventListener("message", onMessage);
202
- clearTimeout(timer);
203
- if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
204
- }
205
- window.addEventListener("message", onMessage);
206
- iframe.src = url;
207
- document.body.appendChild(iframe);
208
- });
209
- }
210
- async function emailSignupMitra(options) {
211
- const { authUrl, projectId } = resolveLoginOptions(options);
212
- const result = await openSilentAuthIframe(authUrl, projectId, {
213
- action: "signup",
214
- name: options.name,
215
- email: options.email,
216
- password: options.password
217
- });
218
- if (!result.needsVerification) {
219
- throw new Error("Resposta inesperada do signup");
220
- }
221
- }
222
- async function emailVerifyCodeMitra(options) {
223
- const { authUrl, projectId } = resolveLoginOptions(options);
224
- const response = await openSilentAuthIframe(authUrl, projectId, {
225
- action: "verifyCode",
226
- email: options.email,
227
- code: options.code,
228
- password: options.password
229
- });
230
- autoConfigureFromLogin(response, authUrl, projectId);
231
- return response;
232
- }
233
- async function emailResendCodeMitra(options) {
234
- const { authUrl, projectId } = resolveLoginOptions(options);
235
- await openSilentAuthIframe(authUrl, projectId, {
236
- action: "resendCode",
237
- email: options.email
238
- });
239
- }
240
- async function emailLoginMitra(options) {
241
- const { authUrl, projectId } = resolveLoginOptions(options);
242
- const response = await openSilentAuthIframe(authUrl, projectId, {
243
- action: "login",
244
- email: options.email,
245
- password: options.password
246
- });
247
- autoConfigureFromLogin(response, authUrl, projectId);
248
- return response;
249
- }
250
161
 
251
162
  // src/auth-new.ts
252
163
  function getFetch() {
253
164
  if (typeof globalThis.fetch === "function") return globalThis.fetch;
254
165
  throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
255
166
  }
256
- function buildEndpoint(authUrl, path) {
257
- const base = authUrl.replace(/\/+$/, "");
258
- return `${base}/iam/api/v1/auth${path}`;
259
- }
260
167
  function buildBffAuthEndpoint(gateway, path) {
261
168
  const base = gateway.replace(/\/+$/, "");
262
169
  return `${base}/auth${path}`;
@@ -285,25 +192,6 @@ function autoConfigureFromLogin2(response, authUrl, projectId) {
285
192
  ...response.integrationURL ? { integrationURL: response.integrationURL } : {}
286
193
  });
287
194
  }
288
- async function postNewAuth(url, body) {
289
- const fetchFn = getFetch();
290
- const response = await fetchFn(url, {
291
- method: "POST",
292
- headers: { "Content-Type": "application/json" },
293
- body: JSON.stringify(body)
294
- });
295
- if (!response.ok) {
296
- const text = await response.text().catch(() => "");
297
- let parsed = null;
298
- try {
299
- parsed = text ? JSON.parse(text) : null;
300
- } catch (e) {
301
- }
302
- const msg = (parsed == null ? void 0 : parsed.message) || (parsed == null ? void 0 : parsed.error) || `HTTP ${response.status}`;
303
- throw { message: msg, status: response.status, details: parsed };
304
- }
305
- return response.json();
306
- }
307
195
  async function postBffAuth(url, body) {
308
196
  const fetchFn = getFetch();
309
197
  const response = await fetchFn(url, {
@@ -311,18 +199,14 @@ async function postBffAuth(url, body) {
311
199
  headers: { "Content-Type": "application/json" },
312
200
  body: JSON.stringify(body)
313
201
  });
202
+ const text = await response.text().catch(() => "");
203
+ const { data, isJson } = parseBody(text);
314
204
  if (!response.ok) {
315
- const text2 = await response.text().catch(() => "");
316
- let parsed = null;
317
- try {
318
- parsed = text2 ? JSON.parse(text2) : null;
319
- } catch (e) {
320
- }
321
- const msg = (parsed == null ? void 0 : parsed.message) || (parsed == null ? void 0 : parsed.error) || `HTTP ${response.status}`;
322
- throw { message: msg, status: response.status, details: parsed };
205
+ const fallback = !isJson && text ? `HTTP ${response.status} \u2014 ${text}` : `HTTP ${response.status}`;
206
+ const msg = isJson && ((data == null ? void 0 : data.message) || (data == null ? void 0 : data.error)) || fallback;
207
+ throw { message: msg, status: response.status, details: data };
323
208
  }
324
- const text = await response.text().catch(() => "");
325
- return text ? JSON.parse(text) : null;
209
+ return data;
326
210
  }
327
211
  function normalizeResponse(tokens, authUrl) {
328
212
  return {
@@ -331,21 +215,89 @@ function normalizeResponse(tokens, authUrl) {
331
215
  baseURL: authUrl
332
216
  };
333
217
  }
334
- var NOT_SUPPORTED_POPUP = 'Login via popup (loginWithEmailMitra/loginMitra com method "email" ou "mitra") ainda n\xE3o suportado no novo Mitra. Use emailLoginMitra({ email, password }).';
335
- var NOT_SUPPORTED_VERIFY = "emailVerifyCodeMitra n\xE3o existe no novo Mitra (signup \xE9 direto, sem c\xF3digo de verifica\xE7\xE3o).";
336
- var NOT_SUPPORTED_RESEND = "emailResendCodeMitra n\xE3o existe no novo Mitra.";
337
- var NOT_SUPPORTED_REDIRECT = 'mode "redirect" ainda n\xE3o suportado no novo Mitra para SSO. Use mode "popup" (default).';
218
+ var NOT_SUPPORTED_POPUP = 'loginMitra com method "email" ou "mitra" n\xE3o \xE9 suportado no novo Mitra. Use SSO (loginWithGoogleMitra).';
338
219
  var OAUTH_RESULT_TYPE = "mitra-oauth-result";
339
220
  var POPUP_W = 480;
340
221
  var POPUP_H = 600;
341
222
  var POPUP_TIMEOUT_MS = 5 * 60 * 1e3;
342
- var SSO_AUTH_PAGE_URL = "https://d2by6yrxhbu2rl.cloudfront.net/sdk-auth.html";
343
- async function fetchSsoAuthPageUrl(_baseURL) {
344
- return SSO_AUTH_PAGE_URL;
223
+ var SSO_AUTH_PAGE_URL = "https://stg.mitralab.io/sdk-auth.html";
224
+ async function fetchSsoAuthPageUrl(gatewayUrl) {
225
+ const config = isConfigured() ? getConfig() : null;
226
+ if (config == null ? void 0 : config.authPageUrl) return config.authPageUrl;
227
+ try {
228
+ return `${new URL(gatewayUrl).origin}/sdk-auth.html`;
229
+ } catch (e) {
230
+ return SSO_AUTH_PAGE_URL;
231
+ }
232
+ }
233
+ var SSO_ENABLED_PROVIDERS = ["google"];
234
+ function providerLabel(provider) {
235
+ return provider === "microsoft" ? "Microsoft" : provider === "google" ? "Google" : provider;
236
+ }
237
+ function assertProviderAvailable(provider) {
238
+ if (!SSO_ENABLED_PROVIDERS.includes(provider)) {
239
+ throw new Error(`Login com ${providerLabel(provider)} ainda n\xE3o dispon\xEDvel no novo Mitra.`);
240
+ }
241
+ }
242
+ function stripToOriginPath(url) {
243
+ try {
244
+ const u = new URL(url);
245
+ return u.origin + u.pathname;
246
+ } catch (e) {
247
+ return url.split("?")[0].split("#")[0];
248
+ }
249
+ }
250
+ async function exchangeSsoCode(authUrl, provider, code, redirectUri, projectId) {
251
+ const data = await postBffAuth(buildBffAuthEndpoint(authUrl, `/${provider}`), {
252
+ appId: String(projectId),
253
+ code,
254
+ redirectUri
255
+ });
256
+ const response = {
257
+ token: data.token,
258
+ // baseURL = authUrl (gateway); o BFF não devolve URLs de bootstrap.
259
+ baseURL: authUrl,
260
+ ...data.refreshToken ? { refreshToken: data.refreshToken } : {}
261
+ };
262
+ autoConfigureFromLogin2(response, authUrl, projectId);
263
+ return response;
264
+ }
265
+ var SSO_REDIRECT_STORE_KEY = "mitra_sso_redirect";
266
+ function persistRedirectContext(ctx) {
267
+ try {
268
+ sessionStorage.setItem(SSO_REDIRECT_STORE_KEY, JSON.stringify(ctx));
269
+ } catch (e) {
270
+ }
271
+ }
272
+ function readRedirectContext() {
273
+ try {
274
+ const raw = sessionStorage.getItem(SSO_REDIRECT_STORE_KEY);
275
+ return raw ? JSON.parse(raw) : null;
276
+ } catch (e) {
277
+ return null;
278
+ }
279
+ }
280
+ function clearRedirectContext() {
281
+ try {
282
+ sessionStorage.removeItem(SSO_REDIRECT_STORE_KEY);
283
+ } catch (e) {
284
+ }
345
285
  }
346
- function buildStartUrl(authPageUrl, provider, state, appId, apiUrl) {
286
+ function buildStartUrl(authPageUrl, provider, state, appId, apiUrl, returnTo) {
347
287
  const sep = authPageUrl.includes("?") ? "&" : "?";
348
- return authPageUrl + sep + new URLSearchParams({ provider, state, appId, apiUrl }).toString();
288
+ const query = {
289
+ provider,
290
+ state,
291
+ appId,
292
+ apiUrl,
293
+ // origin = origin desta SDK; a página trava o postMessage do result nela.
294
+ origin: window.location.origin,
295
+ // Contrato novo: a página NÃO troca mais o code — devolve o code cru (popup
296
+ // via postMessage, redirect via #codeMitra). A SDK troca no BFF /auth/{provider}.
297
+ responseType: "code"
298
+ };
299
+ if (returnTo) query.returnTo = returnTo;
300
+ return authPageUrl + sep + new URLSearchParams(query).toString();
349
301
  }
350
302
  function getOriginFromUrl2(url) {
351
303
  try {
@@ -402,11 +354,11 @@ function openOAuthPopup(providerUrl, expectedOrigin, expectedState) {
402
354
  reject(new Error(data.error || "Erro na autentica\xE7\xE3o OAuth."));
403
355
  return;
404
356
  }
405
- if (!data.code) {
406
- reject(new Error("Resposta OAuth sem code."));
357
+ if (!data.code && !data.token) {
358
+ reject(new Error("Resposta OAuth sem code nem token."));
407
359
  return;
408
360
  }
409
- resolve({ code: data.code });
361
+ resolve({ code: data.code, token: data.token });
410
362
  }
411
363
  function cleanup() {
412
364
  clearTimeout(timer);
@@ -419,13 +371,14 @@ function openOAuthPopup(providerUrl, expectedOrigin, expectedState) {
419
371
  }
420
372
  var _oauthInFlight = null;
421
373
  async function loginWithProvider(provider, options) {
422
- if (_oauthInFlight) return _oauthInFlight;
374
+ assertProviderAvailable(provider);
423
375
  if (typeof window === "undefined") {
424
376
  throw new Error("SSO s\xF3 funciona em ambiente browser.");
425
377
  }
426
378
  if ((options == null ? void 0 : options.mode) === "redirect") {
427
- throw new Error(NOT_SUPPORTED_REDIRECT);
379
+ return startSsoRedirect(provider, options);
428
380
  }
381
+ if (_oauthInFlight) return _oauthInFlight;
429
382
  _oauthInFlight = (async () => {
430
383
  try {
431
384
  const { authUrl, projectId } = resolveLoginOptions2(options);
@@ -433,15 +386,13 @@ async function loginWithProvider(provider, options) {
433
386
  const appId = String(projectId);
434
387
  const authPageUrl = await fetchSsoAuthPageUrl(authUrl);
435
388
  const pageOrigin = getOriginFromUrl2(authPageUrl);
436
- const redirectUri = authPageUrl;
389
+ const redirectUri = stripToOriginPath(authPageUrl);
437
390
  const startUrl = buildStartUrl(authPageUrl, provider, state, appId, authUrl);
438
- const { code } = await openOAuthPopup(startUrl, pageOrigin, state);
439
- const tokens = await postNewAuth(buildEndpoint(authUrl, `/${provider}`), {
440
- code,
441
- redirectUri,
442
- appId
443
- });
444
- const response = normalizeResponse(tokens, authUrl);
391
+ const { code, token } = await openOAuthPopup(startUrl, pageOrigin, state);
392
+ if (code) {
393
+ return await exchangeSsoCode(authUrl, provider, code, redirectUri, projectId);
394
+ }
395
+ const response = normalizeResponse(token, authUrl);
445
396
  autoConfigureFromLogin2(response, authUrl, projectId);
446
397
  return response;
447
398
  } finally {
@@ -450,8 +401,25 @@ async function loginWithProvider(provider, options) {
450
401
  })();
451
402
  return _oauthInFlight;
452
403
  }
453
- async function loginWithEmailMitra2(_options) {
454
- throw new Error(NOT_SUPPORTED_POPUP);
404
+ async function startSsoRedirect(provider, options) {
405
+ const { authUrl, projectId } = resolveLoginOptions2(options);
406
+ const state = generateState();
407
+ const appId = String(projectId);
408
+ const authPageUrl = await fetchSsoAuthPageUrl(authUrl);
409
+ const redirectUri = stripToOriginPath(authPageUrl);
410
+ persistRedirectContext({ state, provider, authUrl, projectId: appId, redirectUri });
411
+ const startUrl = buildStartUrl(authPageUrl, provider, state, appId, authUrl, window.location.href);
412
+ window.location.assign(startUrl);
413
+ return new Promise(() => {
414
+ });
415
+ }
416
+ async function exchangeSsoCodeMitra(options) {
417
+ const ctx = readRedirectContext();
418
+ clearRedirectContext();
419
+ if (!ctx || ctx.state !== options.state) {
420
+ throw new Error("State inv\xE1lido no retorno do SSO (poss\xEDvel CSRF).");
421
+ }
422
+ return exchangeSsoCode(ctx.authUrl, ctx.provider, options.code, ctx.redirectUri, ctx.projectId);
455
423
  }
456
424
  async function loginWithGoogleMitra2(options) {
457
425
  return loginWithProvider("google", options);
@@ -464,36 +432,6 @@ async function loginMitra2(method, options) {
464
432
  if (method === "microsoft") return loginWithProvider("microsoft", options);
465
433
  throw new Error(NOT_SUPPORTED_POPUP);
466
434
  }
467
- async function emailLoginMitra2(options) {
468
- const { authUrl, projectId } = resolveLoginOptions2(options);
469
- const data = await postBffAuth(buildBffAuthEndpoint(authUrl, "/email/login"), {
470
- projectId: String(projectId),
471
- email: options.email,
472
- password: options.password
473
- });
474
- const response = {
475
- token: data.token,
476
- baseURL: data.baseURL || authUrl,
477
- ...data.integrationURL ? { integrationURL: data.integrationURL } : {}
478
- };
479
- autoConfigureFromLogin2(response, authUrl, projectId);
480
- return response;
481
- }
482
- async function emailSignupMitra2(options) {
483
- const { authUrl, projectId } = resolveLoginOptions2(options);
484
- await postBffAuth(buildBffAuthEndpoint(authUrl, "/email/signup"), {
485
- projectId: String(projectId),
486
- name: options.name,
487
- email: options.email,
488
- password: options.password
489
- });
490
- }
491
- async function emailVerifyCodeMitra2(_options) {
492
- throw new Error(NOT_SUPPORTED_VERIFY);
493
- }
494
- async function emailResendCodeMitra2(_options) {
495
- throw new Error(NOT_SUPPORTED_RESEND);
496
- }
497
435
  var _refreshPromise2 = null;
498
436
  async function refreshTokenSilently2(authUrl, _projectId) {
499
437
  if (_refreshPromise2) return _refreshPromise2;
@@ -502,10 +440,15 @@ async function refreshTokenSilently2(authUrl, _projectId) {
502
440
  const config = isConfigured() ? getConfig() : null;
503
441
  const refreshToken = config == null ? void 0 : config.refreshToken;
504
442
  if (!refreshToken) {
505
- throw new Error("refreshToken n\xE3o dispon\xEDvel para renova\xE7\xE3o no novo Mitra. Fa\xE7a login novamente.");
443
+ throw new Error("refreshToken n\xE3o dispon\xEDvel para renova\xE7\xE3o. Fa\xE7a login novamente.");
506
444
  }
507
- const tokens = await postNewAuth(buildEndpoint(authUrl, "/refresh-token"), { refreshToken });
508
- return normalizeResponse(tokens, authUrl);
445
+ const data = await postBffAuth(buildBffAuthEndpoint(authUrl, "/refresh-token"), { refreshToken });
446
+ return {
447
+ token: data.token,
448
+ // Refresh não muda a base — mantém o authUrl (gateway).
449
+ baseURL: authUrl,
450
+ ...data.refreshToken ? { refreshToken: data.refreshToken } : {}
451
+ };
509
452
  } finally {
510
453
  _refreshPromise2 = null;
511
454
  }
@@ -540,10 +483,6 @@ async function loginMitra3(method, options) {
540
483
  const authUrl = resolveAuthUrlFromOptions(options);
541
484
  return isLegacyAuthUrl(authUrl) ? loginMitra(method, options) : loginMitra2(method, options);
542
485
  }
543
- async function loginWithEmailMitra3(options) {
544
- const authUrl = resolveAuthUrlFromOptions(options);
545
- return isLegacyAuthUrl(authUrl) ? loginWithEmailMitra(options) : loginWithEmailMitra2();
546
- }
547
486
  async function loginWithGoogleMitra3(options) {
548
487
  const authUrl = resolveAuthUrlFromOptions(options);
549
488
  return isLegacyAuthUrl(authUrl) ? loginWithGoogleMitra(options) : loginWithGoogleMitra2(options);
@@ -552,1492 +491,63 @@ async function loginWithMicrosoftMitra3(options) {
552
491
  const authUrl = resolveAuthUrlFromOptions(options);
553
492
  return isLegacyAuthUrl(authUrl) ? loginWithMicrosoftMitra(options) : loginWithMicrosoftMitra2(options);
554
493
  }
555
- async function emailSignupMitra3(options) {
556
- const authUrl = resolveAuthUrlFromOptions(options);
557
- return isLegacyAuthUrl(authUrl) ? emailSignupMitra(options) : emailSignupMitra2(options);
558
- }
559
- async function emailLoginMitra3(options) {
560
- const authUrl = resolveAuthUrlFromOptions(options);
561
- return isLegacyAuthUrl(authUrl) ? emailLoginMitra(options) : emailLoginMitra2(options);
562
- }
563
- async function emailVerifyCodeMitra3(options) {
564
- const authUrl = resolveAuthUrlFromOptions(options);
565
- return isLegacyAuthUrl(authUrl) ? emailVerifyCodeMitra(options) : emailVerifyCodeMitra2();
566
- }
567
- async function emailResendCodeMitra3(options) {
568
- const authUrl = resolveAuthUrlFromOptions(options);
569
- return isLegacyAuthUrl(authUrl) ? emailResendCodeMitra(options) : emailResendCodeMitra2();
570
- }
571
494
  async function refreshTokenSilently3(authUrl, projectId) {
572
495
  return isLegacyAuthUrl(authUrl) ? refreshTokenSilently(authUrl, projectId) : refreshTokenSilently2(authUrl);
573
496
  }
574
-
575
- // src/chat.ts
576
- function openChatMitra() {
577
- if (typeof window === "undefined") return;
578
- const chat = window.__mitraChat;
579
- if (!chat) return;
580
- if (chat.isReady) {
581
- chat.open();
582
- } else {
583
- const iv = setInterval(() => {
584
- if (chat.isReady) {
585
- clearInterval(iv);
586
- chat.open();
587
- }
588
- }, 200);
589
- setTimeout(() => clearInterval(iv), 15e3);
590
- }
591
- }
592
- function closeChatMitra() {
593
- var _a;
594
- if (typeof window === "undefined") return;
595
- (_a = window.__mitraChat) == null ? void 0 : _a.close();
497
+ async function exchangeSsoCodeMitra2(options) {
498
+ return exchangeSsoCodeMitra(options);
596
499
  }
597
500
 
598
- // src/password-reset.ts
599
- var AUTH_API_BY_AUTH_URL = {
600
- "https://coder.mitralab.io/sdk-auth/": "https://api0.mitraecp.com:1005",
601
- "https://agent.mitralab.io/sdk-auth/": "https://api2.mitrasheet.com:4133"
602
- };
603
- function normalizeAuthUrl(url) {
604
- const stripped = url.split("?")[0].split("#")[0];
605
- return stripped.endsWith("/") ? stripped : stripped + "/";
606
- }
607
- var NOT_SUPPORTED_SEND = "sendPasswordResetCodeMitra ainda n\xE3o suportado no novo Mitra.";
608
- var NOT_SUPPORTED_VALIDATE = "validatePasswordResetCodeMitra ainda n\xE3o suportado no novo Mitra.";
609
- var NOT_SUPPORTED_RESET = "resetPasswordMitra ainda n\xE3o suportado no novo Mitra.";
610
- function isNewWorld2(opts) {
611
- var _a;
612
- if (opts.authApiURL) return false;
613
- if (typeof window !== "undefined" && ((_a = window.__mitraEnv) == null ? void 0 : _a.apiBaseURL)) return false;
614
- const authUrl = opts.authUrl || (isConfigured() ? getConfig().authUrl : void 0);
615
- if (!authUrl) return false;
616
- return !(normalizeAuthUrl(authUrl) in AUTH_API_BY_AUTH_URL);
617
- }
618
- function resolveProjectId(opts) {
619
- if (opts.projectId != null) return opts.projectId;
620
- if (isConfigured()) {
621
- const pid = getConfig().projectId;
622
- if (pid != null) return pid;
623
- }
624
- throw new Error(
625
- "projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId })."
626
- );
627
- }
628
- function resolveAuthApiURL(opts) {
629
- var _a;
630
- if (opts.authApiURL) return opts.authApiURL.replace(/\/+$/, "");
631
- if (typeof window !== "undefined") {
632
- const injected = (_a = window.__mitraEnv) == null ? void 0 : _a.apiBaseURL;
633
- if (typeof injected === "string" && injected.length > 0) {
634
- return injected.replace(/\/+$/, "");
635
- }
636
- }
637
- const authUrl = opts.authUrl || (isConfigured() ? getConfig().authUrl : void 0);
638
- if (authUrl) {
639
- const apiURL = AUTH_API_BY_AUTH_URL[normalizeAuthUrl(authUrl)];
640
- if (apiURL) return apiURL;
641
- }
642
- throw new Error(
643
- "N\xE3o foi poss\xEDvel resolver a API base. Configure window.__mitraEnv.apiBaseURL via build-proxy, passe authApiURL nas options, ou use um authUrl conhecido (coder.mitralab.io ou agent.mitralab.io)."
644
- );
501
+ // src/instance.ts
502
+ function formatToken(token) {
503
+ return `Bearer ${stripBearer(token)}`;
645
504
  }
646
505
  function getFetch2() {
647
506
  if (typeof globalThis.fetch === "function") return globalThis.fetch;
648
507
  throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
649
508
  }
650
- async function callAuthApi(url, method, body) {
651
- const fetchFn = getFetch2();
652
- const response = await fetchFn(url, {
653
- method,
654
- headers: { "Content-Type": "application/json", accept: "application/json" },
655
- body: JSON.stringify(body)
656
- });
657
- const text = await response.text();
658
- let data = null;
659
- try {
660
- data = text ? JSON.parse(text) : null;
661
- } catch (e) {
662
- }
663
- if (!response.ok) {
664
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
665
- throw { message: msg, status: response.status, details: data };
666
- }
667
- return data;
668
- }
669
- async function sendPasswordResetCodeMitra(options) {
670
- if (isNewWorld2(options)) throw new Error(NOT_SUPPORTED_SEND);
671
- const apiURL = resolveAuthApiURL(options);
672
- const projectId = resolveProjectId(options);
673
- return callAuthApi(`${apiURL}/mitraspace/auth/resetPassword`, "POST", {
674
- email: options.email,
675
- projectId
676
- });
677
- }
678
- async function validatePasswordResetCodeMitra(options) {
679
- if (isNewWorld2(options)) throw new Error(NOT_SUPPORTED_VALIDATE);
680
- const apiURL = resolveAuthApiURL(options);
681
- const projectId = resolveProjectId(options);
682
- return callAuthApi(`${apiURL}/mitraspace/auth/resetPassword/validateCode`, "POST", {
683
- email: options.email,
684
- code: options.code,
685
- projectId
686
- });
687
- }
688
- async function resetPasswordMitra(options) {
689
- if (isNewWorld2(options)) throw new Error(NOT_SUPPORTED_RESET);
690
- const apiURL = resolveAuthApiURL(options);
691
- const projectId = resolveProjectId(options);
692
- return callAuthApi(`${apiURL}/mitraspace/auth/resetPassword`, "PUT", {
693
- email: options.email,
694
- code: options.code,
695
- newPassword: options.newPassword,
696
- projectId
697
- });
509
+ function buildQuery(params) {
510
+ return Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
698
511
  }
699
-
700
- // src/client.ts
701
- function getFetch3() {
702
- if (typeof globalThis.fetch === "function") {
703
- return globalThis.fetch;
512
+ function createMitraInstance(initialConfig) {
513
+ var _a;
514
+ let _config = {
515
+ baseURL: ((_a = initialConfig.baseURL) == null ? void 0 : _a.replace(/\/+$/, "")) || "",
516
+ token: initialConfig.token ? stripBearer(initialConfig.token) : "",
517
+ refreshToken: initialConfig.refreshToken,
518
+ integrationURL: initialConfig.integrationURL,
519
+ authUrl: initialConfig.authUrl,
520
+ projectId: initialConfig.projectId
521
+ };
522
+ function resolveProjectId2(projectId) {
523
+ if (projectId != null) return projectId;
524
+ if (_config.projectId != null) return _config.projectId;
525
+ throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
704
526
  }
705
- throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
706
- }
707
- function formatToken(token) {
708
- return `Bearer ${stripBearer(token)}`;
709
- }
710
- function buildHeaders() {
711
- const config = getConfig();
712
- const headers = { "Content-Type": "application/json" };
713
- if (config.token) headers["Authorization"] = formatToken(config.token);
714
- return headers;
715
- }
716
- function buildUrl(endpoint, params) {
717
- const config = getConfig();
718
- let url = `${config.baseURL}${endpoint}`;
719
- if (params) {
720
- const query = Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
721
- if (query) url += `?${query}`;
527
+ function authHeaders() {
528
+ const headers = { "Content-Type": "application/json" };
529
+ if (_config.token) headers["Authorization"] = formatToken(_config.token);
530
+ return headers;
722
531
  }
723
- return url;
724
- }
725
- async function tryRefreshToken() {
726
- var _a, _b;
727
- const config = getConfig();
728
- if (!config.token || config.projectId == null) return false;
729
- try {
730
- const baseURL = config.baseURL.replace(/\/+$/, "");
731
- const resp = await getFetch3()(`${baseURL}/mitraspace/project/refreshedToken/${config.projectId}`, {
732
- method: "GET",
733
- headers: { "Authorization": formatToken(config.token) }
734
- });
735
- if (resp.ok) {
736
- const data = await resp.json();
737
- if (data.token) {
738
- const newToken = `Bearer ${stripBearer(data.token)}`;
739
- const session = {
740
- token: newToken,
741
- baseURL: ((_a = data.merge) == null ? void 0 : _a.backURL) || config.baseURL,
742
- ...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
743
- };
744
- updateGlobalToken(session.token);
745
- if (config.onTokenRefresh) config.onTokenRefresh(session);
746
- return true;
747
- }
532
+ async function handleResponse2(response) {
533
+ const text = await response.text();
534
+ const { data, isJson } = parseBody(text);
535
+ if (!response.ok) {
536
+ const fallback = !isJson && text ? `HTTP ${response.status} \u2014 ${text}` : `HTTP ${response.status}`;
537
+ const base = isJson && ((data == null ? void 0 : data.message) || (data == null ? void 0 : data.error)) || fallback;
538
+ const msg = isJson && (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
539
+ throw { message: msg, status: response.status, details: data };
748
540
  }
749
- } catch (e) {
750
- }
751
- if (!config.authUrl || typeof window === "undefined") return false;
752
- try {
753
- const session = await refreshTokenSilently3(config.authUrl, config.projectId);
754
- updateGlobalToken(session.token, session.refreshToken);
755
- if (config.onTokenRefresh) config.onTokenRefresh(session);
756
- return true;
757
- } catch (e) {
758
- return false;
759
- }
760
- }
761
- async function handleResponse(response) {
762
- const text = await response.text();
763
- const data = text ? JSON.parse(text) : null;
764
- if (!response.ok) {
765
- const base = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
766
- const msg = (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
767
- throw {
768
- message: msg,
769
- status: response.status,
770
- details: data
771
- };
772
- }
773
- return data;
774
- }
775
- async function fetchWithRefresh(url, init) {
776
- const fetchFn = getFetch3();
777
- const response = await fetchFn(url, init);
778
- if (response.status === 403) {
779
- const refreshed = await tryRefreshToken();
780
- if (refreshed) {
781
- const newHeaders = { ...buildHeaders() };
782
- const oldHeaders = init.headers;
783
- if (oldHeaders) {
784
- for (const [k, v] of Object.entries(oldHeaders)) {
785
- if (k !== "Authorization") newHeaders[k] = v;
786
- }
787
- }
788
- const retryResponse = await fetchFn(url, { ...init, headers: newHeaders });
789
- return handleResponse(retryResponse);
790
- }
791
- }
792
- return handleResponse(response);
793
- }
794
- var http = {
795
- async get(endpoint, params) {
796
- return fetchWithRefresh(buildUrl(endpoint, params), {
797
- method: "GET",
798
- headers: buildHeaders()
799
- });
800
- },
801
- async post(endpoint, body) {
802
- return fetchWithRefresh(buildUrl(endpoint), {
803
- method: "POST",
804
- headers: buildHeaders(),
805
- body: body !== void 0 ? JSON.stringify(body) : void 0
806
- });
807
- },
808
- async put(endpoint, body) {
809
- return fetchWithRefresh(buildUrl(endpoint), {
810
- method: "PUT",
811
- headers: buildHeaders(),
812
- body: body !== void 0 ? JSON.stringify(body) : void 0
813
- });
814
- },
815
- async del(endpoint, params) {
816
- return fetchWithRefresh(buildUrl(endpoint, params), {
817
- method: "DELETE",
818
- headers: buildHeaders()
819
- });
820
- },
821
- async delBody(endpoint, body) {
822
- return fetchWithRefresh(buildUrl(endpoint), {
823
- method: "DELETE",
824
- headers: buildHeaders(),
825
- body: body !== void 0 ? JSON.stringify(body) : void 0
826
- });
827
- },
828
- async upload(endpoint, formData) {
829
- const config = getConfig();
830
- const headers = {};
831
- if (config.token) headers["Authorization"] = formatToken(config.token);
832
- return fetchWithRefresh(buildUrl(endpoint), {
833
- method: "POST",
834
- headers,
835
- body: formData
836
- });
837
- }
838
- };
839
- async function requestWithTenant(method, endpoint, tenantId, options) {
840
- const headers = {
841
- ...buildHeaders(),
842
- "X-TenantID": String(tenantId)
843
- };
844
- return fetchWithRefresh(buildUrl(endpoint, options == null ? void 0 : options.params), {
845
- method,
846
- headers,
847
- body: (options == null ? void 0 : options.body) !== void 0 ? JSON.stringify(options.body) : void 0
848
- });
849
- }
850
- var httpTenant = {
851
- get(endpoint, tenantId, params) {
852
- return requestWithTenant("GET", endpoint, tenantId, { params });
853
- },
854
- post(endpoint, tenantId, body, params) {
855
- return requestWithTenant("POST", endpoint, tenantId, { body, params });
856
- },
857
- put(endpoint, tenantId, body, params) {
858
- return requestWithTenant("PUT", endpoint, tenantId, { body, params });
859
- },
860
- patch(endpoint, tenantId, body, params) {
861
- return requestWithTenant("PATCH", endpoint, tenantId, { body, params });
862
- },
863
- del(endpoint, tenantId, params) {
864
- return requestWithTenant("DELETE", endpoint, tenantId, { params });
865
- }
866
- };
867
-
868
- // src/services.ts
869
- async function executeDataLoaderMitra(options) {
870
- const body = {
871
- projectId: resolveProjectId2(options.projectId),
872
- dataLoaderId: options.dataLoaderId
873
- };
874
- if (options.input !== void 0) body.input = options.input;
875
- return http.post("/interactions/executeDataLoader", body);
876
- }
877
- async function executeDbActionMitra(options) {
878
- const body = {
879
- projectId: resolveProjectId2(options.projectId),
880
- dbActionId: options.dbActionId
881
- };
882
- if (options.input !== void 0) {
883
- body.input = options.input;
884
- }
885
- return http.post("/interactions/executeDbAction", body);
886
- }
887
- async function setFileStatusMitra(options) {
888
- return http.post("/interactions/setFileStatus", {
889
- projectId: resolveProjectId2(options.projectId),
890
- fileName: options.fileName,
891
- targetPath: options.targetPath
892
- });
893
- }
894
- async function setVariableMitra(options) {
895
- const body = {
896
- projectId: resolveProjectId2(options.projectId),
897
- key: options.key
898
- };
899
- if (options.value !== void 0) {
900
- body.value = options.value;
901
- }
902
- return http.post("/interactions/setVariable", body);
903
- }
904
- async function listVariablesMitra(options = {}) {
905
- return http.get("/interactions/listVariables", {
906
- projectId: resolveProjectId2(options.projectId)
907
- });
908
- }
909
- async function getVariableMitra(options) {
910
- return http.get("/interactions/getVariable", {
911
- projectId: resolveProjectId2(options.projectId),
912
- key: options.key
913
- });
914
- }
915
- async function runActionMitra(options) {
916
- const body = {
917
- projectId: resolveProjectId2(options.projectId),
918
- actionId: options.actionId
919
- };
920
- if (options.input !== void 0) {
921
- body.input = options.input;
922
- }
923
- return http.post("/interactions/runAction", body);
924
- }
925
- async function executeServerFunctionMitra(options) {
926
- const body = {
927
- projectId: resolveProjectId2(options.projectId),
928
- serverFunctionId: options.serverFunctionId
929
- };
930
- if (options.input !== void 0) {
931
- body.input = options.input;
932
- }
933
- return http.post("/interactions/executeServerFunction", body);
934
- }
935
- async function executeServerFunctionAsyncMitra(options) {
936
- const body = {
937
- projectId: resolveProjectId2(options.projectId),
938
- serverFunctionId: options.serverFunctionId
939
- };
940
- if (options.input !== void 0) {
941
- body.input = options.input;
942
- }
943
- return http.post("/interactions/executeServerFunctionAsync", body);
944
- }
945
- async function executePublicServerFunctionMitra(options) {
946
- const { projectId, serverFunctionId, input } = options;
947
- const baseURL = getConfig().baseURL;
948
- const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/execute`;
949
- const response = await fetch(url, {
950
- method: "POST",
951
- headers: { "Content-Type": "application/json" },
952
- body: JSON.stringify(input || {})
953
- });
954
- if (!response.ok) {
955
- const data = await response.json().catch(() => null);
956
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
957
- throw { message: msg, status: response.status, details: data };
958
- }
959
- return response.json();
960
- }
961
- async function executePublicServerFunctionAsyncMitra(options) {
962
- const { projectId, serverFunctionId, input } = options;
963
- const baseURL = getConfig().baseURL;
964
- const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/executeAsync`;
965
- const response = await fetch(url, {
966
- method: "POST",
967
- headers: { "Content-Type": "application/json" },
968
- body: JSON.stringify(input || {})
969
- });
970
- if (!response.ok) {
971
- const data = await response.json().catch(() => null);
972
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
973
- throw { message: msg, status: response.status, details: data };
974
- }
975
- return response.json();
976
- }
977
- async function getPublicServerFunctionExecutionMitra(options) {
978
- const { projectId, executionId } = options;
979
- const baseURL = getConfig().baseURL;
980
- const url = `${baseURL}/public/serverFunction/${projectId}/execution/${executionId}`;
981
- const response = await fetch(url, {
982
- method: "GET",
983
- headers: { "Content-Type": "application/json" }
984
- });
985
- if (!response.ok) {
986
- const data = await response.json().catch(() => null);
987
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
988
- throw { message: msg, status: response.status, details: data };
989
- }
990
- return response.json();
991
- }
992
- async function listIntegrationsMitra(options = {}) {
993
- return http.get("/interactions/integrations", {
994
- projectId: resolveProjectId2(options.projectId)
995
- });
996
- }
997
- async function callIntegrationMitra(options) {
998
- const body = {
999
- integrationSlug: options.connection,
1000
- projectId: resolveProjectId2(options.projectId),
1001
- method: options.method
1002
- };
1003
- if (options.endpoint !== void 0) {
1004
- body.endpoint = options.endpoint;
1005
- }
1006
- if (options.params !== void 0) {
1007
- body.params = options.params;
1008
- }
1009
- if (options.body !== void 0) {
1010
- body.body = options.body;
1011
- }
1012
- return http.post("/interactions/integrations/call", body);
1013
- }
1014
- async function stopServerFunctionExecutionMitra(options) {
1015
- return http.post("/interactions/stopServerFunctionExecution", {
1016
- projectId: resolveProjectId2(options.projectId),
1017
- executionId: options.executionId
1018
- });
1019
- }
1020
- async function uploadFilePublicMitra(options) {
1021
- const formData = new FormData();
1022
- formData.append("file", options.file);
1023
- formData.append("projectId", String(resolveProjectId2(options.projectId)));
1024
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
1025
- return http.upload("/interactions/uploadFilePublic", formData);
1026
- }
1027
- async function uploadFileLoadableMitra(options) {
1028
- const formData = new FormData();
1029
- formData.append("file", options.file);
1030
- formData.append("projectId", String(resolveProjectId2(options.projectId)));
1031
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
1032
- return http.upload("/interactions/uploadFileLoadable", formData);
1033
- }
1034
- async function listRecordsMitra(options) {
1035
- const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
1036
- const pid = resolveProjectId2(options.projectId);
1037
- return httpTenant.get(`/interactions/records/${tableName}`, pid, { page, size, jdbcConnectionConfigId, ...filters });
1038
- }
1039
- async function getRecordMitra(options) {
1040
- const { tableName, id, jdbcConnectionConfigId } = options;
1041
- const pid = resolveProjectId2(options.projectId);
1042
- return httpTenant.get(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1043
- }
1044
- async function createRecordMitra(options) {
1045
- const { tableName, data, jdbcConnectionConfigId } = options;
1046
- const pid = resolveProjectId2(options.projectId);
1047
- return httpTenant.post(`/interactions/records/${tableName}`, pid, data, { jdbcConnectionConfigId });
1048
- }
1049
- async function updateRecordMitra(options) {
1050
- const { tableName, id, data, jdbcConnectionConfigId } = options;
1051
- const pid = resolveProjectId2(options.projectId);
1052
- return httpTenant.put(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1053
- }
1054
- async function patchRecordMitra(options) {
1055
- const { tableName, id, data, jdbcConnectionConfigId } = options;
1056
- const pid = resolveProjectId2(options.projectId);
1057
- return httpTenant.patch(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1058
- }
1059
- async function deleteRecordMitra(options) {
1060
- const { tableName, id, jdbcConnectionConfigId } = options;
1061
- const pid = resolveProjectId2(options.projectId);
1062
- return httpTenant.del(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1063
- }
1064
- async function createRecordsBatchMitra(options) {
1065
- const { tableName, records, jdbcConnectionConfigId } = options;
1066
- const pid = resolveProjectId2(options.projectId);
1067
- return httpTenant.post(`/interactions/records/${tableName}/batch`, pid, records, { jdbcConnectionConfigId });
1068
- }
1069
- async function listProfilesMitra(options = {}) {
1070
- return http.get("/interactions/profiles", { projectId: resolveProjectId2(options.projectId) });
1071
- }
1072
- async function getProfileDetailsMitra(options) {
1073
- return http.get(`/interactions/profiles/${options.profileId}`, { projectId: resolveProjectId2(options.projectId) });
1074
- }
1075
- async function createProfileMitra(options) {
1076
- const body = {
1077
- projectId: resolveProjectId2(options.projectId),
1078
- name: options.name
1079
- };
1080
- if (options.color !== void 0) body.color = options.color;
1081
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
1082
- return http.post("/interactions/profiles", body);
1083
- }
1084
- async function updateProfileMitra(options) {
1085
- const body = {
1086
- projectId: resolveProjectId2(options.projectId),
1087
- profileId: options.profileId
1088
- };
1089
- if (options.name !== void 0) body.name = options.name;
1090
- if (options.color !== void 0) body.color = options.color;
1091
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
1092
- return http.put("/interactions/profiles", body);
1093
- }
1094
- async function deleteProfileMitra(options) {
1095
- return http.delBody("/interactions/profiles", {
1096
- projectId: resolveProjectId2(options.projectId),
1097
- profileId: options.profileId
1098
- });
1099
- }
1100
- async function setProfileUsersMitra(options) {
1101
- return http.post("/interactions/profiles/users", {
1102
- projectId: resolveProjectId2(options.projectId),
1103
- profileId: options.profileId,
1104
- userIds: options.userIds
1105
- });
1106
- }
1107
- async function setProfileSelectTablesMitra(options) {
1108
- const body = {
1109
- projectId: resolveProjectId2(options.projectId),
1110
- profileId: options.profileId,
1111
- tables: options.tables
1112
- };
1113
- if (options.jdbcConnectionConfigId !== void 0) body.jdbcConnectionConfigId = options.jdbcConnectionConfigId;
1114
- return http.post("/interactions/profiles/selectTables", body);
1115
- }
1116
- async function setProfileDmlTablesMitra(options) {
1117
- const body = {
1118
- projectId: resolveProjectId2(options.projectId),
1119
- profileId: options.profileId,
1120
- tables: options.tables
1121
- };
1122
- if (options.jdbcConnectionConfigId !== void 0) body.jdbcConnectionConfigId = options.jdbcConnectionConfigId;
1123
- return http.post("/interactions/profiles/dmlTables", body);
1124
- }
1125
- async function setProfileActionsMitra(options) {
1126
- return http.post("/interactions/profiles/actions", {
1127
- projectId: resolveProjectId2(options.projectId),
1128
- profileId: options.profileId,
1129
- actionIds: options.actionIds
1130
- });
1131
- }
1132
- async function setProfileScreensMitra(options) {
1133
- return http.post("/interactions/profiles/screens", {
1134
- projectId: resolveProjectId2(options.projectId),
1135
- profileId: options.profileId,
1136
- screenIds: options.screenIds
1137
- });
1138
- }
1139
- async function setProfileServerFunctionsMitra(options) {
1140
- return http.post("/interactions/profiles/serverFunctions", {
1141
- projectId: resolveProjectId2(options.projectId),
1142
- profileId: options.profileId,
1143
- serverFunctionIds: options.serverFunctionIds
1144
- });
1145
- }
1146
-
1147
- // src/agent-attachments.ts
1148
- var EXTENSION_MAP = {
1149
- // Images
1150
- png: "image",
1151
- jpg: "image",
1152
- jpeg: "image",
1153
- gif: "image",
1154
- webp: "image",
1155
- svg: "image",
1156
- bmp: "image",
1157
- ico: "image",
1158
- // PDF
1159
- pdf: "pdf",
1160
- // CSV
1161
- csv: "csv",
1162
- tsv: "csv",
1163
- // Excel
1164
- xlsx: "excel",
1165
- xls: "excel",
1166
- xlsm: "excel",
1167
- xlsb: "excel",
1168
- ods: "excel",
1169
- // Word
1170
- docx: "word",
1171
- doc: "word",
1172
- odt: "word",
1173
- rtf: "word",
1174
- // PowerPoint
1175
- pptx: "powerpoint",
1176
- ppt: "powerpoint",
1177
- odp: "powerpoint",
1178
- // Text
1179
- txt: "text",
1180
- md: "text",
1181
- log: "text",
1182
- ini: "text",
1183
- cfg: "text",
1184
- env: "text",
1185
- // Code
1186
- js: "code",
1187
- ts: "code",
1188
- jsx: "code",
1189
- tsx: "code",
1190
- py: "code",
1191
- rb: "code",
1192
- java: "code",
1193
- c: "code",
1194
- cpp: "code",
1195
- h: "code",
1196
- cs: "code",
1197
- go: "code",
1198
- rs: "code",
1199
- php: "code",
1200
- swift: "code",
1201
- kt: "code",
1202
- scala: "code",
1203
- html: "code",
1204
- css: "code",
1205
- scss: "code",
1206
- less: "code",
1207
- sql: "code",
1208
- sh: "code",
1209
- bash: "code",
1210
- zsh: "code",
1211
- yaml: "code",
1212
- yml: "code",
1213
- toml: "code",
1214
- xml: "code",
1215
- vue: "code",
1216
- svelte: "code",
1217
- // JSON
1218
- json: "json",
1219
- jsonl: "json",
1220
- geojson: "json",
1221
- // ZIP
1222
- zip: "zip",
1223
- tar: "zip",
1224
- gz: "zip",
1225
- rar: "zip",
1226
- "7z": "zip",
1227
- // Audio
1228
- mp3: "audio",
1229
- wav: "audio",
1230
- ogg: "audio",
1231
- flac: "audio",
1232
- m4a: "audio",
1233
- aac: "audio",
1234
- wma: "audio"
1235
- };
1236
- function detectAttachmentType(file) {
1237
- var _a, _b;
1238
- const ext = (_b = (_a = file.name.split(".").pop()) == null ? void 0 : _a.toLowerCase()) != null ? _b : "";
1239
- if (EXTENSION_MAP[ext]) return EXTENSION_MAP[ext];
1240
- if (file.type.startsWith("image/")) return "image";
1241
- if (file.type === "application/pdf") return "pdf";
1242
- if (file.type.startsWith("audio/")) return "audio";
1243
- if (file.type.startsWith("text/")) return "text";
1244
- return "unknown";
1245
- }
1246
- async function buildAttachmentsFromFiles(files, projectId) {
1247
- return Promise.all(
1248
- files.map(async (file) => {
1249
- var _a;
1250
- const type = detectAttachmentType(file);
1251
- const res = await uploadFilePublicMitra({ file, projectId });
1252
- const url = (_a = res.result) == null ? void 0 : _a.publicUrl;
1253
- if (!url) {
1254
- throw new Error(`upload sem URL p\xFAblica: ${file.name}`);
1255
- }
1256
- return {
1257
- url,
1258
- name: file.name,
1259
- type,
1260
- mimeType: file.type,
1261
- size: file.size
1262
- };
1263
- })
1264
- );
1265
- }
1266
-
1267
- // src/agent-task-session.ts
1268
- var QUEUE_MAX = 10;
1269
- var TURN_STARTED_SAFETY_MS = 3e4;
1270
- var sessionCounter = 0;
1271
- var AgentTaskSession = class {
1272
- constructor(init, transport2) {
1273
- // ── Identidade ────────────────────────
1274
- this._taskId = null;
1275
- this._task = null;
1276
- // ── Estado ────────────────────────────
1277
- this._status = "opening";
1278
- this._history = [];
1279
- this._content = "";
1280
- this._queue = [];
1281
- // ── Cancel state ──────────────────────
1282
- this._cancelled = false;
1283
- this._awaitingTurnStarted = false;
1284
- this._turnStartedTimer = null;
1285
- this._pendingCancelResolve = null;
1286
- // ── Listeners ─────────────────────────
1287
- this._listeners = /* @__PURE__ */ new Map();
1288
- this._wsUnsubscribe = null;
1289
- this._wsUnsubscribePending = null;
1290
- this._transport = transport2;
1291
- this._sessionId = `sess-${++sessionCounter}-${Date.now()}`;
1292
- this._isNew = init.kind === "new";
1293
- if (init.kind === "new") {
1294
- this._projectId = init.projectId;
1295
- this._agentType = init.agentType;
1296
- this._modelId = init.modelId;
1297
- this._initialName = init.name;
1298
- this._setStatus("idle");
1299
- this._wsUnsubscribePending = this._transport.subscribePending(
1300
- this._sessionId,
1301
- (msg) => this._handleMessage(msg)
1302
- );
1303
- } else {
1304
- this._taskId = init.taskId;
1305
- this._transport.register(init.taskId, this);
1306
- this._wsUnsubscribe = this._transport.subscribe(
1307
- init.taskId,
1308
- (msg) => this._handleMessage(msg)
1309
- );
1310
- this._initExisting(init.taskId);
1311
- }
1312
- }
1313
- // ── Properties públicas ────────────────────────────
1314
- get taskId() {
1315
- return this._taskId;
1316
- }
1317
- get task() {
1318
- return this._task;
1319
- }
1320
- get isNew() {
1321
- return this._isNew;
1322
- }
1323
- get status() {
1324
- return this._status;
1325
- }
1326
- get history() {
1327
- return this._history;
1328
- }
1329
- get content() {
1330
- return this._content;
1331
- }
1332
- get queue() {
1333
- return this._queue;
1334
- }
1335
- // ── Lifecycle ──────────────────────────────────────
1336
- async _initExisting(taskId) {
1337
- try {
1338
- await this._transport.ensureConnected();
1339
- if (this._status === "closed") return;
1340
- if (this._transport.isStreaming(taskId)) {
1341
- this._setStatus("streaming");
1342
- } else {
1343
- this._setStatus("idle");
1344
- }
1345
- } catch (err) {
1346
- this._emitError(err instanceof Error ? err.message : String(err));
1347
- }
1348
- }
1349
- async loadHistory(options) {
1350
- if (this._status === "closed") {
1351
- throw new Error("AgentTaskSession: session fechada.");
1352
- }
1353
- if (!this._taskId) {
1354
- this._history = [];
1355
- this._emit("historyLoaded", []);
1356
- return [];
1357
- }
1358
- await this._transport.ensureConnected();
1359
- const payload = { taskId: this._taskId };
1360
- if ((options == null ? void 0 : options.limit) != null) payload.limit = options.limit;
1361
- const msgs = await this._transport.request("get_history", payload);
1362
- this._history = msgs;
1363
- this._emit("historyLoaded", msgs);
1364
- return msgs;
1365
- }
1366
- close() {
1367
- if (this._status === "closed") return;
1368
- this._setStatus("closed");
1369
- if (this._turnStartedTimer) {
1370
- clearTimeout(this._turnStartedTimer);
1371
- this._turnStartedTimer = null;
1372
- }
1373
- if (this._wsUnsubscribe) {
1374
- this._wsUnsubscribe();
1375
- this._wsUnsubscribe = null;
1376
- }
1377
- if (this._wsUnsubscribePending) {
1378
- this._wsUnsubscribePending();
1379
- this._wsUnsubscribePending = null;
1380
- }
1381
- this._transport.unregister(this._taskId, this._sessionId);
1382
- this._listeners.clear();
1383
- }
1384
- // ── Comandos ───────────────────────────────────────
1385
- send(prompt, options) {
1386
- var _a, _b, _c, _d;
1387
- if (this._status === "closed") {
1388
- throw new Error("AgentTaskSession: session fechada.");
1389
- }
1390
- const files = ((_a = options == null ? void 0 : options.files) == null ? void 0 : _a.length) ? options.files : void 0;
1391
- if (!prompt.trim() && !files) return;
1392
- const agentType = (_c = (_b = options == null ? void 0 : options.agentType) != null ? _b : this._agentType) != null ? _c : "claudecode";
1393
- const modelId = (_d = options == null ? void 0 : options.modelId) != null ? _d : this._modelId;
1394
- if (files) {
1395
- void this._uploadThenDispatch(prompt, agentType, modelId, files);
1396
- return;
1397
- }
1398
- this._dispatchSend(prompt, agentType, modelId, void 0);
1399
- }
1400
- async _uploadThenDispatch(prompt, agentType, modelId, files) {
1401
- const wasStreaming = this._status === "streaming";
1402
- if (!wasStreaming) this._setStatus("uploading");
1403
- let attachments;
1404
- try {
1405
- attachments = await buildAttachmentsFromFiles(files, this._projectId);
1406
- } catch (err) {
1407
- this._emit("error", {
1408
- error: `Falha ao subir anexos: ${err instanceof Error ? err.message : String(err)}`
1409
- });
1410
- if (this._status === "uploading") this._setStatus("idle");
1411
- return;
1412
- }
1413
- if (this._status === "closed") return;
1414
- this._dispatchSend(prompt, agentType, modelId, attachments);
1415
- }
1416
- _dispatchSend(prompt, agentType, modelId, attachments) {
1417
- var _a;
1418
- if (this._status === "streaming") {
1419
- this._enqueue(prompt, agentType);
1420
- if (this._taskId) {
1421
- this._transport.send(
1422
- "send_prompt",
1423
- {
1424
- prompt,
1425
- taskId: this._taskId,
1426
- projectId: this._projectId,
1427
- agentType,
1428
- ...modelId ? { modelId } : {},
1429
- ...attachments ? { attachments } : {},
1430
- midSession: true
1431
- },
1432
- this._taskId
1433
- );
1434
- }
1435
- return;
1436
- }
1437
- if (this._status === "cancelled") {
1438
- this._awaitingTurnStarted = true;
1439
- if (this._turnStartedTimer) clearTimeout(this._turnStartedTimer);
1440
- this._turnStartedTimer = setTimeout(() => {
1441
- this._turnStartedTimer = null;
1442
- if (this._awaitingTurnStarted) {
1443
- this._cancelled = false;
1444
- this._awaitingTurnStarted = false;
1445
- this._setStatus("idle");
1446
- }
1447
- }, TURN_STARTED_SAFETY_MS);
1448
- }
1449
- this._setStatus("streaming");
1450
- this._content = "";
1451
- const payload = {
1452
- prompt,
1453
- projectId: this._projectId,
1454
- agentType
1455
- };
1456
- if (modelId) payload.modelId = modelId;
1457
- if (attachments) payload.attachments = attachments;
1458
- if (this._taskId) payload.taskId = this._taskId;
1459
- if (this._initialName && !this._taskId) {
1460
- payload.name = this._initialName;
1461
- }
1462
- this._transport.send("send_prompt", payload, (_a = this._taskId) != null ? _a : void 0);
1463
- }
1464
- async cancel() {
1465
- if (this._status === "closed") return;
1466
- if (this._status !== "streaming" && this._status !== "cancelled") return;
1467
- this._cancelled = true;
1468
- this._clearQueue();
1469
- if (this._taskId) {
1470
- this._transport.send(
1471
- "task_cancel",
1472
- { source: "sdk_cancel" },
1473
- this._taskId
1474
- );
1475
- }
1476
- this._setStatus("cancelled");
1477
- this._emit("cancelled", void 0);
1478
- return new Promise((resolve) => {
1479
- const previousResolve = this._pendingCancelResolve;
1480
- this._pendingCancelResolve = () => {
1481
- resolve();
1482
- if (previousResolve) previousResolve();
1483
- };
1484
- setTimeout(() => {
1485
- if (this._pendingCancelResolve) {
1486
- this._pendingCancelResolve = null;
1487
- resolve();
1488
- }
1489
- }, TURN_STARTED_SAFETY_MS);
1490
- });
1491
- }
1492
- // ── Manipulação de fila ────────────────────────────
1493
- editQueueItem(itemId, newText) {
1494
- const idx = this._queue.findIndex((q) => q.id === itemId);
1495
- if (idx < 0 || this._queue[idx].status !== "pending") return false;
1496
- this._queue = [
1497
- ...this._queue.slice(0, idx),
1498
- { ...this._queue[idx], text: newText },
1499
- ...this._queue.slice(idx + 1)
1500
- ];
1501
- this._emitQueueChange();
1502
- return true;
1503
- }
1504
- removeQueueItem(itemId) {
1505
- const before = this._queue.length;
1506
- this._queue = this._queue.filter((q) => q.id !== itemId);
1507
- if (this._queue.length === before) return false;
1508
- this._emitQueueChange();
1509
- return true;
1510
- }
1511
- clearQueue() {
1512
- if (this._queue.length === 0) return;
1513
- this._clearQueue();
1514
- }
1515
- // ── Eventos ────────────────────────────────────────
1516
- on(event, handler) {
1517
- if (!this._listeners.has(event)) {
1518
- this._listeners.set(event, /* @__PURE__ */ new Set());
1519
- }
1520
- this._listeners.get(event).add(handler);
1521
- return () => {
1522
- var _a;
1523
- (_a = this._listeners.get(event)) == null ? void 0 : _a.delete(handler);
1524
- };
1525
- }
1526
- // ── Internals: routing de mensagens WS ─────────────
1527
- _handleMessage(msg) {
1528
- var _a, _b, _c, _d, _e, _f;
1529
- if (!(msg == null ? void 0 : msg.type)) return;
1530
- if (this._cancelled && msg.type !== "turn_started" && msg.type !== "error" && msg.type !== "task_update") {
1531
- return;
1532
- }
1533
- const payload = (_a = msg.payload) != null ? _a : {};
1534
- switch (msg.type) {
1535
- case "task_update": {
1536
- if (payload.action !== "created") return;
1537
- const task = payload.task;
1538
- if (!task) return;
1539
- if (!this._taskId) {
1540
- this._taskId = task.id;
1541
- this._task = task;
1542
- this._transport.register(task.id, this);
1543
- if (this._wsUnsubscribePending) {
1544
- this._wsUnsubscribePending();
1545
- this._wsUnsubscribePending = null;
1546
- }
1547
- this._wsUnsubscribe = this._transport.subscribe(
1548
- task.id,
1549
- (m) => this._handleMessage(m)
1550
- );
1551
- this._emit("taskCreated", { task });
1552
- } else if (this._taskId === task.id) {
1553
- this._task = task;
1554
- }
1555
- break;
1556
- }
1557
- case "turn_started": {
1558
- if (this._cancelled) {
1559
- this._cancelled = false;
1560
- this._awaitingTurnStarted = false;
1561
- if (this._turnStartedTimer) {
1562
- clearTimeout(this._turnStartedTimer);
1563
- this._turnStartedTimer = null;
1564
- }
1565
- if (this._pendingCancelResolve) {
1566
- this._pendingCancelResolve();
1567
- this._pendingCancelResolve = null;
1568
- }
1569
- }
1570
- if (this._status !== "streaming") {
1571
- this._setStatus("streaming");
1572
- this._content = "";
1573
- }
1574
- this._emit("turnStart", void 0);
1575
- break;
1576
- }
1577
- case "stream_delta": {
1578
- const kind = payload.subtype === "thinking" ? "tool" : "text";
1579
- const delta = String((_b = payload.delta) != null ? _b : "");
1580
- if (kind === "text") this._content += delta;
1581
- this._emit("delta", { delta, kind });
1582
- break;
1583
- }
1584
- case "stream_tool_activity": {
1585
- this._emit("tool", {
1586
- tool: String((_c = payload.tool) != null ? _c : ""),
1587
- input: payload.input,
1588
- content: payload.content,
1589
- timestamp: Number((_d = msg.timestamp) != null ? _d : Date.now())
1590
- });
1591
- break;
1592
- }
1593
- case "stream_end": {
1594
- const finalContent = this._content;
1595
- this._emit("turnEnd", { content: finalContent });
1596
- this._setStatus("idle");
1597
- this._shiftQueueAndSend();
1598
- break;
1599
- }
1600
- case "error": {
1601
- const error = String((_f = (_e = payload.error) != null ? _e : msg.error) != null ? _f : "Erro desconhecido");
1602
- this._emitError(error);
1603
- break;
1604
- }
1605
- }
1606
- }
1607
- // ── Fila interna ───────────────────────────────────
1608
- _enqueue(text, agentType) {
1609
- if (this._queue.length >= QUEUE_MAX) return;
1610
- const trimmed = text.trim();
1611
- if (this._queue.some((q) => q.text.trim() === trimmed)) return;
1612
- const item = {
1613
- id: `q-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
1614
- text,
1615
- agentType,
1616
- seq: this._transport.nextSeq(),
1617
- createdAt: Date.now(),
1618
- status: "pending"
1619
- };
1620
- this._queue = [...this._queue, item];
1621
- this._emitQueueChange();
1622
- }
1623
- _shiftQueueAndSend() {
1624
- if (this._queue.length === 0) return;
1625
- const [next, ...rest] = this._queue;
1626
- this._queue = rest;
1627
- this._emitQueueChange();
1628
- this.send(next.text, { agentType: next.agentType });
1629
- }
1630
- _clearQueue() {
1631
- if (this._queue.length === 0) return;
1632
- this._queue = [];
1633
- this._emitQueueChange();
1634
- }
1635
- // ── Helpers de emissão ─────────────────────────────
1636
- _emit(event, payload) {
1637
- const set = this._listeners.get(event);
1638
- if (!set) return;
1639
- for (const handler of set) {
1640
- try {
1641
- handler(payload);
1642
- } catch (err) {
1643
- console.error(`[AgentTaskSession] handler de '${event}' lan\xE7ou:`, err);
1644
- }
1645
- }
1646
- }
1647
- _emitError(error) {
1648
- this._emit("error", { error });
1649
- this._setStatus("error");
1650
- }
1651
- _emitQueueChange() {
1652
- this._emit("queueChange", { queue: this._queue });
1653
- }
1654
- _setStatus(next) {
1655
- if (this._status === next) return;
1656
- const previous = this._status;
1657
- this._status = next;
1658
- this._emit("statusChange", { status: next, previous });
1659
- }
1660
- };
1661
-
1662
- // src/agent-chat.ts
1663
- var ws = null;
1664
- var connectPromise = null;
1665
- var requestSeq = 0;
1666
- var queueSeq = 0;
1667
- var pendingRequests = /* @__PURE__ */ new Map();
1668
- var sessionsByTaskId = /* @__PURE__ */ new Map();
1669
- var handlersByTaskId = /* @__PURE__ */ new Map();
1670
- var pendingHandlers = /* @__PURE__ */ new Map();
1671
- var streamingTaskIds = /* @__PURE__ */ new Set();
1672
- function nextRequestId() {
1673
- return `req-${Date.now()}-${++requestSeq}`;
1674
- }
1675
- function nextQueueSeq() {
1676
- return ++queueSeq;
1677
- }
1678
- function getRawToken() {
1679
- const config = getConfig();
1680
- if (!config.token) {
1681
- throw new Error("Agent Chat: token n\xE3o configurado. Fa\xE7a login primeiro ou passe token em configureSdkMitra.");
1682
- }
1683
- return stripBearer(config.token);
1684
- }
1685
- function resolveProjectId3(override) {
1686
- const config = getConfig();
1687
- const pid = override != null ? override : config.projectId;
1688
- if (pid == null) {
1689
- throw new Error("Agent Chat: projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
1690
- }
1691
- return pid;
1692
- }
1693
- function getWsUrl() {
1694
- var _a;
1695
- if (typeof window !== "undefined") {
1696
- const injected = (_a = window.__mitraEnv) == null ? void 0 : _a.agentWsUrl;
1697
- if (typeof injected === "string" && injected) return injected;
1698
- }
1699
- throw new Error("Agent Chat: window.__mitraEnv.agentWsUrl indispon\xEDvel. A SDK precisa rodar em uma app publicada pelo Mitra (build-proxy injeta __mitraEnv).");
1700
- }
1701
- function connect() {
1702
- if (ws && ws.readyState === WebSocket.OPEN) {
1703
- return Promise.resolve(ws);
1704
- }
1705
- if (connectPromise) return connectPromise;
1706
- const baseUrl = getWsUrl();
1707
- const token = getRawToken();
1708
- const separator = baseUrl.includes("?") ? "&" : "?";
1709
- const url = `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
1710
- connectPromise = new Promise((resolve, reject) => {
1711
- const socket = new WebSocket(url);
1712
- let opened = false;
1713
- const timer = setTimeout(() => {
1714
- if (!opened) {
1715
- try {
1716
- socket.close();
1717
- } catch (e) {
1718
- }
1719
- connectPromise = null;
1720
- reject(new Error("Agent Chat: timeout ao conectar no WebSocket"));
1721
- }
1722
- }, 15e3);
1723
- socket.onopen = () => {
1724
- opened = true;
1725
- clearTimeout(timer);
1726
- ws = socket;
1727
- connectPromise = null;
1728
- resolve(socket);
1729
- };
1730
- socket.onerror = () => {
1731
- if (!opened) {
1732
- clearTimeout(timer);
1733
- connectPromise = null;
1734
- reject(new Error("Agent Chat: erro ao conectar no WebSocket"));
1735
- }
1736
- };
1737
- socket.onclose = () => {
1738
- if (ws === socket) ws = null;
1739
- for (const [id, pending] of pendingRequests) {
1740
- pending.reject(new Error("Agent Chat: conex\xE3o fechada"));
1741
- pendingRequests.delete(id);
1742
- }
1743
- streamingTaskIds.clear();
1744
- };
1745
- socket.onmessage = (event) => routeMessage(event.data);
1746
- });
1747
- return connectPromise;
1748
- }
1749
- function routeMessage(raw) {
1750
- var _a, _b;
1751
- let msg;
1752
- try {
1753
- msg = typeof raw === "string" ? JSON.parse(raw) : raw;
1754
- } catch (e) {
1755
- return;
1756
- }
1757
- if (!(msg == null ? void 0 : msg.type)) return;
1758
- if (msg.type === "response" && msg.requestId) {
1759
- const pending = pendingRequests.get(msg.requestId);
1760
- if (!pending) return;
1761
- pendingRequests.delete(msg.requestId);
1762
- if (msg.ok) pending.resolve(msg.data);
1763
- else pending.reject(new Error(msg.error || "Erro desconhecido"));
1764
- return;
1765
- }
1766
- if (msg.type === "streaming_state") {
1767
- streamingTaskIds.clear();
1768
- const ids = (_b = (_a = msg.payload) == null ? void 0 : _a.streamingTaskIds) != null ? _b : [];
1769
- for (const id of ids) streamingTaskIds.add(id);
1770
- return;
1771
- }
1772
- if (msg.type === "turn_started" && msg.taskId) {
1773
- streamingTaskIds.add(msg.taskId);
1774
- } else if (msg.type === "stream_end" && msg.taskId) {
1775
- streamingTaskIds.delete(msg.taskId);
1776
- }
1777
- if (msg.taskId) {
1778
- const set = handlersByTaskId.get(msg.taskId);
1779
- if (set) {
1780
- for (const handler of set) handler(msg);
1781
- }
1782
- }
1783
- if (msg.type === "task_update") {
1784
- for (const handler of pendingHandlers.values()) handler(msg);
1785
- }
1786
- }
1787
- var transport = {
1788
- async ensureConnected() {
1789
- await connect();
1790
- },
1791
- async request(type, payload) {
1792
- const socket = await connect();
1793
- const requestId = nextRequestId();
1794
- return new Promise((resolve, reject) => {
1795
- pendingRequests.set(requestId, {
1796
- resolve: (data) => resolve(data),
1797
- reject
1798
- });
1799
- try {
1800
- socket.send(JSON.stringify({ type, requestId, payload }));
1801
- } catch (err) {
1802
- pendingRequests.delete(requestId);
1803
- reject(err instanceof Error ? err : new Error(String(err)));
1804
- }
1805
- });
1806
- },
1807
- send(type, payload, taskId) {
1808
- connect().then((socket) => {
1809
- const requestId = nextRequestId();
1810
- socket.send(JSON.stringify({ type, requestId, payload, taskId }));
1811
- }).catch((err) => {
1812
- console.error("[agent-chat] send falhou:", err);
1813
- });
1814
- },
1815
- resolveProjectId(override) {
1816
- return resolveProjectId3(override);
1817
- },
1818
- nextSeq() {
1819
- return nextQueueSeq();
1820
- },
1821
- subscribe(taskId, handler) {
1822
- if (!handlersByTaskId.has(taskId)) {
1823
- handlersByTaskId.set(taskId, /* @__PURE__ */ new Set());
1824
- }
1825
- handlersByTaskId.get(taskId).add(handler);
1826
- return () => {
1827
- const set = handlersByTaskId.get(taskId);
1828
- if (!set) return;
1829
- set.delete(handler);
1830
- if (set.size === 0) handlersByTaskId.delete(taskId);
1831
- };
1832
- },
1833
- subscribePending(sessionId, handler) {
1834
- pendingHandlers.set(sessionId, handler);
1835
- return () => {
1836
- pendingHandlers.delete(sessionId);
1837
- };
1838
- },
1839
- isStreaming(taskId) {
1840
- return streamingTaskIds.has(taskId);
1841
- },
1842
- register(taskId, session) {
1843
- sessionsByTaskId.set(taskId, session);
1844
- },
1845
- unregister(taskId, _sessionId) {
1846
- if (taskId) sessionsByTaskId.delete(taskId);
1847
- }
1848
- };
1849
- function getTransport() {
1850
- return transport;
1851
- }
1852
- function manageAgentChatMitra(options) {
1853
- var _a;
1854
- if (isNewWorld()) throw new Error("manageAgentChatMitra ainda n\xE3o suportado no novo Mitra.");
1855
- if (options.action === "list") {
1856
- const projectId = resolveProjectId3(options.projectId);
1857
- return transport.request("chats", { action: "list", projectId });
1858
- }
1859
- if (options.action === "rename") {
1860
- if (!options.taskId) throw new Error("manageAgentChatMitra(rename): taskId obrigat\xF3rio.");
1861
- if (!((_a = options.name) == null ? void 0 : _a.trim())) throw new Error("manageAgentChatMitra(rename): name obrigat\xF3rio.");
1862
- return transport.request("chats", { action: "rename", taskId: options.taskId, name: options.name.trim() });
1863
- }
1864
- if (options.action === "delete") {
1865
- if (!options.taskId) throw new Error("manageAgentChatMitra(delete): taskId obrigat\xF3rio.");
1866
- return transport.request("chats", { action: "delete", taskId: options.taskId });
1867
- }
1868
- throw new Error(`manageAgentChatMitra: action inv\xE1lida (${options.action}).`);
1869
- }
1870
- function getAgentTaskMitra(options) {
1871
- if (isNewWorld()) throw new Error("getAgentTaskMitra ainda n\xE3o suportado no novo Mitra.");
1872
- if ("taskId" in options && options.taskId) {
1873
- const cached = sessionsByTaskId.get(options.taskId);
1874
- if (cached) return cached;
1875
- return new AgentTaskSession(
1876
- { kind: "existing", taskId: options.taskId },
1877
- transport
1878
- );
1879
- }
1880
- if ("create" in options && options.create) {
1881
- return new AgentTaskSession(
1882
- {
1883
- kind: "new",
1884
- projectId: options.projectId,
1885
- agentType: options.agentType,
1886
- modelId: options.modelId,
1887
- name: options.name
1888
- },
1889
- transport
1890
- );
1891
- }
1892
- throw new Error("getAgentTaskMitra: passe { create: true } ou { taskId }.");
1893
- }
1894
-
1895
- // src/agent-credentials.ts
1896
- var pendingVerifiers = /* @__PURE__ */ new Map();
1897
- function manageAgentCredentialMitra(options) {
1898
- if (isNewWorld()) throw new Error("manageAgentCredentialMitra ainda n\xE3o suportado no novo Mitra.");
1899
- if (options.action === "auth") return authSubscription(options);
1900
- if (options.action === "connect") return connectSubscription(options);
1901
- return rpc(options);
1902
- }
1903
- function rpc(options) {
1904
- const transport2 = getTransport();
1905
- const { action, target, ...rest } = options;
1906
- const data = {};
1907
- for (const [k, v] of Object.entries(rest)) {
1908
- if (v !== void 0) data[k] = v;
1909
- }
1910
- return transport2.request("credentials", { action, target, data });
1911
- }
1912
- async function authSubscription(options) {
1913
- const { target } = options;
1914
- if (target === "claude") {
1915
- const start = await rpc({
1916
- action: "oauth_start",
1917
- target: "claude"
1918
- });
1919
- pendingVerifiers.set(start.state, start.codeVerifier);
1920
- return { target: "claude", authUrl: start.authUrl, state: start.state };
1921
- }
1922
- if (target === "codex") {
1923
- const start = await rpc({
1924
- action: "device_start",
1925
- target: "codex"
1926
- });
1927
- return {
1928
- target: "codex",
1929
- userCode: start.userCode,
1930
- verificationUrl: start.verificationUrl,
1931
- pollId: start.pollId
1932
- };
1933
- }
1934
- throw new Error(`manageAgentCredentialMitra(auth): target inv\xE1lido (${target}). Use 'claude' ou 'codex'.`);
1935
- }
1936
- function connectSubscription(options) {
1937
- const { target } = options;
1938
- if (target === "claude") return connectClaude(options);
1939
- if (target === "codex") return connectCodex(options);
1940
- throw new Error(`manageAgentCredentialMitra(connect): target inv\xE1lido (${target}). Use 'claude' ou 'codex'.`);
1941
- }
1942
- async function connectClaude(options) {
1943
- var _a;
1944
- const { code, state } = options;
1945
- if (!code || !state) {
1946
- throw new Error("manageAgentCredentialMitra(connect, claude): code e state s\xE3o obrigat\xF3rios (state vem de auth).");
1947
- }
1948
- const codeVerifier = pendingVerifiers.get(state);
1949
- const exchange = await rpc({
1950
- action: "oauth_exchange",
1951
- target: "claude",
1952
- code,
1953
- state,
1954
- // Se a SDK ainda tem o verifier (mesmo runtime), envia; senão o backend
1955
- // resolve via state (pkceStore). Cobre os dois caminhos.
1956
- ...codeVerifier ? { codeVerifier } : {}
1957
- });
1958
- pendingVerifiers.delete(state);
1959
- return {
1960
- target: "claude",
1961
- success: exchange.success === true,
1962
- expiresAt: exchange.expiresAt,
1963
- account: (_a = exchange.account) != null ? _a : null
1964
- };
1965
- }
1966
- async function connectCodex(options) {
1967
- var _a, _b;
1968
- const { pollId } = options;
1969
- if (!pollId) {
1970
- throw new Error("manageAgentCredentialMitra(connect, codex): pollId \xE9 obrigat\xF3rio (vem de auth).");
1971
- }
1972
- const pollInterval = (_a = options.pollIntervalMs) != null ? _a : 2e3;
1973
- const deadline = Date.now() + ((_b = options.deviceTimeoutMs) != null ? _b : 15 * 6e4);
1974
- while (Date.now() < deadline) {
1975
- const result = await rpc({ action: "device_poll", target: "codex", pollId });
1976
- if (result.status === "completed") {
1977
- return { target: "codex", success: true };
1978
- }
1979
- if (result.status === "failed" || result.status === "expired" || result.status === "not_found") {
1980
- throw new Error(`manageAgentCredentialMitra(connect, codex): ${result.status}${result.error ? ` \u2014 ${result.error}` : ""}`);
1981
- }
1982
- await sleep(pollInterval);
1983
- }
1984
- await rpc({ action: "device_cancel", target: "codex", pollId }).catch(() => {
1985
- });
1986
- throw new Error("manageAgentCredentialMitra(connect, codex): timeout.");
1987
- }
1988
- function sleep(ms) {
1989
- return new Promise((r) => setTimeout(r, ms));
1990
- }
1991
-
1992
- // src/instance.ts
1993
- function formatToken2(token) {
1994
- return `Bearer ${stripBearer(token)}`;
1995
- }
1996
- function getFetch4() {
1997
- if (typeof globalThis.fetch === "function") return globalThis.fetch;
1998
- throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
1999
- }
2000
- function buildQuery(params) {
2001
- return Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
2002
- }
2003
- function createMitraInstance(initialConfig) {
2004
- var _a;
2005
- let _config = {
2006
- baseURL: ((_a = initialConfig.baseURL) == null ? void 0 : _a.replace(/\/+$/, "")) || "",
2007
- token: initialConfig.token ? stripBearer(initialConfig.token) : "",
2008
- refreshToken: initialConfig.refreshToken,
2009
- integrationURL: initialConfig.integrationURL,
2010
- authUrl: initialConfig.authUrl,
2011
- projectId: initialConfig.projectId
2012
- };
2013
- function resolveProjectId4(projectId) {
2014
- if (projectId != null) return projectId;
2015
- if (_config.projectId != null) return _config.projectId;
2016
- throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
2017
- }
2018
- function authHeaders() {
2019
- const headers = { "Content-Type": "application/json" };
2020
- if (_config.token) headers["Authorization"] = formatToken2(_config.token);
2021
- return headers;
2022
- }
2023
- async function handleResponse2(response) {
2024
- const text = await response.text();
2025
- const data = text ? JSON.parse(text) : null;
2026
- if (!response.ok) {
2027
- const base = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
2028
- const msg = (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
2029
- throw { message: msg, status: response.status, details: data };
2030
- }
2031
- return data;
541
+ return data;
2032
542
  }
2033
543
  async function tryRefreshToken2() {
2034
544
  var _a2, _b;
2035
545
  if (!_config.token || _config.projectId == null || !_config.baseURL) return false;
2036
546
  try {
2037
547
  const baseURL = _config.baseURL.replace(/\/+$/, "");
2038
- const resp = await getFetch4()(`${baseURL}/mitraspace/project/refreshedToken/${_config.projectId}`, {
548
+ const resp = await getFetch2()(`${baseURL}/mitraspace/project/refreshedToken/${_config.projectId}`, {
2039
549
  method: "GET",
2040
- headers: { "Authorization": formatToken2(_config.token) }
550
+ headers: { "Authorization": formatToken(_config.token) }
2041
551
  });
2042
552
  if (resp.ok) {
2043
553
  const data = await resp.json();
@@ -2070,7 +580,7 @@ function createMitraInstance(initialConfig) {
2070
580
  }
2071
581
  }
2072
582
  async function fetchWithRefresh2(url, init) {
2073
- const fetchFn = getFetch4();
583
+ const fetchFn = getFetch2();
2074
584
  const response = await fetchFn(url, init);
2075
585
  if (response.status === 403) {
2076
586
  const refreshed = await tryRefreshToken2();
@@ -2100,16 +610,6 @@ function createMitraInstance(initialConfig) {
2100
610
  body: (opts == null ? void 0 : opts.body) !== void 0 ? JSON.stringify(opts.body) : void 0
2101
611
  });
2102
612
  }
2103
- async function requestUpload(endpoint, formData) {
2104
- const url = `${_config.baseURL}${endpoint}`;
2105
- const headers = {};
2106
- if (_config.token) headers["Authorization"] = formatToken2(_config.token);
2107
- return fetchWithRefresh2(url, {
2108
- method: "POST",
2109
- headers,
2110
- body: formData
2111
- });
2112
- }
2113
613
  async function requestTenant(method, endpoint, tenantId, opts) {
2114
614
  let url = `${_config.baseURL}${endpoint}`;
2115
615
  if (opts == null ? void 0 : opts.params) {
@@ -2131,51 +631,20 @@ function createMitraInstance(initialConfig) {
2131
631
  _config = { ..._config, token };
2132
632
  },
2133
633
  // Services
2134
- async executeDataLoader(options) {
2135
- const body = { projectId: resolveProjectId4(options.projectId), dataLoaderId: options.dataLoaderId };
2136
- if (options.input !== void 0) body.input = options.input;
2137
- return request("POST", "/interactions/executeDataLoader", { body });
2138
- },
2139
- async executeDbAction(options) {
2140
- const body = { projectId: resolveProjectId4(options.projectId), dbActionId: options.dbActionId };
2141
- if (options.input !== void 0) body.input = options.input;
2142
- return request("POST", "/interactions/executeDbAction", { body });
2143
- },
2144
- async setFileStatus(options) {
2145
- return request("POST", "/interactions/setFileStatus", {
2146
- body: { projectId: resolveProjectId4(options.projectId), fileName: options.fileName, targetPath: options.targetPath }
2147
- });
2148
- },
2149
- async setVariable(options) {
2150
- const body = { projectId: resolveProjectId4(options.projectId), key: options.key };
2151
- if (options.value !== void 0) body.value = options.value;
2152
- return request("POST", "/interactions/setVariable", { body });
2153
- },
2154
- async listVariables(options = {}) {
2155
- return request("GET", "/interactions/listVariables", { params: { projectId: resolveProjectId4(options.projectId) } });
2156
- },
2157
- async getVariable(options) {
2158
- return request("GET", "/interactions/getVariable", { params: { projectId: resolveProjectId4(options.projectId), key: options.key } });
2159
- },
2160
- async runAction(options) {
2161
- const body = { projectId: resolveProjectId4(options.projectId), actionId: options.actionId };
2162
- if (options.input !== void 0) body.input = options.input;
2163
- return request("POST", "/interactions/runAction", { body });
2164
- },
2165
634
  async executeServerFunction(options) {
2166
- const body = { projectId: resolveProjectId4(options.projectId), serverFunctionId: options.serverFunctionId };
635
+ const body = { projectId: resolveProjectId2(options.projectId), serverFunctionId: options.serverFunctionId };
2167
636
  if (options.input !== void 0) body.input = options.input;
2168
637
  return request("POST", "/interactions/executeServerFunction", { body });
2169
638
  },
2170
639
  async executeServerFunctionAsync(options) {
2171
- const body = { projectId: resolveProjectId4(options.projectId), serverFunctionId: options.serverFunctionId };
640
+ const body = { projectId: resolveProjectId2(options.projectId), serverFunctionId: options.serverFunctionId };
2172
641
  if (options.input !== void 0) body.input = options.input;
2173
642
  return request("POST", "/interactions/executeServerFunctionAsync", { body });
2174
643
  },
2175
644
  async executePublicServerFunction(options) {
2176
645
  const { projectId, serverFunctionId, input } = options;
2177
646
  const url = `${_config.baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/execute`;
2178
- const fetchFn = getFetch4();
647
+ const fetchFn = getFetch2();
2179
648
  const response = await fetchFn(url, {
2180
649
  method: "POST",
2181
650
  headers: { "Content-Type": "application/json" },
@@ -2186,7 +655,7 @@ function createMitraInstance(initialConfig) {
2186
655
  async executePublicServerFunctionAsync(options) {
2187
656
  const { projectId, serverFunctionId, input } = options;
2188
657
  const url = `${_config.baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/executeAsync`;
2189
- const fetchFn = getFetch4();
658
+ const fetchFn = getFetch2();
2190
659
  const response = await fetchFn(url, {
2191
660
  method: "POST",
2192
661
  headers: { "Content-Type": "application/json" },
@@ -2197,7 +666,7 @@ function createMitraInstance(initialConfig) {
2197
666
  async getPublicServerFunctionExecution(options) {
2198
667
  const { projectId, executionId } = options;
2199
668
  const url = `${_config.baseURL}/public/serverFunction/${projectId}/execution/${executionId}`;
2200
- const fetchFn = getFetch4();
669
+ const fetchFn = getFetch2();
2201
670
  const response = await fetchFn(url, {
2202
671
  method: "GET",
2203
672
  headers: { "Content-Type": "application/json" }
@@ -2206,32 +675,17 @@ function createMitraInstance(initialConfig) {
2206
675
  },
2207
676
  async stopServerFunctionExecution(options) {
2208
677
  return request("POST", "/interactions/stopServerFunctionExecution", {
2209
- body: { projectId: resolveProjectId4(options.projectId), executionId: options.executionId }
678
+ body: { projectId: resolveProjectId2(options.projectId), executionId: options.executionId }
2210
679
  });
2211
680
  },
2212
- // Upload de Arquivos
2213
- async uploadFilePublic(options) {
2214
- const formData = new FormData();
2215
- formData.append("file", options.file);
2216
- formData.append("projectId", String(resolveProjectId4(options.projectId)));
2217
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
2218
- return requestUpload("/interactions/uploadFilePublic", formData);
2219
- },
2220
- async uploadFileLoadable(options) {
2221
- const formData = new FormData();
2222
- formData.append("file", options.file);
2223
- formData.append("projectId", String(resolveProjectId4(options.projectId)));
2224
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
2225
- return requestUpload("/interactions/uploadFileLoadable", formData);
2226
- },
2227
681
  // Integrations
2228
682
  async listIntegrations(options = {}) {
2229
- return request("GET", "/interactions/integrations", { params: { projectId: resolveProjectId4(options.projectId) } });
683
+ return request("GET", "/interactions/integrations", { params: { projectId: resolveProjectId2(options.projectId) } });
2230
684
  },
2231
685
  async callIntegration(options) {
2232
686
  const body = {
2233
687
  integrationSlug: options.connection,
2234
- projectId: resolveProjectId4(options.projectId),
688
+ projectId: resolveProjectId2(options.projectId),
2235
689
  method: options.method
2236
690
  };
2237
691
  if (options.endpoint !== void 0) body.endpoint = options.endpoint;
@@ -2242,186 +696,450 @@ function createMitraInstance(initialConfig) {
2242
696
  // Dynamic Schema CRUD
2243
697
  async listRecords(options) {
2244
698
  const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
2245
- const pid = resolveProjectId4(options.projectId);
699
+ const pid = resolveProjectId2(options.projectId);
2246
700
  return requestTenant("GET", `/interactions/records/${tableName}`, pid, { params: { page, size, jdbcConnectionConfigId, ...filters } });
2247
701
  },
2248
702
  async getRecord(options) {
2249
703
  const { tableName, id, jdbcConnectionConfigId } = options;
2250
- const pid = resolveProjectId4(options.projectId);
704
+ const pid = resolveProjectId2(options.projectId);
2251
705
  return requestTenant("GET", `/interactions/records/${tableName}/${id}`, pid, { params: { jdbcConnectionConfigId } });
2252
706
  },
2253
707
  async createRecord(options) {
2254
708
  const { tableName, data, jdbcConnectionConfigId } = options;
2255
- const pid = resolveProjectId4(options.projectId);
709
+ const pid = resolveProjectId2(options.projectId);
2256
710
  return requestTenant("POST", `/interactions/records/${tableName}`, pid, { body: data, params: { jdbcConnectionConfigId } });
2257
711
  },
2258
712
  async updateRecord(options) {
2259
713
  const { tableName, id, data, jdbcConnectionConfigId } = options;
2260
- const pid = resolveProjectId4(options.projectId);
714
+ const pid = resolveProjectId2(options.projectId);
2261
715
  return requestTenant("PUT", `/interactions/records/${tableName}/${id}`, pid, { body: data, params: { jdbcConnectionConfigId } });
2262
716
  },
2263
717
  async patchRecord(options) {
2264
718
  const { tableName, id, data, jdbcConnectionConfigId } = options;
2265
- const pid = resolveProjectId4(options.projectId);
719
+ const pid = resolveProjectId2(options.projectId);
2266
720
  return requestTenant("PATCH", `/interactions/records/${tableName}/${id}`, pid, { body: data, params: { jdbcConnectionConfigId } });
2267
721
  },
2268
722
  async deleteRecord(options) {
2269
723
  const { tableName, id, jdbcConnectionConfigId } = options;
2270
- const pid = resolveProjectId4(options.projectId);
724
+ const pid = resolveProjectId2(options.projectId);
2271
725
  return requestTenant("DELETE", `/interactions/records/${tableName}/${id}`, pid, { params: { jdbcConnectionConfigId } });
2272
726
  },
2273
727
  async createRecordsBatch(options) {
2274
728
  const { tableName, records, jdbcConnectionConfigId } = options;
2275
- const pid = resolveProjectId4(options.projectId);
729
+ const pid = resolveProjectId2(options.projectId);
2276
730
  return requestTenant("POST", `/interactions/records/${tableName}/batch`, pid, { body: records, params: { jdbcConnectionConfigId } });
2277
- },
2278
- // Profile Management
2279
- async listProfiles(options = {}) {
2280
- return request("GET", "/interactions/profiles", { params: { projectId: resolveProjectId4(options.projectId) } });
2281
- },
2282
- async getProfileDetails(options) {
2283
- return request("GET", `/interactions/profiles/${options.profileId}`, { params: { projectId: resolveProjectId4(options.projectId) } });
2284
- },
2285
- async createProfile(options) {
2286
- const body = { projectId: resolveProjectId4(options.projectId), name: options.name };
2287
- if (options.color !== void 0) body.color = options.color;
2288
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
2289
- return request("POST", "/interactions/profiles", { body });
2290
- },
2291
- async updateProfile(options) {
2292
- const body = { projectId: resolveProjectId4(options.projectId), profileId: options.profileId };
2293
- if (options.name !== void 0) body.name = options.name;
2294
- if (options.color !== void 0) body.color = options.color;
2295
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
2296
- return request("PUT", "/interactions/profiles", { body });
2297
- },
2298
- async deleteProfile(options) {
2299
- return request("DELETE", "/interactions/profiles", { body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId } });
2300
- },
2301
- async setProfileUsers(options) {
2302
- return request("POST", "/interactions/profiles/users", {
2303
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, userIds: options.userIds }
2304
- });
2305
- },
2306
- async setProfileSelectTables(options) {
2307
- return request("POST", "/interactions/profiles/selectTables", {
2308
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, tables: options.tables }
2309
- });
2310
- },
2311
- async setProfileDmlTables(options) {
2312
- return request("POST", "/interactions/profiles/dmlTables", {
2313
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, tables: options.tables }
2314
- });
2315
- },
2316
- async setProfileActions(options) {
2317
- return request("POST", "/interactions/profiles/actions", {
2318
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, actionIds: options.actionIds }
2319
- });
2320
- },
2321
- async setProfileScreens(options) {
2322
- return request("POST", "/interactions/profiles/screens", {
2323
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, screenIds: options.screenIds }
2324
- });
2325
- },
2326
- async setProfileServerFunctions(options) {
2327
- return request("POST", "/interactions/profiles/serverFunctions", {
2328
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, serverFunctionIds: options.serverFunctionIds }
731
+ }
732
+ };
733
+ return instance;
734
+ }
735
+
736
+ // src/config.ts
737
+ var globalConfig = null;
738
+ function stripBearer(token) {
739
+ let t = token.trim();
740
+ while (/^bearer\s+/i.test(t)) {
741
+ t = t.replace(/^bearer\s+/i, "").trim();
742
+ }
743
+ return t;
744
+ }
745
+ function parseBody(text) {
746
+ if (!text) return { data: null, isJson: true };
747
+ try {
748
+ return { data: JSON.parse(text), isJson: true };
749
+ } catch (e) {
750
+ return { data: text, isJson: false };
751
+ }
752
+ }
753
+ var SESSION_STORE_KEY = "mitra-session";
754
+ function safeLocalStorage() {
755
+ try {
756
+ return typeof localStorage !== "undefined" ? localStorage : null;
757
+ } catch (e) {
758
+ return null;
759
+ }
760
+ }
761
+ function persistRefreshToken(refreshToken) {
762
+ const ls = safeLocalStorage();
763
+ if (!ls) return;
764
+ try {
765
+ const raw = ls.getItem(SESSION_STORE_KEY);
766
+ const obj = raw ? JSON.parse(raw) : {};
767
+ obj.refreshToken = refreshToken;
768
+ ls.setItem(SESSION_STORE_KEY, JSON.stringify(obj));
769
+ } catch (e) {
770
+ }
771
+ }
772
+ function readPersistedRefreshToken() {
773
+ const ls = safeLocalStorage();
774
+ if (!ls) return void 0;
775
+ try {
776
+ const raw = ls.getItem(SESSION_STORE_KEY);
777
+ if (!raw) return void 0;
778
+ const obj = JSON.parse(raw);
779
+ return typeof (obj == null ? void 0 : obj.refreshToken) === "string" && obj.refreshToken ? obj.refreshToken : void 0;
780
+ } catch (e) {
781
+ return void 0;
782
+ }
783
+ }
784
+ function readInjectedEnv() {
785
+ if (typeof window === "undefined") return {};
786
+ const env = window.__mitraEnv;
787
+ if (!env || typeof env !== "object") return {};
788
+ const out = {};
789
+ if (typeof env.apiBaseURL === "string" && env.apiBaseURL) out.baseURL = env.apiBaseURL;
790
+ if (typeof env.integrationURL === "string" && env.integrationURL) out.integrationURL = env.integrationURL;
791
+ if (typeof env.authUrl === "string" && env.authUrl) out.authUrl = env.authUrl;
792
+ if (typeof env.authPageUrl === "string" && env.authPageUrl) out.authPageUrl = env.authPageUrl;
793
+ return out;
794
+ }
795
+ function configureSdkMitra(config = {}) {
796
+ const injected = readInjectedEnv();
797
+ const merged = { ...injected, ...config };
798
+ if (!merged.baseURL) {
799
+ throw new Error("baseURL \xE9 obrigat\xF3rio. Passe em configureSdkMitra({ baseURL }), fa\xE7a login para receber via sdk-auth, ou rode em uma app publicada pelo Mitra (window.__mitraEnv).");
800
+ }
801
+ if (merged.token != null) merged.token = stripBearer(merged.token);
802
+ if (!merged.refreshToken) {
803
+ const persisted = readPersistedRefreshToken();
804
+ if (persisted) merged.refreshToken = persisted;
805
+ } else {
806
+ persistRefreshToken(merged.refreshToken);
807
+ }
808
+ globalConfig = {
809
+ ...merged,
810
+ baseURL: merged.baseURL.replace(/\/+$/, "")
811
+ };
812
+ return createMitraInstance(globalConfig);
813
+ }
814
+ function getConfig() {
815
+ if (!globalConfig) {
816
+ throw new Error("SDK n\xE3o configurado. Chame configureSdkMitra() primeiro.");
817
+ }
818
+ return globalConfig;
819
+ }
820
+ function isConfigured() {
821
+ return globalConfig !== null;
822
+ }
823
+ function updateGlobalToken(token, refreshToken) {
824
+ if (globalConfig) {
825
+ globalConfig = {
826
+ ...globalConfig,
827
+ token: stripBearer(token),
828
+ ...refreshToken !== void 0 ? { refreshToken } : {}
829
+ };
830
+ if (refreshToken) persistRefreshToken(refreshToken);
831
+ }
832
+ }
833
+ function resolveProjectId(projectId) {
834
+ if (projectId != null) return projectId;
835
+ if ((globalConfig == null ? void 0 : globalConfig.projectId) != null) return globalConfig.projectId;
836
+ throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
837
+ }
838
+
839
+ // src/client.ts
840
+ function getFetch3() {
841
+ if (typeof globalThis.fetch === "function") {
842
+ return globalThis.fetch;
843
+ }
844
+ throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
845
+ }
846
+ function formatToken2(token) {
847
+ return `Bearer ${stripBearer(token)}`;
848
+ }
849
+ function buildHeaders() {
850
+ const config = getConfig();
851
+ const headers = { "Content-Type": "application/json" };
852
+ if (config.token) headers["Authorization"] = formatToken2(config.token);
853
+ return headers;
854
+ }
855
+ function buildUrl(endpoint, params) {
856
+ const config = getConfig();
857
+ let url = `${config.baseURL}${endpoint}`;
858
+ if (params) {
859
+ const query = Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
860
+ if (query) url += `?${query}`;
861
+ }
862
+ return url;
863
+ }
864
+ async function tryRefreshToken() {
865
+ var _a, _b;
866
+ const config = getConfig();
867
+ if (!config.token || config.projectId == null || !config.baseURL) return false;
868
+ if (!isNewWorld()) {
869
+ try {
870
+ const baseURL = config.baseURL.replace(/\/+$/, "");
871
+ const resp = await getFetch3()(`${baseURL}/mitraspace/project/refreshedToken/${config.projectId}`, {
872
+ method: "GET",
873
+ headers: { "Authorization": formatToken2(config.token) }
2329
874
  });
2330
- },
2331
- // Password Reset (pré-login)
2332
- sendPasswordResetCode(options) {
2333
- var _a2;
2334
- return sendPasswordResetCodeMitra({ ...options, authUrl: (_a2 = options.authUrl) != null ? _a2 : _config.authUrl });
2335
- },
2336
- validatePasswordResetCode(options) {
2337
- var _a2;
2338
- return validatePasswordResetCodeMitra({ ...options, authUrl: (_a2 = options.authUrl) != null ? _a2 : _config.authUrl });
2339
- },
2340
- resetPassword(options) {
2341
- var _a2;
2342
- return resetPasswordMitra({ ...options, authUrl: (_a2 = options.authUrl) != null ? _a2 : _config.authUrl });
2343
- },
2344
- // Agent Chat (embedded)
2345
- getAgentTask(options) {
2346
- return getAgentTaskMitra(options);
2347
- },
2348
- manageAgentChat(options) {
2349
- return manageAgentChatMitra(options);
2350
- },
2351
- manageAgentCredential(options) {
2352
- return manageAgentCredentialMitra(options);
2353
- },
2354
- // Chat
2355
- openChat() {
2356
- openChatMitra();
2357
- },
2358
- closeChat() {
2359
- closeChatMitra();
875
+ if (resp.ok) {
876
+ const data = await resp.json();
877
+ if (data.token) {
878
+ const newToken = `Bearer ${stripBearer(data.token)}`;
879
+ const session = {
880
+ token: newToken,
881
+ baseURL: ((_a = data.merge) == null ? void 0 : _a.backURL) || config.baseURL,
882
+ ...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
883
+ };
884
+ updateGlobalToken(session.token);
885
+ if (config.onTokenRefresh) config.onTokenRefresh(session);
886
+ return true;
887
+ }
888
+ }
889
+ } catch (e) {
890
+ }
891
+ }
892
+ if (!config.authUrl || typeof window === "undefined") return false;
893
+ try {
894
+ const session = await refreshTokenSilently3(config.authUrl, config.projectId);
895
+ updateGlobalToken(session.token, session.refreshToken);
896
+ if (config.onTokenRefresh) config.onTokenRefresh(session);
897
+ return true;
898
+ } catch (e) {
899
+ return false;
900
+ }
901
+ }
902
+ async function handleResponse(response) {
903
+ const text = await response.text();
904
+ const { data, isJson } = parseBody(text);
905
+ if (!response.ok) {
906
+ const fallback = !isJson && text ? `HTTP ${response.status} \u2014 ${text}` : `HTTP ${response.status}`;
907
+ const base = isJson && ((data == null ? void 0 : data.message) || (data == null ? void 0 : data.error)) || fallback;
908
+ const msg = isJson && (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
909
+ throw {
910
+ message: msg,
911
+ status: response.status,
912
+ details: data
913
+ };
914
+ }
915
+ return data;
916
+ }
917
+ async function fetchWithRefresh(url, init) {
918
+ const fetchFn = getFetch3();
919
+ const response = await fetchFn(url, init);
920
+ const expiredStatus = isNewWorld() ? 401 : 403;
921
+ if (response.status === expiredStatus) {
922
+ const refreshed = await tryRefreshToken();
923
+ if (refreshed) {
924
+ const newHeaders = { ...buildHeaders() };
925
+ const oldHeaders = init.headers;
926
+ if (oldHeaders) {
927
+ for (const [k, v] of Object.entries(oldHeaders)) {
928
+ if (k !== "Authorization") newHeaders[k] = v;
929
+ }
930
+ }
931
+ const retryResponse = await fetchFn(url, { ...init, headers: newHeaders });
932
+ return handleResponse(retryResponse);
2360
933
  }
934
+ }
935
+ return handleResponse(response);
936
+ }
937
+ var http = {
938
+ async get(endpoint, params) {
939
+ return fetchWithRefresh(buildUrl(endpoint, params), {
940
+ method: "GET",
941
+ headers: buildHeaders()
942
+ });
943
+ },
944
+ async post(endpoint, body) {
945
+ return fetchWithRefresh(buildUrl(endpoint), {
946
+ method: "POST",
947
+ headers: buildHeaders(),
948
+ body: body !== void 0 ? JSON.stringify(body) : void 0
949
+ });
950
+ },
951
+ async put(endpoint, body) {
952
+ return fetchWithRefresh(buildUrl(endpoint), {
953
+ method: "PUT",
954
+ headers: buildHeaders(),
955
+ body: body !== void 0 ? JSON.stringify(body) : void 0
956
+ });
957
+ },
958
+ async del(endpoint, params) {
959
+ return fetchWithRefresh(buildUrl(endpoint, params), {
960
+ method: "DELETE",
961
+ headers: buildHeaders()
962
+ });
963
+ },
964
+ async delBody(endpoint, body) {
965
+ return fetchWithRefresh(buildUrl(endpoint), {
966
+ method: "DELETE",
967
+ headers: buildHeaders(),
968
+ body: body !== void 0 ? JSON.stringify(body) : void 0
969
+ });
970
+ },
971
+ async upload(endpoint, formData) {
972
+ const config = getConfig();
973
+ const headers = {};
974
+ if (config.token) headers["Authorization"] = formatToken2(config.token);
975
+ return fetchWithRefresh(buildUrl(endpoint), {
976
+ method: "POST",
977
+ headers,
978
+ body: formData
979
+ });
980
+ }
981
+ };
982
+ async function requestWithTenant(method, endpoint, tenantId, options) {
983
+ const headers = {
984
+ ...buildHeaders(),
985
+ "X-TenantID": String(tenantId)
2361
986
  };
2362
- return instance;
987
+ return fetchWithRefresh(buildUrl(endpoint, options == null ? void 0 : options.params), {
988
+ method,
989
+ headers,
990
+ body: (options == null ? void 0 : options.body) !== void 0 ? JSON.stringify(options.body) : void 0
991
+ });
2363
992
  }
993
+ var httpTenant = {
994
+ get(endpoint, tenantId, params) {
995
+ return requestWithTenant("GET", endpoint, tenantId, { params });
996
+ },
997
+ post(endpoint, tenantId, body, params) {
998
+ return requestWithTenant("POST", endpoint, tenantId, { body, params });
999
+ },
1000
+ put(endpoint, tenantId, body, params) {
1001
+ return requestWithTenant("PUT", endpoint, tenantId, { body, params });
1002
+ },
1003
+ patch(endpoint, tenantId, body, params) {
1004
+ return requestWithTenant("PATCH", endpoint, tenantId, { body, params });
1005
+ },
1006
+ del(endpoint, tenantId, params) {
1007
+ return requestWithTenant("DELETE", endpoint, tenantId, { params });
1008
+ }
1009
+ };
2364
1010
 
2365
- // src/config.ts
2366
- var globalConfig = null;
2367
- function stripBearer(token) {
2368
- let t = token.trim();
2369
- while (/^bearer\s+/i.test(t)) {
2370
- t = t.replace(/^bearer\s+/i, "").trim();
1011
+ // src/services.ts
1012
+ async function executeServerFunctionMitra(options) {
1013
+ const body = {
1014
+ projectId: resolveProjectId(options.projectId),
1015
+ serverFunctionId: options.serverFunctionId
1016
+ };
1017
+ if (options.input !== void 0) {
1018
+ body.input = options.input;
2371
1019
  }
2372
- return t;
1020
+ return http.post("/interactions/executeServerFunction", body);
2373
1021
  }
2374
- function readInjectedEnv() {
2375
- if (typeof window === "undefined") return {};
2376
- const env = window.__mitraEnv;
2377
- if (!env || typeof env !== "object") return {};
2378
- const out = {};
2379
- if (typeof env.apiBaseURL === "string" && env.apiBaseURL) out.baseURL = env.apiBaseURL;
2380
- if (typeof env.integrationURL === "string" && env.integrationURL) out.integrationURL = env.integrationURL;
2381
- if (typeof env.authUrl === "string" && env.authUrl) out.authUrl = env.authUrl;
2382
- return out;
1022
+ async function executeServerFunctionAsyncMitra(options) {
1023
+ const body = {
1024
+ projectId: resolveProjectId(options.projectId),
1025
+ serverFunctionId: options.serverFunctionId
1026
+ };
1027
+ if (options.input !== void 0) {
1028
+ body.input = options.input;
1029
+ }
1030
+ return http.post("/interactions/executeServerFunctionAsync", body);
2383
1031
  }
2384
- function configureSdkMitra(config = {}) {
2385
- const injected = readInjectedEnv();
2386
- const merged = { ...injected, ...config };
2387
- if (!merged.baseURL) {
2388
- throw new Error("baseURL \xE9 obrigat\xF3rio. Passe em configureSdkMitra({ baseURL }), fa\xE7a login para receber via sdk-auth, ou rode em uma app publicada pelo Mitra (window.__mitraEnv).");
1032
+ async function executePublicServerFunctionMitra(options) {
1033
+ const { projectId, serverFunctionId, input } = options;
1034
+ const baseURL = getConfig().baseURL;
1035
+ const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/execute`;
1036
+ const response = await fetch(url, {
1037
+ method: "POST",
1038
+ headers: { "Content-Type": "application/json" },
1039
+ body: JSON.stringify(input || {})
1040
+ });
1041
+ if (!response.ok) {
1042
+ const data = await response.json().catch(() => null);
1043
+ const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
1044
+ throw { message: msg, status: response.status, details: data };
2389
1045
  }
2390
- if (merged.token != null) merged.token = stripBearer(merged.token);
2391
- globalConfig = {
2392
- ...merged,
2393
- baseURL: merged.baseURL.replace(/\/+$/, "")
2394
- };
2395
- if (merged.token && typeof window !== "undefined") {
2396
- const chat = window.__mitraChat;
2397
- if (chat) chat.init(merged.token);
1046
+ return response.json();
1047
+ }
1048
+ async function executePublicServerFunctionAsyncMitra(options) {
1049
+ const { projectId, serverFunctionId, input } = options;
1050
+ const baseURL = getConfig().baseURL;
1051
+ const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/executeAsync`;
1052
+ const response = await fetch(url, {
1053
+ method: "POST",
1054
+ headers: { "Content-Type": "application/json" },
1055
+ body: JSON.stringify(input || {})
1056
+ });
1057
+ if (!response.ok) {
1058
+ const data = await response.json().catch(() => null);
1059
+ const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
1060
+ throw { message: msg, status: response.status, details: data };
2398
1061
  }
2399
- return createMitraInstance(globalConfig);
1062
+ return response.json();
2400
1063
  }
2401
- function getConfig() {
2402
- if (!globalConfig) {
2403
- throw new Error("SDK n\xE3o configurado. Chame configureSdkMitra() primeiro.");
1064
+ async function getPublicServerFunctionExecutionMitra(options) {
1065
+ const { projectId, executionId } = options;
1066
+ const baseURL = getConfig().baseURL;
1067
+ const url = `${baseURL}/public/serverFunction/${projectId}/execution/${executionId}`;
1068
+ const response = await fetch(url, {
1069
+ method: "GET",
1070
+ headers: { "Content-Type": "application/json" }
1071
+ });
1072
+ if (!response.ok) {
1073
+ const data = await response.json().catch(() => null);
1074
+ const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
1075
+ throw { message: msg, status: response.status, details: data };
2404
1076
  }
2405
- return globalConfig;
1077
+ return response.json();
2406
1078
  }
2407
- function isConfigured() {
2408
- return globalConfig !== null;
1079
+ async function listIntegrationsMitra(options = {}) {
1080
+ return http.get("/interactions/integrations", {
1081
+ projectId: resolveProjectId(options.projectId)
1082
+ });
2409
1083
  }
2410
- function updateGlobalToken(token, refreshToken) {
2411
- if (globalConfig) {
2412
- globalConfig = {
2413
- ...globalConfig,
2414
- token: stripBearer(token),
2415
- ...refreshToken !== void 0 ? { refreshToken } : {}
2416
- };
1084
+ async function callIntegrationMitra(options) {
1085
+ const body = {
1086
+ integrationSlug: options.connection,
1087
+ projectId: resolveProjectId(options.projectId),
1088
+ method: options.method
1089
+ };
1090
+ if (options.endpoint !== void 0) {
1091
+ body.endpoint = options.endpoint;
1092
+ }
1093
+ if (options.params !== void 0) {
1094
+ body.params = options.params;
1095
+ }
1096
+ if (options.body !== void 0) {
1097
+ body.body = options.body;
2417
1098
  }
1099
+ return http.post("/interactions/integrations/call", body);
2418
1100
  }
2419
- function resolveProjectId2(projectId) {
2420
- if (projectId != null) return projectId;
2421
- if ((globalConfig == null ? void 0 : globalConfig.projectId) != null) return globalConfig.projectId;
2422
- throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
1101
+ async function stopServerFunctionExecutionMitra(options) {
1102
+ return http.post("/interactions/stopServerFunctionExecution", {
1103
+ projectId: resolveProjectId(options.projectId),
1104
+ executionId: options.executionId
1105
+ });
1106
+ }
1107
+ async function listRecordsMitra(options) {
1108
+ const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
1109
+ const pid = resolveProjectId(options.projectId);
1110
+ return httpTenant.get(`/interactions/records/${tableName}`, pid, { page, size, jdbcConnectionConfigId, ...filters });
1111
+ }
1112
+ async function getRecordMitra(options) {
1113
+ const { tableName, id, jdbcConnectionConfigId } = options;
1114
+ const pid = resolveProjectId(options.projectId);
1115
+ return httpTenant.get(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1116
+ }
1117
+ async function createRecordMitra(options) {
1118
+ const { tableName, data, jdbcConnectionConfigId } = options;
1119
+ const pid = resolveProjectId(options.projectId);
1120
+ return httpTenant.post(`/interactions/records/${tableName}`, pid, data, { jdbcConnectionConfigId });
1121
+ }
1122
+ async function updateRecordMitra(options) {
1123
+ const { tableName, id, data, jdbcConnectionConfigId } = options;
1124
+ const pid = resolveProjectId(options.projectId);
1125
+ return httpTenant.put(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1126
+ }
1127
+ async function patchRecordMitra(options) {
1128
+ const { tableName, id, data, jdbcConnectionConfigId } = options;
1129
+ const pid = resolveProjectId(options.projectId);
1130
+ return httpTenant.patch(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1131
+ }
1132
+ async function deleteRecordMitra(options) {
1133
+ const { tableName, id, jdbcConnectionConfigId } = options;
1134
+ const pid = resolveProjectId(options.projectId);
1135
+ return httpTenant.del(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1136
+ }
1137
+ async function createRecordsBatchMitra(options) {
1138
+ const { tableName, records, jdbcConnectionConfigId } = options;
1139
+ const pid = resolveProjectId(options.projectId);
1140
+ return httpTenant.post(`/interactions/records/${tableName}/batch`, pid, records, { jdbcConnectionConfigId });
2423
1141
  }
2424
1142
 
2425
- export { callIntegrationMitra, closeChatMitra, configureSdkMitra, createMitraInstance, createProfileMitra, createRecordMitra, createRecordsBatchMitra, deleteProfileMitra, deleteRecordMitra, emailLoginMitra3 as emailLoginMitra, emailResendCodeMitra3 as emailResendCodeMitra, emailSignupMitra3 as emailSignupMitra, emailVerifyCodeMitra3 as emailVerifyCodeMitra, executeDataLoaderMitra, executeDbActionMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getAgentTaskMitra, getConfig, getProfileDetailsMitra, getPublicServerFunctionExecutionMitra, getRecordMitra, getVariableMitra, listIntegrationsMitra, listProfilesMitra, listRecordsMitra, listVariablesMitra, loginMitra3 as loginMitra, loginWithEmailMitra3 as loginWithEmailMitra, loginWithGoogleMitra3 as loginWithGoogleMitra, loginWithMicrosoftMitra3 as loginWithMicrosoftMitra, manageAgentChatMitra, manageAgentCredentialMitra, openChatMitra, patchRecordMitra, refreshTokenSilently3 as refreshTokenSilently, resetPasswordMitra, resolveProjectId2 as resolveProjectId, runActionMitra, sendPasswordResetCodeMitra, setFileStatusMitra, setProfileActionsMitra, setProfileDmlTablesMitra, setProfileScreensMitra, setProfileSelectTablesMitra, setProfileServerFunctionsMitra, setProfileUsersMitra, setVariableMitra, stopServerFunctionExecutionMitra, updateProfileMitra, updateRecordMitra, uploadFileLoadableMitra, uploadFilePublicMitra, validatePasswordResetCodeMitra };
1143
+ export { callIntegrationMitra, configureSdkMitra, createMitraInstance, createRecordMitra, createRecordsBatchMitra, deleteRecordMitra, exchangeSsoCodeMitra2 as exchangeSsoCodeMitra, executePublicServerFunctionAsyncMitra, executePublicServerFunctionMitra, executeServerFunctionAsyncMitra, executeServerFunctionMitra, getConfig, getPublicServerFunctionExecutionMitra, getRecordMitra, listIntegrationsMitra, listRecordsMitra, loginMitra3 as loginMitra, loginWithGoogleMitra3 as loginWithGoogleMitra, loginWithMicrosoftMitra3 as loginWithMicrosoftMitra, patchRecordMitra, refreshTokenSilently3 as refreshTokenSilently, resolveProjectId, stopServerFunctionExecutionMitra, updateRecordMitra };
2426
1144
  //# sourceMappingURL=index.mjs.map
2427
1145
  //# sourceMappingURL=index.mjs.map