@neetru/sdk 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +4 -1
  3. package/dist/ai.cjs +1 -1
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +1 -1
  7. package/dist/auth.cjs +1171 -1110
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +1168 -1107
  11. package/dist/catalog.cjs +1 -1
  12. package/dist/catalog.d.cts +1 -1
  13. package/dist/catalog.d.ts +1 -1
  14. package/dist/catalog.mjs +1 -1
  15. package/dist/checkout.cjs +62 -49
  16. package/dist/checkout.d.cts +1 -1
  17. package/dist/checkout.d.ts +1 -1
  18. package/dist/checkout.mjs +62 -49
  19. package/dist/db-react.d.cts +1 -1
  20. package/dist/db-react.d.ts +1 -1
  21. package/dist/db.cjs +303 -270
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +322 -289
  25. package/dist/entitlements.d.cts +1 -1
  26. package/dist/entitlements.d.ts +1 -1
  27. package/dist/firestore-compat.d.cts +1 -1
  28. package/dist/firestore-compat.d.ts +1 -1
  29. package/dist/index.cjs +1275 -1214
  30. package/dist/index.d.cts +2 -2
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.mjs +1390 -1329
  33. package/dist/mobile.cjs +328 -276
  34. package/dist/mobile.d.cts +12 -2
  35. package/dist/mobile.d.ts +12 -2
  36. package/dist/mobile.mjs +328 -276
  37. package/dist/mocks.cjs +5 -5
  38. package/dist/mocks.d.cts +2 -2
  39. package/dist/mocks.d.ts +2 -2
  40. package/dist/mocks.mjs +4 -4
  41. package/dist/notifications.cjs +1 -1
  42. package/dist/notifications.d.cts +1 -1
  43. package/dist/notifications.d.ts +1 -1
  44. package/dist/notifications.mjs +1 -1
  45. package/dist/react.cjs +119 -119
  46. package/dist/react.d.cts +8 -2
  47. package/dist/react.d.ts +8 -2
  48. package/dist/react.mjs +119 -119
  49. package/dist/support.cjs +1 -1
  50. package/dist/support.d.cts +1 -1
  51. package/dist/support.d.ts +1 -1
  52. package/dist/support.mjs +1 -1
  53. package/dist/telemetry.cjs +62 -49
  54. package/dist/telemetry.d.cts +1 -1
  55. package/dist/telemetry.d.ts +1 -1
  56. package/dist/telemetry.mjs +62 -49
  57. package/dist/{types-D-9bjlM0.d.cts → types-Bl_4HROd.d.cts} +118 -19
  58. package/dist/{types-bVztFQTI.d.ts → types-Bqnsqvow.d.ts} +118 -19
  59. package/dist/usage.cjs +1 -1
  60. package/dist/usage.d.cts +1 -1
  61. package/dist/usage.d.ts +1 -1
  62. package/dist/usage.mjs +1 -1
  63. package/dist/webhooks.cjs +1 -1
  64. package/dist/webhooks.d.cts +1 -1
  65. package/dist/webhooks.d.ts +1 -1
  66. package/dist/webhooks.mjs +1 -1
  67. package/package.json +9 -1
package/dist/mobile.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/errors.ts
4
- var n = class t extends Error {
4
+ var o = class t extends Error {
5
5
  code;
6
6
  status;
7
7
  requestId;
@@ -21,65 +21,65 @@ var n = class t extends Error {
21
21
  * `undefined` em erros que acontecem antes de qualquer requisição.
22
22
  */
23
23
  correlationId;
24
- constructor(e, o, s, i, p, m) {
25
- super(o), this.name = "NeetruError", this.code = e, this.status = s, this.requestId = i, this.reason = p, this.correlationId = m, Object.setPrototypeOf(this, t.prototype);
24
+ constructor(e, n, i, a, f, p) {
25
+ super(n), this.name = "NeetruError", this.code = e, this.status = i, this.requestId = a, this.reason = f, this.correlationId = p, Object.setPrototypeOf(this, t.prototype);
26
26
  }
27
- }, v = class t extends n {
28
- constructor(e, o, s, i, p) {
29
- super("auth_required", e, s, i, o, p), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, t.prototype);
27
+ }, R = class t extends o {
28
+ constructor(e, n, i, a, f) {
29
+ super("auth_required", e, i, a, n, f), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, t.prototype);
30
30
  }
31
31
  };
32
32
 
33
33
  // src/types.ts
34
- var H = "https://api.neetru.com";
34
+ var B = "https://api.neetru.com";
35
35
 
36
36
  // src/base-url-allowlist.ts
37
- var B = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), le = ".neetru.com", ue = "neetru.com", de = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
37
+ var F = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), fe = ".neetru.com", ge = "neetru.com", me = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
38
38
  function j(t) {
39
- return de.test(t);
39
+ return me.test(t);
40
40
  }
41
- function pe(t) {
41
+ function he(t) {
42
42
  return t.toLowerCase().replace(/\.+$/, "");
43
43
  }
44
- function F(t, e = []) {
44
+ function z(t, e = []) {
45
45
  if (typeof t != "string" || t.length === 0)
46
- throw new n("invalid_config", "baseUrl is required");
47
- let o;
46
+ throw new o("invalid_config", "baseUrl is required");
47
+ let n;
48
48
  try {
49
- o = new URL(t);
49
+ n = new URL(t);
50
50
  } catch {
51
- throw new n("invalid_config", `baseUrl is not a valid URL: ${t}`);
51
+ throw new o("invalid_config", `baseUrl is not a valid URL: ${t}`);
52
52
  }
53
- let s = o.protocol, i = pe(o.hostname);
54
- if (fe())
53
+ let i = n.protocol, a = he(n.hostname);
54
+ if (ye())
55
55
  return typeof console < "u" && console.warn(
56
56
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${t} aceito sem valida\xE7\xE3o.`
57
57
  ), t.replace(/\/+$/, "");
58
- if (s !== "https:" && s !== "http:")
59
- throw new n(
58
+ if (i !== "https:" && i !== "http:")
59
+ throw new o(
60
60
  "invalid_config",
61
- `baseUrl protocol must be http: or https:, got ${s}`
61
+ `baseUrl protocol must be http: or https:, got ${i}`
62
62
  );
63
- if (s === "http:") {
64
- if (!(B.has(i) || j(i)))
65
- throw new n(
63
+ if (i === "http:") {
64
+ if (!(F.has(a) || j(a)))
65
+ throw new o(
66
66
  "invalid_config",
67
- `baseUrl with http: only allowed for localhost/127.0.0.1/*.test/*.localhost. Got: ${i}. Use https: or set NEETRU_ALLOW_INSECURE_BASEURL=1 to bypass.`
67
+ `baseUrl with http: only allowed for localhost/127.0.0.1/*.test/*.localhost. Got: ${a}. Use https: or set NEETRU_ALLOW_INSECURE_BASEURL=1 to bypass.`
68
68
  );
69
69
  return t.replace(/\/+$/, "");
70
70
  }
71
- let p = i === ue || i.endsWith(le), m = e.some((h) => {
71
+ let f = a === ge || a.endsWith(fe), p = e.some((h) => {
72
72
  let w = h.toLowerCase();
73
- return i === w || i.endsWith(`.${w}`);
74
- }), I = B.has(i) || j(i);
75
- if (!p && !m && !I)
76
- throw new n(
73
+ return a === w || a.endsWith(`.${w}`);
74
+ }), y = F.has(a) || j(a);
75
+ if (!f && !p && !y)
76
+ throw new o(
77
77
  "invalid_config",
78
- `baseUrl ${i} is not in the allowlist. Allowed: *.neetru.com, localhost, or configure { allowedHosts: ['...'] }. Bypass: NEETRU_ALLOW_INSECURE_BASEURL=1.`
78
+ `baseUrl ${a} is not in the allowlist. Allowed: *.neetru.com, localhost, or configure { allowedHosts: ['...'] }. Bypass: NEETRU_ALLOW_INSECURE_BASEURL=1.`
79
79
  );
80
80
  return t.replace(/\/+$/, "");
81
81
  }
82
- function fe() {
82
+ function ye() {
83
83
  try {
84
84
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
85
85
  if (e === "1" || e === "true") return !0;
@@ -94,16 +94,16 @@ function fe() {
94
94
  }
95
95
 
96
96
  // src/api-key.ts
97
- var ge = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
98
- function z(t) {
97
+ var be = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
98
+ function V(t) {
99
99
  if (typeof t != "string" || t.length === 0)
100
- throw new n(
100
+ throw new o(
101
101
  "invalid_config",
102
102
  "apiKey is required (formato nrt_<keyId>_<secret>)"
103
103
  );
104
- let e = ge.exec(t);
104
+ let e = be.exec(t);
105
105
  if (!e)
106
- throw new n(
106
+ throw new o(
107
107
  "invalid_config",
108
108
  "apiKey malformado - esperado formato nrt_<keyId>_<secret>"
109
109
  );
@@ -111,57 +111,57 @@ function z(t) {
111
111
  }
112
112
 
113
113
  // src/auth-pkce-shared.ts
114
- function V() {
114
+ function W() {
115
115
  let t = globalThis.crypto;
116
116
  if (!t || typeof t.getRandomValues != "function" || !t.subtle)
117
- throw new n(
117
+ throw new o(
118
118
  "runtime_unsupported",
119
119
  "auth.signIn requer WebCrypto (crypto.subtle) \u2014 indispon\xEDvel neste runtime. Use HTTPS (ou http://localhost) num browser moderno, ou instale um polyfill WebCrypto (ex: react-native-quick-crypto) em React Native."
120
120
  );
121
121
  return t;
122
122
  }
123
- function W(t) {
123
+ function J(t) {
124
124
  let e = "";
125
- for (let s of t) e += String.fromCharCode(s);
125
+ for (let i of t) e += String.fromCharCode(i);
126
126
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
127
127
  }
128
128
  function x(t, e) {
129
- let o = new Uint8Array(e);
130
- return t.getRandomValues(o), W(o);
129
+ let n = new Uint8Array(e);
130
+ return t.getRandomValues(n), J(n);
131
131
  }
132
- async function J(t, e) {
133
- let o = new TextEncoder().encode(e), s = await t.subtle.digest("SHA-256", o);
134
- return W(new Uint8Array(s));
132
+ async function G(t, e) {
133
+ let n = new TextEncoder().encode(e), i = await t.subtle.digest("SHA-256", n);
134
+ return J(new Uint8Array(i));
135
135
  }
136
- function S(t) {
136
+ function I(t) {
137
137
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? t.replace(/^https?:\/\/api\./, "https://auth.");
138
138
  }
139
- function L(t) {
139
+ function O(t) {
140
140
  let e = t.oidcClientId;
141
- if (!e && t.apiKey && (e = z(t.apiKey).keyId), !e)
142
- throw new n(
141
+ if (!e && t.apiKey && (e = V(t.apiKey).keyId), !e)
142
+ throw new o(
143
143
  "invalid_config",
144
144
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
145
145
  );
146
146
  return e;
147
147
  }
148
- function G(t) {
148
+ function X(t) {
149
149
  let e = new URL("/api/v1/oauth/authorize", t.idpOrigin);
150
150
  return e.searchParams.set("response_type", "code"), e.searchParams.set("client_id", t.clientId), e.searchParams.set("redirect_uri", t.redirectUri), e.searchParams.set("scope", t.scope), e.searchParams.set("state", t.state), e.searchParams.set("nonce", t.nonce), e.searchParams.set("code_challenge", t.codeChallenge), e.searchParams.set("code_challenge_method", "S256"), e;
151
151
  }
152
- var X = "/api/v1/oauth/token";
153
- function O(t) {
152
+ var Y = "/api/v1/oauth/token";
153
+ function L(t) {
154
154
  let e = t.split(".");
155
155
  if (e.length !== 3) return null;
156
156
  try {
157
- let o = e[1].replace(/-/g, "+").replace(/_/g, "/"), s = "=".repeat((4 - o.length % 4) % 4), i = typeof atob == "function" ? atob(o + s) : Buffer.from(o + s, "base64").toString("utf-8");
158
- return JSON.parse(i);
157
+ let n = e[1].replace(/-/g, "+").replace(/_/g, "/"), i = "=".repeat((4 - n.length % 4) % 4), a = typeof atob == "function" ? atob(n + i) : Buffer.from(n + i, "base64").toString("utf-8");
158
+ return JSON.parse(a);
159
159
  } catch {
160
160
  return null;
161
161
  }
162
162
  }
163
- function T(t) {
164
- let e = O(t);
163
+ function A(t) {
164
+ let e = L(t);
165
165
  return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
166
166
  uid: e.sub,
167
167
  email: typeof e.email == "string" ? e.email : "",
@@ -174,35 +174,35 @@ function T(t) {
174
174
  ...e
175
175
  };
176
176
  }
177
- var me = "/api/v1/oauth/revoke";
178
- async function Y(t, e, o, s) {
179
- let i = `${e}${me}`, p = true;
180
- for (let m of s) {
181
- if (!m.token) continue;
182
- let I = new URLSearchParams({
183
- token: m.token,
184
- token_type_hint: m.hint,
185
- client_id: o
177
+ var _e = "/api/v1/oauth/revoke";
178
+ async function Q(t, e, n, i) {
179
+ let a = `${e}${_e}`, f = true;
180
+ for (let p of i) {
181
+ if (!p.token) continue;
182
+ let y = new URLSearchParams({
183
+ token: p.token,
184
+ token_type_hint: p.hint,
185
+ client_id: n
186
186
  }).toString(), h = false;
187
187
  for (let w = 0; w < 2 && !h; w++)
188
188
  try {
189
- if (h = (await t(i, {
189
+ if (h = (await t(a, {
190
190
  method: "POST",
191
191
  headers: { "content-type": "application/x-www-form-urlencoded" },
192
- body: I
192
+ body: y
193
193
  })).ok, !h) break;
194
194
  } catch {
195
- w === 0 && await new Promise((_) => setTimeout(_, 500));
195
+ w === 0 && await new Promise((k) => setTimeout(k, 500));
196
196
  }
197
- h || (p = false);
197
+ h || (f = false);
198
198
  }
199
- return p;
199
+ return f;
200
200
  }
201
201
 
202
202
  // src/server-only-key.ts
203
203
  function Z(t) {
204
204
  if (!(t == null || t === ""))
205
- throw new n(
205
+ throw new o(
206
206
  "server_only_key",
207
207
  "[Neetru SDK] Recusado: @neetru/sdk/mobile n\xE3o aceita apiKey. A credencial nrt_ do produto \xE9 S\xD3 DE SERVIDOR \u2014 dentro do app ela \xE9 extra\xEDvel do pacote (.apk/.ipa). Remova a apiKey (e qualquer EXPO_PUBLIC_*_KEY com ela) do app: fa\xE7a login com oidcClientId (client OIDC p\xFAblico do app) e chame a API do seu produto com o access_token do usu\xE1rio; o backend do produto usa o SDK com a chave.",
208
208
  void 0,
@@ -212,419 +212,471 @@ function Z(t) {
212
212
  }
213
213
 
214
214
  // src/correlation.ts
215
- var Q = "x-correlation-id";
216
- var he = /^[A-Za-z0-9._:\-]+$/;
217
- function ee(t) {
218
- return typeof t == "string" && t.length > 0 && t.length <= 128 && he.test(t);
215
+ var ee = "x-correlation-id";
216
+ var we = /^[A-Za-z0-9._:\-]+$/;
217
+ function te(t) {
218
+ return typeof t == "string" && t.length > 0 && t.length <= 128 && we.test(t);
219
219
  }
220
- function ye() {
220
+ function ke() {
221
221
  let t = globalThis.crypto;
222
222
  try {
223
223
  if (t && typeof t.randomUUID == "function") return t.randomUUID();
224
224
  } catch {
225
225
  }
226
- let e = new Uint8Array(16), o = false;
226
+ let e = new Uint8Array(16), n = false;
227
227
  try {
228
- t && typeof t.getRandomValues == "function" && (t.getRandomValues(e), o = !0);
228
+ t && typeof t.getRandomValues == "function" && (t.getRandomValues(e), n = !0);
229
229
  } catch {
230
- o = false;
230
+ n = false;
231
231
  }
232
- if (!o)
233
- for (let i = 0; i < e.length; i++) e[i] = Math.floor(Math.random() * 256);
232
+ if (!n)
233
+ for (let a = 0; a < e.length; a++) e[a] = Math.floor(Math.random() * 256);
234
234
  e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
235
- let s = Array.from(e, (i) => i.toString(16).padStart(2, "0")).join("");
236
- return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
235
+ let i = Array.from(e, (a) => a.toString(16).padStart(2, "0")).join("");
236
+ return `${i.slice(0, 8)}-${i.slice(8, 12)}-${i.slice(12, 16)}-${i.slice(16, 20)}-${i.slice(20)}`;
237
237
  }
238
238
  function K(t, e) {
239
- let o, s = {};
240
- for (let [p, m] of Object.entries(t)) {
241
- if (p.toLowerCase() === Q) {
242
- ee(m) && (o = m);
239
+ let n, i = {};
240
+ for (let [f, p] of Object.entries(t)) {
241
+ if (f.toLowerCase() === ee) {
242
+ te(p) && (n = p);
243
243
  continue;
244
244
  }
245
- s[p] = m;
245
+ i[f] = p;
246
246
  }
247
- let i = o ?? (ee(e) ? e : void 0) ?? ye();
248
- return s[Q] = i, { headers: s, correlationId: i };
247
+ let a = n ?? (te(e) ? e : void 0) ?? ke();
248
+ return i[ee] = a, { headers: i, correlationId: a };
249
249
  }
250
250
 
251
251
  // src/http.ts
252
- function te(t) {
252
+ function re(t) {
253
253
  return t === 401 ? "unauthorized" : t === 403 ? "forbidden" : t === 404 ? "not_found" : t === 409 ? "conflict" : t === 410 ? "gone" : t === 422 || t === 400 ? "validation_failed" : t === 429 ? "rate_limited" : t >= 500 ? "server_error" : "unknown";
254
254
  }
255
255
 
256
+ // src/timeout.ts
257
+ function ne(t) {
258
+ let e = globalThis.AbortSignal;
259
+ if (typeof e?.timeout == "function")
260
+ return { signal: e.timeout(t), clear: () => {
261
+ } };
262
+ if (typeof globalThis.AbortController != "function")
263
+ return { signal: void 0, clear: () => {
264
+ } };
265
+ let n = new AbortController(), i = setTimeout(() => n.abort(), t);
266
+ return i.unref?.(), { signal: n.signal, clear: () => clearTimeout(i) };
267
+ }
268
+ function oe(t, e, n) {
269
+ let i, a = new Promise((f) => {
270
+ i = setTimeout(() => f(n()), e), i.unref?.();
271
+ });
272
+ return Promise.race([t, a]).finally(() => {
273
+ i !== void 0 && clearTimeout(i);
274
+ });
275
+ }
276
+
256
277
  // src/mobile.ts
257
- var k = "neetru_oauth_tx", U = "neetru_id_token", E = "neetru_refresh_token", C = "neetru_access_token", be = 3e4, we = "/api/v1/oauth/userinfo";
258
- function _e(t) {
278
+ var v = "neetru_oauth_tx", E = "neetru_id_token", U = "neetru_refresh_token", C = "neetru_access_token", ve = 3e4, Re = "/api/v1/oauth/userinfo";
279
+ function Se(t) {
259
280
  if (t === void 0 || t === "") return null;
260
281
  let e;
261
282
  try {
262
283
  e = new URL(t);
263
284
  } catch {
264
- throw new n("invalid_config", `productApiUrl inv\xE1lida: ${t}`);
285
+ throw new o("invalid_config", `productApiUrl inv\xE1lida: ${t}`);
265
286
  }
266
- let o = e.hostname === "localhost" || e.hostname === "127.0.0.1";
267
- if (e.protocol !== "https:" && !(e.protocol === "http:" && o))
268
- throw new n(
287
+ let n = e.hostname === "localhost" || e.hostname === "127.0.0.1";
288
+ if (e.protocol !== "https:" && !(e.protocol === "http:" && n))
289
+ throw new o(
269
290
  "invalid_config",
270
291
  "productApiUrl precisa ser https:// (http s\xF3 para localhost) \u2014 o access_token n\xE3o pode trafegar sem TLS."
271
292
  );
272
293
  return e;
273
294
  }
274
- function ke(t) {
295
+ function Te(t) {
275
296
  if (Z(t.apiKey), !t.storage)
276
- throw new n(
297
+ throw new o(
277
298
  "invalid_config",
278
299
  "createMobileAuthNamespace requer `storage` (MobileAuthStorage) \u2014 ver JSDoc de src/mobile.ts requisito 4."
279
300
  );
280
301
  if (typeof t.openAuthUrl != "function")
281
- throw new n(
302
+ throw new o(
282
303
  "invalid_config",
283
304
  "createMobileAuthNamespace requer `openAuthUrl` (browser externo, NUNCA WebView embutida) \u2014 ver JSDoc de src/mobile.ts requisito 3."
284
305
  );
285
306
  let e = t.fetch ?? globalThis.fetch;
286
307
  if (typeof e != "function")
287
- throw new n(
308
+ throw new o(
288
309
  "invalid_config",
289
310
  "fetch is not available in this runtime. Pass `fetch` explicitly to createMobileAuthNamespace."
290
311
  );
291
312
  if (typeof t.oidcClientId != "string" || t.oidcClientId.length === 0)
292
- throw new n(
313
+ throw new o(
293
314
  "invalid_config",
294
315
  "createMobileAuthNamespace requer `oidcClientId` \u2014 o client OIDC P\xDABLICO do app registrado no Core (a apiKey n\xE3o \xE9 aceita no app; ver requisito 6 no JSDoc de src/mobile.ts)."
295
316
  );
296
- let o = F(t.baseUrl ?? H, t.allowedHosts ?? []);
317
+ let n = z(t.baseUrl ?? B, t.allowedHosts ?? []);
297
318
  return {
298
319
  fetchImpl: e.bind(globalThis),
299
- baseUrl: o,
320
+ baseUrl: n,
300
321
  oidcClientId: t.oidcClientId,
301
- productApiUrl: _e(t.productApiUrl),
322
+ productApiUrl: Se(t.productApiUrl),
302
323
  storage: t.storage,
303
324
  openAuthUrl: t.openAuthUrl
304
325
  };
305
326
  }
306
- function ve(t) {
307
- let o = O(t)?.exp;
308
- return typeof o == "number" ? o * 1e3 : null;
327
+ function Ie(t) {
328
+ let n = L(t)?.exp;
329
+ return typeof n == "number" ? n * 1e3 : null;
309
330
  }
310
- async function re(t, e, o) {
311
- let s;
331
+ async function ie(t, e, n) {
332
+ let { signal: i, clear: a } = ne(15e3), f;
312
333
  try {
313
- s = await t(e, {
334
+ f = await t(e, {
314
335
  method: "POST",
315
336
  headers: { "content-type": "application/x-www-form-urlencoded" },
316
- body: o.toString()
337
+ body: n.toString(),
338
+ signal: i
317
339
  });
318
- } catch (p) {
319
- throw new n(
340
+ } catch (y) {
341
+ throw new o(
320
342
  "network_error",
321
- `POST ${e} falhou (network): ${p?.message ?? String(p)}`
343
+ `POST ${e} falhou (network): ${y?.message ?? String(y)}`
322
344
  );
345
+ } finally {
346
+ a();
323
347
  }
324
- let i = null;
348
+ let p = null;
325
349
  try {
326
- i = await s.json();
350
+ p = await f.json();
327
351
  } catch {
328
- i = null;
352
+ p = null;
329
353
  }
330
- if (!s.ok || typeof i?.error == "string") {
331
- let p = typeof i?.error_description == "string" && i.error_description || typeof i?.error == "string" && i.error || `HTTP ${s.status}`;
332
- throw new n(
354
+ if (!f.ok || typeof p?.error == "string") {
355
+ let y = typeof p?.error_description == "string" && p.error_description || typeof p?.error == "string" && p.error || `HTTP ${f.status}`;
356
+ throw new o(
333
357
  "token_exchange_failed",
334
- `Troca de tokens falhou no /token: ${p}`,
335
- s.status
358
+ `Troca de tokens falhou no /token: ${y}`,
359
+ f.status
336
360
  );
337
361
  }
338
- return i ?? {};
362
+ return p ?? {};
339
363
  }
340
- function je(t) {
341
- let e = ke(t), o = /* @__PURE__ */ new Set();
342
- function s() {
343
- return `${S(e.baseUrl)}${X}`;
364
+ function Ge(t) {
365
+ let e = Te(t), n = /* @__PURE__ */ new Set();
366
+ function i() {
367
+ return `${I(e.baseUrl)}${Y}`;
344
368
  }
345
- async function i() {
346
- let r = await h();
347
- for (let a of o)
369
+ async function a(r) {
370
+ let s = null;
371
+ if (r !== void 0)
372
+ s = r;
373
+ else
348
374
  try {
349
- a(r);
375
+ s = await h();
376
+ } catch {
377
+ s = null;
378
+ }
379
+ for (let l of n)
380
+ try {
381
+ l(s);
350
382
  } catch {
351
383
  }
352
384
  }
353
- async function p(r) {
385
+ async function f(r) {
354
386
  if (!r?.redirectUri)
355
- throw new n(
387
+ throw new o(
356
388
  "invalid_config",
357
389
  "mobile auth.signIn requer `redirectUri` (Universal Link/App Link https://... registrado no Core) \u2014 n\xE3o h\xE1 location.origin impl\xEDcito em React Native."
358
390
  );
359
- let a = V(), c = r.scope ?? "openid profile email", l = L(e), d = x(a, 16), u = x(a, 16), f = x(a, 32), g = await J(a, f), y = {
391
+ let s = W(), l = r.scope ?? "openid profile email", u = O(e), d = x(s, 16), c = x(s, 16), m = x(s, 32), g = await G(s, m), b = {
360
392
  state: d,
361
- nonce: u,
362
- codeVerifier: f,
393
+ nonce: c,
394
+ codeVerifier: m,
363
395
  redirectUri: r.redirectUri,
364
396
  postLoginRedirect: r.postLoginRedirect
365
397
  };
366
- await e.storage.setItem(k, JSON.stringify(y));
367
- let b = S(e.baseUrl), R = G({
368
- idpOrigin: b,
369
- clientId: l,
398
+ await e.storage.setItem(v, JSON.stringify(b));
399
+ let _ = I(e.baseUrl), S = X({
400
+ idpOrigin: _,
401
+ clientId: u,
370
402
  redirectUri: r.redirectUri,
371
- scope: c,
403
+ scope: l,
372
404
  state: d,
373
- nonce: u,
405
+ nonce: c,
374
406
  codeChallenge: g
375
407
  });
376
- await e.openAuthUrl(R.toString());
408
+ await e.openAuthUrl(S.toString());
377
409
  }
378
- async function m(r) {
410
+ async function p(r) {
379
411
  if (!r || typeof r != "string")
380
- throw new n(
412
+ throw new o(
381
413
  "invalid_config",
382
414
  "mobile auth.completeSignIn requer `callbackUrl` (a URL completa do deep link de retorno) \u2014 mobile n\xE3o tem location.href impl\xEDcito."
383
415
  );
384
- let a;
416
+ let s;
385
417
  try {
386
- a = new URL(r);
418
+ s = new URL(r);
387
419
  } catch {
388
- throw new n("invalid_config", `callbackUrl n\xE3o \xE9 uma URL v\xE1lida: ${r}`);
420
+ throw new o("invalid_config", `callbackUrl n\xE3o \xE9 uma URL v\xE1lida: ${r}`);
389
421
  }
390
- let c = a.searchParams, l = c.get("error");
391
- if (l) {
392
- let ce = c.get("error_description") ?? l;
393
- throw await e.storage.removeItem(k), new n(l, `OIDC authorize falhou: ${ce}`);
422
+ let l = s.searchParams, u = l.get("error");
423
+ if (u) {
424
+ let pe = l.get("error_description") ?? u;
425
+ throw await e.storage.removeItem(v), new o(u, `OIDC authorize falhou: ${pe}`);
394
426
  }
395
- let d = c.get("code");
427
+ let d = l.get("code");
396
428
  if (!d)
397
- throw await e.storage.removeItem(k), new n(
429
+ throw await e.storage.removeItem(v), new o(
398
430
  "invalid_config",
399
431
  "callbackUrl n\xE3o cont\xE9m `?code=` nem `?error=` \u2014 n\xE3o \xE9 um callback OIDC v\xE1lido."
400
432
  );
401
- let u = c.get("state"), f = await e.storage.getItem(k), g = null;
402
- if (f)
433
+ let c = l.get("state"), m = await e.storage.getItem(v), g = null;
434
+ if (m)
403
435
  try {
404
- g = JSON.parse(f);
436
+ g = JSON.parse(m);
405
437
  } catch {
406
438
  g = null;
407
439
  }
408
440
  if (!g)
409
- throw new n(
441
+ throw new o(
410
442
  "oidc_state_mismatch",
411
443
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado (ou j\xE1 consumido)."
412
444
  );
413
- if (!u || u !== g.state)
414
- throw await e.storage.removeItem(k), new n(
445
+ if (!c || c !== g.state)
446
+ throw await e.storage.removeItem(v), new o(
415
447
  "oidc_state_mismatch",
416
448
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
417
449
  );
418
- await e.storage.removeItem(k);
419
- let y = L(e), b = new URLSearchParams({
450
+ await e.storage.removeItem(v);
451
+ let b = O(e), _ = new URLSearchParams({
420
452
  grant_type: "authorization_code",
421
453
  code: d,
422
454
  redirect_uri: g.redirectUri,
423
- client_id: y,
455
+ client_id: b,
424
456
  code_verifier: g.codeVerifier
425
- }), R = await re(e.fetchImpl, s(), b), A = R.id_token;
426
- if (typeof A != "string" || A.length === 0)
427
- throw new n(
457
+ }), S = await ie(e.fetchImpl, i(), _), T = S.id_token;
458
+ if (typeof T != "string" || T.length === 0)
459
+ throw new o(
428
460
  "token_exchange_failed",
429
461
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado."
430
462
  );
431
- let $ = O(A);
432
- if (!$)
433
- throw new n(
463
+ let q = L(T);
464
+ if (!q)
465
+ throw new o(
434
466
  "token_exchange_failed",
435
467
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
436
468
  );
437
- if ($.nonce !== g.nonce)
438
- throw new n(
469
+ if (q.nonce !== g.nonce)
470
+ throw new o(
439
471
  "oidc_nonce_mismatch",
440
472
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
441
473
  );
442
- let q = T(A);
443
- if (!q)
444
- throw new n(
474
+ let H = A(T);
475
+ if (!H)
476
+ throw new o(
445
477
  "token_exchange_failed",
446
478
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
447
479
  );
448
- await e.storage.setItem(U, A);
449
- let M = R.refresh_token;
450
- return typeof M == "string" && M.length > 0 && await e.storage.setItem(E, M), await w(R.access_token), await i(), { user: q, postLoginRedirect: g.postLoginRedirect };
480
+ await e.storage.setItem(E, T);
481
+ let M = S.refresh_token;
482
+ return typeof M == "string" && M.length > 0 && await e.storage.setItem(U, M), await w(S.access_token), await a(), { user: H, postLoginRedirect: g.postLoginRedirect };
451
483
  }
452
- async function I() {
453
- let r = await e.storage.getItem(U);
454
- return r && T(r) ? r : null;
484
+ async function y() {
485
+ let r = await e.storage.getItem(E);
486
+ return r && A(r) ? r : null;
455
487
  }
456
488
  async function h() {
457
- let r = await e.storage.getItem(U);
458
- return r ? T(r) : null;
489
+ let r = await e.storage.getItem(E);
490
+ return r ? A(r) : null;
459
491
  }
460
492
  async function w(r) {
461
493
  typeof r == "string" && r.length > 0 ? await e.storage.setItem(C, r) : await e.storage.removeItem(C);
462
494
  }
463
- let _ = null;
495
+ let k = null;
464
496
  function N() {
465
- return _ || (_ = ne().finally(() => {
466
- _ = null;
467
- }), _);
497
+ if (k) return k;
498
+ let r = { abandoned: false };
499
+ return k = oe(ae(r), 15e3, () => (r.abandoned = true, false)).finally(() => {
500
+ k = null;
501
+ }), k;
468
502
  }
469
- async function ne() {
470
- let r = await e.storage.getItem(E);
471
- if (!r) return false;
472
- let a;
503
+ async function ae(r = { abandoned: false }) {
504
+ let s = await e.storage.getItem(U);
505
+ if (!s) return false;
506
+ let l;
473
507
  try {
474
- a = L(e);
508
+ l = O(e);
475
509
  } catch {
476
510
  return false;
477
511
  }
478
- let c = new URLSearchParams({
512
+ let u = new URLSearchParams({
479
513
  grant_type: "refresh_token",
480
- refresh_token: r,
481
- client_id: a
482
- }), l;
514
+ refresh_token: s,
515
+ client_id: l
516
+ }), d;
483
517
  try {
484
- l = await re(e.fetchImpl, s(), c);
518
+ d = await ie(e.fetchImpl, i(), u);
485
519
  } catch {
486
520
  return false;
487
521
  }
488
- let d = l.id_token;
489
- if (typeof d != "string" || d.length === 0 || !T(d)) return false;
490
- await e.storage.setItem(U, d);
491
- let f = l.refresh_token;
492
- return typeof f == "string" && f.length > 0 && await e.storage.setItem(E, f), await w(l.access_token), await i(), true;
522
+ let c = d.id_token;
523
+ if (typeof c != "string" || c.length === 0 || !A(c) || r.abandoned) return false;
524
+ await e.storage.setItem(E, c);
525
+ let g = d.refresh_token;
526
+ return typeof g == "string" && g.length > 0 && await e.storage.setItem(U, g), await w(d.access_token), await a(), true;
493
527
  }
494
528
  async function P() {
495
529
  let r = await e.storage.getItem(C);
496
530
  if (!r) return null;
497
- let a = ve(r);
498
- return a === null || a - be <= Date.now() ? null : r;
531
+ let s = Ie(r);
532
+ return s === null || s - ve <= Date.now() ? null : r;
499
533
  }
500
534
  async function D() {
501
535
  let r = await P();
502
536
  return r || (await N() ? P() : null);
503
537
  }
504
- async function oe() {
505
- let r = `${S(e.baseUrl)}${we}`, a = async (f) => {
506
- let { headers: g, correlationId: y } = K({
538
+ async function ce() {
539
+ let r = `${I(e.baseUrl)}${Re}`, s = async (m) => {
540
+ let { headers: g, correlationId: b } = K({
507
541
  accept: "application/json",
508
- authorization: `Bearer ${f}`
542
+ authorization: `Bearer ${m}`
509
543
  });
510
544
  try {
511
- return { res: await e.fetchImpl(r, { method: "GET", headers: g }), correlationId: y };
512
- } catch (b) {
513
- throw new n(
545
+ return { res: await e.fetchImpl(r, { method: "GET", headers: g }), correlationId: b };
546
+ } catch (_) {
547
+ throw new o(
514
548
  "network_error",
515
- `GET ${r} falhou (network): ${b?.message ?? String(b)}`,
549
+ `GET ${r} falhou (network): ${_?.message ?? String(_)}`,
516
550
  void 0,
517
551
  void 0,
518
552
  void 0,
519
- y
553
+ b
520
554
  );
521
555
  }
522
- }, c = await D();
523
- if (!c)
524
- throw new v(
556
+ }, l = await D();
557
+ if (!l)
558
+ throw new R(
525
559
  "Sem sess\xE3o: fa\xE7a login (auth.signIn) antes de consultar o userinfo.",
526
560
  "no_signed_in_user"
527
561
  );
528
- let { res: l, correlationId: d } = await a(c);
529
- if (l.status === 401 && await N() && (c = await P(), c && ({ res: l, correlationId: d } = await a(c))), l.status === 401)
530
- throw new v(
562
+ let { res: u, correlationId: d } = await s(l);
563
+ if (u.status === 401 && await N() && (l = await P(), l && ({ res: u, correlationId: d } = await s(l))), u.status === 401)
564
+ throw new R(
531
565
  "O Core recusou a sess\xE3o (token revogado/expirado ou usu\xE1rio inativo). Fa\xE7a login novamente.",
532
566
  "invalid_access_token",
533
567
  401,
534
568
  void 0,
535
569
  d
536
570
  );
537
- let u;
571
+ let c;
538
572
  try {
539
- u = await l.json();
573
+ c = await u.json();
540
574
  } catch {
541
- u = void 0;
575
+ c = void 0;
542
576
  }
543
- if (!l.ok) {
544
- let f = u && typeof u == "object" && typeof u.error_description == "string" ? u.error_description : `HTTP ${l.status}`;
545
- throw new n(te(l.status), `userinfo falhou: ${f}`, l.status, void 0, void 0, d);
577
+ if (!u.ok) {
578
+ let m = c && typeof c == "object" && typeof c.error_description == "string" ? c.error_description : `HTTP ${u.status}`;
579
+ throw new o(re(u.status), `userinfo falhou: ${m}`, u.status, void 0, void 0, d);
546
580
  }
547
- if (!u || typeof u != "object" || typeof u.sub != "string")
548
- throw new n("invalid_response", "userinfo sem `sub`.", l.status, void 0, void 0, d);
549
- return u;
581
+ if (!c || typeof c != "object" || typeof c.sub != "string")
582
+ throw new o("invalid_response", "userinfo sem `sub`.", u.status, void 0, void 0, d);
583
+ return c;
550
584
  }
551
- function ie(r) {
552
- let a = e.productApiUrl;
553
- if (!a)
554
- throw new n(
585
+ function le(r) {
586
+ let s = e.productApiUrl;
587
+ if (!s)
588
+ throw new o(
555
589
  "invalid_config",
556
590
  "auth.authFetch requer `productApiUrl` (URL da API do seu produto) no createMobileAuthNamespace."
557
591
  );
558
- let c;
592
+ let l;
559
593
  if (/^[a-z][a-z0-9+.-]*:/i.test(r))
560
594
  try {
561
- c = new URL(r);
595
+ l = new URL(r);
562
596
  } catch {
563
- throw new n("invalid_config", `URL inv\xE1lida: ${r}`);
597
+ throw new o("invalid_config", `URL inv\xE1lida: ${r}`);
564
598
  }
565
599
  else {
566
- let l = a.pathname.replace(/\/+$/, ""), d = r.startsWith("/") ? r : `/${r}`;
567
- c = new URL(`${a.origin}${l}${d}`);
600
+ let u = s.pathname.replace(/\/+$/, ""), d = r.startsWith("/") ? r : `/${r}`;
601
+ l = new URL(`${s.origin}${u}${d}`);
568
602
  }
569
- if (c.origin !== a.origin)
570
- throw new n(
603
+ if (l.origin !== s.origin)
604
+ throw new o(
571
605
  "invalid_config",
572
- `auth.authFetch s\xF3 envia o access_token para a API do produto (${a.origin}); recusado: ${c.origin}.`
606
+ `auth.authFetch s\xF3 envia o access_token para a API do produto (${s.origin}); recusado: ${l.origin}.`
573
607
  );
574
- return c.toString();
608
+ return l.toString();
575
609
  }
576
- async function se(r, a = {}) {
577
- let c = ie(r), l = {};
578
- new Headers(a.headers ?? {}).forEach((y, b) => {
579
- l[b] = y;
610
+ async function ue(r, s = {}) {
611
+ let l = le(r), u = {};
612
+ new Headers(s.headers ?? {}).forEach((b, _) => {
613
+ u[_] = b;
580
614
  });
581
- let d = (y) => {
582
- let { headers: b } = K({ ...l, authorization: `Bearer ${y}` });
583
- return e.fetchImpl(c, { ...a, headers: b });
584
- }, u = await D();
585
- if (!u)
586
- throw new v(
615
+ let d = (b) => {
616
+ let { headers: _ } = K({ ...u, authorization: `Bearer ${b}` });
617
+ return e.fetchImpl(l, { ...s, headers: _ });
618
+ }, c = await D();
619
+ if (!c)
620
+ throw new R(
587
621
  "Sem sess\xE3o: fa\xE7a login (auth.signIn) antes de chamar a API do produto.",
588
622
  "no_signed_in_user"
589
623
  );
590
- let f = await d(u), g = a.body === void 0 || a.body === null || typeof a.body == "string";
591
- return f.status === 401 && g && await N() && (u = await P(), u && (f = await d(u))), f;
624
+ let m = await d(c), g = s.body === void 0 || s.body === null || typeof s.body == "string";
625
+ return m.status === 401 && g && await N() && (c = await P(), c && (m = await d(c))), m;
626
+ }
627
+ async function $(r) {
628
+ try {
629
+ return await e.storage.getItem(r);
630
+ } catch {
631
+ return null;
632
+ }
592
633
  }
593
- async function ae() {
594
- let r = await e.storage.getItem(E), a = await e.storage.getItem(C);
595
- await e.storage.removeItem(U), await e.storage.removeItem(E), await e.storage.removeItem(C), await e.storage.removeItem(k);
596
- let c = [];
597
- r && c.push({ token: r, hint: "refresh_token" }), a && c.push({ token: a, hint: "access_token" }), c.length > 0 && !await Y(
598
- e.fetchImpl,
599
- S(e.baseUrl),
600
- e.oidcClientId,
601
- c
602
- ) && typeof console < "u" && console.warn(
603
- "[neetru-sdk] mobile signOut: a revoga\xE7\xE3o no servidor n\xE3o foi confirmada. A sess\xE3o local foi encerrada, mas o refresh_token pode seguir v\xE1lido at\xE9 expirar."
604
- ), await i();
634
+ async function de() {
635
+ let r = await $(U), s = await $(C), l = true;
636
+ for (let c of [E, U, C, v])
637
+ try {
638
+ await e.storage.removeItem(c);
639
+ } catch {
640
+ l = false;
641
+ }
642
+ let u = [];
643
+ r && u.push({ token: r, hint: "refresh_token" }), s && u.push({ token: s, hint: "access_token" });
644
+ let d = "skipped";
645
+ if (u.length > 0) {
646
+ let c = await Q(
647
+ e.fetchImpl,
648
+ I(e.baseUrl),
649
+ e.oidcClientId,
650
+ u
651
+ );
652
+ d = c ? "accepted" : "failed", !c && typeof console < "u" && console.warn(
653
+ "[neetru-sdk] mobile signOut: a revoga\xE7\xE3o no servidor n\xE3o foi confirmada. A sess\xE3o local foi encerrada, mas o refresh_token pode seguir v\xE1lido at\xE9 expirar. Trate o campo remoteRevocation do SignOutResult no produto."
654
+ );
655
+ }
656
+ return await a(null), { localSessionCleared: l, remoteRevocation: d };
605
657
  }
606
658
  return {
607
- signIn: p,
608
- completeSignIn: m,
609
- getIdToken: I,
659
+ signIn: f,
660
+ completeSignIn: p,
661
+ getIdToken: y,
610
662
  getAccessToken: D,
611
- getUserInfo: oe,
612
- authFetch: se,
663
+ getUserInfo: ce,
664
+ authFetch: ue,
613
665
  getUser: h,
614
666
  onAuthStateChanged(r) {
615
- return o.add(r), h().then((a) => {
616
- if (o.has(r))
667
+ return n.add(r), h().then((s) => {
668
+ if (n.has(r))
617
669
  try {
618
- r(a);
670
+ r(s);
619
671
  } catch {
620
672
  }
621
673
  }), () => {
622
- o.delete(r);
674
+ n.delete(r);
623
675
  };
624
676
  },
625
677
  refreshTokens: N,
626
- signOut: ae
678
+ signOut: de
627
679
  };
628
680
  }
629
681
 
630
- exports.createMobileAuthNamespace = je;
682
+ exports.createMobileAuthNamespace = Ge;