@suqo/sdk 1.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,858 @@
1
+ import { createHmac, timingSafeEqual } from 'crypto';
2
+
3
+ // src/errors/SuqoError.ts
4
+ var SuqoError = class extends Error {
5
+ constructor(message, options = {}) {
6
+ super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
7
+ this.name = new.target.name;
8
+ this.rawBody = options.rawBody;
9
+ if (options.status !== void 0) this.status = options.status;
10
+ if (options.requestId !== void 0) this.requestId = options.requestId;
11
+ Object.setPrototypeOf(this, new.target.prototype);
12
+ }
13
+ };
14
+ var SuqoConfigError = class extends SuqoError {
15
+ constructor(message, options = {}) {
16
+ super(message, options);
17
+ }
18
+ };
19
+ var AuthenticationError = class extends SuqoError {
20
+ };
21
+ var KycRequiredError = class extends SuqoError {
22
+ constructor(message, options = {}) {
23
+ super(message, options);
24
+ if (options.kycStatus !== void 0) this.kycStatus = options.kycStatus;
25
+ }
26
+ };
27
+ var ValidationError = class extends SuqoError {
28
+ constructor(message, options = {}) {
29
+ super(message, options);
30
+ this.fieldErrors = options.fieldErrors ?? {};
31
+ }
32
+ };
33
+ var NotFoundError = class extends SuqoError {
34
+ };
35
+ var RateLimitError = class extends SuqoError {
36
+ constructor(message, options = {}) {
37
+ super(message, options);
38
+ if (options.retryAfter !== void 0) this.retryAfter = options.retryAfter;
39
+ }
40
+ };
41
+ var ServerError = class extends SuqoError {
42
+ };
43
+ var NetworkError = class extends SuqoError {
44
+ };
45
+
46
+ // src/utils/isRecord.ts
47
+ function isRecord(value) {
48
+ return typeof value === "object" && value !== null;
49
+ }
50
+
51
+ // src/errors/mapHttpError.ts
52
+ function isDetailShaped(body) {
53
+ return isRecord(body) && typeof body.detail === "string" && body.detail.length > 0;
54
+ }
55
+ function fieldErrorsFrom(body, pathPrefix = "") {
56
+ if (!isRecord(body)) return {};
57
+ const fieldErrors = {};
58
+ for (const [rawKey, value] of Object.entries(body)) {
59
+ const key = pathPrefix === "" && rawKey === "client" ? "customer" : rawKey;
60
+ const path = pathPrefix === "" ? key : `${pathPrefix}.${key}`;
61
+ if (typeof value === "string") {
62
+ fieldErrors[path] = [value];
63
+ } else if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
64
+ fieldErrors[path] = value;
65
+ } else if (isRecord(value) && !Array.isArray(value)) {
66
+ Object.assign(fieldErrors, fieldErrorsFrom(value, path));
67
+ }
68
+ }
69
+ return fieldErrors;
70
+ }
71
+ function messageFrom(body, fallback) {
72
+ if (isRecord(body)) {
73
+ if (typeof body.detail === "string" && body.detail.length > 0) return body.detail;
74
+ if (typeof body.message === "string" && body.message.length > 0) return body.message;
75
+ }
76
+ return fallback;
77
+ }
78
+ function mapHttpError(input) {
79
+ const { status, statusText, body, requestId, retryAfter } = input;
80
+ const fallbackMessage = `Request failed with status ${status}${statusText ? ` (${statusText})` : ""}`;
81
+ const base = { status, rawBody: body, ...requestId !== void 0 ? { requestId } : {} };
82
+ switch (status) {
83
+ case 401:
84
+ return new AuthenticationError(messageFrom(body, fallbackMessage), base);
85
+ case 403: {
86
+ const kycStatus = isRecord(body) && typeof body.status_code === "string" ? body.status_code : void 0;
87
+ const message = messageFrom(body, "KYC verification needed to perform this action.");
88
+ return new KycRequiredError(message, { ...base, ...kycStatus !== void 0 ? { kycStatus } : {} });
89
+ }
90
+ case 400: {
91
+ if (isDetailShaped(body)) {
92
+ return new ValidationError(body.detail, base);
93
+ }
94
+ return new ValidationError("Validation failed.", { ...base, fieldErrors: fieldErrorsFrom(body) });
95
+ }
96
+ case 404:
97
+ return new NotFoundError(messageFrom(body, "Not found."), base);
98
+ case 429:
99
+ return new RateLimitError(messageFrom(body, fallbackMessage), {
100
+ ...base,
101
+ ...retryAfter !== void 0 ? { retryAfter } : {}
102
+ });
103
+ default:
104
+ return new ServerError(messageFrom(body, fallbackMessage), base);
105
+ }
106
+ }
107
+
108
+ // src/config/environments.ts
109
+ var SANDBOX_BASE_URL = "https://test-be.suqo.ai";
110
+ var LIVE_BASE_URL = "https://be.suqo.ai";
111
+ var KEY_PREFIXES = [
112
+ { prefix: "su_test_key_", environment: "sandbox", baseUrl: SANDBOX_BASE_URL },
113
+ { prefix: "su_key_", environment: "live", baseUrl: LIVE_BASE_URL }
114
+ ];
115
+ function resolveEnvironment(apiKey, override) {
116
+ if (typeof apiKey !== "string" || apiKey.length === 0) {
117
+ throw new SuqoConfigError("A SUQO API key is required.");
118
+ }
119
+ const match = KEY_PREFIXES.find(({ prefix }) => apiKey.startsWith(prefix));
120
+ if (!match) {
121
+ throw new SuqoConfigError(
122
+ 'Malformed SUQO API key: expected prefix "su_key_" (live) or "su_test_key_" (sandbox).'
123
+ );
124
+ }
125
+ if (override !== void 0 && override !== match.baseUrl) {
126
+ throw new SuqoConfigError(
127
+ `Environment mismatch: key implies ${match.baseUrl} but baseUrl was set to ${override}. Remove baseUrl or use a matching key.`
128
+ );
129
+ }
130
+ return { environment: match.environment, baseUrl: override ?? match.baseUrl };
131
+ }
132
+
133
+ // src/config/SdkConfig.ts
134
+ var DEFAULT_TIMEOUT_MS = 3e4;
135
+ var DEFAULT_MAX_RETRIES = 2;
136
+ var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
137
+ var SdkConfig = class {
138
+ #apiKey;
139
+ constructor(input) {
140
+ const { environment, baseUrl } = resolveEnvironment(input.apiKey, input.baseUrl);
141
+ this.environment = environment;
142
+ this.baseUrl = baseUrl;
143
+ this.timeout = input.timeout ?? DEFAULT_TIMEOUT_MS;
144
+ this.maxRetries = input.maxRetries ?? DEFAULT_MAX_RETRIES;
145
+ this.dispatcher = input.dispatcher;
146
+ this.#apiKey = input.apiKey;
147
+ }
148
+ /** The raw API key, for building the `Authorization: Bearer <key>` header (`http.ts`, Ticket 2). Never logged. */
149
+ get apiKey() {
150
+ return this.#apiKey;
151
+ }
152
+ /** Redacts the key so it never appears in `JSON.stringify` output (SDK-SPEC.md §4). */
153
+ toJSON() {
154
+ return {
155
+ environment: this.environment,
156
+ baseUrl: this.baseUrl,
157
+ timeout: this.timeout,
158
+ maxRetries: this.maxRetries,
159
+ apiKey: "[redacted]"
160
+ };
161
+ }
162
+ /** Redacts the key so it never appears in `util.inspect`/`console.log` output (SDK-SPEC.md §4). */
163
+ [NODE_INSPECT_CUSTOM]() {
164
+ return this.toJSON();
165
+ }
166
+ };
167
+
168
+ // src/http/urlBuilder.ts
169
+ function buildUrl(baseUrl, path, query) {
170
+ const url = new URL(path, baseUrl);
171
+ if (!url.pathname.endsWith("/")) {
172
+ url.pathname = `${url.pathname}/`;
173
+ }
174
+ if (query) {
175
+ for (const [key, value] of Object.entries(query)) {
176
+ if (value !== void 0) url.searchParams.set(key, String(value));
177
+ }
178
+ }
179
+ return url.toString();
180
+ }
181
+
182
+ // src/http/retry.ts
183
+ var RETRYABLE_METHODS = /* @__PURE__ */ new Set(["GET"]);
184
+ function isRetryableMethod(method) {
185
+ return RETRYABLE_METHODS.has(method);
186
+ }
187
+ function isRetryableFailure(input) {
188
+ if (input.networkError) return true;
189
+ if (input.status === void 0) return false;
190
+ return input.status === 429 || input.status >= 500 && input.status <= 599;
191
+ }
192
+ var BASE_DELAY_MS = 500;
193
+ var MAX_DELAY_MS = 8e3;
194
+ function backoffDelayMs(attempt) {
195
+ const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
196
+ return Math.random() * cap;
197
+ }
198
+ var MAX_RETRY_AFTER_MS = 6e4;
199
+ function parseRetryAfterMs(headerValue, now = Date.now()) {
200
+ if (headerValue === null) return void 0;
201
+ const trimmed = headerValue.trim();
202
+ if (trimmed.length === 0) return void 0;
203
+ const seconds = Number(trimmed);
204
+ if (Number.isFinite(seconds)) {
205
+ if (seconds < 0) return void 0;
206
+ return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS);
207
+ }
208
+ const dateMs = Date.parse(trimmed);
209
+ if (Number.isNaN(dateMs)) return void 0;
210
+ const delta = Math.max(dateMs - now, 0);
211
+ return Math.min(delta, MAX_RETRY_AFTER_MS);
212
+ }
213
+
214
+ // src/http/signals.ts
215
+ function combineSignals(signals) {
216
+ const controller = new AbortController();
217
+ const cleanupFns = [];
218
+ for (const signal of signals) {
219
+ if (!signal) continue;
220
+ if (signal.aborted) {
221
+ controller.abort(signal.reason);
222
+ break;
223
+ }
224
+ const onAbort = () => controller.abort(signal.reason);
225
+ signal.addEventListener("abort", onAbort, { once: true });
226
+ cleanupFns.push(() => signal.removeEventListener("abort", onAbort));
227
+ }
228
+ return {
229
+ signal: controller.signal,
230
+ cleanup: () => {
231
+ for (const fn of cleanupFns) fn();
232
+ }
233
+ };
234
+ }
235
+
236
+ // src/http/HttpClient.ts
237
+ function defaultSleep(ms) {
238
+ return new Promise((resolve) => setTimeout(resolve, ms));
239
+ }
240
+ async function parseJsonBody(response) {
241
+ const text = await response.text();
242
+ if (text.length === 0) return void 0;
243
+ try {
244
+ return JSON.parse(text);
245
+ } catch {
246
+ return void 0;
247
+ }
248
+ }
249
+ function toNetworkError(cause, timeoutMs, callerCancelled) {
250
+ if (callerCancelled) {
251
+ return new NetworkError("Request cancelled", { cause });
252
+ }
253
+ if (cause instanceof Error && cause.name === "TimeoutError") {
254
+ return new NetworkError(`Request timed out after ${timeoutMs}ms`, { cause });
255
+ }
256
+ const message = cause instanceof Error ? cause.message : String(cause);
257
+ return new NetworkError(`Network request failed: ${message}`, { cause });
258
+ }
259
+ var HttpClient = class {
260
+ #config;
261
+ #sleep;
262
+ constructor(config, options = {}) {
263
+ this.#config = config;
264
+ this.#sleep = options.sleep ?? defaultSleep;
265
+ }
266
+ /**
267
+ * Sends a request and returns the parsed 2xx body, or throws the `SuqoError` subclass
268
+ * `mapHttpError` maps a non-2xx response to. Writes are never retried (SDK-SPEC.md §8, §12);
269
+ * reads retry on network failure, `429`, or `5xx`, bounded by `SdkConfig.maxRetries`.
270
+ *
271
+ * Generic on both `TResponse` and `TBody` — e.g.
272
+ * `request<CreateSubscriptionResponse, CreateSubscriptionParams>({ body, ... })` — so a
273
+ * resource method (Ticket 4) gets its request body checked against the exact shape it means to
274
+ * send, not just `unknown`.
275
+ */
276
+ async request(options) {
277
+ if (options.method === "GET" && options.body !== void 0) {
278
+ throw new TypeError("HttpClient.request: a GET request cannot carry a body.");
279
+ }
280
+ let url;
281
+ try {
282
+ url = buildUrl(this.#config.baseUrl, options.path, options.query);
283
+ if (new URL(url).origin !== new URL(this.#config.baseUrl).origin) {
284
+ throw new Error(
285
+ `Refusing to send a request to ${new URL(url).origin} \u2014 it does not match the configured origin ${new URL(this.#config.baseUrl).origin}. This SDK never sends its API key to a different host.`
286
+ );
287
+ }
288
+ } catch (cause) {
289
+ const message = cause instanceof Error ? cause.message : String(cause);
290
+ throw new NetworkError(`Invalid request URL: ${message}`, { cause });
291
+ }
292
+ const retryable = isRetryableMethod(options.method);
293
+ const maxAttempts = retryable ? this.#config.maxRetries + 1 : 1;
294
+ const timeoutMs = options.timeoutMs ?? this.#config.timeout;
295
+ for (let attempt = 1; ; attempt++) {
296
+ const isLastAttempt = attempt >= maxAttempts;
297
+ try {
298
+ const response = await this.#doFetch(url, options, timeoutMs);
299
+ if (response.ok) {
300
+ return await parseJsonBody(response);
301
+ }
302
+ const body = await parseJsonBody(response);
303
+ const retryAfter = parseRetryAfterMs(response.headers.get("Retry-After"));
304
+ if (!isLastAttempt && retryable && isRetryableFailure({ networkError: false, status: response.status })) {
305
+ await this.#sleepOrAbort(retryAfter ?? backoffDelayMs(attempt - 1), options.signal, timeoutMs);
306
+ continue;
307
+ }
308
+ throw mapHttpError({
309
+ status: response.status,
310
+ statusText: response.statusText,
311
+ body,
312
+ ...retryAfter !== void 0 ? { retryAfter } : {}
313
+ });
314
+ } catch (cause) {
315
+ if (cause instanceof SuqoError) throw cause;
316
+ const callerCancelled = options.signal?.aborted === true;
317
+ if (!callerCancelled && !isLastAttempt && retryable && isRetryableFailure({ networkError: true })) {
318
+ await this.#sleepOrAbort(backoffDelayMs(attempt - 1), options.signal, timeoutMs);
319
+ continue;
320
+ }
321
+ throw toNetworkError(cause, timeoutMs, callerCancelled);
322
+ }
323
+ }
324
+ }
325
+ /**
326
+ * Sleeps for `ms`, but rejects immediately with a "cancelled" `NetworkError` if `signal` aborts
327
+ * *during* the wait — a caller cancelling mid-backoff doesn't have to wait for the sleep to
328
+ * finish first (found in review: the previous version ignored `signal` here entirely).
329
+ */
330
+ async #sleepOrAbort(ms, signal, timeoutMs) {
331
+ if (!signal) {
332
+ await this.#sleep(ms);
333
+ return;
334
+ }
335
+ if (signal.aborted) {
336
+ throw toNetworkError(signal.reason, timeoutMs, true);
337
+ }
338
+ await new Promise((resolve, reject) => {
339
+ const onAbort = () => reject(toNetworkError(signal.reason, timeoutMs, true));
340
+ signal.addEventListener("abort", onAbort, { once: true });
341
+ this.#sleep(ms).then(
342
+ () => {
343
+ signal.removeEventListener("abort", onAbort);
344
+ resolve();
345
+ },
346
+ (sleepError) => {
347
+ signal.removeEventListener("abort", onAbort);
348
+ reject(sleepError);
349
+ }
350
+ );
351
+ });
352
+ }
353
+ async #doFetch(url, options, timeoutMs) {
354
+ const isWrite = options.method !== "GET";
355
+ const headers = {
356
+ Authorization: `Bearer ${this.#config.apiKey}`
357
+ };
358
+ if (isWrite) {
359
+ headers["Content-Type"] = "application/json";
360
+ }
361
+ const body = options.method === "POST" ? options.body : void 0;
362
+ const { signal, cleanup } = combineSignals([AbortSignal.timeout(timeoutMs), options.signal]);
363
+ try {
364
+ const init = {
365
+ method: options.method,
366
+ headers,
367
+ signal,
368
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {},
369
+ ...this.#config.dispatcher !== void 0 ? { dispatcher: this.#config.dispatcher } : {}
370
+ };
371
+ return await fetch(url, init);
372
+ } finally {
373
+ cleanup();
374
+ }
375
+ }
376
+ };
377
+
378
+ // src/pagination.ts
379
+ function toPageQuery(params) {
380
+ return {
381
+ page: params?.page,
382
+ page_size: params?.pageSize
383
+ };
384
+ }
385
+ function deserializePage(wire, deserializeItem) {
386
+ return {
387
+ count: wire.count,
388
+ next: wire.next,
389
+ previous: wire.previous,
390
+ results: wire.results.map(deserializeItem)
391
+ };
392
+ }
393
+ async function* listAll(firstPage, fetchNext, maxPages = 1e4) {
394
+ let page = firstPage;
395
+ let pagesSeen = 0;
396
+ while (true) {
397
+ pagesSeen++;
398
+ if (pagesSeen > maxPages) {
399
+ throw new Error(
400
+ `listAll exceeded ${maxPages} pages without reaching next: null. This usually means the server or the fetchNext callback isn't advancing \u2014 check for a stuck loop.`
401
+ );
402
+ }
403
+ for (const item of page.results) {
404
+ yield item;
405
+ }
406
+ if (page.next === null) {
407
+ return;
408
+ }
409
+ page = await fetchNext(page.next);
410
+ }
411
+ }
412
+ function bridgeAutoPaging(fetchFirstPage, fetchNext, maxPages = 1e4) {
413
+ return (async function* () {
414
+ yield* listAll(await fetchFirstPage(), fetchNext, maxPages);
415
+ })();
416
+ }
417
+
418
+ // src/resources/products.ts
419
+ var PRODUCTS_PATH = "/api/v1/products";
420
+ function deserializeBillingPeriod(wire) {
421
+ return {
422
+ pbpId: wire.pbp_id,
423
+ intervalType: wire.interval_type,
424
+ intervalCount: wire.interval_count,
425
+ label: wire.label,
426
+ price: wire.price,
427
+ currency: wire.currency,
428
+ isCurrent: wire.is_current,
429
+ isLimited: wire.is_limited,
430
+ isArchived: wire.is_archived,
431
+ offers: wire.offers
432
+ };
433
+ }
434
+ function deserializePlan(wire) {
435
+ return {
436
+ planId: wire.plan_id,
437
+ planName: wire.plan_name,
438
+ description: wire.description,
439
+ // `openapi.yaml`'s Product schema has no `required` list at all, so `billing_periods` being
440
+ // omitted entirely (not just an empty array) is spec-legal — `?? []` degrades to an empty
441
+ // list instead of `.map` throwing on `undefined` (found in review, reproduced).
442
+ billingPeriods: (wire.billing_periods ?? []).map(deserializeBillingPeriod)
443
+ };
444
+ }
445
+ function deserializeProductVat(wire) {
446
+ return {
447
+ isVatActive: wire.is_vat_active,
448
+ vatType: wire.vat_type,
449
+ vatPercentage: wire.vat_percentage
450
+ };
451
+ }
452
+ function deserializeProduct(wire) {
453
+ return {
454
+ productId: wire.product_id,
455
+ name: wire.name,
456
+ description: wire.description,
457
+ type: wire.type,
458
+ isActive: wire.is_active,
459
+ termsAndConditions: wire.terms_and_conditions,
460
+ featuresAndBenefits: wire.features_and_benefits,
461
+ // `== null` (not `=== null`) is deliberate — it catches both an explicit `null` and an
462
+ // entirely omitted `vat` key. `openapi.yaml` has no `required` list for Product, so omitting
463
+ // `vat` is spec-legal, and the old `=== null` check crashed on `deserializeProductVat(undefined)`
464
+ // when that happened (found in review, reproduced).
465
+ vat: wire.vat == null ? null : deserializeProductVat(wire.vat),
466
+ productImage: wire.product_image,
467
+ // Same reasoning as `billingPeriods` above — `plan` being omitted entirely is spec-legal.
468
+ plan: (wire.plan ?? []).map(deserializePlan),
469
+ totalSubscribers: wire.total_subscribers,
470
+ createdAt: wire.created_at,
471
+ updatedAt: wire.updated_at
472
+ };
473
+ }
474
+ var ProductsResource = class {
475
+ #http;
476
+ constructor(http) {
477
+ this.#http = http;
478
+ }
479
+ /** Lists the authenticated seller's active products. Paginated (SDK-SPEC.md §6). */
480
+ async list(params) {
481
+ const wire = await this.#http.request({
482
+ method: "GET",
483
+ path: PRODUCTS_PATH,
484
+ query: toPageQuery(params)
485
+ });
486
+ return deserializePage(wire, deserializeProduct);
487
+ }
488
+ /**
489
+ * Auto-iterates every product across every page, following `next` until it's `null`
490
+ * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently — this is
491
+ * additive, not a replacement.
492
+ */
493
+ autoPaging(params) {
494
+ return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {
495
+ const wire = await this.#http.request({ method: "GET", path: nextUrl });
496
+ return deserializePage(wire, deserializeProduct);
497
+ });
498
+ }
499
+ };
500
+
501
+ // src/models/Subscription.ts
502
+ var SubscriptionStatus = {
503
+ /** Newly created; the buyer hasn't paid yet. */
504
+ PendingCheckout: "pending_checkout",
505
+ /** Currently active. */
506
+ Active: "active",
507
+ /** `nextBillingCycle` passed with no payment yet. */
508
+ Due: "due",
509
+ /** Cancelled immediately (user-prompted). */
510
+ Cancelled: "cancelled",
511
+ /** Scheduled to cancel at the end of the current billing cycle — see SDK-SPEC.md §5's `cancel` note. */
512
+ PendingCancellation: "pending_cancellation",
513
+ /** Auto-ended after a grace period without payment. */
514
+ Inactive: "inactive"
515
+ };
516
+
517
+ // src/resources/serialization.ts
518
+ function serializeCustomerInput(customer) {
519
+ const wire = {
520
+ phone: customer.phone,
521
+ full_name: customer.fullName,
522
+ email: customer.email,
523
+ address: customer.address
524
+ };
525
+ if (customer.billing) {
526
+ const billing = {
527
+ billing_business_name: customer.billing.businessName,
528
+ billing_email: customer.billing.email,
529
+ billing_address: customer.billing.address
530
+ };
531
+ if (customer.billing.panVat !== void 0) billing.billing_pan_vat = customer.billing.panVat;
532
+ wire.billing = billing;
533
+ }
534
+ if (customer.shipping) {
535
+ const shipping = {
536
+ phone: customer.shipping.phone,
537
+ full_name: customer.shipping.fullName,
538
+ email: customer.shipping.email
539
+ };
540
+ if (customer.shipping.address !== void 0) shipping.address = customer.shipping.address;
541
+ wire.shipping = shipping;
542
+ }
543
+ return wire;
544
+ }
545
+ function deserializeSubscriptionCustomer(wire) {
546
+ if (!isRecord(wire)) return {};
547
+ const customer = {};
548
+ if (typeof wire.phone === "string") customer.phone = wire.phone;
549
+ if (typeof wire.full_name === "string") customer.fullName = wire.full_name;
550
+ if (typeof wire.email === "string") customer.email = wire.email;
551
+ if (typeof wire.address === "string") customer.address = wire.address;
552
+ if (isRecord(wire.billing)) {
553
+ customer.billing = {
554
+ ...typeof wire.billing.business_name === "string" ? { businessName: wire.billing.business_name } : {},
555
+ ...typeof wire.billing.email === "string" ? { email: wire.billing.email } : {},
556
+ ...typeof wire.billing.address === "string" ? { address: wire.billing.address } : {},
557
+ ...typeof wire.billing.pan_vat === "string" ? { panVat: wire.billing.pan_vat } : {}
558
+ };
559
+ } else if (wire.billing === null) {
560
+ customer.billing = null;
561
+ }
562
+ if (isRecord(wire.shipping)) {
563
+ customer.shipping = {
564
+ ...typeof wire.shipping.phone === "string" ? { phone: wire.shipping.phone } : {},
565
+ ...typeof wire.shipping.full_name === "string" ? { fullName: wire.shipping.full_name } : {},
566
+ ...typeof wire.shipping.email === "string" ? { email: wire.shipping.email } : {},
567
+ ...typeof wire.shipping.address === "string" ? { address: wire.shipping.address } : {}
568
+ };
569
+ } else if (wire.shipping === null) {
570
+ customer.shipping = null;
571
+ }
572
+ return customer;
573
+ }
574
+
575
+ // src/resources/subscriptions.ts
576
+ var SUBSCRIPTIONS_PATH = "/api/v1/subscriptions";
577
+ function deserializeSubscriptionProduct(wire) {
578
+ return {
579
+ productId: wire.product_id,
580
+ name: wire.name,
581
+ planName: wire.plan_name,
582
+ pbpId: wire.pbp_id,
583
+ label: wire.label,
584
+ price: wire.price,
585
+ currency: wire.currency
586
+ };
587
+ }
588
+ function deserializeSubscription(wire) {
589
+ return {
590
+ subscriptionId: wire.subscription_id,
591
+ status: wire.status,
592
+ isActive: wire.is_active,
593
+ // Renamed from the wire's `client` — SDK Naming Map v1.1 §11 "Customer boundary".
594
+ customer: deserializeSubscriptionCustomer(wire.client),
595
+ // `== null` (not `=== null`) is deliberate — same reasoning as Product's `vat` field: catches
596
+ // both an explicit `null` and an entirely omitted `product` key, either of which is spec-legal
597
+ // since `openapi.yaml`'s Subscription schema has no `required` list. The old unconditional call
598
+ // crashed on `deserializeSubscriptionProduct(undefined)` when the key was omitted (found in
599
+ // review, reproduced).
600
+ product: wire.product == null ? null : deserializeSubscriptionProduct(wire.product),
601
+ currentPeriodStart: wire.current_period_start,
602
+ currentPeriodEnd: wire.current_period_end,
603
+ nextBillingCycle: wire.next_billing_cycle,
604
+ createdAt: wire.created_at
605
+ };
606
+ }
607
+ function deserializeSubscriptionPage(wire) {
608
+ return {
609
+ count: wire.count,
610
+ next: wire.next,
611
+ previous: wire.previous,
612
+ totalSubscriptions: wire.total_subscriptions,
613
+ activeSubscriptions: wire.active_subscriptions,
614
+ dueSubscriptions: wire.due_subscriptions,
615
+ inactiveSubscriptions: wire.inactive_subscriptions,
616
+ results: wire.results.map(deserializeSubscription)
617
+ };
618
+ }
619
+ function deserializeCreateSubscriptionResponse(wire) {
620
+ return {
621
+ subscriptionId: wire.subscription_id,
622
+ pbpId: wire.pbp_id,
623
+ status: wire.status,
624
+ checkoutUrl: wire.checkout_url,
625
+ nextBillingCycle: wire.next_billing_cycle,
626
+ createdAt: wire.created_at
627
+ };
628
+ }
629
+ var SubscriptionsResource = class {
630
+ #http;
631
+ constructor(http) {
632
+ this.#http = http;
633
+ }
634
+ /**
635
+ * Lists the seller's subscriptions. Paginated, with four extra status counts alongside the
636
+ * common envelope (SDK-SPEC.md §6).
637
+ */
638
+ async list(params) {
639
+ const wire = await this.#http.request({
640
+ method: "GET",
641
+ path: SUBSCRIPTIONS_PATH,
642
+ query: toPageQuery(params)
643
+ });
644
+ return deserializeSubscriptionPage(wire);
645
+ }
646
+ /**
647
+ * Auto-iterates every subscription across every page, following `next` until it's `null`
648
+ * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently.
649
+ */
650
+ autoPaging(params) {
651
+ return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {
652
+ const wire = await this.#http.request({ method: "GET", path: nextUrl });
653
+ return deserializeSubscriptionPage(wire);
654
+ });
655
+ }
656
+ /**
657
+ * Creates a subscription in `pending_checkout` state and returns a checkout URL for the buyer
658
+ * to pay (SDK-SPEC.md §5). Redirect the buyer to `checkoutUrl`; the return is **not** proof of
659
+ * payment — learn the real outcome via the `checkout.succeeded`/`checkout.failed` webhooks.
660
+ *
661
+ * Reuse behavior: an inactive/expired subscription for the same buyer + product + billing
662
+ * period is reactivated rather than duplicated; only a currently `active` one triggers the
663
+ * duplicate-subscription `ValidationError`.
664
+ *
665
+ * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).
666
+ */
667
+ async create(params) {
668
+ const wire = await this.#http.request({
669
+ method: "POST",
670
+ path: SUBSCRIPTIONS_PATH,
671
+ body: {
672
+ pbp_id: params.pbpId,
673
+ return_url: params.returnUrl,
674
+ // Renamed from the wire's `client` — SDK Naming Map v1.1 §11 "Customer boundary".
675
+ client: serializeCustomerInput(params.customer)
676
+ }
677
+ });
678
+ return deserializeCreateSubscriptionResponse(wire);
679
+ }
680
+ /**
681
+ * Schedules cancellation for the end of the current billing period — **not** immediate
682
+ * (confirmed with backend 2026-08-17; immediate cancellation is a future capability). Status
683
+ * moves to `pending_cancellation`; the subscription stays active until the period ends.
684
+ *
685
+ * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).
686
+ */
687
+ async cancel(id) {
688
+ return this.#http.request({
689
+ method: "POST",
690
+ path: `${SUBSCRIPTIONS_PATH}/${encodeURIComponent(id)}/cancel`
691
+ });
692
+ }
693
+ /**
694
+ * Sets a subscription's next billing date. Collection-level action — the subscription id
695
+ * travels in the body, not the path, mirroring the wire (SDK Naming Map v1.1 §04).
696
+ *
697
+ * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).
698
+ */
699
+ async updateBillingCycle(params) {
700
+ return this.#http.request({
701
+ method: "POST",
702
+ path: `${SUBSCRIPTIONS_PATH}/update-billing-cycle`,
703
+ body: {
704
+ subscription_id: params.subscriptionId,
705
+ next_billing_cycle: params.nextBillingCycle
706
+ }
707
+ });
708
+ }
709
+ /**
710
+ * Resumes a subscription. Confirmed public with backend (2026-08-18); the response shape
711
+ * follows Swagger's `{ message }` example but — unlike Customers — isn't independently
712
+ * confirmed, so treat it as likely-correct-but-unverified (docs/implementation-plan.md Ticket 4).
713
+ *
714
+ * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).
715
+ */
716
+ async resume(id) {
717
+ return this.#http.request({
718
+ method: "POST",
719
+ path: `${SUBSCRIPTIONS_PATH}/${encodeURIComponent(id)}/resume`
720
+ });
721
+ }
722
+ };
723
+
724
+ // src/resources/customers.ts
725
+ var CUSTOMERS_PATH = "/api/v1/customers";
726
+ function deserializeCustomer(wire) {
727
+ return {
728
+ id: wire.id,
729
+ buyerPhone: wire.buyer_phone,
730
+ buyerEmail: wire.buyer_email,
731
+ fullName: wire.full_name,
732
+ createdAt: wire.created_at
733
+ };
734
+ }
735
+ var CustomersResource = class {
736
+ #http;
737
+ constructor(http) {
738
+ this.#http = http;
739
+ }
740
+ /** Lists the authenticated seller's customers. Paginated (SDK-SPEC.md §6). */
741
+ async list(params) {
742
+ const wire = await this.#http.request({
743
+ method: "GET",
744
+ path: CUSTOMERS_PATH,
745
+ query: toPageQuery(params)
746
+ });
747
+ return deserializePage(wire, deserializeCustomer);
748
+ }
749
+ /**
750
+ * Auto-iterates every customer across every page, following `next` until it's `null`
751
+ * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently — this is
752
+ * additive, not a replacement.
753
+ */
754
+ autoPaging(params) {
755
+ return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {
756
+ const wire = await this.#http.request({ method: "GET", path: nextUrl });
757
+ return deserializePage(wire, deserializeCustomer);
758
+ });
759
+ }
760
+ /**
761
+ * Retrieves a single customer by id. Unlike every other resource in this API, `id` is an
762
+ * **integer**, not a UUID (SDK-SPEC.md §5 naming note; `openapi.yaml` `Customer.id`).
763
+ */
764
+ async retrieve(id) {
765
+ const wire = await this.#http.request({
766
+ method: "GET",
767
+ path: `${CUSTOMERS_PATH}/${encodeURIComponent(id)}`
768
+ });
769
+ return deserializeCustomer(wire);
770
+ }
771
+ };
772
+ var DEFAULT_TOLERANCE_SEC = 300;
773
+ var SIGNATURE_PREFIX = "sha256=";
774
+ var HEX_DIGEST_RE = /^[0-9a-f]{64}$/i;
775
+ var WebhooksResource = class {
776
+ /**
777
+ * Verifies an inbound webhook delivery's signature. Returns `false` for any failure mode —
778
+ * malformed signature, expired timestamp, or a genuine mismatch — never throws, so a caller
779
+ * never needs a `try`/`catch` just to check a delivery.
780
+ *
781
+ * @example
782
+ * ```ts
783
+ * // Express: mount express.raw() on this route so req.body is a Buffer, not parsed JSON.
784
+ * const ok = suqo.webhooks.verify({
785
+ * rawBody: req.body,
786
+ * signature: req.header("X-SUQO-Signature")!,
787
+ * timestamp: req.header("X-SUQO-Timestamp")!,
788
+ * secret: process.env.SUQO_WEBHOOK_SECRET!,
789
+ * });
790
+ * ```
791
+ */
792
+ verify(options) {
793
+ const { rawBody, signature, timestamp, secret, toleranceSec = DEFAULT_TOLERANCE_SEC } = options;
794
+ if (typeof signature !== "string" || typeof timestamp !== "string" || typeof secret !== "string") {
795
+ return false;
796
+ }
797
+ if (typeof rawBody !== "string" && !Buffer.isBuffer(rawBody)) {
798
+ return false;
799
+ }
800
+ if (!signature.startsWith(SIGNATURE_PREFIX)) return false;
801
+ const providedHex = signature.slice(SIGNATURE_PREFIX.length);
802
+ if (!HEX_DIGEST_RE.test(providedHex)) return false;
803
+ if (timestamp.trim().length === 0) return false;
804
+ const timestampSeconds = Number(timestamp);
805
+ if (!Number.isFinite(timestampSeconds)) return false;
806
+ const nowSeconds = Date.now() / 1e3;
807
+ if (Math.abs(nowSeconds - timestampSeconds) > toleranceSec) return false;
808
+ const expectedHex = createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex");
809
+ const provided = Buffer.from(providedHex, "hex");
810
+ const expected = Buffer.from(expectedHex, "hex");
811
+ if (provided.length !== expected.length) return false;
812
+ return timingSafeEqual(provided, expected);
813
+ }
814
+ };
815
+
816
+ // src/client.ts
817
+ var SuqoClient = class {
818
+ #config;
819
+ constructor(options) {
820
+ this.#config = new SdkConfig(options);
821
+ const http = new HttpClient(this.#config);
822
+ this.products = new ProductsResource(http);
823
+ this.subscriptions = new SubscriptionsResource(http);
824
+ this.customers = new CustomersResource(http);
825
+ this.webhooks = new WebhooksResource();
826
+ }
827
+ /** `"sandbox" | "live"` — inferred from the key prefix, never selected explicitly (SDK-SPEC.md §2). */
828
+ get environment() {
829
+ return this.#config.environment;
830
+ }
831
+ /** The resolved base URL this client sends requests to. */
832
+ get baseUrl() {
833
+ return this.#config.baseUrl;
834
+ }
835
+ /** The effective request timeout in milliseconds (default 30_000). */
836
+ get timeout() {
837
+ return this.#config.timeout;
838
+ }
839
+ /** The effective max retry count for idempotent reads (default 2). */
840
+ get maxRetries() {
841
+ return this.#config.maxRetries;
842
+ }
843
+ /** Redacts the key so it never appears in `JSON.stringify` output (SDK-SPEC.md §4). */
844
+ toJSON() {
845
+ return this.#config.toJSON();
846
+ }
847
+ /** Redacts the key so it never appears in `util.inspect`/`console.log` output (SDK-SPEC.md §4). */
848
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
849
+ return this.toJSON();
850
+ }
851
+ };
852
+
853
+ // src/index.ts
854
+ var VERSION = "1.0.0";
855
+
856
+ export { AuthenticationError, KycRequiredError, NetworkError, NotFoundError, RateLimitError, ServerError, SubscriptionStatus, SuqoClient, SuqoConfigError, SuqoError, VERSION, ValidationError, bridgeAutoPaging, deserializePage, listAll, mapHttpError, toPageQuery };
857
+ //# sourceMappingURL=index.js.map
858
+ //# sourceMappingURL=index.js.map