@neetru/sdk 3.6.0 → 3.7.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 (116) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/ai.cjs +254 -391
  3. package/dist/ai.d.cts +1 -1
  4. package/dist/ai.d.ts +1 -1
  5. package/dist/ai.mjs +254 -391
  6. package/dist/auth.cjs +3547 -4998
  7. package/dist/auth.d.cts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.mjs +3544 -4995
  10. package/dist/build-guard.cjs +101 -119
  11. package/dist/build-guard.mjs +91 -109
  12. package/dist/catalog.cjs +152 -224
  13. package/dist/catalog.d.cts +1 -1
  14. package/dist/catalog.d.ts +1 -1
  15. package/dist/catalog.mjs +152 -224
  16. package/dist/checkout.cjs +237 -320
  17. package/dist/checkout.d.cts +1 -1
  18. package/dist/checkout.d.ts +1 -1
  19. package/dist/checkout.mjs +236 -319
  20. package/dist/db-react.cjs +59 -87
  21. package/dist/db-react.d.cts +1 -1
  22. package/dist/db-react.d.ts +1 -1
  23. package/dist/db-react.mjs +56 -84
  24. package/dist/db.cjs +2055 -3013
  25. package/dist/db.d.cts +1 -1
  26. package/dist/db.d.ts +1 -1
  27. package/dist/db.mjs +2068 -3026
  28. package/dist/entitlements.cjs +12 -20
  29. package/dist/entitlements.d.cts +1 -1
  30. package/dist/entitlements.d.ts +1 -1
  31. package/dist/entitlements.mjs +12 -20
  32. package/dist/errors.cjs +9 -12
  33. package/dist/errors.d.cts +37 -2
  34. package/dist/errors.d.ts +37 -2
  35. package/dist/errors.mjs +8 -12
  36. package/dist/firestore-compat.cjs +241 -297
  37. package/dist/firestore-compat.d.cts +1 -1
  38. package/dist/firestore-compat.d.ts +1 -1
  39. package/dist/firestore-compat.mjs +215 -271
  40. package/dist/index.cjs +3605 -5131
  41. package/dist/index.d.cts +6 -4
  42. package/dist/index.d.ts +6 -4
  43. package/dist/index.mjs +3710 -5236
  44. package/dist/mobile.cjs +238 -342
  45. package/dist/mobile.d.cts +1 -1
  46. package/dist/mobile.d.ts +1 -1
  47. package/dist/mobile.mjs +238 -342
  48. package/dist/mocks.cjs +312 -447
  49. package/dist/mocks.d.cts +1 -1
  50. package/dist/mocks.d.ts +1 -1
  51. package/dist/mocks.mjs +306 -441
  52. package/dist/notifications.cjs +226 -314
  53. package/dist/notifications.d.cts +1 -1
  54. package/dist/notifications.d.ts +1 -1
  55. package/dist/notifications.mjs +225 -313
  56. package/dist/react.cjs +522 -693
  57. package/dist/react.d.cts +1 -1
  58. package/dist/react.d.ts +1 -1
  59. package/dist/react.mjs +512 -683
  60. package/dist/support.cjs +329 -325
  61. package/dist/support.d.cts +25 -3
  62. package/dist/support.d.ts +25 -3
  63. package/dist/support.mjs +328 -325
  64. package/dist/telemetry.cjs +197 -301
  65. package/dist/telemetry.d.cts +1 -1
  66. package/dist/telemetry.d.ts +1 -1
  67. package/dist/telemetry.mjs +197 -301
  68. package/dist/{types-Du_iioJ7.d.cts → types-Bx4kTLmk.d.cts} +26 -0
  69. package/dist/{types-BPATkXYu.d.ts → types-Dx0IrOSF.d.ts} +26 -0
  70. package/dist/usage.cjs +163 -227
  71. package/dist/usage.d.cts +1 -1
  72. package/dist/usage.d.ts +1 -1
  73. package/dist/usage.mjs +163 -227
  74. package/dist/webhooks.cjs +258 -359
  75. package/dist/webhooks.d.cts +1 -1
  76. package/dist/webhooks.d.ts +1 -1
  77. package/dist/webhooks.mjs +255 -356
  78. package/package.json +4 -3
  79. package/dist/ai.cjs.map +0 -1
  80. package/dist/ai.mjs.map +0 -1
  81. package/dist/auth.cjs.map +0 -1
  82. package/dist/auth.mjs.map +0 -1
  83. package/dist/build-guard.cjs.map +0 -1
  84. package/dist/build-guard.mjs.map +0 -1
  85. package/dist/catalog.cjs.map +0 -1
  86. package/dist/catalog.mjs.map +0 -1
  87. package/dist/checkout.cjs.map +0 -1
  88. package/dist/checkout.mjs.map +0 -1
  89. package/dist/db-react.cjs.map +0 -1
  90. package/dist/db-react.mjs.map +0 -1
  91. package/dist/db.cjs.map +0 -1
  92. package/dist/db.mjs.map +0 -1
  93. package/dist/entitlements.cjs.map +0 -1
  94. package/dist/entitlements.mjs.map +0 -1
  95. package/dist/errors.cjs.map +0 -1
  96. package/dist/errors.mjs.map +0 -1
  97. package/dist/firestore-compat.cjs.map +0 -1
  98. package/dist/firestore-compat.mjs.map +0 -1
  99. package/dist/index.cjs.map +0 -1
  100. package/dist/index.mjs.map +0 -1
  101. package/dist/mobile.cjs.map +0 -1
  102. package/dist/mobile.mjs.map +0 -1
  103. package/dist/mocks.cjs.map +0 -1
  104. package/dist/mocks.mjs.map +0 -1
  105. package/dist/notifications.cjs.map +0 -1
  106. package/dist/notifications.mjs.map +0 -1
  107. package/dist/react.cjs.map +0 -1
  108. package/dist/react.mjs.map +0 -1
  109. package/dist/support.cjs.map +0 -1
  110. package/dist/support.mjs.map +0 -1
  111. package/dist/telemetry.cjs.map +0 -1
  112. package/dist/telemetry.mjs.map +0 -1
  113. package/dist/usage.cjs.map +0 -1
  114. package/dist/usage.mjs.map +0 -1
  115. package/dist/webhooks.cjs.map +0 -1
  116. package/dist/webhooks.mjs.map +0 -1
package/dist/checkout.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 o = class t extends Error {
5
5
  code;
6
6
  status;
7
7
  requestId;
@@ -14,425 +14,342 @@ 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
+ constructor(e, n, r, s, a) {
18
+ super(n), this.name = "NeetruError", this.code = e, this.status = r, this.requestId = s, this.reason = a, Object.setPrototypeOf(this, t.prototype);
25
19
  }
26
20
  };
27
21
 
28
22
  // 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(
23
+ function E() {
24
+ let t = typeof globalThis < "u" && "crypto" in globalThis ? globalThis.crypto : void 0;
25
+ if (t && typeof t.randomUUID == "function")
26
+ return t.randomUUID();
27
+ throw new o(
35
28
  "runtime_unsupported",
36
29
  "crypto.randomUUID not available in this runtime. SDK 3.0 requires Node \u226520 or modern browser/Edge."
37
30
  );
38
31
  }
39
32
 
40
33
  // src/http.ts
41
- var COMPAT_MATRIX = {
34
+ var P = {
42
35
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
43
36
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
44
37
  3: "2026.05.1"
45
38
  };
46
- function stripRevision(v) {
47
- return v.split("+")[0] ?? v;
39
+ function b(t) {
40
+ return t.split("+")[0] ?? t;
48
41
  }
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;
42
+ function M(t, e) {
43
+ let n = b(t).split(".").map(Number), r = b(e).split(".").map(Number), s = Math.max(n.length, r.length);
44
+ for (let a = 0; a < s; a++) {
45
+ let d = n[a] ?? 0, u = r[a] ?? 0;
46
+ if (d !== u) return d - u;
57
47
  }
58
48
  return 0;
59
49
  }
60
- function readInjectedSdkVersion() {
50
+ function D() {
61
51
  try {
62
- return "3.6.0";
52
+ return "3.7.0";
63
53
  } catch {
64
- return void 0;
54
+ return;
65
55
  }
66
56
  }
67
- function getSdkMajor() {
68
- const ver = readInjectedSdkVersion();
69
- if (ver) return parseInt(ver.split(".")[0] ?? "3", 10);
70
- return 3;
57
+ function $() {
58
+ let t = D();
59
+ return t ? parseInt(t.split(".")[0] ?? "3", 10) : 3;
71
60
  }
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
- }
61
+ var v = /* @__PURE__ */ new Set();
62
+ function K(t) {
63
+ if (!t) return;
64
+ let e = $(), n = P[e];
65
+ if (!n) return;
66
+ let r = b(t);
67
+ if (M(r, n) < 0) {
68
+ let s = `${e}:${r}`;
69
+ v.has(s) || (v.add(s), console.warn(
70
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${t}" \xE9 anterior ao m\xEDnimo recomendado "${n}" para SDK major ${e}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
71
+ ));
87
72
  }
88
73
  }
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([
74
+ var j = 2, G = 0, H = /* @__PURE__ */ new Set(["GET", "HEAD"]), F = /* @__PURE__ */ new Set([
93
75
  "rate_limited",
94
76
  "server_error",
95
77
  "network_error"
96
78
  ]);
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));
79
+ function x(t) {
80
+ let e = 200 * Math.pow(4, t), n = e * 0.2 * (Math.random() * 2 - 1);
81
+ return Math.max(50, Math.round(e + n));
101
82
  }
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);
83
+ var A = 6e4;
84
+ function B(t) {
85
+ if (!t) return null;
86
+ let e = Number(t);
87
+ if (Number.isFinite(e) && e >= 0) return Math.min(Math.round(e * 1e3), A);
88
+ let n = Date.parse(t);
89
+ if (Number.isFinite(n)) {
90
+ let r = n - Date.now();
91
+ if (r > 0) return Math.min(r, A);
111
92
  }
112
93
  return null;
113
94
  }
114
- function sleep(ms) {
115
- return new Promise((resolve) => setTimeout(resolve, ms));
95
+ function U(t) {
96
+ return new Promise((e) => setTimeout(e, t));
116
97
  }
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";
98
+ function L(t) {
99
+ 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
100
  }
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));
135
- }
136
- }
137
- return url.toString();
101
+ function z(t, e, n) {
102
+ let r = t.replace(/\/+$/, ""), s = e.startsWith("/") ? e : `/${e}`, a = new URL(`${r}${s}`);
103
+ if (n)
104
+ for (let [d, u] of Object.entries(n))
105
+ u !== void 0 && a.searchParams.set(d, String(u));
106
+ return a.toString();
138
107
  }
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;
146
- }
108
+ async function q(t) {
109
+ let e = await t.text();
110
+ if (e)
111
+ try {
112
+ return JSON.parse(e);
113
+ } catch {
114
+ return;
115
+ }
147
116
  }
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 = {
117
+ async function y(t, e) {
118
+ let n = e.method ?? "GET", r = z(t.baseUrl, e.path, e.query), s = H.has(n) ? j : G, a = e.retries ?? s, d = {
154
119
  accept: "application/json",
155
- ...opts.headers
156
- };
157
- const sdkVersion = readInjectedSdkVersion();
158
- if (sdkVersion) {
159
- headers["x-neetru-sdk-version"] = sdkVersion;
160
- }
161
- if (opts.requireAuth) {
162
- if (!config.apiKey) {
163
- throw new NeetruError(
120
+ ...e.headers
121
+ }, u = D();
122
+ if (u && (d["x-neetru-sdk-version"] = u), e.requireAuth) {
123
+ if (!t.apiKey)
124
+ throw new o(
164
125
  "missing_api_key",
165
126
  "This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
166
127
  );
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;
128
+ d.authorization = `Bearer ${t.apiKey}`;
173
129
  }
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";
130
+ if (e.idempotencyKey) {
131
+ let f = typeof e.idempotencyKey == "string" ? e.idempotencyKey : E();
132
+ d["idempotency-key"] = f;
177
133
  }
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;
134
+ let I = e.body !== void 0 && n !== "GET" && n !== "DELETE" ? JSON.stringify(e.body) : void 0;
135
+ I !== void 0 && (d["content-type"] = "application/json");
136
+ let g = null, p = e.deadlineMs != null ? Date.now() + e.deadlineMs : null;
137
+ for (let f = 0; f <= a; f++) {
138
+ if (p != null && Date.now() >= p)
139
+ throw g ?? new o("network_error", "Deadline excedido antes de completar a request");
140
+ let w = { method: n, headers: d };
141
+ I !== void 0 && (w.body = I);
142
+ let N = p != null ? Math.max(1, Math.min(3e4, p - Date.now())) : 3e4;
143
+ w.signal = AbortSignal.timeout(N);
144
+ let c;
184
145
  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;
146
+ c = await t.fetch(r, w);
147
+ } catch (i) {
148
+ let k = i instanceof DOMException && i.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${i instanceof Error ? i.message : "fetch failed"}`;
149
+ if (g = new o("network_error", k), f < a) {
150
+ let S = x(f);
151
+ if (p == null || Date.now() + S < p) {
152
+ await U(S);
153
+ continue;
154
+ }
192
155
  }
193
- throw lastError;
156
+ throw g;
194
157
  }
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;
158
+ let O = c.headers.get("x-request-id") ?? c.headers.get("x-correlation-id") ?? void 0;
159
+ if (c.ok) {
160
+ let i = c.headers.get("x-neetru-version");
161
+ return i && K(i), await q(c);
201
162
  }
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;
163
+ let l = await q(c), m = L(c.status), h = `HTTP ${c.status}`, T;
164
+ if (l && typeof l == "object") {
165
+ let i = l.error;
166
+ typeof i == "string" ? h = i : i && typeof i == "object" ? (typeof i.code == "string" && (m = i.code), typeof i.message == "string" && (h = i.message), typeof i.reason == "string" && (T = i.reason)) : (typeof l.code == "string" && (m = l.code), typeof l.message == "string" && (h = l.message)), typeof l.reason == "string" && (T = l.reason);
219
167
  }
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;
168
+ if (c.status === 410) {
169
+ let i = c.headers.get("x-neetru-replacement");
170
+ h === `HTTP ${c.status}` && (h = `Endpoint ${e.path} foi removido do Core (HTTP 410 Gone) \u2014 atualize o @neetru/sdk e migre para a API substituta.`), i && !h.includes(i) && (h += ` Substituto: ${i}.`);
228
171
  }
229
- throw err;
172
+ let R = new o(m, h, c.status, O, T);
173
+ if (g = R, F.has(m) && f < a) {
174
+ let k = B(c.headers.get("retry-after")) ?? x(f);
175
+ if (p == null || Date.now() + k < p) {
176
+ await U(k);
177
+ continue;
178
+ }
179
+ }
180
+ throw R;
230
181
  }
231
- throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
182
+ throw g ?? new o("unknown", "unexpected httpRequest exit");
232
183
  }
233
184
 
234
185
  // src/checkout.ts
235
- function checkoutAuth(auth, method) {
236
- const token = auth?.accessToken || auth?.idToken;
237
- if (!token || typeof token !== "string") {
238
- throw new NeetruError(
186
+ function _(t, e) {
187
+ let n = t?.accessToken || t?.idToken;
188
+ if (!n || typeof n != "string")
189
+ throw new o(
239
190
  "validation_failed",
240
- `checkout.${method} requer o access_token OU o id_token OIDC do usu\xE1rio final (passe \`accessToken\` ou \`idToken\`). A chave de API do SDK (nrt_*) N\xC3O \xE9 aceita pelo endpoint de checkout \u2014 ele autentica a identidade do cliente que est\xE1 assinando (Bearer access_token/id_token OIDC ou cookie de sess\xE3o). No padr\xE3o BFF/cookie, passe o \`idToken\` que seu servidor guardou no cookie httpOnly.`
191
+ `checkout.${e} requer o access_token OU o id_token OIDC do usu\xE1rio final (passe \`accessToken\` ou \`idToken\`). A chave de API do SDK (nrt_*) N\xC3O \xE9 aceita pelo endpoint de checkout \u2014 ele autentica a identidade do cliente que est\xE1 assinando (Bearer access_token/id_token OIDC ou cookie de sess\xE3o). No padr\xE3o BFF/cookie, passe o \`idToken\` que seu servidor guardou no cookie httpOnly.`
241
192
  );
242
- }
243
- return { requireAuth: false, headers: { authorization: `Bearer ${token}` } };
193
+ return { requireAuth: false, headers: { authorization: `Bearer ${n}` } };
244
194
  }
245
- function parseStartResponse(raw) {
246
- if (!raw || typeof raw !== "object") {
247
- throw new NeetruError("invalid_response", "checkout.start response is not an object");
248
- }
249
- const r = raw;
250
- if (typeof r.intentId !== "string" || !r.intentId) {
251
- throw new NeetruError("invalid_response", "checkout.start response missing intentId");
252
- }
253
- if (typeof r.redirectUrl !== "string" || !r.redirectUrl) {
254
- throw new NeetruError("invalid_response", "checkout.start response missing redirectUrl");
255
- }
195
+ function V(t) {
196
+ if (!t || typeof t != "object")
197
+ throw new o("invalid_response", "checkout.start response is not an object");
198
+ let e = t;
199
+ if (typeof e.intentId != "string" || !e.intentId)
200
+ throw new o("invalid_response", "checkout.start response missing intentId");
201
+ if (typeof e.redirectUrl != "string" || !e.redirectUrl)
202
+ throw new o("invalid_response", "checkout.start response missing redirectUrl");
256
203
  return {
257
- intentId: r.intentId,
258
- redirectUrl: r.redirectUrl,
259
- status: r.status ?? "pending",
260
- expiresAt: typeof r.expiresAt === "string" ? r.expiresAt : (/* @__PURE__ */ new Date()).toISOString(),
261
- requiresKyc: r.requiresKyc === true
204
+ intentId: e.intentId,
205
+ redirectUrl: e.redirectUrl,
206
+ status: e.status ?? "pending",
207
+ expiresAt: typeof e.expiresAt == "string" ? e.expiresAt : (/* @__PURE__ */ new Date()).toISOString(),
208
+ requiresKyc: e.requiresKyc === true
262
209
  };
263
210
  }
264
- function parseGetResponse(raw) {
265
- if (!raw || typeof raw !== "object") {
266
- throw new NeetruError("invalid_response", "checkout.get response is not an object");
267
- }
268
- const r = raw;
269
- const intent = r.intent;
270
- if (!intent || typeof intent !== "object") {
271
- throw new NeetruError("invalid_response", "checkout.get response missing intent");
272
- }
273
- if (typeof intent.intentId !== "string") {
274
- throw new NeetruError("invalid_response", "checkout.get response missing intentId");
275
- }
211
+ function J(t) {
212
+ if (!t || typeof t != "object")
213
+ throw new o("invalid_response", "checkout.get response is not an object");
214
+ let e = t, n = e.intent;
215
+ if (!n || typeof n != "object")
216
+ throw new o("invalid_response", "checkout.get response missing intent");
217
+ if (typeof n.intentId != "string")
218
+ throw new o("invalid_response", "checkout.get response missing intentId");
276
219
  return {
277
- intentId: intent.intentId,
278
- uid: intent.uid ?? "",
279
- targetTenantId: intent.targetTenantId ?? "",
280
- targetTenantType: intent.targetTenantType ?? "pf",
281
- productId: intent.productId ?? "",
282
- planId: intent.planId ?? "",
283
- callbackUrl: intent.callbackUrl ?? "",
284
- status: intent.status ?? "pending",
285
- stripeSessionId: intent.stripeSessionId ?? null,
286
- expiresAt: intent.expiresAt ?? (/* @__PURE__ */ new Date()).toISOString(),
287
- isStale: r.isStale === true
220
+ intentId: n.intentId,
221
+ uid: n.uid ?? "",
222
+ targetTenantId: n.targetTenantId ?? "",
223
+ targetTenantType: n.targetTenantType ?? "pf",
224
+ productId: n.productId ?? "",
225
+ planId: n.planId ?? "",
226
+ callbackUrl: n.callbackUrl ?? "",
227
+ status: n.status ?? "pending",
228
+ stripeSessionId: n.stripeSessionId ?? null,
229
+ expiresAt: n.expiresAt ?? (/* @__PURE__ */ new Date()).toISOString(),
230
+ isStale: e.isStale === true
288
231
  };
289
232
  }
290
- function inBrowser() {
233
+ function Y() {
291
234
  try {
292
- return typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined" && typeof globalThis.location !== "undefined" && typeof globalThis.location.assign === "function";
235
+ return typeof globalThis < "u" && typeof globalThis.window < "u" && typeof globalThis.location < "u" && typeof globalThis.location.assign == "function";
293
236
  } catch {
294
237
  return false;
295
238
  }
296
239
  }
297
- function performRedirect(url) {
240
+ function W(t) {
298
241
  try {
299
- globalThis.location.assign(url);
242
+ globalThis.location.assign(t);
300
243
  } catch {
301
244
  }
302
245
  }
303
- function createHttpCheckoutNamespace(config) {
246
+ function X(t) {
304
247
  return {
305
- async start(input) {
306
- if (!input?.productId) {
307
- throw new NeetruError("validation_failed", "checkout.start: productId is required");
308
- }
309
- if (!input?.planId) {
310
- throw new NeetruError("validation_failed", "checkout.start: planId is required");
311
- }
312
- if (!input?.callbackUrl) {
313
- throw new NeetruError("validation_failed", "checkout.start: callbackUrl is required");
314
- }
315
- const body = {
316
- productId: input.productId,
317
- planId: input.planId,
318
- callbackUrl: input.callbackUrl
248
+ async start(e) {
249
+ if (!e?.productId)
250
+ throw new o("validation_failed", "checkout.start: productId is required");
251
+ if (!e?.planId)
252
+ throw new o("validation_failed", "checkout.start: planId is required");
253
+ if (!e?.callbackUrl)
254
+ throw new o("validation_failed", "checkout.start: callbackUrl is required");
255
+ let n = {
256
+ productId: e.productId,
257
+ planId: e.planId,
258
+ callbackUrl: e.callbackUrl
319
259
  };
320
- if (input.tenantType) body.targetTenantType = input.tenantType;
321
- if (input.tenantId) body.targetTenantId = input.tenantId;
322
- const { requireAuth, headers } = checkoutAuth(
323
- { accessToken: input.accessToken, idToken: input.idToken },
260
+ e.tenantType && (n.targetTenantType = e.tenantType), e.tenantId && (n.targetTenantId = e.tenantId);
261
+ let { requireAuth: r, headers: s } = _(
262
+ { accessToken: e.accessToken, idToken: e.idToken },
324
263
  "start"
325
- );
326
- const raw = await httpRequest(config, {
264
+ ), a = await y(t, {
327
265
  method: "POST",
328
266
  path: "/api/v1/checkout/intents",
329
- body,
330
- requireAuth,
331
- headers,
267
+ body: n,
268
+ requireAuth: r,
269
+ headers: s,
332
270
  idempotencyKey: true
333
- });
334
- const result = parseStartResponse(raw);
335
- const shouldRedirect = input.autoRedirect !== false;
336
- if (shouldRedirect && inBrowser()) {
337
- performRedirect(result.redirectUrl);
338
- }
339
- return result;
271
+ }), d = V(a);
272
+ return e.autoRedirect !== false && Y() && W(d.redirectUrl), d;
340
273
  },
341
- async get(intentId, opts) {
342
- if (!intentId || typeof intentId !== "string") {
343
- throw new NeetruError("validation_failed", "checkout.get: intentId is required");
344
- }
345
- const { requireAuth, headers } = checkoutAuth(
346
- { accessToken: opts?.accessToken, idToken: opts?.idToken },
274
+ async get(e, n) {
275
+ if (!e || typeof e != "string")
276
+ throw new o("validation_failed", "checkout.get: intentId is required");
277
+ let { requireAuth: r, headers: s } = _(
278
+ { accessToken: n?.accessToken, idToken: n?.idToken },
347
279
  "get"
348
- );
349
- const raw = await httpRequest(config, {
280
+ ), a = await y(t, {
350
281
  method: "GET",
351
- path: `/api/v1/checkout/intents/${encodeURIComponent(intentId)}`,
352
- requireAuth,
353
- headers
282
+ path: `/api/v1/checkout/intents/${encodeURIComponent(e)}`,
283
+ requireAuth: r,
284
+ headers: s
354
285
  });
355
- return parseGetResponse(raw);
286
+ return J(a);
356
287
  },
357
- async cancel(intentId, opts) {
358
- if (!intentId || typeof intentId !== "string") {
359
- throw new NeetruError("validation_failed", "checkout.cancel: intentId is required");
360
- }
361
- const { requireAuth, headers } = checkoutAuth(
362
- { accessToken: opts?.accessToken, idToken: opts?.idToken },
288
+ async cancel(e, n) {
289
+ if (!e || typeof e != "string")
290
+ throw new o("validation_failed", "checkout.cancel: intentId is required");
291
+ let { requireAuth: r, headers: s } = _(
292
+ { accessToken: n?.accessToken, idToken: n?.idToken },
363
293
  "cancel"
364
294
  );
365
- const raw = await httpRequest(config, {
366
- method: "DELETE",
367
- path: `/api/v1/checkout/intents/${encodeURIComponent(intentId)}`,
368
- requireAuth,
369
- headers
370
- });
371
295
  return {
372
296
  ok: true,
373
- alreadyCancelled: raw?.alreadyCancelled === true
297
+ alreadyCancelled: (await y(t, {
298
+ method: "DELETE",
299
+ path: `/api/v1/checkout/intents/${encodeURIComponent(e)}`,
300
+ requireAuth: r,
301
+ headers: s
302
+ }))?.alreadyCancelled === true
374
303
  };
375
304
  }
376
305
  };
377
306
  }
378
- var MockCheckout = class {
307
+ var C = class {
379
308
  intents = /* @__PURE__ */ new Map();
380
- async start(input) {
381
- if (!input?.productId) {
382
- throw new NeetruError("validation_failed", "checkout.start: productId is required");
383
- }
384
- if (!input?.planId) {
385
- throw new NeetruError("validation_failed", "checkout.start: planId is required");
386
- }
387
- if (!input?.callbackUrl) {
388
- throw new NeetruError("validation_failed", "checkout.start: callbackUrl is required");
389
- }
390
- const intentId = `chk_mock_${Math.random().toString(36).slice(2, 10)}`;
391
- const expiresAt = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
392
- const redirectUrl = `https://localhost:9003/portal/checkout/${intentId}`;
393
- this.intents.set(intentId, {
394
- intentId,
309
+ async start(e) {
310
+ if (!e?.productId)
311
+ throw new o("validation_failed", "checkout.start: productId is required");
312
+ if (!e?.planId)
313
+ throw new o("validation_failed", "checkout.start: planId is required");
314
+ if (!e?.callbackUrl)
315
+ throw new o("validation_failed", "checkout.start: callbackUrl is required");
316
+ let n = `chk_mock_${Math.random().toString(36).slice(2, 10)}`, r = new Date(Date.now() + 900 * 1e3).toISOString(), s = `https://localhost:9003/portal/checkout/${n}`;
317
+ return this.intents.set(n, {
318
+ intentId: n,
395
319
  uid: "dev-fixture-uid",
396
- targetTenantId: input.tenantId ?? "dev-fixture-uid",
397
- targetTenantType: input.tenantType ?? "pf",
398
- productId: input.productId,
399
- planId: input.planId,
400
- callbackUrl: input.callbackUrl,
320
+ targetTenantId: e.tenantId ?? "dev-fixture-uid",
321
+ targetTenantType: e.tenantType ?? "pf",
322
+ productId: e.productId,
323
+ planId: e.planId,
324
+ callbackUrl: e.callbackUrl,
401
325
  status: "pending",
402
326
  stripeSessionId: null,
403
- expiresAt
404
- });
405
- return {
406
- intentId,
407
- redirectUrl,
327
+ expiresAt: r
328
+ }), {
329
+ intentId: n,
330
+ redirectUrl: s,
408
331
  status: "pending",
409
- expiresAt,
332
+ expiresAt: r,
410
333
  requiresKyc: false
411
334
  };
412
335
  }
413
- async get(intentId, _opts) {
414
- const found = this.intents.get(intentId);
415
- if (!found) {
416
- throw new NeetruError("not_found", `Mock intent ${intentId} not found`);
417
- }
418
- return { ...found };
336
+ async get(e, n) {
337
+ let r = this.intents.get(e);
338
+ if (!r)
339
+ throw new o("not_found", `Mock intent ${e} not found`);
340
+ return { ...r };
419
341
  }
420
- async cancel(intentId, _opts) {
421
- const found = this.intents.get(intentId);
422
- if (!found) {
423
- throw new NeetruError("not_found", `Mock intent ${intentId} not found`);
424
- }
425
- const alreadyCancelled = found.status === "cancelled";
426
- this.intents.set(intentId, { ...found, status: "cancelled" });
427
- return { ok: true, alreadyCancelled };
342
+ async cancel(e, n) {
343
+ let r = this.intents.get(e);
344
+ if (!r)
345
+ throw new o("not_found", `Mock intent ${e} not found`);
346
+ let s = r.status === "cancelled";
347
+ return this.intents.set(e, { ...r, status: "cancelled" }), { ok: true, alreadyCancelled: s };
428
348
  }
429
349
  };
430
- function createCheckoutNamespace(config) {
431
- if (config.env === "dev") return new MockCheckout();
432
- return createHttpCheckoutNamespace(config);
350
+ function ae(t) {
351
+ return t.env === "dev" ? new C() : X(t);
433
352
  }
434
353
 
435
- exports.MockCheckout = MockCheckout;
436
- exports.createCheckoutNamespace = createCheckoutNamespace;
437
- //# sourceMappingURL=checkout.cjs.map
438
- //# sourceMappingURL=checkout.cjs.map
354
+ exports.MockCheckout = C;
355
+ exports.createCheckoutNamespace = ae;