@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
package/dist/support.cjs CHANGED
@@ -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 e extends Error {
5
5
  code;
6
6
  status;
7
7
  requestId;
@@ -14,293 +14,391 @@ 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(t, r, o, s, u, c) {
25
+ super(r), this.name = "NeetruError", this.code = t, this.status = o, this.requestId = s, this.reason = u, this.correlationId = c, Object.setPrototypeOf(this, e.prototype);
26
+ }
27
+ }, _ = class e extends i {
28
+ constructor(t, r, o, s, u) {
29
+ super("auth_required", t, o, s, r, u), this.name = "NeetruAuthRequiredError", Object.setPrototypeOf(this, e.prototype);
25
30
  }
26
31
  };
27
32
 
28
33
  // 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(
34
+ function C() {
35
+ let e = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
36
+ if (e && typeof e.randomUUID == "function")
37
+ return e.randomUUID();
38
+ throw new i(
35
39
  "runtime_unsupported",
36
40
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
37
41
  );
38
42
  }
39
43
 
44
+ // src/correlation.ts
45
+ var D = "x-correlation-id";
46
+ var Y = /^[A-Za-z0-9._:\-]+$/;
47
+ function U(e) {
48
+ return typeof e == "string" && e.length > 0 && e.length <= 128 && Y.test(e);
49
+ }
50
+ function J() {
51
+ let e = globalThis.crypto;
52
+ try {
53
+ if (e && typeof e.randomUUID == "function") return e.randomUUID();
54
+ } catch {
55
+ }
56
+ let t = new Uint8Array(16), r = false;
57
+ try {
58
+ e && typeof e.getRandomValues == "function" && (e.getRandomValues(t), r = !0);
59
+ } catch {
60
+ r = false;
61
+ }
62
+ if (!r)
63
+ for (let s = 0; s < t.length; s++) t[s] = Math.floor(Math.random() * 256);
64
+ t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128;
65
+ let o = Array.from(t, (s) => s.toString(16).padStart(2, "0")).join("");
66
+ return `${o.slice(0, 8)}-${o.slice(8, 12)}-${o.slice(12, 16)}-${o.slice(16, 20)}-${o.slice(20)}`;
67
+ }
68
+ function x(e, t) {
69
+ let r, o = {};
70
+ for (let [u, c] of Object.entries(e)) {
71
+ if (u.toLowerCase() === D) {
72
+ U(c) && (r = c);
73
+ continue;
74
+ }
75
+ o[u] = c;
76
+ }
77
+ let s = r ?? (U(t) ? t : void 0) ?? J();
78
+ return o[D] = s, { headers: o, correlationId: s };
79
+ }
80
+
81
+ // src/server-only-key.ts
82
+ function O() {
83
+ try {
84
+ let e = globalThis.navigator;
85
+ if (e && e.product === "ReactNative") return "react-native";
86
+ } catch {
87
+ }
88
+ try {
89
+ let e = globalThis;
90
+ if (typeof e.window < "u" && typeof e.document < "u") return "browser";
91
+ } catch {
92
+ }
93
+ return null;
94
+ }
95
+
40
96
  // src/http.ts
41
- var COMPAT_MATRIX = {
97
+ var W = {
42
98
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
43
99
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
44
100
  3: "2026.05.1"
45
101
  };
46
- function stripRevision(v) {
47
- return v.split("+")[0] ?? v;
102
+ function A(e) {
103
+ return e.split("+")[0] ?? e;
48
104
  }
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;
105
+ function Q(e, t) {
106
+ let r = A(e).split(".").map(Number), o = A(t).split(".").map(Number), s = Math.max(r.length, o.length);
107
+ for (let u = 0; u < s; u++) {
108
+ let c = r[u] ?? 0, n = o[u] ?? 0;
109
+ if (c !== n) return c - n;
57
110
  }
58
111
  return 0;
59
112
  }
60
- function readInjectedSdkVersion() {
113
+ function $() {
61
114
  try {
62
- return "3.6.0";
115
+ return "3.8.0";
63
116
  } catch {
64
- return void 0;
117
+ return;
65
118
  }
66
119
  }
67
- function getSdkMajor() {
68
- const ver = readInjectedSdkVersion();
69
- if (ver) return parseInt(ver.split(".")[0] ?? "3", 10);
70
- return 3;
120
+ function Z() {
121
+ let e = $();
122
+ return e ? parseInt(e.split(".")[0] ?? "3", 10) : 3;
71
123
  }
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
- }
124
+ var M = /* @__PURE__ */ new Set();
125
+ function ee(e) {
126
+ if (!e) return;
127
+ let t = Z(), r = W[t];
128
+ if (!r) return;
129
+ let o = A(e);
130
+ if (Q(o, r) < 0) {
131
+ let s = `${t}:${o}`;
132
+ M.has(s) || (M.add(s), console.warn(
133
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${e}" \xE9 anterior ao m\xEDnimo recomendado "${r}" para SDK major ${t}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
134
+ ));
87
135
  }
88
136
  }
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([
137
+ function te() {
138
+ let e = "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.";
139
+ return O() ? "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;
140
+ }
141
+ var ne = 2, re = 0, oe = /* @__PURE__ */ new Set(["GET", "HEAD"]), ie = /* @__PURE__ */ new Set([
93
142
  "rate_limited",
94
143
  "server_error",
95
144
  "network_error"
96
145
  ]);
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));
146
+ function P(e) {
147
+ let t = 200 * Math.pow(4, e), r = t * 0.2 * (Math.random() * 2 - 1);
148
+ return Math.max(50, Math.round(t + r));
101
149
  }
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);
150
+ var q = 6e4;
151
+ function se(e) {
152
+ if (!e) return null;
153
+ let t = Number(e);
154
+ if (Number.isFinite(t) && t >= 0) return Math.min(Math.round(t * 1e3), q);
155
+ let r = Date.parse(e);
156
+ if (Number.isFinite(r)) {
157
+ let o = r - Date.now();
158
+ if (o > 0) return Math.min(o, q);
111
159
  }
112
160
  return null;
113
161
  }
114
- function sleep(ms) {
115
- return new Promise((resolve) => setTimeout(resolve, ms));
162
+ function K(e) {
163
+ return new Promise((t) => setTimeout(t, e));
116
164
  }
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";
165
+ function ae(e) {
166
+ 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";
126
167
  }
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));
168
+ function de(e, t, r) {
169
+ let o = e.replace(/\/+$/, ""), s = t.startsWith("/") ? t : `/${t}`, u = new URL(`${o}${s}`);
170
+ if (r)
171
+ for (let [c, n] of Object.entries(r))
172
+ n !== void 0 && u.searchParams.set(c, String(n));
173
+ return u.toString();
174
+ }
175
+ async function j(e) {
176
+ let t = await e.text();
177
+ if (t)
178
+ try {
179
+ return JSON.parse(t);
180
+ } catch {
181
+ return;
135
182
  }
136
- }
137
- return url.toString();
138
183
  }
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;
184
+ async function v(e, t) {
185
+ let r = t.method ?? "GET", o = de(e.baseUrl, t.path, t.query), s = oe.has(r) ? ne : re, u = t.retries ?? s, { headers: c, correlationId: n } = x(
186
+ { accept: "application/json", ...t.headers },
187
+ t.correlationId
188
+ ), g = $();
189
+ if (g && (c["x-neetru-sdk-version"] = g), t.requireAuth) {
190
+ if (!e.apiKey)
191
+ throw new i("missing_api_key", te());
192
+ c.authorization = `Bearer ${e.apiKey}`;
146
193
  }
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;
194
+ if (t.idempotencyKey) {
195
+ let p = typeof t.idempotencyKey == "string" ? t.idempotencyKey : C();
196
+ c["idempotency-key"] = p;
160
197
  }
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."
198
+ let a = t.body !== void 0 && r !== "GET" && r !== "DELETE" ? JSON.stringify(t.body) : void 0;
199
+ a !== void 0 && (c["content-type"] = "application/json");
200
+ let l = null, f = t.deadlineMs != null ? Date.now() + t.deadlineMs : null;
201
+ for (let p = 0; p <= u; p++) {
202
+ if (f != null && Date.now() >= f)
203
+ throw l ?? new i(
204
+ "network_error",
205
+ "Deadline excedido antes de completar a request",
206
+ void 0,
207
+ void 0,
208
+ void 0,
209
+ n
166
210
  );
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;
211
+ let E = { method: r, headers: c };
212
+ a !== void 0 && (E.body = a);
213
+ let z = f != null ? Math.max(1, Math.min(3e4, f - Date.now())) : 3e4;
214
+ E.signal = AbortSignal.timeout(z);
215
+ let m;
184
216
  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;
217
+ m = await e.fetch(o, E);
218
+ } catch (d) {
219
+ let w = d instanceof DOMException && d.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${d instanceof Error ? d.message : "fetch failed"}`;
220
+ if (l = new i("network_error", w, void 0, void 0, void 0, n), p < u) {
221
+ let N = P(p);
222
+ if (f == null || Date.now() + N < f) {
223
+ await K(N);
224
+ continue;
225
+ }
192
226
  }
193
- throw lastError;
227
+ throw l;
194
228
  }
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;
229
+ let X = m.headers.get("x-request-id") ?? m.headers.get("x-correlation-id") ?? void 0;
230
+ if (m.ok) {
231
+ let d = m.headers.get("x-neetru-version");
232
+ return d && ee(d), await j(m);
201
233
  }
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;
234
+ let y = await j(m), k = ae(m.status), h = `HTTP ${m.status}`, S;
235
+ if (y && typeof y == "object") {
236
+ let d = y.error;
237
+ typeof d == "string" ? h = d : d && typeof d == "object" ? (typeof d.code == "string" && (k = d.code), typeof d.message == "string" && (h = d.message), typeof d.reason == "string" && (S = d.reason)) : (typeof y.code == "string" && (k = y.code), typeof y.message == "string" && (h = y.message)), typeof y.reason == "string" && (S = y.reason);
219
238
  }
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;
239
+ if (m.status === 410) {
240
+ let d = m.headers.get("x-neetru-replacement");
241
+ h === `HTTP ${m.status}` && (h = `Endpoint ${t.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), d && !h.includes(d) && (h += ` Substituto: ${d}.`);
228
242
  }
229
- throw err;
243
+ let T = new i(k, h, m.status, X, S, n);
244
+ if (l = T, ie.has(k) && p < u) {
245
+ let w = se(m.headers.get("retry-after")) ?? P(p);
246
+ if (f == null || Date.now() + w < f) {
247
+ await K(w);
248
+ continue;
249
+ }
250
+ }
251
+ throw T;
230
252
  }
231
- throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
253
+ throw l ?? new i("unknown", "unexpected httpRequest exit", void 0, void 0, void 0, n);
232
254
  }
233
255
 
234
256
  // 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(
257
+ var L = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
258
+ function I(e, t) {
259
+ if (typeof t != "string" || !L.test(t))
260
+ throw new i(
239
261
  "validation_failed",
240
- `${field} must match ${SDK_ID_RE.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
262
+ `${e} must match ${L.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
241
263
  );
242
- }
243
264
  }
244
265
 
245
266
  // src/support.ts
246
- var VALID_SEVERITIES = ["low", "normal", "high", "urgent"];
247
- var VALID_STATUSES = ["open", "pending", "resolved", "closed"];
248
- function toTicket(raw) {
249
- if (!raw || typeof raw !== "object") {
250
- throw new NeetruError("invalid_response", "Ticket response is not an object");
251
- }
252
- const r = raw;
253
- if (typeof r.id !== "string") {
254
- throw new NeetruError("invalid_response", "Ticket missing id");
255
- }
256
- const firstAttachment = Array.isArray(r.attachments) && typeof r.attachments[0] === "string" ? r.attachments[0] : void 0;
267
+ var R = ["low", "normal", "high", "urgent"], ue = ["open", "pending", "resolved", "closed"], V = 50;
268
+ function F(e) {
269
+ if (!e || typeof e != "object")
270
+ throw new i("invalid_response", "Ticket response is not an object");
271
+ let t = e;
272
+ if (typeof t.id != "string")
273
+ throw new i("invalid_response", "Ticket missing id");
274
+ let r = Array.isArray(t.attachments) && typeof t.attachments[0] == "string" ? t.attachments[0] : void 0, o = typeof t.screenshotUrl == "string" ? t.screenshotUrl : r ?? null;
257
275
  return {
258
- id: r.id,
259
- subject: typeof r.subject === "string" ? r.subject : "",
260
- message: typeof r.message === "string" ? r.message : "",
261
- severity: VALID_SEVERITIES.includes(r.severity) ? r.severity : "normal",
262
- status: VALID_STATUSES.includes(r.status) ? r.status : "open",
263
- createdAt: typeof r.createdAt === "string" ? r.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
264
- updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : void 0,
265
- productSlug: typeof r.productId === "string" ? r.productId : typeof r.productSlug === "string" ? r.productSlug : void 0,
266
- pageUrl: typeof r.pageUrl === "string" ? r.pageUrl : null,
267
- screenshotUrl: typeof r.screenshotUrl === "string" ? r.screenshotUrl : firstAttachment ?? null,
268
- resolvedAt: typeof r.resolvedAt === "string" ? r.resolvedAt : null,
269
- resolvedNotifiedAt: typeof r.resolvedNotifiedAt === "string" ? r.resolvedNotifiedAt : null,
270
- satisfactionAttempts: typeof r.satisfactionAttempts === "number" && Number.isFinite(r.satisfactionAttempts) ? r.satisfactionAttempts : 0,
271
- lastSatisfactionAttemptAt: typeof r.lastSatisfactionAttemptAt === "string" ? r.lastSatisfactionAttemptAt : null,
272
- satisfiedAt: typeof r.satisfiedAt === "string" ? r.satisfiedAt : null,
273
- rating: typeof r.rating === "number" && Number.isFinite(r.rating) ? r.rating : null,
274
- satisfactionComment: typeof r.satisfactionComment === "string" ? r.satisfactionComment : null
276
+ id: t.id,
277
+ subject: typeof t.subject == "string" ? t.subject : "",
278
+ message: typeof t.message == "string" ? t.message : "",
279
+ severity: R.includes(t.severity) ? t.severity : "normal",
280
+ status: ue.includes(t.status) ? t.status : "open",
281
+ createdAt: typeof t.createdAt == "string" ? t.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
282
+ updatedAt: typeof t.updatedAt == "string" ? t.updatedAt : void 0,
283
+ productSlug: typeof t.productId == "string" ? t.productId : typeof t.productSlug == "string" ? t.productSlug : void 0,
284
+ pageUrl: typeof t.pageUrl == "string" ? t.pageUrl : null,
285
+ screenshotUrl: o,
286
+ // 3.7.0: a listagem do Core não traz mais `attachments` (screenshotUrl vem
287
+ // null) — `screenshotAttached` diz se o ticket tem print. Fallback: há URL.
288
+ screenshotAttached: typeof t.screenshotAttached == "boolean" ? t.screenshotAttached : o !== null,
289
+ resolvedAt: typeof t.resolvedAt == "string" ? t.resolvedAt : null,
290
+ resolvedNotifiedAt: typeof t.resolvedNotifiedAt == "string" ? t.resolvedNotifiedAt : null,
291
+ satisfactionAttempts: typeof t.satisfactionAttempts == "number" && Number.isFinite(t.satisfactionAttempts) ? t.satisfactionAttempts : 0,
292
+ lastSatisfactionAttemptAt: typeof t.lastSatisfactionAttemptAt == "string" ? t.lastSatisfactionAttemptAt : null,
293
+ satisfiedAt: typeof t.satisfiedAt == "string" ? t.satisfiedAt : null,
294
+ rating: typeof t.rating == "number" && Number.isFinite(t.rating) ? t.rating : null,
295
+ satisfactionComment: typeof t.satisfactionComment == "string" ? t.satisfactionComment : null
275
296
  };
276
297
  }
277
- function assertTicketId(ticketId) {
278
- if (!ticketId || typeof ticketId !== "string") {
279
- throw new NeetruError("validation_failed", "ticketId is required");
280
- }
298
+ function b(e) {
299
+ if (!e || typeof e != "string")
300
+ throw new i("validation_failed", "ticketId is required");
281
301
  }
282
- function assertValidComment(comment) {
283
- if (typeof comment === "string" && comment.length > 2e3) {
284
- throw new NeetruError("validation_failed", "comment max 2000 chars");
285
- }
302
+ function H(e) {
303
+ if (typeof e == "string" && e.length > 2e3)
304
+ throw new i("validation_failed", "comment max 2000 chars");
286
305
  }
287
- function resolveProductId(config, ...candidates) {
288
- for (const c of candidates) {
289
- if (typeof c === "string" && c.length > 0) {
290
- assertValidSdkId("productSlug", c);
291
- return c;
292
- }
293
- }
294
- if (config.productId) {
295
- assertValidSdkId("productId", config.productId);
296
- return config.productId;
297
- }
298
- throw new NeetruError(
306
+ function B(e, ...t) {
307
+ for (let r of t)
308
+ if (typeof r == "string" && r.length > 0)
309
+ return I("productSlug", r), r;
310
+ if (e.productId)
311
+ return I("productId", e.productId), e.productId;
312
+ throw new i(
299
313
  "validation_failed",
300
314
  "productId required (pass to input.productSlug or set on createNeetruClient)"
301
315
  );
302
316
  }
303
- function createSupportNamespace(config) {
317
+ var ce = "X-Neetru-End-User-Token", le = "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.", fe = "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.", pe = "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.", me = "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.";
318
+ function G(e) {
319
+ if (e instanceof i && !(e instanceof _)) {
320
+ if (e.code === "end_user_token_required")
321
+ throw new _(
322
+ fe,
323
+ "end_user_token_required",
324
+ e.status,
325
+ e.requestId,
326
+ e.correlationId
327
+ );
328
+ if (e.code === "invalid_end_user_token")
329
+ throw new _(
330
+ pe,
331
+ "invalid_end_user_token",
332
+ e.status,
333
+ e.requestId,
334
+ e.correlationId
335
+ );
336
+ if (e.code === "end_user_token_product_mismatch")
337
+ throw new i(
338
+ "forbidden",
339
+ me,
340
+ e.status,
341
+ e.requestId,
342
+ "end_user_token_product_mismatch",
343
+ e.correlationId
344
+ );
345
+ }
346
+ throw e;
347
+ }
348
+ function ge(e) {
349
+ return e instanceof i && e.code === "invalid_end_user_token";
350
+ }
351
+ function Ue(e, t = {}) {
352
+ async function r() {
353
+ try {
354
+ let n = await t.getEndUserToken?.();
355
+ return typeof n == "string" && n.length > 0 ? n : null;
356
+ } catch {
357
+ return null;
358
+ }
359
+ }
360
+ async function o() {
361
+ if (!t.refreshEndUserToken) return false;
362
+ try {
363
+ return await t.refreshEndUserToken() === !0;
364
+ } catch {
365
+ return false;
366
+ }
367
+ }
368
+ function s(n) {
369
+ return n ? { [ce]: n } : {};
370
+ }
371
+ async function u(n, g) {
372
+ let a = await r();
373
+ if (!a && n && await o() && (a = await r()), !a && n)
374
+ throw new _(le, "no_signed_in_user");
375
+ try {
376
+ return await g(s(a));
377
+ } catch (l) {
378
+ if (a && ge(l) && await o()) {
379
+ let f = await r();
380
+ if (f)
381
+ try {
382
+ return await g(s(f));
383
+ } catch (p) {
384
+ G(p);
385
+ }
386
+ }
387
+ G(l);
388
+ }
389
+ }
390
+ async function c(n, g = {}) {
391
+ await u(
392
+ true,
393
+ (a) => v(e, {
394
+ method: "POST",
395
+ path: n,
396
+ requireAuth: !0,
397
+ headers: a,
398
+ ...g
399
+ })
400
+ );
401
+ }
304
402
  return {
305
403
  /**
306
404
  * Cria um ticket de suporte. Requer Bearer auth. `productSlug` no input
@@ -308,85 +406,75 @@ function createSupportNamespace(config) {
308
406
  *
309
407
  * Endpoint canonical: `POST /api/sdk/v1/support/tickets`.
310
408
  */
311
- async createTicket(input) {
312
- if (!input || typeof input !== "object") {
313
- throw new NeetruError("validation_failed", "input is required");
314
- }
315
- if (!input.subject || typeof input.subject !== "string") {
316
- throw new NeetruError("validation_failed", "subject is required");
317
- }
318
- if (input.subject.length > 200) {
319
- throw new NeetruError("validation_failed", "subject max 200 chars");
320
- }
321
- if (!input.message || typeof input.message !== "string") {
322
- throw new NeetruError("validation_failed", "message is required");
323
- }
324
- if (input.message.length > 1e4) {
325
- throw new NeetruError("validation_failed", "message max 10000 chars");
326
- }
327
- if (input.severity && !VALID_SEVERITIES.includes(input.severity)) {
328
- throw new NeetruError(
409
+ async createTicket(n) {
410
+ if (!n || typeof n != "object")
411
+ throw new i("validation_failed", "input is required");
412
+ if (!n.subject || typeof n.subject != "string")
413
+ throw new i("validation_failed", "subject is required");
414
+ if (n.subject.length > 200)
415
+ throw new i("validation_failed", "subject max 200 chars");
416
+ if (!n.message || typeof n.message != "string")
417
+ throw new i("validation_failed", "message is required");
418
+ if (n.message.length > 1e4)
419
+ throw new i("validation_failed", "message max 10000 chars");
420
+ if (n.severity && !R.includes(n.severity))
421
+ throw new i(
329
422
  "validation_failed",
330
- `severity must be one of ${VALID_SEVERITIES.join(", ")}`
423
+ `severity must be one of ${R.join(", ")}`
331
424
  );
332
- }
333
- const productId = resolveProductId(config, input.productSlug);
334
- const body = {
335
- productId,
336
- subject: input.subject,
337
- message: input.message,
338
- severity: input.severity ?? "normal"
425
+ let a = {
426
+ productId: B(e, n.productSlug),
427
+ subject: n.subject,
428
+ message: n.message,
429
+ severity: n.severity ?? "normal"
339
430
  };
340
- if (input.metadata && typeof input.metadata === "object") {
341
- body.metadata = input.metadata;
342
- }
343
- if (typeof input.pageUrl === "string") {
344
- body.pageUrl = input.pageUrl;
345
- }
346
- if (typeof input.screenshotBase64 === "string") {
347
- body.screenshotBase64 = input.screenshotBase64;
348
- }
349
- if (typeof input.consoleLogs === "string") {
350
- body.consoleLogs = input.consoleLogs;
351
- }
352
- const raw = await httpRequest(config, {
353
- method: "POST",
354
- path: "/api/sdk/v1/support/tickets",
355
- body,
356
- requireAuth: true,
357
- idempotencyKey: true
358
- });
359
- const candidate = raw && typeof raw === "object" && "ticket" in raw ? raw.ticket : raw;
360
- return toTicket(candidate);
431
+ n.metadata && typeof n.metadata == "object" && (a.metadata = n.metadata), typeof n.pageUrl == "string" && (a.pageUrl = n.pageUrl), typeof n.screenshotBase64 == "string" && (a.screenshotBase64 = n.screenshotBase64), typeof n.consoleLogs == "string" && (a.consoleLogs = n.consoleLogs);
432
+ let l = await u(
433
+ false,
434
+ (p) => v(e, {
435
+ method: "POST",
436
+ path: "/api/sdk/v1/support/tickets",
437
+ body: a,
438
+ requireAuth: !0,
439
+ idempotencyKey: !0,
440
+ headers: p
441
+ })
442
+ ), f = l && typeof l == "object" && "ticket" in l ? l.ticket : l;
443
+ return F(f);
361
444
  },
362
445
  /**
363
446
  * Lista tickets do customer no produto atual. `productSlug` no contexto.
364
447
  *
365
448
  * Endpoint canonical: `GET /api/sdk/v1/support/tickets?productId=...`.
366
449
  */
367
- async listMyTickets(options) {
368
- const productId = resolveProductId(config, options?.productSlug);
369
- const raw = await httpRequest(config, {
370
- method: "GET",
371
- path: "/api/sdk/v1/support/tickets",
372
- query: { productId },
373
- requireAuth: true
374
- });
375
- const list = Array.isArray(raw) ? raw : raw && typeof raw === "object" && "tickets" in raw ? raw.tickets ?? [] : [];
376
- return list.map(toTicket);
450
+ async listMyTickets(n) {
451
+ let g = B(e, n?.productSlug), a = n?.limit;
452
+ if (a !== void 0 && (!Number.isInteger(a) || a < 1 || a > V))
453
+ throw new i(
454
+ "validation_failed",
455
+ `limit must be an integer 1-${V} (Core default 20)`
456
+ );
457
+ let l = await u(
458
+ true,
459
+ (p) => v(e, {
460
+ method: "GET",
461
+ path: "/api/sdk/v1/support/tickets",
462
+ query: { productId: g, limit: a },
463
+ requireAuth: !0,
464
+ headers: p
465
+ })
466
+ );
467
+ return (Array.isArray(l) ? l : l && typeof l == "object" && "tickets" in l ? l.tickets ?? [] : []).map(F);
377
468
  },
378
469
  /**
379
470
  * 3.4: marca a notificação de resolução como vista (`resolvedNotifiedAt`,
380
471
  * idempotente no Core). Endpoint canonical:
381
472
  * `POST /api/sdk/v1/support/tickets/{id}/resolved-seen`.
382
473
  */
383
- async markResolvedSeen(ticketId) {
384
- assertTicketId(ticketId);
385
- await httpRequest(config, {
386
- method: "POST",
387
- path: `/api/sdk/v1/support/tickets/${encodeURIComponent(ticketId)}/resolved-seen`,
388
- requireAuth: true
389
- });
474
+ async markResolvedSeen(n) {
475
+ b(n), await c(
476
+ `/api/sdk/v1/support/tickets/${encodeURIComponent(n)}/resolved-seen`
477
+ );
390
478
  },
391
479
  /**
392
480
  * 3.4: registra uma tentativa de exibição do modal de satisfação
@@ -394,61 +482,47 @@ function createSupportNamespace(config) {
394
482
  * resposta. Endpoint canonical:
395
483
  * `POST /api/sdk/v1/support/tickets/{id}/satisfaction-attempt`.
396
484
  */
397
- async recordSatisfactionAttempt(ticketId) {
398
- assertTicketId(ticketId);
399
- await httpRequest(config, {
400
- method: "POST",
401
- path: `/api/sdk/v1/support/tickets/${encodeURIComponent(ticketId)}/satisfaction-attempt`,
402
- requireAuth: true,
485
+ async recordSatisfactionAttempt(n) {
486
+ b(n), await c(
487
+ `/api/sdk/v1/support/tickets/${encodeURIComponent(n)}/satisfaction-attempt`,
403
488
  // Incrementa satisfactionAttempts += 1 no Core — sem idempotencyKey,
404
489
  // um retry de rede infla o contador (mesmo padrão de createTicket acima).
405
- idempotencyKey: true
406
- });
490
+ { idempotencyKey: true }
491
+ );
407
492
  },
408
493
  /**
409
494
  * 3.4: envia (ou pula) a avaliação de satisfação (CSAT 1-5). Endpoint
410
495
  * canonical: `POST /api/sdk/v1/support/tickets/{id}/satisfaction`.
411
496
  */
412
- async submitSatisfaction(input) {
413
- if (!input || typeof input !== "object") {
414
- throw new NeetruError("validation_failed", "input is required");
415
- }
416
- assertTicketId(input.ticketId);
417
- if (input.rating !== null && input.rating !== void 0) {
418
- if (!Number.isInteger(input.rating) || input.rating < 1 || input.rating > 5) {
419
- throw new NeetruError("validation_failed", "rating must be an integer 1-5 or null");
497
+ async submitSatisfaction(n) {
498
+ if (!n || typeof n != "object")
499
+ throw new i("validation_failed", "input is required");
500
+ if (b(n.ticketId), n.rating !== null && n.rating !== void 0 && (!Number.isInteger(n.rating) || n.rating < 1 || n.rating > 5))
501
+ throw new i("validation_failed", "rating must be an integer 1-5 or null");
502
+ H(n.comment), await c(
503
+ `/api/sdk/v1/support/tickets/${encodeURIComponent(n.ticketId)}/satisfaction`,
504
+ {
505
+ body: {
506
+ rating: n.rating ?? null,
507
+ comment: n.comment ?? null,
508
+ skipped: n.skipped
509
+ }
420
510
  }
421
- }
422
- assertValidComment(input.comment);
423
- await httpRequest(config, {
424
- method: "POST",
425
- path: `/api/sdk/v1/support/tickets/${encodeURIComponent(input.ticketId)}/satisfaction`,
426
- body: {
427
- rating: input.rating ?? null,
428
- comment: input.comment ?? null,
429
- skipped: input.skipped
430
- },
431
- requireAuth: true
432
- });
511
+ );
433
512
  },
434
513
  /**
435
514
  * 3.4: contesta um ticket resolvido — reabre e zera o ciclo de
436
515
  * satisfação/notificação. Endpoint canonical:
437
516
  * `POST /api/sdk/v1/support/tickets/{id}/contest`.
438
517
  */
439
- async contestTicket(ticketId, opts) {
440
- assertTicketId(ticketId);
441
- assertValidComment(opts?.comment);
442
- await httpRequest(config, {
443
- method: "POST",
444
- path: `/api/sdk/v1/support/tickets/${encodeURIComponent(ticketId)}/contest`,
445
- body: { comment: opts?.comment ?? void 0 },
446
- requireAuth: true
447
- });
518
+ async contestTicket(n, g) {
519
+ b(n), H(g?.comment), await c(
520
+ `/api/sdk/v1/support/tickets/${encodeURIComponent(n)}/contest`,
521
+ { body: { comment: g?.comment ?? void 0 } }
522
+ );
448
523
  }
449
524
  };
450
525
  }
451
526
 
452
- exports.createSupportNamespace = createSupportNamespace;
453
- //# sourceMappingURL=support.cjs.map
454
- //# sourceMappingURL=support.cjs.map
527
+ exports.END_USER_TOKEN_HEADER = ce;
528
+ exports.createSupportNamespace = Ue;