@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
@@ -1,5 +1,5 @@
1
1
  // src/errors.ts
2
- var a = class e extends Error {
2
+ var d = class e extends Error {
3
3
  code;
4
4
  status;
5
5
  requestId;
@@ -12,183 +12,250 @@ var a = class e extends Error {
12
12
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
13
13
  */
14
14
  reason;
15
- constructor(r, n, d, m, c) {
16
- super(n), this.name = "NeetruError", this.code = r, this.status = d, this.requestId = m, this.reason = c, Object.setPrototypeOf(this, e.prototype);
15
+ /**
16
+ * 3.8.0: `x-correlation-id` da requisição que falhou. O SDK gera um UUID por
17
+ * chamada (ou usa o que o chamador passou) e manda no header; o Core grava o
18
+ * mesmo id nos logs/auditoria — cite-o ao abrir um ticket de suporte.
19
+ * `undefined` em erros que acontecem antes de qualquer requisição.
20
+ */
21
+ correlationId;
22
+ constructor(t, n, o, i, u, r) {
23
+ super(n), this.name = "NeetruError", this.code = t, this.status = o, this.requestId = i, this.reason = u, this.correlationId = r, Object.setPrototypeOf(this, e.prototype);
17
24
  }
18
25
  };
19
26
 
20
27
  // src/idempotency.ts
21
- function R() {
28
+ function I() {
22
29
  let e = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
23
30
  if (e && typeof e.randomUUID == "function")
24
31
  return e.randomUUID();
25
- throw new a(
32
+ throw new d(
26
33
  "runtime_unsupported",
27
34
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
28
35
  );
29
36
  }
30
37
 
38
+ // src/correlation.ts
39
+ var A = "x-correlation-id";
40
+ var j = /^[A-Za-z0-9._:\-]+$/;
41
+ function S(e) {
42
+ return typeof e == "string" && e.length > 0 && e.length <= 128 && j.test(e);
43
+ }
44
+ function H() {
45
+ let e = globalThis.crypto;
46
+ try {
47
+ if (e && typeof e.randomUUID == "function") return e.randomUUID();
48
+ } catch {
49
+ }
50
+ let t = new Uint8Array(16), n = false;
51
+ try {
52
+ e && typeof e.getRandomValues == "function" && (e.getRandomValues(t), n = !0);
53
+ } catch {
54
+ n = false;
55
+ }
56
+ if (!n)
57
+ for (let i = 0; i < t.length; i++) t[i] = Math.floor(Math.random() * 256);
58
+ t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128;
59
+ let o = Array.from(t, (i) => i.toString(16).padStart(2, "0")).join("");
60
+ return `${o.slice(0, 8)}-${o.slice(8, 12)}-${o.slice(12, 16)}-${o.slice(16, 20)}-${o.slice(20)}`;
61
+ }
62
+ function N(e, t) {
63
+ let n, o = {};
64
+ for (let [u, r] of Object.entries(e)) {
65
+ if (u.toLowerCase() === A) {
66
+ S(r) && (n = r);
67
+ continue;
68
+ }
69
+ o[u] = r;
70
+ }
71
+ let i = n ?? (S(t) ? t : void 0) ?? H();
72
+ return o[A] = i, { headers: o, correlationId: i };
73
+ }
74
+
75
+ // src/server-only-key.ts
76
+ function x() {
77
+ try {
78
+ let e = globalThis.navigator;
79
+ if (e && e.product === "ReactNative") return "react-native";
80
+ } catch {
81
+ }
82
+ try {
83
+ let e = globalThis;
84
+ if (typeof e.window < "u" && typeof e.document < "u") return "browser";
85
+ } catch {
86
+ }
87
+ return null;
88
+ }
89
+
31
90
  // src/http.ts
32
- var L = {
91
+ var F = {
33
92
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
34
93
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
35
94
  3: "2026.05.1"
36
95
  };
37
- function v(e) {
96
+ function R(e) {
38
97
  return e.split("+")[0] ?? e;
39
98
  }
40
- function O(e, r) {
41
- let n = v(e).split(".").map(Number), d = v(r).split(".").map(Number), m = Math.max(n.length, d.length);
42
- for (let c = 0; c < m; c++) {
43
- let t = n[c] ?? 0, i = d[c] ?? 0;
44
- if (t !== i) return t - i;
99
+ function V(e, t) {
100
+ let n = R(e).split(".").map(Number), o = R(t).split(".").map(Number), i = Math.max(n.length, o.length);
101
+ for (let u = 0; u < i; u++) {
102
+ let r = n[u] ?? 0, a = o[u] ?? 0;
103
+ if (r !== a) return r - a;
45
104
  }
46
105
  return 0;
47
106
  }
48
- function D() {
107
+ function L() {
49
108
  try {
50
- return "3.7.0";
109
+ return "3.8.0";
51
110
  } catch {
52
111
  return;
53
112
  }
54
113
  }
55
- function U() {
56
- let e = D();
114
+ function B() {
115
+ let e = L();
57
116
  return e ? parseInt(e.split(".")[0] ?? "3", 10) : 3;
58
117
  }
59
- var A = /* @__PURE__ */ new Set();
60
- function j(e) {
118
+ var D = /* @__PURE__ */ new Set();
119
+ function z(e) {
61
120
  if (!e) return;
62
- let r = U(), n = L[r];
121
+ let t = B(), n = F[t];
63
122
  if (!n) return;
64
- let d = v(e);
65
- if (O(d, n) < 0) {
66
- let m = `${r}:${d}`;
67
- A.has(m) || (A.add(m), console.warn(
68
- `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${e}" \xE9 anterior ao m\xEDnimo recomendado "${n}" para SDK major ${r}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
123
+ let o = R(e);
124
+ if (V(o, n) < 0) {
125
+ let i = `${t}:${o}`;
126
+ D.has(i) || (D.add(i), console.warn(
127
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${e}" \xE9 anterior ao m\xEDnimo recomendado "${n}" para SDK major ${t}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
69
128
  ));
70
129
  }
71
130
  }
72
- var $ = 2, K = 0, H = /* @__PURE__ */ new Set(["GET", "HEAD"]), F = /* @__PURE__ */ new Set([
131
+ function G() {
132
+ let e = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
133
+ 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. (" + e + ")" : e;
134
+ }
135
+ var X = 2, Y = 0, J = /* @__PURE__ */ new Set(["GET", "HEAD"]), W = /* @__PURE__ */ new Set([
73
136
  "rate_limited",
74
137
  "server_error",
75
138
  "network_error"
76
139
  ]);
77
- function I(e) {
78
- let r = 200 * Math.pow(4, e), n = r * 0.2 * (Math.random() * 2 - 1);
79
- return Math.max(50, Math.round(r + n));
140
+ function C(e) {
141
+ let t = 200 * Math.pow(4, e), n = t * 0.2 * (Math.random() * 2 - 1);
142
+ return Math.max(50, Math.round(t + n));
80
143
  }
81
- var S = 6e4;
82
- function V(e) {
144
+ var O = 6e4;
145
+ function Q(e) {
83
146
  if (!e) return null;
84
- let r = Number(e);
85
- if (Number.isFinite(r) && r >= 0) return Math.min(Math.round(r * 1e3), S);
147
+ let t = Number(e);
148
+ if (Number.isFinite(t) && t >= 0) return Math.min(Math.round(t * 1e3), O);
86
149
  let n = Date.parse(e);
87
150
  if (Number.isFinite(n)) {
88
- let d = n - Date.now();
89
- if (d > 0) return Math.min(d, S);
151
+ let o = n - Date.now();
152
+ if (o > 0) return Math.min(o, O);
90
153
  }
91
154
  return null;
92
155
  }
93
156
  function q(e) {
94
- return new Promise((r) => setTimeout(r, e));
157
+ return new Promise((t) => setTimeout(t, e));
95
158
  }
96
- function G(e) {
159
+ function Z(e) {
97
160
  return e === 401 ? "unauthorized" : e === 403 ? "forbidden" : e === 404 ? "not_found" : e === 409 ? "conflict" : e === 410 ? "gone" : e === 422 || e === 400 ? "validation_failed" : e === 429 ? "rate_limited" : e >= 500 ? "server_error" : "unknown";
98
161
  }
99
- function z(e, r, n) {
100
- let d = e.replace(/\/+$/, ""), m = r.startsWith("/") ? r : `/${r}`, c = new URL(`${d}${m}`);
162
+ function ee(e, t, n) {
163
+ let o = e.replace(/\/+$/, ""), i = t.startsWith("/") ? t : `/${t}`, u = new URL(`${o}${i}`);
101
164
  if (n)
102
- for (let [t, i] of Object.entries(n))
103
- i !== void 0 && c.searchParams.set(t, String(i));
104
- return c.toString();
165
+ for (let [r, a] of Object.entries(n))
166
+ a !== void 0 && u.searchParams.set(r, String(a));
167
+ return u.toString();
105
168
  }
106
- async function x(e) {
107
- let r = await e.text();
108
- if (r)
169
+ async function K(e) {
170
+ let t = await e.text();
171
+ if (t)
109
172
  try {
110
- return JSON.parse(r);
173
+ return JSON.parse(t);
111
174
  } catch {
112
175
  return;
113
176
  }
114
177
  }
115
- async function _(e, r) {
116
- let n = r.method ?? "GET", d = z(e.baseUrl, r.path, r.query), m = H.has(n) ? $ : K, c = r.retries ?? m, t = {
117
- accept: "application/json",
118
- ...r.headers
119
- }, i = D();
120
- if (i && (t["x-neetru-sdk-version"] = i), r.requireAuth) {
178
+ async function v(e, t) {
179
+ let n = t.method ?? "GET", o = ee(e.baseUrl, t.path, t.query), i = J.has(n) ? X : Y, u = t.retries ?? i, { headers: r, correlationId: a } = N(
180
+ { accept: "application/json", ...t.headers },
181
+ t.correlationId
182
+ ), l = L();
183
+ if (l && (r["x-neetru-sdk-version"] = l), t.requireAuth) {
121
184
  if (!e.apiKey)
122
- throw new a(
123
- "missing_api_key",
124
- "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
125
- );
126
- t.authorization = `Bearer ${e.apiKey}`;
185
+ throw new d("missing_api_key", G());
186
+ r.authorization = `Bearer ${e.apiKey}`;
127
187
  }
128
- if (r.idempotencyKey) {
129
- let f = typeof r.idempotencyKey == "string" ? r.idempotencyKey : R();
130
- t["idempotency-key"] = f;
188
+ if (t.idempotencyKey) {
189
+ let g = typeof t.idempotencyKey == "string" ? t.idempotencyKey : I();
190
+ r["idempotency-key"] = g;
131
191
  }
132
- let l = r.body !== void 0 && n !== "GET" && n !== "DELETE" ? JSON.stringify(r.body) : void 0;
133
- l !== void 0 && (t["content-type"] = "application/json");
134
- let s = null, u = r.deadlineMs != null ? Date.now() + r.deadlineMs : null;
135
- for (let f = 0; f <= c; f++) {
136
- if (u != null && Date.now() >= u)
137
- throw s ?? new a("network_error", "Deadline excedido antes de completar a request");
138
- let y = { method: n, headers: t };
139
- l !== void 0 && (y.body = l);
140
- let M = u != null ? Math.max(1, Math.min(3e4, u - Date.now())) : 3e4;
141
- y.signal = AbortSignal.timeout(M);
192
+ let c = t.body !== void 0 && n !== "GET" && n !== "DELETE" ? JSON.stringify(t.body) : void 0;
193
+ c !== void 0 && (r["content-type"] = "application/json");
194
+ let f = null, m = t.deadlineMs != null ? Date.now() + t.deadlineMs : null;
195
+ for (let g = 0; g <= u; g++) {
196
+ if (m != null && Date.now() >= m)
197
+ throw f ?? new d(
198
+ "network_error",
199
+ "Deadline excedido antes de completar a request",
200
+ void 0,
201
+ void 0,
202
+ void 0,
203
+ a
204
+ );
205
+ let b = { method: n, headers: r };
206
+ c !== void 0 && (b.body = c);
207
+ let U = m != null ? Math.max(1, Math.min(3e4, m - Date.now())) : 3e4;
208
+ b.signal = AbortSignal.timeout(U);
142
209
  let p;
143
210
  try {
144
- p = await e.fetch(d, y);
145
- } catch (o) {
146
- let w = o instanceof DOMException && o.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${o instanceof Error ? o.message : "fetch failed"}`;
147
- if (s = new a("network_error", w), f < c) {
148
- let k = I(f);
149
- if (u == null || Date.now() + k < u) {
211
+ p = await e.fetch(o, b);
212
+ } catch (s) {
213
+ let _ = s instanceof DOMException && s.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${s instanceof Error ? s.message : "fetch failed"}`;
214
+ if (f = new d("network_error", _, void 0, void 0, void 0, a), g < u) {
215
+ let k = C(g);
216
+ if (m == null || Date.now() + k < m) {
150
217
  await q(k);
151
218
  continue;
152
219
  }
153
220
  }
154
- throw s;
221
+ throw f;
155
222
  }
156
- let P = p.headers.get("x-request-id") ?? p.headers.get("x-correlation-id") ?? void 0;
223
+ let $ = p.headers.get("x-request-id") ?? p.headers.get("x-correlation-id") ?? void 0;
157
224
  if (p.ok) {
158
- let o = p.headers.get("x-neetru-version");
159
- return o && j(o), await x(p);
225
+ let s = p.headers.get("x-neetru-version");
226
+ return s && z(s), await K(p);
160
227
  }
161
- let g = await x(p), b = G(p.status), h = `HTTP ${p.status}`, T;
162
- if (g && typeof g == "object") {
163
- let o = g.error;
164
- typeof o == "string" ? h = o : o && typeof o == "object" ? (typeof o.code == "string" && (b = o.code), typeof o.message == "string" && (h = o.message), typeof o.reason == "string" && (T = o.reason)) : (typeof g.code == "string" && (b = g.code), typeof g.message == "string" && (h = g.message)), typeof g.reason == "string" && (T = g.reason);
228
+ let y = await K(p), w = Z(p.status), h = `HTTP ${p.status}`, E;
229
+ if (y && typeof y == "object") {
230
+ let s = y.error;
231
+ typeof s == "string" ? h = s : s && typeof s == "object" ? (typeof s.code == "string" && (w = s.code), typeof s.message == "string" && (h = s.message), typeof s.reason == "string" && (E = s.reason)) : (typeof y.code == "string" && (w = y.code), typeof y.message == "string" && (h = y.message)), typeof y.reason == "string" && (E = y.reason);
165
232
  }
166
233
  if (p.status === 410) {
167
- let o = p.headers.get("x-neetru-replacement");
168
- h === `HTTP ${p.status}` && (h = `Endpoint ${r.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), o && !h.includes(o) && (h += ` Substituto: ${o}.`);
234
+ let s = p.headers.get("x-neetru-replacement");
235
+ h === `HTTP ${p.status}` && (h = `Endpoint ${t.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), s && !h.includes(s) && (h += ` Substituto: ${s}.`);
169
236
  }
170
- let E = new a(b, h, p.status, P, T);
171
- if (s = E, F.has(b) && f < c) {
172
- let w = V(p.headers.get("retry-after")) ?? I(f);
173
- if (u == null || Date.now() + w < u) {
174
- await q(w);
237
+ let T = new d(w, h, p.status, $, E, a);
238
+ if (f = T, W.has(w) && g < u) {
239
+ let _ = Q(p.headers.get("retry-after")) ?? C(g);
240
+ if (m == null || Date.now() + _ < m) {
241
+ await q(_);
175
242
  continue;
176
243
  }
177
244
  }
178
- throw E;
245
+ throw T;
179
246
  }
180
- throw s ?? new a("unknown", "unexpected httpRequest exit");
247
+ throw f ?? new d("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, a);
181
248
  }
182
249
 
183
250
  // src/telemetry.ts
184
- var N = ["debug", "info", "warn", "error", "fatal"];
185
- function B() {
251
+ var P = ["debug", "info", "warn", "error", "fatal"];
252
+ function te() {
186
253
  return typeof globalThis < "u" && typeof globalThis.window < "u";
187
254
  }
188
- function C() {
189
- return B() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
255
+ function M() {
256
+ return te() ? { path: "/api/sdk/v1/telemetry/event/public", requireAuth: false } : { path: "/api/sdk/v1/telemetry/event", requireAuth: true };
190
257
  }
191
- function J(e) {
258
+ function re(e) {
192
259
  switch (e) {
193
260
  case "debug":
194
261
  return console.debug.bind(console);
@@ -204,41 +271,41 @@ function J(e) {
204
271
  return console.log.bind(console);
205
272
  }
206
273
  }
207
- var X = 500, Y = 50;
208
- function se(e) {
209
- let r = [], n = null, d = null;
210
- async function m() {
211
- if (r.length === 0) return;
212
- let t = r.splice(0, r.length), i = Promise.allSettled(
213
- t.map(async (l) => {
274
+ var ne = 500, oe = 50;
275
+ function _e(e) {
276
+ let t = [], n = null, o = null;
277
+ async function i() {
278
+ if (t.length === 0) return;
279
+ let r = t.splice(0, t.length), a = Promise.allSettled(
280
+ r.map(async (l) => {
214
281
  try {
215
- let s = { name: l.name }, u = l.productSlug ?? e.productId;
216
- u && (s.productSlug = u), l.properties && typeof l.properties == "object" && (s.properties = l.properties), l.timestamp && (s.timestamp = l.timestamp);
217
- let f = C();
218
- await _(e, {
282
+ let c = { name: l.name }, f = l.productSlug ?? e.productId;
283
+ f && (c.productSlug = f), l.properties && typeof l.properties == "object" && (c.properties = l.properties), l.timestamp && (c.timestamp = l.timestamp);
284
+ let m = M();
285
+ await v(e, {
219
286
  method: "POST",
220
- path: f.path,
221
- body: s,
222
- requireAuth: f.requireAuth,
287
+ path: m.path,
288
+ body: c,
289
+ requireAuth: m.requireAuth,
223
290
  retries: 1,
224
291
  // caça-bruxas: retry sem Idempotency-Key duplicava o evento se o
225
292
  // servidor já tinha persistido antes da falha transiente. Mesmo
226
293
  // padrão do usage.report (key estável por chamada, reusada no retry).
227
294
  idempotencyKey: !0
228
295
  });
229
- } catch (s) {
230
- typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", l.name, s);
296
+ } catch (c) {
297
+ typeof console < "u" && console.warn("[neetru-sdk] telemetry.track flush failed for event", l.name, c);
231
298
  }
232
299
  })
233
300
  );
234
- d = i.then(() => {
235
- d = null;
236
- }), await i, n = null, r.length > 0 && c();
301
+ o = a.then(() => {
302
+ o = null;
303
+ }), await a, n = null, t.length > 0 && u();
237
304
  }
238
- function c() {
305
+ function u() {
239
306
  n || (n = setTimeout(() => {
240
- m();
241
- }, X));
307
+ i();
308
+ }, ne));
242
309
  }
243
310
  return {
244
311
  /**
@@ -253,24 +320,24 @@ function se(e) {
253
320
  * });
254
321
  * ```
255
322
  */
256
- async event(t) {
257
- if (!t || typeof t != "object")
258
- throw new a("validation_failed", "event input is required");
259
- if (typeof t.name != "string" || t.name.length === 0)
260
- throw new a("validation_failed", "event.name is required");
261
- if (t.name.length > 128)
262
- throw new a("validation_failed", "event.name max 128 chars");
263
- let i = { name: t.name }, l = t.productSlug ?? e.productId;
264
- l && (i.productSlug = l), t.properties && typeof t.properties == "object" && (i.properties = t.properties), t.timestamp && (i.timestamp = t.timestamp);
265
- let s = C(), u = await _(e, {
323
+ async event(r) {
324
+ if (!r || typeof r != "object")
325
+ throw new d("validation_failed", "event input is required");
326
+ if (typeof r.name != "string" || r.name.length === 0)
327
+ throw new d("validation_failed", "event.name is required");
328
+ if (r.name.length > 128)
329
+ throw new d("validation_failed", "event.name max 128 chars");
330
+ let a = { name: r.name }, l = r.productSlug ?? e.productId;
331
+ l && (a.productSlug = l), r.properties && typeof r.properties == "object" && (a.properties = r.properties), r.timestamp && (a.timestamp = r.timestamp);
332
+ let c = M(), f = await v(e, {
266
333
  method: "POST",
267
- path: s.path,
268
- body: i,
269
- requireAuth: s.requireAuth
334
+ path: c.path,
335
+ body: a,
336
+ requireAuth: c.requireAuth
270
337
  });
271
- if (!u || u.ok !== true || typeof u.eventId != "string")
272
- throw new a("invalid_response", "Telemetry response missing eventId");
273
- return { ok: true, eventId: u.eventId };
338
+ if (!f || f.ok !== true || typeof f.eventId != "string")
339
+ throw new d("invalid_response", "Telemetry response missing eventId");
340
+ return { ok: true, eventId: f.eventId };
274
341
  },
275
342
  /**
276
343
  * Fire-and-forget: enqueue + flush 500ms debounce. Não retorna `eventId`
@@ -282,15 +349,15 @@ function se(e) {
282
349
  * // segue execução; flush async em background
283
350
  * ```
284
351
  */
285
- track(t) {
286
- !t || typeof t != "object" || typeof t.name != "string" || t.name.length === 0 || t.name.length > 128 || (r.push(t), r.length >= Y ? (n && (clearTimeout(n), n = null), m()) : c());
352
+ track(r) {
353
+ !r || typeof r != "object" || typeof r.name != "string" || r.name.length === 0 || r.name.length > 128 || (t.push(r), t.length >= oe ? (n && (clearTimeout(n), n = null), i()) : u());
287
354
  },
288
355
  /**
289
356
  * Força flush imediato da queue de `track()`. Resolva antes de
290
357
  * page unload / SSR boundary pra não perder eventos.
291
358
  */
292
359
  async flush() {
293
- n && (clearTimeout(n), n = null), d && await d, await m();
360
+ n && (clearTimeout(n), n = null), o && await o, await i();
294
361
  },
295
362
  /**
296
363
  * Registra um log estruturado per-product (Sprint 6).
@@ -307,49 +374,49 @@ function se(e) {
307
374
  * });
308
375
  * ```
309
376
  */
310
- async log(t) {
311
- if (!t || typeof t != "object")
312
- throw new a("validation_failed", "log input is required");
313
- if (!N.includes(t.level))
314
- throw new a("validation_failed", `level must be one of ${N.join(", ")}`);
315
- if (typeof t.message != "string" || t.message.length === 0)
316
- throw new a("validation_failed", "message is required");
317
- if (t.message.length > 4e3)
318
- throw new a("validation_failed", "message max 4000 chars");
377
+ async log(r) {
378
+ if (!r || typeof r != "object")
379
+ throw new d("validation_failed", "log input is required");
380
+ if (!P.includes(r.level))
381
+ throw new d("validation_failed", `level must be one of ${P.join(", ")}`);
382
+ if (typeof r.message != "string" || r.message.length === 0)
383
+ throw new d("validation_failed", "message is required");
384
+ if (r.message.length > 4e3)
385
+ throw new d("validation_failed", "message max 4000 chars");
319
386
  if (e.env === "dev")
320
- return J(t.level)(`[neetru-sdk] ${t.level}: ${t.message}`, t.metadata ?? {}), { ok: true, mode: "mock" };
321
- let i = {
322
- level: t.level,
323
- message: t.message
387
+ return re(r.level)(`[neetru-sdk] ${r.level}: ${r.message}`, r.metadata ?? {}), { ok: true, mode: "mock" };
388
+ let a = {
389
+ level: r.level,
390
+ message: r.message
324
391
  };
325
- t.metadata && (i.metadata = t.metadata);
326
- let l = t.productSlug ?? e.productId;
327
- l && (i.productSlug = l);
328
- let s = t.correlationId;
329
- if (!s)
392
+ r.metadata && (a.metadata = r.metadata);
393
+ let l = r.productSlug ?? e.productId;
394
+ l && (a.productSlug = l);
395
+ let c = r.correlationId;
396
+ if (!c)
330
397
  try {
331
- let y = globalThis.NEETRU_CORRELATION_ID;
332
- typeof y == "string" && y.length > 0 && (s = y);
398
+ let g = globalThis.NEETRU_CORRELATION_ID;
399
+ typeof g == "string" && g.length > 0 && (c = g);
333
400
  } catch {
334
401
  }
335
- let u = {};
336
- s && (u["x-correlation-id"] = s);
337
- let f = await _(e, {
402
+ let f = {};
403
+ c && (f["x-correlation-id"] = c);
404
+ let m = await v(e, {
338
405
  method: "POST",
339
406
  path: "/api/sdk/v1/telemetry/log",
340
- body: i,
407
+ body: a,
341
408
  requireAuth: true,
342
- headers: u
409
+ headers: f
343
410
  });
344
- if (!f || f.ok !== true)
345
- throw new a("invalid_response", "Telemetry log response missing ok");
411
+ if (!m || m.ok !== true)
412
+ throw new d("invalid_response", "Telemetry log response missing ok");
346
413
  return {
347
414
  ok: true,
348
- logId: typeof f.logId == "string" ? f.logId : void 0,
415
+ logId: typeof m.logId == "string" ? m.logId : void 0,
349
416
  mode: "http"
350
417
  };
351
418
  }
352
419
  };
353
420
  }
354
421
 
355
- export { se as createTelemetryNamespace };
422
+ export { _e as createTelemetryNamespace };
@@ -113,6 +113,28 @@ declare class MockCheckout implements CheckoutNamespace {
113
113
  }
114
114
  declare function createCheckoutNamespace(config: ResolvedConfig): CheckoutNamespace;
115
115
 
116
+ /**
117
+ * 3.8.0 — Provedor de token do USUÁRIO FINAL, síncrono OU assíncrono.
118
+ *
119
+ * O namespace `auth` web lê o id_token de `localStorage` (síncrono). Em React
120
+ * Native o storage é assíncrono (`@neetru/sdk/mobile` → `getIdToken():
121
+ * Promise`). Antes desta versão `support` e a barra de conta só aceitavam o
122
+ * contrato síncrono — o módulo mobile ficava solto do `createNeetruClient`.
123
+ *
124
+ * Agora `createNeetruClient({ endUserAuth })` aceita qualquer objeto com
125
+ * `getIdToken()` (sync ou Promise) e, opcionalmente, `refreshTokens()` — o
126
+ * `MobileAuthNamespace` encaixa direto. O provedor fica registrado por client
127
+ * (WeakMap, sem mudar o shape público do `NeetruClient`) para a barra de conta
128
+ * (`fetchNeetruAccountBar`) achá-lo.
129
+ */
130
+
131
+ interface EndUserTokenProvider {
132
+ /** id_token OIDC do usuário logado, ou `null`. Pode ser síncrono ou Promise. */
133
+ getIdToken(): string | null | undefined | Promise<string | null | undefined>;
134
+ /** Renova a sessão (refresh_token → id_token novo). `true` se renovou. */
135
+ refreshTokens?(): Promise<boolean>;
136
+ }
137
+
116
138
  /** Bloco de texto de uma mensagem multimodal (OpenAI-compat). */
117
139
  interface AiTextPart {
118
140
  type: 'text';
@@ -1975,6 +1997,10 @@ interface NeetruClientConfig {
1975
1997
  *
1976
1998
  * Endpoints públicos (catalog) funcionam sem apiKey. Endpoints autenticados
1977
1999
  * (entitlements, telemetry) lançam `missing_api_key` se ausente.
2000
+ *
2001
+ * **3.8.0: SÓ DE SERVIDOR.** Nunca coloque a chave no navegador ou no app
2002
+ * (`NEXT_PUBLIC_*`/`EXPO_PUBLIC_*`): o site/app chama a API do próprio produto
2003
+ * e o backend usa o SDK com a chave. Ver `strictServerOnlyKey`.
1978
2004
  */
1979
2005
  apiKey?: string;
1980
2006
  /**
@@ -2053,6 +2079,27 @@ interface NeetruClientConfig {
2053
2079
  * Bypass total: `NEETRU_ALLOW_INSECURE_BASEURL=1` no env.
2054
2080
  */
2055
2081
  allowedHosts?: string[];
2082
+ /**
2083
+ * 3.8.0 — a credencial `nrt_` é SÓ DE SERVIDOR. Quando o SDK recebe chave
2084
+ * (via `apiKey` ou `NEETRU_API_KEY`) rodando em navegador ou React Native:
2085
+ * - `false`/omitido (padrão nesta minor): aviso único no console (PT-BR,
2086
+ * sem imprimir a chave) e segue funcionando — pra não quebrar produtos
2087
+ * que ainda estão migrando;
2088
+ * - `true`: falha FECHADO com `NeetruError('server_only_key')`.
2089
+ *
2090
+ * **Na próxima MAJOR (4.0) a falha fechada vira o padrão.** No servidor
2091
+ * (Node/Edge) a opção não tem efeito.
2092
+ */
2093
+ strictServerOnlyKey?: boolean;
2094
+ /**
2095
+ * 3.8.0 — provedor do token do USUÁRIO FINAL usado pelo `support`
2096
+ * (`X-Neetru-End-User-Token`) e pela barra de conta. Aceita `getIdToken()`
2097
+ * síncrono ou assíncrono (+ `refreshTokens()` opcional). Encaixa direto o
2098
+ * `createMobileAuthNamespace(...)` de `@neetru/sdk/mobile`; no backend do
2099
+ * produto, pode ser `{ getIdToken: () => idTokenQueOAppMandou }`.
2100
+ * Default: `client.auth`.
2101
+ */
2102
+ endUserAuth?: EndUserTokenProvider;
2056
2103
  }
2057
2104
  /**
2058
2105
  * Status do produto no catálogo público.
@@ -2721,4 +2768,4 @@ interface CatalogListOptions {
2721
2768
  includeDrafts?: boolean;
2722
2769
  }
2723
2770
 
2724
- export { NeetruDbError as $, type AiChatChoice as A, type DbChangeType as B, type CatalogListOptions as C, DEFAULT_BASE_URL as D, type DbCollectionRef$1 as E, type DbDoc as F, type DbDocRef as G, type DbGetResult as H, type DbListResult as I, type DbNamespace as J, type DbQuery$1 as K, type DbSqlLease as L, type DbWhereFilter as M, type DbWhereFilter$1 as N, type EntitlementCheck as O, type FieldSentinel as P, type IncrementSentinel as Q, type ListNotificationsOptions as R, MockCheckout as S, MockNotifications as T, MockWebhooks as U, NEETRU_SENTINEL_KEY as V, type NeetruClient as W, type NeetruClientConfig as X, type NeetruDb as Y, type NeetruDbDocuments as Z, type NeetruDbEngine as _, type AiChatMessage as a, type NeetruDbErrorCode as a0, type NeetruDbOptions as a1, type NeetruDbTransport as a2, type NeetruEnv as a3, type NeetruSqlClient as a4, type NeetruUser as a5, type NotificationScopeOptions as a6, type NotificationsNamespace as a7, type Product as a8, type ProductNotification as a9, type VerifyWebhookRequestOptions as aA, type VerifyWebhookRequestResult as aB, type WebhookEndpoint as aC, type WebhookEvent as aD, type WebhookScopeOptions as aE, type WebhookTestResult as aF, type WebhooksNamespace as aG, type WithFieldSentinels as aH, __resetDbIdWarningForTests as aI, createAiNamespace as aJ, createCheckoutNamespace as aK, createNeetruDb as aL, createNotificationsNamespace as aM, createRestSyncTransport as aN, createWebhooksNamespace as aO, getWebSocketRealtimeClient as aP, increment as aQ, isFieldSentinel as aR, isIncrementSentinel as aS, isServerTimestampSentinel as aT, serverTimestamp as aU, verifyWebhookRequest as aV, verifyWebhookSignature as aW, type ProductNotificationSeverity as aa, type ProductPlan as ab, type ProductStatus as ac, type RealtimeTransport as ad, type RedirectCallbackResult as ae, type RegisterWebhookInput as af, type ResolvedConfig as ag, type SendNotificationInput as ah, type ServerTimestampSentinel as ai, type SignInOptions as aj, type SqlOptions as ak, type SupportNamespace as al, type SupportSeverity as am, type SupportStatus as an, type SupportTicket as ao, type SyncErrorEvent as ap, type SyncState as aq, type TelemetryEventAck as ar, type TelemetryEventInput as as, type TelemetryLogAck as at, type TelemetryLogInput as au, type Unsubscribe as av, type UsageEventInput as aw, type UsageNamespace as ax, type UsageQuota as ay, type VerifyTokenOptions as az, type AiChatOptions as b, type AiChatResult as c, type AiChatUsage as d, type AiContentPart as e, type AiImageUrlPart as f, type AiNamespace as g, type AiResponseFormat as h, type AiStreamHandle as i, type AiStreamMeta as j, type AiTextPart as k, type AuthNamespace as l, type AuthStateListener as m, type CatalogListResponse as n, type CheckoutAuthOpts as o, type CheckoutIntentInfo as p, type CheckoutIntentStatus as q, type CheckoutNamespace as r, type CheckoutStartInput as s, type CheckoutStartResult as t, type CheckoutTenantType as u, type CompleteSignInResult as v, type ConflictRecord as w, type CreateOfflineDocumentsOptions as x, type CreateTicketInput as y, type DbBatchOp as z };
2771
+ export { type NeetruDbEngine as $, type AiChatChoice as A, type DbChangeType as B, type CatalogListOptions as C, DEFAULT_BASE_URL as D, type DbCollectionRef$1 as E, type DbDoc as F, type DbDocRef as G, type DbGetResult as H, type DbListResult as I, type DbNamespace as J, type DbQuery$1 as K, type DbSqlLease as L, type DbWhereFilter as M, type DbWhereFilter$1 as N, type EndUserTokenProvider as O, type EntitlementCheck as P, type FieldSentinel as Q, type IncrementSentinel as R, type ListNotificationsOptions as S, MockCheckout as T, MockNotifications as U, MockWebhooks as V, NEETRU_SENTINEL_KEY as W, type NeetruClient as X, type NeetruClientConfig as Y, type NeetruDb as Z, type NeetruDbDocuments as _, type AiChatMessage as a, NeetruDbError as a0, type NeetruDbErrorCode as a1, type NeetruDbOptions as a2, type NeetruDbTransport as a3, type NeetruEnv as a4, type NeetruSqlClient as a5, type NeetruUser as a6, type NotificationScopeOptions as a7, type NotificationsNamespace as a8, type Product as a9, type VerifyTokenOptions as aA, type VerifyWebhookRequestOptions as aB, type VerifyWebhookRequestResult as aC, type WebhookEndpoint as aD, type WebhookEvent as aE, type WebhookScopeOptions as aF, type WebhookTestResult as aG, type WebhooksNamespace as aH, type WithFieldSentinels as aI, __resetDbIdWarningForTests as aJ, createAiNamespace as aK, createCheckoutNamespace as aL, createNeetruDb as aM, createNotificationsNamespace as aN, createRestSyncTransport as aO, createWebhooksNamespace as aP, getWebSocketRealtimeClient as aQ, increment as aR, isFieldSentinel as aS, isIncrementSentinel as aT, isServerTimestampSentinel as aU, serverTimestamp as aV, verifyWebhookRequest as aW, verifyWebhookSignature as aX, type ProductNotification as aa, type ProductNotificationSeverity as ab, type ProductPlan as ac, type ProductStatus as ad, type RealtimeTransport as ae, type RedirectCallbackResult as af, type RegisterWebhookInput as ag, type ResolvedConfig as ah, type SendNotificationInput as ai, type ServerTimestampSentinel as aj, type SignInOptions as ak, type SqlOptions as al, type SupportNamespace as am, type SupportSeverity as an, type SupportStatus as ao, type SupportTicket as ap, type SyncErrorEvent as aq, type SyncState as ar, type TelemetryEventAck as as, type TelemetryEventInput as at, type TelemetryLogAck as au, type TelemetryLogInput as av, type Unsubscribe as aw, type UsageEventInput as ax, type UsageNamespace as ay, type UsageQuota as az, type AiChatOptions as b, type AiChatResult as c, type AiChatUsage as d, type AiContentPart as e, type AiImageUrlPart as f, type AiNamespace as g, type AiResponseFormat as h, type AiStreamHandle as i, type AiStreamMeta as j, type AiTextPart as k, type AuthNamespace as l, type AuthStateListener as m, type CatalogListResponse as n, type CheckoutAuthOpts as o, type CheckoutIntentInfo as p, type CheckoutIntentStatus as q, type CheckoutNamespace as r, type CheckoutStartInput as s, type CheckoutStartResult as t, type CheckoutTenantType as u, type CompleteSignInResult as v, type ConflictRecord as w, type CreateOfflineDocumentsOptions as x, type CreateTicketInput as y, type DbBatchOp as z };