@neetru/sdk 3.6.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 (117) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +66 -1
  3. package/dist/ai.cjs +298 -391
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +298 -391
  7. package/dist/auth.cjs +3717 -5005
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +3714 -5002
  11. package/dist/build-guard.cjs +101 -119
  12. package/dist/build-guard.mjs +91 -109
  13. package/dist/catalog.cjs +220 -225
  14. package/dist/catalog.d.cts +1 -1
  15. package/dist/catalog.d.ts +1 -1
  16. package/dist/catalog.mjs +220 -225
  17. package/dist/checkout.cjs +307 -323
  18. package/dist/checkout.d.cts +1 -1
  19. package/dist/checkout.d.ts +1 -1
  20. package/dist/checkout.mjs +306 -322
  21. package/dist/db-react.cjs +59 -87
  22. package/dist/db-react.d.cts +1 -1
  23. package/dist/db-react.d.ts +1 -1
  24. package/dist/db-react.mjs +56 -84
  25. package/dist/db.cjs +2128 -3014
  26. package/dist/db.d.cts +1 -1
  27. package/dist/db.d.ts +1 -1
  28. package/dist/db.mjs +2141 -3027
  29. package/dist/entitlements.cjs +19 -20
  30. package/dist/entitlements.d.cts +1 -1
  31. package/dist/entitlements.d.ts +1 -1
  32. package/dist/entitlements.mjs +19 -20
  33. package/dist/errors.cjs +16 -12
  34. package/dist/errors.d.cts +59 -3
  35. package/dist/errors.d.ts +59 -3
  36. package/dist/errors.mjs +15 -12
  37. package/dist/firestore-compat.cjs +241 -297
  38. package/dist/firestore-compat.d.cts +1 -1
  39. package/dist/firestore-compat.d.ts +1 -1
  40. package/dist/firestore-compat.mjs +215 -271
  41. package/dist/index.cjs +3942 -5134
  42. package/dist/index.d.cts +181 -5
  43. package/dist/index.d.ts +181 -5
  44. package/dist/index.mjs +4040 -5239
  45. package/dist/mobile.cjs +459 -344
  46. package/dist/mobile.d.cts +59 -4
  47. package/dist/mobile.d.ts +59 -4
  48. package/dist/mobile.mjs +459 -344
  49. package/dist/mocks.cjs +319 -447
  50. package/dist/mocks.d.cts +1 -1
  51. package/dist/mocks.d.ts +1 -1
  52. package/dist/mocks.mjs +313 -441
  53. package/dist/notifications.cjs +296 -317
  54. package/dist/notifications.d.cts +1 -1
  55. package/dist/notifications.d.ts +1 -1
  56. package/dist/notifications.mjs +295 -316
  57. package/dist/react.cjs +557 -707
  58. package/dist/react.d.cts +1 -1
  59. package/dist/react.d.ts +1 -1
  60. package/dist/react.mjs +547 -697
  61. package/dist/support.cjs +402 -328
  62. package/dist/support.d.cts +29 -3
  63. package/dist/support.d.ts +29 -3
  64. package/dist/support.mjs +401 -328
  65. package/dist/telemetry.cjs +267 -304
  66. package/dist/telemetry.d.cts +1 -1
  67. package/dist/telemetry.d.ts +1 -1
  68. package/dist/telemetry.mjs +267 -304
  69. package/dist/{types-Du_iioJ7.d.cts → types-D-9bjlM0.d.cts} +74 -1
  70. package/dist/{types-BPATkXYu.d.ts → types-bVztFQTI.d.ts} +74 -1
  71. package/dist/usage.cjs +233 -230
  72. package/dist/usage.d.cts +1 -1
  73. package/dist/usage.d.ts +1 -1
  74. package/dist/usage.mjs +233 -230
  75. package/dist/webhooks.cjs +328 -362
  76. package/dist/webhooks.d.cts +1 -1
  77. package/dist/webhooks.d.ts +1 -1
  78. package/dist/webhooks.mjs +325 -359
  79. package/package.json +5 -3
  80. package/dist/ai.cjs.map +0 -1
  81. package/dist/ai.mjs.map +0 -1
  82. package/dist/auth.cjs.map +0 -1
  83. package/dist/auth.mjs.map +0 -1
  84. package/dist/build-guard.cjs.map +0 -1
  85. package/dist/build-guard.mjs.map +0 -1
  86. package/dist/catalog.cjs.map +0 -1
  87. package/dist/catalog.mjs.map +0 -1
  88. package/dist/checkout.cjs.map +0 -1
  89. package/dist/checkout.mjs.map +0 -1
  90. package/dist/db-react.cjs.map +0 -1
  91. package/dist/db-react.mjs.map +0 -1
  92. package/dist/db.cjs.map +0 -1
  93. package/dist/db.mjs.map +0 -1
  94. package/dist/entitlements.cjs.map +0 -1
  95. package/dist/entitlements.mjs.map +0 -1
  96. package/dist/errors.cjs.map +0 -1
  97. package/dist/errors.mjs.map +0 -1
  98. package/dist/firestore-compat.cjs.map +0 -1
  99. package/dist/firestore-compat.mjs.map +0 -1
  100. package/dist/index.cjs.map +0 -1
  101. package/dist/index.mjs.map +0 -1
  102. package/dist/mobile.cjs.map +0 -1
  103. package/dist/mobile.mjs.map +0 -1
  104. package/dist/mocks.cjs.map +0 -1
  105. package/dist/mocks.mjs.map +0 -1
  106. package/dist/notifications.cjs.map +0 -1
  107. package/dist/notifications.mjs.map +0 -1
  108. package/dist/react.cjs.map +0 -1
  109. package/dist/react.mjs.map +0 -1
  110. package/dist/support.cjs.map +0 -1
  111. package/dist/support.mjs.map +0 -1
  112. package/dist/telemetry.cjs.map +0 -1
  113. package/dist/telemetry.mjs.map +0 -1
  114. package/dist/usage.cjs.map +0 -1
  115. package/dist/usage.mjs.map +0 -1
  116. package/dist/webhooks.cjs.map +0 -1
  117. package/dist/webhooks.mjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/errors.ts
4
- var NeetruError = class _NeetruError extends Error {
4
+ var i = class t extends Error {
5
5
  code;
6
6
  status;
7
7
  requestId;
@@ -14,421 +14,400 @@ var NeetruError = class _NeetruError extends Error {
14
14
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
15
15
  */
16
16
  reason;
17
- constructor(code, message, status, requestId, reason) {
18
- super(message);
19
- this.name = "NeetruError";
20
- this.code = code;
21
- this.status = status;
22
- this.requestId = requestId;
23
- this.reason = reason;
24
- Object.setPrototypeOf(this, _NeetruError.prototype);
17
+ /**
18
+ * 3.8.0: `x-correlation-id` da requisição que falhou. O SDK gera um UUID por
19
+ * chamada (ou usa o que o chamador passou) e manda no header; o Core grava o
20
+ * mesmo id nos logs/auditoria — cite-o ao abrir um ticket de suporte.
21
+ * `undefined` em erros que acontecem antes de qualquer requisição.
22
+ */
23
+ correlationId;
24
+ constructor(e, r, n, o, s, d) {
25
+ super(r), this.name = "NeetruError", this.code = e, this.status = n, this.requestId = o, this.reason = s, this.correlationId = d, Object.setPrototypeOf(this, t.prototype);
25
26
  }
26
27
  };
27
28
 
28
29
  // src/idempotency.ts
29
- function generateIdempotencyKey() {
30
- const cryptoObj = typeof globalThis !== "undefined" && "crypto" in globalThis ? globalThis.crypto : void 0;
31
- if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
32
- return cryptoObj.randomUUID();
33
- }
34
- throw new NeetruError(
30
+ function x() {
31
+ let t = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
32
+ if (t && typeof t.randomUUID == "function")
33
+ return t.randomUUID();
34
+ throw new i(
35
35
  "runtime_unsupported",
36
36
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
37
37
  );
38
38
  }
39
39
 
40
+ // src/correlation.ts
41
+ var D = "x-correlation-id";
42
+ var B = /^[A-Za-z0-9._:\-]+$/;
43
+ function T(t) {
44
+ return typeof t == "string" && t.length > 0 && t.length <= 128 && B.test(t);
45
+ }
46
+ function G() {
47
+ let t = globalThis.crypto;
48
+ try {
49
+ if (t && typeof t.randomUUID == "function") return t.randomUUID();
50
+ } catch {
51
+ }
52
+ let e = new Uint8Array(16), r = false;
53
+ try {
54
+ t && typeof t.getRandomValues == "function" && (t.getRandomValues(e), r = !0);
55
+ } catch {
56
+ r = false;
57
+ }
58
+ if (!r)
59
+ for (let o = 0; o < e.length; o++) e[o] = Math.floor(Math.random() * 256);
60
+ e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
61
+ let n = Array.from(e, (o) => o.toString(16).padStart(2, "0")).join("");
62
+ return `${n.slice(0, 8)}-${n.slice(8, 12)}-${n.slice(12, 16)}-${n.slice(16, 20)}-${n.slice(20)}`;
63
+ }
64
+ function O(t, e) {
65
+ let r, n = {};
66
+ for (let [s, d] of Object.entries(t)) {
67
+ if (s.toLowerCase() === D) {
68
+ T(d) && (r = d);
69
+ continue;
70
+ }
71
+ n[s] = d;
72
+ }
73
+ let o = r ?? (T(e) ? e : void 0) ?? G();
74
+ return n[D] = o, { headers: n, correlationId: o };
75
+ }
76
+
77
+ // src/server-only-key.ts
78
+ function P() {
79
+ try {
80
+ let t = globalThis.navigator;
81
+ if (t && t.product === "ReactNative") return "react-native";
82
+ } catch {
83
+ }
84
+ try {
85
+ let t = globalThis;
86
+ if (typeof t.window < "u" && typeof t.document < "u") return "browser";
87
+ } catch {
88
+ }
89
+ return null;
90
+ }
91
+
40
92
  // src/http.ts
41
- var COMPAT_MATRIX = {
93
+ var X = {
42
94
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
43
95
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
44
96
  3: "2026.05.1"
45
97
  };
46
- function stripRevision(v) {
47
- return v.split("+")[0] ?? v;
98
+ function k(t) {
99
+ return t.split("+")[0] ?? t;
48
100
  }
49
- function compareCalVer(a, b) {
50
- const partsA = stripRevision(a).split(".").map(Number);
51
- const partsB = stripRevision(b).split(".").map(Number);
52
- const len = Math.max(partsA.length, partsB.length);
53
- for (let i = 0; i < len; i++) {
54
- const pa = partsA[i] ?? 0;
55
- const pb = partsB[i] ?? 0;
56
- if (pa !== pb) return pa - pb;
101
+ function Y(t, e) {
102
+ let r = k(t).split(".").map(Number), n = k(e).split(".").map(Number), o = Math.max(r.length, n.length);
103
+ for (let s = 0; s < o; s++) {
104
+ let d = r[s] ?? 0, u = n[s] ?? 0;
105
+ if (d !== u) return d - u;
57
106
  }
58
107
  return 0;
59
108
  }
60
- function readInjectedSdkVersion() {
109
+ function q() {
61
110
  try {
62
- return "3.6.0";
111
+ return "3.8.0";
63
112
  } catch {
64
- return void 0;
113
+ return;
65
114
  }
66
115
  }
67
- function getSdkMajor() {
68
- const ver = readInjectedSdkVersion();
69
- if (ver) return parseInt(ver.split(".")[0] ?? "3", 10);
70
- return 3;
116
+ function J() {
117
+ let t = q();
118
+ return t ? parseInt(t.split(".")[0] ?? "3", 10) : 3;
71
119
  }
72
- var _warnedCoreTooOld = /* @__PURE__ */ new Set();
73
- function checkCoreVersionCompat(coreVersion) {
74
- if (!coreVersion) return;
75
- const sdkMajor = getSdkMajor();
76
- const minCore = COMPAT_MATRIX[sdkMajor];
77
- if (!minCore) return;
78
- const stripped = stripRevision(coreVersion);
79
- if (compareCalVer(stripped, minCore) < 0) {
80
- const key = `${sdkMajor}:${stripped}`;
81
- if (!_warnedCoreTooOld.has(key)) {
82
- _warnedCoreTooOld.add(key);
83
- console.warn(
84
- `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${coreVersion}" \xE9 anterior ao m\xEDnimo recomendado "${minCore}" para SDK major ${sdkMajor}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
85
- );
86
- }
120
+ var C = /* @__PURE__ */ new Set();
121
+ function W(t) {
122
+ if (!t) return;
123
+ let e = J(), r = X[e];
124
+ if (!r) return;
125
+ let n = k(t);
126
+ if (Y(n, r) < 0) {
127
+ let o = `${e}:${n}`;
128
+ C.has(o) || (C.add(o), console.warn(
129
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${t}" \xE9 anterior ao m\xEDnimo recomendado "${r}" para SDK major ${e}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
130
+ ));
87
131
  }
88
132
  }
89
- var DEFAULT_RETRIES_READ = 2;
90
- var DEFAULT_RETRIES_WRITE = 0;
91
- var READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
92
- var RETRYABLE_CODES = /* @__PURE__ */ new Set([
133
+ function Z() {
134
+ let t = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
135
+ return P() ? "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. (" + t + ")" : t;
136
+ }
137
+ var Q = 2, ee = 0, te = /* @__PURE__ */ new Set(["GET", "HEAD"]), re = /* @__PURE__ */ new Set([
93
138
  "rate_limited",
94
139
  "server_error",
95
140
  "network_error"
96
141
  ]);
97
- function backoffMs(attempt) {
98
- const base = 200 * Math.pow(4, attempt);
99
- const jitter = base * 0.2 * (Math.random() * 2 - 1);
100
- return Math.max(50, Math.round(base + jitter));
142
+ function U(t) {
143
+ let e = 200 * Math.pow(4, t), r = e * 0.2 * (Math.random() * 2 - 1);
144
+ return Math.max(50, Math.round(e + r));
101
145
  }
102
- var MAX_RETRY_AFTER_MS = 6e4;
103
- function parseRetryAfter(value) {
104
- if (!value) return null;
105
- const secs = Number(value);
106
- if (Number.isFinite(secs) && secs >= 0) return Math.min(Math.round(secs * 1e3), MAX_RETRY_AFTER_MS);
107
- const dateMs = Date.parse(value);
108
- if (Number.isFinite(dateMs)) {
109
- const delta = dateMs - Date.now();
110
- if (delta > 0) return Math.min(delta, MAX_RETRY_AFTER_MS);
146
+ var M = 6e4;
147
+ function ne(t) {
148
+ if (!t) return null;
149
+ let e = Number(t);
150
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), M);
151
+ let r = Date.parse(t);
152
+ if (Number.isFinite(r)) {
153
+ let n = r - Date.now();
154
+ if (n > 0) return Math.min(n, M);
111
155
  }
112
156
  return null;
113
157
  }
114
- function sleep(ms) {
115
- return new Promise((resolve) => setTimeout(resolve, ms));
158
+ function $(t) {
159
+ return new Promise((e) => setTimeout(e, t));
116
160
  }
117
- function statusToCode(status) {
118
- if (status === 401) return "unauthorized";
119
- if (status === 403) return "forbidden";
120
- if (status === 404) return "not_found";
121
- if (status === 409) return "conflict";
122
- if (status === 422 || status === 400) return "validation_failed";
123
- if (status === 429) return "rate_limited";
124
- if (status >= 500) return "server_error";
125
- return "unknown";
161
+ function oe(t) {
162
+ return t === 401 ? "unauthorized" : t === 403 ? "forbidden" : t === 404 ? "not_found" : t === 409 ? "conflict" : t === 410 ? "gone" : t === 422 || t === 400 ? "validation_failed" : t === 429 ? "rate_limited" : t >= 500 ? "server_error" : "unknown";
126
163
  }
127
- function buildUrl(baseUrl, path, query) {
128
- const base = baseUrl.replace(/\/+$/, "");
129
- const p = path.startsWith("/") ? path : `/${path}`;
130
- const url = new URL(`${base}${p}`);
131
- if (query) {
132
- for (const [k, v] of Object.entries(query)) {
133
- if (v === void 0) continue;
134
- url.searchParams.set(k, String(v));
164
+ function ie(t, e, r) {
165
+ let n = t.replace(/\/+$/, ""), o = e.startsWith("/") ? e : `/${e}`, s = new URL(`${n}${o}`);
166
+ if (r)
167
+ for (let [d, u] of Object.entries(r))
168
+ u !== void 0 && s.searchParams.set(d, String(u));
169
+ return s.toString();
170
+ }
171
+ async function K(t) {
172
+ let e = await t.text();
173
+ if (e)
174
+ try {
175
+ return JSON.parse(e);
176
+ } catch {
177
+ return;
135
178
  }
136
- }
137
- return url.toString();
138
179
  }
139
- async function safeJson(res) {
140
- const text = await res.text();
141
- if (!text) return void 0;
142
- try {
143
- return JSON.parse(text);
144
- } catch {
145
- return void 0;
180
+ async function h(t, e) {
181
+ let r = e.method ?? "GET", n = ie(t.baseUrl, e.path, e.query), o = te.has(r) ? Q : ee, s = e.retries ?? o, { headers: d, correlationId: u } = O(
182
+ { accept: "application/json", ...e.headers },
183
+ e.correlationId
184
+ ), E = q();
185
+ if (E && (d["x-neetru-sdk-version"] = E), e.requireAuth) {
186
+ if (!t.apiKey)
187
+ throw new i("missing_api_key", Z());
188
+ d.authorization = `Bearer ${t.apiKey}`;
146
189
  }
147
- }
148
- async function httpRequest(config, opts) {
149
- const method = opts.method ?? "GET";
150
- const url = buildUrl(config.baseUrl, opts.path, opts.query);
151
- const defaultRetries = READ_METHODS.has(method) ? DEFAULT_RETRIES_READ : DEFAULT_RETRIES_WRITE;
152
- const maxRetries = opts.retries ?? defaultRetries;
153
- const headers = {
154
- accept: "application/json",
155
- ...opts.headers
156
- };
157
- const sdkVersion = readInjectedSdkVersion();
158
- if (sdkVersion) {
159
- headers["x-neetru-sdk-version"] = sdkVersion;
190
+ if (e.idempotencyKey) {
191
+ let p = typeof e.idempotencyKey == "string" ? e.idempotencyKey : x();
192
+ d["idempotency-key"] = p;
160
193
  }
161
- if (opts.requireAuth) {
162
- if (!config.apiKey) {
163
- throw new NeetruError(
164
- "missing_api_key",
165
- "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
194
+ let b = e.body !== void 0 && r !== "GET" && r !== "DELETE" ? JSON.stringify(e.body) : void 0;
195
+ b !== void 0 && (d["content-type"] = "application/json");
196
+ let g = null, l = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
197
+ for (let p = 0; p <= s; p++) {
198
+ if (l != null && Date.now() >= l)
199
+ throw g ?? new i(
200
+ "network_error",
201
+ "Deadline excedido antes de completar a request",
202
+ void 0,
203
+ void 0,
204
+ void 0,
205
+ u
166
206
  );
167
- }
168
- headers.authorization = `Bearer ${config.apiKey}`;
169
- }
170
- if (opts.idempotencyKey) {
171
- const key = typeof opts.idempotencyKey === "string" ? opts.idempotencyKey : generateIdempotencyKey();
172
- headers["idempotency-key"] = key;
173
- }
174
- const bodyString = opts.body !== void 0 && method !== "GET" && method !== "DELETE" ? JSON.stringify(opts.body) : void 0;
175
- if (bodyString !== void 0) {
176
- headers["content-type"] = "application/json";
177
- }
178
- let lastError = null;
179
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
180
- const init = { method, headers };
181
- if (bodyString !== void 0) init.body = bodyString;
182
- init.signal = AbortSignal.timeout(3e4);
183
- let res;
207
+ let v = { method: r, headers: d };
208
+ b !== void 0 && (v.body = b);
209
+ let z = l != null ? Math.max(1, Math.min(3e4, l - Date.now())) : 3e4;
210
+ v.signal = AbortSignal.timeout(z);
211
+ let c;
184
212
  try {
185
- res = await config.fetch(url, init);
186
- } catch (err2) {
187
- const message2 = err2 instanceof DOMException && err2.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${err2 instanceof Error ? err2.message : "fetch failed"}`;
188
- lastError = new NeetruError("network_error", message2);
189
- if (attempt < maxRetries) {
190
- await sleep(backoffMs(attempt));
191
- continue;
213
+ c = await t.fetch(n, v);
214
+ } catch (a) {
215
+ let y = a instanceof DOMException && a.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${a instanceof Error ? a.message : "fetch failed"}`;
216
+ if (g = new i("network_error", y, void 0, void 0, void 0, u), p < s) {
217
+ let A = U(p);
218
+ if (l == null || Date.now() + A < l) {
219
+ await $(A);
220
+ continue;
221
+ }
192
222
  }
193
- throw lastError;
223
+ throw g;
194
224
  }
195
- const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-correlation-id") ?? void 0;
196
- if (res.ok) {
197
- const coreVersion = res.headers.get("x-neetru-version");
198
- if (coreVersion) checkCoreVersionCompat(coreVersion);
199
- const parsed = await safeJson(res);
200
- return parsed;
225
+ let F = c.headers.get("x-request-id") ?? c.headers.get("x-correlation-id") ?? void 0;
226
+ if (c.ok) {
227
+ let a = c.headers.get("x-neetru-version");
228
+ return a && W(a), await K(c);
201
229
  }
202
- const body = await safeJson(res);
203
- let code = statusToCode(res.status);
204
- let message = `HTTP ${res.status}`;
205
- let reason;
206
- if (body && typeof body === "object") {
207
- const errField = body.error;
208
- if (typeof errField === "string") {
209
- message = errField;
210
- } else if (errField && typeof errField === "object") {
211
- if (typeof errField.code === "string") code = errField.code;
212
- if (typeof errField.message === "string") message = errField.message;
213
- if (typeof errField.reason === "string") reason = errField.reason;
214
- } else {
215
- if (typeof body.code === "string") code = body.code;
216
- if (typeof body.message === "string") message = body.message;
217
- }
218
- if (typeof body.reason === "string") reason = body.reason;
230
+ let f = await K(c), _ = oe(c.status), m = `HTTP ${c.status}`, I;
231
+ if (f && typeof f == "object") {
232
+ let a = f.error;
233
+ typeof a == "string" ? m = a : a && typeof a == "object" ? (typeof a.code == "string" && (_ = a.code), typeof a.message == "string" && (m = a.message), typeof a.reason == "string" && (I = a.reason)) : (typeof f.code == "string" && (_ = f.code), typeof f.message == "string" && (m = f.message)), typeof f.reason == "string" && (I = f.reason);
219
234
  }
220
- const err = new NeetruError(code, message, res.status, requestId, reason);
221
- lastError = err;
222
- const isRetryable = RETRYABLE_CODES.has(code);
223
- if (isRetryable && attempt < maxRetries) {
224
- const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
225
- const delay = retryAfter ?? backoffMs(attempt);
226
- await sleep(delay);
227
- continue;
235
+ if (c.status === 410) {
236
+ let a = c.headers.get("x-neetru-replacement");
237
+ m === `HTTP ${c.status}` && (m = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), a && !m.includes(a) && (m += ` Substituto: ${a}.`);
228
238
  }
229
- throw err;
239
+ let S = new i(_, m, c.status, F, I, u);
240
+ if (g = S, re.has(_) && p < s) {
241
+ let y = ne(c.headers.get("retry-after")) ?? U(p);
242
+ if (l == null || Date.now() + y < l) {
243
+ await $(y);
244
+ continue;
245
+ }
246
+ }
247
+ throw S;
230
248
  }
231
- throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
249
+ throw g ?? new i("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, u);
232
250
  }
233
251
 
234
252
  // src/validators.ts
235
- var SDK_ID_RE = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
236
- function assertValidSdkId(field, value) {
237
- if (typeof value !== "string" || !SDK_ID_RE.test(value)) {
238
- throw new NeetruError(
253
+ var L = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
254
+ function N(t, e) {
255
+ if (typeof e != "string" || !L.test(e))
256
+ throw new i(
239
257
  "validation_failed",
240
- `${field} must match ${SDK_ID_RE.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
258
+ `${t} must match ${L.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
241
259
  );
242
- }
243
260
  }
244
261
 
245
262
  // src/notifications.ts
246
- var VALID_SEVERITIES = [
263
+ var R = [
247
264
  "info",
248
265
  "success",
249
266
  "warning",
250
267
  "error"
251
268
  ];
252
- function toNotification(raw) {
253
- if (!raw || typeof raw !== "object") {
254
- throw new NeetruError("invalid_response", "Notification response is not an object");
255
- }
256
- const r = raw;
257
- if (typeof r.id !== "string") {
258
- throw new NeetruError("invalid_response", "Notification missing id");
259
- }
260
- const sev = VALID_SEVERITIES.includes(r.severity) ? r.severity : "info";
269
+ function j(t) {
270
+ if (!t || typeof t != "object")
271
+ throw new i("invalid_response", "Notification response is not an object");
272
+ let e = t;
273
+ if (typeof e.id != "string")
274
+ throw new i("invalid_response", "Notification missing id");
275
+ let r = R.includes(e.severity) ? e.severity : "info";
261
276
  return {
262
- id: r.id,
263
- userId: typeof r.userId === "string" ? r.userId : "",
264
- kind: typeof r.kind === "string" ? r.kind : "unknown",
265
- severity: sev,
266
- title: typeof r.title === "string" ? r.title : "",
267
- body: typeof r.body === "string" ? r.body : void 0,
268
- link: typeof r.link === "string" ? r.link : void 0,
269
- metadata: r.metadata && typeof r.metadata === "object" ? r.metadata : void 0,
270
- createdAt: typeof r.createdAt === "string" ? r.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
271
- readAt: typeof r.readAt === "string" ? r.readAt : void 0,
272
- dismissedAt: typeof r.dismissedAt === "string" ? r.dismissedAt : void 0
277
+ id: e.id,
278
+ userId: typeof e.userId == "string" ? e.userId : "",
279
+ kind: typeof e.kind == "string" ? e.kind : "unknown",
280
+ severity: r,
281
+ title: typeof e.title == "string" ? e.title : "",
282
+ body: typeof e.body == "string" ? e.body : void 0,
283
+ link: typeof e.link == "string" ? e.link : void 0,
284
+ metadata: e.metadata && typeof e.metadata == "object" ? e.metadata : void 0,
285
+ createdAt: typeof e.createdAt == "string" ? e.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
286
+ readAt: typeof e.readAt == "string" ? e.readAt : void 0,
287
+ dismissedAt: typeof e.dismissedAt == "string" ? e.dismissedAt : void 0
273
288
  };
274
289
  }
275
- function validateInput(input) {
276
- if (!input.userId) throw new NeetruError("validation_failed", "userId obrigat\xF3rio");
277
- if (!input.kind) throw new NeetruError("validation_failed", "kind obrigat\xF3rio");
278
- if (!input.title) throw new NeetruError("validation_failed", "title obrigat\xF3rio");
279
- if (input.severity && !VALID_SEVERITIES.includes(input.severity)) {
280
- throw new NeetruError(
290
+ function H(t) {
291
+ if (!t.userId) throw new i("validation_failed", "userId obrigat\xF3rio");
292
+ if (!t.kind) throw new i("validation_failed", "kind obrigat\xF3rio");
293
+ if (!t.title) throw new i("validation_failed", "title obrigat\xF3rio");
294
+ if (t.severity && !R.includes(t.severity))
295
+ throw new i(
281
296
  "validation_failed",
282
- `severity inv\xE1lida: ${input.severity} (use ${VALID_SEVERITIES.join("|")})`
297
+ `severity inv\xE1lida: ${t.severity} (use ${R.join("|")})`
283
298
  );
284
- }
285
- if (input.title.length > 200) {
286
- throw new NeetruError("validation_failed", "title m\xE1x 200 chars");
287
- }
288
- if (input.body && input.body.length > 2e3) {
289
- throw new NeetruError("validation_failed", "body m\xE1x 2000 chars");
290
- }
299
+ if (t.title.length > 200)
300
+ throw new i("validation_failed", "title m\xE1x 200 chars");
301
+ if (t.body && t.body.length > 2e3)
302
+ throw new i("validation_failed", "body m\xE1x 2000 chars");
291
303
  }
292
- function resolveProductId(config, ...candidates) {
293
- for (const c of candidates) {
294
- if (typeof c === "string" && c.length > 0) {
295
- assertValidSdkId("productId", c);
296
- return c;
297
- }
298
- }
299
- if (config.productId) {
300
- assertValidSdkId("productId", config.productId);
301
- return config.productId;
302
- }
303
- throw new NeetruError(
304
+ function w(t, ...e) {
305
+ for (let r of e)
306
+ if (typeof r == "string" && r.length > 0)
307
+ return N("productId", r), r;
308
+ if (t.productId)
309
+ return N("productId", t.productId), t.productId;
310
+ throw new i(
304
311
  "validation_failed",
305
312
  "productId required (pass to options/input or set on createNeetruClient)"
306
313
  );
307
314
  }
308
- function createNotificationsNamespace(config) {
315
+ function Ie(t) {
309
316
  return {
310
- async send(input) {
311
- validateInput(input);
312
- const productId = resolveProductId(config, input.productId);
313
- const body = {
314
- productId,
315
- userId: input.userId,
316
- kind: input.kind,
317
- title: input.title,
318
- severity: input.severity ?? "info"
317
+ async send(e) {
318
+ H(e);
319
+ let n = {
320
+ productId: w(t, e.productId),
321
+ userId: e.userId,
322
+ kind: e.kind,
323
+ title: e.title,
324
+ severity: e.severity ?? "info"
319
325
  };
320
- if (input.body !== void 0) body.body = input.body;
321
- if (input.link !== void 0) body.link = input.link;
322
- if (input.metadata !== void 0) body.metadata = input.metadata;
323
- if (input.fingerprint !== void 0) body.fingerprint = input.fingerprint;
324
- const raw = await httpRequest(config, {
326
+ e.body !== void 0 && (n.body = e.body), e.link !== void 0 && (n.link = e.link), e.metadata !== void 0 && (n.metadata = e.metadata), e.fingerprint !== void 0 && (n.fingerprint = e.fingerprint);
327
+ let o = await h(t, {
325
328
  method: "POST",
326
329
  path: "/api/sdk/v1/notifications",
327
- body,
330
+ body: n,
328
331
  requireAuth: true,
329
332
  idempotencyKey: true
330
333
  });
331
- return toNotification(raw);
334
+ return j(o);
332
335
  },
333
- async list(userId, options) {
334
- if (!userId) throw new NeetruError("validation_failed", "userId obrigat\xF3rio");
335
- const productId = resolveProductId(config, options?.productId);
336
- const query = {
337
- productId
336
+ async list(e, r) {
337
+ if (!e) throw new i("validation_failed", "userId obrigat\xF3rio");
338
+ let o = {
339
+ productId: w(t, r?.productId)
338
340
  };
339
- if (options?.includeDismissed) query.includeDismissed = true;
340
- if (options?.onlyUnread) query.onlyUnread = true;
341
- if (options?.limit) {
342
- query.limit = Math.min(Math.max(1, options.limit), 200);
343
- }
344
- const raw = await httpRequest(config, {
341
+ r?.includeDismissed && (o.includeDismissed = true), r?.onlyUnread && (o.onlyUnread = true), r?.limit && (o.limit = Math.min(Math.max(1, r.limit), 200));
342
+ let s = await h(t, {
345
343
  method: "GET",
346
- path: `/api/sdk/v1/notifications/user/${encodeURIComponent(userId)}`,
347
- query,
344
+ path: `/api/sdk/v1/notifications/user/${encodeURIComponent(e)}`,
345
+ query: o,
348
346
  requireAuth: true
349
347
  });
350
- const list = Array.isArray(raw?.notifications) ? raw.notifications : [];
351
- return list.map(toNotification);
348
+ return (Array.isArray(s?.notifications) ? s.notifications : []).map(j);
352
349
  },
353
- async markRead(id, options) {
354
- if (!id) throw new NeetruError("validation_failed", "id obrigat\xF3rio");
355
- const productId = resolveProductId(config, options?.productId);
356
- await httpRequest(config, {
350
+ async markRead(e, r) {
351
+ if (!e) throw new i("validation_failed", "id obrigat\xF3rio");
352
+ let n = w(t, r?.productId);
353
+ return await h(t, {
357
354
  method: "POST",
358
- path: `/api/sdk/v1/notifications/${encodeURIComponent(id)}/read`,
359
- query: { productId },
355
+ path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/read`,
356
+ query: { productId: n },
360
357
  requireAuth: true
361
- });
362
- return { ok: true };
358
+ }), { ok: true };
363
359
  },
364
- async dismiss(id, options) {
365
- if (!id) throw new NeetruError("validation_failed", "id obrigat\xF3rio");
366
- const productId = resolveProductId(config, options?.productId);
367
- await httpRequest(config, {
360
+ async dismiss(e, r) {
361
+ if (!e) throw new i("validation_failed", "id obrigat\xF3rio");
362
+ let n = w(t, r?.productId);
363
+ return await h(t, {
368
364
  method: "POST",
369
- path: `/api/sdk/v1/notifications/${encodeURIComponent(id)}/dismiss`,
370
- query: { productId },
365
+ path: `/api/sdk/v1/notifications/${encodeURIComponent(e)}/dismiss`,
366
+ query: { productId: n },
371
367
  requireAuth: true
372
- });
373
- return { ok: true };
368
+ }), { ok: true };
374
369
  }
375
370
  };
376
371
  }
377
- var MockNotifications = class {
372
+ var V = class {
378
373
  notifications = /* @__PURE__ */ new Map();
379
374
  nextId = 1;
380
- async send(input) {
381
- validateInput(input);
382
- if (input.fingerprint) {
383
- const dayAgo = Date.now() - 864e5;
384
- for (const existing of this.notifications.values()) {
385
- const meta = existing.metadata ?? {};
386
- if (meta.fingerprint === input.fingerprint && existing.userId === input.userId && new Date(existing.createdAt).getTime() > dayAgo) {
387
- return existing;
388
- }
389
- }
375
+ async send(e) {
376
+ if (H(e), e.fingerprint) {
377
+ let o = Date.now() - 864e5;
378
+ for (let s of this.notifications.values())
379
+ if ((s.metadata ?? {}).fingerprint === e.fingerprint && s.userId === e.userId && new Date(s.createdAt).getTime() > o)
380
+ return s;
390
381
  }
391
- const id = `mock_notif_${this.nextId++}`;
392
- const notif = {
393
- id,
394
- userId: input.userId,
395
- kind: input.kind,
396
- severity: input.severity ?? "info",
397
- title: input.title,
398
- body: input.body,
399
- link: input.link,
400
- metadata: input.fingerprint ? { ...input.metadata ?? {}, fingerprint: input.fingerprint } : input.metadata,
382
+ let r = `mock_notif_${this.nextId++}`, n = {
383
+ id: r,
384
+ userId: e.userId,
385
+ kind: e.kind,
386
+ severity: e.severity ?? "info",
387
+ title: e.title,
388
+ body: e.body,
389
+ link: e.link,
390
+ metadata: e.fingerprint ? { ...e.metadata ?? {}, fingerprint: e.fingerprint } : e.metadata,
401
391
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
402
392
  };
403
- this.notifications.set(id, notif);
404
- return notif;
393
+ return this.notifications.set(r, n), n;
405
394
  }
406
- async list(userId, options) {
407
- if (!userId) throw new NeetruError("validation_failed", "userId obrigat\xF3rio");
408
- const limit = Math.min(Math.max(1, options?.limit ?? 50), 200);
409
- return [...this.notifications.values()].filter((n) => n.userId === userId).filter((n) => options?.includeDismissed || !n.dismissedAt).filter((n) => !options?.onlyUnread || !n.readAt).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, limit);
395
+ async list(e, r) {
396
+ if (!e) throw new i("validation_failed", "userId obrigat\xF3rio");
397
+ let n = Math.min(Math.max(1, r?.limit ?? 50), 200);
398
+ return [...this.notifications.values()].filter((o) => o.userId === e).filter((o) => r?.includeDismissed || !o.dismissedAt).filter((o) => !r?.onlyUnread || !o.readAt).sort((o, s) => s.createdAt.localeCompare(o.createdAt)).slice(0, n);
410
399
  }
411
- async markRead(id, _options) {
412
- const n = this.notifications.get(id);
413
- if (!n) throw new NeetruError("not_found", `Notification ${id} n\xE3o encontrada`);
414
- if (!n.readAt) {
415
- n.readAt = (/* @__PURE__ */ new Date()).toISOString();
416
- this.notifications.set(id, n);
417
- }
418
- return { ok: true };
400
+ async markRead(e, r) {
401
+ let n = this.notifications.get(e);
402
+ if (!n) throw new i("not_found", `Notification ${e} n\xE3o encontrada`);
403
+ return n.readAt || (n.readAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, n)), { ok: true };
419
404
  }
420
- async dismiss(id, _options) {
421
- const n = this.notifications.get(id);
422
- if (!n) throw new NeetruError("not_found", `Notification ${id} n\xE3o encontrada`);
423
- if (!n.dismissedAt) {
424
- n.dismissedAt = (/* @__PURE__ */ new Date()).toISOString();
425
- this.notifications.set(id, n);
426
- }
427
- return { ok: true };
405
+ async dismiss(e, r) {
406
+ let n = this.notifications.get(e);
407
+ if (!n) throw new i("not_found", `Notification ${e} n\xE3o encontrada`);
408
+ return n.dismissedAt || (n.dismissedAt = (/* @__PURE__ */ new Date()).toISOString(), this.notifications.set(e, n)), { ok: true };
428
409
  }
429
410
  };
430
411
 
431
- exports.MockNotifications = MockNotifications;
432
- exports.createNotificationsNamespace = createNotificationsNamespace;
433
- //# sourceMappingURL=notifications.cjs.map
434
- //# sourceMappingURL=notifications.cjs.map
412
+ exports.MockNotifications = V;
413
+ exports.createNotificationsNamespace = Ie;