@neetru/sdk 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +55 -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 +1227 -1064
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +1224 -1061
  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 +370 -298
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +362 -290
  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 +1409 -1075
  36. package/dist/index.d.cts +177 -3
  37. package/dist/index.d.ts +177 -3
  38. package/dist/index.mjs +1544 -1217
  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-Bx4kTLmk.d.cts → types-D-9bjlM0.d.cts} +48 -1
  64. package/dist/{types-Dx0IrOSF.d.ts → types-bVztFQTI.d.ts} +48 -1
  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,16 +3,16 @@
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 Hn = 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
+ Hn(n, t, { get: e[t], enumerable: true });
11
11
  };
12
12
 
13
13
  // src/errors.ts
14
- var c, V, P = B(() => {
15
- c = class n extends Error {
14
+ var l, V, I = $(() => {
15
+ l = class n extends Error {
16
16
  code;
17
17
  status;
18
18
  requestId;
@@ -25,100 +25,191 @@ 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
- }, 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);
38
+ }, V = class n extends l {
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();
43
- throw new c(
50
+ throw new l(
44
51
  "runtime_unsupported",
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 && er.test(n);
62
+ }
63
+ function tr() {
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) ?? tr();
91
+ return r[yt] = o, { headers: r, correlationId: o };
92
+ }
93
+ var yt, er, Me = $(() => {
94
+ yt = "x-correlation-id", er = /^[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 = nr[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 l("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 nr, vt, qe = $(() => {
131
+ I();
132
+ nr = {
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 or(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.0";
73
160
  } catch {
74
161
  return;
75
162
  }
76
163
  }
77
- function jn() {
78
- let n = ht();
164
+ function ir() {
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 = ir(), t = rr[e];
84
171
  if (!t) return;
85
- let r = xe(n);
86
- if (Fn(r, t) < 0) {
172
+ let r = Fe(n);
173
+ if (or(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 sr() {
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 ur(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 pr(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 = pr(n.baseUrl, e.path, e.query), o = lr.has(t) ? ar : cr, i = e.retries ?? o, { headers: s, correlationId: a } = ae(
223
+ { accept: "application/json", ...e.headers },
224
+ e.correlationId
225
+ ), c = Ct();
226
+ if (c && (s["x-neetru-sdk-version"] = c), 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 l("missing_api_key", sr());
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 l(
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 _ = { method: t, headers: s };
249
+ d !== void 0 && (_.body = d);
250
+ let b = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
251
+ _.signal = AbortSignal.timeout(b);
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, _);
255
+ } catch (h) {
256
+ let C = h instanceof DOMException && h.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${h instanceof Error ? h.message : "fetch failed"}`;
257
+ if (u = new l("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 h = S.headers.get("x-neetru-version");
269
+ return h && ce(h), 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 h = T.error;
274
+ typeof h == "string" ? q = h : h && typeof h == "object" ? (typeof h.code == "string" && (P = h.code), typeof h.message == "string" && (q = h.message), typeof h.reason == "string" && (m = h.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 h = 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.`), h && !q.includes(h) && (q += ` Substituto: ${h}.`);
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 g = new l(P, q, S.status, x, m, a);
281
+ if (u = g, dr.has(P) && f < i) {
282
+ let C = ur(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 g;
194
289
  }
195
- throw d ?? new c("unknown", "unexpected httpRequest exit");
290
+ throw u ?? new l("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 rr, kt, ar, cr, lr, dr, Tt, M = $(() => {
293
+ I();
294
+ gt();
295
+ Me();
296
+ qe();
297
+ rr = {
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
+ ar = 2, cr = 0, lr = /* @__PURE__ */ new Set(["GET", "HEAD"]), dr = /* @__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 Rr, y, Z = $(() => {
313
+ I();
314
+ Rr = /* @__PURE__ */ new Set([
218
315
  "db_unavailable",
219
316
  "db_conflict",
220
317
  "db_timeout"
221
- ]), y = class n extends c {
318
+ ]), y = class n extends l {
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 = Rr.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 Hr(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,36 +350,36 @@ 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 Qe(n) {
257
354
  let e = { current: n }, t = null, r = {
258
- __neetruSwapInner(l) {
355
+ __neetruSwapInner(c) {
259
356
  let d = e.current;
260
- return e.current = l, d;
357
+ return e.current = c, d;
261
358
  },
262
359
  __neetruGetInner() {
263
360
  return e.current;
264
361
  },
265
- __neetruSetReLease(l) {
266
- t = l;
362
+ __neetruSetReLease(c) {
363
+ t = c;
267
364
  }
268
- }, o = (l, d) => l.query(...d), i = (...l) => l.length > 0 && typeof l[l.length - 1] == "function" ? o(e.current, l) : (async () => {
365
+ }, o = (c, d) => c.query(...d), i = (...c) => c.length > 0 && typeof c[c.length - 1] == "function" ? o(e.current, c) : (async () => {
269
366
  try {
270
- return await o(e.current, l);
367
+ return await o(e.current, c);
271
368
  } catch (d) {
272
369
  let u = t;
273
- if (u === null || !Cr(d))
370
+ if (u === null || !Hr(d))
274
371
  throw d;
275
372
  try {
276
373
  await u();
277
374
  } catch {
278
375
  throw d;
279
376
  }
280
- return await o(e.current, l);
377
+ return await o(e.current, c);
281
378
  }
282
379
  })(), s = Object.create(Object.getPrototypeOf(n));
283
380
  return new Proxy(s, {
284
- get(l, d) {
285
- if (d === We) return true;
381
+ get(c, d) {
382
+ if (d === He) return true;
286
383
  if (d === "__neetruSwapInner") return r.__neetruSwapInner;
287
384
  if (d === "__neetruGetInner") return r.__neetruGetInner;
288
385
  if (d === "__neetruSetReLease") return r.__neetruSetReLease;
@@ -294,15 +391,15 @@ function $e(n) {
294
391
  }
295
392
  });
296
393
  }
297
- var We, Be = B(() => {
298
- We = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
394
+ var He, Ge = $(() => {
395
+ He = /* @__PURE__ */ Symbol.for("neetru.sdk.resilientPool");
299
396
  });
300
397
 
301
398
  // src/db/sql/lease.ts
302
- function Pr(n, e) {
399
+ function Gr(n, e) {
303
400
  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
401
  }
305
- function Er(n) {
402
+ function Jr(n) {
306
403
  if (n instanceof y) return n;
307
404
  let e = n instanceof Error ? n.message : String(n), t = n instanceof Error ? n.code : void 0;
308
405
  return typeof t == "string" && (t === "ECONNREFUSED" || t === "ENOTFOUND" || t === "ETIMEDOUT") ? new y(
@@ -310,10 +407,10 @@ function Er(n) {
310
407
  `Pool connection failed (${t}): ${e}`
311
408
  ) : 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}`);
312
409
  }
313
- var Ar, J, ne, Mt = B(() => {
314
- Y();
315
- Be();
316
- Ar = 0.8, J = 3e4, ne = class {
410
+ var Qr, J, re, Gt = $(() => {
411
+ Z();
412
+ Ge();
413
+ Qr = 0.8, J = 3e4, re = class {
317
414
  /**
318
415
  * Lease atual. `null` no modo LAZY antes da 1ª query (o 1º lease é adiado —
319
416
  * ver `_ensureInitialLease`). Após a 1ª aquisição, sempre não-nulo.
@@ -353,7 +450,7 @@ var Ar, J, ne, Mt = B(() => {
353
450
  isolationLevel: t.isolationLevel
354
451
  }) : await this._orm.transaction(e);
355
452
  } catch (r) {
356
- throw Er(r);
453
+ throw Jr(r);
357
454
  }
358
455
  }
359
456
  async close() {
@@ -376,7 +473,7 @@ var Ar, J, ne, Mt = B(() => {
376
473
  if (!Number.isFinite(e)) return J;
377
474
  let t = this._deps.now(), r = e - t;
378
475
  if (r <= 0) return J;
379
- let o = r * (1 - Ar);
476
+ let o = r * (1 - Qr);
380
477
  return Math.max(J, Math.round(o));
381
478
  }
382
479
  _scheduleRenewal() {
@@ -478,7 +575,7 @@ var Ar, J, ne, Mt = B(() => {
478
575
  "SqlLeaseManager foi fechado \u2014 aquisi\xE7\xE3o de lease inicial abortada."
479
576
  );
480
577
  if (this._lease)
481
- return ye(this._pool) ? this._pool.__neetruGetInner() : this._pool;
578
+ return ve(this._pool) ? this._pool.__neetruGetInner() : this._pool;
482
579
  if (this._initInFlight !== null) return this._initInFlight;
483
580
  let e = (async () => {
484
581
  let t;
@@ -496,7 +593,7 @@ var Ar, J, ne, Mt = B(() => {
496
593
  let i = o instanceof Error ? o.message : String(o);
497
594
  throw new y("db_unavailable", `Falha ao abrir pool: ${i}`);
498
595
  }
499
- return ye(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
596
+ return ve(this._pool) ? this._pool.__neetruSwapInner(r).end().catch(() => {
500
597
  }) : this._pool = r, this._lease = t, this._scheduleRenewal(), r;
501
598
  })();
502
599
  this._initInFlight = e;
@@ -512,12 +609,12 @@ var Ar, J, ne, Mt = B(() => {
512
609
  * Exposto como método protegido para testes.
513
610
  */
514
611
  async _swapPool(e) {
515
- if (!Pr(this._lease, e)) {
612
+ if (!Gr(this._lease, e)) {
516
613
  this._lease = e;
517
614
  return;
518
615
  }
519
616
  let t = this._deps.createPool(e);
520
- if (ye(this._pool)) {
617
+ if (ve(this._pool)) {
521
618
  let i = this._pool.__neetruSwapInner(t);
522
619
  this._lease = e, i.end().catch(() => {
523
620
  });
@@ -539,29 +636,29 @@ var Ar, J, ne, Mt = B(() => {
539
636
  });
540
637
 
541
638
  // 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
639
+ var rn = {};
640
+ ot(rn, {
641
+ DEFAULT_POOL_CONNECT_TIMEOUT_MS: () => tn,
642
+ DEFAULT_POOL_IDLE_MS: () => en,
643
+ DEFAULT_POOL_MAX: () => Zt,
644
+ LEASE_ENDPOINT: () => Jt,
645
+ LEASE_RENEW_ENDPOINT: () => Xt,
646
+ createDrizzleHandle: () => eo,
647
+ createHttpLeaseFetcher: () => Yt,
648
+ createPgPool: () => Zr,
649
+ createSqlClientFromConfig: () => no,
650
+ createSqlClientWithDeps: () => nn,
651
+ resolvePoolTuning: () => Xe
555
652
  });
556
- function Dr(n) {
653
+ function Xr(n) {
557
654
  return n === "workspace" ? "staging" : n === "prod" ? "production" : "dev-local";
558
655
  }
559
- function jt(n) {
656
+ function Yt(n) {
560
657
  return async (e) => {
561
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = !!e?.leaseId, o = r ? Ft : qt, i;
658
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = !!e?.leaseId, o = r ? Xt : Jt, i;
562
659
  r ? i = { leaseId: e.leaseId } : (i = {
563
660
  productId: n.productId ?? "",
564
- environment: Dr(n.env ?? "prod")
661
+ environment: Xr(n.env ?? "prod")
565
662
  }, e?.database !== void 0 && (i.database = e.database));
566
663
  let s;
567
664
  try {
@@ -574,23 +671,23 @@ function jt(n) {
574
671
  retries: 2
575
672
  });
576
673
  } catch (a) {
577
- let l = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof c ? a.reason : void 0;
674
+ let c = r ? "renovar" : "obter", d = a instanceof Error ? a.message : String(a), u = a instanceof l ? a.reason : void 0;
578
675
  if (u === "suspended" || u === "archived" || u === "revoked") {
579
676
  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
677
  throw new y(
581
678
  "db_suspended",
582
- `Falha ao ${l} lease SQL: ${p} (reason=${u}).`
679
+ `Falha ao ${c} lease SQL: ${p} (reason=${u}).`
583
680
  );
584
681
  }
585
682
  throw new y(
586
683
  "db_unavailable",
587
- `Falha ao ${l} lease SQL: ${d}`
684
+ `Falha ao ${c} lease SQL: ${d}`
588
685
  );
589
686
  }
590
- return Nr(s);
687
+ return Yr(s);
591
688
  };
592
689
  }
593
- function Nr(n) {
690
+ function Yr(n) {
594
691
  if (!n || typeof n != "object")
595
692
  throw new y("db_unavailable", "Resposta de lease inv\xE1lida (n\xE3o \xE9 objeto).");
596
693
  let t = n.lease;
@@ -622,22 +719,22 @@ function Nr(n) {
622
719
  expiresAt: o("expiresAt", "string")
623
720
  };
624
721
  }
625
- function Ve(n, e, t, r) {
722
+ function Je(n, e, t, r) {
626
723
  let o = typeof process < "u" ? process.env?.[n] : void 0;
627
724
  if (o === void 0 || o.trim() === "") return e;
628
725
  let i = Number.parseInt(o.trim(), 10);
629
726
  return !Number.isFinite(i) || i < t || i > r ? e : i;
630
727
  }
631
- function ze() {
728
+ function Xe() {
632
729
  return {
633
730
  // Teto 100: bem abaixo do `max_client_conn = 500` do PgBouncer, com folga
634
731
  // para múltiplas instâncias do app dividirem o mesmo front-door.
635
- max: Ve("NEETRU_DB_POOL_MAX", Wt, 1, 100),
732
+ max: Je("NEETRU_DB_POOL_MAX", Zt, 1, 100),
636
733
  // Teto 15min = janela do cert; piso 1s.
637
- idleTimeoutMillis: Ve("NEETRU_DB_POOL_IDLE_MS", $t, 1e3, 9e5),
638
- connectionTimeoutMillis: Ve(
734
+ idleTimeoutMillis: Je("NEETRU_DB_POOL_IDLE_MS", en, 1e3, 9e5),
735
+ connectionTimeoutMillis: Je(
639
736
  "NEETRU_DB_POOL_CONNECT_TIMEOUT_MS",
640
- Bt,
737
+ tn,
641
738
  1e3,
642
739
  12e4
643
740
  ),
@@ -645,7 +742,7 @@ function ze() {
645
742
  keepAliveInitialDelayMillis: 1e4
646
743
  };
647
744
  }
648
- async function xr(n) {
745
+ async function Zr(n) {
649
746
  let { Pool: e } = await import(
650
747
  /* webpackIgnore: true */
651
748
  'pg'
@@ -662,17 +759,17 @@ async function xr(n) {
662
759
  user: n.user,
663
760
  password: n.password,
664
761
  ssl: t,
665
- ...ze()
762
+ ...Xe()
666
763
  });
667
764
  }
668
- async function Or(n, e) {
765
+ async function eo(n, e) {
669
766
  let { drizzle: t } = await import(
670
767
  /* webpackIgnore: true */
671
768
  'drizzle-orm/node-postgres'
672
769
  );
673
770
  return t(n, { schema: e });
674
771
  }
675
- function Lr(n, e) {
772
+ function to(n, e) {
676
773
  let t = null, r = null, o = () => t ? Promise.resolve(t) : (r || (r = e().then((s) => (t = s, r = null, s)).catch((s) => {
677
774
  throw r = null, s;
678
775
  })), r), i = {
@@ -688,52 +785,52 @@ function Lr(n, e) {
688
785
  };
689
786
  return n && Object.setPrototypeOf(i, n), i;
690
787
  }
691
- async function Vt(n, e) {
788
+ async function nn(n, e) {
692
789
  let t = e?.database !== void 0 ? { ...n, database: e.database } : n;
693
790
  if (t.lazy) {
694
- let l = null, d = Lr(t.poolPrototype ?? null, () => {
695
- if (!l)
791
+ let c = null, d = to(t.poolPrototype ?? null, () => {
792
+ if (!c)
696
793
  throw new y("db_unavailable", "SQL client n\xE3o inicializado (manager ausente).");
697
- return l._ensureInitialLease();
698
- }), u = $e(d), p;
794
+ return c._ensureInitialLease();
795
+ }), u = Qe(d), p;
699
796
  try {
700
797
  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: ${_}`);
798
+ } catch (_) {
799
+ let b = _ instanceof Error ? _.message : String(_);
800
+ throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${b}`);
704
801
  }
705
- let f = new ne(null, u, p, t);
706
- return l = f, u.__neetruSetReLease(() => f._reactiveReLease()), f;
802
+ let f = new re(null, u, p, t);
803
+ return c = f, u.__neetruSetReLease(() => f._reactiveReLease()), f;
707
804
  }
708
805
  let r;
709
806
  try {
710
807
  e?.database !== void 0 ? r = await t.fetchLease({ database: e.database }) : r = await t.fetchLease();
711
- } catch (l) {
712
- if (l instanceof y) throw l;
713
- let d = l instanceof Error ? l.message : String(l);
808
+ } catch (c) {
809
+ if (c instanceof y) throw c;
810
+ let d = c instanceof Error ? c.message : String(c);
714
811
  throw new y("db_unavailable", `Falha ao obter lease inicial: ${d}`);
715
812
  }
716
813
  let o;
717
814
  try {
718
815
  o = t.createPool(r);
719
- } catch (l) {
720
- let d = l instanceof Error ? l.message : String(l);
816
+ } catch (c) {
817
+ let d = c instanceof Error ? c.message : String(c);
721
818
  throw new y("db_unavailable", `Falha ao abrir pool: ${d}`);
722
819
  }
723
- let i = $e(o), s;
820
+ let i = Qe(o), s;
724
821
  try {
725
822
  s = t.createDrizzle(i, t.schema);
726
- } catch (l) {
823
+ } catch (c) {
727
824
  await o.end().catch(() => {
728
825
  });
729
- let d = l instanceof Error ? l.message : String(l);
826
+ let d = c instanceof Error ? c.message : String(c);
730
827
  throw new y("db_unavailable", `Falha ao criar handle Drizzle: ${d}`);
731
828
  }
732
- let a = new ne(r, i, s, t);
829
+ let a = new re(r, i, s, t);
733
830
  return i.__neetruSetReLease(() => a._reactiveReLease()), a;
734
831
  }
735
- async function Ur(n, e, t) {
736
- let r = jt(n), o, i;
832
+ async function no(n, e, t) {
833
+ let r = Yt(n), o, i;
737
834
  try {
738
835
  o = await import(
739
836
  /* webpackIgnore: true */
@@ -749,7 +846,7 @@ async function Ur(n, e, t) {
749
846
  );
750
847
  }
751
848
  let s = o.Pool ?? o.default?.Pool;
752
- return Vt(
849
+ return nn(
753
850
  {
754
851
  fetchLease: r,
755
852
  createPool: (d) => {
@@ -768,7 +865,7 @@ async function Ur(n, e, t) {
768
865
  ssl: u,
769
866
  // Tuning centralizado (env-tunável) — ver resolvePoolTuning + auditoria
770
867
  // docs/_review/AUDITORIA_DB_CONN_PERF_2026-09-06.md no Core.
771
- ...ze()
868
+ ...Xe()
772
869
  });
773
870
  },
774
871
  createDrizzle: (d, u) => i.drizzle(d, { schema: u }),
@@ -784,89 +881,100 @@ async function Ur(n, e, t) {
784
881
  t
785
882
  );
786
883
  }
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;
884
+ var Jt, Xt, Zt, en, tn, on = $(() => {
885
+ Z();
886
+ I();
887
+ Gt();
888
+ Ge();
889
+ Jt = "/api/sdk/v1/db/lease", Xt = "/api/sdk/v1/db/lease/renew";
890
+ Zt = 10, en = 6e4, tn = 1e4;
794
891
  });
892
+ var Le = /* @__PURE__ */ new Map(), Ue = 3600 * 1e3;
893
+ function it(n, e = Ue) {
894
+ let t = Date.now(), r = Le.get(n);
895
+ if (r && t - r.createdAt < e)
896
+ return r.jwks;
897
+ let o = jose.createRemoteJWKSet(new URL(n));
898
+ return Le.set(n, { jwks: o, createdAt: t }), o;
899
+ }
900
+ function st() {
901
+ Le.clear();
902
+ }
795
903
 
796
904
  // src/auth.ts
797
- P();
905
+ I();
798
906
 
799
907
  // src/api-key.ts
800
- P();
801
- var et = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
802
- function tt(n) {
908
+ I();
909
+ var at = /^nrt_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/;
910
+ function ct(n) {
803
911
  if (typeof n != "string" || n.length === 0)
804
- throw new c(
912
+ throw new l(
805
913
  "invalid_config",
806
914
  "apiKey is required (formato nrt_<keyId>_<secret>)"
807
915
  );
808
- let e = et.exec(n);
916
+ let e = at.exec(n);
809
917
  if (!e)
810
- throw new c(
918
+ throw new l(
811
919
  "invalid_config",
812
920
  "apiKey malformado - esperado formato nrt_<keyId>_<secret>"
813
921
  );
814
922
  return { keyId: e[1], secret: e[2] };
815
923
  }
816
- function nt(n) {
924
+ function lt(n) {
817
925
  if (typeof n != "string" || n.length === 0) return null;
818
- let e = et.exec(n);
926
+ let e = at.exec(n);
819
927
  return e ? { keyId: e[1], secret: e[2] } : null;
820
928
  }
821
929
 
822
930
  // 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);
931
+ I();
932
+ var dt = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]), Gn = ".neetru.com", Jn = "neetru.com", Xn = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.(test|localhost)$/;
933
+ function ut(n) {
934
+ return Xn.test(n);
827
935
  }
828
- function Un(n) {
936
+ function Yn(n) {
829
937
  return n.toLowerCase().replace(/\.+$/, "");
830
938
  }
831
- function it(n, e = []) {
939
+ function pt(n, e = []) {
832
940
  if (typeof n != "string" || n.length === 0)
833
- throw new c("invalid_config", "baseUrl is required");
941
+ throw new l("invalid_config", "baseUrl is required");
834
942
  let t;
835
943
  try {
836
944
  t = new URL(n);
837
945
  } catch {
838
- throw new c("invalid_config", `baseUrl is not a valid URL: ${n}`);
946
+ throw new l("invalid_config", `baseUrl is not a valid URL: ${n}`);
839
947
  }
840
- let r = t.protocol, o = Un(t.hostname);
841
- if (Mn())
948
+ let r = t.protocol, o = Yn(t.hostname);
949
+ if (Zn())
842
950
  return typeof console < "u" && console.warn(
843
951
  `[neetru-sdk] NEETRU_ALLOW_INSECURE_BASEURL=1 ativo. baseUrl=${n} aceito sem valida\xE7\xE3o.`
844
952
  ), n.replace(/\/+$/, "");
845
953
  if (r !== "https:" && r !== "http:")
846
- throw new c(
954
+ throw new l(
847
955
  "invalid_config",
848
956
  `baseUrl protocol must be http: or https:, got ${r}`
849
957
  );
850
958
  if (r === "http:") {
851
- if (!(rt.has(o) || ot(o)))
852
- throw new c(
959
+ if (!(dt.has(o) || ut(o)))
960
+ throw new l(
853
961
  "invalid_config",
854
962
  `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
963
  );
856
964
  return n.replace(/\/+$/, "");
857
965
  }
858
- let i = o === On || o.endsWith(xn), s = e.some((l) => {
859
- let d = l.toLowerCase();
966
+ let i = o === Jn || o.endsWith(Gn), s = e.some((c) => {
967
+ let d = c.toLowerCase();
860
968
  return o === d || o.endsWith(`.${d}`);
861
- }), a = rt.has(o) || ot(o);
969
+ }), a = dt.has(o) || ut(o);
862
970
  if (!i && !s && !a)
863
- throw new c(
971
+ throw new l(
864
972
  "invalid_config",
865
973
  `baseUrl ${o} is not in the allowlist. Allowed: *.neetru.com, localhost, or configure { allowedHosts: ['...'] }. Bypass: NEETRU_ALLOW_INSECURE_BASEURL=1.`
866
974
  );
867
975
  return n.replace(/\/+$/, "");
868
976
  }
869
- function Mn() {
977
+ function Zn() {
870
978
  try {
871
979
  let e = globalThis.process?.env?.NEETRU_ALLOW_INSECURE_BASEURL;
872
980
  if (e === "1" || e === "true") return !0;
@@ -881,19 +989,19 @@ function Mn() {
881
989
  }
882
990
 
883
991
  // src/types.ts
884
- var st = "https://api.neetru.com", at = "http://localhost:9003";
992
+ var ft = "https://api.neetru.com", mt = "http://localhost:9003";
885
993
 
886
994
  // src/catalog.ts
887
- P();
888
- U();
889
- function gt(n) {
995
+ I();
996
+ M();
997
+ function At(n) {
890
998
  if (!n || typeof n != "object")
891
- throw new c("invalid_response", "Catalog response item is not an object");
999
+ throw new l("invalid_response", "Catalog response item is not an object");
892
1000
  let e = n;
893
1001
  if (typeof e.slug != "string" || !e.slug)
894
- throw new c("invalid_response", "Catalog product missing slug");
1002
+ throw new l("invalid_response", "Catalog product missing slug");
895
1003
  if (typeof e.name != "string" || !e.name)
896
- throw new c("invalid_response", "Catalog product missing name");
1004
+ throw new l("invalid_response", "Catalog product missing name");
897
1005
  let t = {
898
1006
  slug: e.slug,
899
1007
  name: e.name
@@ -905,7 +1013,7 @@ function gt(n) {
905
1013
  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
1014
  })), t;
907
1015
  }
908
- function yt(n) {
1016
+ function Et(n) {
909
1017
  return {
910
1018
  /**
911
1019
  * Lista produtos publicados. Por default só `published=true`; staff
@@ -917,12 +1025,12 @@ function yt(n) {
917
1025
  path: "/api/sdk/v1/catalog"
918
1026
  });
919
1027
  if (!t || !Array.isArray(t.products))
920
- throw new c(
1028
+ throw new l(
921
1029
  "invalid_response",
922
1030
  "Catalog list response missing products array"
923
1031
  );
924
1032
  return {
925
- products: t.products.map(gt),
1033
+ products: t.products.map(At),
926
1034
  fetchedAt: typeof t.fetchedAt == "string" ? t.fetchedAt : (/* @__PURE__ */ new Date()).toISOString()
927
1035
  };
928
1036
  },
@@ -933,42 +1041,42 @@ function yt(n) {
933
1041
  */
934
1042
  async get(e) {
935
1043
  if (!e || typeof e != "string")
936
- throw new c("validation_failed", "slug is required");
1044
+ throw new l("validation_failed", "slug is required");
937
1045
  let t = await v(n, {
938
1046
  method: "GET",
939
1047
  path: `/api/sdk/v1/catalog/${encodeURIComponent(e)}`
940
1048
  });
941
1049
  if (!t || !t.product)
942
- throw new c(
1050
+ throw new l(
943
1051
  "invalid_response",
944
1052
  "Catalog get response missing product"
945
1053
  );
946
- return gt(t.product);
1054
+ return At(t.product);
947
1055
  }
948
1056
  };
949
1057
  }
950
1058
 
951
1059
  // 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);
1060
+ I();
1061
+ var fr = "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.";
1062
+ function Pt() {
1063
+ throw new l("validation_failed", fr);
956
1064
  }
957
- function bt(n) {
1065
+ function Dt(n) {
958
1066
  return {
959
1067
  /**
960
1068
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
961
1069
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
962
1070
  */
963
1071
  async check(e, t, r) {
964
- _t();
1072
+ Pt();
965
1073
  },
966
1074
  /**
967
1075
  * @deprecated Endpoint morto no Core — sempre retornava `not_subscribed`.
968
1076
  * Lança `NeetruError`. Use `client.usage.check(resource, {productId, tenantId})`.
969
1077
  */
970
1078
  async checkDetailed(e, t, r) {
971
- _t();
1079
+ Pt();
972
1080
  },
973
1081
  /** Test helper legado — no-op (não há mais cache). Mantido por compat. */
974
1082
  __resetCache() {
@@ -977,16 +1085,16 @@ function bt(n) {
977
1085
  }
978
1086
 
979
1087
  // src/telemetry.ts
980
- P();
981
- U();
982
- var vt = ["debug", "info", "warn", "error", "fatal"];
983
- function Qn() {
1088
+ I();
1089
+ M();
1090
+ var Nt = ["debug", "info", "warn", "error", "fatal"];
1091
+ function mr() {
984
1092
  return typeof globalThis < "u" && typeof globalThis.window < "u";
985
1093
  }
986
- function wt() {
987
- return Qn() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
1094
+ function xt() {
1095
+ return mr() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
988
1096
  }
989
- function Gn(n) {
1097
+ function hr(n) {
990
1098
  switch (n) {
991
1099
  case "debug":
992
1100
  return console.debug.bind(console);
@@ -1002,17 +1110,17 @@ function Gn(n) {
1002
1110
  return console.log.bind(console);
1003
1111
  }
1004
1112
  }
1005
- var Jn = 500, Xn = 50;
1006
- function kt(n) {
1113
+ var gr = 500, yr = 50;
1114
+ function Ot(n) {
1007
1115
  let e = [], t = null, r = null;
1008
1116
  async function o() {
1009
1117
  if (e.length === 0) return;
1010
1118
  let s = e.splice(0, e.length), a = Promise.allSettled(
1011
- s.map(async (l) => {
1119
+ s.map(async (c) => {
1012
1120
  try {
1013
- let d = { name: l.name }, u = l.productSlug ?? n.productId;
1014
- u && (d.productSlug = u), l.properties && typeof l.properties == "object" && (d.properties = l.properties), l.timestamp && (d.timestamp = l.timestamp);
1015
- let p = wt();
1121
+ let d = { name: c.name }, u = c.productSlug ?? n.productId;
1122
+ u && (d.productSlug = u), c.properties && typeof c.properties == "object" && (d.properties = c.properties), c.timestamp && (d.timestamp = c.timestamp);
1123
+ let p = xt();
1016
1124
  await v(n, {
1017
1125
  method: "POST",
1018
1126
  path: p.path,
@@ -1025,7 +1133,7 @@ function kt(n) {
1025
1133
  idempotencyKey: !0
1026
1134
  });
1027
1135
  } catch (d) {
1028
- typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", l.name, d);
1136
+ typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", c.name, d);
1029
1137
  }
1030
1138
  })
1031
1139
  );
@@ -1036,7 +1144,7 @@ function kt(n) {
1036
1144
  function i() {
1037
1145
  t || (t = setTimeout(() => {
1038
1146
  o();
1039
- }, Jn));
1147
+ }, gr));
1040
1148
  }
1041
1149
  return {
1042
1150
  /**
@@ -1053,21 +1161,21 @@ function kt(n) {
1053
1161
  */
1054
1162
  async event(s) {
1055
1163
  if (!s || typeof s != "object")
1056
- throw new c("validation_failed", "event input is required");
1164
+ throw new l("validation_failed", "event input is required");
1057
1165
  if (typeof s.name != "string" || s.name.length === 0)
1058
- throw new c("validation_failed", "event.name is required");
1166
+ throw new l("validation_failed", "event.name is required");
1059
1167
  if (s.name.length > 128)
1060
- throw new c("validation_failed", "event.name max 128 chars");
1061
- let a = { name: s.name }, l = s.productSlug ?? n.productId;
1062
- 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, {
1168
+ throw new l("validation_failed", "event.name max 128 chars");
1169
+ let a = { name: s.name }, c = s.productSlug ?? n.productId;
1170
+ c && (a.productSlug = c), s.properties && typeof s.properties == "object" && (a.properties = s.properties), s.timestamp && (a.timestamp = s.timestamp);
1171
+ let d = xt(), u = await v(n, {
1064
1172
  method: "POST",
1065
1173
  path: d.path,
1066
1174
  body: a,
1067
1175
  requireAuth: d.requireAuth
1068
1176
  });
1069
1177
  if (!u || u.ok !== true || typeof u.eventId != "string")
1070
- throw new c("invalid_response", "Telemetry response missing eventId");
1178
+ throw new l("invalid_response", "Telemetry response missing eventId");
1071
1179
  return { ok: true, eventId: u.eventId };
1072
1180
  },
1073
1181
  /**
@@ -1081,7 +1189,7 @@ function kt(n) {
1081
1189
  * ```
1082
1190
  */
1083
1191
  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());
1192
+ !s || typeof s != "object" || typeof s.name != "string" || s.name.length === 0 || s.name.length > 128 || (e.push(s), e.length >= yr ? (t && (clearTimeout(t), t = null), o()) : i());
1085
1193
  },
1086
1194
  /**
1087
1195
  * Força flush imediato da queue de `track()`. Resolva antes de
@@ -1107,22 +1215,22 @@ function kt(n) {
1107
1215
  */
1108
1216
  async log(s) {
1109
1217
  if (!s || typeof s != "object")
1110
- 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(", ")}`);
1218
+ throw new l("validation_failed", "log input is required");
1219
+ if (!Nt.includes(s.level))
1220
+ throw new l("validation_failed", `level must be one of ${Nt.join(", ")}`);
1113
1221
  if (typeof s.message != "string" || s.message.length === 0)
1114
- throw new c("validation_failed", "message is required");
1222
+ throw new l("validation_failed", "message is required");
1115
1223
  if (s.message.length > 4e3)
1116
- throw new c("validation_failed", "message max 4000 chars");
1224
+ throw new l("validation_failed", "message max 4000 chars");
1117
1225
  if (n.env === "dev")
1118
- return Gn(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1226
+ return hr(s.level)(`[neetru-sdk] ${s.level}: ${s.message}`, s.metadata ?? {}), { ok: true, mode: "mock" };
1119
1227
  let a = {
1120
1228
  level: s.level,
1121
1229
  message: s.message
1122
1230
  };
1123
1231
  s.metadata && (a.metadata = s.metadata);
1124
- let l = s.productSlug ?? n.productId;
1125
- l && (a.productSlug = l);
1232
+ let c = s.productSlug ?? n.productId;
1233
+ c && (a.productSlug = c);
1126
1234
  let d = s.correlationId;
1127
1235
  if (!d)
1128
1236
  try {
@@ -1140,7 +1248,7 @@ function kt(n) {
1140
1248
  headers: u
1141
1249
  });
1142
1250
  if (!p || p.ok !== true)
1143
- throw new c("invalid_response", "Telemetry log response missing ok");
1251
+ throw new l("invalid_response", "Telemetry log response missing ok");
1144
1252
  return {
1145
1253
  ok: true,
1146
1254
  logId: typeof p.logId == "string" ? p.logId : void 0,
@@ -1151,22 +1259,22 @@ function kt(n) {
1151
1259
  }
1152
1260
 
1153
1261
  // src/usage.ts
1154
- P();
1155
- U();
1262
+ I();
1263
+ M();
1156
1264
 
1157
1265
  // 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))
1162
- throw new c(
1266
+ I();
1267
+ var Lt = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
1268
+ function N(n, e) {
1269
+ if (typeof e != "string" || !Lt.test(e))
1270
+ throw new l(
1163
1271
  "validation_failed",
1164
- `${n} must match ${St.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1272
+ `${n} must match ${Lt.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
1165
1273
  );
1166
1274
  }
1167
1275
 
1168
1276
  // src/usage.ts
1169
- function Tt(n) {
1277
+ function Ut(n) {
1170
1278
  return {
1171
1279
  /**
1172
1280
  * Reporta consumo metered de um resource. Hit no endpoint canônico
@@ -1182,21 +1290,21 @@ function Tt(n) {
1182
1290
  */
1183
1291
  async report(e, t = 1, r) {
1184
1292
  if (!e || typeof e != "string")
1185
- throw new c("validation_failed", "resource is required");
1293
+ throw new l("validation_failed", "resource is required");
1186
1294
  if (!Number.isFinite(t) || t <= 0 || !Number.isInteger(t))
1187
- throw new c("validation_failed", "qty must be a positive integer");
1295
+ throw new l("validation_failed", "qty must be a positive integer");
1188
1296
  let o = r?.productId ?? n.productId, i = r?.tenantId ?? n.tenantId;
1189
1297
  if (!o)
1190
- throw new c(
1298
+ throw new l(
1191
1299
  "validation_failed",
1192
1300
  "productId required (pass to options or set on createNeetruClient)"
1193
1301
  );
1194
1302
  if (!i)
1195
- throw new c(
1303
+ throw new l(
1196
1304
  "validation_failed",
1197
1305
  "tenantId required (pass to options or set on createNeetruClient)"
1198
1306
  );
1199
- x("productId", o), x("tenantId", i);
1307
+ N("productId", o), N("tenantId", i);
1200
1308
  let s = await v(n, {
1201
1309
  method: "POST",
1202
1310
  path: "/api/sdk/v1/usage/record",
@@ -1205,7 +1313,7 @@ function Tt(n) {
1205
1313
  idempotencyKey: true
1206
1314
  });
1207
1315
  if (!s || s.ok !== true)
1208
- throw new c("invalid_response", "usage.report response missing ok");
1316
+ throw new l("invalid_response", "usage.report response missing ok");
1209
1317
  return {
1210
1318
  ok: true,
1211
1319
  counterId: s.counterId,
@@ -1223,14 +1331,14 @@ function Tt(n) {
1223
1331
  */
1224
1332
  async check(e, t) {
1225
1333
  if (!e || typeof e != "string")
1226
- throw new c("validation_failed", "resource is required");
1334
+ throw new l("validation_failed", "resource is required");
1227
1335
  let r = t?.productId ?? n.productId, o = t?.tenantId ?? n.tenantId;
1228
1336
  if (!r || !o)
1229
- throw new c(
1337
+ throw new l(
1230
1338
  "validation_failed",
1231
1339
  "productId and tenantId required (pass to options or set on createNeetruClient)"
1232
1340
  );
1233
- x("productId", r), x("tenantId", o);
1341
+ N("productId", r), N("tenantId", o);
1234
1342
  let i = await v(n, {
1235
1343
  method: "GET",
1236
1344
  path: "/api/sdk/v1/entitlements",
@@ -1238,7 +1346,7 @@ function Tt(n) {
1238
1346
  requireAuth: true
1239
1347
  });
1240
1348
  if (!i || typeof i.allowed != "boolean")
1241
- throw new c("invalid_response", "usage.check response missing allowed");
1349
+ throw new l("invalid_response", "usage.check response missing allowed");
1242
1350
  let s = i.behavior ?? (i.reason === "limit_exceeded" ? "readonly" : null);
1243
1351
  return {
1244
1352
  allowed: i.allowed,
@@ -1254,22 +1362,22 @@ function Tt(n) {
1254
1362
  }
1255
1363
 
1256
1364
  // 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) {
1365
+ I();
1366
+ M();
1367
+ var je = ["low", "normal", "high", "urgent"], _r = ["open", "pending", "resolved", "closed"], Mt = 50;
1368
+ function qt(n) {
1261
1369
  if (!n || typeof n != "object")
1262
- throw new c("invalid_response", "Ticket response is not an object");
1370
+ throw new l("invalid_response", "Ticket response is not an object");
1263
1371
  let e = n;
1264
1372
  if (typeof e.id != "string")
1265
- throw new c("invalid_response", "Ticket missing id");
1373
+ throw new l("invalid_response", "Ticket missing id");
1266
1374
  let t = Array.isArray(e.attachments) && typeof e.attachments[0] == "string" ? e.attachments[0] : void 0, r = typeof e.screenshotUrl == "string" ? e.screenshotUrl : t ?? null;
1267
1375
  return {
1268
1376
  id: e.id,
1269
1377
  subject: typeof e.subject == "string" ? e.subject : "",
1270
1378
  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",
1379
+ severity: je.includes(e.severity) ? e.severity : "normal",
1380
+ status: _r.includes(e.status) ? e.status : "open",
1273
1381
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
1274
1382
  updatedAt: typeof e.updatedAt == "string" ? e.updatedAt : void 0,
1275
1383
  productSlug: typeof e.productId == "string" ? e.productId : typeof e.productSlug == "string" ? e.productSlug : void 0,
@@ -1287,60 +1395,63 @@ function It(n) {
1287
1395
  satisfactionComment: typeof e.satisfactionComment == "string" ? e.satisfactionComment : null
1288
1396
  };
1289
1397
  }
1290
- function ae(n) {
1398
+ function de(n) {
1291
1399
  if (!n || typeof n != "string")
1292
- throw new c("validation_failed", "ticketId is required");
1400
+ throw new l("validation_failed", "ticketId is required");
1293
1401
  }
1294
- function Ct(n) {
1402
+ function Ft(n) {
1295
1403
  if (typeof n == "string" && n.length > 2e3)
1296
- throw new c("validation_failed", "comment max 2000 chars");
1404
+ throw new l("validation_failed", "comment max 2000 chars");
1297
1405
  }
1298
- function At(n, ...e) {
1406
+ function jt(n, ...e) {
1299
1407
  for (let t of e)
1300
1408
  if (typeof t == "string" && t.length > 0)
1301
- return x("productSlug", t), t;
1409
+ return N("productSlug", t), t;
1302
1410
  if (n.productId)
1303
- return x("productId", n.productId), n.productId;
1304
- throw new c(
1411
+ return N("productId", n.productId), n.productId;
1412
+ throw new l(
1305
1413
  "validation_failed",
1306
1414
  "productId required (pass to input.productSlug or set on createNeetruClient)"
1307
1415
  );
1308
1416
  }
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) {
1311
- if (n instanceof c && !(n instanceof V)) {
1417
+ var br = "X-Neetru-End-User-Token", vr = "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.", wr = "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.", kr = "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.", Sr = "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.";
1418
+ function $t(n) {
1419
+ if (n instanceof l && !(n instanceof V)) {
1312
1420
  if (n.code === "end_user_token_required")
1313
1421
  throw new V(
1314
- tr,
1422
+ wr,
1315
1423
  "end_user_token_required",
1316
1424
  n.status,
1317
- n.requestId
1425
+ n.requestId,
1426
+ n.correlationId
1318
1427
  );
1319
1428
  if (n.code === "invalid_end_user_token")
1320
1429
  throw new V(
1321
- nr,
1430
+ kr,
1322
1431
  "invalid_end_user_token",
1323
1432
  n.status,
1324
- n.requestId
1433
+ n.requestId,
1434
+ n.correlationId
1325
1435
  );
1326
1436
  if (n.code === "end_user_token_product_mismatch")
1327
- throw new c(
1437
+ throw new l(
1328
1438
  "forbidden",
1329
- rr,
1439
+ Sr,
1330
1440
  n.status,
1331
1441
  n.requestId,
1332
- "end_user_token_product_mismatch"
1442
+ "end_user_token_product_mismatch",
1443
+ n.correlationId
1333
1444
  );
1334
1445
  }
1335
1446
  throw n;
1336
1447
  }
1337
- function or(n) {
1338
- return n instanceof c && n.code === "invalid_end_user_token";
1448
+ function Tr(n) {
1449
+ return n instanceof l && n.code === "invalid_end_user_token";
1339
1450
  }
1340
- function Et(n, e = {}) {
1341
- function t() {
1451
+ function Wt(n, e = {}) {
1452
+ async function t() {
1342
1453
  try {
1343
- let a = e.getEndUserToken?.();
1454
+ let a = await e.getEndUserToken?.();
1344
1455
  return typeof a == "string" && a.length > 0 ? a : null;
1345
1456
  } catch {
1346
1457
  return null;
@@ -1355,28 +1466,28 @@ function Et(n, e = {}) {
1355
1466
  }
1356
1467
  }
1357
1468
  function o(a) {
1358
- return a ? { [Zn]: a } : {};
1469
+ return a ? { [br]: a } : {};
1359
1470
  }
1360
- 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");
1471
+ async function i(a, c) {
1472
+ let d = await t();
1473
+ if (!d && a && await r() && (d = await t()), !d && a)
1474
+ throw new V(vr, "no_signed_in_user");
1364
1475
  try {
1365
- return await l(o(d));
1476
+ return await c(o(d));
1366
1477
  } catch (u) {
1367
- if (d && or(u) && await r()) {
1368
- let p = t();
1478
+ if (d && Tr(u) && await r()) {
1479
+ let p = await t();
1369
1480
  if (p)
1370
1481
  try {
1371
- return await l(o(p));
1482
+ return await c(o(p));
1372
1483
  } catch (f) {
1373
- Pt(f);
1484
+ $t(f);
1374
1485
  }
1375
1486
  }
1376
- Pt(u);
1487
+ $t(u);
1377
1488
  }
1378
1489
  }
1379
- async function s(a, l = {}) {
1490
+ async function s(a, c = {}) {
1380
1491
  await i(
1381
1492
  true,
1382
1493
  (d) => v(n, {
@@ -1384,7 +1495,7 @@ function Et(n, e = {}) {
1384
1495
  path: a,
1385
1496
  requireAuth: !0,
1386
1497
  headers: d,
1387
- ...l
1498
+ ...c
1388
1499
  })
1389
1500
  );
1390
1501
  }
@@ -1397,22 +1508,22 @@ function Et(n, e = {}) {
1397
1508
  */
1398
1509
  async createTicket(a) {
1399
1510
  if (!a || typeof a != "object")
1400
- throw new c("validation_failed", "input is required");
1511
+ throw new l("validation_failed", "input is required");
1401
1512
  if (!a.subject || typeof a.subject != "string")
1402
- throw new c("validation_failed", "subject is required");
1513
+ throw new l("validation_failed", "subject is required");
1403
1514
  if (a.subject.length > 200)
1404
- throw new c("validation_failed", "subject max 200 chars");
1515
+ throw new l("validation_failed", "subject max 200 chars");
1405
1516
  if (!a.message || typeof a.message != "string")
1406
- throw new c("validation_failed", "message is required");
1517
+ throw new l("validation_failed", "message is required");
1407
1518
  if (a.message.length > 1e4)
1408
- throw new c("validation_failed", "message max 10000 chars");
1409
- if (a.severity && !Oe.includes(a.severity))
1410
- throw new c(
1519
+ throw new l("validation_failed", "message max 10000 chars");
1520
+ if (a.severity && !je.includes(a.severity))
1521
+ throw new l(
1411
1522
  "validation_failed",
1412
- `severity must be one of ${Oe.join(", ")}`
1523
+ `severity must be one of ${je.join(", ")}`
1413
1524
  );
1414
1525
  let d = {
1415
- productId: At(n, a.productSlug),
1526
+ productId: jt(n, a.productSlug),
1416
1527
  subject: a.subject,
1417
1528
  message: a.message,
1418
1529
  severity: a.severity ?? "normal"
@@ -1429,7 +1540,7 @@ function Et(n, e = {}) {
1429
1540
  headers: f
1430
1541
  })
1431
1542
  ), p = u && typeof u == "object" && "ticket" in u ? u.ticket : u;
1432
- return It(p);
1543
+ return qt(p);
1433
1544
  },
1434
1545
  /**
1435
1546
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
@@ -1437,23 +1548,23 @@ function Et(n, e = {}) {
1437
1548
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
1438
1549
  */
1439
1550
  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))
1442
- throw new c(
1551
+ let c = jt(n, a?.productSlug), d = a?.limit;
1552
+ if (d !== void 0 && (!Number.isInteger(d) || d < 1 || d > Mt))
1553
+ throw new l(
1443
1554
  "validation_failed",
1444
- `limit must be an integer 1-${Rt} (Core default 20)`
1555
+ `limit must be an integer 1-${Mt} (Core default 20)`
1445
1556
  );
1446
1557
  let u = await i(
1447
1558
  true,
1448
1559
  (f) => v(n, {
1449
1560
  method: "GET",
1450
1561
  path: "/api/sdk/v1/support/tickets",
1451
- query: { productId: l, limit: d },
1562
+ query: { productId: c, limit: d },
1452
1563
  requireAuth: !0,
1453
1564
  headers: f
1454
1565
  })
1455
1566
  );
1456
- return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(It);
1567
+ return (Array.isArray(u) ? u : u && typeof u == "object" && "tickets" in u ? u.tickets ?? [] : []).map(qt);
1457
1568
  },
1458
1569
  /**
1459
1570
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
@@ -1461,7 +1572,7 @@ function Et(n, e = {}) {
1461
1572
  * `POST /api/sdk/v1/support/tickets/{id}/resolved-seen`.
1462
1573
  */
1463
1574
  async markResolvedSeen(a) {
1464
- ae(a), await s(
1575
+ de(a), await s(
1465
1576
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/resolved-seen`
1466
1577
  );
1467
1578
  },
@@ -1472,7 +1583,7 @@ function Et(n, e = {}) {
1472
1583
  * `POST /api/sdk/v1/support/tickets/{id}/satisfaction-attempt`.
1473
1584
  */
1474
1585
  async recordSatisfactionAttempt(a) {
1475
- ae(a), await s(
1586
+ de(a), await s(
1476
1587
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/satisfaction-attempt`,
1477
1588
  // Incrementa satisfactionAttempts += 1 no Core — sem idempotencyKey,
1478
1589
  // um retry de rede infla o contador (mesmo padrão de createTicket acima).
@@ -1485,10 +1596,10 @@ function Et(n, e = {}) {
1485
1596
  */
1486
1597
  async submitSatisfaction(a) {
1487
1598
  if (!a || typeof a != "object")
1488
- 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))
1490
- throw new c("validation_failed", "rating must be an integer 1-5 or null");
1491
- Ct(a.comment), await s(
1599
+ throw new l("validation_failed", "input is required");
1600
+ if (de(a.ticketId), a.rating !== null && a.rating !== void 0 && (!Number.isInteger(a.rating) || a.rating < 1 || a.rating > 5))
1601
+ throw new l("validation_failed", "rating must be an integer 1-5 or null");
1602
+ Ft(a.comment), await s(
1492
1603
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a.ticketId)}/satisfaction`,
1493
1604
  {
1494
1605
  body: {
@@ -1504,24 +1615,24 @@ function Et(n, e = {}) {
1504
1615
  * satisfação/notificação. Endpoint canonical:
1505
1616
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
1506
1617
  */
1507
- async contestTicket(a, l) {
1508
- ae(a), Ct(l?.comment), await s(
1618
+ async contestTicket(a, c) {
1619
+ de(a), Ft(c?.comment), await s(
1509
1620
  `/api/sdk/v1/support/tickets/${encodeURIComponent(a)}/contest`,
1510
- { body: { comment: l?.comment ?? void 0 } }
1621
+ { body: { comment: c?.comment ?? void 0 } }
1511
1622
  );
1512
1623
  }
1513
1624
  };
1514
1625
  }
1515
1626
 
1516
1627
  // src/db/client-db.ts
1517
- Y();
1628
+ Z();
1518
1629
 
1519
1630
  // src/db/offline/query-engine.ts
1520
- function Dt(n) {
1631
+ function Bt(n) {
1521
1632
  return n == null ? 0 : typeof n == "number" ? 1 : typeof n == "string" ? 2 : typeof n == "boolean" ? 3 : 4;
1522
1633
  }
1523
- function Z(n, e) {
1524
- let t = Dt(n), r = Dt(e);
1634
+ function ee(n, e) {
1635
+ let t = Bt(n), r = Bt(e);
1525
1636
  if (t !== r) return t - r;
1526
1637
  if (n == null) return 0;
1527
1638
  if (typeof n == "number" && typeof e == "number") return n - e;
@@ -1530,7 +1641,7 @@ function Z(n, e) {
1530
1641
  let o = String(n), i = String(e);
1531
1642
  return o < i ? -1 : o > i ? 1 : 0;
1532
1643
  }
1533
- function Le(n, e) {
1644
+ function $e(n, e) {
1534
1645
  let t = e.split("."), r = n;
1535
1646
  for (let o of t) {
1536
1647
  if (r == null || typeof r != "object")
@@ -1539,8 +1650,8 @@ function Le(n, e) {
1539
1650
  }
1540
1651
  return r;
1541
1652
  }
1542
- function sr(n, e) {
1543
- let t = Le(n, e.field);
1653
+ function Ir(n, e) {
1654
+ let t = $e(n, e.field);
1544
1655
  if (t === void 0) return false;
1545
1656
  let { op: r, value: o } = e;
1546
1657
  switch (r) {
@@ -1549,13 +1660,13 @@ function sr(n, e) {
1549
1660
  case "!=":
1550
1661
  return t !== o;
1551
1662
  case "<":
1552
- return Z(t, o) < 0;
1663
+ return ee(t, o) < 0;
1553
1664
  case "<=":
1554
- return Z(t, o) <= 0;
1665
+ return ee(t, o) <= 0;
1555
1666
  case ">":
1556
- return Z(t, o) > 0;
1667
+ return ee(t, o) > 0;
1557
1668
  case ">=":
1558
- return Z(t, o) >= 0;
1669
+ return ee(t, o) >= 0;
1559
1670
  case "array-contains":
1560
1671
  return Array.isArray(t) && t.includes(o);
1561
1672
  case "in":
@@ -1570,24 +1681,24 @@ function sr(n, e) {
1570
1681
  );
1571
1682
  }
1572
1683
  }
1573
- function ar(n, e) {
1574
- return e.every((t) => sr(n, t));
1684
+ function Cr(n, e) {
1685
+ return e.every((t) => Ir(n, t));
1575
1686
  }
1576
- function cr(n) {
1687
+ function Ar(n) {
1577
1688
  return (e, t) => {
1578
1689
  if (n) {
1579
- let r = Le(e.data, n.field), o = Le(t.data, n.field), i = Z(r, o);
1690
+ let r = $e(e.data, n.field), o = $e(t.data, n.field), i = ee(r, o);
1580
1691
  if (i !== 0)
1581
1692
  return n.direction === "desc" ? -i : i;
1582
1693
  }
1583
1694
  return e.id < t.id ? -1 : e.id > t.id ? 1 : 0;
1584
1695
  };
1585
1696
  }
1586
- function lr(n, e) {
1697
+ function Er(n, e) {
1587
1698
  let t = n.findIndex((r) => r.id === e.docId);
1588
1699
  return t === -1 ? n : e.type === "startAfter" ? n.slice(t + 1) : n.slice(0, t);
1589
1700
  }
1590
- var K = class n {
1701
+ var z = class n {
1591
1702
  /**
1592
1703
  * Avalia um `QueryDescriptor` contra um array de `OfflineDoc`.
1593
1704
  *
@@ -1601,11 +1712,11 @@ var K = class n {
1601
1712
  evaluate(e, t) {
1602
1713
  let r = e.filter((u) => !u.meta.deleted), o = t.where ?? [];
1603
1714
  o.length > 0 && (r = r.filter(
1604
- (u) => ar(u.data, o)
1715
+ (u) => Cr(u.data, o)
1605
1716
  ));
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);
1717
+ let i = Ar(t.orderBy), s = [...r].sort(i), a = t.cursor ? Er(s, t.cursor) : s, c = Math.min(t.limit ?? 20, 500);
1607
1718
  return {
1608
- docs: a.slice(0, l).map((u) => ({ id: u.id, data: u.data })),
1719
+ docs: a.slice(0, c).map((u) => ({ id: u.id, data: u.data })),
1609
1720
  // `incomplete` é sempre true aqui — o QueryEngine não sabe se o cache
1610
1721
  // tem todos os docs da coleção. É responsabilidade do chamador (LocalStore)
1611
1722
  // injetar o flag de completude baseado nos metadados do query_cache.
@@ -1623,7 +1734,7 @@ var K = class n {
1623
1734
  };
1624
1735
 
1625
1736
  // 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 {
1737
+ var Dr = 1, W = "documents", B = "mutations", te = "query_cache", ue = "sync_meta", H = "conflict_log", pe = class {
1627
1738
  db = null;
1628
1739
  dbName;
1629
1740
  constructor(e) {
@@ -1635,21 +1746,21 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1635
1746
  * Idempotente — chamadas subsequentes são no-ops se o banco já está aberto.
1636
1747
  */
1637
1748
  async open() {
1638
- this.db === null && (this.db = await idb.openDB(this.dbName, ur, {
1749
+ this.db === null && (this.db = await idb.openDB(this.dbName, Dr, {
1639
1750
  upgrade(e) {
1640
- if (!e.objectStoreNames.contains(j)) {
1641
- let t = e.createObjectStore(j, {
1751
+ if (!e.objectStoreNames.contains(W)) {
1752
+ let t = e.createObjectStore(W, {
1642
1753
  keyPath: ["collection", "id"]
1643
1754
  });
1644
1755
  t.createIndex("by_collection", "collection"), t.createIndex("by_collection_state", ["collection", "meta.state"]), t.createIndex("by_updatedAtServer", "meta.updatedAtServer");
1645
1756
  }
1646
- if (!e.objectStoreNames.contains(W)) {
1647
- let t = e.createObjectStore(W, {
1757
+ if (!e.objectStoreNames.contains(B)) {
1758
+ let t = e.createObjectStore(B, {
1648
1759
  keyPath: "mutationId"
1649
1760
  });
1650
1761
  t.createIndex("by_seq", "seq"), t.createIndex("by_status", "status"), t.createIndex("by_doc", ["collection", "docId"]), t.createIndex("by_batch", "batchId");
1651
1762
  }
1652
- if (e.objectStoreNames.contains(ee) || e.createObjectStore(ee, { keyPath: "queryHash" }), e.objectStoreNames.contains(ce) || e.createObjectStore(ce, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1763
+ if (e.objectStoreNames.contains(te) || e.createObjectStore(te, { keyPath: "queryHash" }), e.objectStoreNames.contains(ue) || e.createObjectStore(ue, { keyPath: "key" }), !e.objectStoreNames.contains(H)) {
1653
1764
  let t = e.createObjectStore(H, {
1654
1765
  keyPath: "id",
1655
1766
  autoIncrement: true
@@ -1692,14 +1803,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1692
1803
  * Retorna tombstones (deleted: true) — o chamador decide se deve mostrá-los.
1693
1804
  */
1694
1805
  async getDoc(e, t) {
1695
- return await this.assertOpen().get(j, [e, t]) ?? null;
1806
+ return await this.assertOpen().get(W, [e, t]) ?? null;
1696
1807
  }
1697
1808
  /**
1698
1809
  * Insere ou atualiza um documento na store `documents`.
1699
1810
  * O documento é identificado pelo keyPath composto `[collection, id]`.
1700
1811
  */
1701
1812
  async putDoc(e) {
1702
- await this.assertOpen().put(j, e);
1813
+ await this.assertOpen().put(W, e);
1703
1814
  }
1704
1815
  /**
1705
1816
  * Marca um documento como tombstone (`deleted: true`).
@@ -1707,8 +1818,8 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1707
1818
  * No-op se o documento não existir.
1708
1819
  */
1709
1820
  async deleteDoc(e, t) {
1710
- let r = this.assertOpen(), o = await r.get(j, [e, t]);
1711
- o && await r.put(j, {
1821
+ let r = this.assertOpen(), o = await r.get(W, [e, t]);
1822
+ o && await r.put(W, {
1712
1823
  ...o,
1713
1824
  meta: {
1714
1825
  ...o.meta,
@@ -1724,8 +1835,8 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1724
1835
  * e delega a filtragem/ordenação/paginação ao QueryEngine (que opera em memória).
1725
1836
  */
1726
1837
  async listDocs(e, t) {
1727
- let o = await this.assertOpen().getAllFromIndex(j, "by_collection", e);
1728
- return K.evaluate(o, t);
1838
+ let o = await this.assertOpen().getAllFromIndex(W, "by_collection", e);
1839
+ return z.evaluate(o, t);
1729
1840
  }
1730
1841
  // ─── Sync meta (key-value) ──────────────────────────────────────────────────
1731
1842
  /**
@@ -1736,14 +1847,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1736
1847
  * 'lastFullResyncAt', 'leaderTabId'.
1737
1848
  */
1738
1849
  async getMeta(e) {
1739
- let r = await this.assertOpen().get(ce, e);
1850
+ let r = await this.assertOpen().get(ue, e);
1740
1851
  return r ? r.value : null;
1741
1852
  }
1742
1853
  /**
1743
1854
  * Armazena ou atualiza um valor na store `sync_meta`.
1744
1855
  */
1745
1856
  async setMeta(e, t) {
1746
- await this.assertOpen().put(ce, { key: e, value: t });
1857
+ await this.assertOpen().put(ue, { key: e, value: t });
1747
1858
  }
1748
1859
  // ─── Conflict log ───────────────────────────────────────────────────────────
1749
1860
  /**
@@ -1775,13 +1886,13 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1775
1886
  * Key: `mutationId`.
1776
1887
  */
1777
1888
  async putMutation(e) {
1778
- await this.assertOpen().put(W, e);
1889
+ await this.assertOpen().put(B, e);
1779
1890
  }
1780
1891
  /**
1781
1892
  * Retorna uma mutação pelo `mutationId`, ou `null` se não existir.
1782
1893
  */
1783
1894
  async getMutation(e) {
1784
- return await this.assertOpen().get(W, e) ?? null;
1895
+ return await this.assertOpen().get(B, e) ?? null;
1785
1896
  }
1786
1897
  /**
1787
1898
  * Lista mutações com filtros opcionais.
@@ -1789,14 +1900,14 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1789
1900
  */
1790
1901
  async listMutations(e) {
1791
1902
  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);
1903
+ 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
1904
  }
1794
1905
  /**
1795
1906
  * Remove uma mutação pelo `mutationId`.
1796
1907
  * No-op se não existir.
1797
1908
  */
1798
1909
  async deleteMutation(e) {
1799
- await this.assertOpen().delete(W, e);
1910
+ await this.assertOpen().delete(B, e);
1800
1911
  }
1801
1912
  // ─── Collection discovery ────────────────────────────────────────────────────
1802
1913
  /**
@@ -1809,7 +1920,7 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1809
1920
  * coletar os valores únicos de forma eficiente (sem carregar os docs completos).
1810
1921
  */
1811
1922
  async listCollections() {
1812
- let t = await this.assertOpen().getAllFromIndex(j, "by_collection"), r = /* @__PURE__ */ new Set();
1923
+ let t = await this.assertOpen().getAllFromIndex(W, "by_collection"), r = /* @__PURE__ */ new Set();
1813
1924
  for (let o of t)
1814
1925
  r.add(o.collection);
1815
1926
  return Array.from(r);
@@ -1819,24 +1930,24 @@ var ur = 1, j = "documents", W = "mutations", ee = "query_cache", ce = "sync_met
1819
1930
  * Retorna a entrada de `query_cache` para um hash de query, ou `null`.
1820
1931
  */
1821
1932
  async getQueryCache(e) {
1822
- return await this.assertOpen().get(ee, e) ?? null;
1933
+ return await this.assertOpen().get(te, e) ?? null;
1823
1934
  }
1824
1935
  /**
1825
1936
  * Insere ou atualiza uma entrada de `query_cache`.
1826
1937
  */
1827
1938
  async putQueryCache(e) {
1828
- await this.assertOpen().put(ee, e);
1939
+ await this.assertOpen().put(te, e);
1829
1940
  }
1830
1941
  /**
1831
1942
  * Remove uma entrada de `query_cache` pelo queryHash.
1832
1943
  */
1833
1944
  async deleteQueryCache(e) {
1834
- await this.assertOpen().delete(ee, e);
1945
+ await this.assertOpen().delete(te, e);
1835
1946
  }
1836
1947
  };
1837
1948
 
1838
1949
  // src/db/offline/memory-store.ts
1839
- var de = class {
1950
+ var fe = class {
1840
1951
  // store `documents` — key: `${collection}\0${id}`
1841
1952
  _docs = /* @__PURE__ */ new Map();
1842
1953
  // store `mutations` — key: mutationId
@@ -1884,7 +1995,7 @@ var de = class {
1884
1995
  let r = Array.from(this._docs.values()).filter(
1885
1996
  (o) => o.collection === e
1886
1997
  );
1887
- return K.evaluate(r, t);
1998
+ return z.evaluate(r, t);
1888
1999
  }
1889
2000
  // ─── Sync meta ──────────────────────────────────────────────────────────────
1890
2001
  async getMeta(e) {
@@ -1941,13 +2052,13 @@ var de = class {
1941
2052
  };
1942
2053
 
1943
2054
  // src/db/offline/mutation-queue.ts
1944
- function Ue() {
2055
+ function We() {
1945
2056
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (n) => {
1946
2057
  let e = Math.random() * 16 | 0;
1947
2058
  return (n === "x" ? e : e & 3 | 8).toString(16);
1948
2059
  });
1949
2060
  }
1950
- var ue = class {
2061
+ var me = class {
1951
2062
  store;
1952
2063
  /**
1953
2064
  * Ponteiro de sequência local.
@@ -2043,18 +2154,18 @@ var ue = class {
2043
2154
  * Atômico: a persistência final é uma única operação putMutation.
2044
2155
  */
2045
2156
  async enqueue(e) {
2046
- let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, l = e.docId ?? (r === "add" ? Ue() : "");
2157
+ let { collection: t, op: r, payload: o, baseVersion: i, batchId: s, upsert: a } = e, c = e.docId ?? (r === "add" ? We() : "");
2047
2158
  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];
2159
+ let u = (await this.store.listMutations({ collection: t, docId: c })).filter((_) => _.status === "queued").sort((_, b) => b.seq - _.seq)[0];
2049
2160
  if (u !== void 0) {
2050
- let g = this.tryCoalesce(u, r, o, s, a);
2051
- if (g !== null) {
2052
- if ("removed" in g)
2161
+ let _ = this.tryCoalesce(u, r, o, s, a);
2162
+ if (_ !== null) {
2163
+ if ("removed" in _)
2053
2164
  return await this.store.deleteMutation(u.mutationId), {
2054
2165
  seq: u.seq,
2055
- mutationId: Ue(),
2166
+ mutationId: We(),
2056
2167
  collection: t,
2057
- docId: l,
2168
+ docId: c,
2058
2169
  op: "remove",
2059
2170
  payload: null,
2060
2171
  baseVersion: i,
@@ -2064,15 +2175,15 @@ var ue = class {
2064
2175
  status: "queued",
2065
2176
  batchId: s
2066
2177
  };
2067
- let { coalesced: _ } = g;
2068
- return await this.store.putMutation(_), _;
2178
+ let { coalesced: b } = _;
2179
+ return await this.store.putMutation(b), b;
2069
2180
  }
2070
2181
  }
2071
2182
  let f = {
2072
2183
  seq: this.nextSeq(),
2073
- mutationId: Ue(),
2184
+ mutationId: We(),
2074
2185
  collection: t,
2075
- docId: l,
2186
+ docId: c,
2076
2187
  op: r,
2077
2188
  payload: o,
2078
2189
  baseVersion: i,
@@ -2183,45 +2294,45 @@ var ue = class {
2183
2294
  };
2184
2295
 
2185
2296
  // src/db/field-value.ts
2186
- var Nt = "__neetru__";
2297
+ var Vt = "__neetru__";
2187
2298
  function Q(n) {
2188
- return typeof n == "object" && n !== null && Nt in n && typeof n[Nt] == "string";
2299
+ return typeof n == "object" && n !== null && Vt in n && typeof n[Vt] == "string";
2189
2300
  }
2190
- function pr(n) {
2301
+ function Nr(n) {
2191
2302
  return Q(n) && n.__neetru__ === "serverTimestamp";
2192
2303
  }
2193
- function fr(n) {
2304
+ function xr(n) {
2194
2305
  return Q(n) && n.__neetru__ === "increment" && typeof n.operand == "number" && Number.isFinite(n.operand);
2195
2306
  }
2196
- function mr(n, e) {
2197
- return pr(n) ? Date.now() : fr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2307
+ function Or(n, e) {
2308
+ return Nr(n) ? Date.now() : xr(n) ? (typeof e == "number" && Number.isFinite(e) ? e : 0) + n.operand : n;
2198
2309
  }
2199
- function z(n, e) {
2310
+ function K(n, e) {
2200
2311
  let t = false, r = {};
2201
2312
  for (let [o, i] of Object.entries(n))
2202
- Q(i) ? (t = true, r[o] = mr(i, e?.[o])) : r[o] = i;
2313
+ Q(i) ? (t = true, r[o] = Or(i, e?.[o])) : r[o] = i;
2203
2314
  return t ? r : n;
2204
2315
  }
2205
- function Me(n) {
2316
+ function Be(n) {
2206
2317
  for (let e of Object.values(n))
2207
2318
  if (Q(e)) return true;
2208
2319
  return false;
2209
2320
  }
2210
2321
 
2211
2322
  // 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);
2323
+ var Lr = 8, Ur = 1e3, Mr = 300 * 1e3, Ve = "truncatedCollections";
2324
+ function qr(n) {
2325
+ return n !== null && Be(n);
2215
2326
  }
2216
- function br(n) {
2327
+ function Fr(n) {
2217
2328
  if (n === null) return null;
2218
- if (!Me(n)) return n;
2329
+ if (!Be(n)) return n;
2219
2330
  let e = {};
2220
2331
  for (let [t, r] of Object.entries(n))
2221
2332
  Q(r) || (e[t] = r);
2222
2333
  return e;
2223
2334
  }
2224
- var pe = class {
2335
+ var he = class {
2225
2336
  _store;
2226
2337
  _queue;
2227
2338
  _resolver;
@@ -2365,16 +2476,16 @@ var pe = class {
2365
2476
  try {
2366
2477
  t = await this._transport.pushMutations(e);
2367
2478
  } catch (s) {
2368
- let a = s instanceof Error ? s.message : String(s), l = [], [d, ...u] = e;
2369
- await this._retryOrDeadLetter(d, a, l);
2479
+ let a = s instanceof Error ? s.message : String(s), c = [], [d, ...u] = e;
2480
+ await this._retryOrDeadLetter(d, a, c);
2370
2481
  for (let p of u)
2371
2482
  await this._queue.requeueInflight(p.mutationId);
2372
- return l.length > 0 && this._bus.emit(l), this._refreshPendingWrites().catch(() => {
2483
+ return c.length > 0 && this._bus.emit(c), this._refreshPendingWrites().catch(() => {
2373
2484
  }), false;
2374
2485
  }
2375
2486
  let r = [];
2376
2487
  for (let s of t.results) {
2377
- let a = e.find((l) => l.mutationId === s.mutationId);
2488
+ let a = e.find((c) => c.mutationId === s.mutationId);
2378
2489
  a && (s.outcome === "confirmed" ? (await this._queue.markApplied(a.mutationId), await this._applySyncedDoc(
2379
2490
  a.collection,
2380
2491
  a.docId,
@@ -2392,8 +2503,8 @@ var pe = class {
2392
2503
  "partial_push: muta\xE7\xE3o n\xE3o processada no lote",
2393
2504
  r
2394
2505
  );
2395
- for (let l of a)
2396
- await this._queue.requeueInflight(l.mutationId);
2506
+ for (let c of a)
2507
+ await this._queue.requeueInflight(c.mutationId);
2397
2508
  }
2398
2509
  return r.length > 0 && this._bus.emit(r), i.length === 0;
2399
2510
  }
@@ -2415,13 +2526,13 @@ var pe = class {
2415
2526
  }), s.push({ type: "removed", collection: e, doc: { id: t, data: a.data } }));
2416
2527
  return;
2417
2528
  }
2418
- let d = br(i.payload) ?? a?.data ?? {}, u = {
2529
+ let d = Fr(i.payload) ?? a?.data ?? {}, u = {
2419
2530
  collection: e,
2420
2531
  id: t,
2421
2532
  data: i.op === "update" ? { ...a?.data ?? {}, ...d } : (
2422
2533
  // add/set: se o payload tinha sentinels, o cache otimista (existing.data)
2423
2534
  // é a fonte de verdade até o pull; senão usa o payload literal.
2424
- _r(i.payload) ? { ...a?.data ?? {}, ...d } : d
2535
+ qr(i.payload) ? { ...a?.data ?? {}, ...d } : d
2425
2536
  ),
2426
2537
  meta: {
2427
2538
  serverVersion: r,
@@ -2468,7 +2579,7 @@ var pe = class {
2468
2579
  deleted: false,
2469
2580
  ownerId: null
2470
2581
  }
2471
- }, l = this._resolver.resolve(
2582
+ }, c = this._resolver.resolve(
2472
2583
  s,
2473
2584
  i,
2474
2585
  e
@@ -2482,7 +2593,7 @@ var pe = class {
2482
2593
  detectedAt: Date.now(),
2483
2594
  delivered: false
2484
2595
  };
2485
- await this._store.appendConflict(l);
2596
+ await this._store.appendConflict(c);
2486
2597
  let d = {
2487
2598
  collection: e.collection,
2488
2599
  id: e.docId,
@@ -2525,7 +2636,7 @@ var pe = class {
2525
2636
  ...i.meta,
2526
2637
  serverVersion: t.serverVersion ?? i.meta.serverVersion
2527
2638
  }
2528
- } : null, l = this._resolver.resolveRejected(
2639
+ } : null, c = this._resolver.resolveRejected(
2529
2640
  i,
2530
2641
  s,
2531
2642
  e,
@@ -2540,7 +2651,7 @@ var pe = class {
2540
2651
  detectedAt: Date.now(),
2541
2652
  delivered: false
2542
2653
  };
2543
- await this._store.appendConflict(l), t.serverData ? (await this._store.putDoc({
2654
+ await this._store.appendConflict(c), t.serverData ? (await this._store.putDoc({
2544
2655
  ...i,
2545
2656
  data: t.serverData,
2546
2657
  meta: {
@@ -2574,7 +2685,7 @@ var pe = class {
2574
2685
  * pending do doc no cache + registra `lastError`/dispara `onError`.
2575
2686
  */
2576
2687
  async _retryOrDeadLetter(e, t, r) {
2577
- if (e.attempts + 1 < hr) {
2688
+ if (e.attempts + 1 < Lr) {
2578
2689
  await this._queue.markRetry(e.mutationId, t);
2579
2690
  return;
2580
2691
  }
@@ -2615,7 +2726,7 @@ var pe = class {
2615
2726
  }
2616
2727
  /** Backoff exponencial keyed em `attempts`, com teto `BACKOFF_CAP_MS`. */
2617
2728
  _backoffDelayMs(e) {
2618
- return Math.min(gr * 2 ** (e - 1), yr);
2729
+ return Math.min(Ur * 2 ** (e - 1), Mr);
2619
2730
  }
2620
2731
  // ─── FASE 2 — pull (reconciliar o cache) ─────────────────────────────────────
2621
2732
  /**
@@ -2648,14 +2759,14 @@ var pe = class {
2648
2759
  let r = [];
2649
2760
  await this._applyServerDocs(t.docs, r, true);
2650
2761
  let o = t.truncatedCollections ?? [], i = new Set(o);
2651
- await this._store.setMeta(qe, o);
2762
+ await this._store.setMeta(Ve, o);
2652
2763
  let s = new Set(
2653
2764
  t.docs.map((a) => `${a.collection}::${a.id}`)
2654
2765
  );
2655
2766
  for (let a of e) {
2656
2767
  if (i.has(a)) continue;
2657
- let l = await this._store.listDocs(a, {});
2658
- for (let { id: d } of l.docs) {
2768
+ let c = await this._store.listDocs(a, {});
2769
+ for (let { id: d } of c.docs) {
2659
2770
  let u = `${a}::${d}`;
2660
2771
  if (!s.has(u)) {
2661
2772
  let p = await this._store.getDoc(a, d);
@@ -2705,7 +2816,7 @@ var pe = class {
2705
2816
  continue;
2706
2817
  }
2707
2818
  if (i && i.meta.state === "pending") {
2708
- let l = {
2819
+ let c = {
2709
2820
  collection: o.collection,
2710
2821
  id: o.id,
2711
2822
  data: o.data,
@@ -2722,7 +2833,7 @@ var pe = class {
2722
2833
  (p) => p.collection === o.collection && p.docId === o.id
2723
2834
  );
2724
2835
  if (u) {
2725
- let p = this._resolver.resolve(i, l, u);
2836
+ let p = this._resolver.resolve(i, c, u);
2726
2837
  p.conflictRecord && await this._store.appendConflict(p.conflictRecord), await this._store.putDoc({
2727
2838
  ...i,
2728
2839
  meta: { ...i.meta, state: "conflict" }
@@ -2867,10 +2978,10 @@ var pe = class {
2867
2978
  };
2868
2979
 
2869
2980
  // src/db/offline/conflict-resolver.ts
2870
- function xt(n, e) {
2981
+ function Kt(n, e) {
2871
2982
  return e === null ? false : n === null ? true : e > n;
2872
2983
  }
2873
- var fe = class n {
2984
+ var ge = class n {
2874
2985
  /**
2875
2986
  * Resolve um conflito com base na operação da mutação (auto-dispatch).
2876
2987
  *
@@ -2904,7 +3015,7 @@ var fe = class n {
2904
3015
  resolvedData: t.data,
2905
3016
  conflictRecord: null
2906
3017
  };
2907
- if (!xt(
3018
+ if (!Kt(
2908
3019
  e.meta.updatedAtServer,
2909
3020
  t.meta.updatedAtServer
2910
3021
  ))
@@ -2951,7 +3062,7 @@ var fe = class n {
2951
3062
  let i = t.data;
2952
3063
  if (e === null)
2953
3064
  return { outcome: "no_conflict", resolvedData: { ...i, ...r.payload ?? {} }, conflictRecord: null };
2954
- if (!xt(
3065
+ if (!Kt(
2955
3066
  e.meta.updatedAtServer,
2956
3067
  t.meta.updatedAtServer
2957
3068
  ))
@@ -2959,7 +3070,7 @@ var fe = class n {
2959
3070
  let a = {};
2960
3071
  for (let d of o)
2961
3072
  a[d] = e.data[d];
2962
- let l = {
3073
+ let c = {
2963
3074
  collection: r.collection,
2964
3075
  docId: r.docId,
2965
3076
  mutationId: r.mutationId,
@@ -2972,7 +3083,7 @@ var fe = class n {
2972
3083
  return {
2973
3084
  outcome: "server_wins",
2974
3085
  resolvedData: i,
2975
- conflictRecord: l
3086
+ conflictRecord: c
2976
3087
  };
2977
3088
  }
2978
3089
  /**
@@ -3029,10 +3140,10 @@ var fe = class n {
3029
3140
  };
3030
3141
 
3031
3142
  // src/db/offline/change-bus.ts
3032
- function vr(n) {
3143
+ function jr(n) {
3033
3144
  return `${n.collection}::${n.doc.id}`;
3034
3145
  }
3035
- var me = class {
3146
+ var ye = class {
3036
3147
  /** Listeners filtrados por coleção. */
3037
3148
  _collectionListeners = /* @__PURE__ */ new Map();
3038
3149
  /** Listeners globais (todas as coleções). */
@@ -3077,15 +3188,15 @@ var me = class {
3077
3188
  if (e.length === 0) return;
3078
3189
  let t = /* @__PURE__ */ new Map();
3079
3190
  for (let i of e)
3080
- t.set(vr(i), i);
3191
+ t.set(jr(i), i);
3081
3192
  let r = Array.from(t.values()), o = /* @__PURE__ */ new Map();
3082
3193
  for (let i of r)
3083
3194
  o.has(i.collection) || o.set(i.collection, []), o.get(i.collection).push(i);
3084
3195
  for (let [i, s] of o) {
3085
3196
  let a = this._collectionListeners.get(i);
3086
3197
  if (a)
3087
- for (let l of a)
3088
- this._safeCall(l, s);
3198
+ for (let c of a)
3199
+ this._safeCall(c, s);
3089
3200
  }
3090
3201
  for (let i of this._globalListeners)
3091
3202
  this._safeCall(i, r);
@@ -3116,7 +3227,7 @@ var me = class {
3116
3227
  };
3117
3228
 
3118
3229
  // src/db/offline/connectivity-monitor.ts
3119
- var he = class {
3230
+ var _e = class {
3120
3231
  _state;
3121
3232
  _listeners = /* @__PURE__ */ new Set();
3122
3233
  _nav;
@@ -3218,7 +3329,7 @@ var he = class {
3218
3329
  };
3219
3330
 
3220
3331
  // src/db/offline/tab-coordinator.ts
3221
- var te = class {
3332
+ var ne = class {
3222
3333
  _lockName;
3223
3334
  _channelName;
3224
3335
  _lockManager;
@@ -3395,16 +3506,16 @@ var te = class {
3395
3506
  };
3396
3507
 
3397
3508
  // src/db/collection-ref.ts
3398
- Y();
3399
- function wr() {
3509
+ Z();
3510
+ function $r() {
3400
3511
  return typeof indexedDB > "u" || typeof window > "u";
3401
3512
  }
3402
- var Ot = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3403
- function kr(n) {
3404
- if (!Ot.test(n))
3513
+ var zt = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3514
+ function Wr(n) {
3515
+ if (!zt.test(n))
3405
3516
  throw new y(
3406
3517
  "db_invalid_query",
3407
- `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${Ot}.`
3518
+ `Nome de cole\xE7\xE3o inv\xE1lido: "${n}". Deve seguir o padr\xE3o ${zt}.`
3408
3519
  );
3409
3520
  }
3410
3521
  function G(n, e = "id") {
@@ -3414,7 +3525,7 @@ function G(n, e = "id") {
3414
3525
  `${e} \xE9 obrigat\xF3rio e deve ser uma string n\xE3o-vazia.`
3415
3526
  );
3416
3527
  }
3417
- function Sr(n) {
3528
+ function Br(n) {
3418
3529
  let e = {};
3419
3530
  if (n?.where && (e.where = n.where.map((t) => ({
3420
3531
  field: t.field,
@@ -3431,12 +3542,12 @@ function Sr(n) {
3431
3542
  }
3432
3543
  return e;
3433
3544
  }
3434
- function Tr(n, e) {
3545
+ function Vr(n, e) {
3435
3546
  if (n.length < e) return null;
3436
3547
  let t = n[n.length - 1];
3437
3548
  return t ? btoa(JSON.stringify({ type: "startAfter", docId: t.id })) : null;
3438
3549
  }
3439
- var Fe = class {
3550
+ var Ke = class {
3440
3551
  constructor(e, t, r, o, i, s) {
3441
3552
  this._collection = e;
3442
3553
  this._store = t;
@@ -3478,10 +3589,10 @@ var Fe = class {
3478
3589
  }
3479
3590
  /** Constrói um DbListResult para a coleção com query opcional. */
3480
3591
  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;
3592
+ let t = Br(e), r = t.limit ?? 20, o = await this._store.listDocs(this._collection, t), i = await this._hasPendingWrites(), s = this._isOnline(), a = this._engine.getSyncState(), c = Vr(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
3593
  return {
3483
- docs: o.docs.map((g) => ({ id: g.id, data: g.data })),
3484
- nextCursor: l,
3594
+ docs: o.docs.map((_) => ({ id: _.id, data: _.data })),
3595
+ nextCursor: c,
3485
3596
  fromCache: f,
3486
3597
  stale: p,
3487
3598
  hasPendingWrites: i,
@@ -3497,7 +3608,7 @@ var Fe = class {
3497
3608
  return this._buildListResult(e);
3498
3609
  }
3499
3610
  async add(e) {
3500
- let t = e, r = z(t, void 0), o = await this._queue.enqueue({
3611
+ let t = e, r = K(t, void 0), o = await this._queue.enqueue({
3501
3612
  collection: this._collection,
3502
3613
  op: "add",
3503
3614
  payload: t,
@@ -3525,7 +3636,7 @@ var Fe = class {
3525
3636
  }
3526
3637
  async set(e, t) {
3527
3638
  G(e);
3528
- let r = await this._store.getDoc(this._collection, e), o = t, i = z(o, void 0), s = await this._queue.enqueue({
3639
+ let r = await this._store.getDoc(this._collection, e), o = t, i = K(o, void 0), s = await this._queue.enqueue({
3529
3640
  collection: this._collection,
3530
3641
  docId: e,
3531
3642
  op: "set",
@@ -3554,7 +3665,7 @@ var Fe = class {
3554
3665
  }
3555
3666
  async update(e, t, r) {
3556
3667
  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({
3668
+ let o = await this._store.getDoc(this._collection, e), i = t, s = o?.meta.deleted ? void 0 : o?.data, a = K(i, s), c = o?.meta.deleted ? { ...a } : { ...o?.data ?? {}, ...a }, d = await this._queue.enqueue({
3558
3669
  collection: this._collection,
3559
3670
  docId: e,
3560
3671
  op: "update",
@@ -3567,7 +3678,7 @@ var Fe = class {
3567
3678
  return await this._store.putDoc({
3568
3679
  collection: this._collection,
3569
3680
  id: e,
3570
- data: l,
3681
+ data: c,
3571
3682
  meta: {
3572
3683
  serverVersion: o?.meta.serverVersion ?? null,
3573
3684
  updatedAtServer: o?.meta.updatedAtServer ?? null,
@@ -3583,7 +3694,7 @@ var Fe = class {
3583
3694
  }), this._bus.emit([{
3584
3695
  type: "modified",
3585
3696
  collection: this._collection,
3586
- doc: { id: e, data: l }
3697
+ doc: { id: e, data: c }
3587
3698
  }]), { ok: true };
3588
3699
  }
3589
3700
  async remove(e) {
@@ -3607,13 +3718,13 @@ var Fe = class {
3607
3718
  for (let o of e) {
3608
3719
  let i = this._collection;
3609
3720
  if (o.kind === "add") {
3610
- let s = o.data, a = z(s, void 0), l = await this._queue.enqueue({
3721
+ let s = o.data, a = K(s, void 0), c = await this._queue.enqueue({
3611
3722
  collection: i,
3612
3723
  op: "add",
3613
3724
  payload: s,
3614
3725
  baseVersion: null,
3615
3726
  batchId: t
3616
- }), d = l.docId;
3727
+ }), d = c.docId;
3617
3728
  await this._store.putDoc({
3618
3729
  collection: i,
3619
3730
  id: d,
@@ -3623,18 +3734,18 @@ var Fe = class {
3623
3734
  updatedAtServer: null,
3624
3735
  updatedAtLocal: Date.now(),
3625
3736
  state: "pending",
3626
- pendingMutationIds: [l.mutationId],
3737
+ pendingMutationIds: [c.mutationId],
3627
3738
  deleted: false,
3628
3739
  ownerId: null
3629
3740
  }
3630
3741
  }), r.push({ type: "added", collection: i, doc: { id: d, data: a } });
3631
3742
  } 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({
3743
+ let s = o.id, a = o.data, c = await this._store.getDoc(i, s), d = K(a, void 0), u = await this._queue.enqueue({
3633
3744
  collection: i,
3634
3745
  docId: s,
3635
3746
  op: "set",
3636
3747
  payload: a,
3637
- baseVersion: l?.meta.serverVersion ?? null,
3748
+ baseVersion: c?.meta.serverVersion ?? null,
3638
3749
  batchId: t
3639
3750
  });
3640
3751
  await this._store.putDoc({
@@ -3642,8 +3753,8 @@ var Fe = class {
3642
3753
  id: s,
3643
3754
  data: d,
3644
3755
  meta: {
3645
- serverVersion: l?.meta.serverVersion ?? null,
3646
- updatedAtServer: l?.meta.updatedAtServer ?? null,
3756
+ serverVersion: c?.meta.serverVersion ?? null,
3757
+ updatedAtServer: c?.meta.updatedAtServer ?? null,
3647
3758
  updatedAtLocal: Date.now(),
3648
3759
  state: "pending",
3649
3760
  pendingMutationIds: [u.mutationId],
@@ -3651,17 +3762,17 @@ var Fe = class {
3651
3762
  ownerId: null
3652
3763
  }
3653
3764
  }), r.push({
3654
- type: l && !l.meta.deleted ? "modified" : "added",
3765
+ type: c && !c.meta.deleted ? "modified" : "added",
3655
3766
  collection: i,
3656
3767
  doc: { id: s, data: d }
3657
3768
  });
3658
3769
  } 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({
3770
+ let s = o.id, a = o.data, c = await this._store.getDoc(i, s), d = c?.meta.deleted ? void 0 : c?.data, u = K(a, d), p = { ...c?.data ?? {}, ...u }, f = await this._queue.enqueue({
3660
3771
  collection: i,
3661
3772
  docId: s,
3662
3773
  op: "update",
3663
3774
  payload: a,
3664
- baseVersion: l?.meta.serverVersion ?? null,
3775
+ baseVersion: c?.meta.serverVersion ?? null,
3665
3776
  batchId: t,
3666
3777
  // bug_0273e4dd: propaga merge-upsert (writeBatch.set(merge) cria-se-ausente).
3667
3778
  upsert: o.upsert
@@ -3671,16 +3782,16 @@ var Fe = class {
3671
3782
  id: s,
3672
3783
  data: p,
3673
3784
  meta: {
3674
- serverVersion: l?.meta.serverVersion ?? null,
3675
- updatedAtServer: l?.meta.updatedAtServer ?? null,
3785
+ serverVersion: c?.meta.serverVersion ?? null,
3786
+ updatedAtServer: c?.meta.updatedAtServer ?? null,
3676
3787
  updatedAtLocal: Date.now(),
3677
3788
  state: "pending",
3678
3789
  pendingMutationIds: [
3679
- ...l?.meta.pendingMutationIds ?? [],
3790
+ ...c?.meta.pendingMutationIds ?? [],
3680
3791
  f.mutationId
3681
3792
  ],
3682
3793
  deleted: false,
3683
- ownerId: l?.meta.ownerId ?? null
3794
+ ownerId: c?.meta.ownerId ?? null
3684
3795
  }
3685
3796
  }), r.push({ type: "modified", collection: i, doc: { id: s, data: p } });
3686
3797
  } else if (o.kind === "remove") {
@@ -3711,11 +3822,11 @@ var Fe = class {
3711
3822
  });
3712
3823
  let r = this._bus.subscribe(this._collection, async (s) => {
3713
3824
  try {
3714
- let a = await this._buildListResult(e), l = s.map((d) => ({
3825
+ let a = await this._buildListResult(e), c = s.map((d) => ({
3715
3826
  type: d.type,
3716
3827
  doc: { id: d.doc.id, data: d.doc.data }
3717
3828
  }));
3718
- t({ ...a, changes: l });
3829
+ t({ ...a, changes: c });
3719
3830
  } catch {
3720
3831
  }
3721
3832
  }), o = this._engine.onSyncStateChange(async () => {
@@ -3729,15 +3840,15 @@ var Fe = class {
3729
3840
  this._collection,
3730
3841
  async (s, a) => {
3731
3842
  if (!a)
3732
- for (let l of s)
3733
- l.type === "removed" || l.data === null ? (await this._store.deleteDoc(this._collection, l.docId), this._bus.emit([{
3843
+ for (let c of s)
3844
+ c.type === "removed" || c.data === null ? (await this._store.deleteDoc(this._collection, c.docId), this._bus.emit([{
3734
3845
  type: "removed",
3735
3846
  collection: this._collection,
3736
- doc: { id: l.docId, data: {} }
3847
+ doc: { id: c.docId, data: {} }
3737
3848
  }])) : (await this._store.putDoc({
3738
3849
  collection: this._collection,
3739
- id: l.docId,
3740
- data: l.data,
3850
+ id: c.docId,
3851
+ data: c.data,
3741
3852
  meta: {
3742
3853
  serverVersion: `rt_${Date.now()}`,
3743
3854
  updatedAtServer: Date.now(),
@@ -3748,9 +3859,9 @@ var Fe = class {
3748
3859
  ownerId: null
3749
3860
  }
3750
3861
  }), this._bus.emit([{
3751
- type: l.type,
3862
+ type: c.type,
3752
3863
  collection: this._collection,
3753
- doc: { id: l.docId, data: l.data }
3864
+ doc: { id: c.docId, data: c.data }
3754
3865
  }]));
3755
3866
  }
3756
3867
  )), () => {
@@ -3785,14 +3896,14 @@ var Fe = class {
3785
3896
  onSnapshot(r) {
3786
3897
  t._buildGetResult(e).then((s) => r(s)).catch(() => r(null));
3787
3898
  let o = t._bus.subscribe(t._collection, async (s) => {
3788
- let a = s.find((l) => l.doc.id === e);
3899
+ let a = s.find((c) => c.doc.id === e);
3789
3900
  if (a)
3790
3901
  try {
3791
3902
  if (a.type === "removed")
3792
3903
  r(null);
3793
3904
  else {
3794
- let l = await t._buildGetResult(e);
3795
- r(l);
3905
+ let c = await t._buildGetResult(e);
3906
+ r(c);
3796
3907
  }
3797
3908
  } catch {
3798
3909
  r(null);
@@ -3811,7 +3922,7 @@ var Fe = class {
3811
3922
  }
3812
3923
  };
3813
3924
  }
3814
- }, je = class {
3925
+ }, ze = class {
3815
3926
  _store;
3816
3927
  _queue;
3817
3928
  _bus;
@@ -3821,7 +3932,7 @@ var Fe = class {
3821
3932
  this._store = e.store, this._queue = e.queue, this._bus = e.bus, this._engine = e.engine, this._connectivity = e.connectivity;
3822
3933
  }
3823
3934
  collection(e) {
3824
- return kr(e), new Fe(
3935
+ return Wr(e), new Ke(
3825
3936
  e,
3826
3937
  this._store,
3827
3938
  this._queue,
@@ -3850,23 +3961,23 @@ var Fe = class {
3850
3961
  return this._engine.onError(e);
3851
3962
  }
3852
3963
  };
3853
- async function Lt(n) {
3854
- let e = wr() ? new de() : new le(n.dbName);
3964
+ async function Ht(n) {
3965
+ let e = $r() ? new fe() : new pe(n.dbName);
3855
3966
  await e.open();
3856
- let t = new ue(e), r = new fe(), o = new me(), i = new he({
3967
+ let t = new me(e), r = new ge(), o = new ye(), i = new _e({
3857
3968
  // Se startOnline=false, injeta um navigator falso
3858
3969
  navigator: n.startOnline === false ? { onLine: false } : typeof navigator < "u" ? navigator : void 0
3859
3970
  }), s = n.singleTab ? (
3860
3971
  // Fake tab coordinator para single-tab mode (sempre líder)
3861
3972
  {
3862
3973
  isLeader: () => true,
3863
- onRoleChange: (l) => () => {
3974
+ onRoleChange: (c) => () => {
3864
3975
  }
3865
3976
  }
3866
- ) : new te({
3977
+ ) : new ne({
3867
3978
  lockName: `neetru-offline:${n.dbName}`,
3868
3979
  channelName: `neetru-offline:${n.dbName}`
3869
- }), a = new pe({
3980
+ }), a = new he({
3870
3981
  store: e,
3871
3982
  queue: t,
3872
3983
  resolver: r,
@@ -3876,7 +3987,7 @@ async function Lt(n) {
3876
3987
  connectivity: i,
3877
3988
  periodicSyncIntervalMs: n.periodicSyncIntervalMs ?? 300 * 1e3
3878
3989
  });
3879
- return i.start(), !n.singleTab && s instanceof te && s.start(), new je({
3990
+ return i.start(), !n.singleTab && s instanceof ne && s.start(), new ze({
3880
3991
  store: e,
3881
3992
  queue: t,
3882
3993
  bus: o,
@@ -3886,11 +3997,11 @@ async function Lt(n) {
3886
3997
  }
3887
3998
 
3888
3999
  // 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)}`;
4000
+ var Kr = 0;
4001
+ function Qt() {
4002
+ return typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : `nrt-sub-${Date.now()}-${++Kr}-${Math.random().toString(36).slice(2)}`;
3892
4003
  }
3893
- var ge = class {
4004
+ var be = class {
3894
4005
  // ── configuração ──────────────────────────────────────────────────────────
3895
4006
  _gatewayUrl;
3896
4007
  _wsFactory;
@@ -3928,7 +4039,7 @@ var ge = class {
3928
4039
  _pendingFrames = [];
3929
4040
  // ── construtor ────────────────────────────────────────────────────────────
3930
4041
  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();
4042
+ this._gatewayUrl = e.gatewayUrl, this._wsFactory = e.webSocketFactory ?? zr, 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
4043
  }
3933
4044
  // ── API pública ───────────────────────────────────────────────────────────
3934
4045
  /**
@@ -3942,8 +4053,8 @@ var ge = class {
3942
4053
  */
3943
4054
  subscribe(e, t, r) {
3944
4055
  if (this._closed)
3945
- return Ut();
3946
- let o = Ut();
4056
+ return Qt();
4057
+ let o = Qt();
3947
4058
  this._subscriptions.set(o, {
3948
4059
  subscriptionId: o,
3949
4060
  collection: e,
@@ -4207,7 +4318,7 @@ var ge = class {
4207
4318
  _detachHandlers(e) {
4208
4319
  e.onopen = null, e.onmessage = null, e.onclose = null, e.onerror = null;
4209
4320
  }
4210
- }, Ir = (n) => {
4321
+ }, zr = (n) => {
4211
4322
  if (typeof WebSocket > "u")
4212
4323
  throw new Error(
4213
4324
  "[NeetruRealtimeClient] WebSocket n\xE3o dispon\xEDvel neste ambiente. Injete uma implementa\xE7\xE3o via `webSocketFactory` nas op\xE7\xF5es."
@@ -4216,11 +4327,11 @@ var ge = class {
4216
4327
  };
4217
4328
 
4218
4329
  // 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);
4330
+ var ro = (n) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}`, we = (n, e) => `/api/sdk/v1/datastore/${encodeURIComponent(n)}/${encodeURIComponent(e)}`, sn = 200;
4331
+ function oo(n, e, t) {
4332
+ return e._transport ? e._transport : n === "firestore" && e.firestoreTransport ? e.firestoreTransport : n === "nosql-vm" && e.realtimeGatewayUrl ? io(e.realtimeGatewayUrl, t, e) : cn(t);
4222
4333
  }
4223
- function Gt(n) {
4334
+ function cn(n) {
4224
4335
  return {
4225
4336
  async pushMutations(e) {
4226
4337
  if (!n)
@@ -4228,47 +4339,47 @@ function Gt(n) {
4228
4339
  "db_unavailable",
4229
4340
  "[RestSyncTransport] config n\xE3o dispon\xEDvel \u2014 n\xE3o \xE9 poss\xEDvel enviar ao Core. Inicialize o transporte via createNeetruDb."
4230
4341
  );
4231
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4342
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y)), r = [], o = n.tenantId ?? n.productId, i = o ? { "x-neetru-tenant": o } : void 0;
4232
4343
  for (let s of e)
4233
4344
  try {
4234
4345
  let a;
4235
4346
  s.op === "add" ? a = await t(n, {
4236
4347
  method: "PUT",
4237
- path: _e(s.collection, s.docId),
4348
+ path: we(s.collection, s.docId),
4238
4349
  body: { data: s.payload ?? {} },
4239
4350
  requireAuth: !0,
4240
4351
  retries: 2,
4241
4352
  headers: i
4242
4353
  }) : s.op === "set" ? a = await t(n, {
4243
4354
  method: "PUT",
4244
- path: _e(s.collection, s.docId),
4355
+ path: we(s.collection, s.docId),
4245
4356
  body: { data: s.payload ?? {} },
4246
4357
  requireAuth: !0,
4247
4358
  retries: 2,
4248
4359
  headers: i
4249
4360
  }) : s.op === "update" ? a = await t(n, {
4250
4361
  method: "PATCH",
4251
- path: _e(s.collection, s.docId),
4362
+ path: we(s.collection, s.docId),
4252
4363
  body: { data: s.payload ?? {}, ...s.upsert ? { upsert: !0 } : {} },
4253
4364
  requireAuth: !0,
4254
4365
  retries: 2,
4255
4366
  headers: i
4256
4367
  }) : a = await t(n, {
4257
4368
  method: "DELETE",
4258
- path: _e(s.collection, s.docId),
4369
+ path: we(s.collection, s.docId),
4259
4370
  requireAuth: !0,
4260
4371
  retries: 2,
4261
4372
  headers: i
4262
4373
  });
4263
- let l = a;
4374
+ let c = a;
4264
4375
  r.push({
4265
4376
  mutationId: s.mutationId,
4266
4377
  outcome: "confirmed",
4267
- serverVersion: l?.serverVersion ?? l?.id ?? `rest_${Date.now()}`,
4378
+ serverVersion: c?.serverVersion ?? c?.id ?? `rest_${Date.now()}`,
4268
4379
  serverTimestamp: Date.now()
4269
4380
  });
4270
4381
  } catch (a) {
4271
- let l = a instanceof Error ? a.message : String(a), d = a?.code, u = a?.status;
4382
+ let c = a instanceof Error ? a.message : String(a), d = a?.code, u = a?.status;
4272
4383
  if (d === "forbidden" || d === "unauthorized" || d === "not_found" || d === "conflict" || d === "validation_failed" || typeof u == "number" && u >= 400 && u < 500 && u !== 408 && u !== 429) {
4273
4384
  let f = d === "forbidden" || d === "unauthorized" ? "rejected_permission" : "rejected_validation";
4274
4385
  r.push({
@@ -4281,7 +4392,7 @@ function Gt(n) {
4281
4392
  continue;
4282
4393
  }
4283
4394
  if (r.length === 0)
4284
- throw new y("db_unavailable", `pushMutations falhou: ${l}`);
4395
+ throw new y("db_unavailable", `pushMutations falhou: ${c}`);
4285
4396
  break;
4286
4397
  }
4287
4398
  return { results: r };
@@ -4292,13 +4403,13 @@ function Gt(n) {
4292
4403
  async fullResync(e) {
4293
4404
  if (!n)
4294
4405
  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 = [];
4296
- for (let l of e) {
4406
+ 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 = [];
4407
+ for (let c of e) {
4297
4408
  let d;
4298
4409
  try {
4299
4410
  d = await t(n, {
4300
4411
  method: "GET",
4301
- path: Mr(l),
4412
+ path: ro(c),
4302
4413
  requireAuth: !0,
4303
4414
  retries: 2,
4304
4415
  headers: o,
@@ -4306,37 +4417,37 @@ function Gt(n) {
4306
4417
  // TRUNCADAS — reportadas em `truncatedCollections` p/ o SyncEngine
4307
4418
  // (a) NÃO rodar deleção-por-ausência e (b) sinalizar
4308
4419
  // `DbListResult.truncated`. Paginação por cursor é tarefa Core (gated).
4309
- query: { limit: Ht }
4420
+ query: { limit: sn }
4310
4421
  });
4311
4422
  } catch (f) {
4312
- let g = f instanceof Error ? f.message : String(f);
4423
+ let _ = f instanceof Error ? f.message : String(f);
4313
4424
  throw new y(
4314
4425
  "db_unavailable",
4315
- `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${l}": ${g}`
4426
+ `[RestSyncTransport] fullResync falhou na cole\xE7\xE3o "${c}": ${_}`
4316
4427
  );
4317
4428
  }
4318
4429
  let u = d, p = Array.isArray(u?.items) ? u.items : [];
4319
- p.length >= Ht && a.push(l);
4430
+ p.length >= sn && a.push(c);
4320
4431
  for (let f of p) {
4321
4432
  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);
4433
+ let _ = f, b = typeof _.id == "string" ? _.id : null;
4434
+ if (!b) continue;
4435
+ let { id: S, ...x } = _, T = i, P = x._updatedAt;
4436
+ if (typeof P == "number")
4437
+ T = P;
4438
+ else if (P !== null && typeof P == "object" && typeof P._seconds == "number")
4439
+ T = P._seconds * 1e3;
4440
+ else if (typeof P == "string") {
4441
+ let m = Date.parse(P);
4442
+ Number.isNaN(m) || (T = m);
4332
4443
  }
4333
- let $ = `rest_${_}_${N}`;
4444
+ let q = `rest_${b}_${T}`;
4334
4445
  s.push({
4335
- collection: l,
4336
- id: _,
4337
- data: R,
4338
- serverVersion: $,
4339
- serverTimestamp: N,
4446
+ collection: c,
4447
+ id: b,
4448
+ data: x,
4449
+ serverVersion: q,
4450
+ serverTimestamp: T,
4340
4451
  deleted: false
4341
4452
  });
4342
4453
  }
@@ -4345,10 +4456,10 @@ function Gt(n) {
4345
4456
  }
4346
4457
  };
4347
4458
  }
4348
- function Fr(n, e, t) {
4349
- let r = Gt(e), o = new ge({
4459
+ function io(n, e, t) {
4460
+ let r = cn(e), o = new be({
4350
4461
  gatewayUrl: n,
4351
- ticketProvider: jr(e, t),
4462
+ ticketProvider: so(e, t),
4352
4463
  dbId: t.dbId,
4353
4464
  webSocketFactory: t._wsFactory
4354
4465
  });
@@ -4360,17 +4471,17 @@ function Fr(n, e, t) {
4360
4471
  // quando o engine é nosql-vm. Registra a subscription no NeetruRealtimeClient
4361
4472
  // e traduz os frames inbound para o contrato de `onChange`.
4362
4473
  subscribeCollection(i, s) {
4363
- let a = o.subscribe(i, {}, (l) => {
4364
- if (l.op === "resync") {
4474
+ let a = o.subscribe(i, {}, (c) => {
4475
+ if (c.op === "resync") {
4365
4476
  s([], true);
4366
4477
  return;
4367
4478
  }
4368
- if (l.op === "stale") {
4479
+ if (c.op === "stale") {
4369
4480
  s([], true);
4370
4481
  return;
4371
4482
  }
4372
- if (l.op === "delta" && l.changes) {
4373
- let d = l.changes.map((u) => ({
4483
+ if (c.op === "delta" && c.changes) {
4484
+ let d = c.changes.map((u) => ({
4374
4485
  type: u.type === "insert" ? "added" : u.type === "delete" ? "removed" : "modified",
4375
4486
  docId: u.documentId,
4376
4487
  data: u.data ?? null
@@ -4384,9 +4495,9 @@ function Fr(n, e, t) {
4384
4495
  }
4385
4496
  };
4386
4497
  }
4387
- function jr(n, e) {
4498
+ function so(n, e) {
4388
4499
  return async () => {
4389
- let { httpRequest: t } = await Promise.resolve().then(() => (U(), X));
4500
+ let { httpRequest: t } = await Promise.resolve().then(() => (M(), Y));
4390
4501
  return await t(n, {
4391
4502
  method: "POST",
4392
4503
  path: "/api/sdk/v1/db/realtime/ticket",
@@ -4399,21 +4510,21 @@ function jr(n, e) {
4399
4510
  });
4400
4511
  };
4401
4512
  }
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(
4513
+ var an = false;
4514
+ function ao(n, e) {
4515
+ an || e.dbId && n.env !== "prod" && (typeof window > "u" || typeof console > "u" || typeof console.warn != "function" || (an = true, console.warn(
4405
4516
  '[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
4517
  )));
4407
4518
  }
4408
- function Jt(n, e = {}) {
4409
- Wr(n, e);
4519
+ function ln(n, e = {}) {
4520
+ ao(n, e);
4410
4521
  let t;
4411
4522
  e.transport !== void 0 ? t = e.transport : e.engine !== void 0 ? (console.warn(
4412
4523
  '[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
4524
  ), 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;
4415
- function l() {
4416
- return s || (s = Lt({
4525
+ let r = oo(t, e, n), o = e.dbId ?? "default", i = e.dbName ?? `neetru-db__${n.productId ?? "sdk"}__${o}__${n.env}`, s = null, a = null;
4526
+ function c() {
4527
+ return s || (s = Ht({
4417
4528
  dbName: i,
4418
4529
  transport: r,
4419
4530
  singleTab: e.singleTab ?? n.env !== "prod"
@@ -4421,7 +4532,7 @@ function Jt(n, e = {}) {
4421
4532
  }
4422
4533
  return {
4423
4534
  collection(d) {
4424
- return a ? a.collection(d) : $r(d, l);
4535
+ return a ? a.collection(d) : co(d, c);
4425
4536
  },
4426
4537
  async sql(d, u) {
4427
4538
  if (n.env === "dev")
@@ -4429,7 +4540,7 @@ function Jt(n, e = {}) {
4429
4540
  "db_unavailable",
4430
4541
  "[SDK] db.sql() n\xE3o dispon\xEDvel em NEETRU_ENV=dev. Use `neetru dev` para subir o container Postgres local."
4431
4542
  );
4432
- return (await Promise.resolve().then(() => (Kt(), zt))).createSqlClientFromConfig(n, d, u);
4543
+ return (await Promise.resolve().then(() => (on(), rn))).createSqlClientFromConfig(n, d, u);
4433
4544
  },
4434
4545
  get syncState() {
4435
4546
  return a?.syncState ?? {
@@ -4442,25 +4553,25 @@ function Jt(n, e = {}) {
4442
4553
  onSyncStateChanged(d) {
4443
4554
  if (a) return a.onSyncStateChanged(d);
4444
4555
  let u = null, p = false;
4445
- return l().then((f) => {
4556
+ return c().then((f) => {
4446
4557
  p || (u = f.onSyncStateChanged(d));
4447
4558
  }), () => {
4448
4559
  p = true, u?.();
4449
4560
  };
4450
4561
  },
4451
4562
  async flush() {
4452
- return (await l()).flush();
4563
+ return (await c()).flush();
4453
4564
  },
4454
4565
  async clearCache() {
4455
- return (await l()).clearCache();
4566
+ return (await c()).clearCache();
4456
4567
  },
4457
4568
  async getConflicts() {
4458
- return (await l()).getConflicts();
4569
+ return (await c()).getConflicts();
4459
4570
  },
4460
4571
  onError(d) {
4461
4572
  if (a) return a.onError(d);
4462
4573
  let u = null, p = false;
4463
- return l().then((f) => {
4574
+ return c().then((f) => {
4464
4575
  p || (u = f.onError(d));
4465
4576
  }), () => {
4466
4577
  p = true, u?.();
@@ -4468,7 +4579,7 @@ function Jt(n, e = {}) {
4468
4579
  }
4469
4580
  };
4470
4581
  }
4471
- function $r(n, e) {
4582
+ function co(n, e) {
4472
4583
  async function t() {
4473
4584
  return (await e()).collection(n);
4474
4585
  }
@@ -4547,25 +4658,25 @@ function $r(n, e) {
4547
4658
  }
4548
4659
 
4549
4660
  // src/checkout.ts
4550
- P();
4551
- U();
4552
- function Ke(n, e) {
4661
+ I();
4662
+ M();
4663
+ function Ye(n, e) {
4553
4664
  let t = n?.accessToken || n?.idToken;
4554
4665
  if (!t || typeof t != "string")
4555
- throw new c(
4666
+ throw new l(
4556
4667
  "validation_failed",
4557
4668
  `checkout.${e} requer o access_token OU o id_token OIDC do usu\xE1rio final (passe \`accessToken\` ou \`idToken\`). A chave de API do SDK (nrt_*) N\xC3O \xE9 aceita pelo endpoint de checkout \u2014 ele autentica a identidade do cliente que est\xE1 assinando (Bearer access_token/id_token OIDC ou cookie de sess\xE3o). No padr\xE3o BFF/cookie, passe o \`idToken\` que seu servidor guardou no cookie httpOnly.`
4558
4669
  );
4559
4670
  return { requireAuth: false, headers: { authorization: `Bearer ${t}` } };
4560
4671
  }
4561
- function Br(n) {
4672
+ function lo(n) {
4562
4673
  if (!n || typeof n != "object")
4563
- throw new c("invalid_response", "checkout.start response is not an object");
4674
+ throw new l("invalid_response", "checkout.start response is not an object");
4564
4675
  let e = n;
4565
4676
  if (typeof e.intentId != "string" || !e.intentId)
4566
- throw new c("invalid_response", "checkout.start response missing intentId");
4677
+ throw new l("invalid_response", "checkout.start response missing intentId");
4567
4678
  if (typeof e.redirectUrl != "string" || !e.redirectUrl)
4568
- throw new c("invalid_response", "checkout.start response missing redirectUrl");
4679
+ throw new l("invalid_response", "checkout.start response missing redirectUrl");
4569
4680
  return {
4570
4681
  intentId: e.intentId,
4571
4682
  redirectUrl: e.redirectUrl,
@@ -4574,14 +4685,14 @@ function Br(n) {
4574
4685
  requiresKyc: e.requiresKyc === true
4575
4686
  };
4576
4687
  }
4577
- function Vr(n) {
4688
+ function uo(n) {
4578
4689
  if (!n || typeof n != "object")
4579
- throw new c("invalid_response", "checkout.get response is not an object");
4690
+ throw new l("invalid_response", "checkout.get response is not an object");
4580
4691
  let e = n, t = e.intent;
4581
4692
  if (!t || typeof t != "object")
4582
- throw new c("invalid_response", "checkout.get response missing intent");
4693
+ throw new l("invalid_response", "checkout.get response missing intent");
4583
4694
  if (typeof t.intentId != "string")
4584
- throw new c("invalid_response", "checkout.get response missing intentId");
4695
+ throw new l("invalid_response", "checkout.get response missing intentId");
4585
4696
  return {
4586
4697
  intentId: t.intentId,
4587
4698
  uid: t.uid ?? "",
@@ -4596,35 +4707,35 @@ function Vr(n) {
4596
4707
  isStale: e.isStale === true
4597
4708
  };
4598
4709
  }
4599
- function zr() {
4710
+ function po() {
4600
4711
  try {
4601
4712
  return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
4602
4713
  } catch {
4603
4714
  return false;
4604
4715
  }
4605
4716
  }
4606
- function Kr(n) {
4717
+ function fo(n) {
4607
4718
  try {
4608
4719
  globalThis.location.assign(n);
4609
4720
  } catch {
4610
4721
  }
4611
4722
  }
4612
- function Hr(n) {
4723
+ function mo(n) {
4613
4724
  return {
4614
4725
  async start(e) {
4615
4726
  if (!e?.productId)
4616
- throw new c("validation_failed", "checkout.start: productId is required");
4727
+ throw new l("validation_failed", "checkout.start: productId is required");
4617
4728
  if (!e?.planId)
4618
- throw new c("validation_failed", "checkout.start: planId is required");
4729
+ throw new l("validation_failed", "checkout.start: planId is required");
4619
4730
  if (!e?.callbackUrl)
4620
- throw new c("validation_failed", "checkout.start: callbackUrl is required");
4731
+ throw new l("validation_failed", "checkout.start: callbackUrl is required");
4621
4732
  let t = {
4622
4733
  productId: e.productId,
4623
4734
  planId: e.planId,
4624
4735
  callbackUrl: e.callbackUrl
4625
4736
  };
4626
4737
  e.tenantType && (t.targetTenantType = e.tenantType), e.tenantId && (t.targetTenantId = e.tenantId);
4627
- let { requireAuth: r, headers: o } = Ke(
4738
+ let { requireAuth: r, headers: o } = Ye(
4628
4739
  { accessToken: e.accessToken, idToken: e.idToken },
4629
4740
  "start"
4630
4741
  ), i = await v(n, {
@@ -4634,13 +4745,13 @@ function Hr(n) {
4634
4745
  requireAuth: r,
4635
4746
  headers: o,
4636
4747
  idempotencyKey: true
4637
- }), s = Br(i);
4638
- return e.autoRedirect !== false && zr() && Kr(s.redirectUrl), s;
4748
+ }), s = lo(i);
4749
+ return e.autoRedirect !== false && po() && fo(s.redirectUrl), s;
4639
4750
  },
4640
4751
  async get(e, t) {
4641
4752
  if (!e || typeof e != "string")
4642
- throw new c("validation_failed", "checkout.get: intentId is required");
4643
- let { requireAuth: r, headers: o } = Ke(
4753
+ throw new l("validation_failed", "checkout.get: intentId is required");
4754
+ let { requireAuth: r, headers: o } = Ye(
4644
4755
  { accessToken: t?.accessToken, idToken: t?.idToken },
4645
4756
  "get"
4646
4757
  ), i = await v(n, {
@@ -4649,12 +4760,12 @@ function Hr(n) {
4649
4760
  requireAuth: r,
4650
4761
  headers: o
4651
4762
  });
4652
- return Vr(i);
4763
+ return uo(i);
4653
4764
  },
4654
4765
  async cancel(e, t) {
4655
4766
  if (!e || typeof e != "string")
4656
- throw new c("validation_failed", "checkout.cancel: intentId is required");
4657
- let { requireAuth: r, headers: o } = Ke(
4767
+ throw new l("validation_failed", "checkout.cancel: intentId is required");
4768
+ let { requireAuth: r, headers: o } = Ye(
4658
4769
  { accessToken: t?.accessToken, idToken: t?.idToken },
4659
4770
  "cancel"
4660
4771
  );
@@ -4670,15 +4781,15 @@ function Hr(n) {
4670
4781
  }
4671
4782
  };
4672
4783
  }
4673
- var He = class {
4784
+ var Ze = class {
4674
4785
  intents = /* @__PURE__ */ new Map();
4675
4786
  async start(e) {
4676
4787
  if (!e?.productId)
4677
- throw new c("validation_failed", "checkout.start: productId is required");
4788
+ throw new l("validation_failed", "checkout.start: productId is required");
4678
4789
  if (!e?.planId)
4679
- throw new c("validation_failed", "checkout.start: planId is required");
4790
+ throw new l("validation_failed", "checkout.start: planId is required");
4680
4791
  if (!e?.callbackUrl)
4681
- throw new c("validation_failed", "checkout.start: callbackUrl is required");
4792
+ throw new l("validation_failed", "checkout.start: callbackUrl is required");
4682
4793
  let t = `chk_mock_${Math.random().toString(36).slice(2, 10)}`, r = new Date(Date.now() + 900 * 1e3).toISOString(), o = `https://localhost:9003/portal/checkout/${t}`;
4683
4794
  return this.intents.set(t, {
4684
4795
  intentId: t,
@@ -4702,25 +4813,25 @@ var He = class {
4702
4813
  async get(e, t) {
4703
4814
  let r = this.intents.get(e);
4704
4815
  if (!r)
4705
- throw new c("not_found", `Mock intent ${e} not found`);
4816
+ throw new l("not_found", `Mock intent ${e} not found`);
4706
4817
  return { ...r };
4707
4818
  }
4708
4819
  async cancel(e, t) {
4709
4820
  let r = this.intents.get(e);
4710
4821
  if (!r)
4711
- throw new c("not_found", `Mock intent ${e} not found`);
4822
+ throw new l("not_found", `Mock intent ${e} not found`);
4712
4823
  let o = r.status === "cancelled";
4713
4824
  return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: o };
4714
4825
  }
4715
4826
  };
4716
- function Xt(n) {
4717
- return n.env === "dev" ? new He() : Hr(n);
4827
+ function dn(n) {
4828
+ return n.env === "dev" ? new Ze() : mo(n);
4718
4829
  }
4719
4830
 
4720
4831
  // src/webhooks.ts
4721
- P();
4722
- U();
4723
- var Zt = [
4832
+ I();
4833
+ M();
4834
+ var pn = [
4724
4835
  "subscription.activated",
4725
4836
  "subscription.cancelled",
4726
4837
  "subscription.payment_failed",
@@ -4730,17 +4841,17 @@ var Zt = [
4730
4841
  "account.reactivated",
4731
4842
  "support.ticket_replied"
4732
4843
  ];
4733
- function Yt(n) {
4844
+ function un(n) {
4734
4845
  if (!n || typeof n != "object")
4735
- throw new c("invalid_response", "Webhook response is not an object");
4846
+ throw new l("invalid_response", "Webhook response is not an object");
4736
4847
  let e = n;
4737
4848
  if (typeof e.id != "string")
4738
- throw new c("invalid_response", "Webhook missing id");
4849
+ throw new l("invalid_response", "Webhook missing id");
4739
4850
  return {
4740
4851
  id: e.id,
4741
4852
  url: typeof e.url == "string" ? e.url : "",
4742
4853
  events: Array.isArray(e.events) ? e.events.filter(
4743
- (t) => Zt.includes(t)
4854
+ (t) => pn.includes(t)
4744
4855
  ) : [],
4745
4856
  hasSecret: e.hasSecret === true,
4746
4857
  status: e.status === "active" || e.status === "degraded" || e.status === "disabled" ? e.status : "active",
@@ -4749,40 +4860,40 @@ function Yt(n) {
4749
4860
  createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString()
4750
4861
  };
4751
4862
  }
4752
- function en(n) {
4863
+ function fn(n) {
4753
4864
  if (!n.url || typeof n.url != "string")
4754
- throw new c("validation_failed", "url \xE9 obrigat\xF3ria");
4865
+ throw new l("validation_failed", "url \xE9 obrigat\xF3ria");
4755
4866
  try {
4756
4867
  let e = new URL(n.url);
4757
4868
  if (e.protocol !== "https:" && e.protocol !== "http:")
4758
4869
  throw new Error("invalid protocol");
4759
4870
  } catch {
4760
- throw new c("validation_failed", `url inv\xE1lida: ${n.url}`);
4871
+ throw new l("validation_failed", `url inv\xE1lida: ${n.url}`);
4761
4872
  }
4762
4873
  if (!Array.isArray(n.events) || n.events.length === 0)
4763
- throw new c("validation_failed", "events deve ter pelo menos 1 evento");
4874
+ throw new l("validation_failed", "events deve ter pelo menos 1 evento");
4764
4875
  for (let e of n.events)
4765
- if (!Zt.includes(e))
4766
- throw new c("validation_failed", `evento desconhecido: ${e}`);
4876
+ if (!pn.includes(e))
4877
+ throw new l("validation_failed", `evento desconhecido: ${e}`);
4767
4878
  if (n.secret !== void 0 && n.secret.length < 16)
4768
- throw new c("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4879
+ throw new l("validation_failed", "secret deve ter \u226516 chars (recomendado 32+)");
4769
4880
  }
4770
- function be(n, ...e) {
4881
+ function ke(n, ...e) {
4771
4882
  for (let t of e)
4772
4883
  if (typeof t == "string" && t.length > 0)
4773
- return x("productId", t), t;
4884
+ return N("productId", t), t;
4774
4885
  if (n.productId)
4775
- return x("productId", n.productId), n.productId;
4776
- throw new c(
4886
+ return N("productId", n.productId), n.productId;
4887
+ throw new l(
4777
4888
  "validation_failed",
4778
4889
  "productId required (pass to options/input or set on createNeetruClient)"
4779
4890
  );
4780
4891
  }
4781
- function tn(n) {
4892
+ function mn(n) {
4782
4893
  return {
4783
4894
  async register(e) {
4784
- en(e);
4785
- let t = be(n, e.productId), r = await v(n, {
4895
+ fn(e);
4896
+ let t = ke(n, e.productId), r = await v(n, {
4786
4897
  method: "POST",
4787
4898
  path: "/api/sdk/v1/webhooks",
4788
4899
  body: {
@@ -4798,20 +4909,20 @@ function tn(n) {
4798
4909
  // dedup TTL 24h (mesmo padrão de usage.report/support.createTicket).
4799
4910
  idempotencyKey: true
4800
4911
  });
4801
- return Yt(r);
4912
+ return un(r);
4802
4913
  },
4803
4914
  async list(e) {
4804
- let t = be(n, e?.productId), r = await v(n, {
4915
+ let t = ke(n, e?.productId), r = await v(n, {
4805
4916
  method: "GET",
4806
4917
  path: "/api/sdk/v1/webhooks",
4807
4918
  query: { productId: t },
4808
4919
  requireAuth: true
4809
4920
  });
4810
- return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(Yt);
4921
+ return (Array.isArray(r?.endpoints) ? r.endpoints : []).map(un);
4811
4922
  },
4812
4923
  async unregister(e, t) {
4813
- if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4814
- let r = be(n, t?.productId);
4924
+ if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
4925
+ let r = ke(n, t?.productId);
4815
4926
  return await v(n, {
4816
4927
  method: "DELETE",
4817
4928
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}`,
@@ -4820,8 +4931,8 @@ function tn(n) {
4820
4931
  }), { ok: true };
4821
4932
  },
4822
4933
  async test(e, t) {
4823
- if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4824
- let r = be(n, t?.productId), o = await v(n, {
4934
+ if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
4935
+ let r = ke(n, t?.productId), o = await v(n, {
4825
4936
  method: "POST",
4826
4937
  path: `/api/sdk/v1/webhooks/${encodeURIComponent(e)}/test`,
4827
4938
  query: { productId: r },
@@ -4840,11 +4951,11 @@ function tn(n) {
4840
4951
  }
4841
4952
  };
4842
4953
  }
4843
- var ve = class {
4954
+ var Se = class {
4844
4955
  endpoints = /* @__PURE__ */ new Map();
4845
4956
  nextId = 1;
4846
4957
  async register(e) {
4847
- en(e);
4958
+ fn(e);
4848
4959
  let t = `mock_wh_${this.nextId++}`, r = {
4849
4960
  id: t,
4850
4961
  url: e.url,
@@ -4860,32 +4971,32 @@ var ve = class {
4860
4971
  }
4861
4972
  async unregister(e, t) {
4862
4973
  if (!this.endpoints.has(e))
4863
- throw new c("not_found", `Webhook ${e} n\xE3o encontrado`);
4974
+ throw new l("not_found", `Webhook ${e} n\xE3o encontrado`);
4864
4975
  return this.endpoints.delete(e), { ok: true };
4865
4976
  }
4866
4977
  async test(e, t) {
4867
4978
  if (!this.endpoints.has(e))
4868
- throw new c("not_found", `Webhook ${e} n\xE3o encontrado`);
4979
+ throw new l("not_found", `Webhook ${e} n\xE3o encontrado`);
4869
4980
  return { ok: true, statusCode: 200, durationMs: 42 };
4870
4981
  }
4871
4982
  };
4872
4983
 
4873
4984
  // src/notifications.ts
4874
- P();
4875
- U();
4876
- var Qe = [
4985
+ I();
4986
+ M();
4987
+ var et = [
4877
4988
  "info",
4878
4989
  "success",
4879
4990
  "warning",
4880
4991
  "error"
4881
4992
  ];
4882
- function nn(n) {
4993
+ function hn(n) {
4883
4994
  if (!n || typeof n != "object")
4884
- throw new c("invalid_response", "Notification response is not an object");
4995
+ throw new l("invalid_response", "Notification response is not an object");
4885
4996
  let e = n;
4886
4997
  if (typeof e.id != "string")
4887
- throw new c("invalid_response", "Notification missing id");
4888
- let t = Qe.includes(e.severity) ? e.severity : "info";
4998
+ throw new l("invalid_response", "Notification missing id");
4999
+ let t = et.includes(e.severity) ? e.severity : "info";
4889
5000
  return {
4890
5001
  id: e.id,
4891
5002
  userId: typeof e.userId == "string" ? e.userId : "",
@@ -4900,37 +5011,37 @@ function nn(n) {
4900
5011
  dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
4901
5012
  };
4902
5013
  }
4903
- function rn(n) {
4904
- if (!n.userId) throw new c("validation_failed", "userId obrigat\xF3rio");
4905
- if (!n.kind) throw new c("validation_failed", "kind obrigat\xF3rio");
4906
- if (!n.title) throw new c("validation_failed", "title obrigat\xF3rio");
4907
- if (n.severity && !Qe.includes(n.severity))
4908
- throw new c(
5014
+ function gn(n) {
5015
+ if (!n.userId) throw new l("validation_failed", "userId obrigat\xF3rio");
5016
+ if (!n.kind) throw new l("validation_failed", "kind obrigat\xF3rio");
5017
+ if (!n.title) throw new l("validation_failed", "title obrigat\xF3rio");
5018
+ if (n.severity && !et.includes(n.severity))
5019
+ throw new l(
4909
5020
  "validation_failed",
4910
- `severity inv\xE1lida: ${n.severity} (use ${Qe.join("|")})`
5021
+ `severity inv\xE1lida: ${n.severity} (use ${et.join("|")})`
4911
5022
  );
4912
5023
  if (n.title.length > 200)
4913
- throw new c("validation_failed", "title m\xE1x 200 chars");
5024
+ throw new l("validation_failed", "title m\xE1x 200 chars");
4914
5025
  if (n.body && n.body.length > 2e3)
4915
- throw new c("validation_failed", "body m\xE1x 2000 chars");
5026
+ throw new l("validation_failed", "body m\xE1x 2000 chars");
4916
5027
  }
4917
- function we(n, ...e) {
5028
+ function Te(n, ...e) {
4918
5029
  for (let t of e)
4919
5030
  if (typeof t == "string" && t.length > 0)
4920
- return x("productId", t), t;
5031
+ return N("productId", t), t;
4921
5032
  if (n.productId)
4922
- return x("productId", n.productId), n.productId;
4923
- throw new c(
5033
+ return N("productId", n.productId), n.productId;
5034
+ throw new l(
4924
5035
  "validation_failed",
4925
5036
  "productId required (pass to options/input or set on createNeetruClient)"
4926
5037
  );
4927
5038
  }
4928
- function on(n) {
5039
+ function yn(n) {
4929
5040
  return {
4930
5041
  async send(e) {
4931
- rn(e);
5042
+ gn(e);
4932
5043
  let r = {
4933
- productId: we(n, e.productId),
5044
+ productId: Te(n, e.productId),
4934
5045
  userId: e.userId,
4935
5046
  kind: e.kind,
4936
5047
  title: e.title,
@@ -4944,12 +5055,12 @@ function on(n) {
4944
5055
  requireAuth: true,
4945
5056
  idempotencyKey: true
4946
5057
  });
4947
- return nn(o);
5058
+ return hn(o);
4948
5059
  },
4949
5060
  async list(e, t) {
4950
- if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5061
+ if (!e) throw new l("validation_failed", "userId obrigat\xF3rio");
4951
5062
  let o = {
4952
- productId: we(n, t?.productId)
5063
+ productId: Te(n, t?.productId)
4953
5064
  };
4954
5065
  t?.includeDismissed && (o.includeDismissed = true), t?.onlyUnread && (o.onlyUnread = true), t?.limit && (o.limit = Math.min(Math.max(1, t.limit), 200));
4955
5066
  let i = await v(n, {
@@ -4958,11 +5069,11 @@ function on(n) {
4958
5069
  query: o,
4959
5070
  requireAuth: true
4960
5071
  });
4961
- return (Array.isArray(i?.notifications) ? i.notifications : []).map(nn);
5072
+ return (Array.isArray(i?.notifications) ? i.notifications : []).map(hn);
4962
5073
  },
4963
5074
  async markRead(e, t) {
4964
- if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4965
- let r = we(n, t?.productId);
5075
+ if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5076
+ let r = Te(n, t?.productId);
4966
5077
  return await v(n, {
4967
5078
  method: "POST",
4968
5079
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/read`,
@@ -4971,8 +5082,8 @@ function on(n) {
4971
5082
  }), { ok: true };
4972
5083
  },
4973
5084
  async dismiss(e, t) {
4974
- if (!e) throw new c("validation_failed", "id obrigat\xF3rio");
4975
- let r = we(n, t?.productId);
5085
+ if (!e) throw new l("validation_failed", "id obrigat\xF3rio");
5086
+ let r = Te(n, t?.productId);
4976
5087
  return await v(n, {
4977
5088
  method: "POST",
4978
5089
  path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/dismiss`,
@@ -4982,11 +5093,11 @@ function on(n) {
4982
5093
  }
4983
5094
  };
4984
5095
  }
4985
- var ke = class {
5096
+ var Re = class {
4986
5097
  notifications = /* @__PURE__ */ new Map();
4987
5098
  nextId = 1;
4988
5099
  async send(e) {
4989
- if (rn(e), e.fingerprint) {
5100
+ if (gn(e), e.fingerprint) {
4990
5101
  let o = Date.now() - 864e5;
4991
5102
  for (let i of this.notifications.values())
4992
5103
  if ((i.metadata ?? {}).fingerprint === e.fingerprint && i.userId === e.userId && new Date(i.createdAt).getTime() > o)
@@ -5006,60 +5117,61 @@ var ke = class {
5006
5117
  return this.notifications.set(t, r), r;
5007
5118
  }
5008
5119
  async list(e, t) {
5009
- if (!e) throw new c("validation_failed", "userId obrigat\xF3rio");
5120
+ if (!e) throw new l("validation_failed", "userId obrigat\xF3rio");
5010
5121
  let r = Math.min(Math.max(1, t?.limit ?? 50), 200);
5011
5122
  return [...this.notifications.values()].filter((o) => o.userId === e).filter((o) => t?.includeDismissed || !o.dismissedAt).filter((o) => !t?.onlyUnread || !o.readAt).sort((o, i) => i.createdAt.localeCompare(o.createdAt)).slice(0, r);
5012
5123
  }
5013
5124
  async markRead(e, t) {
5014
5125
  let r = this.notifications.get(e);
5015
- if (!r) throw new c("not_found", `Notification ${e} n\xE3o encontrada`);
5126
+ if (!r) throw new l("not_found", `Notification ${e} n\xE3o encontrada`);
5016
5127
  return r.readAt || (r.readAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, r)), { ok: true };
5017
5128
  }
5018
5129
  async dismiss(e, t) {
5019
5130
  let r = this.notifications.get(e);
5020
- if (!r) throw new c("not_found", `Notification ${e} n\xE3o encontrada`);
5131
+ if (!r) throw new l("not_found", `Notification ${e} n\xE3o encontrada`);
5021
5132
  return r.dismissedAt || (r.dismissedAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, r)), { ok: true };
5022
5133
  }
5023
5134
  };
5024
5135
 
5025
5136
  // 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) {
5030
- throw new c("validation_failed", n);
5031
- }
5032
- function to(n) {
5137
+ I();
5138
+ M();
5139
+ Me();
5140
+ var ho = "/api/sdk/v1/ai/chat", _n = 12e4, Ie = 32768, bn = 32, vn = 4194304, wn = 2048, go = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, yo = /^https:\/\/[^\s]+$/, _o = /* @__PURE__ */ new Set(["low", "high", "auto"]), bo = /* @__PURE__ */ new Set(["system", "user", "assistant"]), kn = 100, Sn = 128, Tn = 32768, Rn = 0, In = 2, Cn = 200, An = 20, En = 12 * 1024 * 1024, Pn = 5e4, Dn = 16, Nn = 500, vo = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), wo = /^[a-zA-Z0-9_-]+$/;
5141
+ function k(n) {
5142
+ throw new l("validation_failed", n);
5143
+ }
5144
+ function ko(n) {
5033
5145
  if (n.length === 0 || n.length % 4 !== 0) return false;
5034
5146
  let e = n.endsWith("==") ? 2 : n.endsWith("=") ? 1 : 0;
5035
5147
  return !(e > 0 ? n.slice(0, n.length - e) : n).includes("=");
5036
5148
  }
5037
- function no(n) {
5149
+ function So(n) {
5038
5150
  let e = n.indexOf(",");
5039
5151
  if (e === -1) return 0;
5040
5152
  let t = n.slice(e + 1), r = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
5041
5153
  return Math.max(0, Math.floor(t.length * 3 / 4) - r);
5042
5154
  }
5043
- function ro(n) {
5155
+ function To(n) {
5044
5156
  let e = 0, t = 0, r = 0;
5045
5157
  for (let o of n) {
5046
5158
  let i = o?.content;
5047
5159
  if (Array.isArray(i))
5048
5160
  for (let s of i) {
5049
- if (e++, e > hn)
5050
- return `ai: total content parts exceeds ${hn} per request`;
5161
+ if (e++, e > Cn)
5162
+ return `ai: total content parts exceeds ${Cn} per request`;
5051
5163
  if (s && typeof s == "object" && s.type === "image_url") {
5052
- if (t++, t > gn)
5053
- return `ai: total images exceeds ${gn} per request`;
5164
+ if (t++, t > An)
5165
+ return `ai: total images exceeds ${An} per request`;
5054
5166
  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`;
5167
+ if (typeof a == "string" && a.startsWith("data:") && (r += So(a), r > En))
5168
+ return `ai: aggregate image bytes exceeds ${En} per request`;
5057
5169
  }
5058
5170
  }
5059
5171
  }
5060
5172
  return null;
5061
5173
  }
5062
- function oo(n) {
5174
+ function Ro(n) {
5063
5175
  if (n === void 0) return null;
5064
5176
  if (n === null || typeof n != "object")
5065
5177
  return "ai: responseFormat json_schema.schema must be an object";
@@ -5070,11 +5182,11 @@ function oo(n) {
5070
5182
  return "ai: responseFormat json_schema.schema is not serializable";
5071
5183
  }
5072
5184
  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`;
5185
+ if (e.length > Pn)
5186
+ return `ai: responseFormat json_schema.schema exceeds ${Pn} serialized chars`;
5075
5187
  let t = 0, r = (o, i) => {
5076
- if (i > bn)
5077
- return `ai: responseFormat json_schema.schema exceeds max depth ${bn}`;
5188
+ if (i > Dn)
5189
+ return `ai: responseFormat json_schema.schema exceeds max depth ${Dn}`;
5078
5190
  if (Array.isArray(o)) {
5079
5191
  for (let s of o) {
5080
5192
  let a = r(s, i + 1);
@@ -5084,10 +5196,10 @@ function oo(n) {
5084
5196
  }
5085
5197
  if (o && typeof o == "object")
5086
5198
  for (let s of Object.getOwnPropertyNames(o)) {
5087
- if (Zr.has(s))
5199
+ if (vo.has(s))
5088
5200
  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`;
5201
+ if (t++, t > Nn)
5202
+ return `ai: responseFormat json_schema.schema exceeds ${Nn} keys`;
5091
5203
  let a = r(o[s], i + 1);
5092
5204
  if (a) return a;
5093
5205
  }
@@ -5095,93 +5207,93 @@ function oo(n) {
5095
5207
  };
5096
5208
  return r(n, 0);
5097
5209
  }
5098
- function io(n) {
5099
- (typeof n != "string" || n.length === 0) && w("ai: image_url.url must be a non-empty string");
5210
+ function Io(n) {
5211
+ (typeof n != "string" || n.length === 0) && k("ai: image_url.url must be a non-empty string");
5100
5212
  let e = n;
5101
5213
  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,<...>");
5214
+ e.length > vn && k(`ai: image_url.url (data:) exceeds ${vn} chars`), go.test(e) || k("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
5103
5215
  let t = e.slice(e.indexOf(",") + 1);
5104
- to(t) || w("ai: image_url.url data: has invalid base64 (length/padding)");
5216
+ ko(t) || k("ai: image_url.url data: has invalid base64 (length/padding)");
5105
5217
  return;
5106
5218
  }
5107
5219
  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");
5220
+ e.length > wn && k(`ai: image_url.url (https:) exceeds ${wn} chars`), yo.test(e) || k("ai: image_url.url https: is invalid");
5109
5221
  return;
5110
5222
  }
5111
- w("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5223
+ k("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
5112
5224
  }
5113
- function so(n, e) {
5225
+ function Co(n, e) {
5114
5226
  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`);
5227
+ n.length === 0 && k("ai: message content string must be non-empty"), n.length > Ie && k(`ai: message content exceeds ${Ie} chars`);
5116
5228
  return;
5117
5229
  }
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`);
5230
+ (!Array.isArray(n) || n.length === 0) && k("ai: message content must be a non-empty string or array of parts"), n.length > bn && k(`ai: message content has more than ${bn} parts`);
5119
5231
  for (let t of n) {
5120
- (!t || typeof t != "object") && w("ai: each content part must be an object");
5232
+ (!t || typeof t != "object") && k("ai: each content part must be an object");
5121
5233
  let r = t.type;
5122
5234
  if (r === "text") {
5123
5235
  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`);
5236
+ (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
5237
  } else if (r === "image_url") {
5126
- e !== "user" && w(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5238
+ e !== "user" && k(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
5127
5239
  let o = t.image_url;
5128
- (!o || typeof o != "object") && w("ai: image_url part must have { image_url: { url } }"), io(o.url);
5240
+ (!o || typeof o != "object") && k("ai: image_url part must have { image_url: { url } }"), Io(o.url);
5129
5241
  let i = o.detail;
5130
- i !== void 0 && (typeof i != "string" || !Xr.has(i)) && w("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5242
+ i !== void 0 && (typeof i != "string" || !_o.has(i)) && k("ai: image_url.detail must be 'low' | 'high' | 'auto'");
5131
5243
  } else
5132
- w("ai: content part type must be 'text' or 'image_url'");
5244
+ k("ai: content part type must be 'text' or 'image_url'");
5133
5245
  }
5134
5246
  }
5135
- function ao(n) {
5136
- (!n || typeof n != "object") && w("ai: responseFormat must be an object");
5247
+ function Ao(n) {
5248
+ (!n || typeof n != "object") && k("ai: responseFormat must be an object");
5137
5249
  let e = n.type;
5138
5250
  if (!(e === "text" || e === "json_object")) {
5139
5251
  if (e === "json_schema") {
5140
5252
  let t = n.json_schema;
5141
- (!t || typeof t != "object") && w("ai: responseFormat json_schema requires { json_schema: { name } }");
5253
+ (!t || typeof t != "object") && k("ai: responseFormat json_schema requires { json_schema: { name } }");
5142
5254
  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);
5255
+ 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"), wo.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) {
5256
+ let i = Ro(r.schema);
5257
+ i && k(i);
5146
5258
  }
5147
5259
  return;
5148
5260
  }
5149
- w("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5261
+ k("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
5150
5262
  }
5151
5263
  }
5152
- function wn(n, e, t) {
5264
+ function xn(n, e, t) {
5153
5265
  if (!e || typeof e != "object")
5154
- throw new c("validation_failed", "ai: options object is required");
5266
+ throw new l("validation_failed", "ai: options object is required");
5155
5267
  if (typeof e.model != "string" || e.model.length === 0)
5156
- 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`);
5268
+ throw new l("validation_failed", "ai: model is required");
5269
+ if (e.model.length > Sn)
5270
+ throw new l("validation_failed", `ai: model exceeds ${Sn} chars`);
5159
5271
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5160
- 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`);
5272
+ throw new l("validation_failed", "ai: messages must be a non-empty array");
5273
+ if (e.messages.length > kn)
5274
+ throw new l("validation_failed", `ai: messages exceeds ${kn} per request`);
5163
5275
  for (let a of e.messages) {
5164
- if (!a || typeof a != "object" || typeof a.role != "string" || !Yr.has(a.role))
5165
- throw new c(
5276
+ if (!a || typeof a != "object" || typeof a.role != "string" || !bo.has(a.role))
5277
+ throw new l(
5166
5278
  "validation_failed",
5167
5279
  "ai: each message role must be 'system' | 'user' | 'assistant'"
5168
5280
  );
5169
- so(a.content, a.role);
5281
+ Co(a.content, a.role);
5170
5282
  }
5171
- let r = ro(e.messages);
5172
- if (r) throw new c("validation_failed", r);
5283
+ let r = To(e.messages);
5284
+ if (r) throw new l("validation_failed", r);
5173
5285
  let o = e.productId ?? n.productId, i = e.tenantId ?? n.tenantId;
5174
5286
  if (!o)
5175
- throw new c(
5287
+ throw new l(
5176
5288
  "validation_failed",
5177
5289
  "ai: productId required (pass to options or set on createNeetruClient)"
5178
5290
  );
5179
5291
  if (!i)
5180
- throw new c(
5292
+ throw new l(
5181
5293
  "validation_failed",
5182
5294
  "ai: tenantId required (pass to options or set on createNeetruClient)"
5183
5295
  );
5184
- x("productId", o), x("tenantId", i);
5296
+ N("productId", o), N("tenantId", i);
5185
5297
  let s = {
5186
5298
  productId: o,
5187
5299
  tenantId: i,
@@ -5190,24 +5302,24 @@ function wn(n, e, t) {
5190
5302
  stream: t
5191
5303
  };
5192
5304
  if (e.maxTokens !== void 0) {
5193
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > pn)
5194
- throw new c(
5305
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > Tn)
5306
+ throw new l(
5195
5307
  "validation_failed",
5196
- `ai: maxTokens must be a positive integer <= ${pn}`
5308
+ `ai: maxTokens must be a positive integer <= ${Tn}`
5197
5309
  );
5198
5310
  s.maxTokens = e.maxTokens;
5199
5311
  }
5200
5312
  if (e.temperature !== void 0) {
5201
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < fn || e.temperature > mn)
5202
- throw new c(
5313
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < Rn || e.temperature > In)
5314
+ throw new l(
5203
5315
  "validation_failed",
5204
- `ai: temperature must be a finite number between ${fn} and ${mn}`
5316
+ `ai: temperature must be a finite number between ${Rn} and ${In}`
5205
5317
  );
5206
5318
  s.temperature = e.temperature;
5207
5319
  }
5208
- return e.responseFormat !== void 0 && (ao(e.responseFormat), s.responseFormat = e.responseFormat), s;
5320
+ return e.responseFormat !== void 0 && (Ao(e.responseFormat), s.responseFormat = e.responseFormat), s;
5209
5321
  }
5210
- async function Rn(n) {
5322
+ async function Mn(n) {
5211
5323
  try {
5212
5324
  let e = await n.text();
5213
5325
  return e ? JSON.parse(e) : void 0;
@@ -5215,48 +5327,48 @@ async function Rn(n) {
5215
5327
  return;
5216
5328
  }
5217
5329
  }
5218
- function co(n, e) {
5330
+ function Eo(n, e) {
5219
5331
  let t = n.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
5220
5332
  return `${t}${r}`;
5221
5333
  }
5222
- async function kn(n, e, t, r) {
5334
+ async function On(n, e, t, r) {
5223
5335
  if (!n.apiKey)
5224
- throw new c(
5336
+ throw new l(
5225
5337
  "missing_api_key",
5226
5338
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
5227
5339
  );
5228
- let o = co(n.baseUrl, Qr), s = { method: "POST", headers: {
5340
+ let o = Eo(n.baseUrl, ho), { headers: i, correlationId: s } = ae({
5229
5341
  "content-type": "application/json",
5230
5342
  accept: r ? "text/event-stream" : "application/json",
5231
5343
  authorization: `Bearer ${n.apiKey}`
5232
- }, body: JSON.stringify(e) };
5233
- r ? t && (s.signal = t) : s.signal = t ?? AbortSignal.timeout(sn);
5234
- let a;
5344
+ }), a = { method: "POST", headers: i, body: JSON.stringify(e) };
5345
+ r ? t && (a.signal = t) : a.signal = t ?? AbortSignal.timeout(_n);
5346
+ let c;
5235
5347
  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));
5348
+ c = await n.fetch(o, a);
5349
+ } catch (p) {
5350
+ let f = p instanceof DOMException && p.name === "TimeoutError" ? `Network error: timeout after ${_n / 1e3}s` : p instanceof DOMException && p.name === "AbortError" ? "Network error: request aborted" : `Network error: ${p instanceof Error ? p.message : "fetch failed"}`;
5351
+ throw new l("network_error", f, void 0, void 0, void 0, s);
5352
+ }
5353
+ let d = c.headers.get("x-request-id") ?? c.headers.get("x-correlation-id") ?? void 0;
5354
+ if (!c.ok) {
5355
+ let p = await Mn(c), f = le(c.status), _ = `HTTP ${c.status}`;
5356
+ if (p && typeof p == "object" && "error" in p) {
5357
+ let b = p.error;
5358
+ typeof b == "string" ? _ = b : b && typeof b == "object" && (typeof b.code == "string" && (f = b.code), typeof b.message == "string" && (_ = b.message));
5247
5359
  }
5248
- throw new c(p, f, a.status, l);
5360
+ throw new l(f, _, c.status, d, void 0, s);
5249
5361
  }
5250
- let d = a.headers.get("x-neetru-version");
5251
- return d && ie(d), a;
5362
+ let u = c.headers.get("x-neetru-version");
5363
+ return u && ce(u), c;
5252
5364
  }
5253
- function Sn(n) {
5365
+ function Ln(n) {
5254
5366
  return {
5255
5367
  provider: n.headers.get("x-neetru-provider") ?? "",
5256
5368
  usageWarning: n.headers.get("x-neetru-ai-usage-warning") === "1"
5257
5369
  };
5258
5370
  }
5259
- function Tn(n) {
5371
+ function Un(n) {
5260
5372
  let e = [];
5261
5373
  for (let r of n.split(`
5262
5374
  `)) {
@@ -5277,12 +5389,12 @@ function Tn(n) {
5277
5389
  return null;
5278
5390
  }
5279
5391
  }
5280
- function In(n) {
5392
+ function qn(n) {
5281
5393
  return {
5282
5394
  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);
5395
+ let t = xn(n, e, false), r = await On(n, t, e.signal, false), { provider: o, usageWarning: i } = Ln(r), s = await Mn(r);
5284
5396
  if (!s || s.ok !== true || !Array.isArray(s.choices))
5285
- throw new c("invalid_response", "ai.chat response missing ok/choices");
5397
+ throw new l("invalid_response", "ai.chat response missing ok/choices");
5286
5398
  return {
5287
5399
  choices: s.choices,
5288
5400
  usage: s.usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
@@ -5292,38 +5404,38 @@ function In(n) {
5292
5404
  };
5293
5405
  },
5294
5406
  stream(e) {
5295
- let t = wn(n, e, true), r = kn(n, t, e.signal, true), o = r.then(Sn);
5407
+ let t = xn(n, e, true), r = On(n, t, e.signal, true), o = r.then(Ln);
5296
5408
  o.catch(() => {
5297
5409
  });
5298
5410
  async function* i() {
5299
5411
  let a = (await r).body;
5300
5412
  if (!a)
5301
- throw new c("invalid_response", "ai.stream: response has no body");
5302
- let l = a.getReader(), d = new TextDecoder(), u = "";
5413
+ throw new l("invalid_response", "ai.stream: response has no body");
5414
+ let c = a.getReader(), d = new TextDecoder(), u = "";
5303
5415
  try {
5304
5416
  for (; ; ) {
5305
- let { done: f, value: g } = await l.read();
5417
+ let { done: f, value: _ } = await c.read();
5306
5418
  if (f) break;
5307
- u += d.decode(g, { stream: !0 });
5308
- let _;
5309
- for (; (_ = u.indexOf(`
5419
+ u += d.decode(_, { stream: !0 });
5420
+ let b;
5421
+ for (; (b = u.indexOf(`
5310
5422
 
5311
5423
  `)) !== -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);
5424
+ let S = u.slice(0, b);
5425
+ u = u.slice(b + 2);
5426
+ let x = Un(S);
5427
+ if (x && "done" in x) return;
5428
+ x && "content" in x && (yield x.content);
5317
5429
  }
5318
5430
  }
5319
5431
  let p = u.trim();
5320
5432
  if (p) {
5321
- let f = Tn(p);
5433
+ let f = Un(p);
5322
5434
  f && "content" in f && (yield f.content);
5323
5435
  }
5324
5436
  } finally {
5325
5437
  try {
5326
- l.releaseLock();
5438
+ c.releaseLock();
5327
5439
  } catch {
5328
5440
  }
5329
5441
  try {
@@ -5341,10 +5453,10 @@ function In(n) {
5341
5453
  }
5342
5454
 
5343
5455
  // src/mocks.ts
5344
- P();
5456
+ I();
5345
5457
 
5346
5458
  // src/runtime-env.ts
5347
- function Te() {
5459
+ function Ce() {
5348
5460
  try {
5349
5461
  if (typeof process < "u" && process.env)
5350
5462
  return process.env.NODE_ENV === "production";
@@ -5354,20 +5466,20 @@ function Te() {
5354
5466
  }
5355
5467
 
5356
5468
  // src/mocks.ts
5357
- var Ge = Object.freeze({
5469
+ var tt = Object.freeze({
5358
5470
  uid: "dev-fixture-uid-0001",
5359
5471
  email: "dev@neetru.local",
5360
5472
  emailVerified: true,
5361
5473
  displayName: "Dev Fixture",
5362
5474
  isCustomer: true,
5363
5475
  isStaff: false
5364
- }), Re = class {
5476
+ }), Ae = class {
5365
5477
  _user;
5366
5478
  _listeners;
5367
5479
  _allowUnsignedDecode;
5368
5480
  constructor(e = null, t) {
5369
- if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Te())
5370
- throw new c(
5481
+ if (this._user = e, this._listeners = /* @__PURE__ */ new Set(), this._allowUnsignedDecode = t?.allowUnsignedDecode ?? false, this._allowUnsignedDecode && Ce())
5482
+ throw new l(
5371
5483
  "invalid_config",
5372
5484
  "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."
5373
5485
  );
@@ -5376,7 +5488,7 @@ var Ge = Object.freeze({
5376
5488
  );
5377
5489
  }
5378
5490
  async signIn(e) {
5379
- return this._user || (this._user = { ...Ge }), this._notify(), this._user;
5491
+ return this._user || (this._user = { ...tt }), this._notify(), this._user;
5380
5492
  }
5381
5493
  async signOut() {
5382
5494
  this._user = null, this._notify();
@@ -5408,9 +5520,9 @@ var Ge = Object.freeze({
5408
5520
  if (this._verifyTokenOverride)
5409
5521
  return this._verifyTokenOverride(e);
5410
5522
  if (!e)
5411
- throw new c("token_invalid_signature", "Token inv\xE1lido: string vazia");
5523
+ throw new l("token_invalid_signature", "Token inv\xE1lido: string vazia");
5412
5524
  if (!this._allowUnsignedDecode)
5413
- throw new c(
5525
+ throw new l(
5414
5526
  "unauthorized",
5415
5527
  "MockAuth.verifyToken n\xE3o verifica assinaturas JWT e N\xC3O deve ser usado como security boundary em c\xF3digo deployado. Em testes, use new MockAuth(user, { allowUnsignedDecode: true }) para habilitar decodifica\xE7\xE3o sem assinatura, ou __mockVerifyToken(fn) para injetar resultado customizado."
5416
5528
  );
@@ -5436,7 +5548,7 @@ var Ge = Object.freeze({
5436
5548
  } catch {
5437
5549
  }
5438
5550
  if (this._user) return this._user;
5439
- throw new c("token_invalid_signature", "Nenhum user mock dispon\xEDvel e JWT sem sub v\xE1lido");
5551
+ throw new l("token_invalid_signature", "Nenhum user mock dispon\xEDvel e JWT sem sub v\xE1lido");
5440
5552
  }
5441
5553
  /**
5442
5554
  * Mock de `handleRedirectCallback` (Bug 2 / 3.1.3) — não há redirect real no
@@ -5497,7 +5609,7 @@ var Ge = Object.freeze({
5497
5609
  } catch {
5498
5610
  }
5499
5611
  }
5500
- }, Ie = class {
5612
+ }, Ee = class {
5501
5613
  _reports = [];
5502
5614
  _quotas;
5503
5615
  _counters = /* @__PURE__ */ new Map();
@@ -5514,14 +5626,14 @@ var Ge = Object.freeze({
5514
5626
  tenantId: r?.tenantId,
5515
5627
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
5516
5628
  });
5517
- let l = this._quotas.get(e)?.limit ?? -1;
5629
+ let c = this._quotas.get(e)?.limit ?? -1;
5518
5630
  return {
5519
5631
  ok: true,
5520
5632
  counterId: `mock_${e}`,
5521
5633
  value: s,
5522
- limit: l,
5523
- remaining: l < 0 ? -1 : Math.max(0, l - s),
5524
- status: l > 0 && s >= l ? "read_only_overlimit" : "ok"
5634
+ limit: c,
5635
+ remaining: c < 0 ? -1 : Math.max(0, c - s),
5636
+ status: c > 0 && s >= c ? "read_only_overlimit" : "ok"
5525
5637
  };
5526
5638
  }
5527
5639
  async check(e, t) {
@@ -5559,14 +5671,14 @@ var Ge = Object.freeze({
5559
5671
  __reset() {
5560
5672
  this._reports = [], this._quotas.clear(), this._counters.clear();
5561
5673
  }
5562
- }, Ce = class {
5674
+ }, Pe = class {
5563
5675
  _tickets = [];
5564
5676
  _ticketSeq = 0;
5565
5677
  async createTicket(e) {
5566
- if (!e?.subject) throw new c("validation_failed", "subject required");
5567
- if (!e?.message) throw new c("validation_failed", "message required");
5678
+ if (!e?.subject) throw new l("validation_failed", "subject required");
5679
+ if (!e?.message) throw new l("validation_failed", "message required");
5568
5680
  if (!e?.productSlug)
5569
- throw new c(
5681
+ throw new l(
5570
5682
  "validation_failed",
5571
5683
  "productSlug required (3.0 breaking \u2014 pass to input or set on createNeetruClient)"
5572
5684
  );
@@ -5598,10 +5710,10 @@ var Ge = Object.freeze({
5598
5710
  }
5599
5711
  _find(e) {
5600
5712
  if (!e || typeof e != "string")
5601
- throw new c("validation_failed", "ticketId is required");
5713
+ throw new l("validation_failed", "ticketId is required");
5602
5714
  let t = this._tickets.find((r) => r.id === e);
5603
5715
  if (!t)
5604
- throw new c("not_found", `ticket ${e} not found`);
5716
+ throw new l("not_found", `ticket ${e} not found`);
5605
5717
  return t;
5606
5718
  }
5607
5719
  /** 3.4: espelha `markResolvedSeen` — idempotente (só seta se ainda null). */
@@ -5617,18 +5729,18 @@ var Ge = Object.freeze({
5617
5729
  /** 3.4: espelha `submitSatisfaction` — terminal, seta `satisfiedAt`. */
5618
5730
  async submitSatisfaction(e) {
5619
5731
  if (!e || typeof e != "object")
5620
- throw new c("validation_failed", "input is required");
5732
+ throw new l("validation_failed", "input is required");
5621
5733
  if (e.rating !== null && e.rating !== void 0 && (!Number.isInteger(e.rating) || e.rating < 1 || e.rating > 5))
5622
- throw new c("validation_failed", "rating must be an integer 1-5 or null");
5734
+ throw new l("validation_failed", "rating must be an integer 1-5 or null");
5623
5735
  if (typeof e.comment == "string" && e.comment.length > 2e3)
5624
- throw new c("validation_failed", "comment max 2000 chars");
5736
+ throw new l("validation_failed", "comment max 2000 chars");
5625
5737
  let t = this._find(e.ticketId);
5626
5738
  t.satisfiedAt = (/* @__PURE__ */ new Date()).toISOString(), t.rating = e.rating ?? null, t.satisfactionComment = e.comment ?? null;
5627
5739
  }
5628
5740
  /** 3.4: espelha `contestTicket` — reabre e zera o ciclo de satisfação. */
5629
5741
  async contestTicket(e, t) {
5630
5742
  if (typeof t?.comment == "string" && t.comment.length > 2e3)
5631
- throw new c("validation_failed", "comment max 2000 chars");
5743
+ throw new l("validation_failed", "comment max 2000 chars");
5632
5744
  let r = this._find(e);
5633
5745
  r.status = "open", r.resolvedAt = null, r.resolvedNotifiedAt = null, r.satisfactionAttempts = 0, r.lastSatisfactionAttemptAt = null, r.satisfiedAt = null, r.rating = null, r.satisfactionComment = null;
5634
5746
  }
@@ -5636,7 +5748,7 @@ var Ge = Object.freeze({
5636
5748
  __reset() {
5637
5749
  this._tickets = [], this._ticketSeq = 0;
5638
5750
  }
5639
- }, Ae = class {
5751
+ }, De = class {
5640
5752
  _denied = /* @__PURE__ */ new Set();
5641
5753
  async check(e, t) {
5642
5754
  return !this._denied.has(`${e}:${t}`);
@@ -5659,7 +5771,7 @@ var Ge = Object.freeze({
5659
5771
  this._denied.clear();
5660
5772
  }
5661
5773
  };
5662
- var Pe = class {
5774
+ var Ne = class {
5663
5775
  _calls = [];
5664
5776
  /** Extrai texto de um content string OU array multimodal (imagens ignoradas). */
5665
5777
  _contentToText(e) {
@@ -5671,9 +5783,9 @@ var Pe = class {
5671
5783
  }
5672
5784
  async chat(e) {
5673
5785
  if (!e || typeof e.model != "string" || e.model.length === 0)
5674
- throw new c("validation_failed", "ai: model is required");
5786
+ throw new l("validation_failed", "ai: model is required");
5675
5787
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5676
- throw new c("validation_failed", "ai: messages must be a non-empty array");
5788
+ throw new l("validation_failed", "ai: messages must be a non-empty array");
5677
5789
  this._calls.push({ model: e.model, messages: e.messages, stream: false });
5678
5790
  let t = this._reply(e), r = e.messages.reduce((i, s) => i + this._contentToText(s.content).length, 0), o = t.length;
5679
5791
  return {
@@ -5690,9 +5802,9 @@ var Pe = class {
5690
5802
  }
5691
5803
  stream(e) {
5692
5804
  if (!e || typeof e.model != "string" || e.model.length === 0)
5693
- throw new c("validation_failed", "ai: model is required");
5805
+ throw new l("validation_failed", "ai: model is required");
5694
5806
  if (!Array.isArray(e.messages) || e.messages.length === 0)
5695
- throw new c("validation_failed", "ai: messages must be a non-empty array");
5807
+ throw new l("validation_failed", "ai: messages must be a non-empty array");
5696
5808
  this._calls.push({ model: e.model, messages: e.messages, stream: true });
5697
5809
  let t = this._reply(e), r = t.match(/\S+\s*/g) ?? [t], o = Promise.resolve({ provider: "mock", usageWarning: false });
5698
5810
  async function* i() {
@@ -5707,46 +5819,46 @@ var Pe = class {
5707
5819
  };
5708
5820
 
5709
5821
  // src/auth-pkce-shared.ts
5710
- P();
5711
- function Cn() {
5822
+ I();
5823
+ function Fn() {
5712
5824
  let n = globalThis.crypto;
5713
5825
  if (!n || typeof n.getRandomValues != "function" || !n.subtle)
5714
- throw new c(
5826
+ throw new l(
5715
5827
  "runtime_unsupported",
5716
5828
  "auth.signIn requer WebCrypto (crypto.subtle) \u2014 indispon\xEDvel neste runtime. Use HTTPS (ou http://localhost) num browser moderno, ou instale um polyfill WebCrypto (ex: react-native-quick-crypto) em React Native."
5717
5829
  );
5718
5830
  return n;
5719
5831
  }
5720
- function An(n) {
5832
+ function jn(n) {
5721
5833
  let e = "";
5722
5834
  for (let r of n) e += String.fromCharCode(r);
5723
5835
  return (typeof btoa == "function" ? btoa(e) : Buffer.from(e, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
5724
5836
  }
5725
- function Ee(n, e) {
5837
+ function xe(n, e) {
5726
5838
  let t = new Uint8Array(e);
5727
- return n.getRandomValues(t), An(t);
5839
+ return n.getRandomValues(t), jn(t);
5728
5840
  }
5729
- async function Pn(n, e) {
5841
+ async function $n(n, e) {
5730
5842
  let t = new TextEncoder().encode(e), r = await n.subtle.digest("SHA-256", t);
5731
- return An(new Uint8Array(r));
5843
+ return jn(new Uint8Array(r));
5732
5844
  }
5733
- function De(n) {
5845
+ function oe(n) {
5734
5846
  return (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.replace(/^https?:\/\/api\./, "https://auth.");
5735
5847
  }
5736
- function En(n) {
5848
+ function Wn(n) {
5737
5849
  let e = n.oidcClientId;
5738
- if (!e && n.apiKey && (e = tt(n.apiKey).keyId), !e)
5739
- throw new c(
5850
+ if (!e && n.apiKey && (e = ct(n.apiKey).keyId), !e)
5851
+ throw new l(
5740
5852
  "invalid_config",
5741
5853
  "auth OIDC requer `oidcClientId` (ou `apiKey`) configurado para montar o client_id."
5742
5854
  );
5743
5855
  return e;
5744
5856
  }
5745
- function Dn(n) {
5857
+ function Bn(n) {
5746
5858
  let e = new URL("/api/v1/oauth/authorize", n.idpOrigin);
5747
5859
  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
5860
  }
5749
- function Je(n) {
5861
+ function nt(n) {
5750
5862
  let e = n.split(".");
5751
5863
  if (e.length !== 3) return null;
5752
5864
  try {
@@ -5756,8 +5868,8 @@ function Je(n) {
5756
5868
  return null;
5757
5869
  }
5758
5870
  }
5759
- function re(n) {
5760
- let e = Je(n);
5871
+ function ie(n) {
5872
+ let e = nt(n);
5761
5873
  return !e || typeof e.sub != "string" || typeof e.exp == "number" && e.exp * 1e3 < Date.now() ? null : {
5762
5874
  uid: e.sub,
5763
5875
  email: typeof e.email == "string" ? e.email : "",
@@ -5770,9 +5882,68 @@ function re(n) {
5770
5882
  ...e
5771
5883
  };
5772
5884
  }
5885
+ var Po = "/api/v1/oauth/revoke";
5886
+ async function Vn(n, e, t, r) {
5887
+ let o = `${e}${Po}`, i = true;
5888
+ for (let s of r) {
5889
+ if (!s.token) continue;
5890
+ let a = new URLSearchParams({
5891
+ token: s.token,
5892
+ token_type_hint: s.hint,
5893
+ client_id: t
5894
+ }).toString(), c = false;
5895
+ for (let d = 0; d < 2 && !c; d++)
5896
+ try {
5897
+ if (c = (await n(o, {
5898
+ method: "POST",
5899
+ headers: { "content-type": "application/x-www-form-urlencoded" },
5900
+ body: a
5901
+ })).ok, !c) break;
5902
+ } catch {
5903
+ d === 0 && await new Promise((u) => setTimeout(u, 500));
5904
+ }
5905
+ c || (i = false);
5906
+ }
5907
+ return i;
5908
+ }
5773
5909
 
5774
5910
  // src/auth.ts
5775
- function po() {
5911
+ qe();
5912
+
5913
+ // src/end-user-token.ts
5914
+ var Do = /* @__PURE__ */ new WeakMap();
5915
+ function Kn(n, e) {
5916
+ Do.set(n, e);
5917
+ }
5918
+
5919
+ // src/unsupported-db.ts
5920
+ I();
5921
+ var No = "[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.)", xo = /* @__PURE__ */ new Set([
5922
+ "then",
5923
+ "toJSON",
5924
+ "valueOf",
5925
+ "constructor",
5926
+ "$$typeof",
5927
+ "asymmetricMatch",
5928
+ "nodeType"
5929
+ ]);
5930
+ function zn() {
5931
+ let n = () => {
5932
+ throw new l("runtime_unsupported", No, void 0, void 0, "react-native");
5933
+ }, e = {};
5934
+ return new Proxy(e, {
5935
+ get(t, r) {
5936
+ if (!(typeof r == "symbol" || xo.has(r)))
5937
+ return r === "toString" ? () => "[NeetruDb indispon\xEDvel em React Native]" : n;
5938
+ },
5939
+ set() {
5940
+ return n(), false;
5941
+ }
5942
+ });
5943
+ }
5944
+
5945
+ // src/auth.ts
5946
+ function Lo() {
5776
5947
  try {
5777
5948
  let e = globalThis.process?.env?.NEETRU_API_KEY;
5778
5949
  return typeof e == "string" && e.length > 0 ? e : void 0;
@@ -5780,7 +5951,7 @@ function po() {
5780
5951
  return;
5781
5952
  }
5782
5953
  }
5783
- function fo(n) {
5954
+ function Uo(n) {
5784
5955
  if (n) return n;
5785
5956
  try {
5786
5957
  let t = globalThis.process?.env?.NEETRU_ENV;
@@ -5794,18 +5965,11 @@ function fo(n) {
5794
5965
  }
5795
5966
  return "prod";
5796
5967
  }
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();
5968
+ var Mo = it;
5969
+ function ra() {
5970
+ st();
5807
5971
  }
5808
- function go(n) {
5972
+ function qo(n) {
5809
5973
  let e = n.sub ?? "", t = typeof n.email == "string" ? n.email : "";
5810
5974
  return {
5811
5975
  uid: e,
@@ -5820,8 +5984,8 @@ function go(n) {
5820
5984
  ...n
5821
5985
  };
5822
5986
  }
5823
- var oe = "neetru_oauth_tx";
5824
- function Xe(n) {
5987
+ var se = "neetru_oauth_tx";
5988
+ function rt(n) {
5825
5989
  try {
5826
5990
  let e = globalThis.history;
5827
5991
  if (!e || typeof e.replaceState != "function") return;
@@ -5832,7 +5996,7 @@ function Xe(n) {
5832
5996
  } catch {
5833
5997
  }
5834
5998
  }
5835
- function yo(n) {
5999
+ function Fo(n) {
5836
6000
  let e = "neetru_id_token", t = "neetru_refresh_token", r = /* @__PURE__ */ new Set(), o = null, i = null, s = null;
5837
6001
  function a() {
5838
6002
  try {
@@ -5841,7 +6005,7 @@ function yo(n) {
5841
6005
  return null;
5842
6006
  }
5843
6007
  }
5844
- function l() {
6008
+ function c() {
5845
6009
  try {
5846
6010
  return typeof globalThis.sessionStorage < "u" ? globalThis.sessionStorage : null;
5847
6011
  } catch {
@@ -5850,21 +6014,21 @@ function yo(n) {
5850
6014
  }
5851
6015
  function d() {
5852
6016
  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;
6017
+ let h = o.exp;
6018
+ return typeof h == "number" && h * 1e3 < Date.now() ? (o = null, a()?.removeItem(e), u(), S(), null) : o;
5855
6019
  }
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);
6020
+ let m = a();
6021
+ if (!m) return null;
6022
+ let g = m.getItem(e);
6023
+ if (!g)
6024
+ return S(), null;
6025
+ let w = ie(g);
6026
+ return w ? (o = w, x(w), o) : (m.removeItem(e), S(), null);
5863
6027
  }
5864
6028
  function u() {
5865
- for (let h of r)
6029
+ for (let m of r)
5866
6030
  try {
5867
- h(o);
6031
+ m(o);
5868
6032
  } catch {
5869
6033
  }
5870
6034
  }
@@ -5874,297 +6038,296 @@ function yo(n) {
5874
6038
  function f() {
5875
6039
  return a()?.getItem(t) ?? null;
5876
6040
  }
5877
- function g() {
6041
+ function _() {
5878
6042
  o = null;
5879
- let h = a();
5880
- h?.removeItem(e), h?.removeItem(t), u();
6043
+ let m = a();
6044
+ m?.removeItem(e), m?.removeItem(t), u();
5881
6045
  }
5882
- function _() {
6046
+ function b() {
5883
6047
  return s || (s = (async () => {
5884
- let h = f();
5885
- if (!h) return false;
5886
- let b;
6048
+ let m = f();
6049
+ if (!m) return false;
6050
+ let g;
5887
6051
  try {
5888
- b = N();
6052
+ g = T();
5889
6053
  } catch {
5890
6054
  return false;
5891
6055
  }
5892
- let T = `${De(n.baseUrl)}/api/v1/oauth/token`, A = new URLSearchParams({
6056
+ let h = `${oe(n.baseUrl)}/api/v1/oauth/token`, C = new URLSearchParams({
5893
6057
  grant_type: "refresh_token",
5894
- refresh_token: h,
5895
- client_id: b
5896
- }), E;
6058
+ refresh_token: m,
6059
+ client_id: g
6060
+ }), D;
5897
6061
  try {
5898
- E = await n.fetch(T, {
6062
+ D = await n.fetch(h, {
5899
6063
  method: "POST",
5900
6064
  headers: { "content-type": "application/x-www-form-urlencoded" },
5901
- body: A.toString()
6065
+ body: C.toString()
5902
6066
  });
5903
6067
  } catch {
5904
6068
  return false;
5905
6069
  }
5906
- let S = null;
6070
+ let E = null;
5907
6071
  try {
5908
- S = await E.json();
6072
+ E = await D.json();
5909
6073
  } catch {
5910
- S = null;
6074
+ E = null;
5911
6075
  }
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;
6076
+ if (!D.ok || typeof E?.error == "string") return false;
6077
+ let R = E?.id_token;
6078
+ if (typeof R != "string" || R.length === 0) return false;
6079
+ let O = ie(R);
6080
+ if (!O) return false;
6081
+ let A = a();
6082
+ A?.setItem(e, R);
6083
+ let U = E?.refresh_token;
6084
+ return typeof U == "string" && U.length > 0 && A?.setItem(t, U), o = O, x(O), u(), true;
5921
6085
  })().finally(() => {
5922
6086
  s = null;
5923
6087
  }), s);
5924
6088
  }
5925
- function M() {
5926
- f() && _().then((h) => {
5927
- h || g();
6089
+ function S() {
6090
+ f() && b().then((m) => {
6091
+ m || _();
5928
6092
  });
5929
6093
  }
5930
- function R(h) {
6094
+ function x(m) {
5931
6095
  p();
5932
- let b = h.exp;
5933
- if (typeof b != "number") return;
5934
- let m = b * 1e3 - Date.now();
5935
- if (!(m <= 0)) {
6096
+ let g = m.exp;
6097
+ if (typeof g != "number") return;
6098
+ let w = g * 1e3 - Date.now();
6099
+ if (!(w <= 0)) {
5936
6100
  if (f()) {
5937
- let T = Math.min(m, Math.max(3e4, m * 0.2)), A = Math.max(1, m - T);
6101
+ let h = Math.min(w, Math.max(3e4, w * 0.2)), C = Math.max(1, w - h);
5938
6102
  i = setTimeout(() => {
5939
- i = null, _().then((E) => {
5940
- E || g();
6103
+ i = null, b().then((D) => {
6104
+ D || _();
5941
6105
  });
5942
- }, A);
6106
+ }, C);
5943
6107
  return;
5944
6108
  }
5945
6109
  i = setTimeout(() => {
5946
6110
  i = null, d();
5947
- }, m + 1);
6111
+ }, w + 1);
5948
6112
  }
5949
6113
  }
5950
- function N() {
5951
- return En(n);
6114
+ function T() {
6115
+ return Wn(n);
5952
6116
  }
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;
6117
+ async function P(m) {
6118
+ let g = m ?? (typeof globalThis.location < "u" ? globalThis.location.href : void 0);
6119
+ if (!g) return null;
6120
+ let w;
5957
6121
  try {
5958
- m = new URL(b);
6122
+ w = new URL(g);
5959
6123
  } catch {
5960
6124
  return null;
5961
6125
  }
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}`);
6126
+ let h = w.searchParams, C = h.get("error");
6127
+ if (C) {
6128
+ let U = h.get("error_description") ?? C;
6129
+ throw c()?.removeItem(se), rt(w), new l(C, `OIDC authorize falhou: ${U}`);
5966
6130
  }
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)
6131
+ let D = h.get("code");
6132
+ if (!D) return null;
6133
+ let E = h.get("state"), R = c(), O = R?.getItem(se) ?? null, A = null;
6134
+ if (O)
5971
6135
  try {
5972
- I = JSON.parse(D);
6136
+ A = JSON.parse(O);
5973
6137
  } catch {
5974
- I = null;
6138
+ A = null;
5975
6139
  }
5976
- if (!I)
5977
- throw new c(
6140
+ if (!A)
6141
+ throw new l(
5978
6142
  "oidc_state_mismatch",
5979
6143
  "Callback OIDC sem transa\xE7\xE3o pendente \u2014 `signIn` n\xE3o foi iniciado nesta sess\xE3o (ou j\xE1 consumido)."
5980
6144
  );
5981
- if (!S || S !== I.state)
5982
- throw k?.removeItem(oe), Xe(m), new c(
6145
+ if (!E || E !== A.state)
6146
+ throw R?.removeItem(se), rt(w), new l(
5983
6147
  "oidc_state_mismatch",
5984
6148
  "state do callback OIDC n\xE3o confere com o da transa\xE7\xE3o (poss\xEDvel CSRF)."
5985
6149
  );
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
6150
+ return R?.removeItem(se), rt(w), {
6151
+ code: D,
6152
+ codeVerifier: A.codeVerifier,
6153
+ redirectUri: A.redirectUri,
6154
+ nonce: A.nonce,
6155
+ state: A.state,
6156
+ postLoginRedirect: A.postLoginRedirect
5993
6157
  };
5994
6158
  }
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({
6159
+ async function q(m) {
6160
+ let g = await P(m);
6161
+ if (!g) return null;
6162
+ let w = T(), C = `${oe(n.baseUrl)}/api/v1/oauth/token`, D = new URLSearchParams({
5999
6163
  grant_type: "authorization_code",
6000
- code: b.code,
6001
- redirect_uri: b.redirectUri,
6002
- client_id: m,
6003
- code_verifier: b.codeVerifier
6004
- }), S;
6164
+ code: g.code,
6165
+ redirect_uri: g.redirectUri,
6166
+ client_id: w,
6167
+ code_verifier: g.codeVerifier
6168
+ }), E;
6005
6169
  try {
6006
- S = await n.fetch(A, {
6170
+ E = await n.fetch(C, {
6007
6171
  method: "POST",
6008
6172
  headers: { "content-type": "application/x-www-form-urlencoded" },
6009
- body: E.toString()
6173
+ body: D.toString()
6010
6174
  });
6011
- } catch (O) {
6012
- throw new c(
6175
+ } catch (L) {
6176
+ throw new l(
6013
6177
  "network_error",
6014
- `POST ${A} falhou (network): ${O?.message ?? String(O)}`
6178
+ `POST ${C} falhou (network): ${L?.message ?? String(L)}`
6015
6179
  );
6016
6180
  }
6017
- let k = null;
6181
+ let R = null;
6018
6182
  try {
6019
- k = await S.json();
6183
+ R = await E.json();
6020
6184
  } catch {
6021
- k = null;
6185
+ R = null;
6022
6186
  }
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}`;
6025
- throw new c(
6187
+ if (!E.ok || typeof R?.error == "string") {
6188
+ let L = typeof R?.error_description == "string" && R.error_description || typeof R?.error == "string" && R.error || `HTTP ${E.status}`;
6189
+ throw new l(
6026
6190
  "token_exchange_failed",
6027
- `Troca do authorization_code por tokens falhou no /token: ${O}`,
6028
- S.status
6191
+ `Troca do authorization_code por tokens falhou no /token: ${L}`,
6192
+ E.status
6029
6193
  );
6030
6194
  }
6031
- let D = k?.id_token;
6032
- if (typeof D != "string" || D.length === 0)
6033
- throw new c(
6195
+ let O = R?.id_token;
6196
+ if (typeof O != "string" || O.length === 0)
6197
+ throw new l(
6034
6198
  "token_exchange_failed",
6035
6199
  "Resposta do /token sem `id_token` \u2014 o login n\xE3o pode ser completado.",
6036
- S.status
6200
+ E.status
6037
6201
  );
6038
- let I = Je(D);
6039
- if (!I)
6040
- throw new c(
6202
+ let A = nt(O);
6203
+ if (!A)
6204
+ throw new l(
6041
6205
  "token_exchange_failed",
6042
6206
  "id_token retornado pelo /token \xE9 malformado (payload indecodific\xE1vel)."
6043
6207
  );
6044
- if (I.nonce !== b.nonce)
6045
- throw new c(
6208
+ if (A.nonce !== g.nonce)
6209
+ throw new l(
6046
6210
  "oidc_nonce_mismatch",
6047
6211
  "nonce do id_token n\xE3o confere com o da transa\xE7\xE3o OIDC (poss\xEDvel replay). Token descartado."
6048
6212
  );
6049
- let L = re(D);
6050
- if (!L)
6051
- throw new c(
6213
+ let U = ie(O);
6214
+ if (!U)
6215
+ throw new l(
6052
6216
  "token_exchange_failed",
6053
6217
  "id_token retornado pelo /token n\xE3o tem `sub` ou j\xE1 est\xE1 expirado."
6054
6218
  );
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 };
6219
+ let F = a();
6220
+ F?.setItem(e, O);
6221
+ let j = R?.refresh_token;
6222
+ return typeof j == "string" && j.length > 0 && F?.setItem(t, j), o = U, x(U), u(), { user: U, postLoginRedirect: g.postLoginRedirect };
6059
6223
  }
6060
6224
  return {
6061
- async signIn(h) {
6225
+ async signIn(m) {
6062
6226
  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)
6065
- throw new c(
6227
+ let g = Fn(), w = m?.redirectUri ?? globalThis.location.origin, h = m?.scope ?? "openid profile email", C = T(), D = xe(g, 16), E = xe(g, 16), R = xe(g, 32), O = await $n(g, R), A = c();
6228
+ if (!A)
6229
+ throw new l(
6066
6230
  "runtime_unsupported",
6067
6231
  "auth.signIn requer sessionStorage para guardar a transa\xE7\xE3o PKCE entre o redirect e o callback."
6068
6232
  );
6069
- let L = {
6070
- state: E,
6071
- nonce: S,
6072
- codeVerifier: k,
6073
- redirectUri: m,
6074
- postLoginRedirect: h?.postLoginRedirect
6233
+ let U = {
6234
+ state: D,
6235
+ nonce: E,
6236
+ codeVerifier: R,
6237
+ redirectUri: w,
6238
+ postLoginRedirect: m?.postLoginRedirect
6075
6239
  };
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
6240
+ A.setItem(se, JSON.stringify(U));
6241
+ let F = oe(n.baseUrl), j = Bn({
6242
+ idpOrigin: F,
6243
+ clientId: C,
6244
+ redirectUri: w,
6245
+ scope: h,
6246
+ state: D,
6247
+ nonce: E,
6248
+ codeChallenge: O
6085
6249
  });
6086
- globalThis.location.assign(F.toString());
6250
+ globalThis.location.assign(j.toString());
6087
6251
  return;
6088
6252
  }
6089
- throw new c(
6253
+ throw new l(
6090
6254
  "invalid_config",
6091
6255
  "auth.signIn requires a browser context or mocks. Use NEETRU_ENV=dev or pass mocks.auth."
6092
6256
  );
6093
6257
  },
6094
- handleRedirectCallback: C,
6095
- completeSignIn: $,
6258
+ handleRedirectCallback: P,
6259
+ completeSignIn: q,
6096
6260
  // 3.7.0: exposto pro client.support renovar a sessão 1x num 401
6097
6261
  // invalid_end_user_token (mesma função do refresh proativo, com dedup).
6098
- refreshTokens: _,
6262
+ refreshTokens: b,
6099
6263
  getIdToken() {
6100
- let b = a()?.getItem(e) ?? null;
6101
- return b && re(b) ? b : null;
6264
+ let g = a()?.getItem(e) ?? null;
6265
+ return g && ie(g) ? g : null;
6102
6266
  },
6103
6267
  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++)
6268
+ let m = a(), g = m?.getItem(t) ?? null;
6269
+ if (m && (m.removeItem(e), m.removeItem(t)), p(), o = null, g) {
6270
+ let w = null;
6108
6271
  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));
6272
+ w = T();
6273
+ } catch {
6274
+ w = null;
6117
6275
  }
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();
6276
+ !(w && await Vn(n.fetch, oe(n.baseUrl), w, [
6277
+ { token: g, hint: "refresh_token" }
6278
+ ])) && typeof console < "u" && console.warn(
6279
+ "[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."
6280
+ );
6281
+ }
6282
+ u();
6122
6283
  },
6123
6284
  getUser() {
6124
6285
  return d();
6125
6286
  },
6126
- onAuthStateChanged(h) {
6127
- r.add(h);
6287
+ onAuthStateChanged(m) {
6288
+ r.add(m);
6128
6289
  try {
6129
- h(d());
6290
+ m(d());
6130
6291
  } catch {
6131
6292
  }
6132
6293
  return () => {
6133
- r.delete(h);
6294
+ r.delete(m);
6134
6295
  };
6135
6296
  },
6136
- async verifyToken(h, b) {
6137
- if (!h || typeof h != "string")
6138
- 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)
6141
- throw new c(
6297
+ async verifyToken(m, g) {
6298
+ if (!m || typeof m != "string")
6299
+ throw new l("token_invalid_signature", "token must be a non-empty string");
6300
+ let h = (typeof globalThis.NEETRU_AUTH_URL == "string" ? globalThis.NEETRU_AUTH_URL : null) ?? n.baseUrl.replace(/^https?:\/\/api\./, "https://auth."), C = h, D = `${h}/api/v1/oauth/.well-known/jwks`, E = g?.jwksCacheTtlMs ?? Ue, R = g?.audience, O = lt(n.apiKey), A = R ?? n.oidcClientId ?? O?.keyId;
6301
+ if (!A)
6302
+ throw new l(
6142
6303
  "invalid_config",
6143
6304
  "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
6305
  );
6145
- let L = ho(E, S);
6306
+ let U = Mo(D, E);
6146
6307
  try {
6147
- let { payload: q } = await jose.jwtVerify(h, L, {
6148
- issuer: A,
6149
- audience: I,
6308
+ let { payload: F } = await jose.jwtVerify(m, U, {
6309
+ issuer: C,
6310
+ audience: A,
6150
6311
  algorithms: ["RS256"]
6151
6312
  });
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}`);
6313
+ return qo(F);
6314
+ } catch (F) {
6315
+ let j = F?.code ?? F?.name ?? "", L = F?.message ?? String(F);
6316
+ throw j === "ERR_JWT_EXPIRED" ? new l("token_expired", `Token expired: ${L}`) : j === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ? new l("token_invalid_signature", `Token signature invalid: ${L}`) : j === "ERR_JWT_CLAIM_VALIDATION_FAILED" ? L.includes('"aud"') || L.includes("audience") ? new l("token_invalid_audience", `Token audience mismatch: ${L}`) : L.includes('"iss"') || L.includes("issuer") ? new l("token_invalid_issuer", `Token issuer mismatch: ${L}`) : new l("token_invalid_signature", `Token claim validation failed: ${L}`) : new l("token_invalid_signature", `Token verification failed: ${L}`);
6156
6317
  }
6157
6318
  }
6158
6319
  };
6159
6320
  }
6160
- function _o(n = {}) {
6321
+ function jo(n = {}) {
6161
6322
  let e = n.fetch ?? globalThis.fetch;
6162
6323
  if (typeof e != "function")
6163
- throw new c(
6324
+ throw new l(
6164
6325
  "invalid_config",
6165
6326
  "fetch is not available in this runtime. Pass `fetch` explicitly to createNeetruClient."
6166
6327
  );
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({
6328
+ let t = n.apiKey ?? Lo();
6329
+ wt({ hasApiKey: !!t, strict: n.strictServerOnlyKey === true });
6330
+ let r = Uo(n.env), o = n.baseUrl ?? (r === "dev-local" ? mt : ft), i = pt(o, n.allowedHosts ?? []), s = Object.freeze({
6168
6331
  apiKey: t,
6169
6332
  oidcClientId: n.oidcClientId,
6170
6333
  baseUrl: i,
@@ -6172,39 +6335,39 @@ function _o(n = {}) {
6172
6335
  env: r,
6173
6336
  productId: n.productId,
6174
6337
  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).
6338
+ }), a = r === "dev" && !Ce(), c = n.mocks?.auth ?? (a ? new Ae({ ...tt }) : Fo(s)), d = n.mocks?.usage ?? (a ? new Ee() : Ut(s)), u = n.endUserAuth ?? c, p = n.mocks?.support ?? (a ? new Pe() : Wt(s, {
6339
+ getEndUserToken: () => u.getIdToken(),
6340
+ // `refreshTokens` é opcional (MockAuth/mocks próprios omitem).
6178
6341
  refreshEndUserToken: (() => {
6179
- let N = l.refreshTokens;
6180
- return typeof N == "function" ? () => N.call(l) : void 0;
6342
+ let P = u.refreshTokens;
6343
+ return typeof P == "function" ? () => P.call(u) : void 0;
6181
6344
  })()
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({
6345
+ })), f = n.mocks?.entitlements ?? (a ? new De() : Dt()), _ = n.mocks?.db ?? (X() === "react-native" ? zn() : ln(s, n.db)), b = n.mocks?.webhooks ?? (a ? new Se() : mn(s)), S = n.mocks?.notifications ?? (a ? new Re() : yn(s)), x = n.mocks?.ai ?? (a ? new Ne() : qn(s)), T = Object.freeze({
6184
6346
  config: s,
6185
- auth: l,
6186
- catalog: yt(s),
6187
- entitlements: p,
6188
- telemetry: kt(s),
6347
+ auth: c,
6348
+ catalog: Et(s),
6349
+ entitlements: f,
6350
+ telemetry: Ot(s),
6189
6351
  usage: d,
6190
- support: u,
6191
- db: f,
6192
- checkout: Xt(s),
6193
- webhooks: g,
6194
- notifications: _,
6195
- ai: M
6352
+ support: p,
6353
+ db: _,
6354
+ checkout: dn(s),
6355
+ webhooks: b,
6356
+ notifications: S,
6357
+ ai: x
6196
6358
  });
6359
+ return n.endUserAuth && Kn(T, n.endUserAuth), T;
6197
6360
  }
6198
- var Ne = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6199
- function ws(n = {}) {
6361
+ var Oe = /* @__PURE__ */ Symbol.for("@neetru/sdk:serverClient");
6362
+ function oa(n = {}) {
6200
6363
  let e = globalThis;
6201
- return e[Ne] || (e[Ne] = _o(n)), e[Ne];
6364
+ return e[Oe] || (e[Oe] = jo(n)), e[Oe];
6202
6365
  }
6203
- function ks() {
6204
- delete globalThis[Ne];
6366
+ function ia() {
6367
+ delete globalThis[Oe];
6205
6368
  }
6206
6369
 
6207
- exports.__resetJwksCacheForTests = vs;
6208
- exports.__resetServerNeetruClientForTests = ks;
6209
- exports.createNeetruClient = _o;
6210
- exports.getServerNeetruClient = ws;
6370
+ exports.__resetJwksCacheForTests = ra;
6371
+ exports.__resetServerNeetruClientForTests = ia;
6372
+ exports.createNeetruClient = jo;
6373
+ exports.getServerNeetruClient = oa;