@thorprovider/medusa-extended 1.14.0 → 1.14.2

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.mjs DELETED
@@ -1,2168 +0,0 @@
1
- // src/admin.ts
2
- import { createLogger, ProviderAPIError as ProviderAPIError2 } from "@thorprovider/adapters";
3
-
4
- // src/request-resilience.ts
5
- import { ProviderAPIError, backendCircuitBreaker } from "@thorprovider/adapters";
6
- var DEFAULT_RETRY_CONFIG = {
7
- maxRetries: 3,
8
- initialDelayMs: 300,
9
- backoffMultiplier: 2,
10
- maxDelayMs: 5e3,
11
- timeoutMs: 1e4,
12
- retryableStatusCodes: [408, 429, 500, 502, 503, 504]
13
- };
14
- function sleep(ms) {
15
- return new Promise((resolve) => setTimeout(resolve, ms));
16
- }
17
- function calculateDelay(attempt, config) {
18
- const delay = config.initialDelayMs * Math.pow(config.backoffMultiplier, attempt);
19
- return Math.min(delay, config.maxDelayMs);
20
- }
21
- function isRetryableError(error, config) {
22
- const err = error;
23
- if (err.name === "TypeError" || err.message?.includes("fetch failed")) return true;
24
- if (err.name === "AbortError" || err.message?.includes("timeout")) return true;
25
- if (typeof err.status === "number" && config.retryableStatusCodes.includes(err.status)) return true;
26
- return false;
27
- }
28
- async function fetchWithRetry(url, init, retryConfig) {
29
- const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };
30
- const method = (init.method || "GET").toUpperCase();
31
- const isMutation = ["POST", "PUT", "PATCH", "DELETE"].includes(method);
32
- let lastError;
33
- for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
34
- try {
35
- const controller = new AbortController();
36
- const timeoutId = setTimeout(() => controller.abort(), config.timeoutMs);
37
- const response = await fetch(url, { ...init, signal: controller.signal });
38
- clearTimeout(timeoutId);
39
- if (!response.ok && config.retryableStatusCodes.includes(response.status)) {
40
- const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
41
- error.status = response.status;
42
- throw error;
43
- }
44
- return response;
45
- } catch (error) {
46
- lastError = error;
47
- const isTimeoutOrNetwork = error instanceof Error && (error.name === "AbortError" || error.message?.includes("timeout") || error.message?.includes("fetch failed"));
48
- if (isMutation && isTimeoutOrNetwork) {
49
- break;
50
- }
51
- const shouldRetry = attempt < config.maxRetries && isRetryableError(error, config);
52
- if (shouldRetry) {
53
- await sleep(calculateDelay(attempt, config));
54
- continue;
55
- }
56
- break;
57
- }
58
- }
59
- throw lastError instanceof Error ? lastError : new Error("Backend request failed");
60
- }
61
- async function fetchBackendWithResilience(url, init, retryConfig) {
62
- try {
63
- return await backendCircuitBreaker.execute(() => fetchWithRetry(url, init, retryConfig));
64
- } catch (error) {
65
- const message = error instanceof Error ? error.message : String(error);
66
- throw new ProviderAPIError(`Backend request failed: ${message}`, "backend", 503);
67
- }
68
- }
69
-
70
- // src/admin.ts
71
- var MedusaAdminClient = class {
72
- baseUrl;
73
- apiKey;
74
- logger;
75
- constructor(config) {
76
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
77
- this.apiKey = config.apiKey;
78
- this.logger = createLogger("MedusaAdminClient", config.debug);
79
- }
80
- // -----------------------------------------------------------------------
81
- // Private — HTTP helper
82
- // -----------------------------------------------------------------------
83
- async request(method, path, body) {
84
- const url = `${this.baseUrl}${path}`;
85
- this.logger.debug(`[admin] ${method} ${path}`);
86
- const headers = {
87
- "x-medusa-access-token": this.apiKey,
88
- "Content-Type": "application/json"
89
- };
90
- const init = {
91
- method,
92
- headers,
93
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
94
- };
95
- let response;
96
- try {
97
- response = await fetchBackendWithResilience(url, init);
98
- } catch (networkError) {
99
- throw new ProviderAPIError2(
100
- `[admin] Network error on ${method} ${path}: ${networkError.message}`,
101
- "NETWORK_ERROR",
102
- networkError
103
- );
104
- }
105
- if (!response.ok) {
106
- let message = `HTTP ${response.status}`;
107
- try {
108
- const json = await response.json();
109
- message = json?.message ?? message;
110
- } catch {
111
- }
112
- throw new ProviderAPIError2(
113
- `[admin] ${method} ${path} failed: ${message}`,
114
- `ADMIN_API_${response.status}`,
115
- response.status
116
- );
117
- }
118
- return response.json();
119
- }
120
- // -----------------------------------------------------------------------
121
- // 3.1 — Sales Channel: Customers
122
- // -----------------------------------------------------------------------
123
- /**
124
- * Paginated list of customers linked to a sales channel.
125
- *
126
- * `GET /admin/thor/sales-channels/:id/customers`
127
- */
128
- async getChannelCustomers(salesChannelId, options = {}) {
129
- const { limit = 20, offset = 0 } = options;
130
- return this.request(
131
- "GET",
132
- `/admin/thor/sales-channels/${salesChannelId}/customers?limit=${limit}&offset=${offset}`
133
- );
134
- }
135
- // -----------------------------------------------------------------------
136
- // 3.2 — Sales Channel: API Keys
137
- // -----------------------------------------------------------------------
138
- /**
139
- * Publishable API keys associated with a sales channel.
140
- *
141
- * `GET /admin/thor/sales-channels/:id/api-keys`
142
- */
143
- async getChannelApiKeys(salesChannelId) {
144
- return this.request(
145
- "GET",
146
- `/admin/thor/sales-channels/${salesChannelId}/api-keys`
147
- );
148
- }
149
- // -----------------------------------------------------------------------
150
- // 3.3 — Sales Channel: Categories
151
- // -----------------------------------------------------------------------
152
- /**
153
- * Product categories assigned to a sales channel.
154
- *
155
- * `GET /admin/thor/sales-channels/:id/categories`
156
- */
157
- async getChannelCategories(salesChannelId, options = {}) {
158
- const { limit = 20, offset = 0, include_descendants = false } = options;
159
- const qs = new URLSearchParams({
160
- limit: String(limit),
161
- offset: String(offset),
162
- include_descendants: String(include_descendants)
163
- });
164
- return this.request(
165
- "GET",
166
- `/admin/thor/sales-channels/${salesChannelId}/categories?${qs}`
167
- );
168
- }
169
- // -----------------------------------------------------------------------
170
- // 3.4 — Category: Sales Channels
171
- // -----------------------------------------------------------------------
172
- /**
173
- * Sales channels to which a category is assigned.
174
- *
175
- * `GET /admin/thor/categories/:id/sales-channels`
176
- */
177
- async getCategorySalesChannels(categoryId) {
178
- return this.request(
179
- "GET",
180
- `/admin/thor/categories/${categoryId}/sales-channels`
181
- );
182
- }
183
- // -----------------------------------------------------------------------
184
- // 3.5 — Category: Assign to Sales Channels
185
- // -----------------------------------------------------------------------
186
- /**
187
- * Assign a category to one or more sales channels (idempotent).
188
- *
189
- * `POST /admin/thor/categories/:id/sales-channels`
190
- */
191
- async assignCategoryToChannels(categoryId, body) {
192
- return this.request(
193
- "POST",
194
- `/admin/thor/categories/${categoryId}/sales-channels`,
195
- body
196
- );
197
- }
198
- // -----------------------------------------------------------------------
199
- // 3.6 — Category: Unassign from Sales Channels
200
- // -----------------------------------------------------------------------
201
- /**
202
- * Remove category assignment from one or more sales channels (idempotent).
203
- *
204
- * `DELETE /admin/thor/categories/:id/sales-channels`
205
- */
206
- async unassignCategoryFromChannels(categoryId, body) {
207
- return this.request(
208
- "DELETE",
209
- `/admin/thor/categories/${categoryId}/sales-channels`,
210
- body
211
- );
212
- }
213
- // -----------------------------------------------------------------------
214
- // 3.7 — Collection: Sales Channels
215
- // -----------------------------------------------------------------------
216
- /**
217
- * Sales channels to which a collection is assigned.
218
- *
219
- * `GET /admin/thor/collections/:id/sales-channels`
220
- */
221
- async getCollectionSalesChannels(collectionId) {
222
- return this.request(
223
- "GET",
224
- `/admin/thor/collections/${collectionId}/sales-channels`
225
- );
226
- }
227
- // -----------------------------------------------------------------------
228
- // 3.8 — Collection: Assign to Sales Channels
229
- // -----------------------------------------------------------------------
230
- /**
231
- * Assign a collection to one or more sales channels (idempotent).
232
- *
233
- * `POST /admin/thor/collections/:id/sales-channels`
234
- */
235
- async assignCollectionToChannels(collectionId, body) {
236
- return this.request(
237
- "POST",
238
- `/admin/thor/collections/${collectionId}/sales-channels`,
239
- body
240
- );
241
- }
242
- // -----------------------------------------------------------------------
243
- // 3.9 — Collection: Unassign from Sales Channels
244
- // -----------------------------------------------------------------------
245
- /**
246
- * Remove collection assignment from one or more sales channels (idempotent).
247
- *
248
- * `DELETE /admin/thor/collections/:id/sales-channels`
249
- */
250
- async unassignCollectionFromChannels(collectionId, body) {
251
- return this.request(
252
- "DELETE",
253
- `/admin/thor/collections/${collectionId}/sales-channels`,
254
- body
255
- );
256
- }
257
- // -----------------------------------------------------------------------
258
- // 3.10 — Storefront Config: Read
259
- // -----------------------------------------------------------------------
260
- /**
261
- * Read the visual storefront configuration for a channel.
262
- * `:id` is the `sales_channel_id`.
263
- *
264
- * `GET /admin/thor/storefront-config/:id`
265
- */
266
- async getStorefrontConfig(salesChannelId) {
267
- return this.request(
268
- "GET",
269
- `/admin/thor/storefront-config/${salesChannelId}`
270
- );
271
- }
272
- // -----------------------------------------------------------------------
273
- // 3.11 — Storefront Config: Update
274
- // -----------------------------------------------------------------------
275
- /**
276
- * Update the visual storefront configuration for a channel.
277
- * Triggers the `storefront_config.updated` event → ISR webhook.
278
- *
279
- * `PUT /admin/thor/storefront-config/:id`
280
- */
281
- async updateStorefrontConfig(salesChannelId, body) {
282
- return this.request(
283
- "PUT",
284
- `/admin/thor/storefront-config/${salesChannelId}`,
285
- body
286
- );
287
- }
288
- // -----------------------------------------------------------------------
289
- // 3.12 — Site Designer Config: Read
290
- // -----------------------------------------------------------------------
291
- /**
292
- * Read the active Site Designer configuration for a channel, including the
293
- * last 10 history entries.
294
- *
295
- * `GET /admin/thor/site-config/:sales_channel_id`
296
- */
297
- async getSiteConfig(salesChannelId) {
298
- return this.request(
299
- "GET",
300
- `/admin/thor/site-config/${salesChannelId}`
301
- );
302
- }
303
- // -----------------------------------------------------------------------
304
- // 3.13 — Site Designer Config: Update
305
- // -----------------------------------------------------------------------
306
- /**
307
- * Update the Site Designer configuration for a channel.
308
- * Creates a new history entry on every PUT.
309
- *
310
- * `PUT /admin/thor/site-config/:sales_channel_id`
311
- */
312
- async updateSiteConfig(salesChannelId, body) {
313
- return this.request(
314
- "PUT",
315
- `/admin/thor/site-config/${salesChannelId}`,
316
- body
317
- );
318
- }
319
- // -----------------------------------------------------------------------
320
- // 3.14 — Site Designer Config: History
321
- // -----------------------------------------------------------------------
322
- /**
323
- * Full paginated history of Site Designer versions for a channel.
324
- * Entries are immutable — they are never deleted.
325
- *
326
- * `GET /admin/thor/site-config/:sales_channel_id/history`
327
- */
328
- async getSiteConfigHistory(salesChannelId, options = {}) {
329
- const { limit = 20, offset = 0 } = options;
330
- return this.request(
331
- "GET",
332
- `/admin/thor/site-config/${salesChannelId}/history?limit=${limit}&offset=${offset}`
333
- );
334
- }
335
- // -----------------------------------------------------------------------
336
- // 3.15 — Site Designer Config: Restore
337
- // -----------------------------------------------------------------------
338
- /**
339
- * Restore a previous Site Designer version.
340
- * Internally runs the update workflow with the stored config of the target
341
- * version — this creates a **new** history entry and does NOT mutate past
342
- * entries.
343
- *
344
- * `POST /admin/thor/site-config/:sales_channel_id/restore/:version`
345
- */
346
- async restoreSiteConfig(salesChannelId, version) {
347
- return this.request(
348
- "POST",
349
- `/admin/thor/site-config/${salesChannelId}/restore/${encodeURIComponent(version)}`
350
- );
351
- }
352
- };
353
-
354
- // src/dropshipper.ts
355
- import { createLogger as createLogger2, ProviderAPIError as ProviderAPIError3 } from "@thorprovider/adapters";
356
- var DropshipperClient = class {
357
- baseUrl;
358
- token;
359
- logger;
360
- constructor(config) {
361
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
362
- this.token = config.token;
363
- this.logger = createLogger2("DropshipperClient", config.debug);
364
- }
365
- // -------------------------------------------------------------------------
366
- // Private — HTTP helper
367
- // -------------------------------------------------------------------------
368
- async request(method, path, body) {
369
- const url = `${this.baseUrl}${path}`;
370
- this.logger.debug(`[dropshipper] ${method} ${path}`);
371
- const headers = {
372
- Authorization: `Bearer ${this.token}`,
373
- "Content-Type": "application/json"
374
- };
375
- const init = {
376
- method,
377
- headers,
378
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
379
- };
380
- let response;
381
- try {
382
- response = await fetchBackendWithResilience(url, init);
383
- } catch (networkError) {
384
- throw new ProviderAPIError3(
385
- `[dropshipper] Network error on ${method} ${path}: ${networkError.message}`,
386
- "NETWORK_ERROR",
387
- networkError
388
- );
389
- }
390
- if (!response.ok) {
391
- let message = `HTTP ${response.status}`;
392
- try {
393
- const json = await response.json();
394
- message = json?.message ?? message;
395
- } catch {
396
- }
397
- throw new ProviderAPIError3(
398
- `[dropshipper] ${method} ${path} failed: ${message}`,
399
- `DROPSHIPPER_API_${response.status}`,
400
- response.status
401
- );
402
- }
403
- return response.json();
404
- }
405
- // -------------------------------------------------------------------------
406
- // Unified Query
407
- // -------------------------------------------------------------------------
408
- /**
409
- * Resolve multiple entities in a single request.
410
- *
411
- * `POST /admin/thor/dropshipper/query`
412
- *
413
- * Entities are resolved in parallel (per layer) and errors are isolated per
414
- * entity: `response.errors[key]` holds the per-entity error while the rest
415
- * of `data` still resolves. `data[key]` is an array (list entities) or a
416
- * single object (singular entities such as account, balance, me).
417
- *
418
- * @example
419
- * ```typescript
420
- * const { data } = await client.query({
421
- * entities: [
422
- * { entity: 'capabilities' },
423
- * { entity: 'me' },
424
- * { entity: 'account' },
425
- * ],
426
- * });
427
- * ```
428
- */
429
- async query(input) {
430
- return this.request(
431
- "POST",
432
- "/admin/thor/dropshipper/query",
433
- input
434
- );
435
- }
436
- // -------------------------------------------------------------------------
437
- // Capabilities
438
- // -------------------------------------------------------------------------
439
- /**
440
- * Fetch dashboard capabilities from the backend.
441
- *
442
- * `GET /admin/thor/dropshipper/capabilities`
443
- */
444
- async getCapabilities() {
445
- return this.request(
446
- "GET",
447
- "/admin/thor/dropshipper/capabilities"
448
- );
449
- }
450
- /**
451
- * Fetch the authenticated dropshipper's personal profile including
452
- * first_name, last_name, email, avatar_url, and linked sales channel.
453
- *
454
- * `GET /admin/thor/dropshipper/me`
455
- */
456
- async getMyProfile() {
457
- return this.request(
458
- "GET",
459
- "/admin/thor/dropshipper/me"
460
- );
461
- }
462
- /**
463
- * Send a chat message to the AI assistant (catalog intelligence).
464
- * The conversation is stateless — the client sends the full message
465
- * history on every request.
466
- *
467
- * `POST /admin/thor/dropshipper/ai/chat`
468
- *
469
- * @example
470
- * ```typescript
471
- * const { answer, sources } = await client.chatAssistant({
472
- * messages: [{ role: 'user', content: 'productos con mejor margen' }],
473
- * });
474
- * ```
475
- */
476
- async chatAssistant(body) {
477
- return this.request(
478
- "POST",
479
- "/admin/thor/dropshipper/ai/chat",
480
- body
481
- );
482
- }
483
- /**
484
- * Stream the AI assistant's reply.
485
- *
486
- * Unlike `chatAssistant`, this surfaces the model's progress: the backend
487
- * resolves the intent first and then streams the answer token by token
488
- * (catalog searches) or returns the full answer in one shot (`default`).
489
- * The response is normalized into a single `ReadableStream<ChatStreamEvent>`
490
- * so callers can show a live "thinking" label and render text incrementally.
491
- *
492
- * `POST /admin/thor/dropshipper/ai/chat`
493
- */
494
- async chatAssistantStream(body) {
495
- const url = `${this.baseUrl}/admin/thor/dropshipper/ai/chat`;
496
- this.logger.debug("[dropshipper] POST /admin/thor/dropshipper/ai/chat (stream)");
497
- const init = {
498
- method: "POST",
499
- headers: {
500
- Authorization: `Bearer ${this.token}`,
501
- "Content-Type": "application/json",
502
- Accept: "text/event-stream"
503
- },
504
- body: JSON.stringify(body)
505
- };
506
- let response;
507
- try {
508
- response = await fetchBackendWithResilience(url, init, {
509
- timeoutMs: 6e4,
510
- maxRetries: 1
511
- });
512
- } catch (networkError) {
513
- throw new ProviderAPIError3(
514
- `[dropshipper] Network error on POST /admin/thor/dropshipper/ai/chat: ${networkError.message}`,
515
- "NETWORK_ERROR",
516
- networkError
517
- );
518
- }
519
- if (!response.ok) {
520
- let message = `HTTP ${response.status}`;
521
- let errorCode;
522
- let requestId;
523
- let details;
524
- try {
525
- const json = await response.json();
526
- message = json?.message ?? message;
527
- errorCode = json?.error_code ?? json?.type;
528
- requestId = json?.request_id;
529
- details = json?.details;
530
- } catch {
531
- }
532
- this.logger.error(
533
- `[dropshipper] POST /admin/thor/dropshipper/ai/chat failed status=${response.status} message=${message}` + (errorCode ? ` error_code=${errorCode}` : "") + (requestId ? ` request_id=${requestId}` : "") + (details ? ` details=${details}` : "")
534
- );
535
- throw new ProviderAPIError3(
536
- `[dropshipper] POST /admin/thor/dropshipper/ai/chat failed: ${message}`,
537
- `DROPSHIPPER_API_${response.status}`,
538
- response.status,
539
- {
540
- message,
541
- status: response.status,
542
- errorCode,
543
- requestId,
544
- details
545
- }
546
- );
547
- }
548
- const contentType = response.headers.get("content-type") ?? "";
549
- if (contentType.includes("text/event-stream") && response.body) {
550
- return mapUiMessageStreamToEvents(response.body, this.logger);
551
- }
552
- const data = await response.json();
553
- return new ReadableStream({
554
- start(controller) {
555
- controller.enqueue({ type: "start", intent: data.intent });
556
- controller.enqueue({ type: "text-delta", delta: data.answer });
557
- controller.enqueue({
558
- type: "finish",
559
- intent: data.intent,
560
- sources: data.sources ?? []
561
- });
562
- controller.close();
563
- }
564
- });
565
- }
566
- /**
567
- * Cheap liveness probe for the AI assistant.
568
- *
569
- * The backend performs no LLM or retrieval work, so this is safe to poll
570
- * (e.g. from a dashboard availability indicator). Returns 200 with
571
- * `available: true` when the assistant is configured; the backend answers
572
- * HTTP 503 with `available: false` when `AI_GATEWAY_API_KEY` is missing.
573
- *
574
- * Deliberately does NOT go through `fetchBackendWithResilience`: that layer
575
- * funnels every call through the SHARED `backendCircuitBreaker`, and the
576
- * definitive 503 "not configured" answer would count as failures and could
577
- * open the circuit, taking down all dropshipper API traffic. A health probe
578
- * must stay isolated, with no retries and a short timeout.
579
- *
580
- * `GET /admin/thor/dropshipper/ai/health`
581
- */
582
- async chatAssistantHealth() {
583
- const url = `${this.baseUrl}/admin/thor/dropshipper/ai/health`;
584
- const controller = new AbortController();
585
- const timeoutId = setTimeout(() => controller.abort(), 5e3);
586
- let response;
587
- try {
588
- response = await fetch(url, {
589
- method: "GET",
590
- headers: { Authorization: `Bearer ${this.token}` },
591
- signal: controller.signal,
592
- cache: "no-store"
593
- });
594
- } catch (error) {
595
- clearTimeout(timeoutId);
596
- throw new ProviderAPIError3(
597
- `[dropshipper] Network error on GET /admin/thor/dropshipper/ai/health: ${error.message}`,
598
- "NETWORK_ERROR",
599
- 0
600
- );
601
- }
602
- clearTimeout(timeoutId);
603
- if (response.status === 503) {
604
- try {
605
- const body = await response.json();
606
- if (body && typeof body.available === "boolean") {
607
- return body;
608
- }
609
- } catch {
610
- }
611
- }
612
- if (!response.ok) {
613
- throw new ProviderAPIError3(
614
- `[dropshipper] GET /admin/thor/dropshipper/ai/health failed: HTTP ${response.status}`,
615
- `DROPSHIPPER_API_${response.status}`,
616
- response.status
617
- );
618
- }
619
- return response.json();
620
- }
621
- // -------------------------------------------------------------------------
622
- // Notifications
623
- // -------------------------------------------------------------------------
624
- /**
625
- * List feed notifications for the authenticated dropshipper.
626
- *
627
- * `GET /admin/thor/dropshipper/notifications`
628
- */
629
- async getNotifications(options = {}) {
630
- const { limit = 20, offset = 0 } = options;
631
- const qs = new URLSearchParams({
632
- limit: String(limit),
633
- offset: String(offset)
634
- });
635
- return this.request(
636
- "GET",
637
- `/admin/thor/dropshipper/notifications?${qs}`
638
- );
639
- }
640
- /**
641
- * Get the authenticated dropshipper's notification preferences.
642
- *
643
- * `GET /admin/thor/dropshipper/notifications/preferences`
644
- */
645
- async getNotificationPreferences() {
646
- return this.request(
647
- "GET",
648
- "/admin/thor/dropshipper/notifications/preferences"
649
- );
650
- }
651
- /**
652
- * Update the authenticated dropshipper's notification preferences.
653
- *
654
- * `PATCH /admin/thor/dropshipper/notifications/preferences`
655
- */
656
- async updateNotificationPreferences(body) {
657
- return this.request(
658
- "PATCH",
659
- "/admin/thor/dropshipper/notifications/preferences",
660
- body
661
- );
662
- }
663
- // -------------------------------------------------------------------------
664
- // Onboarding (Solo X)
665
- // -------------------------------------------------------------------------
666
- /**
667
- * Create a new dropshipper account (sales channel + user + price list).
668
- *
669
- * `POST /admin/thor/dropshipper/onboard`
670
- */
671
- async onboardDropshipper(body) {
672
- return this.request(
673
- "POST",
674
- "/admin/thor/dropshipper/onboard",
675
- body
676
- );
677
- }
678
- // -------------------------------------------------------------------------
679
- // Products (Solo Y)
680
- // -------------------------------------------------------------------------
681
- /**
682
- * List products available in Y's channel with cost/margin data.
683
- *
684
- * `GET /admin/thor/dropshipper/products`
685
- */
686
- async getProducts(options = {}) {
687
- const { q, category_id, collection_id, status, in_stock, limit = 20, offset = 0 } = options;
688
- const qs = new URLSearchParams({
689
- limit: String(limit),
690
- offset: String(offset),
691
- ...q ? { q } : {},
692
- ...category_id ? { category_id } : {},
693
- ...collection_id ? { collection_id } : {},
694
- ...status ? { status } : {},
695
- ...in_stock !== void 0 ? { in_stock: String(in_stock) } : {}
696
- });
697
- return this.request(
698
- "GET",
699
- `/admin/thor/dropshipper/products?${qs}`
700
- );
701
- }
702
- /**
703
- * Validate cart items for checkout — returns current availableQuantity, sale_price,
704
- * and cost_price for each variant so the client can detect stale prices or
705
- * insufficient stock before creating an order or converting a draft.
706
- *
707
- * `POST /admin/thor/dropshipper/checkout/validate`
708
- */
709
- async validateCheckoutItems(body) {
710
- return this.request(
711
- "POST",
712
- "/admin/thor/dropshipper/checkout/validate",
713
- body
714
- );
715
- }
716
- /**
717
- * Check whether cost prices have changed since the last acknowledgment.
718
- * Compares a hash of all base cost prices from the channel's price list
719
- * against a stored snapshot on the dropshipper account.
720
- *
721
- * `GET /admin/thor/dropshipper/cost-prices/has-changes`
722
- */
723
- async checkCostPriceChanges() {
724
- return this.request(
725
- "GET",
726
- "/admin/thor/dropshipper/cost-prices/has-changes"
727
- );
728
- }
729
- /**
730
- * Get the full diff of cost price changes since the last acknowledgment.
731
- * Returns product/variant info with old and new cost prices.
732
- *
733
- * `GET /admin/thor/dropshipper/cost-prices/changes`
734
- */
735
- async getCostPriceChanges() {
736
- return this.request(
737
- "GET",
738
- "/admin/thor/dropshipper/cost-prices/changes"
739
- );
740
- }
741
- /**
742
- * Acknowledge current cost prices as reviewed. Stores the current hash
743
- * and snapshot so subsequent checks will not report these prices as changed.
744
- *
745
- * `POST /admin/thor/dropshipper/cost-prices/acknowledge`
746
- */
747
- async acknowledgeCostPriceChanges() {
748
- return this.request(
749
- "POST",
750
- "/admin/thor/dropshipper/cost-prices/acknowledge"
751
- );
752
- }
753
- /**
754
- * Toggle whether a product is visible in the public store for the current sales channel.
755
- * This does not mutate the shared global Medusa product status.
756
- *
757
- * `POST /admin/thor/dropshipper/products/:id/status`
758
- */
759
- async updateProductStatus(productId, body) {
760
- return this.request(
761
- "POST",
762
- `/admin/thor/dropshipper/products/${productId}/status`,
763
- body
764
- );
765
- }
766
- /**
767
- * Fetch custom attribute values assigned to a product, grouped by attribute.
768
- *
769
- * `GET /admin/thor/dropshipper/products/:id/attributes`
770
- */
771
- async getProductAttributes(productId) {
772
- return this.request(
773
- "GET",
774
- `/admin/thor/dropshipper/products/${productId}/attributes`
775
- );
776
- }
777
- /**
778
- * List attribute definitions (with their possible values) scoped to the
779
- * dropshipper's channel. Only attributes linked to at least one channel
780
- * product are returned.
781
- *
782
- * `GET /admin/thor/dropshipper/attributes`
783
- */
784
- async getAttributes() {
785
- return this.request(
786
- "GET",
787
- "/admin/thor/dropshipper/attributes"
788
- );
789
- }
790
- // -------------------------------------------------------------------------
791
- // Prices (Solo Y)
792
- // -------------------------------------------------------------------------
793
- /**
794
- * Bulk-update product and variant margins on Y's channel price list.
795
- *
796
- * `PUT /admin/thor/dropshipper/prices`
797
- */
798
- async updatePrices(body) {
799
- return this.request(
800
- "PUT",
801
- "/admin/thor/dropshipper/prices",
802
- body
803
- );
804
- }
805
- // -------------------------------------------------------------------------
806
- // Orders (Y + X for set-payment-collector)
807
- // -------------------------------------------------------------------------
808
- /**
809
- * Paginated list of orders in Y's channel.
810
- *
811
- * `GET /admin/thor/dropshipper/orders`
812
- */
813
- async getOrders(options = {}) {
814
- const { status, payment_collector, settlement_status, from, to, q, customer_id, limit = 20, offset = 0 } = options;
815
- const qs = new URLSearchParams({
816
- limit: String(limit),
817
- offset: String(offset),
818
- ...status ? { status } : {},
819
- ...payment_collector ? { payment_collector } : {},
820
- ...settlement_status ? { settlement_status } : {},
821
- ...from ? { from } : {},
822
- ...to ? { to } : {},
823
- ...q ? { q } : {},
824
- ...customer_id ? { customer_id } : {}
825
- });
826
- return this.request(
827
- "GET",
828
- `/admin/thor/dropshipper/orders?${qs}`
829
- );
830
- }
831
- /**
832
- * Full detail for a single order with profit breakdown.
833
- *
834
- * `GET /admin/thor/dropshipper/orders/:id`
835
- */
836
- async getOrder(orderId) {
837
- return this.request(
838
- "GET",
839
- `/admin/thor/dropshipper/orders/${orderId}`
840
- );
841
- }
842
- /**
843
- * List shipping groups and their valid options for a manual dropshipper order.
844
- *
845
- * `POST /admin/thor/dropshipper/orders/shipping-options`
846
- */
847
- async getOrderShippingOptions(body) {
848
- return this.request(
849
- "POST",
850
- "/admin/thor/dropshipper/orders/shipping-options",
851
- {
852
- ...body,
853
- currency_code: body.currency_code.toLowerCase()
854
- }
855
- );
856
- }
857
- /**
858
- * Manually create an order on behalf of a customer.
859
- *
860
- * `POST /admin/thor/dropshipper/orders`
861
- */
862
- async createOrder(body) {
863
- return this.request(
864
- "POST",
865
- "/admin/thor/dropshipper/orders",
866
- body
867
- );
868
- }
869
- /**
870
- * Preview order totals (including taxes) without creating the order.
871
- *
872
- * Replicates the creation pipeline (pricing honoring `unit_price`, region,
873
- * shipping groups) and computes tax lines with the Medusa tax module, so the
874
- * totals match what the created order will produce.
875
- *
876
- * `POST /admin/thor/dropshipper/orders/preview-totals`
877
- */
878
- async previewOrderTotals(body) {
879
- return this.request(
880
- "POST",
881
- "/admin/thor/dropshipper/orders/preview-totals",
882
- {
883
- ...body,
884
- currency_code: body.currency_code.toLowerCase()
885
- }
886
- );
887
- }
888
- /**
889
- * Set who collects payment for an order (Solo X).
890
- *
891
- * `POST /admin/thor/dropshipper/orders/:id/set-payment-collector`
892
- */
893
- async setPaymentCollector(orderId, body) {
894
- return this.request(
895
- "POST",
896
- `/admin/thor/dropshipper/orders/${orderId}/set-payment-collector`,
897
- body
898
- );
899
- }
900
- /**
901
- * Change the payment method of a confirmed order.
902
- *
903
- * `POST /admin/thor/dropshipper/orders/:id/set-payment-method`
904
- */
905
- async setPaymentMethod(orderId, body) {
906
- return this.request(
907
- "POST",
908
- `/admin/thor/dropshipper/orders/${orderId}/set-payment-method`,
909
- body
910
- );
911
- }
912
- // -------------------------------------------------------------------------
913
- // Order Cancel & Edits (Solo Y) — B-04
914
- // -------------------------------------------------------------------------
915
- /**
916
- * Cancel a dropshipper order.
917
- *
918
- * `POST /admin/thor/dropshipper/orders/:id/cancel`
919
- */
920
- async cancelOrder(orderId) {
921
- return this.request(
922
- "POST",
923
- `/admin/thor/dropshipper/orders/${orderId}/cancel`
924
- );
925
- }
926
- /**
927
- * Create an order edit for a dropshipper order.
928
- *
929
- * `POST /admin/thor/dropshipper/orders/:id/edit`
930
- */
931
- async createOrderEdit(orderId, body = {}) {
932
- return this.request(
933
- "POST",
934
- `/admin/thor/dropshipper/orders/${orderId}/edit`,
935
- body
936
- );
937
- }
938
- /**
939
- * Add an item to the active order edit.
940
- *
941
- * `POST /admin/thor/dropshipper/orders/:id/edit/items`
942
- */
943
- async addOrderEditItem(orderId, body) {
944
- return this.request(
945
- "POST",
946
- `/admin/thor/dropshipper/orders/${orderId}/edit/items`,
947
- body
948
- );
949
- }
950
- /**
951
- * Confirm the active order edit, applying changes to the order.
952
- *
953
- * `POST /admin/thor/dropshipper/orders/:id/edit/confirm`
954
- */
955
- async confirmOrderEdit(orderId) {
956
- return this.request(
957
- "POST",
958
- `/admin/thor/dropshipper/orders/${orderId}/edit/confirm`
959
- );
960
- }
961
- /**
962
- * Get all notes for an order.
963
- *
964
- * `GET /admin/thor/dropshipper/orders/:id/notes`
965
- */
966
- async getOrderNotes(orderId) {
967
- return this.request(
968
- "GET",
969
- `/admin/thor/dropshipper/orders/${orderId}/notes`
970
- );
971
- }
972
- /**
973
- * Create a new note for an order.
974
- *
975
- * `POST /admin/thor/dropshipper/orders/:id/notes`
976
- */
977
- async createOrderNote(orderId, body) {
978
- return this.request(
979
- "POST",
980
- `/admin/thor/dropshipper/orders/${orderId}/notes`,
981
- body
982
- );
983
- }
984
- /**
985
- * Delete a note from an order.
986
- *
987
- * `DELETE /admin/thor/dropshipper/orders/:id/notes/:noteId`
988
- */
989
- async deleteOrderNote(orderId, noteId) {
990
- return this.request(
991
- "DELETE",
992
- `/admin/thor/dropshipper/orders/${orderId}/notes/${noteId}`
993
- );
994
- }
995
- // -------------------------------------------------------------------------
996
- // Custom Categories (Solo Y)
997
- // -------------------------------------------------------------------------
998
- /**
999
- * List Medusa provider categories linked to Y's channel (read-only).
1000
- *
1001
- * `GET /admin/thor/dropshipper/categories/provider`
1002
- */
1003
- async getProviderCategories() {
1004
- return this.request(
1005
- "GET",
1006
- "/admin/thor/dropshipper/categories/provider"
1007
- );
1008
- }
1009
- /**
1010
- * List Y's custom product categories.
1011
- *
1012
- * `GET /admin/thor/dropshipper/categories`
1013
- */
1014
- async getCategories(options = {}) {
1015
- const { parent_id, include_children } = options;
1016
- const qs = new URLSearchParams({
1017
- ...parent_id ? { parent_id } : {},
1018
- ...include_children !== void 0 ? { include_children: String(include_children) } : {}
1019
- });
1020
- const query = qs.toString() ? `?${qs}` : "";
1021
- return this.request(
1022
- "GET",
1023
- `/admin/thor/dropshipper/categories${query}`
1024
- );
1025
- }
1026
- /**
1027
- * Create a custom category in Y's channel.
1028
- *
1029
- * `POST /admin/thor/dropshipper/categories`
1030
- */
1031
- async createCategory(body) {
1032
- return this.request(
1033
- "POST",
1034
- "/admin/thor/dropshipper/categories",
1035
- body
1036
- );
1037
- }
1038
- /**
1039
- * Update a custom category.
1040
- *
1041
- * `PUT /admin/thor/dropshipper/categories/:id`
1042
- */
1043
- async updateCategory(categoryId, body) {
1044
- return this.request(
1045
- "PUT",
1046
- `/admin/thor/dropshipper/categories/${categoryId}`,
1047
- body
1048
- );
1049
- }
1050
- /**
1051
- * Delete a custom category.
1052
- *
1053
- * `DELETE /admin/thor/dropshipper/categories/:id`
1054
- */
1055
- async deleteCategory(categoryId, options = {}) {
1056
- const qs = options.force ? "?force=true" : "";
1057
- return this.request(
1058
- "DELETE",
1059
- `/admin/thor/dropshipper/categories/${categoryId}${qs}`
1060
- );
1061
- }
1062
- /**
1063
- * List product-to-category mappings, optionally filtered by product.
1064
- *
1065
- * `GET /admin/thor/dropshipper/category-mappings`
1066
- */
1067
- async getCategoryMappings(options = {}) {
1068
- const qs = options.product_id ? `?product_id=${options.product_id}` : "";
1069
- return this.request(
1070
- "GET",
1071
- `/admin/thor/dropshipper/category-mappings${qs}`
1072
- );
1073
- }
1074
- /**
1075
- * Map a product to a custom category.
1076
- *
1077
- * `POST /admin/thor/dropshipper/category-mappings`
1078
- */
1079
- async createCategoryMapping(body) {
1080
- return this.request(
1081
- "POST",
1082
- `/admin/thor/dropshipper/category-mappings`,
1083
- body
1084
- );
1085
- }
1086
- /**
1087
- * Remove a product-to-category mapping.
1088
- *
1089
- * `DELETE /admin/thor/dropshipper/category-mappings/:id`
1090
- */
1091
- async deleteCategoryMapping(mappingId) {
1092
- return this.request(
1093
- "DELETE",
1094
- `/admin/thor/dropshipper/category-mappings/${mappingId}`
1095
- );
1096
- }
1097
- // -------------------------------------------------------------------------
1098
- // Customers (Solo Y)
1099
- // -------------------------------------------------------------------------
1100
- /**
1101
- * Paginated list of customers in Y's channel.
1102
- *
1103
- * `GET /admin/thor/dropshipper/customers`
1104
- */
1105
- async getCustomers(options = {}) {
1106
- const { q, has_orders, from, limit = 20, offset = 0, order } = options;
1107
- const qs = new URLSearchParams({
1108
- limit: String(limit),
1109
- offset: String(offset),
1110
- ...q ? { q } : {},
1111
- ...has_orders !== void 0 ? { has_orders: String(has_orders) } : {},
1112
- ...from ? { from } : {},
1113
- ...order ? { order } : {}
1114
- });
1115
- return this.request(
1116
- "GET",
1117
- `/admin/thor/dropshipper/customers?${qs}`
1118
- );
1119
- }
1120
- /**
1121
- * Backwards-compatible alias used by the dashboard checkout flow.
1122
- */
1123
- async getChannelCustomers(_channelId, options = {}) {
1124
- return this.getCustomers(options);
1125
- }
1126
- /**
1127
- * Full detail for a single customer.
1128
- *
1129
- * `GET /admin/thor/dropshipper/customers/:id`
1130
- */
1131
- async getCustomer(customerId) {
1132
- return this.request(
1133
- "GET",
1134
- `/admin/thor/dropshipper/customers/${customerId}`
1135
- );
1136
- }
1137
- /**
1138
- * Create a customer scoped to Y's channel.
1139
- *
1140
- * `POST /admin/thor/dropshipper/customers`
1141
- */
1142
- async createCustomer(body) {
1143
- return this.request(
1144
- "POST",
1145
- "/admin/thor/dropshipper/customers",
1146
- body
1147
- );
1148
- }
1149
- /**
1150
- * Update a customer scoped to Y's channel.
1151
- *
1152
- * `POST /admin/thor/dropshipper/customers/:id`
1153
- */
1154
- async updateCustomer(customerId, body) {
1155
- return this.request(
1156
- "POST",
1157
- `/admin/thor/dropshipper/customers/${customerId}`,
1158
- body
1159
- );
1160
- }
1161
- // -------------------------------------------------------------------------
1162
- // Customer Addresses (Solo Y) — B-06
1163
- // -------------------------------------------------------------------------
1164
- /**
1165
- * Transform a raw snake_case address from the API into a camelCase Address.
1166
- */
1167
- transformAddress(raw) {
1168
- return {
1169
- id: raw.id ?? void 0,
1170
- firstName: raw.first_name ?? "",
1171
- lastName: raw.last_name ?? "",
1172
- company: raw.company ?? void 0,
1173
- address1: raw.address_1 ?? "",
1174
- address2: raw.address_2 ?? void 0,
1175
- city: raw.city ?? "",
1176
- province: raw.province ?? "",
1177
- postalCode: raw.postal_code ?? "",
1178
- countryCode: raw.country_code ?? "",
1179
- phone: raw.phone ?? void 0,
1180
- isDefault: raw.is_default ?? void 0,
1181
- isDefaultBilling: raw.is_default_billing ?? void 0,
1182
- isDefaultShipping: raw.is_default_shipping ?? void 0,
1183
- metadata: raw.address_name ? { ...raw.metadata ?? {}, label: raw.address_name } : raw.metadata ?? void 0
1184
- };
1185
- }
1186
- /**
1187
- * List addresses for a customer in Y's channel.
1188
- *
1189
- * `GET /admin/thor/dropshipper/customers/:id/addresses`
1190
- */
1191
- async getCustomerAddresses(customerId) {
1192
- const raw = await this.request("GET", `/admin/thor/dropshipper/customers/${customerId}/addresses`);
1193
- return {
1194
- addresses: raw.addresses.map((a) => this.transformAddress(a)),
1195
- count: raw.count
1196
- };
1197
- }
1198
- /**
1199
- * Create a new address for a customer.
1200
- *
1201
- * `POST /admin/thor/dropshipper/customers/:id/addresses`
1202
- */
1203
- async createCustomerAddress(customerId, body) {
1204
- const raw = await this.request(
1205
- "POST",
1206
- `/admin/thor/dropshipper/customers/${customerId}/addresses`,
1207
- body
1208
- );
1209
- return { address: this.transformAddress(raw.address) };
1210
- }
1211
- /**
1212
- * Update an existing customer address.
1213
- *
1214
- * `POST /admin/thor/dropshipper/customers/:id/addresses/:addressId`
1215
- */
1216
- async updateCustomerAddress(customerId, addressId, body) {
1217
- const raw = await this.request(
1218
- "POST",
1219
- `/admin/thor/dropshipper/customers/${customerId}/addresses/${addressId}`,
1220
- body
1221
- );
1222
- return { address: this.transformAddress(raw.address) };
1223
- }
1224
- /**
1225
- * Delete a customer address.
1226
- *
1227
- * `DELETE /admin/thor/dropshipper/customers/:id/addresses/:addressId`
1228
- */
1229
- async deleteCustomerAddress(customerId, addressId) {
1230
- return this.request(
1231
- "DELETE",
1232
- `/admin/thor/dropshipper/customers/${customerId}/addresses/${addressId}`
1233
- );
1234
- }
1235
- // -------------------------------------------------------------------------
1236
- // Account & Settlements (Y read-only)
1237
- // -------------------------------------------------------------------------
1238
- /**
1239
- * Y's account info with current balance.
1240
- *
1241
- * `GET /admin/thor/dropshipper/account`
1242
- */
1243
- async getAccount() {
1244
- return this.request(
1245
- "GET",
1246
- "/admin/thor/dropshipper/account"
1247
- );
1248
- }
1249
- /**
1250
- * Get the authenticated dropshipper's business policy text.
1251
- * Returns an empty string when no policy is set.
1252
- *
1253
- * `GET /admin/thor/dropshipper/account/policies`
1254
- */
1255
- async getBusinessPolicy() {
1256
- return this.request(
1257
- "GET",
1258
- "/admin/thor/dropshipper/account/policies"
1259
- );
1260
- }
1261
- /**
1262
- * Update the authenticated dropshipper's business policy text.
1263
- * The value is trimmed server-side before being persisted.
1264
- *
1265
- * `PATCH /admin/thor/dropshipper/account/policies`
1266
- */
1267
- async updateBusinessPolicy(body) {
1268
- return this.request(
1269
- "PATCH",
1270
- "/admin/thor/dropshipper/account/policies",
1271
- body
1272
- );
1273
- }
1274
- /**
1275
- * Orders where Y owes money to X (Y collected payment, needs to pay costs).
1276
- *
1277
- * `GET /admin/thor/dropshipper/account/payable`
1278
- */
1279
- async getPayable() {
1280
- return this.request(
1281
- "GET",
1282
- "/admin/thor/dropshipper/account/payable"
1283
- );
1284
- }
1285
- /**
1286
- * Orders where X owes money to Y (X collected COD, needs to transfer profit).
1287
- *
1288
- * `GET /admin/thor/dropshipper/account/receivable`
1289
- */
1290
- async getReceivable() {
1291
- return this.request(
1292
- "GET",
1293
- "/admin/thor/dropshipper/account/receivable"
1294
- );
1295
- }
1296
- /**
1297
- * List settlements (Y sees own; X can filter by account_id).
1298
- *
1299
- * `GET /admin/thor/dropshipper/settlements`
1300
- */
1301
- async getSettlements(options = {}) {
1302
- const { status, type, account_id, limit = 20, offset = 0 } = options;
1303
- const qs = new URLSearchParams({
1304
- limit: String(limit),
1305
- offset: String(offset),
1306
- ...status ? { status } : {},
1307
- ...type ? { type } : {},
1308
- ...account_id ? { account_id } : {}
1309
- });
1310
- return this.request(
1311
- "GET",
1312
- `/admin/thor/dropshipper/settlements?${qs}`
1313
- );
1314
- }
1315
- /**
1316
- * Full detail for a single settlement record.
1317
- *
1318
- * `GET /admin/thor/dropshipper/settlements/:id`
1319
- */
1320
- async getSettlement(settlementId) {
1321
- return this.request(
1322
- "GET",
1323
- `/admin/thor/dropshipper/settlements/${settlementId}`
1324
- );
1325
- }
1326
- /**
1327
- * Consolidated financial balance for the authenticated dropshipper.
1328
- *
1329
- * `GET /admin/thor/dropshipper/account/balance`
1330
- */
1331
- async getAccountBalance() {
1332
- return this.request(
1333
- "GET",
1334
- "/admin/thor/dropshipper/account/balance"
1335
- );
1336
- }
1337
- /**
1338
- * Unified financial order list for the authenticated dropshipper.
1339
- *
1340
- * `GET /admin/thor/dropshipper/account/orders`
1341
- */
1342
- async getAccountOrders(options = {}) {
1343
- const { tab, status, limit = 20, offset = 0, q } = options;
1344
- const qs = new URLSearchParams({
1345
- limit: String(limit),
1346
- offset: String(offset),
1347
- ...tab ? { tab } : {},
1348
- ...status ? { status } : {},
1349
- ...q ? { q } : {}
1350
- });
1351
- return this.request(
1352
- "GET",
1353
- `/admin/thor/dropshipper/account/orders?${qs}`
1354
- );
1355
- }
1356
- // -------------------------------------------------------------------------
1357
- // Admin Settlements (Solo X)
1358
- // -------------------------------------------------------------------------
1359
- /**
1360
- * Create a settlement record for a dropshipper account.
1361
- *
1362
- * `POST /admin/thor/dropshipper/admin/settlements`
1363
- */
1364
- async createSettlement(body) {
1365
- return this.request(
1366
- "POST",
1367
- "/admin/thor/dropshipper/admin/settlements",
1368
- body
1369
- );
1370
- }
1371
- /**
1372
- * Confirm a pending settlement (marks it as paid/received).
1373
- *
1374
- * `POST /admin/thor/dropshipper/admin/settlements/:id/confirm`
1375
- */
1376
- async confirmSettlement(settlementId, body = {}) {
1377
- return this.request(
1378
- "POST",
1379
- `/admin/thor/dropshipper/admin/settlements/${settlementId}/confirm`,
1380
- body
1381
- );
1382
- }
1383
- /**
1384
- * Cancel a pending settlement.
1385
- *
1386
- * `POST /admin/thor/dropshipper/admin/settlements/:id/cancel`
1387
- */
1388
- async cancelSettlement(settlementId, body = {}) {
1389
- return this.request(
1390
- "POST",
1391
- `/admin/thor/dropshipper/admin/settlements/${settlementId}/cancel`,
1392
- body
1393
- );
1394
- }
1395
- // -------------------------------------------------------------------------
1396
- // Admin Settlements — list (Solo X)
1397
- // -------------------------------------------------------------------------
1398
- /**
1399
- * X views all settlement records across all dropshipper accounts.
1400
- *
1401
- * `GET /admin/thor/dropshipper/admin/settlements`
1402
- */
1403
- async getAdminSettlements(options = {}) {
1404
- const { status, type, account_id, limit = 20, offset = 0 } = options;
1405
- const qs = new URLSearchParams({
1406
- limit: String(limit),
1407
- offset: String(offset),
1408
- ...status ? { status } : {},
1409
- ...type ? { type } : {},
1410
- ...account_id ? { account_id } : {}
1411
- });
1412
- return this.request(
1413
- "GET",
1414
- `/admin/thor/dropshipper/admin/settlements?${qs}`
1415
- );
1416
- }
1417
- // -------------------------------------------------------------------------
1418
- // Admin Account Management (Solo X)
1419
- // -------------------------------------------------------------------------
1420
- /**
1421
- * List all dropshipper accounts.
1422
- *
1423
- * `GET /admin/thor/dropshipper/admin/accounts`
1424
- */
1425
- async getAdminAccounts() {
1426
- return this.request(
1427
- "GET",
1428
- "/admin/thor/dropshipper/admin/accounts"
1429
- );
1430
- }
1431
- /**
1432
- * Full balance detail for a specific dropshipper account.
1433
- *
1434
- * `GET /admin/thor/dropshipper/admin/accounts/:id/balance`
1435
- */
1436
- async getAdminAccountBalance(accountId) {
1437
- return this.request(
1438
- "GET",
1439
- `/admin/thor/dropshipper/admin/accounts/${accountId}/balance`
1440
- );
1441
- }
1442
- /**
1443
- * List all dropshipper price lists.
1444
- *
1445
- * `GET /admin/thor/dropshipper/admin/price-lists`
1446
- */
1447
- async getAdminPriceLists() {
1448
- return this.request(
1449
- "GET",
1450
- "/admin/thor/dropshipper/admin/price-lists"
1451
- );
1452
- }
1453
- /**
1454
- * Utility: look up which sales channel a user belongs to.
1455
- *
1456
- * `GET /admin/thor/dropshipper/admin/user-channel`
1457
- */
1458
- async getUserChannel() {
1459
- return this.request(
1460
- "GET",
1461
- "/admin/thor/dropshipper/admin/user-channel"
1462
- );
1463
- }
1464
- // -------------------------------------------------------------------------
1465
- // Financial Endpoints — Group A (Admin X)
1466
- // -------------------------------------------------------------------------
1467
- /**
1468
- * List orders with financial detail for a dropshipper account (Admin only).
1469
- *
1470
- * `GET /admin/thor/dropshipper/admin/accounts/:id/orders`
1471
- */
1472
- async getAdminAccountOrders(accountId, options = {}) {
1473
- const { tab, status, limit = 20, offset = 0, q } = options;
1474
- const qs = new URLSearchParams({
1475
- limit: String(limit),
1476
- offset: String(offset),
1477
- ...tab ? { tab } : {},
1478
- ...status ? { status } : {},
1479
- ...q ? { q } : {}
1480
- });
1481
- return this.request(
1482
- "GET",
1483
- `/admin/thor/dropshipper/admin/accounts/${accountId}/orders?${qs}`
1484
- );
1485
- }
1486
- /**
1487
- * List financial movements for a dropshipper account (Admin only).
1488
- *
1489
- * `GET /admin/thor/dropshipper/admin/accounts/:id/settlements`
1490
- */
1491
- async getAdminAccountSettlements(accountId, options = {}) {
1492
- const { type, status, limit = 20, offset = 0 } = options;
1493
- const qs = new URLSearchParams({
1494
- limit: String(limit),
1495
- offset: String(offset),
1496
- ...type ? { type } : {},
1497
- ...status ? { status } : {}
1498
- });
1499
- return this.request(
1500
- "GET",
1501
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements?${qs}`
1502
- );
1503
- }
1504
- /**
1505
- * Manually resolve a guarantee on an order (Admin only).
1506
- *
1507
- * `POST /admin/thor/dropshipper/admin/accounts/:id/guarantee/:order_id`
1508
- */
1509
- async resolveGuarantee(accountId, orderId, body) {
1510
- return this.request(
1511
- "POST",
1512
- `/admin/thor/dropshipper/admin/accounts/${accountId}/guarantee/${orderId}`,
1513
- body
1514
- );
1515
- }
1516
- /**
1517
- * Create an internal compensation (netting) between DS and Thor debts (Admin only).
1518
- *
1519
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/compensacion`
1520
- */
1521
- async createCompensacion(accountId, body) {
1522
- return this.request(
1523
- "POST",
1524
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/compensacion`,
1525
- body
1526
- );
1527
- }
1528
- /**
1529
- * Create a financial adjustment (Admin only).
1530
- *
1531
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/ajuste`
1532
- */
1533
- async createAjuste(accountId, body) {
1534
- return this.request(
1535
- "POST",
1536
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/ajuste`,
1537
- body
1538
- );
1539
- }
1540
- // -------------------------------------------------------------------------
1541
- // Financial Endpoints — Group B (Admin X)
1542
- // -------------------------------------------------------------------------
1543
- /**
1544
- * Register a cobro — DS pays Thor the product cost (Admin only).
1545
- *
1546
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/cobro`
1547
- */
1548
- async createCobro(accountId, body) {
1549
- return this.request(
1550
- "POST",
1551
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/cobro`,
1552
- body
1553
- );
1554
- }
1555
- /**
1556
- * Register a pago — Thor pays the dropshipper their commission (Admin only).
1557
- *
1558
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/pago`
1559
- */
1560
- async createPago(accountId, body) {
1561
- return this.request(
1562
- "POST",
1563
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/pago`,
1564
- body
1565
- );
1566
- }
1567
- /**
1568
- * Reverse a confirmed financial movement (Admin only).
1569
- *
1570
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/:mov_id/reverso`
1571
- */
1572
- async reverseSettlement(accountId, movementId, body) {
1573
- return this.request(
1574
- "POST",
1575
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/${movementId}/reverso`,
1576
- body
1577
- );
1578
- }
1579
- /**
1580
- * Confirm a pending financial movement (Admin only).
1581
- *
1582
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/:mov_id/confirm`
1583
- */
1584
- async confirmSettlementMovement(accountId, movementId, body = {}) {
1585
- return this.request(
1586
- "POST",
1587
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/${movementId}/confirm`,
1588
- body
1589
- );
1590
- }
1591
- /**
1592
- * Cancel a pending financial movement draft (Admin only).
1593
- *
1594
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/:mov_id/cancel`
1595
- */
1596
- async cancelSettlementMovement(accountId, movementId, body) {
1597
- return this.request(
1598
- "POST",
1599
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/${movementId}/cancel`,
1600
- body
1601
- );
1602
- }
1603
- /**
1604
- * Get financial analysis for a dropshipper order (Admin only).
1605
- *
1606
- * `GET /admin/thor/dropshipper/admin/orders/:id/financial-analysis`
1607
- */
1608
- async getOrderFinancialAnalysis(orderId) {
1609
- return this.request(
1610
- "GET",
1611
- `/admin/thor/dropshipper/admin/orders/${orderId}/financial-analysis`
1612
- );
1613
- }
1614
- /**
1615
- * Register a partial or full payment for an order.
1616
- *
1617
- * `POST /admin/thor/dropshipper/orders/:id/payment`
1618
- */
1619
- async registerOrderPayment(orderId, body) {
1620
- return this.request(
1621
- "POST",
1622
- `/admin/thor/dropshipper/orders/${orderId}/payment`,
1623
- body
1624
- );
1625
- }
1626
- // -------------------------------------------------------------------------
1627
- // Promotions (Solo Y)
1628
- // -------------------------------------------------------------------------
1629
- /**
1630
- * List Y's promotions (discount codes).
1631
- *
1632
- * `GET /admin/thor/dropshipper/promotions`
1633
- */
1634
- async getPromotions(options = {}) {
1635
- const { type, limit = 20, offset = 0 } = options;
1636
- const qs = new URLSearchParams({
1637
- limit: String(limit),
1638
- offset: String(offset),
1639
- ...type ? { type } : {}
1640
- });
1641
- return this.request(
1642
- "GET",
1643
- `/admin/thor/dropshipper/promotions?${qs}`
1644
- );
1645
- }
1646
- /**
1647
- * Create a promotion for Y's channel.
1648
- *
1649
- * `POST /admin/thor/dropshipper/promotions`
1650
- */
1651
- async createPromotion(body) {
1652
- return this.request(
1653
- "POST",
1654
- "/admin/thor/dropshipper/promotions",
1655
- body
1656
- );
1657
- }
1658
- /**
1659
- * Get a single promotion by ID.
1660
- *
1661
- * `GET /admin/thor/dropshipper/promotions/:id`
1662
- */
1663
- async getPromotion(promotionId) {
1664
- return this.request(
1665
- "GET",
1666
- `/admin/thor/dropshipper/promotions/${promotionId}`
1667
- );
1668
- }
1669
- /**
1670
- * Update an existing promotion.
1671
- *
1672
- * `PUT /admin/thor/dropshipper/promotions/:id`
1673
- */
1674
- async updatePromotion(promotionId, body) {
1675
- return this.request(
1676
- "PUT",
1677
- `/admin/thor/dropshipper/promotions/${promotionId}`,
1678
- body
1679
- );
1680
- }
1681
- /**
1682
- * Delete a promotion.
1683
- *
1684
- * `DELETE /admin/thor/dropshipper/promotions/:id`
1685
- */
1686
- async deletePromotion(promotionId) {
1687
- return this.request(
1688
- "DELETE",
1689
- `/admin/thor/dropshipper/promotions/${promotionId}`
1690
- );
1691
- }
1692
- // -------------------------------------------------------------------------
1693
- // Dashboard (Solo Y)
1694
- // -------------------------------------------------------------------------
1695
- /**
1696
- * Aggregate stats for Y's dashboard (revenue, profit, top products).
1697
- *
1698
- * `GET /admin/thor/dropshipper/dashboard/stats`
1699
- */
1700
- async getDashboardStats(options = {}) {
1701
- const { period, from, to, currency_code } = options;
1702
- const qs = new URLSearchParams({
1703
- ...period ? { period } : {},
1704
- ...from ? { from } : {},
1705
- ...to ? { to } : {},
1706
- ...currency_code ? { currency_code } : {}
1707
- });
1708
- const query = qs.toString() ? `?${qs}` : "";
1709
- return this.request(
1710
- "GET",
1711
- `/admin/thor/dropshipper/dashboard/stats${query}`
1712
- );
1713
- }
1714
- // -------------------------------------------------------------------------
1715
- // Storefront (V — end customer, uses publishable API key)
1716
- // -------------------------------------------------------------------------
1717
- /**
1718
- * Public endpoint: dropshipper-scoped categories for the storefront.
1719
- * Typically called with a publishable API key rather than a JWT.
1720
- *
1721
- * `GET /store/thor/dropshipper-categories`
1722
- */
1723
- async getStorefrontCategories() {
1724
- return this.request(
1725
- "GET",
1726
- "/store/thor/dropshipper-categories"
1727
- );
1728
- }
1729
- // -------------------------------------------------------------------------
1730
- // Draft Orders
1731
- // -------------------------------------------------------------------------
1732
- /**
1733
- * List all draft orders in the dropshipper's channel.
1734
- *
1735
- * `GET /admin/thor/dropshipper/draft-orders`
1736
- */
1737
- async getDraftOrders(options = {}) {
1738
- const { customer_id, from, to, q, limit = 20, offset = 0 } = options;
1739
- const qs = new URLSearchParams({
1740
- limit: String(limit),
1741
- offset: String(offset),
1742
- ...customer_id ? { customer_id } : {},
1743
- ...from ? { from } : {},
1744
- ...to ? { to } : {},
1745
- ...q ? { q } : {}
1746
- });
1747
- return this.request(
1748
- "GET",
1749
- `/admin/thor/dropshipper/draft-orders?${qs}`
1750
- );
1751
- }
1752
- /**
1753
- * Get a specific draft order by ID.
1754
- *
1755
- * `GET /admin/thor/dropshipper/draft-orders/:id`
1756
- */
1757
- async getDraftOrder(draftOrderId) {
1758
- return this.request(
1759
- "GET",
1760
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}`
1761
- );
1762
- }
1763
- /**
1764
- * Create a new draft order.
1765
- *
1766
- * `POST /admin/thor/dropshipper/draft-orders`
1767
- */
1768
- async createDraftOrder(body) {
1769
- return this.request(
1770
- "POST",
1771
- "/admin/thor/dropshipper/draft-orders",
1772
- body
1773
- );
1774
- }
1775
- /**
1776
- * Update a draft order.
1777
- *
1778
- * `POST /admin/thor/dropshipper/draft-orders/:id`
1779
- */
1780
- async updateDraftOrder(draftOrderId, body) {
1781
- return this.request(
1782
- "POST",
1783
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}`,
1784
- body
1785
- );
1786
- }
1787
- /**
1788
- * Convert a draft order to a real order.
1789
- *
1790
- * `POST /admin/thor/dropshipper/draft-orders/:id/convert`
1791
- */
1792
- async convertDraftOrder(draftOrderId, body) {
1793
- return this.request(
1794
- "POST",
1795
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}/convert`,
1796
- body
1797
- );
1798
- }
1799
- /**
1800
- * Delete a draft order.
1801
- *
1802
- * `DELETE /admin/thor/dropshipper/draft-orders/:id`
1803
- */
1804
- async deleteDraftOrder(draftOrderId) {
1805
- return this.request(
1806
- "DELETE",
1807
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}`
1808
- );
1809
- }
1810
- // -------------------------------------------------------------------------
1811
- // Geo-reference
1812
- // -------------------------------------------------------------------------
1813
- /**
1814
- * List all geo-reference countries.
1815
- *
1816
- * `GET /admin/geo-reference`
1817
- */
1818
- async getGeoCountries() {
1819
- return this.request("GET", "/admin/geo-reference");
1820
- }
1821
- /**
1822
- * List provinces/states for a country.
1823
- *
1824
- * `GET /admin/geo-reference/countries/:iso_2/provinces`
1825
- */
1826
- async getGeoProvinces(iso2) {
1827
- return this.request(
1828
- "GET",
1829
- `/admin/geo-reference/countries/${iso2}/provinces`
1830
- );
1831
- }
1832
- /**
1833
- * List cities for a province/state.
1834
- *
1835
- * `GET /admin/geo-reference/provinces/:code/cities`
1836
- */
1837
- async getGeoCities(code) {
1838
- return this.request(
1839
- "GET",
1840
- `/admin/geo-reference/provinces/${code}/cities`
1841
- );
1842
- }
1843
- };
1844
- async function* parseSse(stream, logger) {
1845
- const reader = stream.getReader();
1846
- const decoder = new TextDecoder();
1847
- let buffer = "";
1848
- let frameIndex = 0;
1849
- try {
1850
- while (true) {
1851
- const { done, value } = await reader.read();
1852
- if (done) break;
1853
- buffer += decoder.decode(value, { stream: true });
1854
- const lines = buffer.split(/\r?\n/);
1855
- buffer = lines.pop() ?? "";
1856
- for (const line of lines) {
1857
- const trimmed = line.trim();
1858
- if (!trimmed.startsWith("data:")) continue;
1859
- const payload = trimmed.slice(5).trim();
1860
- if (!payload || payload === "[DONE]") continue;
1861
- frameIndex += 1;
1862
- try {
1863
- yield JSON.parse(payload);
1864
- } catch (err) {
1865
- logger?.warn(
1866
- `[dropshipper] sse-malformed-frame frame=${frameIndex} payload=${payload.slice(0, 200)}`
1867
- );
1868
- }
1869
- }
1870
- }
1871
- const tail = buffer.trim();
1872
- if (tail.startsWith("data:")) {
1873
- const payload = tail.slice(5).trim();
1874
- if (payload && payload !== "[DONE]") {
1875
- frameIndex += 1;
1876
- try {
1877
- yield JSON.parse(payload);
1878
- } catch (err) {
1879
- logger?.warn(
1880
- `[dropshipper] sse-malformed-frame frame=${frameIndex} payload=${payload.slice(0, 200)}`
1881
- );
1882
- }
1883
- }
1884
- }
1885
- } finally {
1886
- reader.releaseLock();
1887
- }
1888
- }
1889
- function mapUiMessageStreamToEvents(stream, logger) {
1890
- return new ReadableStream({
1891
- async start(controller) {
1892
- let eventCount = 0;
1893
- for await (const raw of parseSse(stream, logger)) {
1894
- const chunk = raw;
1895
- switch (chunk.type) {
1896
- case "start":
1897
- controller.enqueue({
1898
- type: "start",
1899
- intent: chunk.messageMetadata?.intent
1900
- });
1901
- eventCount += 1;
1902
- break;
1903
- case "text-delta":
1904
- if (chunk.delta !== void 0) {
1905
- controller.enqueue({ type: "text-delta", delta: chunk.delta });
1906
- eventCount += 1;
1907
- }
1908
- break;
1909
- case "finish":
1910
- controller.enqueue({
1911
- type: "finish",
1912
- intent: chunk.messageMetadata?.intent ?? "default",
1913
- sources: chunk.messageMetadata?.sources ?? []
1914
- });
1915
- eventCount += 1;
1916
- break;
1917
- case "error":
1918
- logger?.warn(
1919
- `[dropshipper] chat-stream-error errorText=${chunk.errorText}`
1920
- );
1921
- controller.enqueue({
1922
- type: "error",
1923
- errorText: chunk.errorText ?? "Error inesperado del asistente."
1924
- });
1925
- eventCount += 1;
1926
- break;
1927
- default:
1928
- logger?.debug(
1929
- `[dropshipper] chat-stream-unknown-frame type=${chunk.type}`
1930
- );
1931
- }
1932
- }
1933
- logger?.debug(`[dropshipper] chat-stream-completed events=${eventCount}`);
1934
- controller.close();
1935
- },
1936
- cancel() {
1937
- stream.cancel?.();
1938
- }
1939
- });
1940
- }
1941
-
1942
- // src/recovery.ts
1943
- import { createLogger as createLogger3, ProviderAPIError as ProviderAPIError4 } from "@thorprovider/adapters";
1944
- var RecoveryClient = class {
1945
- baseUrl;
1946
- logger;
1947
- constructor(config) {
1948
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
1949
- this.logger = createLogger3("RecoveryClient", config.debug);
1950
- }
1951
- // -------------------------------------------------------------------------
1952
- // Private — HTTP helper
1953
- // -------------------------------------------------------------------------
1954
- async request(method, path, body, retryConfig) {
1955
- const url = `${this.baseUrl}${path}`;
1956
- this.logger.debug(`[recovery] ${method} ${path}`);
1957
- const headers = {
1958
- "Content-Type": "application/json"
1959
- };
1960
- const init = {
1961
- method,
1962
- headers,
1963
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
1964
- };
1965
- let response;
1966
- try {
1967
- response = await fetchBackendWithResilience(url, init, retryConfig);
1968
- } catch (networkError) {
1969
- throw new ProviderAPIError4(
1970
- `[recovery] Network error on ${method} ${path}: ${networkError.message}`,
1971
- "NETWORK_ERROR",
1972
- networkError
1973
- );
1974
- }
1975
- if (!response.ok) {
1976
- let message = `HTTP ${response.status}`;
1977
- let details;
1978
- try {
1979
- const json = await response.json();
1980
- message = json?.message ?? message;
1981
- details = json && typeof json === "object" ? json : void 0;
1982
- } catch {
1983
- }
1984
- throw new ProviderAPIError4(
1985
- `[recovery] ${method} ${path} failed: ${message}`,
1986
- `RECOVERY_API_${response.status}`,
1987
- response.status,
1988
- details
1989
- );
1990
- }
1991
- if ((response.headers.get("content-type") ?? "").includes("application/json")) {
1992
- try {
1993
- return await response.json();
1994
- } catch {
1995
- return {};
1996
- }
1997
- }
1998
- return {};
1999
- }
2000
- // -------------------------------------------------------------------------
2001
- // Password reset
2002
- // -------------------------------------------------------------------------
2003
- /**
2004
- * Solicita un email de reset de contraseña para el actor `user`
2005
- * (dropshippers). El backend responde de forma uniforme exista o no la
2006
- * cuenta (anti enumeración).
2007
- *
2008
- * `POST /dropshipper/auth/emailpass/reset-password`
2009
- */
2010
- async requestUserPasswordReset(email) {
2011
- await this.request("POST", "/dropshipper/auth/emailpass/reset-password", {
2012
- email
2013
- });
2014
- }
2015
- /**
2016
- * Verifica un token de reset de contraseña sin consumirlo. Devuelve el
2017
- * email enmascarado (p. ej. `j***@ejemplo.com`) solo cuando `status === 'valid'`.
2018
- *
2019
- * `GET /dropshipper/auth/emailpass/reset-password/verify`
2020
- */
2021
- async verifyUserPasswordResetToken(token) {
2022
- return this.request("GET", `/dropshipper/auth/emailpass/reset-password/verify?token=${encodeURIComponent(token)}`);
2023
- }
2024
- /**
2025
- * Confirma el reset: re-verifica el token (sin consumir), luego consume el
2026
- * token vía `POST /dropshipper/auth/emailpass/update`. El email se deriva del
2027
- * propio JWT en el backend; aquí solo se envía la nueva contraseña. Nunca
2028
- * devuelve auto-login: al éxito, la UI redirige a /login.
2029
- */
2030
- async confirmUserPasswordReset(token, password) {
2031
- const verify = await this.verifyUserPasswordResetToken(token);
2032
- if (verify.status !== "valid") {
2033
- return { ok: false, status: verify.status };
2034
- }
2035
- try {
2036
- const headers = {
2037
- Authorization: `Bearer ${token}`,
2038
- "Content-Type": "application/json"
2039
- };
2040
- const response = await fetchBackendWithResilience(`${this.baseUrl}/dropshipper/auth/emailpass/update`, {
2041
- method: "POST",
2042
- headers,
2043
- body: JSON.stringify({ password })
2044
- });
2045
- if (!response.ok) {
2046
- throw new ProviderAPIError4(
2047
- `[recovery] POST /dropshipper/auth/emailpass/update failed: HTTP ${response.status}`,
2048
- "RECOVERY_API_" + response.status,
2049
- response.status
2050
- );
2051
- }
2052
- return { ok: true };
2053
- } catch (error) {
2054
- this.logger.warn("[recovery] confirmUserPasswordReset failed, re-verifying", error);
2055
- try {
2056
- const recheck = await this.verifyUserPasswordResetToken(token);
2057
- return { ok: false, status: recheck.status };
2058
- } catch {
2059
- return { ok: false, status: "invalid" };
2060
- }
2061
- }
2062
- }
2063
- // -------------------------------------------------------------------------
2064
- // Account activation
2065
- // -------------------------------------------------------------------------
2066
- /**
2067
- * Verifica un token de activación de cuenta dropshipper sin consumirlo.
2068
- *
2069
- * `GET /store/dropshipper/applications/activate/verify`
2070
- */
2071
- async verifyActivationToken(token) {
2072
- return this.request("GET", `/store/dropshipper/applications/activate/verify?token=${encodeURIComponent(token)}`);
2073
- }
2074
- /**
2075
- * Activa la cuenta: re-verifica el token (sin consumir), luego consume el
2076
- * token vía `POST /store/dropshipper/applications/activate` y establece la
2077
- * contraseña inicial. Al éxito, la UI redirige a /login sin auto-login.
2078
- */
2079
- async activateAccount(token, password) {
2080
- const verify = await this.verifyActivationToken(token);
2081
- if (verify.status !== "valid") {
2082
- return { ok: false, status: verify.status };
2083
- }
2084
- try {
2085
- await this.request("POST", "/store/dropshipper/applications/activate", { token, password });
2086
- return { ok: true };
2087
- } catch (error) {
2088
- this.logger.warn("[recovery] activateAccount failed, re-verifying", error);
2089
- try {
2090
- const recheck = await this.verifyActivationToken(token);
2091
- return { ok: false, status: recheck.status };
2092
- } catch {
2093
- return { ok: false, status: "invalid" };
2094
- }
2095
- }
2096
- }
2097
- // -------------------------------------------------------------------------
2098
- // Dropshipper application submission
2099
- // -------------------------------------------------------------------------
2100
- /**
2101
- * Envía una solicitud de acceso dropshipper al endpoint público.
2102
- *
2103
- * `POST /public/dropshipper/applications`
2104
- *
2105
- * No requiere autenticación. Devuelve un resultado discriminado:
2106
- * - `{ ok: true }` → 201, solicitud creada (`application.number`).
2107
- * - `{ ok: false, reason: 'conflict' }` → 409, email ya registrado; la
2108
- * solicitud existente incluye `status_label`/`reason` para la UI.
2109
- * - `{ ok: false, reason: 'rate_limited' }` → 429, se respetó el límite del
2110
- * backend; `retryAfterSeconds` indica cuándo reintentar.
2111
- * - `{ ok: false, reason: 'invalid_data' }` → 400, validación del backend.
2112
- *
2113
- * Los errores de red/5xx se re-lanzan como `ProviderAPIError` para que el
2114
- * llamador los categorice (p. ej. con `parseError`). El 429 no se reintenta
2115
- * (`retryableStatusCodes` sin 429) para que el caller reciba de inmediato el
2116
- * `retry_after_seconds` del backend y pueda bloquear el envío.
2117
- */
2118
- async submitApplication(body) {
2119
- try {
2120
- const response = await this.request(
2121
- "POST",
2122
- "/public/dropshipper/applications",
2123
- body,
2124
- { retryableStatusCodes: [408, 500, 502, 503, 504] }
2125
- );
2126
- return { ok: true, application: response.application };
2127
- } catch (error) {
2128
- if (error instanceof ProviderAPIError4) {
2129
- const details = error.details ?? {};
2130
- if (error.status === 409 && details.application) {
2131
- return {
2132
- ok: false,
2133
- reason: "conflict",
2134
- application: details.application
2135
- };
2136
- }
2137
- if (error.status === 429 && typeof details.retry_after_seconds === "number") {
2138
- return {
2139
- ok: false,
2140
- reason: "rate_limited",
2141
- retryAfterSeconds: details.retry_after_seconds
2142
- };
2143
- }
2144
- if (error.status === 400 && details?.type === "challenge_failed") {
2145
- return {
2146
- ok: false,
2147
- reason: "challenge_failed",
2148
- ...typeof details.message === "string" ? { message: details.message } : {}
2149
- };
2150
- }
2151
- if (error.status === 400) {
2152
- return {
2153
- ok: false,
2154
- reason: "invalid_data",
2155
- fields: details.fields
2156
- };
2157
- }
2158
- }
2159
- throw error;
2160
- }
2161
- }
2162
- };
2163
- export {
2164
- DropshipperClient,
2165
- MedusaAdminClient,
2166
- RecoveryClient
2167
- };
2168
- //# sourceMappingURL=index.mjs.map