@neetru/sdk 3.8.1 → 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 +33 -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 +844 -803
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +841 -800
  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 +200 -187
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +193 -180
  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 +880 -839
  30. package/dist/index.d.cts +2 -2
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.mjs +847 -806
  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-yv3EDKg2.d.cts → types-Bl_4HROd.d.cts} +62 -3
  58. package/dist/{types-BYPk_3HR.d.ts → types-Bqnsqvow.d.ts} +62 -3
  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/auth.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  import { jwtVerify, createRemoteJWKSet } from 'jose';
2
2
  import { openDB } from 'idb';
3
3
 
4
- var Qn = Object.defineProperty;
4
+ var Zn = Object.defineProperty;
5
5
  var $ = (n, e) => () => (n && (e = n(n = 0)), e);
6
- var ot = (n, e) => {
6
+ var st = (n, e) => {
7
7
  for (var t in e)
8
- Qn(n, t, { get: e[t], enumerable: true });
8
+ Zn(n, t, { get: e[t], enumerable: true });
9
9
  };
10
10
 
11
11
  // src/errors.ts
12
- var c, V, I = $(() => {
12
+ var c, K, C = $(() => {
13
13
  c = class n extends Error {
14
14
  code;
15
15
  status;
@@ -33,7 +33,7 @@ var c, V, I = $(() => {
33
33
  constructor(e, t, r, o, i, s) {
34
34
  super(t), this.name = "NeetruError", this.code = e, this.status = r, this.requestId = o, this.reason = i, this.correlationId = s, Object.setPrototypeOf(this, n.prototype);
35
35
  }
36
- }, V = class n extends c {
36
+ }, K = class n extends c {
37
37
  constructor(e, t, r, o, i) {
38
38
  super("auth_required", e, r, o, t, i), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, n.prototype);
39
39
  }
@@ -41,7 +41,7 @@ var c, V, I = $(() => {
41
41
  });
42
42
 
43
43
  // src/idempotency.ts
44
- function ht() {
44
+ function yt() {
45
45
  let n = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
46
46
  if (n && typeof n.randomUUID == "function")
47
47
  return n.randomUUID();
@@ -50,15 +50,15 @@ function ht() {
50
50
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
51
51
  );
52
52
  }
53
- var gt = $(() => {
54
- I();
53
+ var _t = $(() => {
54
+ C();
55
55
  });
56
56
 
57
57
  // src/correlation.ts
58
- function _t(n) {
59
- return typeof n == "string" && n.length > 0 && n.length <= 128 && tr.test(n);
58
+ function vt(n) {
59
+ return typeof n == "string" && n.length > 0 && n.length <= 128 && sr.test(n);
60
60
  }
61
- function nr() {
61
+ function ar() {
62
62
  let n = globalThis.crypto;
63
63
  try {
64
64
  if (n && typeof n.randomUUID == "function") return n.randomUUID();
@@ -76,24 +76,24 @@ function nr() {
76
76
  let r = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
77
77
  return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
78
78
  }
79
- function ae(n, e) {
79
+ function ce(n, e) {
80
80
  let t, r = {};
81
81
  for (let [i, s] of Object.entries(n)) {
82
- if (i.toLowerCase() === yt) {
83
- _t(s) && (t = s);
82
+ if (i.toLowerCase() === bt) {
83
+ vt(s) && (t = s);
84
84
  continue;
85
85
  }
86
86
  r[i] = s;
87
87
  }
88
- let o = t ?? (_t(e) ? e : void 0) ?? nr();
89
- return r[yt] = o, { headers: r, correlationId: o };
88
+ let o = t ?? (vt(e) ? e : void 0) ?? ar();
89
+ return r[bt] = o, { headers: r, correlationId: o };
90
90
  }
91
- var yt, tr, Me = $(() => {
92
- yt = "x-correlation-id", tr = /^[A-Za-z0-9._:\-]+$/;
91
+ var bt, sr, qe = $(() => {
92
+ bt = "x-correlation-id", sr = /^[A-Za-z0-9._:\-]+$/;
93
93
  });
94
94
 
95
95
  // src/server-only-key.ts
96
- function X() {
96
+ function Y() {
97
97
  try {
98
98
  let n = globalThis.navigator;
99
99
  if (n && n.product === "ReactNative") return "react-native";
@@ -106,108 +106,108 @@ function X() {
106
106
  }
107
107
  return null;
108
108
  }
109
- function bt(n, e) {
110
- let t = rr[n];
109
+ function wt(n, e) {
110
+ let t = cr[n];
111
111
  return (`${e ? `[Neetru SDK] Recusado: a credencial nrt_ do produto foi passada ao SDK rodando ${t}.` : `[Neetru SDK] ATEN\xC7\xC3O: a credencial nrt_ do produto est\xE1 sendo usada ${t}.`} Essa chave \xE9 S\xD3 DE SERVIDOR \u2014 quem abrir o DevTools (ou descompactar o app) copia a chave e fala com o Core como se fosse o seu produto. Como corrigir: o site/app chama a API do SEU produto (ex.: https://<produto>.neetru.com/api/v1) com o token do usu\xE1rio (Authorization: Bearer <access_token>); o backend do produto valida com verifyAccessToken() e usa o SDK com a chave (NEETRU_API_KEY, sem prefixo NEXT_PUBLIC_/EXPO_PUBLIC_). ` + (e ? "" : "Nesta vers\xE3o \xE9 s\xF3 um aviso; use strictServerOnlyKey: true para bloquear j\xE1. Na pr\xF3xima vers\xE3o MAJOR do SDK isso passa a falhar sempre.")).trim();
112
112
  }
113
- function wt(n) {
113
+ function St(n) {
114
114
  if (!n.hasApiKey) return;
115
- let e = n.runtime === void 0 ? X() : n.runtime;
115
+ let e = n.runtime === void 0 ? Y() : n.runtime;
116
116
  if (e) {
117
117
  if (n.strict)
118
- throw new c("server_only_key", bt(e, true), void 0, void 0, e);
119
- if (!vt) {
120
- vt = true;
118
+ throw new c("server_only_key", wt(e, true), void 0, void 0, e);
119
+ if (!kt) {
120
+ kt = true;
121
121
  try {
122
- typeof console < "u" && typeof console.warn == "function" && console.warn(bt(e, !1));
122
+ typeof console < "u" && typeof console.warn == "function" && console.warn(wt(e, !1));
123
123
  } catch {
124
124
  }
125
125
  }
126
126
  }
127
127
  }
128
- var rr, vt, qe = $(() => {
129
- I();
130
- rr = {
128
+ var cr, kt, Fe = $(() => {
129
+ C();
130
+ cr = {
131
131
  browser: "no navegador",
132
132
  "react-native": "num app React Native"
133
133
  };
134
- vt = false;
134
+ kt = false;
135
135
  });
136
136
 
137
137
  // src/http.ts
138
- var Y = {};
139
- ot(Y, {
140
- checkCoreVersionCompat: () => ce,
138
+ var Z = {};
139
+ st(Z, {
140
+ checkCoreVersionCompat: () => le,
141
141
  httpRequest: () => v,
142
- statusToCode: () => le
142
+ statusToCode: () => de
143
143
  });
144
- function Fe(n) {
144
+ function je(n) {
145
145
  return n.split("+")[0] ?? n;
146
146
  }
147
- function ir(n, e) {
148
- let t = Fe(n).split(".").map(Number), r = Fe(e).split(".").map(Number), o = Math.max(t.length, r.length);
147
+ function dr(n, e) {
148
+ let t = je(n).split(".").map(Number), r = je(e).split(".").map(Number), o = Math.max(t.length, r.length);
149
149
  for (let i = 0; i < o; i++) {
150
150
  let s = t[i] ?? 0, a = r[i] ?? 0;
151
151
  if (s !== a) return s - a;
152
152
  }
153
153
  return 0;
154
154
  }
155
- function Ct() {
155
+ function Et() {
156
156
  try {
157
- return "3.8.1";
157
+ return "3.9.0";
158
158
  } catch {
159
159
  return;
160
160
  }
161
161
  }
162
- function sr() {
163
- let n = Ct();
162
+ function ur() {
163
+ let n = Et();
164
164
  return n ? parseInt(n.split(".")[0] ?? "3", 10) : 3;
165
165
  }
166
- function ce(n) {
166
+ function le(n) {
167
167
  if (!n) return;
168
- let e = sr(), t = or[e];
168
+ let e = ur(), t = lr[e];
169
169
  if (!t) return;
170
- let r = Fe(n);
171
- if (ir(r, t) < 0) {
170
+ let r = je(n);
171
+ if (dr(r, t) < 0) {
172
172
  let o = `${e}:${r}`;
173
- kt.has(o) || (kt.add(o), console.warn(
173
+ Tt.has(o) || (Tt.add(o), console.warn(
174
174
  `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${n}" \xE9 anterior ao m\xEDnimo recomendado "${t}" para SDK major ${e}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
175
175
  ));
176
176
  }
177
177
  }
178
- function ar() {
178
+ function pr() {
179
179
  let n = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
180
- return X() ? "Esta opera\xE7\xE3o exige a credencial nrt_ do produto, que \xE9 S\xD3 DE SERVIDOR. No navegador/app, chame a API do seu produto (ex.: https://<produto>.neetru.com/api/v1) com o token do usu\xE1rio \u2014 o backend do produto faz esta chamada com o SDK e a chave. (" + n + ")" : n;
180
+ return Y() ? "Esta opera\xE7\xE3o exige a credencial nrt_ do produto, que \xE9 S\xD3 DE SERVIDOR. No navegador/app, chame a API do seu produto (ex.: https://<produto>.neetru.com/api/v1) com o token do usu\xE1rio \u2014 o backend do produto faz esta chamada com o SDK e a chave. (" + n + ")" : n;
181
181
  }
182
- function St(n) {
182
+ function Rt(n) {
183
183
  let e = 200 * Math.pow(4, n), t = e * 0.2 * (Math.random() * 2 - 1);
184
184
  return Math.max(50, Math.round(e + t));
185
185
  }
186
- function pr(n) {
186
+ function yr(n) {
187
187
  if (!n) return null;
188
188
  let e = Number(n);
189
- if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), Tt);
189
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), It);
190
190
  let t = Date.parse(n);
191
191
  if (Number.isFinite(t)) {
192
192
  let r = t - Date.now();
193
- if (r > 0) return Math.min(r, Tt);
193
+ if (r > 0) return Math.min(r, It);
194
194
  }
195
195
  return null;
196
196
  }
197
- function Rt(n) {
197
+ function Ct(n) {
198
198
  return new Promise((e) => setTimeout(e, n));
199
199
  }
200
- function le(n) {
200
+ function de(n) {
201
201
  return n === 401 ? "unauthorized" : n === 403 ? "forbidden" : n === 404 ? "not_found" : n === 409 ? "conflict" : n === 410 ? "gone" : n === 422 || n === 400 ? "validation_failed" : n === 429 ? "rate_limited" : n >= 500 ? "server_error" : "unknown";
202
202
  }
203
- function fr(n, e, t) {
203
+ function _r(n, e, t) {
204
204
  let r = n.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, i = new URL(`${r}${o}`);
205
205
  if (t)
206
206
  for (let [s, a] of Object.entries(t))
207
207
  a !== void 0 && i.searchParams.set(s, String(a));
208
208
  return i.toString();
209
209
  }
210
- async function It(n) {
210
+ async function At(n) {
211
211
  let e = await n.text();
212
212
  if (e)
213
213
  try {
@@ -217,17 +217,17 @@ async function It(n) {
217
217
  }
218
218
  }
219
219
  async function v(n, e) {
220
- let t = e.method ?? "GET", r = fr(n.baseUrl, e.path, e.query), o = dr.has(t) ? cr : lr, i = e.retries ?? o, { headers: s, correlationId: a } = ae(
220
+ let t = e.method ?? "GET", r = _r(n.baseUrl, e.path, e.query), o = hr.has(t) ? fr : mr, i = e.retries ?? o, { headers: s, correlationId: a } = ce(
221
221
  { accept: "application/json", ...e.headers },
222
222
  e.correlationId
223
- ), l = Ct();
223
+ ), l = Et();
224
224
  if (l && (s["x-neetru-sdk-version"] = l), e.requireAuth) {
225
225
  if (!n.apiKey)
226
- throw new c("missing_api_key", ar());
226
+ throw new c("missing_api_key", pr());
227
227
  s.authorization = `Bearer ${n.apiKey}`;
228
228
  }
229
229
  if (e.idempotencyKey) {
230
- let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : ht();
230
+ let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : yt();
231
231
  s["idempotency-key"] = f;
232
232
  }
233
233
  let d = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
@@ -247,73 +247,73 @@ async function v(n, e) {
247
247
  d !== void 0 && (h.body = d);
248
248
  let y = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
249
249
  h.signal = AbortSignal.timeout(y);
250
- let S;
250
+ let T;
251
251
  try {
252
- S = await n.fetch(r, h);
253
- } catch (g) {
254
- let C = g instanceof DOMException && g.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${g instanceof Error ? g.message : "fetch failed"}`;
255
- if (u = new c("network_error", C, void 0, void 0, void 0, a), f < i) {
256
- let D = St(f);
252
+ T = await n.fetch(r, h);
253
+ } catch (m) {
254
+ let S = m instanceof DOMException && m.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${m instanceof Error ? m.message : "fetch failed"}`;
255
+ if (u = new c("network_error", S, void 0, void 0, void 0, a), f < i) {
256
+ let D = Rt(f);
257
257
  if (p == null || Date.now() + D < p) {
258
- await Rt(D);
258
+ await Ct(D);
259
259
  continue;
260
260
  }
261
261
  }
262
262
  throw u;
263
263
  }
264
- let x = S.headers.get("x-request-id") ?? S.headers.get("x-correlation-id") ?? void 0;
265
- if (S.ok) {
266
- let g = S.headers.get("x-neetru-version");
267
- return g && ce(g), await It(S);
264
+ let x = T.headers.get("x-request-id") ?? T.headers.get("x-correlation-id") ?? void 0;
265
+ if (T.ok) {
266
+ let m = T.headers.get("x-neetru-version");
267
+ return m && le(m), await At(T);
268
268
  }
269
- let T = await It(S), P = le(S.status), q = `HTTP ${S.status}`, m;
270
- if (T && typeof T == "object") {
271
- let g = T.error;
272
- typeof g == "string" ? q = g : g && typeof g == "object" ? (typeof g.code == "string" && (P = g.code), typeof g.message == "string" && (q = g.message), typeof g.reason == "string" && (m = g.reason)) : (typeof T.code == "string" && (P = T.code), typeof T.message == "string" && (q = T.message)), typeof T.reason == "string" && (m = T.reason);
269
+ let R = await At(T), E = de(T.status), j = `HTTP ${T.status}`, g;
270
+ if (R && typeof R == "object") {
271
+ let m = R.error;
272
+ typeof m == "string" ? j = m : m && typeof m == "object" ? (typeof m.code == "string" && (E = m.code), typeof m.message == "string" && (j = m.message), typeof m.reason == "string" && (g = m.reason)) : (typeof R.code == "string" && (E = R.code), typeof R.message == "string" && (j = R.message)), typeof R.reason == "string" && (g = R.reason);
273
273
  }
274
- if (S.status === 410) {
275
- let g = S.headers.get("x-neetru-replacement");
276
- q === `HTTP ${S.status}` && (q = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), g && !q.includes(g) && (q += ` Substituto: ${g}.`);
274
+ if (T.status === 410) {
275
+ let m = T.headers.get("x-neetru-replacement");
276
+ j === `HTTP ${T.status}` && (j = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), m && !j.includes(m) && (j += ` Substituto: ${m}.`);
277
277
  }
278
- let _ = new c(P, q, S.status, x, m, a);
279
- if (u = _, ur.has(P) && f < i) {
280
- let C = pr(S.headers.get("retry-after")) ?? St(f);
281
- if (p == null || Date.now() + C < p) {
282
- await Rt(C);
278
+ let b = new c(E, j, T.status, x, g, a);
279
+ if (u = b, gr.has(E) && f < i) {
280
+ let S = yr(T.headers.get("retry-after")) ?? Rt(f);
281
+ if (p == null || Date.now() + S < p) {
282
+ await Ct(S);
283
283
  continue;
284
284
  }
285
285
  }
286
- throw _;
286
+ throw b;
287
287
  }
288
288
  throw u ?? new c("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
289
289
  }
290
- var or, kt, cr, lr, dr, ur, Tt, M = $(() => {
291
- I();
292
- gt();
293
- Me();
290
+ var lr, Tt, fr, mr, hr, gr, It, F = $(() => {
291
+ C();
292
+ _t();
294
293
  qe();
295
- or = {
294
+ Fe();
295
+ lr = {
296
296
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
297
297
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
298
298
  3: "2026.05.1"
299
299
  };
300
- kt = /* @__PURE__ */ new Set();
301
- cr = 2, lr = 0, dr = /* @__PURE__ */ new Set(["GET", "HEAD"]), ur = /* @__PURE__ */ new Set([
300
+ Tt = /* @__PURE__ */ new Set();
301
+ fr = 2, mr = 0, hr = /* @__PURE__ */ new Set(["GET", "HEAD"]), gr = /* @__PURE__ */ new Set([
302
302
  "rate_limited",
303
303
  "server_error",
304
304
  "network_error"
305
305
  ]);
306
- Tt = 6e4;
306
+ It = 6e4;
307
307
  });
308
308
 
309
309
  // src/db-errors.ts
310
- var Ir, b, Z = $(() => {
311
- I();
312
- Ir = /* @__PURE__ */ new Set([
310
+ var Dr, _, ee = $(() => {
311
+ C();
312
+ Dr = /* @__PURE__ */ new Set([
313
313
  "db_unavailable",
314
314
  "db_conflict",
315
315
  "db_timeout"
316
- ]), b = class n extends c {
316
+ ]), _ = class n extends c {
317
317
  /** Código de erro fechado — específico de DB. */
318
318
  code;
319
319
  /**
@@ -327,16 +327,16 @@ var Ir, b, Z = $(() => {
327
327
  */
328
328
  dbId;
329
329
  constructor(e, t, r) {
330
- super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Ir.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
330
+ super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Dr.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
331
331
  }
332
332
  };
333
333
  });
334
334
 
335
335
  // src/db/sql/resilient-pool.ts
336
- function ve(n) {
337
- return typeof n == "object" && n !== null && n[He] === true;
336
+ function we(n) {
337
+ return typeof n == "object" && n !== null && n[Ge] === true;
338
338
  }
339
- function Qr(n) {
339
+ function Zr(n) {
340
340
  let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
341
341
  if (e === "ECONNREFUSED" || e === "ETIMEDOUT" || e === "ENOTFOUND" || e === "EHOSTUNREACH" || e === "EAI_AGAIN")
342
342
  return true;
@@ -348,17 +348,17 @@ function Qr(n) {
348
348
  let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
349
349
  return r.length === 0 ? false : !!(r.includes("certificate expired") || r.includes("certificate has expired") || r.includes("cert_has_expired") || r.includes("alert certificate expired") || r.includes("err_ssl") || r.includes("sslv3 alert") || r.includes("tlsv1 alert") || r.includes("econnrefused") || r.includes("etimedout") || r.includes("enotfound") || r.includes("ehostunreach") || r.includes("getaddrinfo"));
350
350
  }
351
- function Gt(n) {
351
+ function Xt(n) {
352
352
  let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
353
- if (typeof e == "string" && Gr.has(e.toUpperCase()))
353
+ if (typeof e == "string" && eo.has(e.toUpperCase()))
354
354
  return true;
355
355
  let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
356
356
  return r.length === 0 ? false : r.includes("password authentication failed") || r.includes("sasl authentication failed");
357
357
  }
358
- function Jr(n) {
359
- return Qr(n) || Gt(n);
358
+ function to(n) {
359
+ return Zr(n) || Xt(n);
360
360
  }
361
- function Qe(n) {
361
+ function Je(n) {
362
362
  let e = { current: n }, t = null, r = {
363
363
  __neetruSwapInner(u) {
364
364
  let p = e.current;
@@ -386,10 +386,10 @@ function Qe(n) {
386
386
  }
387
387
  return await o(u, e.current, f);
388
388
  }
389
- })(), s = i("query", Jr), a = i("connect", Gt), l = Object.create(Object.getPrototypeOf(n));
389
+ })(), s = i("query", to), a = i("connect", Xt), l = Object.create(Object.getPrototypeOf(n));
390
390
  return new Proxy(l, {
391
391
  get(u, p) {
392
- if (p === He) return true;
392
+ if (p === Ge) return true;
393
393
  if (p === "__neetruSwapInner") return r.__neetruSwapInner;
394
394
  if (p === "__neetruGetInner") return r.__neetruGetInner;
395
395
  if (p === "__neetruSetReLease") return r.__neetruSetReLease;
@@ -405,27 +405,27 @@ function Qe(n) {
405
405
  }
406
406
  });
407
407
  }
408
- var He, Gr, Ge = $(() => {
409
- He = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
410
- Gr = /* @__PURE__ */ new Set(["28P01", "28000"]);
408
+ var Ge, eo, Xe = $(() => {
409
+ Ge = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
410
+ eo = /* @__PURE__ */ new Set(["28P01", "28000"]);
411
411
  });
412
412
 
413
413
  // src/db/sql/lease.ts
414
- function Yr(n, e) {
414
+ function ro(n, e) {
415
415
  return n ? n.leaseId !== e.leaseId || n.credentialVersion !== e.credentialVersion || n.host !== e.host || n.port !== e.port || n.dbName !== e.dbName || n.user !== e.user || n.password !== e.password || n.sslca !== e.sslca || n.clientCert !== e.clientCert || n.clientKey !== e.clientKey : true;
416
416
  }
417
- function Zr(n) {
418
- if (n instanceof b) return n;
417
+ function oo(n) {
418
+ if (n instanceof _) return n;
419
419
  let e = n instanceof Error ? n.message : String(n), t = n instanceof Error ? n.code : void 0;
420
- return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new b(
420
+ return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new _(
421
421
  "db_unavailable",
422
422
  `Pool connection failed (${t}): ${e}`
423
- ) : e.includes("statement timeout") || e.includes("lock timeout") ? new b("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new b("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new b("db_permission_denied", `Permission denied: ${e}`) : new b("db_unavailable", `Database error: ${e}`);
423
+ ) : e.includes("statement timeout") || e.includes("lock timeout") ? new _("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new _("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new _("db_permission_denied", `Permission denied: ${e}`) : new _("db_unavailable", `Database error: ${e}`);
424
424
  }
425
- var Xr, J, re, Jt = $(() => {
426
- Z();
427
- Ge();
428
- Xr = 0.8, J = 3e4, re = class {
425
+ var no, X, oe, Yt = $(() => {
426
+ ee();
427
+ Xe();
428
+ no = 0.8, X = 3e4, oe = class {
429
429
  /**
430
430
  * Lease atual. `null` no modo LAZY antes da 1ª query (o 1º lease é adiado —
431
431
  * ver `_ensureInitialLease`). Após a 1ª aquisição, sempre não-nulo.
@@ -465,7 +465,7 @@ var Xr, J, re, Jt = $(() => {
465
465
  isolationLevel: t.isolationLevel
466
466
  }) : await this._orm.transaction(e);
467
467
  } catch (r) {
468
- throw Zr(r);
468
+ throw oo(r);
469
469
  }
470
470
  }
471
471
  async close() {
@@ -483,13 +483,13 @@ var Xr, J, re, Jt = $(() => {
483
483
  * usa `MIN_RENEWAL_DELAY_MS` como fallback seguro.
484
484
  */
485
485
  _calcRenewalDelayMs() {
486
- if (!this._lease) return J;
486
+ if (!this._lease) return X;
487
487
  let e = Date.parse(this._lease.expiresAt);
488
- if (!Number.isFinite(e)) return J;
488
+ if (!Number.isFinite(e)) return X;
489
489
  let t = this._deps.now(), r = e - t;
490
- if (r <= 0) return J;
491
- let o = r * (1 - Xr);
492
- return Math.max(J, Math.round(o));
490
+ if (r <= 0) return X;
491
+ let o = r * (1 - no);
492
+ return Math.max(X, Math.round(o));
493
493
  }
494
494
  _scheduleRenewal() {
495
495
  if (this._closed) return;
@@ -516,8 +516,8 @@ var Xr, J, re, Jt = $(() => {
516
516
  } catch (t) {
517
517
  this._renewalTimer = setTimeout(() => {
518
518
  this._doRenew();
519
- }, J), console.warn(
520
- `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${J}ms (o cert de cliente mTLS do lease expira ~15min ap\xF3s o \xFAltimo swap):`,
519
+ }, X), console.warn(
520
+ `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${X}ms (o cert de cliente mTLS do lease expira ~15min ap\xF3s o \xFAltimo swap):`,
521
521
  t instanceof Error ? t.message : t
522
522
  );
523
523
  return;
@@ -551,7 +551,7 @@ var Xr, J, re, Jt = $(() => {
551
551
  */
552
552
  async _reactiveReLease() {
553
553
  if (this._closed)
554
- throw new b(
554
+ throw new _(
555
555
  "db_unavailable",
556
556
  "SqlLeaseManager foi fechado \u2014 re-lease reativo abortado."
557
557
  );
@@ -588,30 +588,30 @@ var Xr, J, re, Jt = $(() => {
588
588
  */
589
589
  async _ensureInitialLease() {
590
590
  if (this._closed)
591
- throw new b(
591
+ throw new _(
592
592
  "db_unavailable",
593
593
  "SqlLeaseManager foi fechado \u2014 aquisi\xE7\xE3o de lease inicial abortada."
594
594
  );
595
595
  if (this._lease)
596
- return ve(this._pool) ? this._pool.__neetruGetInner() : this._pool;
596
+ return we(this._pool) ? this._pool.__neetruGetInner() : this._pool;
597
597
  if (this._initInFlight !== null) return this._initInFlight;
598
598
  let e = (async () => {
599
599
  let t;
600
600
  try {
601
601
  t = this._deps.database !== void 0 ? await this._deps.fetchLease({ database: this._deps.database }) : await this._deps.fetchLease();
602
602
  } catch (o) {
603
- if (o instanceof b) throw o;
603
+ if (o instanceof _) throw o;
604
604
  let i = o instanceof Error ? o.message : String(o);
605
- throw new b("db_unavailable", `Falha ao obter lease inicial: ${i}`);
605
+ throw new _("db_unavailable", `Falha ao obter lease inicial: ${i}`);
606
606
  }
607
607
  let r;
608
608
  try {
609
609
  r = this._deps.createPool(t);
610
610
  } catch (o) {
611
611
  let i = o instanceof Error ? o.message : String(o);
612
- throw new b("db_unavailable", `Falha ao abrir pool: ${i}`);
612
+ throw new _("db_unavailable", `Falha ao abrir pool: ${i}`);
613
613
  }
614
- return ve(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
614
+ return we(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
615
615
  }) : this._pool = r, this._lease = t, this._scheduleRenewal(), r;
616
616
  })();
617
617
  this._initInFlight = e;
@@ -627,12 +627,12 @@ var Xr, J, re, Jt = $(() => {
627
627
  * Exposto como método protegido para testes.
628
628
  */
629
629
  async _swapPool(e) {
630
- if (!Yr(this._lease, e)) {
630
+ if (!ro(this._lease, e)) {
631
631
  this._lease = e;
632
632
  return;
633
633
  }
634
634
  let t = this._deps.createPool(e);
635
- if (ve(this._pool)) {
635
+ if (we(this._pool)) {
636
636
  let i = this._pool.__neetruSwapInner(t);
637
637
  this._lease = e, i.end().catch(() => {
638
638
  });
@@ -645,7 +645,7 @@ var Xr, J, re, Jt = $(() => {
645
645
  // ─── Helpers ───────────────────────────────────────────────────────────────
646
646
  _assertOpen() {
647
647
  if (this._closed)
648
- throw new b(
648
+ throw new _(
649
649
  "db_unavailable",
650
650
  "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
651
651
  );
@@ -654,29 +654,29 @@ var Xr, J, re, Jt = $(() => {
654
654
  });
655
655
 
656
656
  // src/db/sql/sql-client.ts
657
- var on = {};
658
- ot(on, {
659
- DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => nn,
660
- DEFAULT_POOL_IDLE_MS: () => tn,
661
- DEFAULT_POOL_MAX: () => en,
662
- LEASE_ENDPOINT: () => Xt,
663
- LEASE_RENEW_ENDPOINT: () => Yt,
664
- createDrizzleHandle: () => ro,
665
- createHttpLeaseFetcher: () => Zt,
666
- createPgPool: () => no,
667
- createSqlClientFromConfig: () => io,
668
- createSqlClientWithDeps: () => rn,
669
- resolvePoolTuning: () => Xe
657
+ var an = {};
658
+ st(an, {
659
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => on,
660
+ DEFAULT_POOL_IDLE_MS: () => rn,
661
+ DEFAULT_POOL_MAX: () => nn,
662
+ LEASE_ENDPOINT: () => Zt,
663
+ LEASE_RENEW_ENDPOINT: () => en,
664
+ createDrizzleHandle: () => co,
665
+ createHttpLeaseFetcher: () => tn,
666
+ createPgPool: () => ao,
667
+ createSqlClientFromConfig: () => uo,
668
+ createSqlClientWithDeps: () => sn,
669
+ resolvePoolTuning: () => Ze
670
670
  });
671
- function eo(n) {
671
+ function io(n) {
672
672
  return n === "workspace" ? "staging" : n === "prod" ? "production" : "dev-local";
673
673
  }
674
- function Zt(n) {
674
+ function tn(n) {
675
675
  return async (e) => {
676
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = !!e?.leaseId, o = r ? Yt : Xt, i;
676
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = !!e?.leaseId, o = r ? en : Zt, i;
677
677
  r ? i = { leaseId: e.leaseId } : (i = {
678
678
  productId: n.productId ?? "",
679
- environment: eo(n.env ?? "prod")
679
+ environment: io(n.env ?? "prod")
680
680
  }, e?.database !== void 0 && (i.database = e.database));
681
681
  let s;
682
682
  try {
@@ -692,32 +692,32 @@ function Zt(n) {
692
692
  let l = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof c ? a.reason : void 0;
693
693
  if (u === "suspended" || u === "archived" || u === "revoked") {
694
694
  let p = u === "suspended" ? "ambiente suspenso \u2014 a m\xE1quina que o servia parou; ser\xE1 religado quando o ambiente voltar" : u === "archived" ? "ambiente arquivado \u2014 este banco foi arquivado e n\xE3o aceita mais conex\xF5es" : "lease revogado \u2014 as credenciais deste ambiente foram revogadas pelo Core";
695
- throw new b(
695
+ throw new _(
696
696
  "db_suspended",
697
697
  `Falha ao ${l} lease SQL: ${p} (reason=${u}).`
698
698
  );
699
699
  }
700
- throw new b(
700
+ throw new _(
701
701
  "db_unavailable",
702
702
  `Falha ao ${l} lease SQL: ${d}`
703
703
  );
704
704
  }
705
- return to(s);
705
+ return so(s);
706
706
  };
707
707
  }
708
- function to(n) {
708
+ function so(n) {
709
709
  if (!n || typeof n != "object")
710
- throw new b("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
710
+ throw new _("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
711
711
  let t = n.lease;
712
712
  if (!t || typeof t != "object")
713
- throw new b(
713
+ throw new _(
714
714
  "db_unavailable",
715
715
  'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
716
716
  );
717
717
  let r = t;
718
718
  function o(i, s) {
719
719
  if (typeof r[i] !== s)
720
- throw new b(
720
+ throw new _(
721
721
  "db_unavailable",
722
722
  `Campo obrigat\xF3rio "${i}" ausente ou tipo inv\xE1lido na resposta de lease.`
723
723
  );
@@ -737,22 +737,22 @@ function to(n) {
737
737
  expiresAt: o("expiresAt", "string")
738
738
  };
739
739
  }
740
- function Je(n, e, t, r) {
740
+ function Ye(n, e, t, r) {
741
741
  let o = typeof process < "u" ? process.env?.[n] : void 0;
742
742
  if (o === void 0 || o.trim() === "") return e;
743
743
  let i = Number.parseInt(o.trim(), 10);
744
744
  return !Number.isFinite(i) || i < t || i > r ? e : i;
745
745
  }
746
- function Xe() {
746
+ function Ze() {
747
747
  return {
748
748
  // Teto 100: bem abaixo do `max_client_conn = 500` do PgBouncer, com folga
749
749
  // para múltiplas instâncias do app dividirem o mesmo front-door.
750
- max: Je("NEETRU_DB_POOL_MAX", en, 1, 100),
750
+ max: Ye("NEETRU_DB_POOL_MAX", nn, 1, 100),
751
751
  // Teto 15min = janela do cert; piso 1s.
752
- idleTimeoutMillis: Je("NEETRU_DB_POOL_IDLE_MS", tn, 1e3, 9e5),
753
- connectionTimeoutMillis: Je(
752
+ idleTimeoutMillis: Ye("NEETRU_DB_POOL_IDLE_MS", rn, 1e3, 9e5),
753
+ connectionTimeoutMillis: Ye(
754
754
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
755
- nn,
755
+ on,
756
756
  1e3,
757
757
  12e4
758
758
  ),
@@ -760,7 +760,7 @@ function Xe() {
760
760
  keepAliveInitialDelayMillis: 1e4
761
761
  };
762
762
  }
763
- async function no(n) {
763
+ async function ao(n) {
764
764
  let { Pool: e } = await import(
765
765
  /* webpackIgnore: true */
766
766
  'pg'
@@ -777,17 +777,17 @@ async function no(n) {
777
777
  user: n.user,
778
778
  password: n.password,
779
779
  ssl: t,
780
- ...Xe()
780
+ ...Ze()
781
781
  });
782
782
  }
783
- async function ro(n, e) {
783
+ async function co(n, e) {
784
784
  let { drizzle: t } = await import(
785
785
  /* webpackIgnore: true */
786
786
  'drizzle-orm/node-postgres'
787
787
  );
788
788
  return t(n, { schema: e });
789
789
  }
790
- function oo(n, e) {
790
+ function lo(n, e) {
791
791
  let t = null, r = null, o = () => t ? Promise.resolve(t) : (r || (r = e().then((s) => (t = s, r = null, s)).catch((s) => {
792
792
  throw r = null, s;
793
793
  })), r), i = {
@@ -803,52 +803,52 @@ function oo(n, e) {
803
803
  };
804
804
  return n && Object.setPrototypeOf(i, n), i;
805
805
  }
806
- async function rn(n, e) {
806
+ async function sn(n, e) {
807
807
  let t = e?.database !== void 0 ? { ...n, database: e.database } : n;
808
808
  if (t.lazy) {
809
- let l = null, d = oo(t.poolPrototype ?? null, () => {
809
+ let l = null, d = lo(t.poolPrototype ?? null, () => {
810
810
  if (!l)
811
- throw new b("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
811
+ throw new _("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
812
812
  return l._ensureInitialLease();
813
- }), u = Qe(d), p;
813
+ }), u = Je(d), p;
814
814
  try {
815
815
  p = t.createDrizzle(u, t.schema);
816
816
  } catch (h) {
817
817
  let y = h instanceof Error ? h.message : String(h);
818
- throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${y}`);
818
+ throw new _("db_unavailable", `Falha ao criar handle Drizzle: ${y}`);
819
819
  }
820
- let f = new re(null, u, p, t);
820
+ let f = new oe(null, u, p, t);
821
821
  return l = f, u.__neetruSetReLease(() => f._reactiveReLease()), f;
822
822
  }
823
823
  let r;
824
824
  try {
825
825
  e?.database !== void 0 ? r = await t.fetchLease({ database: e.database }) : r = await t.fetchLease();
826
826
  } catch (l) {
827
- if (l instanceof b) throw l;
827
+ if (l instanceof _) throw l;
828
828
  let d = l instanceof Error ? l.message : String(l);
829
- throw new b("db_unavailable", `Falha ao obter lease inicial: ${d}`);
829
+ throw new _("db_unavailable", `Falha ao obter lease inicial: ${d}`);
830
830
  }
831
831
  let o;
832
832
  try {
833
833
  o = t.createPool(r);
834
834
  } catch (l) {
835
835
  let d = l instanceof Error ? l.message : String(l);
836
- throw new b("db_unavailable", `Falha ao abrir pool: ${d}`);
836
+ throw new _("db_unavailable", `Falha ao abrir pool: ${d}`);
837
837
  }
838
- let i = Qe(o), s;
838
+ let i = Je(o), s;
839
839
  try {
840
840
  s = t.createDrizzle(i, t.schema);
841
841
  } catch (l) {
842
842
  await o.end().catch(() => {
843
843
  });
844
844
  let d = l instanceof Error ? l.message : String(l);
845
- throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
845
+ throw new _("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
846
846
  }
847
- let a = new re(r, i, s, t);
847
+ let a = new oe(r, i, s, t);
848
848
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
849
849
  }
850
- async function io(n, e, t) {
851
- let r = Zt(n), o, i;
850
+ async function uo(n, e, t) {
851
+ let r = tn(n), o, i;
852
852
  try {
853
853
  o = await import(
854
854
  /* webpackIgnore: true */
@@ -858,13 +858,13 @@ async function io(n, e, t) {
858
858
  'drizzle-orm/node-postgres'
859
859
  );
860
860
  } catch (d) {
861
- throw new b(
861
+ throw new _(
862
862
  "db_unavailable",
863
863
  `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${d.message})`
864
864
  );
865
865
  }
866
866
  let s = o.Pool ?? o.default?.Pool;
867
- return rn(
867
+ return sn(
868
868
  {
869
869
  fetchLease: r,
870
870
  createPool: (d) => {
@@ -883,7 +883,7 @@ async function io(n, e, t) {
883
883
  ssl: u,
884
884
  // Tuning centralizado (env-tunável) — ver resolvePoolTuning + auditoria
885
885
  // docs/_review/AUDITORIA_DB_CONN_PERF_2026-09-06.md no Core.
886
- ...Xe()
886
+ ...Ze()
887
887
  });
888
888
  },
889
889
  createDrizzle: (d, u) => i.drizzle(d, { schema: u }),
@@ -899,39 +899,39 @@ async function io(n, e, t) {
899
899
  t
900
900
  );
901
901
  }
902
- var Xt, Yt, en, tn, nn, sn = $(() => {
903
- Z();
904
- I();
905
- Jt();
906
- Ge();
907
- Xt = "/api/sdk/v1/db/lease", Yt = "/api/sdk/v1/db/lease/renew";
908
- en = 10, tn = 6e4, nn = 1e4;
902
+ var Zt, en, nn, rn, on, cn = $(() => {
903
+ ee();
904
+ C();
905
+ Yt();
906
+ Xe();
907
+ Zt = "/api/sdk/v1/db/lease", en = "/api/sdk/v1/db/lease/renew";
908
+ nn = 10, rn = 6e4, on = 1e4;
909
909
  });
910
- var Le = /* @__PURE__ */ new Map(), Ue = 3600 * 1e3;
911
- function it(n, e = Ue) {
912
- let t = Date.now(), r = Le.get(n);
910
+ var Ue = /* @__PURE__ */ new Map(), Me = 3600 * 1e3;
911
+ function at(n, e = Me) {
912
+ let t = Date.now(), r = Ue.get(n);
913
913
  if (r && t - r.createdAt < e)
914
914
  return r.jwks;
915
915
  let o = createRemoteJWKSet(new URL(n));
916
- return Le.set(n, { jwks: o, createdAt: t }), o;
916
+ return Ue.set(n, { jwks: o, createdAt: t }), o;
917
917
  }
918
- function st() {
919
- Le.clear();
918
+ function ct() {
919
+ Ue.clear();
920
920
  }
921
921
 
922
922
  // src/auth.ts
923
- I();
923
+ C();
924
924
 
925
925
  // src/api-key.ts
926
- I();
927
- var at = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
928
- function ct(n) {
926
+ C();
927
+ var lt = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
928
+ function dt(n) {
929
929
  if (typeof n != "string" || n.length === 0)
930
930
  throw new c(
931
931
  "invalid_config",
932
932
  "apiKey is required (formato nrt_<keyId>_<secret>)"
933
933
  );
934
- let e = at.exec(n);
934
+ let e = lt.exec(n);
935
935
  if (!e)
936
936
  throw new c(
937
937
  "invalid_config",
@@ -939,22 +939,22 @@ function ct(n) {
939
939
  );
940
940
  return { keyId: e[1], secret: e[2] };
941
941
  }
942
- function lt(n) {
942
+ function ut(n) {
943
943
  if (typeof n != "string" || n.length === 0) return null;
944
- let e = at.exec(n);
944
+ let e = lt.exec(n);
945
945
  return e ? { keyId: e[1], secret: e[2] } : null;
946
946
  }
947
947
 
948
948
  // src/base-url-allowlist.ts
949
- I();
950
- var dt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), Jn = ".neetru.com", Xn = "neetru.com", Yn = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
951
- function ut(n) {
952
- return Yn.test(n);
949
+ C();
950
+ var pt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), tr = ".neetru.com", nr = "neetru.com", rr = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
951
+ function ft(n) {
952
+ return rr.test(n);
953
953
  }
954
- function Zn(n) {
954
+ function or(n) {
955
955
  return n.toLowerCase().replace(/\.+$/, "");
956
956
  }
957
- function pt(n, e = []) {
957
+ function mt(n, e = []) {
958
958
  if (typeof n != "string" || n.length === 0)
959
959
  throw new c("invalid_config", "baseUrl is required");
960
960
  let t;
@@ -963,8 +963,8 @@ function pt(n, e = []) {
963
963
  } catch {
964
964
  throw new c("invalid_config", `baseUrl is not a valid URL: ${n}`);
965
965
  }
966
- let r = t.protocol, o = Zn(t.hostname);
967
- if (er())
966
+ let r = t.protocol, o = or(t.hostname);
967
+ if (ir())
968
968
  return typeof console < "u" && console.warn(
969
969
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${n} aceito sem valida\xE7\xE3o.`
970
970
  ), n.replace(/\/+$/, "");
@@ -974,17 +974,17 @@ function pt(n, e = []) {
974
974
  `baseUrl protocol must be http: or https:, got ${r}`
975
975
  );
976
976
  if (r === "http:") {
977
- if (!(dt.has(o) || ut(o)))
977
+ if (!(pt.has(o) || ft(o)))
978
978
  throw new c(
979
979
  "invalid_config",
980
980
  `baseUrl with http: only allowed for localhost/127.0.0.1/*.test/*.localhost. Got: ${o}. Use https: or set NEETRU_ALLOW_INSECURE_BASEURL=1 to bypass.`
981
981
  );
982
982
  return n.replace(/\/+$/, "");
983
983
  }
984
- let i = o === Xn || o.endsWith(Jn), s = e.some((l) => {
984
+ let i = o === nr || o.endsWith(tr), s = e.some((l) => {
985
985
  let d = l.toLowerCase();
986
986
  return o === d || o.endsWith(`.${d}`);
987
- }), a = dt.has(o) || ut(o);
987
+ }), a = pt.has(o) || ft(o);
988
988
  if (!i && !s && !a)
989
989
  throw new c(
990
990
  "invalid_config",
@@ -992,7 +992,7 @@ function pt(n, e = []) {
992
992
  );
993
993
  return n.replace(/\/+$/, "");
994
994
  }
995
- function er() {
995
+ function ir() {
996
996
  try {
997
997
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
998
998
  if (e === "1" || e === "true") return !0;
@@ -1007,12 +1007,12 @@ function er() {
1007
1007
  }
1008
1008
 
1009
1009
  // src/types.ts
1010
- var ft = "https://api.neetru.com", mt = "http://localhost:9003";
1010
+ var ht = "https://api.neetru.com", gt = "http://localhost:9003";
1011
1011
 
1012
1012
  // src/catalog.ts
1013
- I();
1014
- M();
1015
- function At(n) {
1013
+ C();
1014
+ F();
1015
+ function Pt(n) {
1016
1016
  if (!n || typeof n != "object")
1017
1017
  throw new c("invalid_response", "Catalog response item is not an object");
1018
1018
  let e = n;
@@ -1031,7 +1031,7 @@ function At(n) {
1031
1031
  return typeof r.amountCents == "number" && (o.amountCents = r.amountCents), Array.isArray(r.features) && r.features.every((i) => typeof i == "string") && (o.features = r.features), o;
1032
1032
  })), t;
1033
1033
  }
1034
- function Et(n) {
1034
+ function Dt(n) {
1035
1035
  return {
1036
1036
  /**
1037
1037
  * Lista produtos publicados. Por default só `published=true`; staff
@@ -1048,7 +1048,7 @@ function Et(n) {
1048
1048
  "Catalog list response missing products array"
1049
1049
  );
1050
1050
  return {
1051
- products: t.products.map(At),
1051
+ products: t.products.map(Pt),
1052
1052
  fetchedAt: typeof t.fetchedAt == "string" ? t.fetchedAt : (/* @__PURE__ */ new Date()).toISOString()
1053
1053
  };
1054
1054
  },
@@ -1069,32 +1069,32 @@ function Et(n) {
1069
1069
  "invalid_response",
1070
1070
  "Catalog get response missing product"
1071
1071
  );
1072
- return At(t.product);
1072
+ return Pt(t.product);
1073
1073
  }
1074
1074
  };
1075
1075
  }
1076
1076
 
1077
1077
  // src/entitlements.ts
1078
- I();
1079
- var mr = "client.entitlements.check()/checkDetailed() est\xE3o DEPRECADOS \u2014 apontavam para GET /api/v1/sdk/entitlements/check, um endpoint que o Core nunca escreve (sempre retornava not_subscribed). Use client.usage.check(resource, { productId, tenantId }) no lugar \u2014 mesmo resultado (allowed/reason/remaining/limit/behavior), endpoint real.";
1080
- function Pt() {
1081
- throw new c("validation_failed", mr);
1078
+ C();
1079
+ var br = "client.entitlements.check()/checkDetailed() est\xE3o DEPRECADOS \u2014 apontavam para GET /api/v1/sdk/entitlements/check, um endpoint que o Core nunca escreve (sempre retornava not_subscribed). Use client.usage.check(resource, { productId, tenantId }) no lugar \u2014 mesmo resultado (allowed/reason/remaining/limit/behavior), endpoint real.";
1080
+ function Nt() {
1081
+ throw new c("validation_failed", br);
1082
1082
  }
1083
- function Dt(n) {
1083
+ function xt(n) {
1084
1084
  return {
1085
1085
  /**
1086
1086
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
1087
1087
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
1088
1088
  */
1089
1089
  async check(e, t, r) {
1090
- Pt();
1090
+ Nt();
1091
1091
  },
1092
1092
  /**
1093
1093
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
1094
1094
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
1095
1095
  */
1096
1096
  async checkDetailed(e, t, r) {
1097
- Pt();
1097
+ Nt();
1098
1098
  },
1099
1099
  /** Test helper legado — no-op (não há mais cache). Mantido por compat. */
1100
1100
  __resetCache() {
@@ -1103,16 +1103,31 @@ function Dt(n) {
1103
1103
  }
1104
1104
 
1105
1105
  // src/telemetry.ts
1106
- I();
1107
- M();
1108
- var Nt = ["debug", "info", "warn", "error", "fatal"];
1109
- function hr() {
1106
+ C();
1107
+ F();
1108
+
1109
+ // src/runtime-env.ts
1110
+ function $e() {
1111
+ try {
1112
+ if (typeof process < "u" && process.env)
1113
+ return process.env.NODE_ENV === "production";
1114
+ } catch {
1115
+ }
1116
+ return false;
1117
+ }
1118
+ function W(n) {
1119
+ return n === "dev" && !$e();
1120
+ }
1121
+
1122
+ // src/telemetry.ts
1123
+ var Ot = ["debug", "info", "warn", "error", "fatal"];
1124
+ function vr() {
1110
1125
  return typeof globalThis < "u" && typeof globalThis.window < "u";
1111
1126
  }
1112
- function xt() {
1113
- return hr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1127
+ function Lt() {
1128
+ return vr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1114
1129
  }
1115
- function gr(n) {
1130
+ function wr(n) {
1116
1131
  switch (n) {
1117
1132
  case "debug":
1118
1133
  return console.debug.bind(console);
@@ -1128,8 +1143,8 @@ function gr(n) {
1128
1143
  return console.log.bind(console);
1129
1144
  }
1130
1145
  }
1131
- var yr = 500, _r = 50;
1132
- function Ot(n) {
1146
+ var kr = 500, Sr = 50;
1147
+ function Ut(n) {
1133
1148
  let e = [], t = null, r = null;
1134
1149
  async function o() {
1135
1150
  if (e.length === 0) return;
@@ -1138,7 +1153,7 @@ function Ot(n) {
1138
1153
  try {
1139
1154
  let d = { name: l.name }, u = l.productSlug ?? n.productId;
1140
1155
  u && (d.productSlug = u), l.properties && typeof l.properties == "object" && (d.properties = l.properties), l.timestamp && (d.timestamp = l.timestamp);
1141
- let p = xt();
1156
+ let p = Lt();
1142
1157
  await v(n, {
1143
1158
  method: "POST",
1144
1159
  path: p.path,
@@ -1162,7 +1177,7 @@ function Ot(n) {
1162
1177
  function i() {
1163
1178
  t || (t = setTimeout(() => {
1164
1179
  o();
1165
- }, yr));
1180
+ }, kr));
1166
1181
  }
1167
1182
  return {
1168
1183
  /**
@@ -1186,7 +1201,7 @@ function Ot(n) {
1186
1201
  throw new c("validation_failed", "event.name max 128 chars");
1187
1202
  let a = { name: s.name }, l = s.productSlug ?? n.productId;
1188
1203
  l && (a.productSlug = l), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1189
- let d = xt(), u = await v(n, {
1204
+ let d = Lt(), u = await v(n, {
1190
1205
  method: "POST",
1191
1206
  path: d.path,
1192
1207
  body: a,
@@ -1207,7 +1222,7 @@ function Ot(n) {
1207
1222
  * ```
1208
1223
  */
1209
1224
  track(s) {
1210
- !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= _r ? (t && (clearTimeout(t), t = null), o()) : i());
1225
+ !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= Sr ? (t && (clearTimeout(t), t = null), o()) : i());
1211
1226
  },
1212
1227
  /**
1213
1228
  * Força flush imediato da queue de `track()`. Resolva antes de
@@ -1234,14 +1249,14 @@ function Ot(n) {
1234
1249
  async log(s) {
1235
1250
  if (!s || typeof s != "object")
1236
1251
  throw new c("validation_failed", "log input is required");
1237
- if (!Nt.includes(s.level))
1238
- throw new c("validation_failed", `level must be one of ${Nt.join(", ")}`);
1252
+ if (!Ot.includes(s.level))
1253
+ throw new c("validation_failed", `level must be one of ${Ot.join(", ")}`);
1239
1254
  if (typeof s.message != "string" || s.message.length === 0)
1240
1255
  throw new c("validation_failed", "message is required");
1241
1256
  if (s.message.length > 4e3)
1242
1257
  throw new c("validation_failed", "message max 4000 chars");
1243
- if (n.env === "dev")
1244
- return gr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1258
+ if (W(n.env))
1259
+ return wr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1245
1260
  let a = {
1246
1261
  level: s.level,
1247
1262
  message: s.message
@@ -1277,22 +1292,22 @@ function Ot(n) {
1277
1292
  }
1278
1293
 
1279
1294
  // src/usage.ts
1280
- I();
1281
- M();
1295
+ C();
1296
+ F();
1282
1297
 
1283
1298
  // src/validators.ts
1284
- I();
1285
- var Lt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1299
+ C();
1300
+ var Mt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1286
1301
  function N(n, e) {
1287
- if (typeof e != "string" || !Lt.test(e))
1302
+ if (typeof e != "string" || !Mt.test(e))
1288
1303
  throw new c(
1289
1304
  "validation_failed",
1290
- `${n} must match ${Lt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1305
+ `${n} must match ${Mt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1291
1306
  );
1292
1307
  }
1293
1308
 
1294
1309
  // src/usage.ts
1295
- function Ut(n) {
1310
+ function qt(n) {
1296
1311
  return {
1297
1312
  /**
1298
1313
  * Reporta consumo metered de um resource. Hit no endpoint canônico
@@ -1380,10 +1395,10 @@ function Ut(n) {
1380
1395
  }
1381
1396
 
1382
1397
  // src/support.ts
1383
- I();
1384
- M();
1385
- var je = ["low", "normal", "high", "urgent"], br = ["open", "pending", "resolved", "closed"], Mt = 50;
1386
- function qt(n) {
1398
+ C();
1399
+ F();
1400
+ var We = ["low", "normal", "high", "urgent"], Tr = ["open", "pending", "resolved", "closed"], Ft = 50;
1401
+ function jt(n) {
1387
1402
  if (!n || typeof n != "object")
1388
1403
  throw new c("invalid_response", "Ticket response is not an object");
1389
1404
  let e = n;
@@ -1394,8 +1409,8 @@ function qt(n) {
1394
1409
  id: e.id,
1395
1410
  subject: typeof e.subject == "string" ? e.subject : "",
1396
1411
  message: typeof e.message == "string" ? e.message : "",
1397
- severity: je.includes(e.severity) ? e.severity : "normal",
1398
- status: br.includes(e.status) ? e.status : "open",
1412
+ severity: We.includes(e.severity) ? e.severity : "normal",
1413
+ status: Tr.includes(e.status) ? e.status : "open",
1399
1414
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
1400
1415
  updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : void 0,
1401
1416
  productSlug: typeof e.productId == "string" ? e.productId : typeof e.productSlug == "string" ? e.productSlug : void 0,
@@ -1413,15 +1428,15 @@ function qt(n) {
1413
1428
  satisfactionComment: typeof e.satisfactionComment == "string" ? e.satisfactionComment : null
1414
1429
  };
1415
1430
  }
1416
- function de(n) {
1431
+ function ue(n) {
1417
1432
  if (!n || typeof n != "string")
1418
1433
  throw new c("validation_failed", "ticketId is required");
1419
1434
  }
1420
- function Ft(n) {
1435
+ function $t(n) {
1421
1436
  if (typeof n == "string" && n.length > 2e3)
1422
1437
  throw new c("validation_failed", "comment max 2000 chars");
1423
1438
  }
1424
- function jt(n, ...e) {
1439
+ function Wt(n, ...e) {
1425
1440
  for (let t of e)
1426
1441
  if (typeof t == "string" && t.length > 0)
1427
1442
  return N("productSlug", t), t;
@@ -1432,20 +1447,20 @@ function jt(n, ...e) {
1432
1447
  "productId required (pass to input.productSlug or set on createNeetruClient)"
1433
1448
  );
1434
1449
  }
1435
- var vr = "X-Neetru-End-User-Token", wr = "Esta opera\xE7\xE3o de suporte exige um usu\xE1rio final logado: o Core s\xF3 mostra/altera os tickets do pr\xF3prio usu\xE1rio (header X-Neetru-End-User-Token com o id_token OIDC). Fa\xE7a login com client.auth.signIn() e tente de novo.", kr = "O Core exige a identidade do usu\xE1rio final para esta opera\xE7\xE3o (403 end_user_token_required) e nenhum id_token foi aceito. Fa\xE7a login com client.auth.signIn() e tente de novo.", Sr = "O Core recusou o token do usu\xE1rio final (401 invalid_end_user_token \u2014 sess\xE3o expirada, usu\xE1rio inativo ou token que n\xE3o \xE9 id_token) e a renova\xE7\xE3o autom\xE1tica n\xE3o resolveu. Fa\xE7a login novamente com client.auth.signIn() e tente de novo.", Tr = "O id_token do usu\xE1rio final foi emitido para o client OIDC de OUTRO produto (403 end_user_token_product_mismatch). Confira se o login (client.auth / clientId OIDC) e a apiKey/productId do createNeetruClient s\xE3o do MESMO produto.";
1436
- function $t(n) {
1437
- if (n instanceof c && !(n instanceof V)) {
1450
+ var Rr = "X-Neetru-End-User-Token", Ir = "Esta opera\xE7\xE3o de suporte exige um usu\xE1rio final logado: o Core s\xF3 mostra/altera os tickets do pr\xF3prio usu\xE1rio (header X-Neetru-End-User-Token com o id_token OIDC). Fa\xE7a login com client.auth.signIn() e tente de novo.", Cr = "O Core exige a identidade do usu\xE1rio final para esta opera\xE7\xE3o (403 end_user_token_required) e nenhum id_token foi aceito. Fa\xE7a login com client.auth.signIn() e tente de novo.", Ar = "O Core recusou o token do usu\xE1rio final (401 invalid_end_user_token \u2014 sess\xE3o expirada, usu\xE1rio inativo ou token que n\xE3o \xE9 id_token) e a renova\xE7\xE3o autom\xE1tica n\xE3o resolveu. Fa\xE7a login novamente com client.auth.signIn() e tente de novo.", Er = "O id_token do usu\xE1rio final foi emitido para o client OIDC de OUTRO produto (403 end_user_token_product_mismatch). Confira se o login (client.auth / clientId OIDC) e a apiKey/productId do createNeetruClient s\xE3o do MESMO produto.";
1451
+ function Bt(n) {
1452
+ if (n instanceof c && !(n instanceof K)) {
1438
1453
  if (n.code === "end_user_token_required")
1439
- throw new V(
1440
- kr,
1454
+ throw new K(
1455
+ Cr,
1441
1456
  "end_user_token_required",
1442
1457
  n.status,
1443
1458
  n.requestId,
1444
1459
  n.correlationId
1445
1460
  );
1446
1461
  if (n.code === "invalid_end_user_token")
1447
- throw new V(
1448
- Sr,
1462
+ throw new K(
1463
+ Ar,
1449
1464
  "invalid_end_user_token",
1450
1465
  n.status,
1451
1466
  n.requestId,
@@ -1454,7 +1469,7 @@ function $t(n) {
1454
1469
  if (n.code === "end_user_token_product_mismatch")
1455
1470
  throw new c(
1456
1471
  "forbidden",
1457
- Tr,
1472
+ Er,
1458
1473
  n.status,
1459
1474
  n.requestId,
1460
1475
  "end_user_token_product_mismatch",
@@ -1463,10 +1478,10 @@ function $t(n) {
1463
1478
  }
1464
1479
  throw n;
1465
1480
  }
1466
- function Rr(n) {
1481
+ function Pr(n) {
1467
1482
  return n instanceof c && n.code === "invalid_end_user_token";
1468
1483
  }
1469
- function Wt(n, e = {}) {
1484
+ function Vt(n, e = {}) {
1470
1485
  async function t() {
1471
1486
  try {
1472
1487
  let a = await e.getEndUserToken?.();
@@ -1484,25 +1499,25 @@ function Wt(n, e = {}) {
1484
1499
  }
1485
1500
  }
1486
1501
  function o(a) {
1487
- return a ? { [vr]: a } : {};
1502
+ return a ? { [Rr]: a } : {};
1488
1503
  }
1489
1504
  async function i(a, l) {
1490
1505
  let d = await t();
1491
1506
  if (!d && a && await r() && (d = await t()), !d && a)
1492
- throw new V(wr, "no_signed_in_user");
1507
+ throw new K(Ir, "no_signed_in_user");
1493
1508
  try {
1494
1509
  return await l(o(d));
1495
1510
  } catch (u) {
1496
- if (d && Rr(u) && await r()) {
1511
+ if (d && Pr(u) && await r()) {
1497
1512
  let p = await t();
1498
1513
  if (p)
1499
1514
  try {
1500
1515
  return await l(o(p));
1501
1516
  } catch (f) {
1502
- $t(f);
1517
+ Bt(f);
1503
1518
  }
1504
1519
  }
1505
- $t(u);
1520
+ Bt(u);
1506
1521
  }
1507
1522
  }
1508
1523
  async function s(a, l = {}) {
@@ -1535,13 +1550,13 @@ function Wt(n, e = {}) {
1535
1550
  throw new c("validation_failed", "message is required");
1536
1551
  if (a.message.length > 1e4)
1537
1552
  throw new c("validation_failed", "message max 10000 chars");
1538
- if (a.severity && !je.includes(a.severity))
1553
+ if (a.severity && !We.includes(a.severity))
1539
1554
  throw new c(
1540
1555
  "validation_failed",
1541
- `severity must be one of ${je.join(", ")}`
1556
+ `severity must be one of ${We.join(", ")}`
1542
1557
  );
1543
1558
  let d = {
1544
- productId: jt(n, a.productSlug),
1559
+ productId: Wt(n, a.productSlug),
1545
1560
  subject: a.subject,
1546
1561
  message: a.message,
1547
1562
  severity: a.severity ?? "normal"
@@ -1558,7 +1573,7 @@ function Wt(n, e = {}) {
1558
1573
  headers: f
1559
1574
  })
1560
1575
  ), p = u && typeof u == "object" && "ticket" in u ? u.ticket : u;
1561
- return qt(p);
1576
+ return jt(p);
1562
1577
  },
1563
1578
  /**
1564
1579
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
@@ -1566,11 +1581,11 @@ function Wt(n, e = {}) {
1566
1581
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
1567
1582
  */
1568
1583
  async listMyTickets(a) {
1569
- let l = jt(n, a?.productSlug), d = a?.limit;
1570
- if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Mt))
1584
+ let l = Wt(n, a?.productSlug), d = a?.limit;
1585
+ if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Ft))
1571
1586
  throw new c(
1572
1587
  "validation_failed",
1573
- `limit must be an integer 1-${Mt} (Core default 20)`
1588
+ `limit must be an integer 1-${Ft} (Core default 20)`
1574
1589
  );
1575
1590
  let u = await i(
1576
1591
  true,
@@ -1582,7 +1597,7 @@ function Wt(n, e = {}) {
1582
1597
  headers: f
1583
1598
  })
1584
1599
  );
1585
- return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(qt);
1600
+ return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(jt);
1586
1601
  },
1587
1602
  /**
1588
1603
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
@@ -1590,7 +1605,7 @@ function Wt(n, e = {}) {
1590
1605
  * `POST /api/sdk/v1/support/tickets/{id}/resolved-seen`.
1591
1606
  */
1592
1607
  async markResolvedSeen(a) {
1593
- de(a), await s(
1608
+ ue(a), await s(
1594
1609
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/resolved-seen`
1595
1610
  );
1596
1611
  },
@@ -1601,7 +1616,7 @@ function Wt(n, e = {}) {
1601
1616
  * `POST /api/sdk/v1/support/tickets/{id}/satisfaction-attempt`.
1602
1617
  */
1603
1618
  async recordSatisfactionAttempt(a) {
1604
- de(a), await s(
1619
+ ue(a), await s(
1605
1620
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/satisfaction-attempt`,
1606
1621
  // Incrementa satisfactionAttempts += 1 no Core — sem idempotencyKey,
1607
1622
  // um retry de rede infla o contador (mesmo padrão de createTicket acima).
@@ -1615,9 +1630,9 @@ function Wt(n, e = {}) {
1615
1630
  async submitSatisfaction(a) {
1616
1631
  if (!a || typeof a != "object")
1617
1632
  throw new c("validation_failed", "input is required");
1618
- if (de(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1633
+ if (ue(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1619
1634
  throw new c("validation_failed", "rating must be an integer 1-5 or null");
1620
- Ft(a.comment), await s(
1635
+ $t(a.comment), await s(
1621
1636
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a.ticketId)}/satisfaction`,
1622
1637
  {
1623
1638
  body: {
@@ -1634,7 +1649,7 @@ function Wt(n, e = {}) {
1634
1649
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
1635
1650
  */
1636
1651
  async contestTicket(a, l) {
1637
- de(a), Ft(l?.comment), await s(
1652
+ ue(a), $t(l?.comment), await s(
1638
1653
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/contest`,
1639
1654
  { body: { comment: l?.comment ?? void 0 } }
1640
1655
  );
@@ -1643,14 +1658,14 @@ function Wt(n, e = {}) {
1643
1658
  }
1644
1659
 
1645
1660
  // src/db/client-db.ts
1646
- Z();
1661
+ ee();
1647
1662
 
1648
1663
  // src/db/offline/query-engine.ts
1649
- function Bt(n) {
1664
+ function Kt(n) {
1650
1665
  return n == null ? 0 : typeof n == "number" ? 1 : typeof n == "string" ? 2 : typeof n == "boolean" ? 3 : 4;
1651
1666
  }
1652
- function ee(n, e) {
1653
- let t = Bt(n), r = Bt(e);
1667
+ function te(n, e) {
1668
+ let t = Kt(n), r = Kt(e);
1654
1669
  if (t !== r) return t - r;
1655
1670
  if (n == null) return 0;
1656
1671
  if (typeof n == "number" && typeof e == "number") return n - e;
@@ -1659,7 +1674,7 @@ function ee(n, e) {
1659
1674
  let o = String(n), i = String(e);
1660
1675
  return o < i ? -1 : o > i ? 1 : 0;
1661
1676
  }
1662
- function $e(n, e) {
1677
+ function Be(n, e) {
1663
1678
  let t = e.split("."), r = n;
1664
1679
  for (let o of t) {
1665
1680
  if (r == null || typeof r != "object")
@@ -1668,8 +1683,8 @@ function $e(n, e) {
1668
1683
  }
1669
1684
  return r;
1670
1685
  }
1671
- function Cr(n, e) {
1672
- let t = $e(n, e.field);
1686
+ function Nr(n, e) {
1687
+ let t = Be(n, e.field);
1673
1688
  if (t === void 0) return false;
1674
1689
  let { op: r, value: o } = e;
1675
1690
  switch (r) {
@@ -1678,13 +1693,13 @@ function Cr(n, e) {
1678
1693
  case "!=":
1679
1694
  return t !== o;
1680
1695
  case "<":
1681
- return ee(t, o) < 0;
1696
+ return te(t, o) < 0;
1682
1697
  case "<=":
1683
- return ee(t, o) <= 0;
1698
+ return te(t, o) <= 0;
1684
1699
  case ">":
1685
- return ee(t, o) > 0;
1700
+ return te(t, o) > 0;
1686
1701
  case ">=":
1687
- return ee(t, o) >= 0;
1702
+ return te(t, o) >= 0;
1688
1703
  case "array-contains":
1689
1704
  return Array.isArray(t) && t.includes(o);
1690
1705
  case "in":
@@ -1699,24 +1714,24 @@ function Cr(n, e) {
1699
1714
  );
1700
1715
  }
1701
1716
  }
1702
- function Ar(n, e) {
1703
- return e.every((t) => Cr(n, t));
1717
+ function xr(n, e) {
1718
+ return e.every((t) => Nr(n, t));
1704
1719
  }
1705
- function Er(n) {
1720
+ function Or(n) {
1706
1721
  return (e, t) => {
1707
1722
  if (n) {
1708
- let r = $e(e.data, n.field), o = $e(t.data, n.field), i = ee(r, o);
1723
+ let r = Be(e.data, n.field), o = Be(t.data, n.field), i = te(r, o);
1709
1724
  if (i !== 0)
1710
1725
  return n.direction === "desc" ? -i : i;
1711
1726
  }
1712
1727
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
1713
1728
  };
1714
1729
  }
1715
- function Pr(n, e) {
1730
+ function Lr(n, e) {
1716
1731
  let t = n.findIndex((r) => r.id === e.docId);
1717
1732
  return t === -1 ? n : e.type === "startAfter" ? n.slice(t + 1) : n.slice(0, t);
1718
1733
  }
1719
- var z = class n {
1734
+ var H = class n {
1720
1735
  /**
1721
1736
  * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
1722
1737
  *
@@ -1730,9 +1745,9 @@ var z = class n {
1730
1745
  evaluate(e, t) {
1731
1746
  let r = e.filter((u) => !u.meta.deleted), o = t.where ?? [];
1732
1747
  o.length > 0 && (r = r.filter(
1733
- (u) => Ar(u.data, o)
1748
+ (u) => xr(u.data, o)
1734
1749
  ));
1735
- let i = Er(t.orderBy), s = [...r].sort(i), a = t.cursor ? Pr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1750
+ let i = Or(t.orderBy), s = [...r].sort(i), a = t.cursor ? Lr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1736
1751
  return {
1737
1752
  docs: a.slice(0, l).map((u) => ({ id: u.id, data: u.data })),
1738
1753
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
@@ -1752,7 +1767,7 @@ var z = class n {
1752
1767
  };
1753
1768
 
1754
1769
  // src/db/offline/local-store.ts
1755
- var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_meta", H = "conflict_log", pe = class {
1770
+ var Mr = 1, B = "documents", V = "mutations", ne = "query_cache", pe = "sync_meta", Q = "conflict_log", fe = class {
1756
1771
  db = null;
1757
1772
  dbName;
1758
1773
  constructor(e) {
@@ -1764,22 +1779,22 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1764
1779
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
1765
1780
  */
1766
1781
  async open() {
1767
- this.db === null && (this.db = await openDB(this.dbName, Nr, {
1782
+ this.db === null && (this.db = await openDB(this.dbName, Mr, {
1768
1783
  upgrade(e) {
1769
- if (!e.objectStoreNames.contains(W)) {
1770
- let t = e.createObjectStore(W, {
1784
+ if (!e.objectStoreNames.contains(B)) {
1785
+ let t = e.createObjectStore(B, {
1771
1786
  keyPath: ["collection", "id"]
1772
1787
  });
1773
1788
  t.createIndex("by_collection", "collection"), t.createIndex("by_collection_state", ["collection", "meta.state"]), t.createIndex("by_updatedAtServer", "meta.updatedAtServer");
1774
1789
  }
1775
- if (!e.objectStoreNames.contains(B)) {
1776
- let t = e.createObjectStore(B, {
1790
+ if (!e.objectStoreNames.contains(V)) {
1791
+ let t = e.createObjectStore(V, {
1777
1792
  keyPath: "mutationId"
1778
1793
  });
1779
1794
  t.createIndex("by_seq", "seq"), t.createIndex("by_status", "status"), t.createIndex("by_doc", ["collection", "docId"]), t.createIndex("by_batch", "batchId");
1780
1795
  }
1781
- if (e.objectStoreNames.contains(te) || e.createObjectStore(te, { keyPath: "queryHash" }), e.objectStoreNames.contains(ue) || e.createObjectStore(ue, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1782
- let t = e.createObjectStore(H, {
1796
+ if (e.objectStoreNames.contains(ne) || e.createObjectStore(ne, { keyPath: "queryHash" }), e.objectStoreNames.contains(pe) || e.createObjectStore(pe, { keyPath: "key" }), !e.objectStoreNames.contains(Q)) {
1797
+ let t = e.createObjectStore(Q, {
1783
1798
  keyPath: "id",
1784
1799
  autoIncrement: true
1785
1800
  });
@@ -1821,14 +1836,14 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1821
1836
  * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
1822
1837
  */
1823
1838
  async getDoc(e, t) {
1824
- return await this.assertOpen().get(W, [e, t]) ?? null;
1839
+ return await this.assertOpen().get(B, [e, t]) ?? null;
1825
1840
  }
1826
1841
  /**
1827
1842
  * Insere ou atualiza um documento na store `documents`.
1828
1843
  * O documento é identificado pelo keyPath composto `[collection, id]`.
1829
1844
  */
1830
1845
  async putDoc(e) {
1831
- await this.assertOpen().put(W, e);
1846
+ await this.assertOpen().put(B, e);
1832
1847
  }
1833
1848
  /**
1834
1849
  * Marca um documento como tombstone (`deleted: true`).
@@ -1836,8 +1851,8 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1836
1851
  * No-op se o documento não existir.
1837
1852
  */
1838
1853
  async deleteDoc(e, t) {
1839
- let r = this.assertOpen(), o = await r.get(W, [e, t]);
1840
- o && await r.put(W, {
1854
+ let r = this.assertOpen(), o = await r.get(B, [e, t]);
1855
+ o && await r.put(B, {
1841
1856
  ...o,
1842
1857
  meta: {
1843
1858
  ...o.meta,
@@ -1853,8 +1868,8 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1853
1868
  * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
1854
1869
  */
1855
1870
  async listDocs(e, t) {
1856
- let o = await this.assertOpen().getAllFromIndex(W, "by_collection", e);
1857
- return z.evaluate(o, t);
1871
+ let o = await this.assertOpen().getAllFromIndex(B, "by_collection", e);
1872
+ return H.evaluate(o, t);
1858
1873
  }
1859
1874
  // ─── Sync meta (key-value) ──────────────────────────────────────────────────
1860
1875
  /**
@@ -1865,14 +1880,14 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1865
1880
  * 'lastFullResyncAt', 'leaderTabId'.
1866
1881
  */
1867
1882
  async getMeta(e) {
1868
- let r = await this.assertOpen().get(ue, e);
1883
+ let r = await this.assertOpen().get(pe, e);
1869
1884
  return r ? r.value : null;
1870
1885
  }
1871
1886
  /**
1872
1887
  * Armazena ou atualiza um valor na store `sync_meta`.
1873
1888
  */
1874
1889
  async setMeta(e, t) {
1875
- await this.assertOpen().put(ue, { key: e, value: t });
1890
+ await this.assertOpen().put(pe, { key: e, value: t });
1876
1891
  }
1877
1892
  // ─── Conflict log ───────────────────────────────────────────────────────────
1878
1893
  /**
@@ -1880,7 +1895,7 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1880
1895
  * O `id` é autoIncrement — não deve ser fornecido pelo chamador.
1881
1896
  */
1882
1897
  async appendConflict(e) {
1883
- let r = await this.assertOpen().add(H, e);
1898
+ let r = await this.assertOpen().add(Q, e);
1884
1899
  return { ...e, id: r };
1885
1900
  }
1886
1901
  /**
@@ -1888,15 +1903,15 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1888
1903
  * Filtra por `delivered` se a opção for fornecida.
1889
1904
  */
1890
1905
  async listConflicts(e) {
1891
- let r = await this.assertOpen().getAll(H);
1906
+ let r = await this.assertOpen().getAll(Q);
1892
1907
  return e?.delivered !== void 0 ? r.filter((o) => o.delivered === e.delivered) : r;
1893
1908
  }
1894
1909
  /**
1895
1910
  * Marca um registro do `conflict_log` como entregue ao produto.
1896
1911
  */
1897
1912
  async markConflictDelivered(e) {
1898
- let t = this.assertOpen(), r = await t.get(H, e);
1899
- r && await t.put(H, { ...r, delivered: true });
1913
+ let t = this.assertOpen(), r = await t.get(Q, e);
1914
+ r && await t.put(Q, { ...r, delivered: true });
1900
1915
  }
1901
1916
  // ─── Mutations (acessores usados pelo MutationQueue) ────────────────────────
1902
1917
  /**
@@ -1904,13 +1919,13 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1904
1919
  * Key: `mutationId`.
1905
1920
  */
1906
1921
  async putMutation(e) {
1907
- await this.assertOpen().put(B, e);
1922
+ await this.assertOpen().put(V, e);
1908
1923
  }
1909
1924
  /**
1910
1925
  * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
1911
1926
  */
1912
1927
  async getMutation(e) {
1913
- return await this.assertOpen().get(B, e) ?? null;
1928
+ return await this.assertOpen().get(V, e) ?? null;
1914
1929
  }
1915
1930
  /**
1916
1931
  * Lista mutações com filtros opcionais.
@@ -1918,14 +1933,14 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1918
1933
  */
1919
1934
  async listMutations(e) {
1920
1935
  let t = this.assertOpen(), r;
1921
- return e?.status !== void 0 ? r = await t.getAllFromIndex(B, "by_status", e.status) : e?.collection !== void 0 && e.docId !== void 0 ? r = await t.getAllFromIndex(B, "by_doc", [e.collection, e.docId]) : r = await t.getAllFromIndex(B, "by_seq"), r.sort((o, i) => o.seq - i.seq);
1936
+ return e?.status !== void 0 ? r = await t.getAllFromIndex(V, "by_status", e.status) : e?.collection !== void 0 && e.docId !== void 0 ? r = await t.getAllFromIndex(V, "by_doc", [e.collection, e.docId]) : r = await t.getAllFromIndex(V, "by_seq"), r.sort((o, i) => o.seq - i.seq);
1922
1937
  }
1923
1938
  /**
1924
1939
  * Remove uma mutação pelo `mutationId`.
1925
1940
  * No-op se não existir.
1926
1941
  */
1927
1942
  async deleteMutation(e) {
1928
- await this.assertOpen().delete(B, e);
1943
+ await this.assertOpen().delete(V, e);
1929
1944
  }
1930
1945
  // ─── Collection discovery ────────────────────────────────────────────────────
1931
1946
  /**
@@ -1938,7 +1953,7 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1938
1953
  * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
1939
1954
  */
1940
1955
  async listCollections() {
1941
- let t = await this.assertOpen().getAllFromIndex(W, "by_collection"), r = /* @__PURE__ */ new Set();
1956
+ let t = await this.assertOpen().getAllFromIndex(B, "by_collection"), r = /* @__PURE__ */ new Set();
1942
1957
  for (let o of t)
1943
1958
  r.add(o.collection);
1944
1959
  return Array.from(r);
@@ -1948,24 +1963,24 @@ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_met
1948
1963
  * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
1949
1964
  */
1950
1965
  async getQueryCache(e) {
1951
- return await this.assertOpen().get(te, e) ?? null;
1966
+ return await this.assertOpen().get(ne, e) ?? null;
1952
1967
  }
1953
1968
  /**
1954
1969
  * Insere ou atualiza uma entrada de `query_cache`.
1955
1970
  */
1956
1971
  async putQueryCache(e) {
1957
- await this.assertOpen().put(te, e);
1972
+ await this.assertOpen().put(ne, e);
1958
1973
  }
1959
1974
  /**
1960
1975
  * Remove uma entrada de `query_cache` pelo queryHash.
1961
1976
  */
1962
1977
  async deleteQueryCache(e) {
1963
- await this.assertOpen().delete(te, e);
1978
+ await this.assertOpen().delete(ne, e);
1964
1979
  }
1965
1980
  };
1966
1981
 
1967
1982
  // src/db/offline/memory-store.ts
1968
- var fe = class {
1983
+ var me = class {
1969
1984
  // store `documents` — key: `${collection}\0${id}`
1970
1985
  _docs = /* @__PURE__ */ new Map();
1971
1986
  // store `mutations` — key: mutationId
@@ -2013,7 +2028,7 @@ var fe = class {
2013
2028
  let r = Array.from(this._docs.values()).filter(
2014
2029
  (o) => o.collection === e
2015
2030
  );
2016
- return z.evaluate(r, t);
2031
+ return H.evaluate(r, t);
2017
2032
  }
2018
2033
  // ─── Sync meta ──────────────────────────────────────────────────────────────
2019
2034
  async getMeta(e) {
@@ -2070,13 +2085,13 @@ var fe = class {
2070
2085
  };
2071
2086
 
2072
2087
  // src/db/offline/mutation-queue.ts
2073
- function We() {
2088
+ function Ve() {
2074
2089
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (n) => {
2075
2090
  let e = Math.random() * 16 | 0;
2076
2091
  return (n === "x" ? e : e & 3 | 8).toString(16);
2077
2092
  });
2078
2093
  }
2079
- var me = class {
2094
+ var he = class {
2080
2095
  store;
2081
2096
  /**
2082
2097
  * Ponteiro de sequência local.
@@ -2172,7 +2187,7 @@ var me = class {
2172
2187
  * Atômico: a persistência final é uma única operação putMutation.
2173
2188
  */
2174
2189
  async enqueue(e) {
2175
- let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? We() : "");
2190
+ let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? Ve() : "");
2176
2191
  await this.syncSeq();
2177
2192
  let u = (await this.store.listMutations({ collection: t, docId: l })).filter((h) => h.status === "queued").sort((h, y) => y.seq - h.seq)[0];
2178
2193
  if (u !== void 0) {
@@ -2181,7 +2196,7 @@ var me = class {
2181
2196
  if ("removed" in h)
2182
2197
  return await this.store.deleteMutation(u.mutationId), {
2183
2198
  seq: u.seq,
2184
- mutationId: We(),
2199
+ mutationId: Ve(),
2185
2200
  collection: t,
2186
2201
  docId: l,
2187
2202
  op: "remove",
@@ -2199,7 +2214,7 @@ var me = class {
2199
2214
  }
2200
2215
  let f = {
2201
2216
  seq: this.nextSeq(),
2202
- mutationId: We(),
2217
+ mutationId: Ve(),
2203
2218
  collection: t,
2204
2219
  docId: l,
2205
2220
  op: r,
@@ -2312,45 +2327,45 @@ var me = class {
2312
2327
  };
2313
2328
 
2314
2329
  // src/db/field-value.ts
2315
- var Vt = "__neetru__";
2316
- function Q(n) {
2317
- return typeof n == "object" && n !== null && Vt in n && typeof n[Vt] == "string";
2330
+ var zt = "__neetru__";
2331
+ function G(n) {
2332
+ return typeof n == "object" && n !== null && zt in n && typeof n[zt] == "string";
2318
2333
  }
2319
- function xr(n) {
2320
- return Q(n) && n.__neetru__ === "serverTimestamp";
2334
+ function qr(n) {
2335
+ return G(n) && n.__neetru__ === "serverTimestamp";
2321
2336
  }
2322
- function Or(n) {
2323
- return Q(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2337
+ function Fr(n) {
2338
+ return G(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2324
2339
  }
2325
- function Lr(n, e) {
2326
- return xr(n) ? Date.now() : Or(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2340
+ function jr(n, e) {
2341
+ return qr(n) ? Date.now() : Fr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2327
2342
  }
2328
- function K(n, e) {
2343
+ function z(n, e) {
2329
2344
  let t = false, r = {};
2330
2345
  for (let [o, i] of Object.entries(n))
2331
- Q(i) ? (t = true, r[o] = Lr(i, e?.[o])) : r[o] = i;
2346
+ G(i) ? (t = true, r[o] = jr(i, e?.[o])) : r[o] = i;
2332
2347
  return t ? r : n;
2333
2348
  }
2334
- function Be(n) {
2349
+ function Ke(n) {
2335
2350
  for (let e of Object.values(n))
2336
- if (Q(e)) return true;
2351
+ if (G(e)) return true;
2337
2352
  return false;
2338
2353
  }
2339
2354
 
2340
2355
  // src/db/offline/sync-engine.ts
2341
- var Ur = 8, Mr = 1e3, qr = 300 * 1e3, Ve = "truncatedCollections";
2342
- function Fr(n) {
2343
- return n !== null && Be(n);
2356
+ var $r = 8, Wr = 1e3, Br = 300 * 1e3, ze = "truncatedCollections";
2357
+ function Vr(n) {
2358
+ return n !== null && Ke(n);
2344
2359
  }
2345
- function jr(n) {
2360
+ function Kr(n) {
2346
2361
  if (n === null) return null;
2347
- if (!Be(n)) return n;
2362
+ if (!Ke(n)) return n;
2348
2363
  let e = {};
2349
2364
  for (let [t, r] of Object.entries(n))
2350
- Q(r) || (e[t] = r);
2365
+ G(r) || (e[t] = r);
2351
2366
  return e;
2352
2367
  }
2353
- var he = class {
2368
+ var ge = class {
2354
2369
  _store;
2355
2370
  _queue;
2356
2371
  _resolver;
@@ -2544,13 +2559,13 @@ var he = class {
2544
2559
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
2545
2560
  return;
2546
2561
  }
2547
- let d = jr(i.payload) ?? a?.data ?? {}, u = {
2562
+ let d = Kr(i.payload) ?? a?.data ?? {}, u = {
2548
2563
  collection: e,
2549
2564
  id: t,
2550
2565
  data: i.op === "update" ? { ...a?.data ?? {}, ...d } : (
2551
2566
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2552
2567
  // é a fonte de verdade até o pull; senão usa o payload literal.
2553
- Fr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2568
+ Vr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2554
2569
  ),
2555
2570
  meta: {
2556
2571
  serverVersion: r,
@@ -2703,7 +2718,7 @@ var he = class {
2703
2718
  * pending do doc no cache + registra `lastError`/dispara `onError`.
2704
2719
  */
2705
2720
  async _retryOrDeadLetter(e, t, r) {
2706
- if (e.attempts + 1 < Ur) {
2721
+ if (e.attempts + 1 < $r) {
2707
2722
  await this._queue.markRetry(e.mutationId, t);
2708
2723
  return;
2709
2724
  }
@@ -2744,7 +2759,7 @@ var he = class {
2744
2759
  }
2745
2760
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
2746
2761
  _backoffDelayMs(e) {
2747
- return Math.min(Mr * 2 ** (e - 1), qr);
2762
+ return Math.min(Wr * 2 ** (e - 1), Br);
2748
2763
  }
2749
2764
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
2750
2765
  /**
@@ -2777,7 +2792,7 @@ var he = class {
2777
2792
  let r = [];
2778
2793
  await this._applyServerDocs(t.docs, r, true);
2779
2794
  let o = t.truncatedCollections ?? [], i = new Set(o);
2780
- await this._store.setMeta(Ve, o);
2795
+ await this._store.setMeta(ze, o);
2781
2796
  let s = new Set(
2782
2797
  t.docs.map((a) => `${a.collection}::${a.id}`)
2783
2798
  );
@@ -2996,10 +3011,10 @@ var he = class {
2996
3011
  };
2997
3012
 
2998
3013
  // src/db/offline/conflict-resolver.ts
2999
- function Kt(n, e) {
3014
+ function Ht(n, e) {
3000
3015
  return e === null ? false : n === null ? true : e > n;
3001
3016
  }
3002
- var ge = class n {
3017
+ var ye = class n {
3003
3018
  /**
3004
3019
  * Resolve um conflito com base na operação da mutação (auto-dispatch).
3005
3020
  *
@@ -3033,7 +3048,7 @@ var ge = class n {
3033
3048
  resolvedData: t.data,
3034
3049
  conflictRecord: null
3035
3050
  };
3036
- if (!Kt(
3051
+ if (!Ht(
3037
3052
  e.meta.updatedAtServer,
3038
3053
  t.meta.updatedAtServer
3039
3054
  ))
@@ -3080,7 +3095,7 @@ var ge = class n {
3080
3095
  let i = t.data;
3081
3096
  if (e === null)
3082
3097
  return { outcome: "no_conflict", resolvedData: { ...i, ...r.payload ?? {} }, conflictRecord: null };
3083
- if (!Kt(
3098
+ if (!Ht(
3084
3099
  e.meta.updatedAtServer,
3085
3100
  t.meta.updatedAtServer
3086
3101
  ))
@@ -3158,10 +3173,10 @@ var ge = class n {
3158
3173
  };
3159
3174
 
3160
3175
  // src/db/offline/change-bus.ts
3161
- function $r(n) {
3176
+ function zr(n) {
3162
3177
  return `${n.collection}::${n.doc.id}`;
3163
3178
  }
3164
- var ye = class {
3179
+ var _e = class {
3165
3180
  /** Listeners filtrados por coleção. */
3166
3181
  _collectionListeners = /* @__PURE__ */ new Map();
3167
3182
  /** Listeners globais (todas as coleções). */
@@ -3206,7 +3221,7 @@ var ye = class {
3206
3221
  if (e.length === 0) return;
3207
3222
  let t = /* @__PURE__ */ new Map();
3208
3223
  for (let i of e)
3209
- t.set($r(i), i);
3224
+ t.set(zr(i), i);
3210
3225
  let r = Array.from(t.values()), o = /* @__PURE__ */ new Map();
3211
3226
  for (let i of r)
3212
3227
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
@@ -3245,7 +3260,7 @@ var ye = class {
3245
3260
  };
3246
3261
 
3247
3262
  // src/db/offline/connectivity-monitor.ts
3248
- var _e = class {
3263
+ var be = class {
3249
3264
  _state;
3250
3265
  _listeners = /* @__PURE__ */ new Set();
3251
3266
  _nav;
@@ -3347,7 +3362,7 @@ var _e = class {
3347
3362
  };
3348
3363
 
3349
3364
  // src/db/offline/tab-coordinator.ts
3350
- var ne = class {
3365
+ var re = class {
3351
3366
  _lockName;
3352
3367
  _channelName;
3353
3368
  _lockManager;
@@ -3524,26 +3539,26 @@ var ne = class {
3524
3539
  };
3525
3540
 
3526
3541
  // src/db/collection-ref.ts
3527
- Z();
3528
- function Wr() {
3542
+ ee();
3543
+ function Hr() {
3529
3544
  return typeof indexedDB > "u" || typeof window > "u";
3530
3545
  }
3531
- var zt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3532
- function Br(n) {
3533
- if (!zt.test(n))
3534
- throw new b(
3546
+ var Qt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3547
+ function Qr(n) {
3548
+ if (!Qt.test(n))
3549
+ throw new _(
3535
3550
  "db_invalid_query",
3536
- `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${zt}.`
3551
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${Qt}.`
3537
3552
  );
3538
3553
  }
3539
- function G(n, e = "id") {
3554
+ function J(n, e = "id") {
3540
3555
  if (!n || typeof n != "string" || n.trim() === "")
3541
- throw new b(
3556
+ throw new _(
3542
3557
  "db_invalid_query",
3543
3558
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
3544
3559
  );
3545
3560
  }
3546
- function Vr(n) {
3561
+ function Gr(n) {
3547
3562
  let e = {};
3548
3563
  if (n?.where && (e.where = n.where.map((t) => ({
3549
3564
  field: t.field,
@@ -3560,12 +3575,12 @@ function Vr(n) {
3560
3575
  }
3561
3576
  return e;
3562
3577
  }
3563
- function Kr(n, e) {
3578
+ function Jr(n, e) {
3564
3579
  if (n.length < e) return null;
3565
3580
  let t = n[n.length - 1];
3566
3581
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
3567
3582
  }
3568
- var Ke = class {
3583
+ var He = class {
3569
3584
  constructor(e, t, r, o, i, s) {
3570
3585
  this._collection = e;
3571
3586
  this._store = t;
@@ -3607,7 +3622,7 @@ var Ke = class {
3607
3622
  }
3608
3623
  /** Constrói um DbListResult para a coleção com query opcional. */
3609
3624
  async _buildListResult(e) {
3610
- let t = Vr(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), l = Kr(o.docs, r), d = await this._store.getMeta(Ve), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3625
+ let t = Gr(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), l = Jr(o.docs, r), d = await this._store.getMeta(ze), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3611
3626
  return {
3612
3627
  docs: o.docs.map((h) => ({ id: h.id, data: h.data })),
3613
3628
  nextCursor: l,
@@ -3620,13 +3635,13 @@ var Ke = class {
3620
3635
  }
3621
3636
  // ── CRUD ────────────────────────────────────────────────────────────────────
3622
3637
  async get(e) {
3623
- return G(e), this._buildGetResult(e);
3638
+ return J(e), this._buildGetResult(e);
3624
3639
  }
3625
3640
  async list(e) {
3626
3641
  return this._buildListResult(e);
3627
3642
  }
3628
3643
  async add(e) {
3629
- let t = e, r = K(t, void 0), o = await this._queue.enqueue({
3644
+ let t = e, r = z(t, void 0), o = await this._queue.enqueue({
3630
3645
  collection: this._collection,
3631
3646
  op: "add",
3632
3647
  payload: t,
@@ -3653,8 +3668,8 @@ var Ke = class {
3653
3668
  }]), { ok: true, id: i };
3654
3669
  }
3655
3670
  async set(e, t) {
3656
- G(e);
3657
- let r = await this._store.getDoc(this._collection, e), o = t, i = K(o, void 0), s = await this._queue.enqueue({
3671
+ J(e);
3672
+ let r = await this._store.getDoc(this._collection, e), o = t, i = z(o, void 0), s = await this._queue.enqueue({
3658
3673
  collection: this._collection,
3659
3674
  docId: e,
3660
3675
  op: "set",
@@ -3682,8 +3697,8 @@ var Ke = class {
3682
3697
  }]), { ok: true };
3683
3698
  }
3684
3699
  async update(e, t, r) {
3685
- G(e);
3686
- let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = K(i, s), l = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3700
+ J(e);
3701
+ let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = z(i, s), l = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3687
3702
  collection: this._collection,
3688
3703
  docId: e,
3689
3704
  op: "update",
@@ -3716,7 +3731,7 @@ var Ke = class {
3716
3731
  }]), { ok: true };
3717
3732
  }
3718
3733
  async remove(e) {
3719
- G(e);
3734
+ J(e);
3720
3735
  let t = await this._store.getDoc(this._collection, e);
3721
3736
  return !t || t.meta.deleted, await this._queue.enqueue({
3722
3737
  collection: this._collection,
@@ -3736,7 +3751,7 @@ var Ke = class {
3736
3751
  for (let o of e) {
3737
3752
  let i = this._collection;
3738
3753
  if (o.kind === "add") {
3739
- let s = o.data, a = K(s, void 0), l = await this._queue.enqueue({
3754
+ let s = o.data, a = z(s, void 0), l = await this._queue.enqueue({
3740
3755
  collection: i,
3741
3756
  op: "add",
3742
3757
  payload: s,
@@ -3758,7 +3773,7 @@ var Ke = class {
3758
3773
  }
3759
3774
  }), r.push({ type: "added", collection: i, doc: { id: d, data: a } });
3760
3775
  } else if (o.kind === "set") {
3761
- let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = K(a, void 0), u = await this._queue.enqueue({
3776
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = z(a, void 0), u = await this._queue.enqueue({
3762
3777
  collection: i,
3763
3778
  docId: s,
3764
3779
  op: "set",
@@ -3785,7 +3800,7 @@ var Ke = class {
3785
3800
  doc: { id: s, data: d }
3786
3801
  });
3787
3802
  } else if (o.kind === "update") {
3788
- let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = l?.meta.deleted ? void 0 : l?.data, u = K(a, d), p = { ...l?.data ?? {}, ...u }, f = await this._queue.enqueue({
3803
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = l?.meta.deleted ? void 0 : l?.data, u = z(a, d), p = { ...l?.data ?? {}, ...u }, f = await this._queue.enqueue({
3789
3804
  collection: i,
3790
3805
  docId: s,
3791
3806
  op: "update",
@@ -3828,7 +3843,7 @@ var Ke = class {
3828
3843
  }
3829
3844
  // ── Realtime ─────────────────────────────────────────────────────────────────
3830
3845
  onDoc(e, t) {
3831
- return G(e), this._buildGetResult(e).then((r) => {
3846
+ return J(e), this._buildGetResult(e).then((r) => {
3832
3847
  t(r ? r.docs[0]?.data ?? null : null);
3833
3848
  }).catch(() => t(null)), this._bus.subscribe(this._collection, (r) => {
3834
3849
  let o = r.find((i) => i.doc.id === e);
@@ -3887,7 +3902,7 @@ var Ke = class {
3887
3902
  };
3888
3903
  }
3889
3904
  doc(e) {
3890
- G(e);
3905
+ J(e);
3891
3906
  let t = this;
3892
3907
  return {
3893
3908
  get id() {
@@ -3940,7 +3955,7 @@ var Ke = class {
3940
3955
  }
3941
3956
  };
3942
3957
  }
3943
- }, ze = class {
3958
+ }, Qe = class {
3944
3959
  _store;
3945
3960
  _queue;
3946
3961
  _bus;
@@ -3950,7 +3965,7 @@ var Ke = class {
3950
3965
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3951
3966
  }
3952
3967
  collection(e) {
3953
- return Br(e), new Ke(
3968
+ return Qr(e), new He(
3954
3969
  e,
3955
3970
  this._store,
3956
3971
  this._queue,
@@ -3979,10 +3994,10 @@ var Ke = class {
3979
3994
  return this._engine.onError(e);
3980
3995
  }
3981
3996
  };
3982
- async function Ht(n) {
3983
- let e = Wr() ? new fe() : new pe(n.dbName);
3997
+ async function Gt(n) {
3998
+ let e = Hr() ? new me() : new fe(n.dbName);
3984
3999
  await e.open();
3985
- let t = new me(e), r = new ge(), o = new ye(), i = new _e({
4000
+ let t = new he(e), r = new ye(), o = new _e(), i = new be({
3986
4001
  // Se startOnline=false, injeta um navigator falso
3987
4002
  navigator: n.startOnline === false ? { onLine: false } : typeof navigator < "u" ? navigator : void 0
3988
4003
  }), s = n.singleTab ? (
@@ -3992,10 +4007,10 @@ async function Ht(n) {
3992
4007
  onRoleChange: (l) => () => {
3993
4008
  }
3994
4009
  }
3995
- ) : new ne({
4010
+ ) : new re({
3996
4011
  lockName: `neetru-offline:${n.dbName}`,
3997
4012
  channelName: `neetru-offline:${n.dbName}`
3998
- }), a = new he({
4013
+ }), a = new ge({
3999
4014
  store: e,
4000
4015
  queue: t,
4001
4016
  resolver: r,
@@ -4005,7 +4020,7 @@ async function Ht(n) {
4005
4020
  connectivity: i,
4006
4021
  periodicSyncIntervalMs: n.periodicSyncIntervalMs ?? 300 * 1e3
4007
4022
  });
4008
- return i.start(), !n.singleTab && s instanceof ne && s.start(), new ze({
4023
+ return i.start(), !n.singleTab && s instanceof re && s.start(), new Qe({
4009
4024
  store: e,
4010
4025
  queue: t,
4011
4026
  bus: o,
@@ -4015,11 +4030,11 @@ async function Ht(n) {
4015
4030
  }
4016
4031
 
4017
4032
  // src/db/realtime/realtime-client.ts
4018
- var zr = 0;
4019
- function Qt() {
4020
- return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++zr}-${Math.random().toString(36).slice(2)}`;
4033
+ var Xr = 0;
4034
+ function Jt() {
4035
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++Xr}-${Math.random().toString(36).slice(2)}`;
4021
4036
  }
4022
- var be = class {
4037
+ var ve = class {
4023
4038
  // ── configuração ──────────────────────────────────────────────────────────
4024
4039
  _gatewayUrl;
4025
4040
  _wsFactory;
@@ -4057,7 +4072,7 @@ var be = class {
4057
4072
  _pendingFrames = [];
4058
4073
  // ── construtor ────────────────────────────────────────────────────────────
4059
4074
  constructor(e) {
4060
- this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? Hr, this._setTimeout = e.setTimeoutFn ?? globalThis.setTimeout.bind(globalThis), this._clearTimeout = e.clearTimeoutFn ?? globalThis.clearTimeout.bind(globalThis), this._backoffBaseMs = e.backoffBaseMs ?? 1e3, this._backoffMaxMs = e.backoffMaxMs ?? 3e4, this._heartbeatIntervalMs = e.heartbeatIntervalMs ?? 25e3, this._ticketProvider = e.ticketProvider, this._dbId = e.dbId, this._connect();
4075
+ this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? Yr, this._setTimeout = e.setTimeoutFn ?? globalThis.setTimeout.bind(globalThis), this._clearTimeout = e.clearTimeoutFn ?? globalThis.clearTimeout.bind(globalThis), this._backoffBaseMs = e.backoffBaseMs ?? 1e3, this._backoffMaxMs = e.backoffMaxMs ?? 3e4, this._heartbeatIntervalMs = e.heartbeatIntervalMs ?? 25e3, this._ticketProvider = e.ticketProvider, this._dbId = e.dbId, this._connect();
4061
4076
  }
4062
4077
  // ── API pública ───────────────────────────────────────────────────────────
4063
4078
  /**
@@ -4071,8 +4086,8 @@ var be = class {
4071
4086
  */
4072
4087
  subscribe(e, t, r) {
4073
4088
  if (this._closed)
4074
- return Qt();
4075
- let o = Qt();
4089
+ return Jt();
4090
+ let o = Jt();
4076
4091
  this._subscriptions.set(o, {
4077
4092
  subscriptionId: o,
4078
4093
  collection: e,
@@ -4336,7 +4351,7 @@ var be = class {
4336
4351
  _detachHandlers(e) {
4337
4352
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
4338
4353
  }
4339
- }, Hr = (n) => {
4354
+ }, Yr = (n) => {
4340
4355
  if (typeof WebSocket > "u")
4341
4356
  throw new Error(
4342
4357
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -4345,46 +4360,46 @@ var be = class {
4345
4360
  };
4346
4361
 
4347
4362
  // src/db/client-db.ts
4348
- var so = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, we = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, an = 200;
4349
- function ao(n, e, t) {
4350
- return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? co(e.realtimeGatewayUrl, t, e) : ln(t);
4363
+ var po = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, ke = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, ln = 200;
4364
+ function fo(n, e, t) {
4365
+ return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? mo(e.realtimeGatewayUrl, t, e) : un(t);
4351
4366
  }
4352
- function ln(n) {
4367
+ function un(n) {
4353
4368
  return {
4354
4369
  async pushMutations(e) {
4355
4370
  if (!n)
4356
- throw new b(
4371
+ throw new _(
4357
4372
  "db_unavailable",
4358
4373
  "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
4359
4374
  );
4360
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4375
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4361
4376
  for (let s of e)
4362
4377
  try {
4363
4378
  let a;
4364
4379
  s.op === "add" ? a = await t(n, {
4365
4380
  method: "PUT",
4366
- path: we(s.collection, s.docId),
4381
+ path: ke(s.collection, s.docId),
4367
4382
  body: { data: s.payload ?? {} },
4368
4383
  requireAuth: !0,
4369
4384
  retries: 2,
4370
4385
  headers: i
4371
4386
  }) : s.op === "set" ? a = await t(n, {
4372
4387
  method: "PUT",
4373
- path: we(s.collection, s.docId),
4388
+ path: ke(s.collection, s.docId),
4374
4389
  body: { data: s.payload ?? {} },
4375
4390
  requireAuth: !0,
4376
4391
  retries: 2,
4377
4392
  headers: i
4378
4393
  }) : s.op === "update" ? a = await t(n, {
4379
4394
  method: "PATCH",
4380
- path: we(s.collection, s.docId),
4395
+ path: ke(s.collection, s.docId),
4381
4396
  body: { data: s.payload ?? {}, ...s.upsert ? { upsert: !0 } : {} },
4382
4397
  requireAuth: !0,
4383
4398
  retries: 2,
4384
4399
  headers: i
4385
4400
  }) : a = await t(n, {
4386
4401
  method: "DELETE",
4387
- path: we(s.collection, s.docId),
4402
+ path: ke(s.collection, s.docId),
4388
4403
  requireAuth: !0,
4389
4404
  retries: 2,
4390
4405
  headers: i
@@ -4410,7 +4425,7 @@ function ln(n) {
4410
4425
  continue;
4411
4426
  }
4412
4427
  if (r.length === 0)
4413
- throw new b("db_unavailable", `pushMutations falhou: ${l}`);
4428
+ throw new _("db_unavailable", `pushMutations falhou: ${l}`);
4414
4429
  break;
4415
4430
  }
4416
4431
  return { results: r };
@@ -4421,13 +4436,13 @@ function ln(n) {
4421
4436
  async fullResync(e) {
4422
4437
  if (!n)
4423
4438
  return { docs: [], newWatermark: Date.now() };
4424
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4439
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4425
4440
  for (let l of e) {
4426
4441
  let d;
4427
4442
  try {
4428
4443
  d = await t(n, {
4429
4444
  method: "GET",
4430
- path: so(l),
4445
+ path: po(l),
4431
4446
  requireAuth: !0,
4432
4447
  retries: 2,
4433
4448
  headers: o,
@@ -4435,37 +4450,37 @@ function ln(n) {
4435
4450
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
4436
4451
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
4437
4452
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
4438
- query: { limit: an }
4453
+ query: { limit: ln }
4439
4454
  });
4440
4455
  } catch (f) {
4441
4456
  let h = f instanceof Error ? f.message : String(f);
4442
- throw new b(
4457
+ throw new _(
4443
4458
  "db_unavailable",
4444
4459
  `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${h}`
4445
4460
  );
4446
4461
  }
4447
4462
  let u = d, p = Array.isArray(u?.items) ? u.items : [];
4448
- p.length >= an && a.push(l);
4463
+ p.length >= ln && a.push(l);
4449
4464
  for (let f of p) {
4450
4465
  if (!f || typeof f != "object") continue;
4451
4466
  let h = f, y = typeof h.id == "string" ? h.id : null;
4452
4467
  if (!y) continue;
4453
- let { id: S, ...x } = h, T = i, P = x._updatedAt;
4454
- if (typeof P == "number")
4455
- T = P;
4456
- else if (P !== null && typeof P == "object" && typeof P._seconds == "number")
4457
- T = P._seconds * 1e3;
4458
- else if (typeof P == "string") {
4459
- let m = Date.parse(P);
4460
- Number.isNaN(m) || (T = m);
4468
+ let { id: T, ...x } = h, R = i, E = x._updatedAt;
4469
+ if (typeof E == "number")
4470
+ R = E;
4471
+ else if (E !== null && typeof E == "object" && typeof E._seconds == "number")
4472
+ R = E._seconds * 1e3;
4473
+ else if (typeof E == "string") {
4474
+ let g = Date.parse(E);
4475
+ Number.isNaN(g) || (R = g);
4461
4476
  }
4462
- let q = `rest_${y}_${T}`;
4477
+ let j = `rest_${y}_${R}`;
4463
4478
  s.push({
4464
4479
  collection: l,
4465
4480
  id: y,
4466
4481
  data: x,
4467
- serverVersion: q,
4468
- serverTimestamp: T,
4482
+ serverVersion: j,
4483
+ serverTimestamp: R,
4469
4484
  deleted: false
4470
4485
  });
4471
4486
  }
@@ -4474,10 +4489,10 @@ function ln(n) {
4474
4489
  }
4475
4490
  };
4476
4491
  }
4477
- function co(n, e, t) {
4478
- let r = ln(e), o = new be({
4492
+ function mo(n, e, t) {
4493
+ let r = un(e), o = new ve({
4479
4494
  gatewayUrl: n,
4480
- ticketProvider: lo(e, t),
4495
+ ticketProvider: ho(e, t),
4481
4496
  dbId: t.dbId,
4482
4497
  webSocketFactory: t._wsFactory
4483
4498
  });
@@ -4513,9 +4528,9 @@ function co(n, e, t) {
4513
4528
  }
4514
4529
  };
4515
4530
  }
4516
- function lo(n, e) {
4531
+ function ho(n, e) {
4517
4532
  return async () => {
4518
- let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y));
4533
+ let { httpRequest: t } = await Promise.resolve().then(() => (F(), Z));
4519
4534
  return await t(n, {
4520
4535
  method: "POST",
4521
4536
  path: "/api/sdk/v1/db/realtime/ticket",
@@ -4528,21 +4543,21 @@ function lo(n, e) {
4528
4543
  });
4529
4544
  };
4530
4545
  }
4531
- var cn = false;
4532
- function uo(n, e) {
4533
- cn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (cn = true, console.warn(
4546
+ var dn = false;
4547
+ function go(n, e) {
4548
+ dn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (dn = true, console.warn(
4534
4549
  '[neetru/sdk] client.db recebeu `dbId` ("' + e.dbId + '") mas ele N\xC3O roteia nem escopa nada no servidor: as escritas do mundo Documentos (add/set/update/remove/list) SEMPRE caem no datastore gen\xE9rico do Core, escopado s\xF3 por tenant/produto (header x-neetru-tenant). `dbId` apenas nomeia o cache offline LOCAL (IndexedDB). ATEN\xC7\xC3O: usar dbIds distintos no MESMO tenant/produto N\xC3O isola os dados no servidor \u2014 eles se misturam (co-mingling). Veja o JSDoc de NeetruDbOptions.dbId.'
4535
4550
  )));
4536
4551
  }
4537
- function dn(n, e = {}) {
4538
- uo(n, e);
4552
+ function pn(n, e = {}) {
4553
+ go(n, e);
4539
4554
  let t;
4540
4555
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
4541
4556
  '[neetru/sdk] NeetruDbOptions.engine est\xE1 depreciado e ser\xE1 removido em v3.0. Use NeetruDbOptions.transport em vez de engine. Valores v\xE1lidos: "rest" | "firestore" | "nosql-vm". Nota: "engine" no SDK configura o TRANSPORTE (REST/Firestore/WebSocket), n\xE3o o storage engine do admin database (firestore-instance, cloud-sql-postgres, \u2026).'
4542
4557
  ), t = e.engine) : t = "rest";
4543
- let r = ao(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4558
+ let r = fo(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4544
4559
  function l() {
4545
- return s || (s = Ht({
4560
+ return s || (s = Gt({
4546
4561
  dbName: i,
4547
4562
  transport: r,
4548
4563
  singleTab: e.singleTab ?? n.env !== "prod"
@@ -4550,15 +4565,15 @@ function dn(n, e = {}) {
4550
4565
  }
4551
4566
  return {
4552
4567
  collection(d) {
4553
- return a ? a.collection(d) : po(d, l);
4568
+ return a ? a.collection(d) : yo(d, l);
4554
4569
  },
4555
4570
  async sql(d, u) {
4556
- if (n.env === "dev")
4557
- throw new b(
4571
+ if (W(n.env))
4572
+ throw new _(
4558
4573
  "db_unavailable",
4559
4574
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4560
4575
  );
4561
- return (await Promise.resolve().then(() => (sn(), on))).createSqlClientFromConfig(n, d, u);
4576
+ return (await Promise.resolve().then(() => (cn(), an))).createSqlClientFromConfig(n, d, u);
4562
4577
  },
4563
4578
  get syncState() {
4564
4579
  return a?.syncState ?? {
@@ -4597,7 +4612,7 @@ function dn(n, e = {}) {
4597
4612
  }
4598
4613
  };
4599
4614
  }
4600
- function po(n, e) {
4615
+ function yo(n, e) {
4601
4616
  async function t() {
4602
4617
  return (await e()).collection(n);
4603
4618
  }
@@ -4676,9 +4691,9 @@ function po(n, e) {
4676
4691
  }
4677
4692
 
4678
4693
  // src/checkout.ts
4679
- I();
4680
- M();
4681
- function Ye(n, e) {
4694
+ C();
4695
+ F();
4696
+ function et(n, e) {
4682
4697
  let t = n?.accessToken || n?.idToken;
4683
4698
  if (!t || typeof t != "string")
4684
4699
  throw new c(
@@ -4687,7 +4702,7 @@ function Ye(n, e) {
4687
4702
  );
4688
4703
  return { requireAuth: false, headers: { authorization: `Bearer ${t}` } };
4689
4704
  }
4690
- function fo(n) {
4705
+ function _o(n) {
4691
4706
  if (!n || typeof n != "object")
4692
4707
  throw new c("invalid_response", "checkout.start response is not an object");
4693
4708
  let e = n;
@@ -4703,7 +4718,7 @@ function fo(n) {
4703
4718
  requiresKyc: e.requiresKyc === true
4704
4719
  };
4705
4720
  }
4706
- function mo(n) {
4721
+ function bo(n) {
4707
4722
  if (!n || typeof n != "object")
4708
4723
  throw new c("invalid_response", "checkout.get response is not an object");
4709
4724
  let e = n, t = e.intent;
@@ -4725,20 +4740,20 @@ function mo(n) {
4725
4740
  isStale: e.isStale === true
4726
4741
  };
4727
4742
  }
4728
- function ho() {
4743
+ function vo() {
4729
4744
  try {
4730
4745
  return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
4731
4746
  } catch {
4732
4747
  return false;
4733
4748
  }
4734
4749
  }
4735
- function go(n) {
4750
+ function wo(n) {
4736
4751
  try {
4737
4752
  globalThis.location.assign(n);
4738
4753
  } catch {
4739
4754
  }
4740
4755
  }
4741
- function yo(n) {
4756
+ function ko(n) {
4742
4757
  return {
4743
4758
  async start(e) {
4744
4759
  if (!e?.productId)
@@ -4753,7 +4768,7 @@ function yo(n) {
4753
4768
  callbackUrl: e.callbackUrl
4754
4769
  };
4755
4770
  e.tenantType && (t.targetTenantType = e.tenantType), e.tenantId && (t.targetTenantId = e.tenantId);
4756
- let { requireAuth: r, headers: o } = Ye(
4771
+ let { requireAuth: r, headers: o } = et(
4757
4772
  { accessToken: e.accessToken, idToken: e.idToken },
4758
4773
  "start"
4759
4774
  ), i = await v(n, {
@@ -4763,13 +4778,13 @@ function yo(n) {
4763
4778
  requireAuth: r,
4764
4779
  headers: o,
4765
4780
  idempotencyKey: true
4766
- }), s = fo(i);
4767
- return e.autoRedirect !== false && ho() && go(s.redirectUrl), s;
4781
+ }), s = _o(i);
4782
+ return e.autoRedirect !== false && vo() && wo(s.redirectUrl), s;
4768
4783
  },
4769
4784
  async get(e, t) {
4770
4785
  if (!e || typeof e != "string")
4771
4786
  throw new c("validation_failed", "checkout.get: intentId is required");
4772
- let { requireAuth: r, headers: o } = Ye(
4787
+ let { requireAuth: r, headers: o } = et(
4773
4788
  { accessToken: t?.accessToken, idToken: t?.idToken },
4774
4789
  "get"
4775
4790
  ), i = await v(n, {
@@ -4778,12 +4793,12 @@ function yo(n) {
4778
4793
  requireAuth: r,
4779
4794
  headers: o
4780
4795
  });
4781
- return mo(i);
4796
+ return bo(i);
4782
4797
  },
4783
4798
  async cancel(e, t) {
4784
4799
  if (!e || typeof e != "string")
4785
4800
  throw new c("validation_failed", "checkout.cancel: intentId is required");
4786
- let { requireAuth: r, headers: o } = Ye(
4801
+ let { requireAuth: r, headers: o } = et(
4787
4802
  { accessToken: t?.accessToken, idToken: t?.idToken },
4788
4803
  "cancel"
4789
4804
  );
@@ -4799,7 +4814,7 @@ function yo(n) {
4799
4814
  }
4800
4815
  };
4801
4816
  }
4802
- var Ze = class {
4817
+ var tt = class {
4803
4818
  intents = /* @__PURE__ */ new Map();
4804
4819
  async start(e) {
4805
4820
  if (!e?.productId)
@@ -4842,14 +4857,14 @@ var Ze = class {
4842
4857
  return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
4843
4858
  }
4844
4859
  };
4845
- function un(n) {
4846
- return n.env === "dev" ? new Ze() : yo(n);
4860
+ function fn(n) {
4861
+ return W(n.env) ? new tt() : ko(n);
4847
4862
  }
4848
4863
 
4849
4864
  // src/webhooks.ts
4850
- I();
4851
- M();
4852
- var fn = [
4865
+ C();
4866
+ F();
4867
+ var hn = [
4853
4868
  "subscription.activated",
4854
4869
  "subscription.cancelled",
4855
4870
  "subscription.payment_failed",
@@ -4859,7 +4874,7 @@ var fn = [
4859
4874
  "account.reactivated",
4860
4875
  "support.ticket_replied"
4861
4876
  ];
4862
- function pn(n) {
4877
+ function mn(n) {
4863
4878
  if (!n || typeof n != "object")
4864
4879
  throw new c("invalid_response", "Webhook response is not an object");
4865
4880
  let e = n;
@@ -4869,7 +4884,7 @@ function pn(n) {
4869
4884
  id: e.id,
4870
4885
  url: typeof e.url == "string" ? e.url : "",
4871
4886
  events: Array.isArray(e.events) ? e.events.filter(
4872
- (t) => fn.includes(t)
4887
+ (t) => hn.includes(t)
4873
4888
  ) : [],
4874
4889
  hasSecret: e.hasSecret === true,
4875
4890
  status: e.status === "active" || e.status === "degraded" || e.status === "disabled" ? e.status : "active",
@@ -4878,7 +4893,7 @@ function pn(n) {
4878
4893
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString()
4879
4894
  };
4880
4895
  }
4881
- function mn(n) {
4896
+ function gn(n) {
4882
4897
  if (!n.url || typeof n.url != "string")
4883
4898
  throw new c("validation_failed", "url \xE9 obrigat\xF3ria");
4884
4899
  try {
@@ -4891,12 +4906,12 @@ function mn(n) {
4891
4906
  if (!Array.isArray(n.events) || n.events.length === 0)
4892
4907
  throw new c("validation_failed", "events deve ter pelo menos 1 evento");
4893
4908
  for (let e of n.events)
4894
- if (!fn.includes(e))
4909
+ if (!hn.includes(e))
4895
4910
  throw new c("validation_failed", `evento desconhecido: ${e}`);
4896
4911
  if (n.secret !== void 0 && n.secret.length < 16)
4897
4912
  throw new c("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4898
4913
  }
4899
- function ke(n, ...e) {
4914
+ function Se(n, ...e) {
4900
4915
  for (let t of e)
4901
4916
  if (typeof t == "string" && t.length > 0)
4902
4917
  return N("productId", t), t;
@@ -4907,11 +4922,11 @@ function ke(n, ...e) {
4907
4922
  "productId required (pass to options/input or set on createNeetruClient)"
4908
4923
  );
4909
4924
  }
4910
- function hn(n) {
4925
+ function yn(n) {
4911
4926
  return {
4912
4927
  async register(e) {
4913
- mn(e);
4914
- let t = ke(n, e.productId), r = await v(n, {
4928
+ gn(e);
4929
+ let t = Se(n, e.productId), r = await v(n, {
4915
4930
  method: "POST",
4916
4931
  path: "/api/sdk/v1/webhooks",
4917
4932
  body: {
@@ -4927,20 +4942,20 @@ function hn(n) {
4927
4942
  // dedup TTL 24h (mesmo padrão de usage.report/support.createTicket).
4928
4943
  idempotencyKey: true
4929
4944
  });
4930
- return pn(r);
4945
+ return mn(r);
4931
4946
  },
4932
4947
  async list(e) {
4933
- let t = ke(n, e?.productId), r = await v(n, {
4948
+ let t = Se(n, e?.productId), r = await v(n, {
4934
4949
  method: "GET",
4935
4950
  path: "/api/sdk/v1/webhooks",
4936
4951
  query: { productId: t },
4937
4952
  requireAuth: true
4938
4953
  });
4939
- return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(pn);
4954
+ return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(mn);
4940
4955
  },
4941
4956
  async unregister(e, t) {
4942
4957
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4943
- let r = ke(n, t?.productId);
4958
+ let r = Se(n, t?.productId);
4944
4959
  return await v(n, {
4945
4960
  method: "DELETE",
4946
4961
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}`,
@@ -4950,7 +4965,7 @@ function hn(n) {
4950
4965
  },
4951
4966
  async test(e, t) {
4952
4967
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4953
- let r = ke(n, t?.productId), o = await v(n, {
4968
+ let r = Se(n, t?.productId), o = await v(n, {
4954
4969
  method: "POST",
4955
4970
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}/test`,
4956
4971
  query: { productId: r },
@@ -4969,11 +4984,11 @@ function hn(n) {
4969
4984
  }
4970
4985
  };
4971
4986
  }
4972
- var Se = class {
4987
+ var Te = class {
4973
4988
  endpoints = /* @__PURE__ */ new Map();
4974
4989
  nextId = 1;
4975
4990
  async register(e) {
4976
- mn(e);
4991
+ gn(e);
4977
4992
  let t = `mock_wh_${this.nextId++}`, r = {
4978
4993
  id: t,
4979
4994
  url: e.url,
@@ -5000,21 +5015,21 @@ var Se = class {
5000
5015
  };
5001
5016
 
5002
5017
  // src/notifications.ts
5003
- I();
5004
- M();
5005
- var et = [
5018
+ C();
5019
+ F();
5020
+ var nt = [
5006
5021
  "info",
5007
5022
  "success",
5008
5023
  "warning",
5009
5024
  "error"
5010
5025
  ];
5011
- function gn(n) {
5026
+ function _n(n) {
5012
5027
  if (!n || typeof n != "object")
5013
5028
  throw new c("invalid_response", "Notification response is not an object");
5014
5029
  let e = n;
5015
5030
  if (typeof e.id != "string")
5016
5031
  throw new c("invalid_response", "Notification missing id");
5017
- let t = et.includes(e.severity) ? e.severity : "info";
5032
+ let t = nt.includes(e.severity) ? e.severity : "info";
5018
5033
  return {
5019
5034
  id: e.id,
5020
5035
  userId: typeof e.userId == "string" ? e.userId : "",
@@ -5029,21 +5044,21 @@ function gn(n) {
5029
5044
  dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
5030
5045
  };
5031
5046
  }
5032
- function yn(n) {
5047
+ function bn(n) {
5033
5048
  if (!n.userId) throw new c("validation_failed", "userId obrigat\xF3rio");
5034
5049
  if (!n.kind) throw new c("validation_failed", "kind obrigat\xF3rio");
5035
5050
  if (!n.title) throw new c("validation_failed", "title obrigat\xF3rio");
5036
- if (n.severity && !et.includes(n.severity))
5051
+ if (n.severity && !nt.includes(n.severity))
5037
5052
  throw new c(
5038
5053
  "validation_failed",
5039
- `severity inv\xE1lida: ${n.severity} (use ${et.join("|")})`
5054
+ `severity inv\xE1lida: ${n.severity} (use ${nt.join("|")})`
5040
5055
  );
5041
5056
  if (n.title.length > 200)
5042
5057
  throw new c("validation_failed", "title m\xE1x 200 chars");
5043
5058
  if (n.body && n.body.length > 2e3)
5044
5059
  throw new c("validation_failed", "body m\xE1x 2000 chars");
5045
5060
  }
5046
- function Te(n, ...e) {
5061
+ function Re(n, ...e) {
5047
5062
  for (let t of e)
5048
5063
  if (typeof t == "string" && t.length > 0)
5049
5064
  return N("productId", t), t;
@@ -5054,12 +5069,12 @@ function Te(n, ...e) {
5054
5069
  "productId required (pass to options/input or set on createNeetruClient)"
5055
5070
  );
5056
5071
  }
5057
- function _n(n) {
5072
+ function vn(n) {
5058
5073
  return {
5059
5074
  async send(e) {
5060
- yn(e);
5075
+ bn(e);
5061
5076
  let r = {
5062
- productId: Te(n, e.productId),
5077
+ productId: Re(n, e.productId),
5063
5078
  userId: e.userId,
5064
5079
  kind: e.kind,
5065
5080
  title: e.title,
@@ -5073,12 +5088,12 @@ function _n(n) {
5073
5088
  requireAuth: true,
5074
5089
  idempotencyKey: true
5075
5090
  });
5076
- return gn(o);
5091
+ return _n(o);
5077
5092
  },
5078
5093
  async list(e, t) {
5079
5094
  if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5080
5095
  let o = {
5081
- productId: Te(n, t?.productId)
5096
+ productId: Re(n, t?.productId)
5082
5097
  };
5083
5098
  t?.includeDismissed && (o.includeDismissed = true), t?.onlyUnread && (o.onlyUnread = true), t?.limit && (o.limit = Math.min(Math.max(1, t.limit), 200));
5084
5099
  let i = await v(n, {
@@ -5087,11 +5102,11 @@ function _n(n) {
5087
5102
  query: o,
5088
5103
  requireAuth: true
5089
5104
  });
5090
- return (Array.isArray(i?.notifications) ? i.notifications : []).map(gn);
5105
+ return (Array.isArray(i?.notifications) ? i.notifications : []).map(_n);
5091
5106
  },
5092
5107
  async markRead(e, t) {
5093
5108
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5094
- let r = Te(n, t?.productId);
5109
+ let r = Re(n, t?.productId);
5095
5110
  return await v(n, {
5096
5111
  method: "POST",
5097
5112
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/read`,
@@ -5101,7 +5116,7 @@ function _n(n) {
5101
5116
  },
5102
5117
  async dismiss(e, t) {
5103
5118
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
5104
- let r = Te(n, t?.productId);
5119
+ let r = Re(n, t?.productId);
5105
5120
  return await v(n, {
5106
5121
  method: "POST",
5107
5122
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/dismiss`,
@@ -5111,11 +5126,11 @@ function _n(n) {
5111
5126
  }
5112
5127
  };
5113
5128
  }
5114
- var Re = class {
5129
+ var Ie = class {
5115
5130
  notifications = /* @__PURE__ */ new Map();
5116
5131
  nextId = 1;
5117
5132
  async send(e) {
5118
- if (yn(e), e.fingerprint) {
5133
+ if (bn(e), e.fingerprint) {
5119
5134
  let o = Date.now() - 864e5;
5120
5135
  for (let i of this.notifications.values())
5121
5136
  if ((i.metadata ?? {}).fingerprint === e.fingerprint && i.userId === e.userId && new Date(i.createdAt).getTime() > o)
@@ -5152,44 +5167,44 @@ var Re = class {
5152
5167
  };
5153
5168
 
5154
5169
  // src/ai.ts
5155
- I();
5156
- M();
5157
- Me();
5158
- var _o = "/api/sdk/v1/ai/chat", bn = 12e4, Ie = 32768, vn = 32, wn = 4194304, kn = 2048, bo = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, vo = /^https:\/\/[^\s]+$/, wo = /* @__PURE__ */ new Set(["low", "high", "auto"]), ko = /* @__PURE__ */ new Set(["system", "user", "assistant"]), Sn = 100, Tn = 128, Rn = 32768, In = 0, Cn = 2, An = 200, En = 20, Pn = 12 * 1024 * 1024, Dn = 5e4, Nn = 16, xn = 500, So = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), To = /^[a-zA-Z0-9_-]+$/;
5170
+ C();
5171
+ F();
5172
+ qe();
5173
+ var So = "/api/sdk/v1/ai/chat", wn = 12e4, Ce = 32768, kn = 32, Sn = 4194304, Tn = 2048, To = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, Ro = /^https:\/\/[^\s]+$/, Io = /* @__PURE__ */ new Set(["low", "high", "auto"]), Co = /* @__PURE__ */ new Set(["system", "user", "assistant"]), Rn = 100, In = 128, Cn = 32768, An = 0, En = 2, Pn = 200, Dn = 20, Nn = 12 * 1024 * 1024, xn = 5e4, On = 16, Ln = 500, Ao = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), Eo = /^[a-zA-Z0-9_-]+$/;
5159
5174
  function k(n) {
5160
5175
  throw new c("validation_failed", n);
5161
5176
  }
5162
- function Ro(n) {
5177
+ function Po(n) {
5163
5178
  if (n.length === 0 || n.length % 4 !== 0) return false;
5164
5179
  let e = n.endsWith("==") ? 2 : n.endsWith("=") ? 1 : 0;
5165
5180
  return !(e > 0 ? n.slice(0, n.length - e) : n).includes("=");
5166
5181
  }
5167
- function Io(n) {
5182
+ function Do(n) {
5168
5183
  let e = n.indexOf(",");
5169
5184
  if (e === -1) return 0;
5170
5185
  let t = n.slice(e + 1), r = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
5171
5186
  return Math.max(0, Math.floor(t.length * 3 / 4) - r);
5172
5187
  }
5173
- function Co(n) {
5188
+ function No(n) {
5174
5189
  let e = 0, t = 0, r = 0;
5175
5190
  for (let o of n) {
5176
5191
  let i = o?.content;
5177
5192
  if (Array.isArray(i))
5178
5193
  for (let s of i) {
5179
- if (e++, e > An)
5180
- return `ai: total content parts exceeds ${An} per request`;
5194
+ if (e++, e > Pn)
5195
+ return `ai: total content parts exceeds ${Pn} per request`;
5181
5196
  if (s && typeof s == "object" && s.type === "image_url") {
5182
- if (t++, t > En)
5183
- return `ai: total images exceeds ${En} per request`;
5197
+ if (t++, t > Dn)
5198
+ return `ai: total images exceeds ${Dn} per request`;
5184
5199
  let a = s.image_url?.url;
5185
- if (typeof a == "string" && a.startsWith("data:") && (r += Io(a), r > Pn))
5186
- return `ai: aggregate image bytes exceeds ${Pn} per request`;
5200
+ if (typeof a == "string" && a.startsWith("data:") && (r += Do(a), r > Nn))
5201
+ return `ai: aggregate image bytes exceeds ${Nn} per request`;
5187
5202
  }
5188
5203
  }
5189
5204
  }
5190
5205
  return null;
5191
5206
  }
5192
- function Ao(n) {
5207
+ function xo(n) {
5193
5208
  if (n === void 0) return null;
5194
5209
  if (n === null || typeof n != "object")
5195
5210
  return "ai: responseFormat json_schema.schema must be an object";
@@ -5200,11 +5215,11 @@ function Ao(n) {
5200
5215
  return "ai: responseFormat json_schema.schema is not serializable";
5201
5216
  }
5202
5217
  if (e === void 0) return "ai: responseFormat json_schema.schema is invalid";
5203
- if (e.length > Dn)
5204
- return `ai: responseFormat json_schema.schema exceeds ${Dn} serialized chars`;
5218
+ if (e.length > xn)
5219
+ return `ai: responseFormat json_schema.schema exceeds ${xn} serialized chars`;
5205
5220
  let t = 0, r = (o, i) => {
5206
- if (i > Nn)
5207
- return `ai: responseFormat json_schema.schema exceeds max depth ${Nn}`;
5221
+ if (i > On)
5222
+ return `ai: responseFormat json_schema.schema exceeds max depth ${On}`;
5208
5223
  if (Array.isArray(o)) {
5209
5224
  for (let s of o) {
5210
5225
  let a = r(s, i + 1);
@@ -5214,10 +5229,10 @@ function Ao(n) {
5214
5229
  }
5215
5230
  if (o && typeof o == "object")
5216
5231
  for (let s of Object.getOwnPropertyNames(o)) {
5217
- if (So.has(s))
5232
+ if (Ao.has(s))
5218
5233
  return `ai: responseFormat json_schema.schema has forbidden key: ${s}`;
5219
- if (t++, t > xn)
5220
- return `ai: responseFormat json_schema.schema exceeds ${xn} keys`;
5234
+ if (t++, t > Ln)
5235
+ return `ai: responseFormat json_schema.schema exceeds ${Ln} keys`;
5221
5236
  let a = r(o[s], i + 1);
5222
5237
  if (a) return a;
5223
5238
  }
@@ -5225,44 +5240,44 @@ function Ao(n) {
5225
5240
  };
5226
5241
  return r(n, 0);
5227
5242
  }
5228
- function Eo(n) {
5243
+ function Oo(n) {
5229
5244
  (typeof n != "string" || n.length === 0) && k("ai: image_url.url must be a non-empty string");
5230
5245
  let e = n;
5231
5246
  if (e.startsWith("data:")) {
5232
- e.length > wn && k(`ai: image_url.url (data:) exceeds ${wn} chars`), bo.test(e) || k("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5247
+ e.length > Sn && k(`ai: image_url.url (data:) exceeds ${Sn} chars`), To.test(e) || k("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5233
5248
  let t = e.slice(e.indexOf(",") + 1);
5234
- Ro(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5249
+ Po(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5235
5250
  return;
5236
5251
  }
5237
5252
  if (e.startsWith("https://")) {
5238
- e.length > kn && k(`ai: image_url.url (https:) exceeds ${kn} chars`), vo.test(e) || k("ai: image_url.url https: is invalid");
5253
+ e.length > Tn && k(`ai: image_url.url (https:) exceeds ${Tn} chars`), Ro.test(e) || k("ai: image_url.url https: is invalid");
5239
5254
  return;
5240
5255
  }
5241
5256
  k("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5242
5257
  }
5243
- function Po(n, e) {
5258
+ function Lo(n, e) {
5244
5259
  if (typeof n == "string") {
5245
- n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ie && k(`ai: message content exceeds ${Ie} chars`);
5260
+ n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ce && k(`ai: message content exceeds ${Ce} chars`);
5246
5261
  return;
5247
5262
  }
5248
- (!Array.isArray(n) || n.length === 0) && k("ai: message content must be a non-empty string or array of parts"), n.length > vn && k(`ai: message content has more than ${vn} parts`);
5263
+ (!Array.isArray(n) || n.length === 0) && k("ai: message content must be a non-empty string or array of parts"), n.length > kn && k(`ai: message content has more than ${kn} parts`);
5249
5264
  for (let t of n) {
5250
5265
  (!t || typeof t != "object") && k("ai: each content part must be an object");
5251
5266
  let r = t.type;
5252
5267
  if (r === "text") {
5253
5268
  let o = t.text;
5254
- (typeof o != "string" || o.length === 0) && k("ai: text part must have non-empty { text: string }"), o.length > Ie && k(`ai: text part exceeds ${Ie} chars`);
5269
+ (typeof o != "string" || o.length === 0) && k("ai: text part must have non-empty { text: string }"), o.length > Ce && k(`ai: text part exceeds ${Ce} chars`);
5255
5270
  } else if (r === "image_url") {
5256
5271
  e !== "user" && k(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5257
5272
  let o = t.image_url;
5258
- (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Eo(o.url);
5273
+ (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Oo(o.url);
5259
5274
  let i = o.detail;
5260
- i !== void 0 && (typeof i != "string" || !wo.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5275
+ i !== void 0 && (typeof i != "string" || !Io.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5261
5276
  } else
5262
5277
  k("ai: content part type must be 'text' or 'image_url'");
5263
5278
  }
5264
5279
  }
5265
- function Do(n) {
5280
+ function Uo(n) {
5266
5281
  (!n || typeof n != "object") && k("ai: responseFormat must be an object");
5267
5282
  let e = n.type;
5268
5283
  if (!(e === "text" || e === "json_object")) {
@@ -5270,8 +5285,8 @@ function Do(n) {
5270
5285
  let t = n.json_schema;
5271
5286
  (!t || typeof t != "object") && k("ai: responseFormat json_schema requires { json_schema: { name } }");
5272
5287
  let r = t, o = r.name;
5273
- if ((typeof o != "string" || o.length === 0) && k("ai: responseFormat json_schema.name is required"), o.length > 64 && k("ai: responseFormat json_schema.name exceeds 64 chars"), To.test(o) || k("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && k("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && k("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && k("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5274
- let i = Ao(r.schema);
5288
+ if ((typeof o != "string" || o.length === 0) && k("ai: responseFormat json_schema.name is required"), o.length > 64 && k("ai: responseFormat json_schema.name exceeds 64 chars"), Eo.test(o) || k("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && k("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && k("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && k("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5289
+ let i = xo(r.schema);
5275
5290
  i && k(i);
5276
5291
  }
5277
5292
  return;
@@ -5279,26 +5294,26 @@ function Do(n) {
5279
5294
  k("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5280
5295
  }
5281
5296
  }
5282
- function On(n, e, t) {
5297
+ function Un(n, e, t) {
5283
5298
  if (!e || typeof e != "object")
5284
5299
  throw new c("validation_failed", "ai: options object is required");
5285
5300
  if (typeof e.model != "string" || e.model.length === 0)
5286
5301
  throw new c("validation_failed", "ai: model is required");
5287
- if (e.model.length > Tn)
5288
- throw new c("validation_failed", `ai: model exceeds ${Tn} chars`);
5302
+ if (e.model.length > In)
5303
+ throw new c("validation_failed", `ai: model exceeds ${In} chars`);
5289
5304
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5290
5305
  throw new c("validation_failed", "ai: messages must be a non-empty array");
5291
- if (e.messages.length > Sn)
5292
- throw new c("validation_failed", `ai: messages exceeds ${Sn} per request`);
5306
+ if (e.messages.length > Rn)
5307
+ throw new c("validation_failed", `ai: messages exceeds ${Rn} per request`);
5293
5308
  for (let a of e.messages) {
5294
- if (!a || typeof a != "object" || typeof a.role != "string" || !ko.has(a.role))
5309
+ if (!a || typeof a != "object" || typeof a.role != "string" || !Co.has(a.role))
5295
5310
  throw new c(
5296
5311
  "validation_failed",
5297
5312
  "ai: each message role must be 'system' | 'user' | 'assistant'"
5298
5313
  );
5299
- Po(a.content, a.role);
5314
+ Lo(a.content, a.role);
5300
5315
  }
5301
- let r = Co(e.messages);
5316
+ let r = No(e.messages);
5302
5317
  if (r) throw new c("validation_failed", r);
5303
5318
  let o = e.productId ?? n.productId, i = e.tenantId ?? n.tenantId;
5304
5319
  if (!o)
@@ -5320,24 +5335,24 @@ function On(n, e, t) {
5320
5335
  stream: t
5321
5336
  };
5322
5337
  if (e.maxTokens !== void 0) {
5323
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Rn)
5338
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Cn)
5324
5339
  throw new c(
5325
5340
  "validation_failed",
5326
- `ai: maxTokens must be a positive integer <= ${Rn}`
5341
+ `ai: maxTokens must be a positive integer <= ${Cn}`
5327
5342
  );
5328
5343
  s.maxTokens = e.maxTokens;
5329
5344
  }
5330
5345
  if (e.temperature !== void 0) {
5331
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < In || e.temperature > Cn)
5346
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < An || e.temperature > En)
5332
5347
  throw new c(
5333
5348
  "validation_failed",
5334
- `ai: temperature must be a finite number between ${In} and ${Cn}`
5349
+ `ai: temperature must be a finite number between ${An} and ${En}`
5335
5350
  );
5336
5351
  s.temperature = e.temperature;
5337
5352
  }
5338
- return e.responseFormat !== void 0 && (Do(e.responseFormat), s.responseFormat = e.responseFormat), s;
5353
+ return e.responseFormat !== void 0 && (Uo(e.responseFormat), s.responseFormat = e.responseFormat), s;
5339
5354
  }
5340
- async function qn(n) {
5355
+ async function jn(n) {
5341
5356
  try {
5342
5357
  let e = await n.text();
5343
5358
  return e ? JSON.parse(e) : void 0;
@@ -5345,32 +5360,32 @@ async function qn(n) {
5345
5360
  return;
5346
5361
  }
5347
5362
  }
5348
- function No(n, e) {
5363
+ function Mo(n, e) {
5349
5364
  let t = n.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
5350
5365
  return `${t}${r}`;
5351
5366
  }
5352
- async function Ln(n, e, t, r) {
5367
+ async function Mn(n, e, t, r) {
5353
5368
  if (!n.apiKey)
5354
5369
  throw new c(
5355
5370
  "missing_api_key",
5356
5371
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
5357
5372
  );
5358
- let o = No(n.baseUrl, _o), { headers: i, correlationId: s } = ae({
5373
+ let o = Mo(n.baseUrl, So), { headers: i, correlationId: s } = ce({
5359
5374
  "content-type": "application/json",
5360
5375
  accept: r ? "text/event-stream" : "application/json",
5361
5376
  authorization: `Bearer ${n.apiKey}`
5362
5377
  }), a = { method: "POST", headers: i, body: JSON.stringify(e) };
5363
- r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(bn);
5378
+ r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(wn);
5364
5379
  let l;
5365
5380
  try {
5366
5381
  l = await n.fetch(o, a);
5367
5382
  } catch (p) {
5368
- let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${bn / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5383
+ let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${wn / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5369
5384
  throw new c("network_error", f, void 0, void 0, void 0, s);
5370
5385
  }
5371
5386
  let d = l.headers.get("x-request-id") ?? l.headers.get("x-correlation-id") ?? void 0;
5372
5387
  if (!l.ok) {
5373
- let p = await qn(l), f = le(l.status), h = `HTTP ${l.status}`;
5388
+ let p = await jn(l), f = de(l.status), h = `HTTP ${l.status}`;
5374
5389
  if (p && typeof p == "object" && "error" in p) {
5375
5390
  let y = p.error;
5376
5391
  typeof y == "string" ? h = y : y && typeof y == "object" && (typeof y.code == "string" && (f = y.code), typeof y.message == "string" && (h = y.message));
@@ -5378,15 +5393,15 @@ async function Ln(n, e, t, r) {
5378
5393
  throw new c(f, h, l.status, d, void 0, s);
5379
5394
  }
5380
5395
  let u = l.headers.get("x-neetru-version");
5381
- return u && ce(u), l;
5396
+ return u && le(u), l;
5382
5397
  }
5383
- function Un(n) {
5398
+ function qn(n) {
5384
5399
  return {
5385
5400
  provider: n.headers.get("x-neetru-provider") ?? "",
5386
5401
  usageWarning: n.headers.get("x-neetru-ai-usage-warning") === "1"
5387
5402
  };
5388
5403
  }
5389
- function Mn(n) {
5404
+ function Fn(n) {
5390
5405
  let e = [];
5391
5406
  for (let r of n.split(`
5392
5407
  `)) {
@@ -5407,10 +5422,10 @@ function Mn(n) {
5407
5422
  return null;
5408
5423
  }
5409
5424
  }
5410
- function Fn(n) {
5425
+ function $n(n) {
5411
5426
  return {
5412
5427
  async chat(e) {
5413
- let t = On(n, e, false), r = await Ln(n, t, e.signal, false), { provider: o, usageWarning: i } = Un(r), s = await qn(r);
5428
+ let t = Un(n, e, false), r = await Mn(n, t, e.signal, false), { provider: o, usageWarning: i } = qn(r), s = await jn(r);
5414
5429
  if (!s || s.ok !== true || !Array.isArray(s.choices))
5415
5430
  throw new c("invalid_response", "ai.chat response missing ok/choices");
5416
5431
  return {
@@ -5422,7 +5437,7 @@ function Fn(n) {
5422
5437
  };
5423
5438
  },
5424
5439
  stream(e) {
5425
- let t = On(n, e, true), r = Ln(n, t, e.signal, true), o = r.then(Un);
5440
+ let t = Un(n, e, true), r = Mn(n, t, e.signal, true), o = r.then(qn);
5426
5441
  o.catch(() => {
5427
5442
  });
5428
5443
  async function* i() {
@@ -5439,16 +5454,16 @@ function Fn(n) {
5439
5454
  for (; (y = u.indexOf(`
5440
5455
 
5441
5456
  `)) !== -1; ) {
5442
- let S = u.slice(0, y);
5457
+ let T = u.slice(0, y);
5443
5458
  u = u.slice(y + 2);
5444
- let x = Mn(S);
5459
+ let x = Fn(T);
5445
5460
  if (x && "done" in x) return;
5446
5461
  x && "content" in x && (yield x.content);
5447
5462
  }
5448
5463
  }
5449
5464
  let p = u.trim();
5450
5465
  if (p) {
5451
- let f = Mn(p);
5466
+ let f = Fn(p);
5452
5467
  f && "content" in f && (yield f.content);
5453
5468
  }
5454
5469
  } finally {
@@ -5471,20 +5486,8 @@ function Fn(n) {
5471
5486
  }
5472
5487
 
5473
5488
  // src/mocks.ts
5474
- I();
5475
-
5476
- // src/runtime-env.ts
5477
- function Ce() {
5478
- try {
5479
- if (typeof process < "u" && process.env)
5480
- return process.env.NODE_ENV === "production";
5481
- } catch {
5482
- }
5483
- return false;
5484
- }
5485
-
5486
- // src/mocks.ts
5487
- var tt = Object.freeze({
5489
+ C();
5490
+ var rt = Object.freeze({
5488
5491
  uid: "dev-fixture-uid-0001",
5489
5492
  email: "dev@neetru.local",
5490
5493
  emailVerified: true,
@@ -5496,7 +5499,7 @@ var tt = Object.freeze({
5496
5499
  _listeners;
5497
5500
  _allowUnsignedDecode;
5498
5501
  constructor(e = null, t) {
5499
- if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Ce())
5502
+ if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && $e())
5500
5503
  throw new c(
5501
5504
  "invalid_config",
5502
5505
  "MockAuth com allowUnsignedDecode=true \xE9 PROIBIDO em produ\xE7\xE3o (NODE_ENV=production): decodificar JWT sem verificar assinatura \xE9 bypass de autentica\xE7\xE3o. Este modo existe exclusivamente para testes."
@@ -5506,10 +5509,10 @@ var tt = Object.freeze({
5506
5509
  );
5507
5510
  }
5508
5511
  async signIn(e) {
5509
- return this._user || (this._user = { ...tt }), this._notify(), this._user;
5512
+ return this._user || (this._user = { ...rt }), this._notify(), this._user;
5510
5513
  }
5511
5514
  async signOut() {
5512
- this._user = null, this._notify();
5515
+ return this._user = null, this._notify(), { localSessionCleared: true, remoteRevocation: "skipped" };
5513
5516
  }
5514
5517
  getUser() {
5515
5518
  return this._user;
@@ -5836,9 +5839,30 @@ var Ne = class {
5836
5839
  }
5837
5840
  };
5838
5841
 
5842
+ // src/timeout.ts
5843
+ function Wn(n) {
5844
+ let e = globalThis.AbortSignal;
5845
+ if (typeof e?.timeout == "function")
5846
+ return { signal: e.timeout(n), clear: () => {
5847
+ } };
5848
+ if (typeof globalThis.AbortController != "function")
5849
+ return { signal: void 0, clear: () => {
5850
+ } };
5851
+ let t = new AbortController(), r = setTimeout(() => t.abort(), n);
5852
+ return r.unref?.(), { signal: t.signal, clear: () => clearTimeout(r) };
5853
+ }
5854
+ function Bn(n, e, t) {
5855
+ let r, o = new Promise((i) => {
5856
+ r = setTimeout(() => i(t()), e), r.unref?.();
5857
+ });
5858
+ return Promise.race([n, o]).finally(() => {
5859
+ r !== void 0 && clearTimeout(r);
5860
+ });
5861
+ }
5862
+
5839
5863
  // src/auth-pkce-shared.ts
5840
- I();
5841
- function jn() {
5864
+ C();
5865
+ function Vn() {
5842
5866
  let n = globalThis.crypto;
5843
5867
  if (!n || typeof n.getRandomValues != "function" || !n.subtle)
5844
5868
  throw new c(
@@ -5847,36 +5871,36 @@ function jn() {
5847
5871
  );
5848
5872
  return n;
5849
5873
  }
5850
- function $n(n) {
5874
+ function Kn(n) {
5851
5875
  let e = "";
5852
5876
  for (let r of n) e += String.fromCharCode(r);
5853
5877
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
5854
5878
  }
5855
5879
  function xe(n, e) {
5856
5880
  let t = new Uint8Array(e);
5857
- return n.getRandomValues(t), $n(t);
5881
+ return n.getRandomValues(t), Kn(t);
5858
5882
  }
5859
- async function Wn(n, e) {
5883
+ async function zn(n, e) {
5860
5884
  let t = new TextEncoder().encode(e), r = await n.subtle.digest("SHA-256", t);
5861
- return $n(new Uint8Array(r));
5885
+ return Kn(new Uint8Array(r));
5862
5886
  }
5863
- function oe(n) {
5887
+ function ie(n) {
5864
5888
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.replace(/^https?:\/\/api\./, "https://auth.");
5865
5889
  }
5866
- function Bn(n) {
5890
+ function Hn(n) {
5867
5891
  let e = n.oidcClientId;
5868
- if (!e && n.apiKey && (e = ct(n.apiKey).keyId), !e)
5892
+ if (!e && n.apiKey && (e = dt(n.apiKey).keyId), !e)
5869
5893
  throw new c(
5870
5894
  "invalid_config",
5871
5895
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
5872
5896
  );
5873
5897
  return e;
5874
5898
  }
5875
- function Vn(n) {
5899
+ function Qn(n) {
5876
5900
  let e = new URL("/api/v1/oauth/authorize", n.idpOrigin);
5877
5901
  return e.searchParams.set("response_type", "code"), e.searchParams.set("client_id", n.clientId), e.searchParams.set("redirect_uri", n.redirectUri), e.searchParams.set("scope", n.scope), e.searchParams.set("state", n.state), e.searchParams.set("nonce", n.nonce), e.searchParams.set("code_challenge", n.codeChallenge), e.searchParams.set("code_challenge_method", "S256"), e;
5878
5902
  }
5879
- function nt(n) {
5903
+ function ot(n) {
5880
5904
  let e = n.split(".");
5881
5905
  if (e.length !== 3) return null;
5882
5906
  try {
@@ -5886,8 +5910,8 @@ function nt(n) {
5886
5910
  return null;
5887
5911
  }
5888
5912
  }
5889
- function ie(n) {
5890
- let e = nt(n);
5913
+ function se(n) {
5914
+ let e = ot(n);
5891
5915
  return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
5892
5916
  uid: e.sub,
5893
5917
  email: typeof e.email == "string" ? e.email : "",
@@ -5900,9 +5924,9 @@ function ie(n) {
5900
5924
  ...e
5901
5925
  };
5902
5926
  }
5903
- var xo = "/api/v1/oauth/revoke";
5904
- async function Kn(n, e, t, r) {
5905
- let o = `${e}${xo}`, i = true;
5927
+ var qo = "/api/v1/oauth/revoke";
5928
+ async function Gn(n, e, t, r) {
5929
+ let o = `${e}${qo}`, i = true;
5906
5930
  for (let s of r) {
5907
5931
  if (!s.token) continue;
5908
5932
  let a = new URLSearchParams({
@@ -5926,17 +5950,17 @@ async function Kn(n, e, t, r) {
5926
5950
  }
5927
5951
 
5928
5952
  // src/auth.ts
5929
- qe();
5953
+ Fe();
5930
5954
 
5931
5955
  // src/end-user-token.ts
5932
- var Oo = /* @__PURE__ */ new WeakMap();
5933
- function zn(n, e) {
5934
- Oo.set(n, e);
5956
+ var Fo = /* @__PURE__ */ new WeakMap();
5957
+ function Jn(n, e) {
5958
+ Fo.set(n, e);
5935
5959
  }
5936
5960
 
5937
5961
  // src/unsupported-db.ts
5938
- I();
5939
- var Lo = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O app n\xE3o acessa o banco do produto diretamente: chame a API do SEU produto (ex.: https://<produto>.neetru.com/api/v1) com o access_token do usu\xE1rio (Authorization: Bearer) \u2014 o backend do produto usa client.db no servidor. (At\xE9 a 3.7.x o db ca\xEDa em mem\xF3ria em sil\xEAncio e os dados sumiam ao fechar o app.)", Uo = /* @__PURE__ */ new Set([
5962
+ C();
5963
+ var jo = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O app n\xE3o acessa o banco do produto diretamente: chame a API do SEU produto (ex.: https://<produto>.neetru.com/api/v1) com o access_token do usu\xE1rio (Authorization: Bearer) \u2014 o backend do produto usa client.db no servidor. (At\xE9 a 3.7.x o db ca\xEDa em mem\xF3ria em sil\xEAncio e os dados sumiam ao fechar o app.)", $o = /* @__PURE__ */ new Set([
5940
5964
  "then",
5941
5965
  "toJSON",
5942
5966
  "valueOf",
@@ -5945,13 +5969,13 @@ var Lo = "[Neetru SDK] client.db n\xE3o est\xE1 dispon\xEDvel em React Native. O
5945
5969
  "asymmetricMatch",
5946
5970
  "nodeType"
5947
5971
  ]);
5948
- function Hn() {
5972
+ function Xn() {
5949
5973
  let n = () => {
5950
- throw new c("runtime_unsupported", Lo, void 0, void 0, "react-native");
5974
+ throw new c("runtime_unsupported", jo, void 0, void 0, "react-native");
5951
5975
  }, e = {};
5952
5976
  return new Proxy(e, {
5953
5977
  get(t, r) {
5954
- if (!(typeof r == "symbol" || Uo.has(r)))
5978
+ if (!(typeof r == "symbol" || $o.has(r)))
5955
5979
  return r === "toString" ? () => "[NeetruDb indispon\xEDvel em React Native]" : n;
5956
5980
  },
5957
5981
  set() {
@@ -5961,7 +5985,7 @@ function Hn() {
5961
5985
  }
5962
5986
 
5963
5987
  // src/auth.ts
5964
- function qo() {
5988
+ function Bo() {
5965
5989
  try {
5966
5990
  let e = globalThis.process?.env?.NEETRU_API_KEY;
5967
5991
  return typeof e == "string" && e.length > 0 ? e : void 0;
@@ -5969,7 +5993,7 @@ function qo() {
5969
5993
  return;
5970
5994
  }
5971
5995
  }
5972
- function Fo(n) {
5996
+ function Vo(n) {
5973
5997
  if (n) return n;
5974
5998
  try {
5975
5999
  let t = globalThis.process?.env?.NEETRU_ENV;
@@ -5983,11 +6007,11 @@ function Fo(n) {
5983
6007
  }
5984
6008
  return "prod";
5985
6009
  }
5986
- var jo = it;
5987
- function sa() {
5988
- st();
6010
+ var Ko = at;
6011
+ function ga() {
6012
+ ct();
5989
6013
  }
5990
- function $o(n) {
6014
+ function zo(n) {
5991
6015
  let e = n.sub ?? "", t = typeof n.email == "string" ? n.email : "";
5992
6016
  return {
5993
6017
  uid: e,
@@ -6002,8 +6026,8 @@ function $o(n) {
6002
6026
  ...n
6003
6027
  };
6004
6028
  }
6005
- var se = "neetru_oauth_tx";
6006
- function rt(n) {
6029
+ var ae = "neetru_oauth_tx";
6030
+ function it(n) {
6007
6031
  try {
6008
6032
  let e = globalThis.history;
6009
6033
  if (!e || typeof e.replaceState != "function") return;
@@ -6014,7 +6038,7 @@ function rt(n) {
6014
6038
  } catch {
6015
6039
  }
6016
6040
  }
6017
- function Wo(n) {
6041
+ function Ho(n) {
6018
6042
  let e = "neetru_id_token", t = "neetru_refresh_token", r = /* @__PURE__ */ new Set(), o = null, i = null, s = null;
6019
6043
  function a() {
6020
6044
  try {
@@ -6032,21 +6056,21 @@ function Wo(n) {
6032
6056
  }
6033
6057
  function d() {
6034
6058
  if (o) {
6035
- let g = o.exp;
6036
- return typeof g == "number" && g * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), S(), null) : o;
6059
+ let m = o.exp;
6060
+ return typeof m == "number" && m * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), T(), null) : o;
6037
6061
  }
6038
- let m = a();
6039
- if (!m) return null;
6040
- let _ = m.getItem(e);
6041
- if (!_)
6042
- return S(), null;
6043
- let w = ie(_);
6044
- return w ? (o = w, x(w), o) : (m.removeItem(e), S(), null);
6062
+ let g = a();
6063
+ if (!g) return null;
6064
+ let b = g.getItem(e);
6065
+ if (!b)
6066
+ return T(), null;
6067
+ let w = se(b);
6068
+ return w ? (o = w, x(w), o) : (g.removeItem(e), T(), null);
6045
6069
  }
6046
6070
  function u() {
6047
- for (let m of r)
6071
+ for (let g of r)
6048
6072
  try {
6049
- m(o);
6073
+ g(o);
6050
6074
  } catch {
6051
6075
  }
6052
6076
  }
@@ -6058,70 +6082,75 @@ function Wo(n) {
6058
6082
  }
6059
6083
  function h() {
6060
6084
  o = null;
6061
- let m = a();
6062
- m?.removeItem(e), m?.removeItem(t), u();
6085
+ let g = a();
6086
+ g?.removeItem(e), g?.removeItem(t), u();
6063
6087
  }
6064
6088
  function y() {
6065
- return s || (s = (async () => {
6066
- let m = f();
6067
- if (!m) return false;
6068
- let _;
6089
+ if (s) return s;
6090
+ let g = false, b = (async () => {
6091
+ let w = f();
6092
+ if (!w) return false;
6093
+ let m;
6069
6094
  try {
6070
- _ = T();
6095
+ m = R();
6071
6096
  } catch {
6072
6097
  return false;
6073
6098
  }
6074
- let g = `${oe(n.baseUrl)}/api/v1/oauth/token`, C = new URLSearchParams({
6099
+ let D = `${ie(n.baseUrl)}/api/v1/oauth/token`, O = new URLSearchParams({
6075
6100
  grant_type: "refresh_token",
6076
- refresh_token: m,
6077
- client_id: _
6078
- }), D;
6101
+ refresh_token: w,
6102
+ client_id: m
6103
+ }), { signal: A, clear: M } = Wn(15e3), I;
6079
6104
  try {
6080
- D = await n.fetch(g, {
6105
+ I = await n.fetch(D, {
6081
6106
  method: "POST",
6082
6107
  headers: { "content-type": "application/x-www-form-urlencoded" },
6083
- body: C.toString()
6108
+ body: O.toString(),
6109
+ signal: A
6084
6110
  });
6085
6111
  } catch {
6086
6112
  return false;
6113
+ } finally {
6114
+ M();
6087
6115
  }
6088
- let E = null;
6116
+ let L = null;
6089
6117
  try {
6090
- E = await D.json();
6118
+ L = await I.json();
6091
6119
  } catch {
6092
- E = null;
6120
+ L = null;
6093
6121
  }
6094
- if (!D.ok || typeof E?.error == "string") return false;
6095
- let R = E?.id_token;
6096
- if (typeof R != "string" || R.length === 0) return false;
6097
- let O = ie(R);
6098
- if (!O) return false;
6099
- let A = a();
6100
- A?.setItem(e, R);
6101
- let U = E?.refresh_token;
6102
- return typeof U == "string" && U.length > 0 && A?.setItem(t, U), o = O, x(O), u(), true;
6103
- })().finally(() => {
6122
+ if (!I.ok || typeof L?.error == "string") return false;
6123
+ let U = L?.id_token;
6124
+ if (typeof U != "string" || U.length === 0) return false;
6125
+ let q = se(U);
6126
+ if (!q || g) return false;
6127
+ let P = a();
6128
+ P?.setItem(e, U);
6129
+ let Le = L?.refresh_token;
6130
+ return typeof Le == "string" && Le.length > 0 && P?.setItem(t, Le), o = q, x(q), u(), true;
6131
+ })();
6132
+ return s = Bn(b, 15e3, () => (g = true, false)).finally(() => {
6104
6133
  s = null;
6105
- }), s);
6134
+ }), s;
6106
6135
  }
6107
- function S() {
6108
- f() && y().then((m) => {
6109
- m || h();
6136
+ function T() {
6137
+ f() && y().then((g) => {
6138
+ g || h();
6110
6139
  });
6111
6140
  }
6112
- function x(m) {
6141
+ function x(g) {
6113
6142
  p();
6114
- let _ = m.exp;
6115
- if (typeof _ != "number") return;
6116
- let w = _ * 1e3 - Date.now();
6143
+ let b = g.exp;
6144
+ if (typeof b != "number") return;
6145
+ let w = b * 1e3 - Date.now();
6117
6146
  if (!(w <= 0)) {
6118
6147
  if (f()) {
6119
- let g = Math.min(w, Math.max(3e4, w * 0.2)), C = Math.max(1, w - g);
6148
+ let m = Math.min(w, Math.max(3e4, w * 0.2)), S = Math.max(1, w - m);
6120
6149
  i = setTimeout(() => {
6121
6150
  i = null, y().then((D) => {
6122
6151
  D || h();
6123
6152
  });
6124
- }, C);
6153
+ }, S);
6125
6154
  return;
6126
6155
  }
6127
6156
  i = setTimeout(() => {
@@ -6129,143 +6158,143 @@ function Wo(n) {
6129
6158
  }, w + 1);
6130
6159
  }
6131
6160
  }
6132
- function T() {
6133
- return Bn(n);
6161
+ function R() {
6162
+ return Hn(n);
6134
6163
  }
6135
- async function P(m) {
6136
- let _ = m ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6137
- if (!_) return null;
6164
+ async function E(g) {
6165
+ let b = g ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6166
+ if (!b) return null;
6138
6167
  let w;
6139
6168
  try {
6140
- w = new URL(_);
6169
+ w = new URL(b);
6141
6170
  } catch {
6142
6171
  return null;
6143
6172
  }
6144
- let g = w.searchParams, C = g.get("error");
6145
- if (C) {
6146
- let U = g.get("error_description") ?? C;
6147
- throw l()?.removeItem(se), rt(w), new c(C, `OIDC authorize falhou: ${U}`);
6173
+ let m = w.searchParams, S = m.get("error");
6174
+ if (S) {
6175
+ let L = m.get("error_description") ?? S;
6176
+ throw l()?.removeItem(ae), it(w), new c(S, `OIDC authorize falhou: ${L}`);
6148
6177
  }
6149
- let D = g.get("code");
6178
+ let D = m.get("code");
6150
6179
  if (!D) return null;
6151
- let E = g.get("state"), R = l(), O = R?.getItem(se) ?? null, A = null;
6152
- if (O)
6180
+ let O = m.get("state"), A = l(), M = A?.getItem(ae) ?? null, I = null;
6181
+ if (M)
6153
6182
  try {
6154
- A = JSON.parse(O);
6183
+ I = JSON.parse(M);
6155
6184
  } catch {
6156
- A = null;
6185
+ I = null;
6157
6186
  }
6158
- if (!A)
6187
+ if (!I)
6159
6188
  throw new c(
6160
6189
  "oidc_state_mismatch",
6161
6190
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado nesta sess\xE3o (ou j\xE1 consumido)."
6162
6191
  );
6163
- if (!E || E !== A.state)
6164
- throw R?.removeItem(se), rt(w), new c(
6192
+ if (!O || O !== I.state)
6193
+ throw A?.removeItem(ae), it(w), new c(
6165
6194
  "oidc_state_mismatch",
6166
6195
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
6167
6196
  );
6168
- return R?.removeItem(se), rt(w), {
6197
+ return A?.removeItem(ae), it(w), {
6169
6198
  code: D,
6170
- codeVerifier: A.codeVerifier,
6171
- redirectUri: A.redirectUri,
6172
- nonce: A.nonce,
6173
- state: A.state,
6174
- postLoginRedirect: A.postLoginRedirect
6199
+ codeVerifier: I.codeVerifier,
6200
+ redirectUri: I.redirectUri,
6201
+ nonce: I.nonce,
6202
+ state: I.state,
6203
+ postLoginRedirect: I.postLoginRedirect
6175
6204
  };
6176
6205
  }
6177
- async function q(m) {
6178
- let _ = await P(m);
6179
- if (!_) return null;
6180
- let w = T(), C = `${oe(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
6206
+ async function j(g) {
6207
+ let b = await E(g);
6208
+ if (!b) return null;
6209
+ let w = R(), S = `${ie(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
6181
6210
  grant_type: "authorization_code",
6182
- code: _.code,
6183
- redirect_uri: _.redirectUri,
6211
+ code: b.code,
6212
+ redirect_uri: b.redirectUri,
6184
6213
  client_id: w,
6185
- code_verifier: _.codeVerifier
6186
- }), E;
6214
+ code_verifier: b.codeVerifier
6215
+ }), O;
6187
6216
  try {
6188
- E = await n.fetch(C, {
6217
+ O = await n.fetch(S, {
6189
6218
  method: "POST",
6190
6219
  headers: { "content-type": "application/x-www-form-urlencoded" },
6191
6220
  body: D.toString()
6192
6221
  });
6193
- } catch (L) {
6222
+ } catch (P) {
6194
6223
  throw new c(
6195
6224
  "network_error",
6196
- `POST ${C} falhou (network): ${L?.message ?? String(L)}`
6225
+ `POST ${S} falhou (network): ${P?.message ?? String(P)}`
6197
6226
  );
6198
6227
  }
6199
- let R = null;
6228
+ let A = null;
6200
6229
  try {
6201
- R = await E.json();
6230
+ A = await O.json();
6202
6231
  } catch {
6203
- R = null;
6232
+ A = null;
6204
6233
  }
6205
- if (!E.ok || typeof R?.error == "string") {
6206
- let L = typeof R?.error_description == "string" && R.error_description || typeof R?.error == "string" && R.error || `HTTP ${E.status}`;
6234
+ if (!O.ok || typeof A?.error == "string") {
6235
+ let P = typeof A?.error_description == "string" && A.error_description || typeof A?.error == "string" && A.error || `HTTP ${O.status}`;
6207
6236
  throw new c(
6208
6237
  "token_exchange_failed",
6209
- `Troca do authorization_code por tokens falhou no /token: ${L}`,
6210
- E.status
6238
+ `Troca do authorization_code por tokens falhou no /token: ${P}`,
6239
+ O.status
6211
6240
  );
6212
6241
  }
6213
- let O = R?.id_token;
6214
- if (typeof O != "string" || O.length === 0)
6242
+ let M = A?.id_token;
6243
+ if (typeof M != "string" || M.length === 0)
6215
6244
  throw new c(
6216
6245
  "token_exchange_failed",
6217
6246
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado.",
6218
- E.status
6247
+ O.status
6219
6248
  );
6220
- let A = nt(O);
6221
- if (!A)
6249
+ let I = ot(M);
6250
+ if (!I)
6222
6251
  throw new c(
6223
6252
  "token_exchange_failed",
6224
6253
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
6225
6254
  );
6226
- if (A.nonce !== _.nonce)
6255
+ if (I.nonce !== b.nonce)
6227
6256
  throw new c(
6228
6257
  "oidc_nonce_mismatch",
6229
6258
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
6230
6259
  );
6231
- let U = ie(O);
6232
- if (!U)
6260
+ let L = se(M);
6261
+ if (!L)
6233
6262
  throw new c(
6234
6263
  "token_exchange_failed",
6235
6264
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
6236
6265
  );
6237
- let F = a();
6238
- F?.setItem(e, O);
6239
- let j = R?.refresh_token;
6240
- return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = U, x(U), u(), { user: U, postLoginRedirect: _.postLoginRedirect };
6266
+ let U = a();
6267
+ U?.setItem(e, M);
6268
+ let q = A?.refresh_token;
6269
+ return typeof q == "string" && q.length > 0 && U?.setItem(t, q), o = L, x(L), u(), { user: L, postLoginRedirect: b.postLoginRedirect };
6241
6270
  }
6242
6271
  return {
6243
- async signIn(m) {
6272
+ async signIn(g) {
6244
6273
  if (typeof globalThis.location < "u" && typeof globalThis.location.assign == "function") {
6245
- let _ = jn(), w = m?.redirectUri ?? globalThis.location.origin, g = m?.scope ?? "openid profile email", C = T(), D = xe(_, 16), E = xe(_, 16), R = xe(_, 32), O = await Wn(_, R), A = l();
6246
- if (!A)
6274
+ let b = Vn(), w = g?.redirectUri ?? globalThis.location.origin, m = g?.scope ?? "openid profile email", S = R(), D = xe(b, 16), O = xe(b, 16), A = xe(b, 32), M = await zn(b, A), I = l();
6275
+ if (!I)
6247
6276
  throw new c(
6248
6277
  "runtime_unsupported",
6249
6278
  "auth.signIn requer sessionStorage para guardar a transa\xE7\xE3o PKCE entre o redirect e o callback."
6250
6279
  );
6251
- let U = {
6280
+ let L = {
6252
6281
  state: D,
6253
- nonce: E,
6254
- codeVerifier: R,
6282
+ nonce: O,
6283
+ codeVerifier: A,
6255
6284
  redirectUri: w,
6256
- postLoginRedirect: m?.postLoginRedirect
6285
+ postLoginRedirect: g?.postLoginRedirect
6257
6286
  };
6258
- A.setItem(se, JSON.stringify(U));
6259
- let F = oe(n.baseUrl), j = Vn({
6260
- idpOrigin: F,
6261
- clientId: C,
6287
+ I.setItem(ae, JSON.stringify(L));
6288
+ let U = ie(n.baseUrl), q = Qn({
6289
+ idpOrigin: U,
6290
+ clientId: S,
6262
6291
  redirectUri: w,
6263
- scope: g,
6292
+ scope: m,
6264
6293
  state: D,
6265
- nonce: E,
6266
- codeChallenge: O
6294
+ nonce: O,
6295
+ codeChallenge: M
6267
6296
  });
6268
- globalThis.location.assign(j.toString());
6297
+ globalThis.location.assign(q.toString());
6269
6298
  return;
6270
6299
  }
6271
6300
  throw new c(
@@ -6273,79 +6302,91 @@ function Wo(n) {
6273
6302
  "auth.signIn requires a browser context or mocks. Use NEETRU_ENV=dev or pass mocks.auth."
6274
6303
  );
6275
6304
  },
6276
- handleRedirectCallback: P,
6277
- completeSignIn: q,
6305
+ handleRedirectCallback: E,
6306
+ completeSignIn: j,
6278
6307
  // 3.7.0: exposto pro client.support renovar a sessão 1x num 401
6279
6308
  // invalid_end_user_token (mesma função do refresh proativo, com dedup).
6280
6309
  refreshTokens: y,
6281
6310
  getIdToken() {
6282
- let _ = a()?.getItem(e) ?? null;
6283
- return _ && ie(_) ? _ : null;
6311
+ let b = a()?.getItem(e) ?? null;
6312
+ return b && se(b) ? b : null;
6284
6313
  },
6285
6314
  async signOut() {
6286
- let m = a(), _ = m?.getItem(t) ?? null;
6287
- if (m && (m.removeItem(e), m.removeItem(t)), p(), o = null, _) {
6288
- let w = null;
6315
+ let g = a(), b = g?.getItem(t) ?? null, w = true;
6316
+ if (g)
6317
+ for (let S of [e, t])
6318
+ try {
6319
+ g.removeItem(S);
6320
+ } catch {
6321
+ w = false;
6322
+ }
6323
+ p(), o = null;
6324
+ let m = "skipped";
6325
+ if (b) {
6326
+ let S = null;
6289
6327
  try {
6290
- w = T();
6328
+ S = R();
6291
6329
  } catch {
6292
- w = null;
6330
+ S = null;
6293
6331
  }
6294
- !(w && await Kn(n.fetch, oe(n.baseUrl), w, [
6295
- { token: _, hint: "refresh_token" }
6296
- ])) && typeof console < "u" && console.warn(
6297
- "[neetru-sdk] signOut: a revoga\xE7\xE3o do refresh_token no servidor n\xE3o foi confirmada. A sess\xE3o local foi encerrada, mas o refresh_token pode seguir v\xE1lido at\xE9 expirar."
6332
+ S ? m = await Gn(
6333
+ n.fetch,
6334
+ ie(n.baseUrl),
6335
+ S,
6336
+ [{ token: b, hint: "refresh_token" }]
6337
+ ) ? "accepted" : "failed" : m = "not_configured", m !== "accepted" && typeof console < "u" && console.warn(
6338
+ "[neetru-sdk] signOut: a revoga\xE7\xE3o do refresh_token no servidor n\xE3o foi confirmada (" + m + "). 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."
6298
6339
  );
6299
6340
  }
6300
- u();
6341
+ return u(), { localSessionCleared: w, remoteRevocation: m };
6301
6342
  },
6302
6343
  getUser() {
6303
6344
  return d();
6304
6345
  },
6305
- onAuthStateChanged(m) {
6306
- r.add(m);
6346
+ onAuthStateChanged(g) {
6347
+ r.add(g);
6307
6348
  try {
6308
- m(d());
6349
+ g(d());
6309
6350
  } catch {
6310
6351
  }
6311
6352
  return () => {
6312
- r.delete(m);
6353
+ r.delete(g);
6313
6354
  };
6314
6355
  },
6315
- async verifyToken(m, _) {
6316
- if (!m || typeof m != "string")
6356
+ async verifyToken(g, b) {
6357
+ if (!g || typeof g != "string")
6317
6358
  throw new c("token_invalid_signature", "token must be a non-empty string");
6318
- let g = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), C = g, D = `${g}/api/v1/oauth/.well-known/jwks`, E = _?.jwksCacheTtlMs ?? Ue, R = _?.audience, O = lt(n.apiKey), A = R ?? n.oidcClientId ?? O?.keyId;
6319
- if (!A)
6359
+ let m = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), S = m, D = `${m}/api/v1/oauth/.well-known/jwks`, O = b?.jwksCacheTtlMs ?? Me, A = b?.audience, M = ut(n.apiKey), I = A ?? n.oidcClientId ?? M?.keyId;
6360
+ if (!I)
6320
6361
  throw new c(
6321
6362
  "invalid_config",
6322
6363
  "verifyToken requires an audience: provide oidcClientId/apiKey on the client or pass options.audience. Calling jwtVerify without an audience allows tokens issued for other OIDC clients to pass."
6323
6364
  );
6324
- let U = jo(D, E);
6365
+ let L = Ko(D, O);
6325
6366
  try {
6326
- let { payload: F } = await jwtVerify(m, U, {
6327
- issuer: C,
6328
- audience: A,
6367
+ let { payload: U } = await jwtVerify(g, L, {
6368
+ issuer: S,
6369
+ audience: I,
6329
6370
  algorithms: ["RS256"]
6330
6371
  });
6331
- return $o(F);
6332
- } catch (F) {
6333
- let j = F?.code ?? F?.name ?? "", L = F?.message ?? String(F);
6334
- throw j === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${L}`) : j === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${L}`) : j === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? L.includes('"aud"') || L.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${L}`) : L.includes('"iss"') || L.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${L}`) : new c("token_invalid_signature", `Token claim validation failed: ${L}`) : new c("token_invalid_signature", `Token verification failed: ${L}`);
6372
+ return zo(U);
6373
+ } catch (U) {
6374
+ let q = U?.code ?? U?.name ?? "", P = U?.message ?? String(U);
6375
+ throw q === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${P}`) : q === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${P}`) : q === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? P.includes('"aud"') || P.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${P}`) : P.includes('"iss"') || P.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${P}`) : new c("token_invalid_signature", `Token claim validation failed: ${P}`) : new c("token_invalid_signature", `Token verification failed: ${P}`);
6335
6376
  }
6336
6377
  }
6337
6378
  };
6338
6379
  }
6339
- function Bo(n = {}) {
6380
+ function Qo(n = {}) {
6340
6381
  let e = n.fetch ?? globalThis.fetch;
6341
6382
  if (typeof e != "function")
6342
6383
  throw new c(
6343
6384
  "invalid_config",
6344
6385
  "fetch is not available in this runtime. Pass `fetch` explicitly to createNeetruClient."
6345
6386
  );
6346
- let t = n.apiKey ?? qo();
6347
- wt({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6348
- let r = Fo(n.env), o = n.baseUrl ?? (r === "dev-local" ? mt : ft), i = pt(o, n.allowedHosts ?? []), s = Object.freeze({
6387
+ let t = n.apiKey ?? Bo();
6388
+ St({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6389
+ let r = Vo(n.env), o = n.baseUrl ?? (r === "dev-local" ? gt : ht), i = mt(o, n.allowedHosts ?? []), s = Object.freeze({
6349
6390
  apiKey: t,
6350
6391
  oidcClientId: n.oidcClientId,
6351
6392
  baseUrl: i,
@@ -6353,36 +6394,36 @@ function Bo(n = {}) {
6353
6394
  env: r,
6354
6395
  productId: n.productId,
6355
6396
  tenantId: n.tenantId
6356
- }), a = r === "dev" && !Ce(), l = n.mocks?.auth ?? (a ? new Ae({ ...tt }) : Wo(s)), d = n.mocks?.usage ?? (a ? new Ee() : Ut(s)), u = n.endUserAuth ?? l, p = n.mocks?.support ?? (a ? new Pe() : Wt(s, {
6397
+ }), a = W(r), l = n.mocks?.auth ?? (a ? new Ae({ ...rt }) : Ho(s)), d = n.mocks?.usage ?? (a ? new Ee() : qt(s)), u = n.endUserAuth ?? l, p = n.mocks?.support ?? (a ? new Pe() : Vt(s, {
6357
6398
  getEndUserToken: () => u.getIdToken(),
6358
6399
  // `refreshTokens` é opcional (MockAuth/mocks próprios omitem).
6359
6400
  refreshEndUserToken: (() => {
6360
- let P = u.refreshTokens;
6361
- return typeof P == "function" ? () => P.call(u) : void 0;
6401
+ let E = u.refreshTokens;
6402
+ return typeof E == "function" ? () => E.call(u) : void 0;
6362
6403
  })()
6363
- })), f = n.mocks?.entitlements ?? (a ? new De() : Dt()), h = n.mocks?.db ?? (X() === "react-native" ? Hn() : dn(s, n.db)), y = n.mocks?.webhooks ?? (a ? new Se() : hn(s)), S = n.mocks?.notifications ?? (a ? new Re() : _n(s)), x = n.mocks?.ai ?? (a ? new Ne() : Fn(s)), T = Object.freeze({
6404
+ })), f = n.mocks?.entitlements ?? (a ? new De() : xt()), h = n.mocks?.db ?? (Y() === "react-native" ? Xn() : pn(s, n.db)), y = n.mocks?.webhooks ?? (a ? new Te() : yn(s)), T = n.mocks?.notifications ?? (a ? new Ie() : vn(s)), x = n.mocks?.ai ?? (a ? new Ne() : $n(s)), R = Object.freeze({
6364
6405
  config: s,
6365
6406
  auth: l,
6366
- catalog: Et(s),
6407
+ catalog: Dt(s),
6367
6408
  entitlements: f,
6368
- telemetry: Ot(s),
6409
+ telemetry: Ut(s),
6369
6410
  usage: d,
6370
6411
  support: p,
6371
6412
  db: h,
6372
- checkout: un(s),
6413
+ checkout: fn(s),
6373
6414
  webhooks: y,
6374
- notifications: S,
6415
+ notifications: T,
6375
6416
  ai: x
6376
6417
  });
6377
- return n.endUserAuth && zn(T, n.endUserAuth), T;
6418
+ return n.endUserAuth && Jn(R, n.endUserAuth), R;
6378
6419
  }
6379
6420
  var Oe = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6380
- function aa(n = {}) {
6421
+ function ya(n = {}) {
6381
6422
  let e = globalThis;
6382
- return e[Oe] || (e[Oe] = Bo(n)), e[Oe];
6423
+ return e[Oe] || (e[Oe] = Qo(n)), e[Oe];
6383
6424
  }
6384
- function ca() {
6425
+ function _a() {
6385
6426
  delete globalThis[Oe];
6386
6427
  }
6387
6428
 
6388
- export { sa as __resetJwksCacheForTests, ca as __resetServerNeetruClientForTests, Bo as createNeetruClient, aa as getServerNeetruClient };
6429
+ export { ga as __resetJwksCacheForTests, _a as __resetServerNeetruClientForTests, Qo as createNeetruClient, ya as getServerNeetruClient };