@neetru/sdk 3.7.0 → 3.8.1

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 (73) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +66 -1
  3. package/dist/ai.cjs +221 -177
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +221 -177
  7. package/dist/auth.cjs +1051 -868
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +1048 -865
  11. package/dist/catalog.cjs +164 -97
  12. package/dist/catalog.d.cts +1 -1
  13. package/dist/catalog.d.ts +1 -1
  14. package/dist/catalog.mjs +164 -97
  15. package/dist/checkout.cjs +182 -115
  16. package/dist/checkout.d.cts +1 -1
  17. package/dist/checkout.d.ts +1 -1
  18. package/dist/checkout.mjs +181 -114
  19. package/dist/db-react.d.cts +1 -1
  20. package/dist/db-react.d.ts +1 -1
  21. package/dist/db.cjs +437 -345
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +455 -363
  25. package/dist/entitlements.cjs +17 -10
  26. package/dist/entitlements.d.cts +1 -1
  27. package/dist/entitlements.d.ts +1 -1
  28. package/dist/entitlements.mjs +17 -10
  29. package/dist/errors.cjs +15 -8
  30. package/dist/errors.d.cts +24 -3
  31. package/dist/errors.d.ts +24 -3
  32. package/dist/errors.mjs +14 -7
  33. package/dist/firestore-compat.d.cts +1 -1
  34. package/dist/firestore-compat.d.ts +1 -1
  35. package/dist/index.cjs +1544 -1190
  36. package/dist/index.d.cts +177 -3
  37. package/dist/index.d.ts +177 -3
  38. package/dist/index.mjs +1676 -1329
  39. package/dist/mobile.cjs +400 -181
  40. package/dist/mobile.d.cts +59 -4
  41. package/dist/mobile.d.ts +59 -4
  42. package/dist/mobile.mjs +400 -181
  43. package/dist/mocks.cjs +9 -2
  44. package/dist/mocks.d.cts +1 -1
  45. package/dist/mocks.d.ts +1 -1
  46. package/dist/mocks.mjs +9 -2
  47. package/dist/notifications.cjs +197 -130
  48. package/dist/notifications.d.cts +1 -1
  49. package/dist/notifications.d.ts +1 -1
  50. package/dist/notifications.mjs +196 -129
  51. package/dist/react.cjs +303 -282
  52. package/dist/react.d.cts +1 -1
  53. package/dist/react.d.ts +1 -1
  54. package/dist/react.mjs +295 -274
  55. package/dist/support.cjs +299 -229
  56. package/dist/support.d.cts +8 -4
  57. package/dist/support.d.ts +8 -4
  58. package/dist/support.mjs +298 -228
  59. package/dist/telemetry.cjs +234 -167
  60. package/dist/telemetry.d.cts +1 -1
  61. package/dist/telemetry.d.ts +1 -1
  62. package/dist/telemetry.mjs +234 -167
  63. package/dist/{types-Dx0IrOSF.d.ts → types-BYPk_3HR.d.ts} +104 -17
  64. package/dist/{types-Bx4kTLmk.d.cts → types-yv3EDKg2.d.cts} +104 -17
  65. package/dist/usage.cjs +183 -116
  66. package/dist/usage.d.cts +1 -1
  67. package/dist/usage.d.ts +1 -1
  68. package/dist/usage.mjs +183 -116
  69. package/dist/webhooks.cjs +215 -148
  70. package/dist/webhooks.d.cts +1 -1
  71. package/dist/webhooks.d.ts +1 -1
  72. package/dist/webhooks.mjs +212 -145
  73. package/package.json +2 -1
package/dist/auth.cjs CHANGED
@@ -3,15 +3,15 @@
3
3
  var jose = require('jose');
4
4
  var idb = require('idb');
5
5
 
6
- var Nn = Object.defineProperty;
7
- var B = (n, e) => () => (n && (e = n(n = 0)), e);
8
- var Ze = (n, e) => {
6
+ var Qn = Object.defineProperty;
7
+ var $ = (n, e) => () => (n && (e = n(n = 0)), e);
8
+ var ot = (n, e) => {
9
9
  for (var t in e)
10
- Nn(n, t, { get: e[t], enumerable: true });
10
+ Qn(n, t, { get: e[t], enumerable: true });
11
11
  };
12
12
 
13
13
  // src/errors.ts
14
- var c, V, P = B(() => {
14
+ var c, V, I = $(() => {
15
15
  c = class n extends Error {
16
16
  code;
17
17
  status;
@@ -25,18 +25,25 @@ var c, V, P = B(() => {
25
25
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
26
26
  */
27
27
  reason;
28
- constructor(e, t, r, o, i) {
29
- super(t), this.name = "NeetruError", this.code = e, this.status = r, this.requestId = o, this.reason = i, Object.setPrototypeOf(this, n.prototype);
28
+ /**
29
+ * 3.8.0: `x-correlation-id` da requisição que falhou. O SDK gera um UUID por
30
+ * chamada (ou usa o que o chamador passou) e manda no header; o Core grava o
31
+ * mesmo id nos logs/auditoria — cite-o ao abrir um ticket de suporte.
32
+ * `undefined` em erros que acontecem antes de qualquer requisição.
33
+ */
34
+ correlationId;
35
+ constructor(e, t, r, o, i, s) {
36
+ 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);
30
37
  }
31
38
  }, V = class n extends c {
32
- constructor(e, t, r, o) {
33
- super("auth_required", e, r, o, t), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, n.prototype);
39
+ constructor(e, t, r, o, i) {
40
+ super("auth_required", e, r, o, t, i), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, n.prototype);
34
41
  }
35
42
  };
36
43
  });
37
44
 
38
45
  // src/idempotency.ts
39
- function ct() {
46
+ function ht() {
40
47
  let n = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
41
48
  if (n && typeof n.randomUUID == "function")
42
49
  return n.randomUUID();
@@ -45,80 +52,164 @@ function ct() {
45
52
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
46
53
  );
47
54
  }
48
- var lt = B(() => {
49
- P();
55
+ var gt = $(() => {
56
+ I();
57
+ });
58
+
59
+ // src/correlation.ts
60
+ function _t(n) {
61
+ return typeof n == "string" && n.length > 0 && n.length <= 128 && tr.test(n);
62
+ }
63
+ function nr() {
64
+ let n = globalThis.crypto;
65
+ try {
66
+ if (n && typeof n.randomUUID == "function") return n.randomUUID();
67
+ } catch {
68
+ }
69
+ let e = new Uint8Array(16), t = false;
70
+ try {
71
+ n && typeof n.getRandomValues == "function" && (n.getRandomValues(e), t = !0);
72
+ } catch {
73
+ t = false;
74
+ }
75
+ if (!t)
76
+ for (let o = 0; o < e.length; o++) e[o] = Math.floor(Math.random() * 256);
77
+ e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
78
+ let r = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
79
+ return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
80
+ }
81
+ function ae(n, e) {
82
+ let t, r = {};
83
+ for (let [i, s] of Object.entries(n)) {
84
+ if (i.toLowerCase() === yt) {
85
+ _t(s) && (t = s);
86
+ continue;
87
+ }
88
+ r[i] = s;
89
+ }
90
+ let o = t ?? (_t(e) ? e : void 0) ?? nr();
91
+ return r[yt] = o, { headers: r, correlationId: o };
92
+ }
93
+ var yt, tr, Me = $(() => {
94
+ yt = "x-correlation-id", tr = /^[A-Za-z0-9._:\-]+$/;
95
+ });
96
+
97
+ // src/server-only-key.ts
98
+ function X() {
99
+ try {
100
+ let n = globalThis.navigator;
101
+ if (n && n.product === "ReactNative") return "react-native";
102
+ } catch {
103
+ }
104
+ try {
105
+ let n = globalThis;
106
+ if (typeof n.window < "u" && typeof n.document < "u") return "browser";
107
+ } catch {
108
+ }
109
+ return null;
110
+ }
111
+ function bt(n, e) {
112
+ let t = rr[n];
113
+ 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();
114
+ }
115
+ function wt(n) {
116
+ if (!n.hasApiKey) return;
117
+ let e = n.runtime === void 0 ? X() : n.runtime;
118
+ if (e) {
119
+ if (n.strict)
120
+ throw new c("server_only_key", bt(e, true), void 0, void 0, e);
121
+ if (!vt) {
122
+ vt = true;
123
+ try {
124
+ typeof console < "u" && typeof console.warn == "function" && console.warn(bt(e, !1));
125
+ } catch {
126
+ }
127
+ }
128
+ }
129
+ }
130
+ var rr, vt, qe = $(() => {
131
+ I();
132
+ rr = {
133
+ browser: "no navegador",
134
+ "react-native": "num app React Native"
135
+ };
136
+ vt = false;
50
137
  });
51
138
 
52
139
  // src/http.ts
53
- var X = {};
54
- Ze(X, {
55
- checkCoreVersionCompat: () => ie,
140
+ var Y = {};
141
+ ot(Y, {
142
+ checkCoreVersionCompat: () => ce,
56
143
  httpRequest: () => v,
57
- statusToCode: () => se
144
+ statusToCode: () => le
58
145
  });
59
- function xe(n) {
146
+ function Fe(n) {
60
147
  return n.split("+")[0] ?? n;
61
148
  }
62
- function Fn(n, e) {
63
- let t = xe(n).split(".").map(Number), r = xe(e).split(".").map(Number), o = Math.max(t.length, r.length);
149
+ function ir(n, e) {
150
+ let t = Fe(n).split(".").map(Number), r = Fe(e).split(".").map(Number), o = Math.max(t.length, r.length);
64
151
  for (let i = 0; i < o; i++) {
65
152
  let s = t[i] ?? 0, a = r[i] ?? 0;
66
153
  if (s !== a) return s - a;
67
154
  }
68
155
  return 0;
69
156
  }
70
- function ht() {
157
+ function Ct() {
71
158
  try {
72
- return "3.7.0";
159
+ return "3.8.1";
73
160
  } catch {
74
161
  return;
75
162
  }
76
163
  }
77
- function jn() {
78
- let n = ht();
164
+ function sr() {
165
+ let n = Ct();
79
166
  return n ? parseInt(n.split(".")[0] ?? "3", 10) : 3;
80
167
  }
81
- function ie(n) {
168
+ function ce(n) {
82
169
  if (!n) return;
83
- let e = jn(), t = qn[e];
170
+ let e = sr(), t = or[e];
84
171
  if (!t) return;
85
- let r = xe(n);
86
- if (Fn(r, t) < 0) {
172
+ let r = Fe(n);
173
+ if (ir(r, t) < 0) {
87
174
  let o = `${e}:${r}`;
88
- dt.has(o) || (dt.add(o), console.warn(
175
+ kt.has(o) || (kt.add(o), console.warn(
89
176
  `[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.`
90
177
  ));
91
178
  }
92
179
  }
93
- function ut(n) {
180
+ function ar() {
181
+ let n = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
182
+ 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;
183
+ }
184
+ function St(n) {
94
185
  let e = 200 * Math.pow(4, n), t = e * 0.2 * (Math.random() * 2 - 1);
95
186
  return Math.max(50, Math.round(e + t));
96
187
  }
97
- function zn(n) {
188
+ function pr(n) {
98
189
  if (!n) return null;
99
190
  let e = Number(n);
100
- if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), pt);
191
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), Tt);
101
192
  let t = Date.parse(n);
102
193
  if (Number.isFinite(t)) {
103
194
  let r = t - Date.now();
104
- if (r > 0) return Math.min(r, pt);
195
+ if (r > 0) return Math.min(r, Tt);
105
196
  }
106
197
  return null;
107
198
  }
108
- function ft(n) {
199
+ function Rt(n) {
109
200
  return new Promise((e) => setTimeout(e, n));
110
201
  }
111
- function se(n) {
202
+ function le(n) {
112
203
  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";
113
204
  }
114
- function Kn(n, e, t) {
205
+ function fr(n, e, t) {
115
206
  let r = n.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, i = new URL(`${r}${o}`);
116
207
  if (t)
117
208
  for (let [s, a] of Object.entries(t))
118
209
  a !== void 0 && i.searchParams.set(s, String(a));
119
210
  return i.toString();
120
211
  }
121
- async function mt(n) {
212
+ async function It(n) {
122
213
  let e = await n.text();
123
214
  if (e)
124
215
  try {
@@ -128,97 +219,103 @@ async function mt(n) {
128
219
  }
129
220
  }
130
221
  async function v(n, e) {
131
- let t = e.method ?? "GET", r = Kn(n.baseUrl, e.path, e.query), o = Bn.has(t) ? Wn : $n, i = e.retries ?? o, s = {
132
- accept: "application/json",
133
- ...e.headers
134
- }, a = ht();
135
- if (a && (s["x-neetru-sdk-version"] = a), e.requireAuth) {
222
+ 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(
223
+ { accept: "application/json", ...e.headers },
224
+ e.correlationId
225
+ ), l = Ct();
226
+ if (l && (s["x-neetru-sdk-version"] = l), e.requireAuth) {
136
227
  if (!n.apiKey)
137
- throw new c(
138
- "missing_api_key",
139
- "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
140
- );
228
+ throw new c("missing_api_key", ar());
141
229
  s.authorization = `Bearer ${n.apiKey}`;
142
230
  }
143
231
  if (e.idempotencyKey) {
144
- let p = typeof e.idempotencyKey == "string" ? e.idempotencyKey : ct();
145
- s["idempotency-key"] = p;
146
- }
147
- let l = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
148
- l !== void 0 && (s["content-type"] = "application/json");
149
- let d = null, u = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
150
- for (let p = 0; p <= i; p++) {
151
- if (u != null && Date.now() >= u)
152
- throw d ?? new c("network_error", "Deadline excedido antes de completar a request");
153
- let f = { method: t, headers: s };
154
- l !== void 0 && (f.body = l);
155
- let g = u != null ? Math.max(1, Math.min(3e4, u - Date.now())) : 3e4;
156
- f.signal = AbortSignal.timeout(g);
157
- let _;
232
+ let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : ht();
233
+ s["idempotency-key"] = f;
234
+ }
235
+ let d = e.body !== void 0 && t !== "GET" && t !== "DELETE" ? JSON.stringify(e.body) : void 0;
236
+ d !== void 0 && (s["content-type"] = "application/json");
237
+ let u = null, p = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
238
+ for (let f = 0; f <= i; f++) {
239
+ if (p != null && Date.now() >= p)
240
+ throw u ?? new c(
241
+ "network_error",
242
+ "Deadline excedido antes de completar a request",
243
+ void 0,
244
+ void 0,
245
+ void 0,
246
+ a
247
+ );
248
+ let h = { method: t, headers: s };
249
+ d !== void 0 && (h.body = d);
250
+ let y = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
251
+ h.signal = AbortSignal.timeout(y);
252
+ let S;
158
253
  try {
159
- _ = await n.fetch(r, f);
160
- } catch (m) {
161
- let T = m instanceof DOMException && m.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${m instanceof Error ? m.message : "fetch failed"}`;
162
- if (d = new c("network_error", T), p < i) {
163
- let A = ut(p);
164
- if (u == null || Date.now() + A < u) {
165
- await ft(A);
254
+ S = await n.fetch(r, h);
255
+ } catch (g) {
256
+ let C = g instanceof DOMException && g.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${g instanceof Error ? g.message : "fetch failed"}`;
257
+ if (u = new c("network_error", C, void 0, void 0, void 0, a), f < i) {
258
+ let D = St(f);
259
+ if (p == null || Date.now() + D < p) {
260
+ await Rt(D);
166
261
  continue;
167
262
  }
168
263
  }
169
- throw d;
264
+ throw u;
170
265
  }
171
- let M = _.headers.get("x-request-id") ?? _.headers.get("x-correlation-id") ?? void 0;
172
- if (_.ok) {
173
- let m = _.headers.get("x-neetru-version");
174
- return m && ie(m), await mt(_);
266
+ let x = S.headers.get("x-request-id") ?? S.headers.get("x-correlation-id") ?? void 0;
267
+ if (S.ok) {
268
+ let g = S.headers.get("x-neetru-version");
269
+ return g && ce(g), await It(S);
175
270
  }
176
- let R = await mt(_), N = se(_.status), C = `HTTP ${_.status}`, $;
177
- if (R && typeof R == "object") {
178
- let m = R.error;
179
- typeof m == "string" ? C = m : m && typeof m == "object" ? (typeof m.code == "string" && (N = m.code), typeof m.message == "string" && (C = m.message), typeof m.reason == "string" && ($ = m.reason)) : (typeof R.code == "string" && (N = R.code), typeof R.message == "string" && (C = R.message)), typeof R.reason == "string" && ($ = R.reason);
271
+ let T = await It(S), P = le(S.status), q = `HTTP ${S.status}`, m;
272
+ if (T && typeof T == "object") {
273
+ let g = T.error;
274
+ 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);
180
275
  }
181
- if (_.status === 410) {
182
- let m = _.headers.get("x-neetru-replacement");
183
- C === `HTTP ${_.status}` && (C = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), m && !C.includes(m) && (C += ` Substituto: ${m}.`);
276
+ if (S.status === 410) {
277
+ let g = S.headers.get("x-neetru-replacement");
278
+ 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}.`);
184
279
  }
185
- let h = new c(N, C, _.status, M, $);
186
- if (d = h, Vn.has(N) && p < i) {
187
- let T = zn(_.headers.get("retry-after")) ?? ut(p);
188
- if (u == null || Date.now() + T < u) {
189
- await ft(T);
280
+ let _ = new c(P, q, S.status, x, m, a);
281
+ if (u = _, ur.has(P) && f < i) {
282
+ let C = pr(S.headers.get("retry-after")) ?? St(f);
283
+ if (p == null || Date.now() + C < p) {
284
+ await Rt(C);
190
285
  continue;
191
286
  }
192
287
  }
193
- throw h;
288
+ throw _;
194
289
  }
195
- throw d ?? new c("unknown", "unexpected httpRequest exit");
290
+ throw u ?? new c("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
196
291
  }
197
- var qn, dt, Wn, $n, Bn, Vn, pt, U = B(() => {
198
- P();
199
- lt();
200
- qn = {
292
+ var or, kt, cr, lr, dr, ur, Tt, M = $(() => {
293
+ I();
294
+ gt();
295
+ Me();
296
+ qe();
297
+ or = {
201
298
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
202
299
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
203
300
  3: "2026.05.1"
204
301
  };
205
- dt = /* @__PURE__ */ new Set();
206
- Wn = 2, $n = 0, Bn = /* @__PURE__ */ new Set(["GET", "HEAD"]), Vn = /* @__PURE__ */ new Set([
302
+ kt = /* @__PURE__ */ new Set();
303
+ cr = 2, lr = 0, dr = /* @__PURE__ */ new Set(["GET", "HEAD"]), ur = /* @__PURE__ */ new Set([
207
304
  "rate_limited",
208
305
  "server_error",
209
306
  "network_error"
210
307
  ]);
211
- pt = 6e4;
308
+ Tt = 6e4;
212
309
  });
213
310
 
214
311
  // src/db-errors.ts
215
- var ir, y, Y = B(() => {
216
- P();
217
- ir = /* @__PURE__ */ new Set([
312
+ var Ir, b, Z = $(() => {
313
+ I();
314
+ Ir = /* @__PURE__ */ new Set([
218
315
  "db_unavailable",
219
316
  "db_conflict",
220
317
  "db_timeout"
221
- ]), y = class n extends c {
318
+ ]), b = class n extends c {
222
319
  /** Código de erro fechado — específico de DB. */
223
320
  code;
224
321
  /**
@@ -232,16 +329,16 @@ var ir, y, Y = B(() => {
232
329
  */
233
330
  dbId;
234
331
  constructor(e, t, r) {
235
- super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = ir.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
332
+ super(e, t), this.name = "NeetruDbError", this.code = e, this.retryable = Ir.has(e), this.dbId = r, Object.setPrototypeOf(this, n.prototype);
236
333
  }
237
334
  };
238
335
  });
239
336
 
240
337
  // src/db/sql/resilient-pool.ts
241
- function ye(n) {
242
- return typeof n == "object" && n !== null && n[We] === true;
338
+ function ve(n) {
339
+ return typeof n == "object" && n !== null && n[He] === true;
243
340
  }
244
- function Cr(n) {
341
+ function Qr(n) {
245
342
  let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
246
343
  if (e === "ECONNREFUSED" || e === "ETIMEDOUT" || e === "ENOTFOUND" || e === "EHOSTUNREACH" || e === "EAI_AGAIN")
247
344
  return true;
@@ -253,67 +350,84 @@ function Cr(n) {
253
350
  let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
254
351
  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"));
255
352
  }
256
- function $e(n) {
353
+ function Gt(n) {
354
+ let e = n && typeof n == "object" && "code" in n ? n.code : void 0;
355
+ if (typeof e == "string" && Gr.has(e.toUpperCase()))
356
+ return true;
357
+ let r = (n instanceof Error ? n.message : typeof n == "string" ? n : "").toLowerCase();
358
+ return r.length === 0 ? false : r.includes("password authentication failed") || r.includes("sasl authentication failed");
359
+ }
360
+ function Jr(n) {
361
+ return Qr(n) || Gt(n);
362
+ }
363
+ function Qe(n) {
257
364
  let e = { current: n }, t = null, r = {
258
- __neetruSwapInner(l) {
259
- let d = e.current;
260
- return e.current = l, d;
365
+ __neetruSwapInner(u) {
366
+ let p = e.current;
367
+ return e.current = u, p;
261
368
  },
262
369
  __neetruGetInner() {
263
370
  return e.current;
264
371
  },
265
- __neetruSetReLease(l) {
266
- t = l;
372
+ __neetruSetReLease(u) {
373
+ t = u;
267
374
  }
268
- }, o = (l, d) => l.query(...d), i = (...l) => l.length > 0 && typeof l[l.length - 1] == "function" ? o(e.current, l) : (async () => {
375
+ }, o = (u, p, f) => p[u](
376
+ ...f
377
+ ), i = (u, p) => (...f) => f.length > 0 && typeof f[f.length - 1] == "function" ? o(u, e.current, f) : (async () => {
269
378
  try {
270
- return await o(e.current, l);
271
- } catch (d) {
272
- let u = t;
273
- if (u === null || !Cr(d))
274
- throw d;
379
+ return await o(u, e.current, f);
380
+ } catch (h) {
381
+ let y = t;
382
+ if (y === null || !p(h))
383
+ throw h;
275
384
  try {
276
- await u();
385
+ await y();
277
386
  } catch {
278
- throw d;
387
+ throw h;
279
388
  }
280
- return await o(e.current, l);
389
+ return await o(u, e.current, f);
281
390
  }
282
- })(), s = Object.create(Object.getPrototypeOf(n));
283
- return new Proxy(s, {
284
- get(l, d) {
285
- if (d === We) return true;
286
- if (d === "__neetruSwapInner") return r.__neetruSwapInner;
287
- if (d === "__neetruGetInner") return r.__neetruGetInner;
288
- if (d === "__neetruSetReLease") return r.__neetruSetReLease;
289
- if (d === "query") return i;
290
- if (d === "constructor")
391
+ })(), s = i("query", Jr), a = i("connect", Gt), l = Object.create(Object.getPrototypeOf(n));
392
+ return new Proxy(l, {
393
+ get(u, p) {
394
+ if (p === He) return true;
395
+ if (p === "__neetruSwapInner") return r.__neetruSwapInner;
396
+ if (p === "__neetruGetInner") return r.__neetruGetInner;
397
+ if (p === "__neetruSetReLease") return r.__neetruSetReLease;
398
+ if (p === "query") return s;
399
+ if (p === "connect") {
400
+ let y = e.current;
401
+ return typeof y.connect == "function" ? a : y.connect;
402
+ }
403
+ if (p === "constructor")
291
404
  return e.current.constructor;
292
- let u = e.current, p = Reflect.get(u, d, u);
293
- return typeof p == "function" ? p.bind(u) : p;
405
+ let f = e.current, h = Reflect.get(f, p, f);
406
+ return typeof h == "function" ? h.bind(f) : h;
294
407
  }
295
408
  });
296
409
  }
297
- var We, Be = B(() => {
298
- We = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
410
+ var He, Gr, Ge = $(() => {
411
+ He = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
412
+ Gr = /* @__PURE__ */ new Set(["28P01", "28000"]);
299
413
  });
300
414
 
301
415
  // src/db/sql/lease.ts
302
- function Pr(n, e) {
416
+ function Yr(n, e) {
303
417
  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;
304
418
  }
305
- function Er(n) {
306
- if (n instanceof y) return n;
419
+ function Zr(n) {
420
+ if (n instanceof b) return n;
307
421
  let e = n instanceof Error ? n.message : String(n), t = n instanceof Error ? n.code : void 0;
308
- return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new y(
422
+ return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new b(
309
423
  "db_unavailable",
310
424
  `Pool connection failed (${t}): ${e}`
311
- ) : e.includes("statement timeout") || e.includes("lock timeout") ? new y("db_timeout", `Query timeout: ${e}`) : e.includes("40001") || e.includes("40P01") || e.includes("deadlock") ? new y("db_conflict", `Transaction conflict: ${e}`) : e.includes("42501") || e.toLowerCase().includes("permission denied") ? new y("db_permission_denied", `Permission denied: ${e}`) : new y("db_unavailable", `Database error: ${e}`);
425
+ ) : 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}`);
312
426
  }
313
- var Ar, J, ne, Mt = B(() => {
314
- Y();
315
- Be();
316
- Ar = 0.8, J = 3e4, ne = class {
427
+ var Xr, J, re, Jt = $(() => {
428
+ Z();
429
+ Ge();
430
+ Xr = 0.8, J = 3e4, re = class {
317
431
  /**
318
432
  * Lease atual. `null` no modo LAZY antes da 1ª query (o 1º lease é adiado —
319
433
  * ver `_ensureInitialLease`). Após a 1ª aquisição, sempre não-nulo.
@@ -353,7 +467,7 @@ var Ar, J, ne, Mt = B(() => {
353
467
  isolationLevel: t.isolationLevel
354
468
  }) : await this._orm.transaction(e);
355
469
  } catch (r) {
356
- throw Er(r);
470
+ throw Zr(r);
357
471
  }
358
472
  }
359
473
  async close() {
@@ -376,7 +490,7 @@ var Ar, J, ne, Mt = B(() => {
376
490
  if (!Number.isFinite(e)) return J;
377
491
  let t = this._deps.now(), r = e - t;
378
492
  if (r <= 0) return J;
379
- let o = r * (1 - Ar);
493
+ let o = r * (1 - Xr);
380
494
  return Math.max(J, Math.round(o));
381
495
  }
382
496
  _scheduleRenewal() {
@@ -405,7 +519,7 @@ var Ar, J, ne, Mt = B(() => {
405
519
  this._renewalTimer = setTimeout(() => {
406
520
  this._doRenew();
407
521
  }, J), console.warn(
408
- `[SqlLeaseManager] renova\xE7\xE3o E emiss\xE3o de lease novo falharam; re-tentando em ${J}ms (cert TLS ef\xEAmero do servidor expira ~15min ap\xF3s o \xFAltimo swap):`,
522
+ `[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):`,
409
523
  t instanceof Error ? t.message : t
410
524
  );
411
525
  return;
@@ -417,10 +531,13 @@ var Ar, J, ne, Mt = B(() => {
417
531
  /**
418
532
  * Recuperação REATIVA: chamado pelo wrapper resiliente (`resilient-pool.ts`)
419
533
  * quando uma query plana falha num erro de ESTABELECIMENTO de conexão (cert
420
- * TLS efêmero do servidor expirado no meio de uma request, ou timer de
421
- * renovação que não disparou). Emite um lease NOVO e faz o swap do pool interno
422
- * do wrapper com
423
- * o certificado fresco; o wrapper então re-tenta a query 1x no pool novo.
534
+ * TLS de cliente mTLS do lease expirado no meio de uma request, ou timer de
535
+ * renovação que não disparou) ou de AUTENTICAÇÃO (senha rotacionada por
536
+ * `rotate-credentials` antes do próximo renew — SQLSTATE 28P01/28000, ou o
537
+ * 08P01+SASL do PgBouncer; também no `connect()` de uma transação). Emite um
538
+ * lease NOVO e faz o swap do pool interno do wrapper com a credencial e o
539
+ * certificado frescos (o pool velho é drenado com `end()`); o wrapper então
540
+ * re-tenta a operação 1x no pool novo.
424
541
  *
425
542
  * Vai DIRETO ao lease novo (sem `leaseId`) — a conexão falhou porque o
426
543
  * certificado do lease atual está ruim, então `renew` (que depende do lease
@@ -436,7 +553,7 @@ var Ar, J, ne, Mt = B(() => {
436
553
  */
437
554
  async _reactiveReLease() {
438
555
  if (this._closed)
439
- throw new y(
556
+ throw new b(
440
557
  "db_unavailable",
441
558
  "SqlLeaseManager foi fechado \u2014 re-lease reativo abortado."
442
559
  );
@@ -473,30 +590,30 @@ var Ar, J, ne, Mt = B(() => {
473
590
  */
474
591
  async _ensureInitialLease() {
475
592
  if (this._closed)
476
- throw new y(
593
+ throw new b(
477
594
  "db_unavailable",
478
595
  "SqlLeaseManager foi fechado \u2014 aquisi\xE7\xE3o de lease inicial abortada."
479
596
  );
480
597
  if (this._lease)
481
- return ye(this._pool) ? this._pool.__neetruGetInner() : this._pool;
598
+ return ve(this._pool) ? this._pool.__neetruGetInner() : this._pool;
482
599
  if (this._initInFlight !== null) return this._initInFlight;
483
600
  let e = (async () => {
484
601
  let t;
485
602
  try {
486
603
  t = this._deps.database !== void 0 ? await this._deps.fetchLease({ database: this._deps.database }) : await this._deps.fetchLease();
487
604
  } catch (o) {
488
- if (o instanceof y) throw o;
605
+ if (o instanceof b) throw o;
489
606
  let i = o instanceof Error ? o.message : String(o);
490
- throw new y("db_unavailable", `Falha ao obter lease inicial: ${i}`);
607
+ throw new b("db_unavailable", `Falha ao obter lease inicial: ${i}`);
491
608
  }
492
609
  let r;
493
610
  try {
494
611
  r = this._deps.createPool(t);
495
612
  } catch (o) {
496
613
  let i = o instanceof Error ? o.message : String(o);
497
- throw new y("db_unavailable", `Falha ao abrir pool: ${i}`);
614
+ throw new b("db_unavailable", `Falha ao abrir pool: ${i}`);
498
615
  }
499
- return ye(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
616
+ return ve(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
500
617
  }) : this._pool = r, this._lease = t, this._scheduleRenewal(), r;
501
618
  })();
502
619
  this._initInFlight = e;
@@ -512,12 +629,12 @@ var Ar, J, ne, Mt = B(() => {
512
629
  * Exposto como método protegido para testes.
513
630
  */
514
631
  async _swapPool(e) {
515
- if (!Pr(this._lease, e)) {
632
+ if (!Yr(this._lease, e)) {
516
633
  this._lease = e;
517
634
  return;
518
635
  }
519
636
  let t = this._deps.createPool(e);
520
- if (ye(this._pool)) {
637
+ if (ve(this._pool)) {
521
638
  let i = this._pool.__neetruSwapInner(t);
522
639
  this._lease = e, i.end().catch(() => {
523
640
  });
@@ -530,7 +647,7 @@ var Ar, J, ne, Mt = B(() => {
530
647
  // ─── Helpers ───────────────────────────────────────────────────────────────
531
648
  _assertOpen() {
532
649
  if (this._closed)
533
- throw new y(
650
+ throw new b(
534
651
  "db_unavailable",
535
652
  "SqlLeaseManager foi fechado \u2014 chame close() apenas no shutdown."
536
653
  );
@@ -539,29 +656,29 @@ var Ar, J, ne, Mt = B(() => {
539
656
  });
540
657
 
541
658
  // src/db/sql/sql-client.ts
542
- var zt = {};
543
- Ze(zt, {
544
- DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => Bt,
545
- DEFAULT_POOL_IDLE_MS: () => $t,
546
- DEFAULT_POOL_MAX: () => Wt,
547
- LEASE_ENDPOINT: () => qt,
548
- LEASE_RENEW_ENDPOINT: () => Ft,
549
- createDrizzleHandle: () => Or,
550
- createHttpLeaseFetcher: () => jt,
551
- createPgPool: () => xr,
552
- createSqlClientFromConfig: () => Ur,
553
- createSqlClientWithDeps: () => Vt,
554
- resolvePoolTuning: () => ze
659
+ var on = {};
660
+ ot(on, {
661
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => nn,
662
+ DEFAULT_POOL_IDLE_MS: () => tn,
663
+ DEFAULT_POOL_MAX: () => en,
664
+ LEASE_ENDPOINT: () => Xt,
665
+ LEASE_RENEW_ENDPOINT: () => Yt,
666
+ createDrizzleHandle: () => ro,
667
+ createHttpLeaseFetcher: () => Zt,
668
+ createPgPool: () => no,
669
+ createSqlClientFromConfig: () => io,
670
+ createSqlClientWithDeps: () => rn,
671
+ resolvePoolTuning: () => Xe
555
672
  });
556
- function Dr(n) {
673
+ function eo(n) {
557
674
  return n === "workspace" ? "staging" : n === "prod" ? "production" : "dev-local";
558
675
  }
559
- function jt(n) {
676
+ function Zt(n) {
560
677
  return async (e) => {
561
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = !!e?.leaseId, o = r ? Ft : qt, i;
678
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = !!e?.leaseId, o = r ? Yt : Xt, i;
562
679
  r ? i = { leaseId: e.leaseId } : (i = {
563
680
  productId: n.productId ?? "",
564
- environment: Dr(n.env ?? "prod")
681
+ environment: eo(n.env ?? "prod")
565
682
  }, e?.database !== void 0 && (i.database = e.database));
566
683
  let s;
567
684
  try {
@@ -577,32 +694,32 @@ function jt(n) {
577
694
  let l = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof c ? a.reason : void 0;
578
695
  if (u === "suspended" || u === "archived" || u === "revoked") {
579
696
  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";
580
- throw new y(
697
+ throw new b(
581
698
  "db_suspended",
582
699
  `Falha ao ${l} lease SQL: ${p} (reason=${u}).`
583
700
  );
584
701
  }
585
- throw new y(
702
+ throw new b(
586
703
  "db_unavailable",
587
704
  `Falha ao ${l} lease SQL: ${d}`
588
705
  );
589
706
  }
590
- return Nr(s);
707
+ return to(s);
591
708
  };
592
709
  }
593
- function Nr(n) {
710
+ function to(n) {
594
711
  if (!n || typeof n != "object")
595
- throw new y("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
712
+ throw new b("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
596
713
  let t = n.lease;
597
714
  if (!t || typeof t != "object")
598
- throw new y(
715
+ throw new b(
599
716
  "db_unavailable",
600
717
  'Resposta de lease inv\xE1lida: campo "lease" ausente ou n\xE3o \xE9 objeto. O Core retorna { kind, lease: { leaseId, host, ... } }.'
601
718
  );
602
719
  let r = t;
603
720
  function o(i, s) {
604
721
  if (typeof r[i] !== s)
605
- throw new y(
722
+ throw new b(
606
723
  "db_unavailable",
607
724
  `Campo obrigat\xF3rio "${i}" ausente ou tipo inv\xE1lido na resposta de lease.`
608
725
  );
@@ -622,22 +739,22 @@ function Nr(n) {
622
739
  expiresAt: o("expiresAt", "string")
623
740
  };
624
741
  }
625
- function Ve(n, e, t, r) {
742
+ function Je(n, e, t, r) {
626
743
  let o = typeof process < "u" ? process.env?.[n] : void 0;
627
744
  if (o === void 0 || o.trim() === "") return e;
628
745
  let i = Number.parseInt(o.trim(), 10);
629
746
  return !Number.isFinite(i) || i < t || i > r ? e : i;
630
747
  }
631
- function ze() {
748
+ function Xe() {
632
749
  return {
633
750
  // Teto 100: bem abaixo do `max_client_conn = 500` do PgBouncer, com folga
634
751
  // para múltiplas instâncias do app dividirem o mesmo front-door.
635
- max: Ve("NEETRU_DB_POOL_MAX", Wt, 1, 100),
752
+ max: Je("NEETRU_DB_POOL_MAX", en, 1, 100),
636
753
  // Teto 15min = janela do cert; piso 1s.
637
- idleTimeoutMillis: Ve("NEETRU_DB_POOL_IDLE_MS", $t, 1e3, 9e5),
638
- connectionTimeoutMillis: Ve(
754
+ idleTimeoutMillis: Je("NEETRU_DB_POOL_IDLE_MS", tn, 1e3, 9e5),
755
+ connectionTimeoutMillis: Je(
639
756
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
640
- Bt,
757
+ nn,
641
758
  1e3,
642
759
  12e4
643
760
  ),
@@ -645,7 +762,7 @@ function ze() {
645
762
  keepAliveInitialDelayMillis: 1e4
646
763
  };
647
764
  }
648
- async function xr(n) {
765
+ async function no(n) {
649
766
  let { Pool: e } = await import(
650
767
  /* webpackIgnore: true */
651
768
  'pg'
@@ -662,17 +779,17 @@ async function xr(n) {
662
779
  user: n.user,
663
780
  password: n.password,
664
781
  ssl: t,
665
- ...ze()
782
+ ...Xe()
666
783
  });
667
784
  }
668
- async function Or(n, e) {
785
+ async function ro(n, e) {
669
786
  let { drizzle: t } = await import(
670
787
  /* webpackIgnore: true */
671
788
  'drizzle-orm/node-postgres'
672
789
  );
673
790
  return t(n, { schema: e });
674
791
  }
675
- function Lr(n, e) {
792
+ function oo(n, e) {
676
793
  let t = null, r = null, o = () => t ? Promise.resolve(t) : (r || (r = e().then((s) => (t = s, r = null, s)).catch((s) => {
677
794
  throw r = null, s;
678
795
  })), r), i = {
@@ -688,52 +805,52 @@ function Lr(n, e) {
688
805
  };
689
806
  return n && Object.setPrototypeOf(i, n), i;
690
807
  }
691
- async function Vt(n, e) {
808
+ async function rn(n, e) {
692
809
  let t = e?.database !== void 0 ? { ...n, database: e.database } : n;
693
810
  if (t.lazy) {
694
- let l = null, d = Lr(t.poolPrototype ?? null, () => {
811
+ let l = null, d = oo(t.poolPrototype ?? null, () => {
695
812
  if (!l)
696
- throw new y("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
813
+ throw new b("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
697
814
  return l._ensureInitialLease();
698
- }), u = $e(d), p;
815
+ }), u = Qe(d), p;
699
816
  try {
700
817
  p = t.createDrizzle(u, t.schema);
701
- } catch (g) {
702
- let _ = g instanceof Error ? g.message : String(g);
703
- throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${_}`);
818
+ } catch (h) {
819
+ let y = h instanceof Error ? h.message : String(h);
820
+ throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${y}`);
704
821
  }
705
- let f = new ne(null, u, p, t);
822
+ let f = new re(null, u, p, t);
706
823
  return l = f, u.__neetruSetReLease(() => f._reactiveReLease()), f;
707
824
  }
708
825
  let r;
709
826
  try {
710
827
  e?.database !== void 0 ? r = await t.fetchLease({ database: e.database }) : r = await t.fetchLease();
711
828
  } catch (l) {
712
- if (l instanceof y) throw l;
829
+ if (l instanceof b) throw l;
713
830
  let d = l instanceof Error ? l.message : String(l);
714
- throw new y("db_unavailable", `Falha ao obter lease inicial: ${d}`);
831
+ throw new b("db_unavailable", `Falha ao obter lease inicial: ${d}`);
715
832
  }
716
833
  let o;
717
834
  try {
718
835
  o = t.createPool(r);
719
836
  } catch (l) {
720
837
  let d = l instanceof Error ? l.message : String(l);
721
- throw new y("db_unavailable", `Falha ao abrir pool: ${d}`);
838
+ throw new b("db_unavailable", `Falha ao abrir pool: ${d}`);
722
839
  }
723
- let i = $e(o), s;
840
+ let i = Qe(o), s;
724
841
  try {
725
842
  s = t.createDrizzle(i, t.schema);
726
843
  } catch (l) {
727
844
  await o.end().catch(() => {
728
845
  });
729
846
  let d = l instanceof Error ? l.message : String(l);
730
- throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
847
+ throw new b("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
731
848
  }
732
- let a = new ne(r, i, s, t);
849
+ let a = new re(r, i, s, t);
733
850
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
734
851
  }
735
- async function Ur(n, e, t) {
736
- let r = jt(n), o, i;
852
+ async function io(n, e, t) {
853
+ let r = Zt(n), o, i;
737
854
  try {
738
855
  o = await import(
739
856
  /* webpackIgnore: true */
@@ -743,13 +860,13 @@ async function Ur(n, e, t) {
743
860
  'drizzle-orm/node-postgres'
744
861
  );
745
862
  } catch (d) {
746
- throw new y(
863
+ throw new b(
747
864
  "db_unavailable",
748
865
  `[client.db.sql] requer pg + drizzle-orm como peerDependencies do servidor. Instale: npm install pg drizzle-orm. (${d.message})`
749
866
  );
750
867
  }
751
868
  let s = o.Pool ?? o.default?.Pool;
752
- return Vt(
869
+ return rn(
753
870
  {
754
871
  fetchLease: r,
755
872
  createPool: (d) => {
@@ -768,7 +885,7 @@ async function Ur(n, e, t) {
768
885
  ssl: u,
769
886
  // Tuning centralizado (env-tunável) — ver resolvePoolTuning + auditoria
770
887
  // docs/_review/AUDITORIA_DB_CONN_PERF_2026-09-06.md no Core.
771
- ...ze()
888
+ ...Xe()
772
889
  });
773
890
  },
774
891
  createDrizzle: (d, u) => i.drizzle(d, { schema: u }),
@@ -784,28 +901,39 @@ async function Ur(n, e, t) {
784
901
  t
785
902
  );
786
903
  }
787
- var qt, Ft, Wt, $t, Bt, Kt = B(() => {
788
- Y();
789
- P();
790
- Mt();
791
- Be();
792
- qt = "/api/sdk/v1/db/lease", Ft = "/api/sdk/v1/db/lease/renew";
793
- Wt = 10, $t = 6e4, Bt = 1e4;
904
+ var Xt, Yt, en, tn, nn, sn = $(() => {
905
+ Z();
906
+ I();
907
+ Jt();
908
+ Ge();
909
+ Xt = "/api/sdk/v1/db/lease", Yt = "/api/sdk/v1/db/lease/renew";
910
+ en = 10, tn = 6e4, nn = 1e4;
794
911
  });
912
+ var Le = /* @__PURE__ */ new Map(), Ue = 3600 * 1e3;
913
+ function it(n, e = Ue) {
914
+ let t = Date.now(), r = Le.get(n);
915
+ if (r && t - r.createdAt < e)
916
+ return r.jwks;
917
+ let o = jose.createRemoteJWKSet(new URL(n));
918
+ return Le.set(n, { jwks: o, createdAt: t }), o;
919
+ }
920
+ function st() {
921
+ Le.clear();
922
+ }
795
923
 
796
924
  // src/auth.ts
797
- P();
925
+ I();
798
926
 
799
927
  // src/api-key.ts
800
- P();
801
- var et = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
802
- function tt(n) {
928
+ I();
929
+ var at = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
930
+ function ct(n) {
803
931
  if (typeof n != "string" || n.length === 0)
804
932
  throw new c(
805
933
  "invalid_config",
806
934
  "apiKey is required (formato nrt_<keyId>_<secret>)"
807
935
  );
808
- let e = et.exec(n);
936
+ let e = at.exec(n);
809
937
  if (!e)
810
938
  throw new c(
811
939
  "invalid_config",
@@ -813,22 +941,22 @@ function tt(n) {
813
941
  );
814
942
  return { keyId: e[1], secret: e[2] };
815
943
  }
816
- function nt(n) {
944
+ function lt(n) {
817
945
  if (typeof n != "string" || n.length === 0) return null;
818
- let e = et.exec(n);
946
+ let e = at.exec(n);
819
947
  return e ? { keyId: e[1], secret: e[2] } : null;
820
948
  }
821
949
 
822
950
  // src/base-url-allowlist.ts
823
- P();
824
- var rt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), xn = ".neetru.com", On = "neetru.com", Ln = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
825
- function ot(n) {
826
- return Ln.test(n);
951
+ I();
952
+ 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)$/;
953
+ function ut(n) {
954
+ return Yn.test(n);
827
955
  }
828
- function Un(n) {
956
+ function Zn(n) {
829
957
  return n.toLowerCase().replace(/\.+$/, "");
830
958
  }
831
- function it(n, e = []) {
959
+ function pt(n, e = []) {
832
960
  if (typeof n != "string" || n.length === 0)
833
961
  throw new c("invalid_config", "baseUrl is required");
834
962
  let t;
@@ -837,8 +965,8 @@ function it(n, e = []) {
837
965
  } catch {
838
966
  throw new c("invalid_config", `baseUrl is not a valid URL: ${n}`);
839
967
  }
840
- let r = t.protocol, o = Un(t.hostname);
841
- if (Mn())
968
+ let r = t.protocol, o = Zn(t.hostname);
969
+ if (er())
842
970
  return typeof console < "u" && console.warn(
843
971
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${n} aceito sem valida\xE7\xE3o.`
844
972
  ), n.replace(/\/+$/, "");
@@ -848,17 +976,17 @@ function it(n, e = []) {
848
976
  `baseUrl protocol must be http: or https:, got ${r}`
849
977
  );
850
978
  if (r === "http:") {
851
- if (!(rt.has(o) || ot(o)))
979
+ if (!(dt.has(o) || ut(o)))
852
980
  throw new c(
853
981
  "invalid_config",
854
982
  `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.`
855
983
  );
856
984
  return n.replace(/\/+$/, "");
857
985
  }
858
- let i = o === On || o.endsWith(xn), s = e.some((l) => {
986
+ let i = o === Xn || o.endsWith(Jn), s = e.some((l) => {
859
987
  let d = l.toLowerCase();
860
988
  return o === d || o.endsWith(`.${d}`);
861
- }), a = rt.has(o) || ot(o);
989
+ }), a = dt.has(o) || ut(o);
862
990
  if (!i && !s && !a)
863
991
  throw new c(
864
992
  "invalid_config",
@@ -866,7 +994,7 @@ function it(n, e = []) {
866
994
  );
867
995
  return n.replace(/\/+$/, "");
868
996
  }
869
- function Mn() {
997
+ function er() {
870
998
  try {
871
999
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
872
1000
  if (e === "1" || e === "true") return !0;
@@ -881,12 +1009,12 @@ function Mn() {
881
1009
  }
882
1010
 
883
1011
  // src/types.ts
884
- var st = "https://api.neetru.com", at = "http://localhost:9003";
1012
+ var ft = "https://api.neetru.com", mt = "http://localhost:9003";
885
1013
 
886
1014
  // src/catalog.ts
887
- P();
888
- U();
889
- function gt(n) {
1015
+ I();
1016
+ M();
1017
+ function At(n) {
890
1018
  if (!n || typeof n != "object")
891
1019
  throw new c("invalid_response", "Catalog response item is not an object");
892
1020
  let e = n;
@@ -905,7 +1033,7 @@ function gt(n) {
905
1033
  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;
906
1034
  })), t;
907
1035
  }
908
- function yt(n) {
1036
+ function Et(n) {
909
1037
  return {
910
1038
  /**
911
1039
  * Lista produtos publicados. Por default só `published=true`; staff
@@ -922,7 +1050,7 @@ function yt(n) {
922
1050
  "Catalog list response missing products array"
923
1051
  );
924
1052
  return {
925
- products: t.products.map(gt),
1053
+ products: t.products.map(At),
926
1054
  fetchedAt: typeof t.fetchedAt == "string" ? t.fetchedAt : (/* @__PURE__ */ new Date()).toISOString()
927
1055
  };
928
1056
  },
@@ -943,32 +1071,32 @@ function yt(n) {
943
1071
  "invalid_response",
944
1072
  "Catalog get response missing product"
945
1073
  );
946
- return gt(t.product);
1074
+ return At(t.product);
947
1075
  }
948
1076
  };
949
1077
  }
950
1078
 
951
1079
  // src/entitlements.ts
952
- P();
953
- var Hn = "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.";
954
- function _t() {
955
- throw new c("validation_failed", Hn);
1080
+ I();
1081
+ 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.";
1082
+ function Pt() {
1083
+ throw new c("validation_failed", mr);
956
1084
  }
957
- function bt(n) {
1085
+ function Dt(n) {
958
1086
  return {
959
1087
  /**
960
1088
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
961
1089
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
962
1090
  */
963
1091
  async check(e, t, r) {
964
- _t();
1092
+ Pt();
965
1093
  },
966
1094
  /**
967
1095
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
968
1096
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
969
1097
  */
970
1098
  async checkDetailed(e, t, r) {
971
- _t();
1099
+ Pt();
972
1100
  },
973
1101
  /** Test helper legado — no-op (não há mais cache). Mantido por compat. */
974
1102
  __resetCache() {
@@ -977,16 +1105,16 @@ function bt(n) {
977
1105
  }
978
1106
 
979
1107
  // src/telemetry.ts
980
- P();
981
- U();
982
- var vt = ["debug", "info", "warn", "error", "fatal"];
983
- function Qn() {
1108
+ I();
1109
+ M();
1110
+ var Nt = ["debug", "info", "warn", "error", "fatal"];
1111
+ function hr() {
984
1112
  return typeof globalThis < "u" && typeof globalThis.window < "u";
985
1113
  }
986
- function wt() {
987
- return Qn() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1114
+ function xt() {
1115
+ return hr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
988
1116
  }
989
- function Gn(n) {
1117
+ function gr(n) {
990
1118
  switch (n) {
991
1119
  case "debug":
992
1120
  return console.debug.bind(console);
@@ -1002,8 +1130,8 @@ function Gn(n) {
1002
1130
  return console.log.bind(console);
1003
1131
  }
1004
1132
  }
1005
- var Jn = 500, Xn = 50;
1006
- function kt(n) {
1133
+ var yr = 500, _r = 50;
1134
+ function Ot(n) {
1007
1135
  let e = [], t = null, r = null;
1008
1136
  async function o() {
1009
1137
  if (e.length === 0) return;
@@ -1012,7 +1140,7 @@ function kt(n) {
1012
1140
  try {
1013
1141
  let d = { name: l.name }, u = l.productSlug ?? n.productId;
1014
1142
  u && (d.productSlug = u), l.properties && typeof l.properties == "object" && (d.properties = l.properties), l.timestamp && (d.timestamp = l.timestamp);
1015
- let p = wt();
1143
+ let p = xt();
1016
1144
  await v(n, {
1017
1145
  method: "POST",
1018
1146
  path: p.path,
@@ -1036,7 +1164,7 @@ function kt(n) {
1036
1164
  function i() {
1037
1165
  t || (t = setTimeout(() => {
1038
1166
  o();
1039
- }, Jn));
1167
+ }, yr));
1040
1168
  }
1041
1169
  return {
1042
1170
  /**
@@ -1060,7 +1188,7 @@ function kt(n) {
1060
1188
  throw new c("validation_failed", "event.name max 128 chars");
1061
1189
  let a = { name: s.name }, l = s.productSlug ?? n.productId;
1062
1190
  l && (a.productSlug = l), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1063
- let d = wt(), u = await v(n, {
1191
+ let d = xt(), u = await v(n, {
1064
1192
  method: "POST",
1065
1193
  path: d.path,
1066
1194
  body: a,
@@ -1081,7 +1209,7 @@ function kt(n) {
1081
1209
  * ```
1082
1210
  */
1083
1211
  track(s) {
1084
- !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= Xn ? (t && (clearTimeout(t), t = null), o()) : i());
1212
+ !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());
1085
1213
  },
1086
1214
  /**
1087
1215
  * Força flush imediato da queue de `track()`. Resolva antes de
@@ -1108,14 +1236,14 @@ function kt(n) {
1108
1236
  async log(s) {
1109
1237
  if (!s || typeof s != "object")
1110
1238
  throw new c("validation_failed", "log input is required");
1111
- if (!vt.includes(s.level))
1112
- throw new c("validation_failed", `level must be one of ${vt.join(", ")}`);
1239
+ if (!Nt.includes(s.level))
1240
+ throw new c("validation_failed", `level must be one of ${Nt.join(", ")}`);
1113
1241
  if (typeof s.message != "string" || s.message.length === 0)
1114
1242
  throw new c("validation_failed", "message is required");
1115
1243
  if (s.message.length > 4e3)
1116
1244
  throw new c("validation_failed", "message max 4000 chars");
1117
1245
  if (n.env === "dev")
1118
- return Gn(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1246
+ return gr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1119
1247
  let a = {
1120
1248
  level: s.level,
1121
1249
  message: s.message
@@ -1151,22 +1279,22 @@ function kt(n) {
1151
1279
  }
1152
1280
 
1153
1281
  // src/usage.ts
1154
- P();
1155
- U();
1282
+ I();
1283
+ M();
1156
1284
 
1157
1285
  // src/validators.ts
1158
- P();
1159
- var St = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1160
- function x(n, e) {
1161
- if (typeof e != "string" || !St.test(e))
1286
+ I();
1287
+ var Lt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1288
+ function N(n, e) {
1289
+ if (typeof e != "string" || !Lt.test(e))
1162
1290
  throw new c(
1163
1291
  "validation_failed",
1164
- `${n} must match ${St.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1292
+ `${n} must match ${Lt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1165
1293
  );
1166
1294
  }
1167
1295
 
1168
1296
  // src/usage.ts
1169
- function Tt(n) {
1297
+ function Ut(n) {
1170
1298
  return {
1171
1299
  /**
1172
1300
  * Reporta consumo metered de um resource. Hit no endpoint canônico
@@ -1196,7 +1324,7 @@ function Tt(n) {
1196
1324
  "validation_failed",
1197
1325
  "tenantId required (pass to options or set on createNeetruClient)"
1198
1326
  );
1199
- x("productId", o), x("tenantId", i);
1327
+ N("productId", o), N("tenantId", i);
1200
1328
  let s = await v(n, {
1201
1329
  method: "POST",
1202
1330
  path: "/api/sdk/v1/usage/record",
@@ -1230,7 +1358,7 @@ function Tt(n) {
1230
1358
  "validation_failed",
1231
1359
  "productId and tenantId required (pass to options or set on createNeetruClient)"
1232
1360
  );
1233
- x("productId", r), x("tenantId", o);
1361
+ N("productId", r), N("tenantId", o);
1234
1362
  let i = await v(n, {
1235
1363
  method: "GET",
1236
1364
  path: "/api/sdk/v1/entitlements",
@@ -1254,10 +1382,10 @@ function Tt(n) {
1254
1382
  }
1255
1383
 
1256
1384
  // src/support.ts
1257
- P();
1258
- U();
1259
- var Oe = ["low", "normal", "high", "urgent"], Yn = ["open", "pending", "resolved", "closed"], Rt = 50;
1260
- function It(n) {
1385
+ I();
1386
+ M();
1387
+ var je = ["low", "normal", "high", "urgent"], br = ["open", "pending", "resolved", "closed"], Mt = 50;
1388
+ function qt(n) {
1261
1389
  if (!n || typeof n != "object")
1262
1390
  throw new c("invalid_response", "Ticket response is not an object");
1263
1391
  let e = n;
@@ -1268,8 +1396,8 @@ function It(n) {
1268
1396
  id: e.id,
1269
1397
  subject: typeof e.subject == "string" ? e.subject : "",
1270
1398
  message: typeof e.message == "string" ? e.message : "",
1271
- severity: Oe.includes(e.severity) ? e.severity : "normal",
1272
- status: Yn.includes(e.status) ? e.status : "open",
1399
+ severity: je.includes(e.severity) ? e.severity : "normal",
1400
+ status: br.includes(e.status) ? e.status : "open",
1273
1401
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
1274
1402
  updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : void 0,
1275
1403
  productSlug: typeof e.productId == "string" ? e.productId : typeof e.productSlug == "string" ? e.productSlug : void 0,
@@ -1287,60 +1415,63 @@ function It(n) {
1287
1415
  satisfactionComment: typeof e.satisfactionComment == "string" ? e.satisfactionComment : null
1288
1416
  };
1289
1417
  }
1290
- function ae(n) {
1418
+ function de(n) {
1291
1419
  if (!n || typeof n != "string")
1292
1420
  throw new c("validation_failed", "ticketId is required");
1293
1421
  }
1294
- function Ct(n) {
1422
+ function Ft(n) {
1295
1423
  if (typeof n == "string" && n.length > 2e3)
1296
1424
  throw new c("validation_failed", "comment max 2000 chars");
1297
1425
  }
1298
- function At(n, ...e) {
1426
+ function jt(n, ...e) {
1299
1427
  for (let t of e)
1300
1428
  if (typeof t == "string" && t.length > 0)
1301
- return x("productSlug", t), t;
1429
+ return N("productSlug", t), t;
1302
1430
  if (n.productId)
1303
- return x("productId", n.productId), n.productId;
1431
+ return N("productId", n.productId), n.productId;
1304
1432
  throw new c(
1305
1433
  "validation_failed",
1306
1434
  "productId required (pass to input.productSlug or set on createNeetruClient)"
1307
1435
  );
1308
1436
  }
1309
- var Zn = "X-Neetru-End-User-Token", er = "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.", tr = "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.", nr = "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.", rr = "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.";
1310
- function Pt(n) {
1437
+ 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.";
1438
+ function $t(n) {
1311
1439
  if (n instanceof c && !(n instanceof V)) {
1312
1440
  if (n.code === "end_user_token_required")
1313
1441
  throw new V(
1314
- tr,
1442
+ kr,
1315
1443
  "end_user_token_required",
1316
1444
  n.status,
1317
- n.requestId
1445
+ n.requestId,
1446
+ n.correlationId
1318
1447
  );
1319
1448
  if (n.code === "invalid_end_user_token")
1320
1449
  throw new V(
1321
- nr,
1450
+ Sr,
1322
1451
  "invalid_end_user_token",
1323
1452
  n.status,
1324
- n.requestId
1453
+ n.requestId,
1454
+ n.correlationId
1325
1455
  );
1326
1456
  if (n.code === "end_user_token_product_mismatch")
1327
1457
  throw new c(
1328
1458
  "forbidden",
1329
- rr,
1459
+ Tr,
1330
1460
  n.status,
1331
1461
  n.requestId,
1332
- "end_user_token_product_mismatch"
1462
+ "end_user_token_product_mismatch",
1463
+ n.correlationId
1333
1464
  );
1334
1465
  }
1335
1466
  throw n;
1336
1467
  }
1337
- function or(n) {
1468
+ function Rr(n) {
1338
1469
  return n instanceof c && n.code === "invalid_end_user_token";
1339
1470
  }
1340
- function Et(n, e = {}) {
1341
- function t() {
1471
+ function Wt(n, e = {}) {
1472
+ async function t() {
1342
1473
  try {
1343
- let a = e.getEndUserToken?.();
1474
+ let a = await e.getEndUserToken?.();
1344
1475
  return typeof a == "string" && a.length > 0 ? a : null;
1345
1476
  } catch {
1346
1477
  return null;
@@ -1355,25 +1486,25 @@ function Et(n, e = {}) {
1355
1486
  }
1356
1487
  }
1357
1488
  function o(a) {
1358
- return a ? { [Zn]: a } : {};
1489
+ return a ? { [vr]: a } : {};
1359
1490
  }
1360
1491
  async function i(a, l) {
1361
- let d = t();
1362
- if (!d && a && await r() && (d = t()), !d && a)
1363
- throw new V(er, "no_signed_in_user");
1492
+ let d = await t();
1493
+ if (!d && a && await r() && (d = await t()), !d && a)
1494
+ throw new V(wr, "no_signed_in_user");
1364
1495
  try {
1365
1496
  return await l(o(d));
1366
1497
  } catch (u) {
1367
- if (d && or(u) && await r()) {
1368
- let p = t();
1498
+ if (d && Rr(u) && await r()) {
1499
+ let p = await t();
1369
1500
  if (p)
1370
1501
  try {
1371
1502
  return await l(o(p));
1372
1503
  } catch (f) {
1373
- Pt(f);
1504
+ $t(f);
1374
1505
  }
1375
1506
  }
1376
- Pt(u);
1507
+ $t(u);
1377
1508
  }
1378
1509
  }
1379
1510
  async function s(a, l = {}) {
@@ -1406,13 +1537,13 @@ function Et(n, e = {}) {
1406
1537
  throw new c("validation_failed", "message is required");
1407
1538
  if (a.message.length > 1e4)
1408
1539
  throw new c("validation_failed", "message max 10000 chars");
1409
- if (a.severity && !Oe.includes(a.severity))
1540
+ if (a.severity && !je.includes(a.severity))
1410
1541
  throw new c(
1411
1542
  "validation_failed",
1412
- `severity must be one of ${Oe.join(", ")}`
1543
+ `severity must be one of ${je.join(", ")}`
1413
1544
  );
1414
1545
  let d = {
1415
- productId: At(n, a.productSlug),
1546
+ productId: jt(n, a.productSlug),
1416
1547
  subject: a.subject,
1417
1548
  message: a.message,
1418
1549
  severity: a.severity ?? "normal"
@@ -1429,7 +1560,7 @@ function Et(n, e = {}) {
1429
1560
  headers: f
1430
1561
  })
1431
1562
  ), p = u && typeof u == "object" && "ticket" in u ? u.ticket : u;
1432
- return It(p);
1563
+ return qt(p);
1433
1564
  },
1434
1565
  /**
1435
1566
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
@@ -1437,11 +1568,11 @@ function Et(n, e = {}) {
1437
1568
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
1438
1569
  */
1439
1570
  async listMyTickets(a) {
1440
- let l = At(n, a?.productSlug), d = a?.limit;
1441
- if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Rt))
1571
+ let l = jt(n, a?.productSlug), d = a?.limit;
1572
+ if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Mt))
1442
1573
  throw new c(
1443
1574
  "validation_failed",
1444
- `limit must be an integer 1-${Rt} (Core default 20)`
1575
+ `limit must be an integer 1-${Mt} (Core default 20)`
1445
1576
  );
1446
1577
  let u = await i(
1447
1578
  true,
@@ -1453,7 +1584,7 @@ function Et(n, e = {}) {
1453
1584
  headers: f
1454
1585
  })
1455
1586
  );
1456
- return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(It);
1587
+ return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(qt);
1457
1588
  },
1458
1589
  /**
1459
1590
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
@@ -1461,7 +1592,7 @@ function Et(n, e = {}) {
1461
1592
  * `POST /api/sdk/v1/support/tickets/{id}/resolved-seen`.
1462
1593
  */
1463
1594
  async markResolvedSeen(a) {
1464
- ae(a), await s(
1595
+ de(a), await s(
1465
1596
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/resolved-seen`
1466
1597
  );
1467
1598
  },
@@ -1472,7 +1603,7 @@ function Et(n, e = {}) {
1472
1603
  * `POST /api/sdk/v1/support/tickets/{id}/satisfaction-attempt`.
1473
1604
  */
1474
1605
  async recordSatisfactionAttempt(a) {
1475
- ae(a), await s(
1606
+ de(a), await s(
1476
1607
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/satisfaction-attempt`,
1477
1608
  // Incrementa satisfactionAttempts += 1 no Core — sem idempotencyKey,
1478
1609
  // um retry de rede infla o contador (mesmo padrão de createTicket acima).
@@ -1486,9 +1617,9 @@ function Et(n, e = {}) {
1486
1617
  async submitSatisfaction(a) {
1487
1618
  if (!a || typeof a != "object")
1488
1619
  throw new c("validation_failed", "input is required");
1489
- if (ae(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1620
+ if (de(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1490
1621
  throw new c("validation_failed", "rating must be an integer 1-5 or null");
1491
- Ct(a.comment), await s(
1622
+ Ft(a.comment), await s(
1492
1623
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a.ticketId)}/satisfaction`,
1493
1624
  {
1494
1625
  body: {
@@ -1505,7 +1636,7 @@ function Et(n, e = {}) {
1505
1636
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
1506
1637
  */
1507
1638
  async contestTicket(a, l) {
1508
- ae(a), Ct(l?.comment), await s(
1639
+ de(a), Ft(l?.comment), await s(
1509
1640
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/contest`,
1510
1641
  { body: { comment: l?.comment ?? void 0 } }
1511
1642
  );
@@ -1514,14 +1645,14 @@ function Et(n, e = {}) {
1514
1645
  }
1515
1646
 
1516
1647
  // src/db/client-db.ts
1517
- Y();
1648
+ Z();
1518
1649
 
1519
1650
  // src/db/offline/query-engine.ts
1520
- function Dt(n) {
1651
+ function Bt(n) {
1521
1652
  return n == null ? 0 : typeof n == "number" ? 1 : typeof n == "string" ? 2 : typeof n == "boolean" ? 3 : 4;
1522
1653
  }
1523
- function Z(n, e) {
1524
- let t = Dt(n), r = Dt(e);
1654
+ function ee(n, e) {
1655
+ let t = Bt(n), r = Bt(e);
1525
1656
  if (t !== r) return t - r;
1526
1657
  if (n == null) return 0;
1527
1658
  if (typeof n == "number" && typeof e == "number") return n - e;
@@ -1530,7 +1661,7 @@ function Z(n, e) {
1530
1661
  let o = String(n), i = String(e);
1531
1662
  return o < i ? -1 : o > i ? 1 : 0;
1532
1663
  }
1533
- function Le(n, e) {
1664
+ function $e(n, e) {
1534
1665
  let t = e.split("."), r = n;
1535
1666
  for (let o of t) {
1536
1667
  if (r == null || typeof r != "object")
@@ -1539,8 +1670,8 @@ function Le(n, e) {
1539
1670
  }
1540
1671
  return r;
1541
1672
  }
1542
- function sr(n, e) {
1543
- let t = Le(n, e.field);
1673
+ function Cr(n, e) {
1674
+ let t = $e(n, e.field);
1544
1675
  if (t === void 0) return false;
1545
1676
  let { op: r, value: o } = e;
1546
1677
  switch (r) {
@@ -1549,13 +1680,13 @@ function sr(n, e) {
1549
1680
  case "!=":
1550
1681
  return t !== o;
1551
1682
  case "<":
1552
- return Z(t, o) < 0;
1683
+ return ee(t, o) < 0;
1553
1684
  case "<=":
1554
- return Z(t, o) <= 0;
1685
+ return ee(t, o) <= 0;
1555
1686
  case ">":
1556
- return Z(t, o) > 0;
1687
+ return ee(t, o) > 0;
1557
1688
  case ">=":
1558
- return Z(t, o) >= 0;
1689
+ return ee(t, o) >= 0;
1559
1690
  case "array-contains":
1560
1691
  return Array.isArray(t) && t.includes(o);
1561
1692
  case "in":
@@ -1570,24 +1701,24 @@ function sr(n, e) {
1570
1701
  );
1571
1702
  }
1572
1703
  }
1573
- function ar(n, e) {
1574
- return e.every((t) => sr(n, t));
1704
+ function Ar(n, e) {
1705
+ return e.every((t) => Cr(n, t));
1575
1706
  }
1576
- function cr(n) {
1707
+ function Er(n) {
1577
1708
  return (e, t) => {
1578
1709
  if (n) {
1579
- let r = Le(e.data, n.field), o = Le(t.data, n.field), i = Z(r, o);
1710
+ let r = $e(e.data, n.field), o = $e(t.data, n.field), i = ee(r, o);
1580
1711
  if (i !== 0)
1581
1712
  return n.direction === "desc" ? -i : i;
1582
1713
  }
1583
1714
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
1584
1715
  };
1585
1716
  }
1586
- function lr(n, e) {
1717
+ function Pr(n, e) {
1587
1718
  let t = n.findIndex((r) => r.id === e.docId);
1588
1719
  return t === -1 ? n : e.type === "startAfter" ? n.slice(t + 1) : n.slice(0, t);
1589
1720
  }
1590
- var K = class n {
1721
+ var z = class n {
1591
1722
  /**
1592
1723
  * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
1593
1724
  *
@@ -1601,9 +1732,9 @@ var K = class n {
1601
1732
  evaluate(e, t) {
1602
1733
  let r = e.filter((u) => !u.meta.deleted), o = t.where ?? [];
1603
1734
  o.length > 0 && (r = r.filter(
1604
- (u) => ar(u.data, o)
1735
+ (u) => Ar(u.data, o)
1605
1736
  ));
1606
- let i = cr(t.orderBy), s = [...r].sort(i), a = t.cursor ? lr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1737
+ let i = Er(t.orderBy), s = [...r].sort(i), a = t.cursor ? Pr(s, t.cursor) : s, l = Math.min(t.limit ?? 20, 500);
1607
1738
  return {
1608
1739
  docs: a.slice(0, l).map((u) => ({ id: u.id, data: u.data })),
1609
1740
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
@@ -1623,7 +1754,7 @@ var K = class n {
1623
1754
  };
1624
1755
 
1625
1756
  // src/db/offline/local-store.ts
1626
- var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_meta", H = "conflict_log", le = class {
1757
+ var Nr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_meta", H = "conflict_log", pe = class {
1627
1758
  db = null;
1628
1759
  dbName;
1629
1760
  constructor(e) {
@@ -1635,21 +1766,21 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1635
1766
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
1636
1767
  */
1637
1768
  async open() {
1638
- this.db === null && (this.db = await idb.openDB(this.dbName, ur, {
1769
+ this.db === null && (this.db = await idb.openDB(this.dbName, Nr, {
1639
1770
  upgrade(e) {
1640
- if (!e.objectStoreNames.contains(j)) {
1641
- let t = e.createObjectStore(j, {
1771
+ if (!e.objectStoreNames.contains(W)) {
1772
+ let t = e.createObjectStore(W, {
1642
1773
  keyPath: ["collection", "id"]
1643
1774
  });
1644
1775
  t.createIndex("by_collection", "collection"), t.createIndex("by_collection_state", ["collection", "meta.state"]), t.createIndex("by_updatedAtServer", "meta.updatedAtServer");
1645
1776
  }
1646
- if (!e.objectStoreNames.contains(W)) {
1647
- let t = e.createObjectStore(W, {
1777
+ if (!e.objectStoreNames.contains(B)) {
1778
+ let t = e.createObjectStore(B, {
1648
1779
  keyPath: "mutationId"
1649
1780
  });
1650
1781
  t.createIndex("by_seq", "seq"), t.createIndex("by_status", "status"), t.createIndex("by_doc", ["collection", "docId"]), t.createIndex("by_batch", "batchId");
1651
1782
  }
1652
- if (e.objectStoreNames.contains(ee) || e.createObjectStore(ee, { keyPath: "queryHash" }), e.objectStoreNames.contains(ce) || e.createObjectStore(ce, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1783
+ if (e.objectStoreNames.contains(te) || e.createObjectStore(te, { keyPath: "queryHash" }), e.objectStoreNames.contains(ue) || e.createObjectStore(ue, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1653
1784
  let t = e.createObjectStore(H, {
1654
1785
  keyPath: "id",
1655
1786
  autoIncrement: true
@@ -1692,14 +1823,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1692
1823
  * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
1693
1824
  */
1694
1825
  async getDoc(e, t) {
1695
- return await this.assertOpen().get(j, [e, t]) ?? null;
1826
+ return await this.assertOpen().get(W, [e, t]) ?? null;
1696
1827
  }
1697
1828
  /**
1698
1829
  * Insere ou atualiza um documento na store `documents`.
1699
1830
  * O documento é identificado pelo keyPath composto `[collection, id]`.
1700
1831
  */
1701
1832
  async putDoc(e) {
1702
- await this.assertOpen().put(j, e);
1833
+ await this.assertOpen().put(W, e);
1703
1834
  }
1704
1835
  /**
1705
1836
  * Marca um documento como tombstone (`deleted: true`).
@@ -1707,8 +1838,8 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1707
1838
  * No-op se o documento não existir.
1708
1839
  */
1709
1840
  async deleteDoc(e, t) {
1710
- let r = this.assertOpen(), o = await r.get(j, [e, t]);
1711
- o && await r.put(j, {
1841
+ let r = this.assertOpen(), o = await r.get(W, [e, t]);
1842
+ o && await r.put(W, {
1712
1843
  ...o,
1713
1844
  meta: {
1714
1845
  ...o.meta,
@@ -1724,8 +1855,8 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1724
1855
  * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
1725
1856
  */
1726
1857
  async listDocs(e, t) {
1727
- let o = await this.assertOpen().getAllFromIndex(j, "by_collection", e);
1728
- return K.evaluate(o, t);
1858
+ let o = await this.assertOpen().getAllFromIndex(W, "by_collection", e);
1859
+ return z.evaluate(o, t);
1729
1860
  }
1730
1861
  // ─── Sync meta (key-value) ──────────────────────────────────────────────────
1731
1862
  /**
@@ -1736,14 +1867,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1736
1867
  * 'lastFullResyncAt', 'leaderTabId'.
1737
1868
  */
1738
1869
  async getMeta(e) {
1739
- let r = await this.assertOpen().get(ce, e);
1870
+ let r = await this.assertOpen().get(ue, e);
1740
1871
  return r ? r.value : null;
1741
1872
  }
1742
1873
  /**
1743
1874
  * Armazena ou atualiza um valor na store `sync_meta`.
1744
1875
  */
1745
1876
  async setMeta(e, t) {
1746
- await this.assertOpen().put(ce, { key: e, value: t });
1877
+ await this.assertOpen().put(ue, { key: e, value: t });
1747
1878
  }
1748
1879
  // ─── Conflict log ───────────────────────────────────────────────────────────
1749
1880
  /**
@@ -1775,13 +1906,13 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1775
1906
  * Key: `mutationId`.
1776
1907
  */
1777
1908
  async putMutation(e) {
1778
- await this.assertOpen().put(W, e);
1909
+ await this.assertOpen().put(B, e);
1779
1910
  }
1780
1911
  /**
1781
1912
  * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
1782
1913
  */
1783
1914
  async getMutation(e) {
1784
- return await this.assertOpen().get(W, e) ?? null;
1915
+ return await this.assertOpen().get(B, e) ?? null;
1785
1916
  }
1786
1917
  /**
1787
1918
  * Lista mutações com filtros opcionais.
@@ -1789,14 +1920,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1789
1920
  */
1790
1921
  async listMutations(e) {
1791
1922
  let t = this.assertOpen(), r;
1792
- return e?.status !== void 0 ? r = await t.getAllFromIndex(W, "by_status", e.status) : e?.collection !== void 0 && e.docId !== void 0 ? r = await t.getAllFromIndex(W, "by_doc", [e.collection, e.docId]) : r = await t.getAllFromIndex(W, "by_seq"), r.sort((o, i) => o.seq - i.seq);
1923
+ 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);
1793
1924
  }
1794
1925
  /**
1795
1926
  * Remove uma mutação pelo `mutationId`.
1796
1927
  * No-op se não existir.
1797
1928
  */
1798
1929
  async deleteMutation(e) {
1799
- await this.assertOpen().delete(W, e);
1930
+ await this.assertOpen().delete(B, e);
1800
1931
  }
1801
1932
  // ─── Collection discovery ────────────────────────────────────────────────────
1802
1933
  /**
@@ -1809,7 +1940,7 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1809
1940
  * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
1810
1941
  */
1811
1942
  async listCollections() {
1812
- let t = await this.assertOpen().getAllFromIndex(j, "by_collection"), r = /* @__PURE__ */ new Set();
1943
+ let t = await this.assertOpen().getAllFromIndex(W, "by_collection"), r = /* @__PURE__ */ new Set();
1813
1944
  for (let o of t)
1814
1945
  r.add(o.collection);
1815
1946
  return Array.from(r);
@@ -1819,24 +1950,24 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1819
1950
  * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
1820
1951
  */
1821
1952
  async getQueryCache(e) {
1822
- return await this.assertOpen().get(ee, e) ?? null;
1953
+ return await this.assertOpen().get(te, e) ?? null;
1823
1954
  }
1824
1955
  /**
1825
1956
  * Insere ou atualiza uma entrada de `query_cache`.
1826
1957
  */
1827
1958
  async putQueryCache(e) {
1828
- await this.assertOpen().put(ee, e);
1959
+ await this.assertOpen().put(te, e);
1829
1960
  }
1830
1961
  /**
1831
1962
  * Remove uma entrada de `query_cache` pelo queryHash.
1832
1963
  */
1833
1964
  async deleteQueryCache(e) {
1834
- await this.assertOpen().delete(ee, e);
1965
+ await this.assertOpen().delete(te, e);
1835
1966
  }
1836
1967
  };
1837
1968
 
1838
1969
  // src/db/offline/memory-store.ts
1839
- var de = class {
1970
+ var fe = class {
1840
1971
  // store `documents` — key: `${collection}\0${id}`
1841
1972
  _docs = /* @__PURE__ */ new Map();
1842
1973
  // store `mutations` — key: mutationId
@@ -1884,7 +2015,7 @@ var de = class {
1884
2015
  let r = Array.from(this._docs.values()).filter(
1885
2016
  (o) => o.collection === e
1886
2017
  );
1887
- return K.evaluate(r, t);
2018
+ return z.evaluate(r, t);
1888
2019
  }
1889
2020
  // ─── Sync meta ──────────────────────────────────────────────────────────────
1890
2021
  async getMeta(e) {
@@ -1941,13 +2072,13 @@ var de = class {
1941
2072
  };
1942
2073
 
1943
2074
  // src/db/offline/mutation-queue.ts
1944
- function Ue() {
2075
+ function We() {
1945
2076
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (n) => {
1946
2077
  let e = Math.random() * 16 | 0;
1947
2078
  return (n === "x" ? e : e & 3 | 8).toString(16);
1948
2079
  });
1949
2080
  }
1950
- var ue = class {
2081
+ var me = class {
1951
2082
  store;
1952
2083
  /**
1953
2084
  * Ponteiro de sequência local.
@@ -2043,16 +2174,16 @@ var ue = class {
2043
2174
  * Atômico: a persistência final é uma única operação putMutation.
2044
2175
  */
2045
2176
  async enqueue(e) {
2046
- let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? Ue() : "");
2177
+ let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? We() : "");
2047
2178
  await this.syncSeq();
2048
- let u = (await this.store.listMutations({ collection: t, docId: l })).filter((g) => g.status === "queued").sort((g, _) => _.seq - g.seq)[0];
2179
+ let u = (await this.store.listMutations({ collection: t, docId: l })).filter((h) => h.status === "queued").sort((h, y) => y.seq - h.seq)[0];
2049
2180
  if (u !== void 0) {
2050
- let g = this.tryCoalesce(u, r, o, s, a);
2051
- if (g !== null) {
2052
- if ("removed" in g)
2181
+ let h = this.tryCoalesce(u, r, o, s, a);
2182
+ if (h !== null) {
2183
+ if ("removed" in h)
2053
2184
  return await this.store.deleteMutation(u.mutationId), {
2054
2185
  seq: u.seq,
2055
- mutationId: Ue(),
2186
+ mutationId: We(),
2056
2187
  collection: t,
2057
2188
  docId: l,
2058
2189
  op: "remove",
@@ -2064,13 +2195,13 @@ var ue = class {
2064
2195
  status: "queued",
2065
2196
  batchId: s
2066
2197
  };
2067
- let { coalesced: _ } = g;
2068
- return await this.store.putMutation(_), _;
2198
+ let { coalesced: y } = h;
2199
+ return await this.store.putMutation(y), y;
2069
2200
  }
2070
2201
  }
2071
2202
  let f = {
2072
2203
  seq: this.nextSeq(),
2073
- mutationId: Ue(),
2204
+ mutationId: We(),
2074
2205
  collection: t,
2075
2206
  docId: l,
2076
2207
  op: r,
@@ -2183,45 +2314,45 @@ var ue = class {
2183
2314
  };
2184
2315
 
2185
2316
  // src/db/field-value.ts
2186
- var Nt = "__neetru__";
2317
+ var Vt = "__neetru__";
2187
2318
  function Q(n) {
2188
- return typeof n == "object" && n !== null && Nt in n && typeof n[Nt] == "string";
2319
+ return typeof n == "object" && n !== null && Vt in n && typeof n[Vt] == "string";
2189
2320
  }
2190
- function pr(n) {
2321
+ function xr(n) {
2191
2322
  return Q(n) && n.__neetru__ === "serverTimestamp";
2192
2323
  }
2193
- function fr(n) {
2324
+ function Or(n) {
2194
2325
  return Q(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2195
2326
  }
2196
- function mr(n, e) {
2197
- return pr(n) ? Date.now() : fr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2327
+ function Lr(n, e) {
2328
+ return xr(n) ? Date.now() : Or(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2198
2329
  }
2199
- function z(n, e) {
2330
+ function K(n, e) {
2200
2331
  let t = false, r = {};
2201
2332
  for (let [o, i] of Object.entries(n))
2202
- Q(i) ? (t = true, r[o] = mr(i, e?.[o])) : r[o] = i;
2333
+ Q(i) ? (t = true, r[o] = Lr(i, e?.[o])) : r[o] = i;
2203
2334
  return t ? r : n;
2204
2335
  }
2205
- function Me(n) {
2336
+ function Be(n) {
2206
2337
  for (let e of Object.values(n))
2207
2338
  if (Q(e)) return true;
2208
2339
  return false;
2209
2340
  }
2210
2341
 
2211
2342
  // src/db/offline/sync-engine.ts
2212
- var hr = 8, gr = 1e3, yr = 300 * 1e3, qe = "truncatedCollections";
2213
- function _r(n) {
2214
- return n !== null && Me(n);
2343
+ var Ur = 8, Mr = 1e3, qr = 300 * 1e3, Ve = "truncatedCollections";
2344
+ function Fr(n) {
2345
+ return n !== null && Be(n);
2215
2346
  }
2216
- function br(n) {
2347
+ function jr(n) {
2217
2348
  if (n === null) return null;
2218
- if (!Me(n)) return n;
2349
+ if (!Be(n)) return n;
2219
2350
  let e = {};
2220
2351
  for (let [t, r] of Object.entries(n))
2221
2352
  Q(r) || (e[t] = r);
2222
2353
  return e;
2223
2354
  }
2224
- var pe = class {
2355
+ var he = class {
2225
2356
  _store;
2226
2357
  _queue;
2227
2358
  _resolver;
@@ -2415,13 +2546,13 @@ var pe = class {
2415
2546
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
2416
2547
  return;
2417
2548
  }
2418
- let d = br(i.payload) ?? a?.data ?? {}, u = {
2549
+ let d = jr(i.payload) ?? a?.data ?? {}, u = {
2419
2550
  collection: e,
2420
2551
  id: t,
2421
2552
  data: i.op === "update" ? { ...a?.data ?? {}, ...d } : (
2422
2553
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2423
2554
  // é a fonte de verdade até o pull; senão usa o payload literal.
2424
- _r(i.payload) ? { ...a?.data ?? {}, ...d } : d
2555
+ Fr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2425
2556
  ),
2426
2557
  meta: {
2427
2558
  serverVersion: r,
@@ -2574,7 +2705,7 @@ var pe = class {
2574
2705
  * pending do doc no cache + registra `lastError`/dispara `onError`.
2575
2706
  */
2576
2707
  async _retryOrDeadLetter(e, t, r) {
2577
- if (e.attempts + 1 < hr) {
2708
+ if (e.attempts + 1 < Ur) {
2578
2709
  await this._queue.markRetry(e.mutationId, t);
2579
2710
  return;
2580
2711
  }
@@ -2615,7 +2746,7 @@ var pe = class {
2615
2746
  }
2616
2747
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
2617
2748
  _backoffDelayMs(e) {
2618
- return Math.min(gr * 2 ** (e - 1), yr);
2749
+ return Math.min(Mr * 2 ** (e - 1), qr);
2619
2750
  }
2620
2751
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
2621
2752
  /**
@@ -2648,7 +2779,7 @@ var pe = class {
2648
2779
  let r = [];
2649
2780
  await this._applyServerDocs(t.docs, r, true);
2650
2781
  let o = t.truncatedCollections ?? [], i = new Set(o);
2651
- await this._store.setMeta(qe, o);
2782
+ await this._store.setMeta(Ve, o);
2652
2783
  let s = new Set(
2653
2784
  t.docs.map((a) => `${a.collection}::${a.id}`)
2654
2785
  );
@@ -2867,10 +2998,10 @@ var pe = class {
2867
2998
  };
2868
2999
 
2869
3000
  // src/db/offline/conflict-resolver.ts
2870
- function xt(n, e) {
3001
+ function Kt(n, e) {
2871
3002
  return e === null ? false : n === null ? true : e > n;
2872
3003
  }
2873
- var fe = class n {
3004
+ var ge = class n {
2874
3005
  /**
2875
3006
  * Resolve um conflito com base na operação da mutação (auto-dispatch).
2876
3007
  *
@@ -2904,7 +3035,7 @@ var fe = class n {
2904
3035
  resolvedData: t.data,
2905
3036
  conflictRecord: null
2906
3037
  };
2907
- if (!xt(
3038
+ if (!Kt(
2908
3039
  e.meta.updatedAtServer,
2909
3040
  t.meta.updatedAtServer
2910
3041
  ))
@@ -2951,7 +3082,7 @@ var fe = class n {
2951
3082
  let i = t.data;
2952
3083
  if (e === null)
2953
3084
  return { outcome: "no_conflict", resolvedData: { ...i, ...r.payload ?? {} }, conflictRecord: null };
2954
- if (!xt(
3085
+ if (!Kt(
2955
3086
  e.meta.updatedAtServer,
2956
3087
  t.meta.updatedAtServer
2957
3088
  ))
@@ -3029,10 +3160,10 @@ var fe = class n {
3029
3160
  };
3030
3161
 
3031
3162
  // src/db/offline/change-bus.ts
3032
- function vr(n) {
3163
+ function $r(n) {
3033
3164
  return `${n.collection}::${n.doc.id}`;
3034
3165
  }
3035
- var me = class {
3166
+ var ye = class {
3036
3167
  /** Listeners filtrados por coleção. */
3037
3168
  _collectionListeners = /* @__PURE__ */ new Map();
3038
3169
  /** Listeners globais (todas as coleções). */
@@ -3077,7 +3208,7 @@ var me = class {
3077
3208
  if (e.length === 0) return;
3078
3209
  let t = /* @__PURE__ */ new Map();
3079
3210
  for (let i of e)
3080
- t.set(vr(i), i);
3211
+ t.set($r(i), i);
3081
3212
  let r = Array.from(t.values()), o = /* @__PURE__ */ new Map();
3082
3213
  for (let i of r)
3083
3214
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
@@ -3116,7 +3247,7 @@ var me = class {
3116
3247
  };
3117
3248
 
3118
3249
  // src/db/offline/connectivity-monitor.ts
3119
- var he = class {
3250
+ var _e = class {
3120
3251
  _state;
3121
3252
  _listeners = /* @__PURE__ */ new Set();
3122
3253
  _nav;
@@ -3218,7 +3349,7 @@ var he = class {
3218
3349
  };
3219
3350
 
3220
3351
  // src/db/offline/tab-coordinator.ts
3221
- var te = class {
3352
+ var ne = class {
3222
3353
  _lockName;
3223
3354
  _channelName;
3224
3355
  _lockManager;
@@ -3395,26 +3526,26 @@ var te = class {
3395
3526
  };
3396
3527
 
3397
3528
  // src/db/collection-ref.ts
3398
- Y();
3399
- function wr() {
3529
+ Z();
3530
+ function Wr() {
3400
3531
  return typeof indexedDB > "u" || typeof window > "u";
3401
3532
  }
3402
- var Ot = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3403
- function kr(n) {
3404
- if (!Ot.test(n))
3405
- throw new y(
3533
+ var zt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3534
+ function Br(n) {
3535
+ if (!zt.test(n))
3536
+ throw new b(
3406
3537
  "db_invalid_query",
3407
- `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${Ot}.`
3538
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${zt}.`
3408
3539
  );
3409
3540
  }
3410
3541
  function G(n, e = "id") {
3411
3542
  if (!n || typeof n != "string" || n.trim() === "")
3412
- throw new y(
3543
+ throw new b(
3413
3544
  "db_invalid_query",
3414
3545
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
3415
3546
  );
3416
3547
  }
3417
- function Sr(n) {
3548
+ function Vr(n) {
3418
3549
  let e = {};
3419
3550
  if (n?.where && (e.where = n.where.map((t) => ({
3420
3551
  field: t.field,
@@ -3431,12 +3562,12 @@ function Sr(n) {
3431
3562
  }
3432
3563
  return e;
3433
3564
  }
3434
- function Tr(n, e) {
3565
+ function Kr(n, e) {
3435
3566
  if (n.length < e) return null;
3436
3567
  let t = n[n.length - 1];
3437
3568
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
3438
3569
  }
3439
- var Fe = class {
3570
+ var Ke = class {
3440
3571
  constructor(e, t, r, o, i, s) {
3441
3572
  this._collection = e;
3442
3573
  this._store = t;
@@ -3478,9 +3609,9 @@ var Fe = class {
3478
3609
  }
3479
3610
  /** Constrói um DbListResult para a coleção com query opcional. */
3480
3611
  async _buildListResult(e) {
3481
- let t = Sr(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 = Tr(o.docs, r), d = await this._store.getMeta(qe), u = Array.isArray(d) && d.includes(this._collection), p = !s || a.status === "offline" || u, f = i || a.lastSyncedAt === null || p;
3612
+ 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;
3482
3613
  return {
3483
- docs: o.docs.map((g) => ({ id: g.id, data: g.data })),
3614
+ docs: o.docs.map((h) => ({ id: h.id, data: h.data })),
3484
3615
  nextCursor: l,
3485
3616
  fromCache: f,
3486
3617
  stale: p,
@@ -3497,7 +3628,7 @@ var Fe = class {
3497
3628
  return this._buildListResult(e);
3498
3629
  }
3499
3630
  async add(e) {
3500
- let t = e, r = z(t, void 0), o = await this._queue.enqueue({
3631
+ let t = e, r = K(t, void 0), o = await this._queue.enqueue({
3501
3632
  collection: this._collection,
3502
3633
  op: "add",
3503
3634
  payload: t,
@@ -3525,7 +3656,7 @@ var Fe = class {
3525
3656
  }
3526
3657
  async set(e, t) {
3527
3658
  G(e);
3528
- let r = await this._store.getDoc(this._collection, e), o = t, i = z(o, void 0), s = await this._queue.enqueue({
3659
+ let r = await this._store.getDoc(this._collection, e), o = t, i = K(o, void 0), s = await this._queue.enqueue({
3529
3660
  collection: this._collection,
3530
3661
  docId: e,
3531
3662
  op: "set",
@@ -3554,7 +3685,7 @@ var Fe = class {
3554
3685
  }
3555
3686
  async update(e, t, r) {
3556
3687
  G(e);
3557
- 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({
3688
+ 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({
3558
3689
  collection: this._collection,
3559
3690
  docId: e,
3560
3691
  op: "update",
@@ -3607,7 +3738,7 @@ var Fe = class {
3607
3738
  for (let o of e) {
3608
3739
  let i = this._collection;
3609
3740
  if (o.kind === "add") {
3610
- let s = o.data, a = z(s, void 0), l = await this._queue.enqueue({
3741
+ let s = o.data, a = K(s, void 0), l = await this._queue.enqueue({
3611
3742
  collection: i,
3612
3743
  op: "add",
3613
3744
  payload: s,
@@ -3629,7 +3760,7 @@ var Fe = class {
3629
3760
  }
3630
3761
  }), r.push({ type: "added", collection: i, doc: { id: d, data: a } });
3631
3762
  } else if (o.kind === "set") {
3632
- let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = z(a, void 0), u = await this._queue.enqueue({
3763
+ let s = o.id, a = o.data, l = await this._store.getDoc(i, s), d = K(a, void 0), u = await this._queue.enqueue({
3633
3764
  collection: i,
3634
3765
  docId: s,
3635
3766
  op: "set",
@@ -3656,7 +3787,7 @@ var Fe = class {
3656
3787
  doc: { id: s, data: d }
3657
3788
  });
3658
3789
  } else if (o.kind === "update") {
3659
- 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({
3790
+ 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({
3660
3791
  collection: i,
3661
3792
  docId: s,
3662
3793
  op: "update",
@@ -3811,7 +3942,7 @@ var Fe = class {
3811
3942
  }
3812
3943
  };
3813
3944
  }
3814
- }, je = class {
3945
+ }, ze = class {
3815
3946
  _store;
3816
3947
  _queue;
3817
3948
  _bus;
@@ -3821,7 +3952,7 @@ var Fe = class {
3821
3952
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3822
3953
  }
3823
3954
  collection(e) {
3824
- return kr(e), new Fe(
3955
+ return Br(e), new Ke(
3825
3956
  e,
3826
3957
  this._store,
3827
3958
  this._queue,
@@ -3850,10 +3981,10 @@ var Fe = class {
3850
3981
  return this._engine.onError(e);
3851
3982
  }
3852
3983
  };
3853
- async function Lt(n) {
3854
- let e = wr() ? new de() : new le(n.dbName);
3984
+ async function Ht(n) {
3985
+ let e = Wr() ? new fe() : new pe(n.dbName);
3855
3986
  await e.open();
3856
- let t = new ue(e), r = new fe(), o = new me(), i = new he({
3987
+ let t = new me(e), r = new ge(), o = new ye(), i = new _e({
3857
3988
  // Se startOnline=false, injeta um navigator falso
3858
3989
  navigator: n.startOnline === false ? { onLine: false } : typeof navigator < "u" ? navigator : void 0
3859
3990
  }), s = n.singleTab ? (
@@ -3863,10 +3994,10 @@ async function Lt(n) {
3863
3994
  onRoleChange: (l) => () => {
3864
3995
  }
3865
3996
  }
3866
- ) : new te({
3997
+ ) : new ne({
3867
3998
  lockName: `neetru-offline:${n.dbName}`,
3868
3999
  channelName: `neetru-offline:${n.dbName}`
3869
- }), a = new pe({
4000
+ }), a = new he({
3870
4001
  store: e,
3871
4002
  queue: t,
3872
4003
  resolver: r,
@@ -3876,7 +4007,7 @@ async function Lt(n) {
3876
4007
  connectivity: i,
3877
4008
  periodicSyncIntervalMs: n.periodicSyncIntervalMs ?? 300 * 1e3
3878
4009
  });
3879
- return i.start(), !n.singleTab && s instanceof te && s.start(), new je({
4010
+ return i.start(), !n.singleTab && s instanceof ne && s.start(), new ze({
3880
4011
  store: e,
3881
4012
  queue: t,
3882
4013
  bus: o,
@@ -3886,11 +4017,11 @@ async function Lt(n) {
3886
4017
  }
3887
4018
 
3888
4019
  // src/db/realtime/realtime-client.ts
3889
- var Rr = 0;
3890
- function Ut() {
3891
- return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++Rr}-${Math.random().toString(36).slice(2)}`;
4020
+ var zr = 0;
4021
+ function Qt() {
4022
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++zr}-${Math.random().toString(36).slice(2)}`;
3892
4023
  }
3893
- var ge = class {
4024
+ var be = class {
3894
4025
  // ── configuração ──────────────────────────────────────────────────────────
3895
4026
  _gatewayUrl;
3896
4027
  _wsFactory;
@@ -3928,7 +4059,7 @@ var ge = class {
3928
4059
  _pendingFrames = [];
3929
4060
  // ── construtor ────────────────────────────────────────────────────────────
3930
4061
  constructor(e) {
3931
- this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? Ir, 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();
4062
+ 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();
3932
4063
  }
3933
4064
  // ── API pública ───────────────────────────────────────────────────────────
3934
4065
  /**
@@ -3942,8 +4073,8 @@ var ge = class {
3942
4073
  */
3943
4074
  subscribe(e, t, r) {
3944
4075
  if (this._closed)
3945
- return Ut();
3946
- let o = Ut();
4076
+ return Qt();
4077
+ let o = Qt();
3947
4078
  this._subscriptions.set(o, {
3948
4079
  subscriptionId: o,
3949
4080
  collection: e,
@@ -4207,7 +4338,7 @@ var ge = class {
4207
4338
  _detachHandlers(e) {
4208
4339
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
4209
4340
  }
4210
- }, Ir = (n) => {
4341
+ }, Hr = (n) => {
4211
4342
  if (typeof WebSocket > "u")
4212
4343
  throw new Error(
4213
4344
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -4216,46 +4347,46 @@ var ge = class {
4216
4347
  };
4217
4348
 
4218
4349
  // src/db/client-db.ts
4219
- var Mr = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, _e = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, Ht = 200;
4220
- function qr(n, e, t) {
4221
- return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? Fr(e.realtimeGatewayUrl, t, e) : Gt(t);
4350
+ var so = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, we = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, an = 200;
4351
+ function ao(n, e, t) {
4352
+ return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? co(e.realtimeGatewayUrl, t, e) : ln(t);
4222
4353
  }
4223
- function Gt(n) {
4354
+ function ln(n) {
4224
4355
  return {
4225
4356
  async pushMutations(e) {
4226
4357
  if (!n)
4227
- throw new y(
4358
+ throw new b(
4228
4359
  "db_unavailable",
4229
4360
  "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
4230
4361
  );
4231
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4362
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4232
4363
  for (let s of e)
4233
4364
  try {
4234
4365
  let a;
4235
4366
  s.op === "add" ? a = await t(n, {
4236
4367
  method: "PUT",
4237
- path: _e(s.collection, s.docId),
4368
+ path: we(s.collection, s.docId),
4238
4369
  body: { data: s.payload ?? {} },
4239
4370
  requireAuth: !0,
4240
4371
  retries: 2,
4241
4372
  headers: i
4242
4373
  }) : s.op === "set" ? a = await t(n, {
4243
4374
  method: "PUT",
4244
- path: _e(s.collection, s.docId),
4375
+ path: we(s.collection, s.docId),
4245
4376
  body: { data: s.payload ?? {} },
4246
4377
  requireAuth: !0,
4247
4378
  retries: 2,
4248
4379
  headers: i
4249
4380
  }) : s.op === "update" ? a = await t(n, {
4250
4381
  method: "PATCH",
4251
- path: _e(s.collection, s.docId),
4382
+ path: we(s.collection, s.docId),
4252
4383
  body: { data: s.payload ?? {}, ...s.upsert ? { upsert: !0 } : {} },
4253
4384
  requireAuth: !0,
4254
4385
  retries: 2,
4255
4386
  headers: i
4256
4387
  }) : a = await t(n, {
4257
4388
  method: "DELETE",
4258
- path: _e(s.collection, s.docId),
4389
+ path: we(s.collection, s.docId),
4259
4390
  requireAuth: !0,
4260
4391
  retries: 2,
4261
4392
  headers: i
@@ -4281,7 +4412,7 @@ function Gt(n) {
4281
4412
  continue;
4282
4413
  }
4283
4414
  if (r.length === 0)
4284
- throw new y("db_unavailable", `pushMutations falhou: ${l}`);
4415
+ throw new b("db_unavailable", `pushMutations falhou: ${l}`);
4285
4416
  break;
4286
4417
  }
4287
4418
  return { results: r };
@@ -4292,13 +4423,13 @@ function Gt(n) {
4292
4423
  async fullResync(e) {
4293
4424
  if (!n)
4294
4425
  return { docs: [], newWatermark: Date.now() };
4295
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = n.tenantId ?? n.productId, o = r ? { "x-neetru-tenant": r } : void 0, i = Date.now(), s = [], a = [];
4426
+ 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 = [];
4296
4427
  for (let l of e) {
4297
4428
  let d;
4298
4429
  try {
4299
4430
  d = await t(n, {
4300
4431
  method: "GET",
4301
- path: Mr(l),
4432
+ path: so(l),
4302
4433
  requireAuth: !0,
4303
4434
  retries: 2,
4304
4435
  headers: o,
@@ -4306,37 +4437,37 @@ function Gt(n) {
4306
4437
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
4307
4438
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
4308
4439
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
4309
- query: { limit: Ht }
4440
+ query: { limit: an }
4310
4441
  });
4311
4442
  } catch (f) {
4312
- let g = f instanceof Error ? f.message : String(f);
4313
- throw new y(
4443
+ let h = f instanceof Error ? f.message : String(f);
4444
+ throw new b(
4314
4445
  "db_unavailable",
4315
- `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${g}`
4446
+ `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${h}`
4316
4447
  );
4317
4448
  }
4318
4449
  let u = d, p = Array.isArray(u?.items) ? u.items : [];
4319
- p.length >= Ht && a.push(l);
4450
+ p.length >= an && a.push(l);
4320
4451
  for (let f of p) {
4321
4452
  if (!f || typeof f != "object") continue;
4322
- let g = f, _ = typeof g.id == "string" ? g.id : null;
4323
- if (!_) continue;
4324
- let { id: M, ...R } = g, N = i, C = R._updatedAt;
4325
- if (typeof C == "number")
4326
- N = C;
4327
- else if (C !== null && typeof C == "object" && typeof C._seconds == "number")
4328
- N = C._seconds * 1e3;
4329
- else if (typeof C == "string") {
4330
- let h = Date.parse(C);
4331
- Number.isNaN(h) || (N = h);
4453
+ let h = f, y = typeof h.id == "string" ? h.id : null;
4454
+ if (!y) continue;
4455
+ let { id: S, ...x } = h, T = i, P = x._updatedAt;
4456
+ if (typeof P == "number")
4457
+ T = P;
4458
+ else if (P !== null && typeof P == "object" && typeof P._seconds == "number")
4459
+ T = P._seconds * 1e3;
4460
+ else if (typeof P == "string") {
4461
+ let m = Date.parse(P);
4462
+ Number.isNaN(m) || (T = m);
4332
4463
  }
4333
- let $ = `rest_${_}_${N}`;
4464
+ let q = `rest_${y}_${T}`;
4334
4465
  s.push({
4335
4466
  collection: l,
4336
- id: _,
4337
- data: R,
4338
- serverVersion: $,
4339
- serverTimestamp: N,
4467
+ id: y,
4468
+ data: x,
4469
+ serverVersion: q,
4470
+ serverTimestamp: T,
4340
4471
  deleted: false
4341
4472
  });
4342
4473
  }
@@ -4345,10 +4476,10 @@ function Gt(n) {
4345
4476
  }
4346
4477
  };
4347
4478
  }
4348
- function Fr(n, e, t) {
4349
- let r = Gt(e), o = new ge({
4479
+ function co(n, e, t) {
4480
+ let r = ln(e), o = new be({
4350
4481
  gatewayUrl: n,
4351
- ticketProvider: jr(e, t),
4482
+ ticketProvider: lo(e, t),
4352
4483
  dbId: t.dbId,
4353
4484
  webSocketFactory: t._wsFactory
4354
4485
  });
@@ -4384,9 +4515,9 @@ function Fr(n, e, t) {
4384
4515
  }
4385
4516
  };
4386
4517
  }
4387
- function jr(n, e) {
4518
+ function lo(n, e) {
4388
4519
  return async () => {
4389
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X));
4520
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y));
4390
4521
  return await t(n, {
4391
4522
  method: "POST",
4392
4523
  path: "/api/sdk/v1/db/realtime/ticket",
@@ -4399,21 +4530,21 @@ function jr(n, e) {
4399
4530
  });
4400
4531
  };
4401
4532
  }
4402
- var Qt = false;
4403
- function Wr(n, e) {
4404
- Qt || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (Qt = true, console.warn(
4533
+ var cn = false;
4534
+ function uo(n, e) {
4535
+ cn || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (cn = true, console.warn(
4405
4536
  '[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.'
4406
4537
  )));
4407
4538
  }
4408
- function Jt(n, e = {}) {
4409
- Wr(n, e);
4539
+ function dn(n, e = {}) {
4540
+ uo(n, e);
4410
4541
  let t;
4411
4542
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
4412
4543
  '[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).'
4413
4544
  ), t = e.engine) : t = "rest";
4414
- let r = qr(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4545
+ 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;
4415
4546
  function l() {
4416
- return s || (s = Lt({
4547
+ return s || (s = Ht({
4417
4548
  dbName: i,
4418
4549
  transport: r,
4419
4550
  singleTab: e.singleTab ?? n.env !== "prod"
@@ -4421,15 +4552,15 @@ function Jt(n, e = {}) {
4421
4552
  }
4422
4553
  return {
4423
4554
  collection(d) {
4424
- return a ? a.collection(d) : $r(d, l);
4555
+ return a ? a.collection(d) : po(d, l);
4425
4556
  },
4426
4557
  async sql(d, u) {
4427
4558
  if (n.env === "dev")
4428
- throw new y(
4559
+ throw new b(
4429
4560
  "db_unavailable",
4430
4561
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4431
4562
  );
4432
- return (await Promise.resolve().then(() => (Kt(), zt))).createSqlClientFromConfig(n, d, u);
4563
+ return (await Promise.resolve().then(() => (sn(), on))).createSqlClientFromConfig(n, d, u);
4433
4564
  },
4434
4565
  get syncState() {
4435
4566
  return a?.syncState ?? {
@@ -4468,7 +4599,7 @@ function Jt(n, e = {}) {
4468
4599
  }
4469
4600
  };
4470
4601
  }
4471
- function $r(n, e) {
4602
+ function po(n, e) {
4472
4603
  async function t() {
4473
4604
  return (await e()).collection(n);
4474
4605
  }
@@ -4547,9 +4678,9 @@ function $r(n, e) {
4547
4678
  }
4548
4679
 
4549
4680
  // src/checkout.ts
4550
- P();
4551
- U();
4552
- function Ke(n, e) {
4681
+ I();
4682
+ M();
4683
+ function Ye(n, e) {
4553
4684
  let t = n?.accessToken || n?.idToken;
4554
4685
  if (!t || typeof t != "string")
4555
4686
  throw new c(
@@ -4558,7 +4689,7 @@ function Ke(n, e) {
4558
4689
  );
4559
4690
  return { requireAuth: false, headers: { authorization: `Bearer ${t}` } };
4560
4691
  }
4561
- function Br(n) {
4692
+ function fo(n) {
4562
4693
  if (!n || typeof n != "object")
4563
4694
  throw new c("invalid_response", "checkout.start response is not an object");
4564
4695
  let e = n;
@@ -4574,7 +4705,7 @@ function Br(n) {
4574
4705
  requiresKyc: e.requiresKyc === true
4575
4706
  };
4576
4707
  }
4577
- function Vr(n) {
4708
+ function mo(n) {
4578
4709
  if (!n || typeof n != "object")
4579
4710
  throw new c("invalid_response", "checkout.get response is not an object");
4580
4711
  let e = n, t = e.intent;
@@ -4596,20 +4727,20 @@ function Vr(n) {
4596
4727
  isStale: e.isStale === true
4597
4728
  };
4598
4729
  }
4599
- function zr() {
4730
+ function ho() {
4600
4731
  try {
4601
4732
  return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
4602
4733
  } catch {
4603
4734
  return false;
4604
4735
  }
4605
4736
  }
4606
- function Kr(n) {
4737
+ function go(n) {
4607
4738
  try {
4608
4739
  globalThis.location.assign(n);
4609
4740
  } catch {
4610
4741
  }
4611
4742
  }
4612
- function Hr(n) {
4743
+ function yo(n) {
4613
4744
  return {
4614
4745
  async start(e) {
4615
4746
  if (!e?.productId)
@@ -4624,7 +4755,7 @@ function Hr(n) {
4624
4755
  callbackUrl: e.callbackUrl
4625
4756
  };
4626
4757
  e.tenantType && (t.targetTenantType = e.tenantType), e.tenantId && (t.targetTenantId = e.tenantId);
4627
- let { requireAuth: r, headers: o } = Ke(
4758
+ let { requireAuth: r, headers: o } = Ye(
4628
4759
  { accessToken: e.accessToken, idToken: e.idToken },
4629
4760
  "start"
4630
4761
  ), i = await v(n, {
@@ -4634,13 +4765,13 @@ function Hr(n) {
4634
4765
  requireAuth: r,
4635
4766
  headers: o,
4636
4767
  idempotencyKey: true
4637
- }), s = Br(i);
4638
- return e.autoRedirect !== false && zr() && Kr(s.redirectUrl), s;
4768
+ }), s = fo(i);
4769
+ return e.autoRedirect !== false && ho() && go(s.redirectUrl), s;
4639
4770
  },
4640
4771
  async get(e, t) {
4641
4772
  if (!e || typeof e != "string")
4642
4773
  throw new c("validation_failed", "checkout.get: intentId is required");
4643
- let { requireAuth: r, headers: o } = Ke(
4774
+ let { requireAuth: r, headers: o } = Ye(
4644
4775
  { accessToken: t?.accessToken, idToken: t?.idToken },
4645
4776
  "get"
4646
4777
  ), i = await v(n, {
@@ -4649,12 +4780,12 @@ function Hr(n) {
4649
4780
  requireAuth: r,
4650
4781
  headers: o
4651
4782
  });
4652
- return Vr(i);
4783
+ return mo(i);
4653
4784
  },
4654
4785
  async cancel(e, t) {
4655
4786
  if (!e || typeof e != "string")
4656
4787
  throw new c("validation_failed", "checkout.cancel: intentId is required");
4657
- let { requireAuth: r, headers: o } = Ke(
4788
+ let { requireAuth: r, headers: o } = Ye(
4658
4789
  { accessToken: t?.accessToken, idToken: t?.idToken },
4659
4790
  "cancel"
4660
4791
  );
@@ -4670,7 +4801,7 @@ function Hr(n) {
4670
4801
  }
4671
4802
  };
4672
4803
  }
4673
- var He = class {
4804
+ var Ze = class {
4674
4805
  intents = /* @__PURE__ */ new Map();
4675
4806
  async start(e) {
4676
4807
  if (!e?.productId)
@@ -4713,14 +4844,14 @@ var He = class {
4713
4844
  return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
4714
4845
  }
4715
4846
  };
4716
- function Xt(n) {
4717
- return n.env === "dev" ? new He() : Hr(n);
4847
+ function un(n) {
4848
+ return n.env === "dev" ? new Ze() : yo(n);
4718
4849
  }
4719
4850
 
4720
4851
  // src/webhooks.ts
4721
- P();
4722
- U();
4723
- var Zt = [
4852
+ I();
4853
+ M();
4854
+ var fn = [
4724
4855
  "subscription.activated",
4725
4856
  "subscription.cancelled",
4726
4857
  "subscription.payment_failed",
@@ -4730,7 +4861,7 @@ var Zt = [
4730
4861
  "account.reactivated",
4731
4862
  "support.ticket_replied"
4732
4863
  ];
4733
- function Yt(n) {
4864
+ function pn(n) {
4734
4865
  if (!n || typeof n != "object")
4735
4866
  throw new c("invalid_response", "Webhook response is not an object");
4736
4867
  let e = n;
@@ -4740,7 +4871,7 @@ function Yt(n) {
4740
4871
  id: e.id,
4741
4872
  url: typeof e.url == "string" ? e.url : "",
4742
4873
  events: Array.isArray(e.events) ? e.events.filter(
4743
- (t) => Zt.includes(t)
4874
+ (t) => fn.includes(t)
4744
4875
  ) : [],
4745
4876
  hasSecret: e.hasSecret === true,
4746
4877
  status: e.status === "active" || e.status === "degraded" || e.status === "disabled" ? e.status : "active",
@@ -4749,7 +4880,7 @@ function Yt(n) {
4749
4880
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString()
4750
4881
  };
4751
4882
  }
4752
- function en(n) {
4883
+ function mn(n) {
4753
4884
  if (!n.url || typeof n.url != "string")
4754
4885
  throw new c("validation_failed", "url \xE9 obrigat\xF3ria");
4755
4886
  try {
@@ -4762,27 +4893,27 @@ function en(n) {
4762
4893
  if (!Array.isArray(n.events) || n.events.length === 0)
4763
4894
  throw new c("validation_failed", "events deve ter pelo menos 1 evento");
4764
4895
  for (let e of n.events)
4765
- if (!Zt.includes(e))
4896
+ if (!fn.includes(e))
4766
4897
  throw new c("validation_failed", `evento desconhecido: ${e}`);
4767
4898
  if (n.secret !== void 0 && n.secret.length < 16)
4768
4899
  throw new c("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4769
4900
  }
4770
- function be(n, ...e) {
4901
+ function ke(n, ...e) {
4771
4902
  for (let t of e)
4772
4903
  if (typeof t == "string" && t.length > 0)
4773
- return x("productId", t), t;
4904
+ return N("productId", t), t;
4774
4905
  if (n.productId)
4775
- return x("productId", n.productId), n.productId;
4906
+ return N("productId", n.productId), n.productId;
4776
4907
  throw new c(
4777
4908
  "validation_failed",
4778
4909
  "productId required (pass to options/input or set on createNeetruClient)"
4779
4910
  );
4780
4911
  }
4781
- function tn(n) {
4912
+ function hn(n) {
4782
4913
  return {
4783
4914
  async register(e) {
4784
- en(e);
4785
- let t = be(n, e.productId), r = await v(n, {
4915
+ mn(e);
4916
+ let t = ke(n, e.productId), r = await v(n, {
4786
4917
  method: "POST",
4787
4918
  path: "/api/sdk/v1/webhooks",
4788
4919
  body: {
@@ -4798,20 +4929,20 @@ function tn(n) {
4798
4929
  // dedup TTL 24h (mesmo padrão de usage.report/support.createTicket).
4799
4930
  idempotencyKey: true
4800
4931
  });
4801
- return Yt(r);
4932
+ return pn(r);
4802
4933
  },
4803
4934
  async list(e) {
4804
- let t = be(n, e?.productId), r = await v(n, {
4935
+ let t = ke(n, e?.productId), r = await v(n, {
4805
4936
  method: "GET",
4806
4937
  path: "/api/sdk/v1/webhooks",
4807
4938
  query: { productId: t },
4808
4939
  requireAuth: true
4809
4940
  });
4810
- return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(Yt);
4941
+ return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(pn);
4811
4942
  },
4812
4943
  async unregister(e, t) {
4813
4944
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4814
- let r = be(n, t?.productId);
4945
+ let r = ke(n, t?.productId);
4815
4946
  return await v(n, {
4816
4947
  method: "DELETE",
4817
4948
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}`,
@@ -4821,7 +4952,7 @@ function tn(n) {
4821
4952
  },
4822
4953
  async test(e, t) {
4823
4954
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4824
- let r = be(n, t?.productId), o = await v(n, {
4955
+ let r = ke(n, t?.productId), o = await v(n, {
4825
4956
  method: "POST",
4826
4957
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}/test`,
4827
4958
  query: { productId: r },
@@ -4840,11 +4971,11 @@ function tn(n) {
4840
4971
  }
4841
4972
  };
4842
4973
  }
4843
- var ve = class {
4974
+ var Se = class {
4844
4975
  endpoints = /* @__PURE__ */ new Map();
4845
4976
  nextId = 1;
4846
4977
  async register(e) {
4847
- en(e);
4978
+ mn(e);
4848
4979
  let t = `mock_wh_${this.nextId++}`, r = {
4849
4980
  id: t,
4850
4981
  url: e.url,
@@ -4871,21 +5002,21 @@ var ve = class {
4871
5002
  };
4872
5003
 
4873
5004
  // src/notifications.ts
4874
- P();
4875
- U();
4876
- var Qe = [
5005
+ I();
5006
+ M();
5007
+ var et = [
4877
5008
  "info",
4878
5009
  "success",
4879
5010
  "warning",
4880
5011
  "error"
4881
5012
  ];
4882
- function nn(n) {
5013
+ function gn(n) {
4883
5014
  if (!n || typeof n != "object")
4884
5015
  throw new c("invalid_response", "Notification response is not an object");
4885
5016
  let e = n;
4886
5017
  if (typeof e.id != "string")
4887
5018
  throw new c("invalid_response", "Notification missing id");
4888
- let t = Qe.includes(e.severity) ? e.severity : "info";
5019
+ let t = et.includes(e.severity) ? e.severity : "info";
4889
5020
  return {
4890
5021
  id: e.id,
4891
5022
  userId: typeof e.userId == "string" ? e.userId : "",
@@ -4900,37 +5031,37 @@ function nn(n) {
4900
5031
  dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
4901
5032
  };
4902
5033
  }
4903
- function rn(n) {
5034
+ function yn(n) {
4904
5035
  if (!n.userId) throw new c("validation_failed", "userId obrigat\xF3rio");
4905
5036
  if (!n.kind) throw new c("validation_failed", "kind obrigat\xF3rio");
4906
5037
  if (!n.title) throw new c("validation_failed", "title obrigat\xF3rio");
4907
- if (n.severity && !Qe.includes(n.severity))
5038
+ if (n.severity && !et.includes(n.severity))
4908
5039
  throw new c(
4909
5040
  "validation_failed",
4910
- `severity inv\xE1lida: ${n.severity} (use ${Qe.join("|")})`
5041
+ `severity inv\xE1lida: ${n.severity} (use ${et.join("|")})`
4911
5042
  );
4912
5043
  if (n.title.length > 200)
4913
5044
  throw new c("validation_failed", "title m\xE1x 200 chars");
4914
5045
  if (n.body && n.body.length > 2e3)
4915
5046
  throw new c("validation_failed", "body m\xE1x 2000 chars");
4916
5047
  }
4917
- function we(n, ...e) {
5048
+ function Te(n, ...e) {
4918
5049
  for (let t of e)
4919
5050
  if (typeof t == "string" && t.length > 0)
4920
- return x("productId", t), t;
5051
+ return N("productId", t), t;
4921
5052
  if (n.productId)
4922
- return x("productId", n.productId), n.productId;
5053
+ return N("productId", n.productId), n.productId;
4923
5054
  throw new c(
4924
5055
  "validation_failed",
4925
5056
  "productId required (pass to options/input or set on createNeetruClient)"
4926
5057
  );
4927
5058
  }
4928
- function on(n) {
5059
+ function _n(n) {
4929
5060
  return {
4930
5061
  async send(e) {
4931
- rn(e);
5062
+ yn(e);
4932
5063
  let r = {
4933
- productId: we(n, e.productId),
5064
+ productId: Te(n, e.productId),
4934
5065
  userId: e.userId,
4935
5066
  kind: e.kind,
4936
5067
  title: e.title,
@@ -4944,12 +5075,12 @@ function on(n) {
4944
5075
  requireAuth: true,
4945
5076
  idempotencyKey: true
4946
5077
  });
4947
- return nn(o);
5078
+ return gn(o);
4948
5079
  },
4949
5080
  async list(e, t) {
4950
5081
  if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
4951
5082
  let o = {
4952
- productId: we(n, t?.productId)
5083
+ productId: Te(n, t?.productId)
4953
5084
  };
4954
5085
  t?.includeDismissed && (o.includeDismissed = true), t?.onlyUnread && (o.onlyUnread = true), t?.limit && (o.limit = Math.min(Math.max(1, t.limit), 200));
4955
5086
  let i = await v(n, {
@@ -4958,11 +5089,11 @@ function on(n) {
4958
5089
  query: o,
4959
5090
  requireAuth: true
4960
5091
  });
4961
- return (Array.isArray(i?.notifications) ? i.notifications : []).map(nn);
5092
+ return (Array.isArray(i?.notifications) ? i.notifications : []).map(gn);
4962
5093
  },
4963
5094
  async markRead(e, t) {
4964
5095
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4965
- let r = we(n, t?.productId);
5096
+ let r = Te(n, t?.productId);
4966
5097
  return await v(n, {
4967
5098
  method: "POST",
4968
5099
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/read`,
@@ -4972,7 +5103,7 @@ function on(n) {
4972
5103
  },
4973
5104
  async dismiss(e, t) {
4974
5105
  if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4975
- let r = we(n, t?.productId);
5106
+ let r = Te(n, t?.productId);
4976
5107
  return await v(n, {
4977
5108
  method: "POST",
4978
5109
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/dismiss`,
@@ -4982,11 +5113,11 @@ function on(n) {
4982
5113
  }
4983
5114
  };
4984
5115
  }
4985
- var ke = class {
5116
+ var Re = class {
4986
5117
  notifications = /* @__PURE__ */ new Map();
4987
5118
  nextId = 1;
4988
5119
  async send(e) {
4989
- if (rn(e), e.fingerprint) {
5120
+ if (yn(e), e.fingerprint) {
4990
5121
  let o = Date.now() - 864e5;
4991
5122
  for (let i of this.notifications.values())
4992
5123
  if ((i.metadata ?? {}).fingerprint === e.fingerprint && i.userId === e.userId && new Date(i.createdAt).getTime() > o)
@@ -5023,43 +5154,44 @@ var ke = class {
5023
5154
  };
5024
5155
 
5025
5156
  // src/ai.ts
5026
- P();
5027
- U();
5028
- var Qr = "/api/sdk/v1/ai/chat", sn = 12e4, Se = 32768, an = 32, cn = 4194304, ln = 2048, Gr = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, Jr = /^https:\/\/[^\s]+$/, Xr = /* @__PURE__ */ new Set(["low", "high", "auto"]), Yr = /* @__PURE__ */ new Set(["system", "user", "assistant"]), dn = 100, un = 128, pn = 32768, fn = 0, mn = 2, hn = 200, gn = 20, yn = 12 * 1024 * 1024, _n = 5e4, bn = 16, vn = 500, Zr = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), eo = /^[a-zA-Z0-9_-]+$/;
5029
- function w(n) {
5157
+ I();
5158
+ M();
5159
+ Me();
5160
+ 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_-]+$/;
5161
+ function k(n) {
5030
5162
  throw new c("validation_failed", n);
5031
5163
  }
5032
- function to(n) {
5164
+ function Ro(n) {
5033
5165
  if (n.length === 0 || n.length % 4 !== 0) return false;
5034
5166
  let e = n.endsWith("==") ? 2 : n.endsWith("=") ? 1 : 0;
5035
5167
  return !(e > 0 ? n.slice(0, n.length - e) : n).includes("=");
5036
5168
  }
5037
- function no(n) {
5169
+ function Io(n) {
5038
5170
  let e = n.indexOf(",");
5039
5171
  if (e === -1) return 0;
5040
5172
  let t = n.slice(e + 1), r = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
5041
5173
  return Math.max(0, Math.floor(t.length * 3 / 4) - r);
5042
5174
  }
5043
- function ro(n) {
5175
+ function Co(n) {
5044
5176
  let e = 0, t = 0, r = 0;
5045
5177
  for (let o of n) {
5046
5178
  let i = o?.content;
5047
5179
  if (Array.isArray(i))
5048
5180
  for (let s of i) {
5049
- if (e++, e > hn)
5050
- return `ai: total content parts exceeds ${hn} per request`;
5181
+ if (e++, e > An)
5182
+ return `ai: total content parts exceeds ${An} per request`;
5051
5183
  if (s && typeof s == "object" && s.type === "image_url") {
5052
- if (t++, t > gn)
5053
- return `ai: total images exceeds ${gn} per request`;
5184
+ if (t++, t > En)
5185
+ return `ai: total images exceeds ${En} per request`;
5054
5186
  let a = s.image_url?.url;
5055
- if (typeof a == "string" && a.startsWith("data:") && (r += no(a), r > yn))
5056
- return `ai: aggregate image bytes exceeds ${yn} per request`;
5187
+ if (typeof a == "string" && a.startsWith("data:") && (r += Io(a), r > Pn))
5188
+ return `ai: aggregate image bytes exceeds ${Pn} per request`;
5057
5189
  }
5058
5190
  }
5059
5191
  }
5060
5192
  return null;
5061
5193
  }
5062
- function oo(n) {
5194
+ function Ao(n) {
5063
5195
  if (n === void 0) return null;
5064
5196
  if (n === null || typeof n != "object")
5065
5197
  return "ai: responseFormat json_schema.schema must be an object";
@@ -5070,11 +5202,11 @@ function oo(n) {
5070
5202
  return "ai: responseFormat json_schema.schema is not serializable";
5071
5203
  }
5072
5204
  if (e === void 0) return "ai: responseFormat json_schema.schema is invalid";
5073
- if (e.length > _n)
5074
- return `ai: responseFormat json_schema.schema exceeds ${_n} serialized chars`;
5205
+ if (e.length > Dn)
5206
+ return `ai: responseFormat json_schema.schema exceeds ${Dn} serialized chars`;
5075
5207
  let t = 0, r = (o, i) => {
5076
- if (i > bn)
5077
- return `ai: responseFormat json_schema.schema exceeds max depth ${bn}`;
5208
+ if (i > Nn)
5209
+ return `ai: responseFormat json_schema.schema exceeds max depth ${Nn}`;
5078
5210
  if (Array.isArray(o)) {
5079
5211
  for (let s of o) {
5080
5212
  let a = r(s, i + 1);
@@ -5084,10 +5216,10 @@ function oo(n) {
5084
5216
  }
5085
5217
  if (o && typeof o == "object")
5086
5218
  for (let s of Object.getOwnPropertyNames(o)) {
5087
- if (Zr.has(s))
5219
+ if (So.has(s))
5088
5220
  return `ai: responseFormat json_schema.schema has forbidden key: ${s}`;
5089
- if (t++, t > vn)
5090
- return `ai: responseFormat json_schema.schema exceeds ${vn} keys`;
5221
+ if (t++, t > xn)
5222
+ return `ai: responseFormat json_schema.schema exceeds ${xn} keys`;
5091
5223
  let a = r(o[s], i + 1);
5092
5224
  if (a) return a;
5093
5225
  }
@@ -5095,80 +5227,80 @@ function oo(n) {
5095
5227
  };
5096
5228
  return r(n, 0);
5097
5229
  }
5098
- function io(n) {
5099
- (typeof n != "string" || n.length === 0) && w("ai: image_url.url must be a non-empty string");
5230
+ function Eo(n) {
5231
+ (typeof n != "string" || n.length === 0) && k("ai: image_url.url must be a non-empty string");
5100
5232
  let e = n;
5101
5233
  if (e.startsWith("data:")) {
5102
- e.length > cn && w(`ai: image_url.url (data:) exceeds ${cn} chars`), Gr.test(e) || w("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5234
+ 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,<...>");
5103
5235
  let t = e.slice(e.indexOf(",") + 1);
5104
- to(t) || w("ai: image_url.url data: has invalid base64 (length/padding)");
5236
+ Ro(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5105
5237
  return;
5106
5238
  }
5107
5239
  if (e.startsWith("https://")) {
5108
- e.length > ln && w(`ai: image_url.url (https:) exceeds ${ln} chars`), Jr.test(e) || w("ai: image_url.url https: is invalid");
5240
+ e.length > kn && k(`ai: image_url.url (https:) exceeds ${kn} chars`), vo.test(e) || k("ai: image_url.url https: is invalid");
5109
5241
  return;
5110
5242
  }
5111
- w("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5243
+ k("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5112
5244
  }
5113
- function so(n, e) {
5245
+ function Po(n, e) {
5114
5246
  if (typeof n == "string") {
5115
- n.length === 0 && w("ai: message content string must be non-empty"), n.length > Se && w(`ai: message content exceeds ${Se} chars`);
5247
+ n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ie && k(`ai: message content exceeds ${Ie} chars`);
5116
5248
  return;
5117
5249
  }
5118
- (!Array.isArray(n) || n.length === 0) && w("ai: message content must be a non-empty string or array of parts"), n.length > an && w(`ai: message content has more than ${an} parts`);
5250
+ (!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`);
5119
5251
  for (let t of n) {
5120
- (!t || typeof t != "object") && w("ai: each content part must be an object");
5252
+ (!t || typeof t != "object") && k("ai: each content part must be an object");
5121
5253
  let r = t.type;
5122
5254
  if (r === "text") {
5123
5255
  let o = t.text;
5124
- (typeof o != "string" || o.length === 0) && w("ai: text part must have non-empty { text: string }"), o.length > Se && w(`ai: text part exceeds ${Se} chars`);
5256
+ (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`);
5125
5257
  } else if (r === "image_url") {
5126
- e !== "user" && w(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5258
+ e !== "user" && k(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5127
5259
  let o = t.image_url;
5128
- (!o || typeof o != "object") && w("ai: image_url part must have { image_url: { url } }"), io(o.url);
5260
+ (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Eo(o.url);
5129
5261
  let i = o.detail;
5130
- i !== void 0 && (typeof i != "string" || !Xr.has(i)) && w("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5262
+ i !== void 0 && (typeof i != "string" || !wo.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5131
5263
  } else
5132
- w("ai: content part type must be 'text' or 'image_url'");
5264
+ k("ai: content part type must be 'text' or 'image_url'");
5133
5265
  }
5134
5266
  }
5135
- function ao(n) {
5136
- (!n || typeof n != "object") && w("ai: responseFormat must be an object");
5267
+ function Do(n) {
5268
+ (!n || typeof n != "object") && k("ai: responseFormat must be an object");
5137
5269
  let e = n.type;
5138
5270
  if (!(e === "text" || e === "json_object")) {
5139
5271
  if (e === "json_schema") {
5140
5272
  let t = n.json_schema;
5141
- (!t || typeof t != "object") && w("ai: responseFormat json_schema requires { json_schema: { name } }");
5273
+ (!t || typeof t != "object") && k("ai: responseFormat json_schema requires { json_schema: { name } }");
5142
5274
  let r = t, o = r.name;
5143
- if ((typeof o != "string" || o.length === 0) && w("ai: responseFormat json_schema.name is required"), o.length > 64 && w("ai: responseFormat json_schema.name exceeds 64 chars"), eo.test(o) || w("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && w("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && w("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && w("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
5144
- let i = oo(r.schema);
5145
- i && w(i);
5275
+ 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) {
5276
+ let i = Ao(r.schema);
5277
+ i && k(i);
5146
5278
  }
5147
5279
  return;
5148
5280
  }
5149
- w("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5281
+ k("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5150
5282
  }
5151
5283
  }
5152
- function wn(n, e, t) {
5284
+ function On(n, e, t) {
5153
5285
  if (!e || typeof e != "object")
5154
5286
  throw new c("validation_failed", "ai: options object is required");
5155
5287
  if (typeof e.model != "string" || e.model.length === 0)
5156
5288
  throw new c("validation_failed", "ai: model is required");
5157
- if (e.model.length > un)
5158
- throw new c("validation_failed", `ai: model exceeds ${un} chars`);
5289
+ if (e.model.length > Tn)
5290
+ throw new c("validation_failed", `ai: model exceeds ${Tn} chars`);
5159
5291
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5160
5292
  throw new c("validation_failed", "ai: messages must be a non-empty array");
5161
- if (e.messages.length > dn)
5162
- throw new c("validation_failed", `ai: messages exceeds ${dn} per request`);
5293
+ if (e.messages.length > Sn)
5294
+ throw new c("validation_failed", `ai: messages exceeds ${Sn} per request`);
5163
5295
  for (let a of e.messages) {
5164
- if (!a || typeof a != "object" || typeof a.role != "string" || !Yr.has(a.role))
5296
+ if (!a || typeof a != "object" || typeof a.role != "string" || !ko.has(a.role))
5165
5297
  throw new c(
5166
5298
  "validation_failed",
5167
5299
  "ai: each message role must be 'system' | 'user' | 'assistant'"
5168
5300
  );
5169
- so(a.content, a.role);
5301
+ Po(a.content, a.role);
5170
5302
  }
5171
- let r = ro(e.messages);
5303
+ let r = Co(e.messages);
5172
5304
  if (r) throw new c("validation_failed", r);
5173
5305
  let o = e.productId ?? n.productId, i = e.tenantId ?? n.tenantId;
5174
5306
  if (!o)
@@ -5181,7 +5313,7 @@ function wn(n, e, t) {
5181
5313
  "validation_failed",
5182
5314
  "ai: tenantId required (pass to options or set on createNeetruClient)"
5183
5315
  );
5184
- x("productId", o), x("tenantId", i);
5316
+ N("productId", o), N("tenantId", i);
5185
5317
  let s = {
5186
5318
  productId: o,
5187
5319
  tenantId: i,
@@ -5190,24 +5322,24 @@ function wn(n, e, t) {
5190
5322
  stream: t
5191
5323
  };
5192
5324
  if (e.maxTokens !== void 0) {
5193
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > pn)
5325
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Rn)
5194
5326
  throw new c(
5195
5327
  "validation_failed",
5196
- `ai: maxTokens must be a positive integer <= ${pn}`
5328
+ `ai: maxTokens must be a positive integer <= ${Rn}`
5197
5329
  );
5198
5330
  s.maxTokens = e.maxTokens;
5199
5331
  }
5200
5332
  if (e.temperature !== void 0) {
5201
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < fn || e.temperature > mn)
5333
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < In || e.temperature > Cn)
5202
5334
  throw new c(
5203
5335
  "validation_failed",
5204
- `ai: temperature must be a finite number between ${fn} and ${mn}`
5336
+ `ai: temperature must be a finite number between ${In} and ${Cn}`
5205
5337
  );
5206
5338
  s.temperature = e.temperature;
5207
5339
  }
5208
- return e.responseFormat !== void 0 && (ao(e.responseFormat), s.responseFormat = e.responseFormat), s;
5340
+ return e.responseFormat !== void 0 && (Do(e.responseFormat), s.responseFormat = e.responseFormat), s;
5209
5341
  }
5210
- async function Rn(n) {
5342
+ async function qn(n) {
5211
5343
  try {
5212
5344
  let e = await n.text();
5213
5345
  return e ? JSON.parse(e) : void 0;
@@ -5215,48 +5347,48 @@ async function Rn(n) {
5215
5347
  return;
5216
5348
  }
5217
5349
  }
5218
- function co(n, e) {
5350
+ function No(n, e) {
5219
5351
  let t = n.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
5220
5352
  return `${t}${r}`;
5221
5353
  }
5222
- async function kn(n, e, t, r) {
5354
+ async function Ln(n, e, t, r) {
5223
5355
  if (!n.apiKey)
5224
5356
  throw new c(
5225
5357
  "missing_api_key",
5226
5358
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
5227
5359
  );
5228
- let o = co(n.baseUrl, Qr), s = { method: "POST", headers: {
5360
+ let o = No(n.baseUrl, _o), { headers: i, correlationId: s } = ae({
5229
5361
  "content-type": "application/json",
5230
5362
  accept: r ? "text/event-stream" : "application/json",
5231
5363
  authorization: `Bearer ${n.apiKey}`
5232
- }, body: JSON.stringify(e) };
5233
- r ? t && (s.signal = t) : s.signal = t ?? AbortSignal.timeout(sn);
5234
- let a;
5364
+ }), a = { method: "POST", headers: i, body: JSON.stringify(e) };
5365
+ r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(bn);
5366
+ let l;
5235
5367
  try {
5236
- a = await n.fetch(o, s);
5237
- } catch (u) {
5238
- let p = u instanceof DOMException && u.name === "TimeoutError" ? `Network error: timeout after ${sn / 1e3}s` : u instanceof DOMException && u.name === "AbortError" ? "Network error: request aborted" : `Network error: ${u instanceof Error ? u.message : "fetch failed"}`;
5239
- throw new c("network_error", p);
5240
- }
5241
- let l = a.headers.get("x-request-id") ?? a.headers.get("x-correlation-id") ?? void 0;
5242
- if (!a.ok) {
5243
- let u = await Rn(a), p = se(a.status), f = `HTTP ${a.status}`;
5244
- if (u && typeof u == "object" && "error" in u) {
5245
- let g = u.error;
5246
- typeof g == "string" ? f = g : g && typeof g == "object" && (typeof g.code == "string" && (p = g.code), typeof g.message == "string" && (f = g.message));
5368
+ l = await n.fetch(o, a);
5369
+ } catch (p) {
5370
+ 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"}`;
5371
+ throw new c("network_error", f, void 0, void 0, void 0, s);
5372
+ }
5373
+ let d = l.headers.get("x-request-id") ?? l.headers.get("x-correlation-id") ?? void 0;
5374
+ if (!l.ok) {
5375
+ let p = await qn(l), f = le(l.status), h = `HTTP ${l.status}`;
5376
+ if (p && typeof p == "object" && "error" in p) {
5377
+ let y = p.error;
5378
+ typeof y == "string" ? h = y : y && typeof y == "object" && (typeof y.code == "string" && (f = y.code), typeof y.message == "string" && (h = y.message));
5247
5379
  }
5248
- throw new c(p, f, a.status, l);
5380
+ throw new c(f, h, l.status, d, void 0, s);
5249
5381
  }
5250
- let d = a.headers.get("x-neetru-version");
5251
- return d && ie(d), a;
5382
+ let u = l.headers.get("x-neetru-version");
5383
+ return u && ce(u), l;
5252
5384
  }
5253
- function Sn(n) {
5385
+ function Un(n) {
5254
5386
  return {
5255
5387
  provider: n.headers.get("x-neetru-provider") ?? "",
5256
5388
  usageWarning: n.headers.get("x-neetru-ai-usage-warning") === "1"
5257
5389
  };
5258
5390
  }
5259
- function Tn(n) {
5391
+ function Mn(n) {
5260
5392
  let e = [];
5261
5393
  for (let r of n.split(`
5262
5394
  `)) {
@@ -5277,10 +5409,10 @@ function Tn(n) {
5277
5409
  return null;
5278
5410
  }
5279
5411
  }
5280
- function In(n) {
5412
+ function Fn(n) {
5281
5413
  return {
5282
5414
  async chat(e) {
5283
- let t = wn(n, e, false), r = await kn(n, t, e.signal, false), { provider: o, usageWarning: i } = Sn(r), s = await Rn(r);
5415
+ let t = On(n, e, false), r = await Ln(n, t, e.signal, false), { provider: o, usageWarning: i } = Un(r), s = await qn(r);
5284
5416
  if (!s || s.ok !== true || !Array.isArray(s.choices))
5285
5417
  throw new c("invalid_response", "ai.chat response missing ok/choices");
5286
5418
  return {
@@ -5292,7 +5424,7 @@ function In(n) {
5292
5424
  };
5293
5425
  },
5294
5426
  stream(e) {
5295
- let t = wn(n, e, true), r = kn(n, t, e.signal, true), o = r.then(Sn);
5427
+ let t = On(n, e, true), r = Ln(n, t, e.signal, true), o = r.then(Un);
5296
5428
  o.catch(() => {
5297
5429
  });
5298
5430
  async function* i() {
@@ -5302,23 +5434,23 @@ function In(n) {
5302
5434
  let l = a.getReader(), d = new TextDecoder(), u = "";
5303
5435
  try {
5304
5436
  for (; ; ) {
5305
- let { done: f, value: g } = await l.read();
5437
+ let { done: f, value: h } = await l.read();
5306
5438
  if (f) break;
5307
- u += d.decode(g, { stream: !0 });
5308
- let _;
5309
- for (; (_ = u.indexOf(`
5439
+ u += d.decode(h, { stream: !0 });
5440
+ let y;
5441
+ for (; (y = u.indexOf(`
5310
5442
 
5311
5443
  `)) !== -1; ) {
5312
- let M = u.slice(0, _);
5313
- u = u.slice(_ + 2);
5314
- let R = Tn(M);
5315
- if (R && "done" in R) return;
5316
- R && "content" in R && (yield R.content);
5444
+ let S = u.slice(0, y);
5445
+ u = u.slice(y + 2);
5446
+ let x = Mn(S);
5447
+ if (x && "done" in x) return;
5448
+ x && "content" in x && (yield x.content);
5317
5449
  }
5318
5450
  }
5319
5451
  let p = u.trim();
5320
5452
  if (p) {
5321
- let f = Tn(p);
5453
+ let f = Mn(p);
5322
5454
  f && "content" in f && (yield f.content);
5323
5455
  }
5324
5456
  } finally {
@@ -5341,10 +5473,10 @@ function In(n) {
5341
5473
  }
5342
5474
 
5343
5475
  // src/mocks.ts
5344
- P();
5476
+ I();
5345
5477
 
5346
5478
  // src/runtime-env.ts
5347
- function Te() {
5479
+ function Ce() {
5348
5480
  try {
5349
5481
  if (typeof process < "u" && process.env)
5350
5482
  return process.env.NODE_ENV === "production";
@@ -5354,19 +5486,19 @@ function Te() {
5354
5486
  }
5355
5487
 
5356
5488
  // src/mocks.ts
5357
- var Ge = Object.freeze({
5489
+ var tt = Object.freeze({
5358
5490
  uid: "dev-fixture-uid-0001",
5359
5491
  email: "dev@neetru.local",
5360
5492
  emailVerified: true,
5361
5493
  displayName: "Dev Fixture",
5362
5494
  isCustomer: true,
5363
5495
  isStaff: false
5364
- }), Re = class {
5496
+ }), Ae = class {
5365
5497
  _user;
5366
5498
  _listeners;
5367
5499
  _allowUnsignedDecode;
5368
5500
  constructor(e = null, t) {
5369
- if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Te())
5501
+ if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Ce())
5370
5502
  throw new c(
5371
5503
  "invalid_config",
5372
5504
  "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."
@@ -5376,7 +5508,7 @@ var Ge = Object.freeze({
5376
5508
  );
5377
5509
  }
5378
5510
  async signIn(e) {
5379
- return this._user || (this._user = { ...Ge }), this._notify(), this._user;
5511
+ return this._user || (this._user = { ...tt }), this._notify(), this._user;
5380
5512
  }
5381
5513
  async signOut() {
5382
5514
  this._user = null, this._notify();
@@ -5497,7 +5629,7 @@ var Ge = Object.freeze({
5497
5629
  } catch {
5498
5630
  }
5499
5631
  }
5500
- }, Ie = class {
5632
+ }, Ee = class {
5501
5633
  _reports = [];
5502
5634
  _quotas;
5503
5635
  _counters = /* @__PURE__ */ new Map();
@@ -5559,7 +5691,7 @@ var Ge = Object.freeze({
5559
5691
  __reset() {
5560
5692
  this._reports = [], this._quotas.clear(), this._counters.clear();
5561
5693
  }
5562
- }, Ce = class {
5694
+ }, Pe = class {
5563
5695
  _tickets = [];
5564
5696
  _ticketSeq = 0;
5565
5697
  async createTicket(e) {
@@ -5636,7 +5768,7 @@ var Ge = Object.freeze({
5636
5768
  __reset() {
5637
5769
  this._tickets = [], this._ticketSeq = 0;
5638
5770
  }
5639
- }, Ae = class {
5771
+ }, De = class {
5640
5772
  _denied = /* @__PURE__ */ new Set();
5641
5773
  async check(e, t) {
5642
5774
  return !this._denied.has(`${e}:${t}`);
@@ -5659,7 +5791,7 @@ var Ge = Object.freeze({
5659
5791
  this._denied.clear();
5660
5792
  }
5661
5793
  };
5662
- var Pe = class {
5794
+ var Ne = class {
5663
5795
  _calls = [];
5664
5796
  /** Extrai texto de um content string OU array multimodal (imagens ignoradas). */
5665
5797
  _contentToText(e) {
@@ -5707,8 +5839,8 @@ var Pe = class {
5707
5839
  };
5708
5840
 
5709
5841
  // src/auth-pkce-shared.ts
5710
- P();
5711
- function Cn() {
5842
+ I();
5843
+ function jn() {
5712
5844
  let n = globalThis.crypto;
5713
5845
  if (!n || typeof n.getRandomValues != "function" || !n.subtle)
5714
5846
  throw new c(
@@ -5717,36 +5849,36 @@ function Cn() {
5717
5849
  );
5718
5850
  return n;
5719
5851
  }
5720
- function An(n) {
5852
+ function $n(n) {
5721
5853
  let e = "";
5722
5854
  for (let r of n) e += String.fromCharCode(r);
5723
5855
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
5724
5856
  }
5725
- function Ee(n, e) {
5857
+ function xe(n, e) {
5726
5858
  let t = new Uint8Array(e);
5727
- return n.getRandomValues(t), An(t);
5859
+ return n.getRandomValues(t), $n(t);
5728
5860
  }
5729
- async function Pn(n, e) {
5861
+ async function Wn(n, e) {
5730
5862
  let t = new TextEncoder().encode(e), r = await n.subtle.digest("SHA-256", t);
5731
- return An(new Uint8Array(r));
5863
+ return $n(new Uint8Array(r));
5732
5864
  }
5733
- function De(n) {
5865
+ function oe(n) {
5734
5866
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.replace(/^https?:\/\/api\./, "https://auth.");
5735
5867
  }
5736
- function En(n) {
5868
+ function Bn(n) {
5737
5869
  let e = n.oidcClientId;
5738
- if (!e && n.apiKey && (e = tt(n.apiKey).keyId), !e)
5870
+ if (!e && n.apiKey && (e = ct(n.apiKey).keyId), !e)
5739
5871
  throw new c(
5740
5872
  "invalid_config",
5741
5873
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
5742
5874
  );
5743
5875
  return e;
5744
5876
  }
5745
- function Dn(n) {
5877
+ function Vn(n) {
5746
5878
  let e = new URL("/api/v1/oauth/authorize", n.idpOrigin);
5747
5879
  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;
5748
5880
  }
5749
- function Je(n) {
5881
+ function nt(n) {
5750
5882
  let e = n.split(".");
5751
5883
  if (e.length !== 3) return null;
5752
5884
  try {
@@ -5756,8 +5888,8 @@ function Je(n) {
5756
5888
  return null;
5757
5889
  }
5758
5890
  }
5759
- function re(n) {
5760
- let e = Je(n);
5891
+ function ie(n) {
5892
+ let e = nt(n);
5761
5893
  return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
5762
5894
  uid: e.sub,
5763
5895
  email: typeof e.email == "string" ? e.email : "",
@@ -5770,9 +5902,68 @@ function re(n) {
5770
5902
  ...e
5771
5903
  };
5772
5904
  }
5905
+ var xo = "/api/v1/oauth/revoke";
5906
+ async function Kn(n, e, t, r) {
5907
+ let o = `${e}${xo}`, i = true;
5908
+ for (let s of r) {
5909
+ if (!s.token) continue;
5910
+ let a = new URLSearchParams({
5911
+ token: s.token,
5912
+ token_type_hint: s.hint,
5913
+ client_id: t
5914
+ }).toString(), l = false;
5915
+ for (let d = 0; d < 2 && !l; d++)
5916
+ try {
5917
+ if (l = (await n(o, {
5918
+ method: "POST",
5919
+ headers: { "content-type": "application/x-www-form-urlencoded" },
5920
+ body: a
5921
+ })).ok, !l) break;
5922
+ } catch {
5923
+ d === 0 && await new Promise((u) => setTimeout(u, 500));
5924
+ }
5925
+ l || (i = false);
5926
+ }
5927
+ return i;
5928
+ }
5773
5929
 
5774
5930
  // src/auth.ts
5775
- function po() {
5931
+ qe();
5932
+
5933
+ // src/end-user-token.ts
5934
+ var Oo = /* @__PURE__ */ new WeakMap();
5935
+ function zn(n, e) {
5936
+ Oo.set(n, e);
5937
+ }
5938
+
5939
+ // src/unsupported-db.ts
5940
+ I();
5941
+ 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([
5942
+ "then",
5943
+ "toJSON",
5944
+ "valueOf",
5945
+ "constructor",
5946
+ "$$typeof",
5947
+ "asymmetricMatch",
5948
+ "nodeType"
5949
+ ]);
5950
+ function Hn() {
5951
+ let n = () => {
5952
+ throw new c("runtime_unsupported", Lo, void 0, void 0, "react-native");
5953
+ }, e = {};
5954
+ return new Proxy(e, {
5955
+ get(t, r) {
5956
+ if (!(typeof r == "symbol" || Uo.has(r)))
5957
+ return r === "toString" ? () => "[NeetruDb indispon\xEDvel em React Native]" : n;
5958
+ },
5959
+ set() {
5960
+ return n(), false;
5961
+ }
5962
+ });
5963
+ }
5964
+
5965
+ // src/auth.ts
5966
+ function qo() {
5776
5967
  try {
5777
5968
  let e = globalThis.process?.env?.NEETRU_API_KEY;
5778
5969
  return typeof e == "string" && e.length > 0 ? e : void 0;
@@ -5780,7 +5971,7 @@ function po() {
5780
5971
  return;
5781
5972
  }
5782
5973
  }
5783
- function fo(n) {
5974
+ function Fo(n) {
5784
5975
  if (n) return n;
5785
5976
  try {
5786
5977
  let t = globalThis.process?.env?.NEETRU_ENV;
@@ -5794,18 +5985,11 @@ function fo(n) {
5794
5985
  }
5795
5986
  return "prod";
5796
5987
  }
5797
- var Ye = /* @__PURE__ */ new Map(), mo = 3600 * 1e3;
5798
- function ho(n, e) {
5799
- let t = Date.now(), r = Ye.get(n);
5800
- if (r && t - r.createdAt < e)
5801
- return r.jwks;
5802
- let o = jose.createRemoteJWKSet(new URL(n));
5803
- return Ye.set(n, { jwks: o, createdAt: t }), o;
5804
- }
5805
- function vs() {
5806
- Ye.clear();
5988
+ var jo = it;
5989
+ function sa() {
5990
+ st();
5807
5991
  }
5808
- function go(n) {
5992
+ function $o(n) {
5809
5993
  let e = n.sub ?? "", t = typeof n.email == "string" ? n.email : "";
5810
5994
  return {
5811
5995
  uid: e,
@@ -5820,8 +6004,8 @@ function go(n) {
5820
6004
  ...n
5821
6005
  };
5822
6006
  }
5823
- var oe = "neetru_oauth_tx";
5824
- function Xe(n) {
6007
+ var se = "neetru_oauth_tx";
6008
+ function rt(n) {
5825
6009
  try {
5826
6010
  let e = globalThis.history;
5827
6011
  if (!e || typeof e.replaceState != "function") return;
@@ -5832,7 +6016,7 @@ function Xe(n) {
5832
6016
  } catch {
5833
6017
  }
5834
6018
  }
5835
- function yo(n) {
6019
+ function Wo(n) {
5836
6020
  let e = "neetru_id_token", t = "neetru_refresh_token", r = /* @__PURE__ */ new Set(), o = null, i = null, s = null;
5837
6021
  function a() {
5838
6022
  try {
@@ -5850,21 +6034,21 @@ function yo(n) {
5850
6034
  }
5851
6035
  function d() {
5852
6036
  if (o) {
5853
- let T = o.exp;
5854
- return typeof T == "number" && T * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), M(), null) : o;
6037
+ let g = o.exp;
6038
+ return typeof g == "number" && g * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), S(), null) : o;
5855
6039
  }
5856
- let h = a();
5857
- if (!h) return null;
5858
- let b = h.getItem(e);
5859
- if (!b)
5860
- return M(), null;
5861
- let m = re(b);
5862
- return m ? (o = m, R(m), o) : (h.removeItem(e), M(), null);
6040
+ let m = a();
6041
+ if (!m) return null;
6042
+ let _ = m.getItem(e);
6043
+ if (!_)
6044
+ return S(), null;
6045
+ let w = ie(_);
6046
+ return w ? (o = w, x(w), o) : (m.removeItem(e), S(), null);
5863
6047
  }
5864
6048
  function u() {
5865
- for (let h of r)
6049
+ for (let m of r)
5866
6050
  try {
5867
- h(o);
6051
+ m(o);
5868
6052
  } catch {
5869
6053
  }
5870
6054
  }
@@ -5874,216 +6058,216 @@ function yo(n) {
5874
6058
  function f() {
5875
6059
  return a()?.getItem(t) ?? null;
5876
6060
  }
5877
- function g() {
6061
+ function h() {
5878
6062
  o = null;
5879
- let h = a();
5880
- h?.removeItem(e), h?.removeItem(t), u();
6063
+ let m = a();
6064
+ m?.removeItem(e), m?.removeItem(t), u();
5881
6065
  }
5882
- function _() {
6066
+ function y() {
5883
6067
  return s || (s = (async () => {
5884
- let h = f();
5885
- if (!h) return false;
5886
- let b;
6068
+ let m = f();
6069
+ if (!m) return false;
6070
+ let _;
5887
6071
  try {
5888
- b = N();
6072
+ _ = T();
5889
6073
  } catch {
5890
6074
  return false;
5891
6075
  }
5892
- let T = `${De(n.baseUrl)}/api/v1/oauth/token`, A = new URLSearchParams({
6076
+ let g = `${oe(n.baseUrl)}/api/v1/oauth/token`, C = new URLSearchParams({
5893
6077
  grant_type: "refresh_token",
5894
- refresh_token: h,
5895
- client_id: b
5896
- }), E;
6078
+ refresh_token: m,
6079
+ client_id: _
6080
+ }), D;
5897
6081
  try {
5898
- E = await n.fetch(T, {
6082
+ D = await n.fetch(g, {
5899
6083
  method: "POST",
5900
6084
  headers: { "content-type": "application/x-www-form-urlencoded" },
5901
- body: A.toString()
6085
+ body: C.toString()
5902
6086
  });
5903
6087
  } catch {
5904
6088
  return false;
5905
6089
  }
5906
- let S = null;
6090
+ let E = null;
5907
6091
  try {
5908
- S = await E.json();
6092
+ E = await D.json();
5909
6093
  } catch {
5910
- S = null;
6094
+ E = null;
5911
6095
  }
5912
- if (!E.ok || typeof S?.error == "string") return false;
5913
- let k = S?.id_token;
5914
- if (typeof k != "string" || k.length === 0) return false;
5915
- let D = re(k);
5916
- if (!D) return false;
5917
- let I = a();
5918
- I?.setItem(e, k);
5919
- let L = S?.refresh_token;
5920
- return typeof L == "string" && L.length > 0 && I?.setItem(t, L), o = D, R(D), u(), true;
6096
+ if (!D.ok || typeof E?.error == "string") return false;
6097
+ let R = E?.id_token;
6098
+ if (typeof R != "string" || R.length === 0) return false;
6099
+ let O = ie(R);
6100
+ if (!O) return false;
6101
+ let A = a();
6102
+ A?.setItem(e, R);
6103
+ let U = E?.refresh_token;
6104
+ return typeof U == "string" && U.length > 0 && A?.setItem(t, U), o = O, x(O), u(), true;
5921
6105
  })().finally(() => {
5922
6106
  s = null;
5923
6107
  }), s);
5924
6108
  }
5925
- function M() {
5926
- f() && _().then((h) => {
5927
- h || g();
6109
+ function S() {
6110
+ f() && y().then((m) => {
6111
+ m || h();
5928
6112
  });
5929
6113
  }
5930
- function R(h) {
6114
+ function x(m) {
5931
6115
  p();
5932
- let b = h.exp;
5933
- if (typeof b != "number") return;
5934
- let m = b * 1e3 - Date.now();
5935
- if (!(m <= 0)) {
6116
+ let _ = m.exp;
6117
+ if (typeof _ != "number") return;
6118
+ let w = _ * 1e3 - Date.now();
6119
+ if (!(w <= 0)) {
5936
6120
  if (f()) {
5937
- let T = Math.min(m, Math.max(3e4, m * 0.2)), A = Math.max(1, m - T);
6121
+ let g = Math.min(w, Math.max(3e4, w * 0.2)), C = Math.max(1, w - g);
5938
6122
  i = setTimeout(() => {
5939
- i = null, _().then((E) => {
5940
- E || g();
6123
+ i = null, y().then((D) => {
6124
+ D || h();
5941
6125
  });
5942
- }, A);
6126
+ }, C);
5943
6127
  return;
5944
6128
  }
5945
6129
  i = setTimeout(() => {
5946
6130
  i = null, d();
5947
- }, m + 1);
6131
+ }, w + 1);
5948
6132
  }
5949
6133
  }
5950
- function N() {
5951
- return En(n);
6134
+ function T() {
6135
+ return Bn(n);
5952
6136
  }
5953
- async function C(h) {
5954
- let b = h ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
5955
- if (!b) return null;
5956
- let m;
6137
+ async function P(m) {
6138
+ let _ = m ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6139
+ if (!_) return null;
6140
+ let w;
5957
6141
  try {
5958
- m = new URL(b);
6142
+ w = new URL(_);
5959
6143
  } catch {
5960
6144
  return null;
5961
6145
  }
5962
- let T = m.searchParams, A = T.get("error");
5963
- if (A) {
5964
- let L = T.get("error_description") ?? A;
5965
- throw l()?.removeItem(oe), Xe(m), new c(A, `OIDC authorize falhou: ${L}`);
6146
+ let g = w.searchParams, C = g.get("error");
6147
+ if (C) {
6148
+ let U = g.get("error_description") ?? C;
6149
+ throw l()?.removeItem(se), rt(w), new c(C, `OIDC authorize falhou: ${U}`);
5966
6150
  }
5967
- let E = T.get("code");
5968
- if (!E) return null;
5969
- let S = T.get("state"), k = l(), D = k?.getItem(oe) ?? null, I = null;
5970
- if (D)
6151
+ let D = g.get("code");
6152
+ if (!D) return null;
6153
+ let E = g.get("state"), R = l(), O = R?.getItem(se) ?? null, A = null;
6154
+ if (O)
5971
6155
  try {
5972
- I = JSON.parse(D);
6156
+ A = JSON.parse(O);
5973
6157
  } catch {
5974
- I = null;
6158
+ A = null;
5975
6159
  }
5976
- if (!I)
6160
+ if (!A)
5977
6161
  throw new c(
5978
6162
  "oidc_state_mismatch",
5979
6163
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado nesta sess\xE3o (ou j\xE1 consumido)."
5980
6164
  );
5981
- if (!S || S !== I.state)
5982
- throw k?.removeItem(oe), Xe(m), new c(
6165
+ if (!E || E !== A.state)
6166
+ throw R?.removeItem(se), rt(w), new c(
5983
6167
  "oidc_state_mismatch",
5984
6168
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
5985
6169
  );
5986
- return k?.removeItem(oe), Xe(m), {
5987
- code: E,
5988
- codeVerifier: I.codeVerifier,
5989
- redirectUri: I.redirectUri,
5990
- nonce: I.nonce,
5991
- state: I.state,
5992
- postLoginRedirect: I.postLoginRedirect
6170
+ return R?.removeItem(se), rt(w), {
6171
+ code: D,
6172
+ codeVerifier: A.codeVerifier,
6173
+ redirectUri: A.redirectUri,
6174
+ nonce: A.nonce,
6175
+ state: A.state,
6176
+ postLoginRedirect: A.postLoginRedirect
5993
6177
  };
5994
6178
  }
5995
- async function $(h) {
5996
- let b = await C(h);
5997
- if (!b) return null;
5998
- let m = N(), A = `${De(n.baseUrl)}/api/v1/oauth/token`, E = new URLSearchParams({
6179
+ async function q(m) {
6180
+ let _ = await P(m);
6181
+ if (!_) return null;
6182
+ let w = T(), C = `${oe(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
5999
6183
  grant_type: "authorization_code",
6000
- code: b.code,
6001
- redirect_uri: b.redirectUri,
6002
- client_id: m,
6003
- code_verifier: b.codeVerifier
6004
- }), S;
6184
+ code: _.code,
6185
+ redirect_uri: _.redirectUri,
6186
+ client_id: w,
6187
+ code_verifier: _.codeVerifier
6188
+ }), E;
6005
6189
  try {
6006
- S = await n.fetch(A, {
6190
+ E = await n.fetch(C, {
6007
6191
  method: "POST",
6008
6192
  headers: { "content-type": "application/x-www-form-urlencoded" },
6009
- body: E.toString()
6193
+ body: D.toString()
6010
6194
  });
6011
- } catch (O) {
6195
+ } catch (L) {
6012
6196
  throw new c(
6013
6197
  "network_error",
6014
- `POST ${A} falhou (network): ${O?.message ?? String(O)}`
6198
+ `POST ${C} falhou (network): ${L?.message ?? String(L)}`
6015
6199
  );
6016
6200
  }
6017
- let k = null;
6201
+ let R = null;
6018
6202
  try {
6019
- k = await S.json();
6203
+ R = await E.json();
6020
6204
  } catch {
6021
- k = null;
6205
+ R = null;
6022
6206
  }
6023
- if (!S.ok || typeof k?.error == "string") {
6024
- let O = typeof k?.error_description == "string" && k.error_description || typeof k?.error == "string" && k.error || `HTTP ${S.status}`;
6207
+ if (!E.ok || typeof R?.error == "string") {
6208
+ let L = typeof R?.error_description == "string" && R.error_description || typeof R?.error == "string" && R.error || `HTTP ${E.status}`;
6025
6209
  throw new c(
6026
6210
  "token_exchange_failed",
6027
- `Troca do authorization_code por tokens falhou no /token: ${O}`,
6028
- S.status
6211
+ `Troca do authorization_code por tokens falhou no /token: ${L}`,
6212
+ E.status
6029
6213
  );
6030
6214
  }
6031
- let D = k?.id_token;
6032
- if (typeof D != "string" || D.length === 0)
6215
+ let O = R?.id_token;
6216
+ if (typeof O != "string" || O.length === 0)
6033
6217
  throw new c(
6034
6218
  "token_exchange_failed",
6035
6219
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado.",
6036
- S.status
6220
+ E.status
6037
6221
  );
6038
- let I = Je(D);
6039
- if (!I)
6222
+ let A = nt(O);
6223
+ if (!A)
6040
6224
  throw new c(
6041
6225
  "token_exchange_failed",
6042
6226
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
6043
6227
  );
6044
- if (I.nonce !== b.nonce)
6228
+ if (A.nonce !== _.nonce)
6045
6229
  throw new c(
6046
6230
  "oidc_nonce_mismatch",
6047
6231
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
6048
6232
  );
6049
- let L = re(D);
6050
- if (!L)
6233
+ let U = ie(O);
6234
+ if (!U)
6051
6235
  throw new c(
6052
6236
  "token_exchange_failed",
6053
6237
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
6054
6238
  );
6055
- let q = a();
6056
- q?.setItem(e, D);
6057
- let F = k?.refresh_token;
6058
- return typeof F == "string" && F.length > 0 && q?.setItem(t, F), o = L, R(L), u(), { user: L, postLoginRedirect: b.postLoginRedirect };
6239
+ let F = a();
6240
+ F?.setItem(e, O);
6241
+ let j = R?.refresh_token;
6242
+ return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = U, x(U), u(), { user: U, postLoginRedirect: _.postLoginRedirect };
6059
6243
  }
6060
6244
  return {
6061
- async signIn(h) {
6245
+ async signIn(m) {
6062
6246
  if (typeof globalThis.location < "u" && typeof globalThis.location.assign == "function") {
6063
- let b = Cn(), m = h?.redirectUri ?? globalThis.location.origin, T = h?.scope ?? "openid profile email", A = N(), E = Ee(b, 16), S = Ee(b, 16), k = Ee(b, 32), D = await Pn(b, k), I = l();
6064
- if (!I)
6247
+ 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();
6248
+ if (!A)
6065
6249
  throw new c(
6066
6250
  "runtime_unsupported",
6067
6251
  "auth.signIn requer sessionStorage para guardar a transa\xE7\xE3o PKCE entre o redirect e o callback."
6068
6252
  );
6069
- let L = {
6070
- state: E,
6071
- nonce: S,
6072
- codeVerifier: k,
6073
- redirectUri: m,
6074
- postLoginRedirect: h?.postLoginRedirect
6253
+ let U = {
6254
+ state: D,
6255
+ nonce: E,
6256
+ codeVerifier: R,
6257
+ redirectUri: w,
6258
+ postLoginRedirect: m?.postLoginRedirect
6075
6259
  };
6076
- I.setItem(oe, JSON.stringify(L));
6077
- let q = De(n.baseUrl), F = Dn({
6078
- idpOrigin: q,
6079
- clientId: A,
6080
- redirectUri: m,
6081
- scope: T,
6082
- state: E,
6083
- nonce: S,
6084
- codeChallenge: D
6260
+ A.setItem(se, JSON.stringify(U));
6261
+ let F = oe(n.baseUrl), j = Vn({
6262
+ idpOrigin: F,
6263
+ clientId: C,
6264
+ redirectUri: w,
6265
+ scope: g,
6266
+ state: D,
6267
+ nonce: E,
6268
+ codeChallenge: O
6085
6269
  });
6086
- globalThis.location.assign(F.toString());
6270
+ globalThis.location.assign(j.toString());
6087
6271
  return;
6088
6272
  }
6089
6273
  throw new c(
@@ -6091,80 +6275,79 @@ function yo(n) {
6091
6275
  "auth.signIn requires a browser context or mocks. Use NEETRU_ENV=dev or pass mocks.auth."
6092
6276
  );
6093
6277
  },
6094
- handleRedirectCallback: C,
6095
- completeSignIn: $,
6278
+ handleRedirectCallback: P,
6279
+ completeSignIn: q,
6096
6280
  // 3.7.0: exposto pro client.support renovar a sessão 1x num 401
6097
6281
  // invalid_end_user_token (mesma função do refresh proativo, com dedup).
6098
- refreshTokens: _,
6282
+ refreshTokens: y,
6099
6283
  getIdToken() {
6100
- let b = a()?.getItem(e) ?? null;
6101
- return b && re(b) ? b : null;
6284
+ let _ = a()?.getItem(e) ?? null;
6285
+ return _ && ie(_) ? _ : null;
6102
6286
  },
6103
6287
  async signOut() {
6104
- let h = a(), b = h?.getItem(e) ?? null;
6105
- h && (h.removeItem(e), h.removeItem(t)), p(), o = null;
6106
- let A = `${(typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth.")}/api/v1/oauth/revoke`, E = b ? JSON.stringify({ token: b }) : null, S = null;
6107
- for (let k = 0; k < 2; k++)
6288
+ let m = a(), _ = m?.getItem(t) ?? null;
6289
+ if (m && (m.removeItem(e), m.removeItem(t)), p(), o = null, _) {
6290
+ let w = null;
6108
6291
  try {
6109
- E && await n.fetch(A, {
6110
- method: "POST",
6111
- headers: { "content-type": "application/json" },
6112
- body: E
6113
- }), S = null;
6114
- break;
6115
- } catch (D) {
6116
- S = D, k === 0 && await new Promise((I) => setTimeout(I, 500));
6292
+ w = T();
6293
+ } catch {
6294
+ w = null;
6117
6295
  }
6118
- S && typeof console < "u" && console.warn(
6119
- "[neetru-sdk] signOut: server-side revoke falhou (2 tentativas). Refresh token pode estar stale.",
6120
- S
6121
- ), u();
6296
+ !(w && await Kn(n.fetch, oe(n.baseUrl), w, [
6297
+ { token: _, hint: "refresh_token" }
6298
+ ])) && typeof console < "u" && console.warn(
6299
+ "[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."
6300
+ );
6301
+ }
6302
+ u();
6122
6303
  },
6123
6304
  getUser() {
6124
6305
  return d();
6125
6306
  },
6126
- onAuthStateChanged(h) {
6127
- r.add(h);
6307
+ onAuthStateChanged(m) {
6308
+ r.add(m);
6128
6309
  try {
6129
- h(d());
6310
+ m(d());
6130
6311
  } catch {
6131
6312
  }
6132
6313
  return () => {
6133
- r.delete(h);
6314
+ r.delete(m);
6134
6315
  };
6135
6316
  },
6136
- async verifyToken(h, b) {
6137
- if (!h || typeof h != "string")
6317
+ async verifyToken(m, _) {
6318
+ if (!m || typeof m != "string")
6138
6319
  throw new c("token_invalid_signature", "token must be a non-empty string");
6139
- let T = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), A = T, E = `${T}/api/v1/oauth/.well-known/jwks`, S = b?.jwksCacheTtlMs ?? mo, k = b?.audience, D = nt(n.apiKey), I = k ?? n.oidcClientId ?? D?.keyId;
6140
- if (!I)
6320
+ 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;
6321
+ if (!A)
6141
6322
  throw new c(
6142
6323
  "invalid_config",
6143
6324
  "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."
6144
6325
  );
6145
- let L = ho(E, S);
6326
+ let U = jo(D, E);
6146
6327
  try {
6147
- let { payload: q } = await jose.jwtVerify(h, L, {
6148
- issuer: A,
6149
- audience: I,
6328
+ let { payload: F } = await jose.jwtVerify(m, U, {
6329
+ issuer: C,
6330
+ audience: A,
6150
6331
  algorithms: ["RS256"]
6151
6332
  });
6152
- return go(q);
6153
- } catch (q) {
6154
- let F = q?.code ?? q?.name ?? "", O = q?.message ?? String(q);
6155
- throw F === "ERR_JWT_EXPIRED" ? new c("token_expired", `Token expired: ${O}`) : F === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new c("token_invalid_signature", `Token signature invalid: ${O}`) : F === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? O.includes('"aud"') || O.includes("audience") ? new c("token_invalid_audience", `Token audience mismatch: ${O}`) : O.includes('"iss"') || O.includes("issuer") ? new c("token_invalid_issuer", `Token issuer mismatch: ${O}`) : new c("token_invalid_signature", `Token claim validation failed: ${O}`) : new c("token_invalid_signature", `Token verification failed: ${O}`);
6333
+ return $o(F);
6334
+ } catch (F) {
6335
+ let j = F?.code ?? F?.name ?? "", L = F?.message ?? String(F);
6336
+ 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}`);
6156
6337
  }
6157
6338
  }
6158
6339
  };
6159
6340
  }
6160
- function _o(n = {}) {
6341
+ function Bo(n = {}) {
6161
6342
  let e = n.fetch ?? globalThis.fetch;
6162
6343
  if (typeof e != "function")
6163
6344
  throw new c(
6164
6345
  "invalid_config",
6165
6346
  "fetch is not available in this runtime. Pass `fetch` explicitly to createNeetruClient."
6166
6347
  );
6167
- let t = n.apiKey ?? po(), r = fo(n.env), o = n.baseUrl ?? (r === "dev-local" ? at : st), i = it(o, n.allowedHosts ?? []), s = Object.freeze({
6348
+ let t = n.apiKey ?? qo();
6349
+ wt({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6350
+ let r = Fo(n.env), o = n.baseUrl ?? (r === "dev-local" ? mt : ft), i = pt(o, n.allowedHosts ?? []), s = Object.freeze({
6168
6351
  apiKey: t,
6169
6352
  oidcClientId: n.oidcClientId,
6170
6353
  baseUrl: i,
@@ -6172,39 +6355,39 @@ function _o(n = {}) {
6172
6355
  env: r,
6173
6356
  productId: n.productId,
6174
6357
  tenantId: n.tenantId
6175
- }), a = r === "dev" && !Te(), l = n.mocks?.auth ?? (a ? new Re({ ...Ge }) : yo(s)), d = n.mocks?.usage ?? (a ? new Ie() : Tt(s)), u = n.mocks?.support ?? (a ? new Ce() : Et(s, {
6176
- getEndUserToken: () => l.getIdToken(),
6177
- // `refreshTokens` é opcional no AuthNamespace (MockAuth/mocks próprios omitem).
6358
+ }), 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, {
6359
+ getEndUserToken: () => u.getIdToken(),
6360
+ // `refreshTokens` é opcional (MockAuth/mocks próprios omitem).
6178
6361
  refreshEndUserToken: (() => {
6179
- let N = l.refreshTokens;
6180
- return typeof N == "function" ? () => N.call(l) : void 0;
6362
+ let P = u.refreshTokens;
6363
+ return typeof P == "function" ? () => P.call(u) : void 0;
6181
6364
  })()
6182
- })), p = n.mocks?.entitlements ?? (a ? new Ae() : bt()), f = n.mocks?.db ?? Jt(s, n.db), g = n.mocks?.webhooks ?? (a ? new ve() : tn(s)), _ = n.mocks?.notifications ?? (a ? new ke() : on(s)), M = n.mocks?.ai ?? (a ? new Pe() : In(s));
6183
- return Object.freeze({
6365
+ })), 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({
6184
6366
  config: s,
6185
6367
  auth: l,
6186
- catalog: yt(s),
6187
- entitlements: p,
6188
- telemetry: kt(s),
6368
+ catalog: Et(s),
6369
+ entitlements: f,
6370
+ telemetry: Ot(s),
6189
6371
  usage: d,
6190
- support: u,
6191
- db: f,
6192
- checkout: Xt(s),
6193
- webhooks: g,
6194
- notifications: _,
6195
- ai: M
6372
+ support: p,
6373
+ db: h,
6374
+ checkout: un(s),
6375
+ webhooks: y,
6376
+ notifications: S,
6377
+ ai: x
6196
6378
  });
6379
+ return n.endUserAuth && zn(T, n.endUserAuth), T;
6197
6380
  }
6198
- var Ne = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6199
- function ws(n = {}) {
6381
+ var Oe = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6382
+ function aa(n = {}) {
6200
6383
  let e = globalThis;
6201
- return e[Ne] || (e[Ne] = _o(n)), e[Ne];
6384
+ return e[Oe] || (e[Oe] = Bo(n)), e[Oe];
6202
6385
  }
6203
- function ks() {
6204
- delete globalThis[Ne];
6386
+ function ca() {
6387
+ delete globalThis[Oe];
6205
6388
  }
6206
6389
 
6207
- exports.__resetJwksCacheForTests = vs;
6208
- exports.__resetServerNeetruClientForTests = ks;
6209
- exports.createNeetruClient = _o;
6210
- exports.getServerNeetruClient = ws;
6390
+ exports.__resetJwksCacheForTests = sa;
6391
+ exports.__resetServerNeetruClientForTests = ca;
6392
+ exports.createNeetruClient = Bo;
6393
+ exports.getServerNeetruClient = aa;