@ecomweb/sdk 0.2.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,2776 @@
1
+ // src/core/response.ts
2
+ var ApiClientError = class extends Error {
3
+ constructor(message, statusCode = 0, code, details) {
4
+ super(message);
5
+ this.name = "ApiClientError";
6
+ this.statusCode = statusCode;
7
+ this.code = code;
8
+ this.details = details;
9
+ }
10
+ };
11
+ function toClientError(response) {
12
+ return new ApiClientError(
13
+ response.error?.message || "Request failed",
14
+ response.error?.statusCode || 0,
15
+ response.error?.error,
16
+ response.error?.details
17
+ );
18
+ }
19
+ function unwrap(response) {
20
+ if (response.success && response.data !== void 0) {
21
+ return response.data;
22
+ }
23
+ throw toClientError(response);
24
+ }
25
+ function unwrapOrNull(response, nullStatusCodes = [404]) {
26
+ if (response.success && response.data !== void 0) {
27
+ return response.data;
28
+ }
29
+ if (!response.success && response.error && nullStatusCodes.includes(response.error.statusCode)) {
30
+ return null;
31
+ }
32
+ throw toClientError(response);
33
+ }
34
+ function ensureSuccess(response) {
35
+ if (response.success) return;
36
+ throw toClientError(response);
37
+ }
38
+
39
+ // src/types/common.ts
40
+ import { z as z2 } from "zod";
41
+
42
+ // src/types/product-status.ts
43
+ import { z } from "zod";
44
+ var productStatusSchema = z.enum([
45
+ "draft",
46
+ // Work in progress, not visible to customers
47
+ "active",
48
+ // Published and visible to customers
49
+ "unlisted"
50
+ // Hidden from public view, can be restored
51
+ ]);
52
+ var ProductStatus = {
53
+ DRAFT: "draft",
54
+ ACTIVE: "active",
55
+ UNLISTED: "unlisted"
56
+ };
57
+ var inventoryStatusSchema = z.enum([
58
+ "in_stock",
59
+ // Quantity > low_stock_threshold
60
+ "low_stock",
61
+ // Quantity <= low_stock_threshold && quantity > 0
62
+ "out_of_stock",
63
+ // Quantity = 0 && !backorder_allowed
64
+ "backordered"
65
+ // Quantity = 0 && backorder_allowed
66
+ ]);
67
+ var InventoryStatus = {
68
+ IN_STOCK: "in_stock",
69
+ LOW_STOCK: "low_stock",
70
+ OUT_OF_STOCK: "out_of_stock",
71
+ BACKORDERED: "backordered"
72
+ };
73
+ var LEGACY_STATUS_MIGRATION_MAP = {
74
+ active: ProductStatus.ACTIVE,
75
+ inactive: ProductStatus.UNLISTED,
76
+ // inactive → unlisted
77
+ archived: ProductStatus.UNLISTED,
78
+ // archived → unlisted (old status)
79
+ pending: ProductStatus.DRAFT,
80
+ // pending → draft (removed approval workflow)
81
+ scheduled: ProductStatus.DRAFT,
82
+ // scheduled → draft (removed scheduling)
83
+ draft: ProductStatus.DRAFT,
84
+ out_of_stock: ProductStatus.ACTIVE,
85
+ // Was inventory status, map to active
86
+ low_stock: ProductStatus.ACTIVE
87
+ // Was inventory status, map to active
88
+ };
89
+ var PRODUCT_STATUS_LABELS = {
90
+ draft: "Nh\xE1p",
91
+ active: "Ho\u1EA1t \u0111\u1ED9ng",
92
+ unlisted: "Kh\xF4ng c\xF4ng khai"
93
+ };
94
+ var INVENTORY_STATUS_LABELS = {
95
+ in_stock: "C\xF2n h\xE0ng",
96
+ low_stock: "S\u1EAFp h\u1EBFt h\xE0ng",
97
+ out_of_stock: "H\u1EBFt h\xE0ng",
98
+ backordered: "Cho ph\xE9p \u0111\u1EB7t tr\u01B0\u1EDBc"
99
+ };
100
+ function isPublishableStatus(status) {
101
+ return status === ProductStatus.ACTIVE;
102
+ }
103
+ function isUnpublishedStatus(status) {
104
+ return status === ProductStatus.DRAFT || status === ProductStatus.UNLISTED;
105
+ }
106
+ function isEditableStatus(status) {
107
+ return status === ProductStatus.DRAFT;
108
+ }
109
+
110
+ // src/types/common.ts
111
+ var timestampSchema = z2.object({
112
+ created_at: z2.iso.datetime(),
113
+ updated_at: z2.iso.datetime()
114
+ });
115
+ var optionalTimestampSchema = z2.object({
116
+ created_at: z2.iso.datetime().optional().nullable(),
117
+ updated_at: z2.iso.datetime().optional().nullable()
118
+ });
119
+ var deletedAtSchema = z2.object({
120
+ deleted_at: z2.iso.datetime().optional().nullable()
121
+ });
122
+ var uuidSchema = z2.uuidv4();
123
+ var idSchema = z2.int32().positive();
124
+ var storeIdSchema = z2.int32().positive();
125
+ var storeStatusSchema = z2.enum(["pending", "active", "disabled"]);
126
+ var legacyProductStatusSchema = z2.enum([
127
+ "active",
128
+ "inactive",
129
+ "draft"
130
+ ]);
131
+ var orderStatusSchema = z2.enum([
132
+ "pending",
133
+ "confirmed",
134
+ "processing",
135
+ "cancelled",
136
+ "on_hold",
137
+ "completed"
138
+ ]);
139
+ var fulfillmentStatusSchema = z2.enum([
140
+ "unfulfilled",
141
+ "fulfilled",
142
+ "returned",
143
+ "return_requested"
144
+ ]);
145
+ var shippingStatusSchema = z2.enum([
146
+ "not_shipped",
147
+ "shipped",
148
+ "in_transit",
149
+ "out_for_delivery",
150
+ "delivered",
151
+ "delivery_failed"
152
+ ]);
153
+ var paymentStatusSchema = z2.enum([
154
+ "pending",
155
+ "authorized",
156
+ "paid",
157
+ "captured",
158
+ "failed",
159
+ "refunded",
160
+ "voided",
161
+ "expired"
162
+ ]);
163
+ var legacyOrderStatusSchema = z2.enum([
164
+ "pending",
165
+ "confirmed",
166
+ "processing",
167
+ "shipped",
168
+ "delivered",
169
+ "cancelled",
170
+ "completed"
171
+ ]);
172
+ var KNOWN_PAYMENT_METHODS = [
173
+ "cod",
174
+ "bank_transfer",
175
+ "e_wallet",
176
+ "credit_card",
177
+ "momo",
178
+ "zalopay",
179
+ "vnpay",
180
+ "onepay"
181
+ ];
182
+ var paymentMethodSchema = z2.string().min(1);
183
+ var blogPostStatusSchema = z2.enum([
184
+ "draft",
185
+ "published",
186
+ "scheduled",
187
+ "unlisted"
188
+ ]);
189
+ var integrationStatusSchema = z2.enum(["active", "inactive", "error"]);
190
+ var variantStatusSchema = z2.enum([
191
+ "active",
192
+ "inactive",
193
+ "out_of_stock"
194
+ ]);
195
+ var messageOutboxStatusSchema = z2.enum([
196
+ "PENDING",
197
+ "PUBLISHED",
198
+ "FAILED"
199
+ ]);
200
+ var emailSchema = z2.email();
201
+ var phoneSchema = z2.string().regex(/^[0-9+\-\s()]+$/).optional().nullable();
202
+ var urlSchema = z2.url().optional().nullable();
203
+ var strictUrlSchema = z2.url();
204
+ var slugSchema = z2.string().min(1).regex(/^[a-z0-9-]+$/);
205
+ var colorSchema = z2.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().nullable();
206
+ var optionalUrlSchema = z2.url().optional().or(z2.literal(""));
207
+ var moneySchema = z2.float64().multipleOf(0.01);
208
+ var decimalSchema = z2.float64();
209
+ var jsonSchema = z2.record(z2.string(), z2.any());
210
+ var paginationSchema = z2.object({
211
+ page: z2.int32().min(1).default(1),
212
+ limit: z2.int32().min(1).max(100).default(20)
213
+ });
214
+ var positionOrderSchema = z2.int32().default(0);
215
+ var sortOrderSchema = z2.enum(["asc", "desc"]);
216
+ var dimensionsSchema = z2.object({
217
+ width: z2.float64(),
218
+ height: z2.float64(),
219
+ length: z2.float64().optional()
220
+ }).optional().nullable();
221
+
222
+ // src/types/email-branding.ts
223
+ import { z as z3 } from "zod";
224
+ var EMAIL_PALETTE_DEFAULTS = {
225
+ accent: "#f4644f",
226
+ bg: "#FFFFFF",
227
+ bodyBg: "#FFFFFF",
228
+ text: "#1A1A1A",
229
+ footerText: "#6B7280"
230
+ };
231
+ var EMAIL_COLOR_PATTERN = /^#[0-9A-Fa-f]{6}$/;
232
+ var emailColorSchema = z3.string().regex(EMAIL_COLOR_PATTERN, "Must be a 6-digit hex colour, e.g. #1D4ED8").optional().nullable();
233
+ var emailBrandingShape = {
234
+ email_accent_color: emailColorSchema,
235
+ email_bg_color: emailColorSchema,
236
+ email_body_bg_color: emailColorSchema,
237
+ email_text_color: emailColorSchema,
238
+ email_footer_text_color: emailColorSchema,
239
+ email_logo_url: urlSchema,
240
+ email_header_tagline: z3.string().max(120).optional().nullable(),
241
+ email_footer_address: z3.string().max(255).optional().nullable(),
242
+ email_footer_phone: z3.string().max(32).optional().nullable()
243
+ };
244
+ var emailBrandingSchema = z3.object(emailBrandingShape);
245
+
246
+ // src/types/store.ts
247
+ import { z as z6 } from "zod";
248
+
249
+ // src/types/embedded-script.ts
250
+ import { z as z4 } from "zod";
251
+ var embeddedScriptPlacementSchema = z4.enum([
252
+ "head",
253
+ "body_start",
254
+ "body_end"
255
+ ]);
256
+ var embeddedScriptSchema = z4.object({
257
+ id: idSchema,
258
+ name: z4.string().min(1).max(255),
259
+ code: z4.string().min(1),
260
+ placement: embeddedScriptPlacementSchema,
261
+ created_at: z4.iso.datetime().optional().nullable(),
262
+ updated_at: z4.iso.datetime().optional().nullable()
263
+ });
264
+ var createEmbeddedScriptSchema = embeddedScriptSchema.pick({
265
+ name: true,
266
+ code: true,
267
+ placement: true
268
+ });
269
+ var updateEmbeddedScriptSchema = createEmbeddedScriptSchema.partial();
270
+
271
+ // src/types/storefront-builder.ts
272
+ import { z as z5 } from "zod";
273
+ var sectionTypeSchema = z5.enum([
274
+ "hero_banner",
275
+ "category_grid",
276
+ "collection_grid",
277
+ "featured_products",
278
+ "text_with_image",
279
+ "rich_text",
280
+ "newsletter_signup"
281
+ ]);
282
+ var sectionStyleSchema = z5.object({
283
+ background_color: z5.string().optional(),
284
+ text_color: z5.string().optional(),
285
+ padding_top: z5.string().optional(),
286
+ padding_right: z5.string().optional(),
287
+ padding_bottom: z5.string().optional(),
288
+ padding_left: z5.string().optional(),
289
+ margin_top: z5.string().optional(),
290
+ margin_right: z5.string().optional(),
291
+ margin_bottom: z5.string().optional(),
292
+ margin_left: z5.string().optional(),
293
+ text_align: z5.enum(["left", "center", "right", "justify"]).optional(),
294
+ max_width: z5.enum(["full", "xl", "lg", "md"]).optional()
295
+ });
296
+ var heroBannerItemSchema = z5.object({
297
+ id: z5.string(),
298
+ title: z5.string().optional(),
299
+ subtitle: z5.string().optional(),
300
+ image_url: z5.string().min(1),
301
+ link_url: z5.string().optional(),
302
+ button_text: z5.string().optional()
303
+ });
304
+ var heroBannerConfigSchema = z5.object({
305
+ banners: z5.array(heroBannerItemSchema).default([]),
306
+ autoplay: z5.boolean().default(true),
307
+ autoplay_interval: z5.number().min(1e3).max(3e4).default(5e3)
308
+ });
309
+ var categoryGridConfigSchema = z5.object({
310
+ category_ids: z5.array(z5.number()).default([]),
311
+ columns: z5.union([z5.literal(2), z5.literal(3), z5.literal(4), z5.literal(6)]).default(4),
312
+ show_names: z5.boolean().default(true),
313
+ show_count: z5.boolean().default(false),
314
+ title: z5.string().optional()
315
+ });
316
+ var collectionGridConfigSchema = z5.object({
317
+ collection_ids: z5.array(z5.number()).default([]),
318
+ columns: z5.union([z5.literal(2), z5.literal(3), z5.literal(4), z5.literal(6)]).default(4),
319
+ show_names: z5.boolean().default(true),
320
+ show_count: z5.boolean().default(false),
321
+ title: z5.string().optional()
322
+ });
323
+ var featuredProductsConfigSchema = z5.object({
324
+ collection_slug: z5.string().optional(),
325
+ product_ids: z5.array(z5.number()).optional(),
326
+ limit: z5.number().min(1).max(48).default(12),
327
+ columns: z5.union([z5.literal(2), z5.literal(3), z5.literal(4), z5.literal(6)]).default(4),
328
+ title: z5.string().optional()
329
+ });
330
+ var textWithImageConfigSchema = z5.object({
331
+ content: z5.string().default(""),
332
+ image_url: z5.string().default(""),
333
+ image_position: z5.enum(["left", "right"]).default("right")
334
+ });
335
+ var richTextConfigSchema = z5.object({
336
+ content: z5.string().default("")
337
+ });
338
+ var newsletterSignupConfigSchema = z5.object({
339
+ title: z5.string().optional(),
340
+ description: z5.string().optional(),
341
+ button_text: z5.string().optional()
342
+ });
343
+ var sectionConfigSchema = z5.union([
344
+ heroBannerConfigSchema,
345
+ categoryGridConfigSchema,
346
+ collectionGridConfigSchema,
347
+ featuredProductsConfigSchema,
348
+ textWithImageConfigSchema,
349
+ richTextConfigSchema,
350
+ newsletterSignupConfigSchema
351
+ ]);
352
+ var builderSectionSchema = z5.object({
353
+ id: z5.string(),
354
+ type: sectionTypeSchema,
355
+ title: z5.string().optional(),
356
+ is_visible: z5.boolean().default(true),
357
+ content: z5.record(z5.string(), z5.any()).default({}),
358
+ style: sectionStyleSchema.default({})
359
+ });
360
+ var SECTION_CONFIG_SCHEMAS = {
361
+ hero_banner: heroBannerConfigSchema,
362
+ category_grid: categoryGridConfigSchema,
363
+ collection_grid: collectionGridConfigSchema,
364
+ featured_products: featuredProductsConfigSchema,
365
+ text_with_image: textWithImageConfigSchema,
366
+ rich_text: richTextConfigSchema,
367
+ newsletter_signup: newsletterSignupConfigSchema
368
+ };
369
+ function parseSectionContent(type, content) {
370
+ return SECTION_CONFIG_SCHEMAS[type].parse(content);
371
+ }
372
+ var WIDGET_REGISTRY = {
373
+ hero_banner: {
374
+ type: "hero_banner",
375
+ name: "section_types.hero_banner",
376
+ icon: "Image",
377
+ description: "type_descriptions.hero_banner",
378
+ category: "media",
379
+ defaultContent: { banners: [], autoplay: true, autoplay_interval: 5e3 },
380
+ defaultStyle: { padding_top: "0", padding_bottom: "0" }
381
+ },
382
+ category_grid: {
383
+ type: "category_grid",
384
+ name: "section_types.category_grid",
385
+ icon: "Grid3X3",
386
+ description: "type_descriptions.category_grid",
387
+ category: "commerce",
388
+ defaultContent: { category_ids: [], columns: 4, show_names: true, show_count: false, title: "" },
389
+ defaultStyle: { padding_top: "2rem", padding_bottom: "2rem" }
390
+ },
391
+ collection_grid: {
392
+ type: "collection_grid",
393
+ name: "section_types.collection_grid",
394
+ icon: "Grid3X3",
395
+ description: "type_descriptions.collection_grid",
396
+ category: "commerce",
397
+ defaultContent: {
398
+ collection_ids: [],
399
+ columns: 4,
400
+ show_names: true,
401
+ show_count: false,
402
+ title: ""
403
+ },
404
+ defaultStyle: { padding_top: "2rem", padding_bottom: "2rem" }
405
+ },
406
+ featured_products: {
407
+ type: "featured_products",
408
+ name: "section_types.featured_products",
409
+ icon: "Package",
410
+ description: "type_descriptions.featured_products",
411
+ category: "commerce",
412
+ defaultContent: { collection_slug: "", limit: 12, columns: 4, title: "" },
413
+ defaultStyle: { padding_top: "2rem", padding_bottom: "2rem" }
414
+ },
415
+ text_with_image: {
416
+ type: "text_with_image",
417
+ name: "section_types.text_with_image",
418
+ icon: "LayoutList",
419
+ description: "type_descriptions.text_with_image",
420
+ category: "content",
421
+ defaultContent: { content: "", image_url: "", image_position: "right" },
422
+ defaultStyle: { padding_top: "2rem", padding_bottom: "2rem" }
423
+ },
424
+ rich_text: {
425
+ type: "rich_text",
426
+ name: "section_types.rich_text",
427
+ icon: "Type",
428
+ description: "type_descriptions.rich_text",
429
+ category: "content",
430
+ defaultContent: { content: "" },
431
+ defaultStyle: { padding_top: "2rem", padding_bottom: "2rem", max_width: "lg" }
432
+ },
433
+ newsletter_signup: {
434
+ type: "newsletter_signup",
435
+ name: "section_types.newsletter_signup",
436
+ icon: "Mail",
437
+ description: "type_descriptions.newsletter_signup",
438
+ category: "engagement",
439
+ defaultContent: { title: "", description: "", button_text: "" },
440
+ defaultStyle: { padding_top: "2rem", padding_bottom: "2rem", max_width: "lg" }
441
+ }
442
+ };
443
+ var headerConfigSchema = z5.object({
444
+ show_logo: z5.boolean().default(true),
445
+ show_search: z5.boolean().default(true),
446
+ show_cart: z5.boolean().default(true),
447
+ show_auth: z5.boolean().default(true),
448
+ main_menu_ref: z5.string().optional(),
449
+ background_color: z5.string().optional(),
450
+ text_color: z5.string().optional(),
451
+ // Topbar (announcement bar above header)
452
+ topbar_message: z5.string().optional(),
453
+ topbar_container_class: z5.string().optional()
454
+ });
455
+ var footerConfigSchema = z5.object({
456
+ show_logo: z5.boolean().default(true),
457
+ show_social_links: z5.boolean().default(true),
458
+ customer_support_menu_ref: z5.string().optional(),
459
+ about_us_menu_ref: z5.string().optional(),
460
+ copyright_text: z5.string().optional(),
461
+ background_color: z5.string().optional(),
462
+ text_color: z5.string().optional()
463
+ });
464
+ var builderThemeConfigSchema = z5.object({
465
+ // Legacy fields (preserved for backward compat)
466
+ menu: z5.object({
467
+ main_menu: z5.string().optional(),
468
+ customer_support_menu: z5.string().optional(),
469
+ about_us_menu: z5.string().optional()
470
+ }).optional(),
471
+ topbar: z5.object({
472
+ message: z5.string().optional(),
473
+ container_class: z5.string().optional()
474
+ }).optional(),
475
+ homepage: z5.object({
476
+ collection_slug: z5.string().optional()
477
+ }).optional(),
478
+ checkout: z5.object({
479
+ term_link: z5.string().optional(),
480
+ policy_link: z5.string().optional()
481
+ }).optional(),
482
+ // Builder fields
483
+ sections: z5.array(builderSectionSchema).optional(),
484
+ header: headerConfigSchema.optional(),
485
+ footer: footerConfigSchema.optional()
486
+ }).passthrough();
487
+ var themeVersionSchema = z5.object({
488
+ id: z5.number(),
489
+ name: z5.string(),
490
+ theme_config_snapshot: builderThemeConfigSchema,
491
+ created_by: z5.string(),
492
+ created_at: z5.string(),
493
+ updated_at: z5.string()
494
+ });
495
+
496
+ // src/types/store.ts
497
+ var storeSchema = z6.object({
498
+ id: idSchema,
499
+ user_id: uuidSchema,
500
+ name: z6.string().min(1),
501
+ description: z6.string().optional().nullable(),
502
+ status: storeStatusSchema.default("pending")
503
+ }).extend(timestampSchema.shape).extend(deletedAtSchema.shape);
504
+ var storeConfigSchema = z6.object({
505
+ id: idSchema,
506
+ store_id: idSchema,
507
+ subdomain: z6.string().optional().nullable(),
508
+ custom_domain: z6.string().optional().nullable()
509
+ }).extend(timestampSchema.shape);
510
+ var themeConfigSchema = builderThemeConfigSchema.optional().nullable();
511
+ var storeSettingsSchema = z6.object({
512
+ id: idSchema,
513
+ store_id: idSchema,
514
+ logo_url: urlSchema,
515
+ favicon_url: urlSchema,
516
+ featured_image: urlSchema,
517
+ tiktok_link: urlSchema,
518
+ shopee_link: urlSchema,
519
+ facebook_link: urlSchema,
520
+ instagram_link: urlSchema,
521
+ google_analytics_key: z6.string().optional().nullable(),
522
+ shop_introduction: z6.string().optional().nullable(),
523
+ tagline: z6.string().optional().nullable(),
524
+ blog_title: z6.string().optional().nullable(),
525
+ is_blog_enabled: z6.boolean().optional().nullable(),
526
+ currency_code: z6.string().min(3).max(3).default("VND").optional().nullable(),
527
+ review_requests_enabled: z6.boolean().optional().nullable(),
528
+ /**
529
+ * Wrap the order sequence to form Order.order_code. A null prefix means
530
+ * the store never configured one and takes the default "#"; an empty
531
+ * string means the merchant deliberately cleared it.
532
+ */
533
+ order_number_prefix: z6.string().optional().nullable(),
534
+ order_number_suffix: z6.string().optional().nullable(),
535
+ theme_config: themeConfigSchema
536
+ }).extend(emailBrandingShape).extend(optionalTimestampSchema.shape);
537
+ var createStoreSchema = storeSchema.omit({
538
+ id: true,
539
+ created_at: true,
540
+ updated_at: true,
541
+ deleted_at: true
542
+ });
543
+ var updateStoreSchema = createStoreSchema.partial();
544
+ var createStoreConfigSchema = storeConfigSchema.omit({
545
+ id: true,
546
+ created_at: true,
547
+ updated_at: true
548
+ });
549
+ var updateStoreConfigSchema = createStoreConfigSchema.partial().omit({
550
+ store_id: true
551
+ });
552
+ var createStoreSettingsSchema = storeSettingsSchema.omit({
553
+ id: true,
554
+ created_at: true,
555
+ updated_at: true
556
+ });
557
+ var updateStoreSettingsSchema = createStoreSettingsSchema.partial().omit({
558
+ store_id: true
559
+ });
560
+ var storeWithRelationsSchema = storeSchema.extend({
561
+ store_config: storeConfigSchema.optional().nullable(),
562
+ store_settings: storeSettingsSchema.optional().nullable(),
563
+ theme_config: themeConfigSchema,
564
+ embedded_scripts: z6.array(embeddedScriptSchema).optional()
565
+ });
566
+
567
+ // src/types/product.ts
568
+ import { z as z9 } from "zod";
569
+
570
+ // src/types/product-review.ts
571
+ import { z as z8 } from "zod";
572
+
573
+ // src/types/pagination.ts
574
+ import { z as z7 } from "zod";
575
+ var paginationMetaSchema = z7.object({
576
+ total: z7.uint32(),
577
+ limit: z7.int32().positive(),
578
+ offset: z7.uint32(),
579
+ page: z7.int32().positive(),
580
+ totalPages: z7.uint32(),
581
+ hasNext: z7.boolean(),
582
+ hasPrev: z7.boolean()
583
+ });
584
+ var paginatedResponseSchema = (itemSchema) => z7.object({
585
+ data: z7.array(itemSchema),
586
+ meta: paginationMetaSchema
587
+ });
588
+ var baseQueryParamsSchema = z7.object({
589
+ limit: z7.int32().min(1).max(100).optional(),
590
+ offset: z7.uint32().optional(),
591
+ search: z7.string().optional(),
592
+ sort_by: z7.string().optional(),
593
+ sort_order: sortOrderSchema.optional(),
594
+ created_after: timestampSchema.optional(),
595
+ created_before: timestampSchema.optional(),
596
+ updated_after: timestampSchema.optional(),
597
+ updated_before: timestampSchema.optional()
598
+ });
599
+ var baseDeleteOptionsSchema = z7.object({
600
+ soft_delete: z7.boolean().optional(),
601
+ reason: z7.string().optional(),
602
+ force: z7.boolean().optional()
603
+ });
604
+ var baseDeleteResultSchema = z7.object({
605
+ success: z7.boolean(),
606
+ type: z7.enum(["soft", "hard"]),
607
+ message: z7.string(),
608
+ entity_id: z7.union([z7.number(), z7.string()]),
609
+ deleted_at: timestampSchema.optional()
610
+ });
611
+ var PAGINATION_DEFAULTS = {
612
+ LIMIT: 20,
613
+ MAX_LIMIT: 100,
614
+ MIN_LIMIT: 1,
615
+ DEFAULT_OFFSET: 0,
616
+ DEFAULT_ORDER: "desc"
617
+ };
618
+ var validatePaginationMeta = (data) => {
619
+ try {
620
+ return paginationMetaSchema.parse(data);
621
+ } catch (error) {
622
+ if (error instanceof z7.ZodError) {
623
+ throw new Error(z7.prettifyError(error));
624
+ }
625
+ throw error;
626
+ }
627
+ };
628
+ var safeParsePaginationMeta = (data) => paginationMetaSchema.safeParse(data);
629
+ var safeParseBaseQueryParams = (data) => baseQueryParamsSchema.safeParse(data);
630
+
631
+ // src/types/product-review.ts
632
+ var reviewStatusSchema = z8.enum([
633
+ "PENDING",
634
+ "APPROVED",
635
+ "REJECTED",
636
+ "HIDDEN"
637
+ ]);
638
+ var productReviewReplySchema = z8.object({
639
+ id: uuidSchema,
640
+ review_id: uuidSchema,
641
+ content: z8.string().min(1),
642
+ author_id: uuidSchema,
643
+ author_name: z8.string().min(1),
644
+ is_visible: z8.boolean().default(true)
645
+ }).extend(timestampSchema.shape).extend(deletedAtSchema.shape);
646
+ var createProductReviewReplySchema = productReviewReplySchema.omit({
647
+ id: true,
648
+ created_at: true,
649
+ updated_at: true,
650
+ deleted_at: true
651
+ });
652
+ var updateProductReviewReplySchema = productReviewReplySchema.partial().omit({ id: true, review_id: true, created_at: true });
653
+ var productReviewSchema = z8.object({
654
+ id: uuidSchema,
655
+ product_id: z8.bigint(),
656
+ product_name: z8.string().min(1),
657
+ variant_id: z8.bigint().optional().nullable(),
658
+ variant_name: z8.string().optional().nullable(),
659
+ order_id: z8.bigint().optional().nullable(),
660
+ order_number: z8.bigint().optional().nullable(),
661
+ user_id: uuidSchema.optional().nullable(),
662
+ reviewer_name: z8.string().min(1),
663
+ reviewer_email: emailSchema,
664
+ reviewer_avatar: z8.string().url().optional().nullable(),
665
+ is_verified_buyer: z8.boolean().default(false),
666
+ rating: z8.int32().min(1).max(5),
667
+ title: z8.string().max(200).optional().nullable(),
668
+ content: z8.string().min(1),
669
+ pros: z8.array(z8.string()).default([]),
670
+ cons: z8.array(z8.string()).default([]),
671
+ media: z8.array(z8.any()).default([]),
672
+ status: reviewStatusSchema.default("PENDING"),
673
+ moderation_notes: z8.string().optional().nullable(),
674
+ approved_by: uuidSchema.optional().nullable(),
675
+ approved_at: z8.iso.datetime().optional().nullable(),
676
+ rejected_reason: z8.string().optional().nullable(),
677
+ is_featured: z8.boolean().default(false),
678
+ is_pinned: z8.boolean().default(false),
679
+ display_order: z8.int32().optional().nullable(),
680
+ review_date: z8.iso.datetime().optional().nullable()
681
+ }).extend(timestampSchema.shape).extend(deletedAtSchema.shape);
682
+ var createProductReviewSchema = productReviewSchema.omit({
683
+ id: true,
684
+ created_at: true,
685
+ updated_at: true,
686
+ deleted_at: true
687
+ });
688
+ var updateProductReviewSchema = productReviewSchema.partial().omit({ id: true, created_at: true });
689
+ var productReviewWithRepliesSchema = productReviewSchema.extend({
690
+ review_replies: z8.array(productReviewReplySchema).optional()
691
+ });
692
+ var productReviewStatsSchema = z8.object({
693
+ id: idSchema,
694
+ product_id: z8.bigint(),
695
+ total_reviews: z8.int32().default(0),
696
+ verified_reviews: z8.int32().default(0),
697
+ reviews_with_media: z8.int32().default(0),
698
+ reviews_with_reply: z8.int32().default(0),
699
+ average_rating: z8.float64().default(0),
700
+ rating_1_count: z8.int32().default(0),
701
+ rating_2_count: z8.int32().default(0),
702
+ rating_3_count: z8.int32().default(0),
703
+ rating_4_count: z8.int32().default(0),
704
+ rating_5_count: z8.int32().default(0),
705
+ last_review_at: z8.iso.datetime().optional().nullable(),
706
+ last_calculated_at: z8.iso.datetime(),
707
+ updated_at: z8.iso.datetime()
708
+ });
709
+ var productReviewFiltersSchema = baseQueryParamsSchema.extend({
710
+ id: uuidSchema.optional(),
711
+ product_id: z8.bigint().optional(),
712
+ user_id: uuidSchema.optional(),
713
+ rating: z8.int32().min(1).max(5).optional(),
714
+ min_rating: z8.int32().min(1).max(5).optional(),
715
+ max_rating: z8.int32().min(1).max(5).optional(),
716
+ status: reviewStatusSchema.optional(),
717
+ is_verified_buyer: z8.boolean().optional(),
718
+ reviewer_email: emailSchema.optional(),
719
+ reviewer_name: z8.string().optional(),
720
+ has_media: z8.boolean().optional(),
721
+ include_replies: z8.boolean().optional()
722
+ });
723
+ var productReviewReplyFiltersSchema = baseQueryParamsSchema.extend({
724
+ id: uuidSchema.optional(),
725
+ review_id: uuidSchema.optional(),
726
+ is_visible: z8.boolean().optional(),
727
+ author_id: uuidSchema.optional()
728
+ });
729
+
730
+ // src/types/inventory.ts
731
+ var INVENTORY_STATES = [
732
+ "available",
733
+ "committed",
734
+ "damaged",
735
+ "quality_control",
736
+ "safety_stock",
737
+ "other",
738
+ "incoming"
739
+ ];
740
+ var UNAVAILABLE_STATES = [
741
+ "damaged",
742
+ "quality_control",
743
+ "safety_stock",
744
+ "other"
745
+ ];
746
+ var ADJUSTABLE_STATES = [
747
+ "available",
748
+ "damaged",
749
+ "quality_control",
750
+ "safety_stock",
751
+ "other"
752
+ ];
753
+ var INVENTORY_POLICIES = ["deny", "continue"];
754
+ var INVENTORY_ADJUSTMENT_REASONS = [
755
+ // Reasons a merchant picks
756
+ "correction",
757
+ "count",
758
+ "received",
759
+ "return_restock",
760
+ "damaged",
761
+ "theft_or_loss",
762
+ "promotion_or_donation",
763
+ "other",
764
+ // Reasons the system records
765
+ "initial_stock",
766
+ "order_reserved",
767
+ "order_fulfilled",
768
+ "order_released",
769
+ "order_restocked",
770
+ "cancelled_not_restocked",
771
+ "migration_backfill",
772
+ "purchase_order_ordered",
773
+ "purchase_order_edited",
774
+ "purchase_order_cancelled",
775
+ "purchase_order_closed"
776
+ ];
777
+ var MERCHANT_ADJUSTMENT_REASONS = [
778
+ "correction",
779
+ "count",
780
+ "received",
781
+ "return_restock",
782
+ "damaged",
783
+ "theft_or_loss",
784
+ "promotion_or_donation",
785
+ "other"
786
+ ];
787
+ var INVENTORY_ERROR_CODES = {
788
+ /** 409. `details.items: InsufficientInventoryItem[]`. */
789
+ INSUFFICIENT_INVENTORY: "INSUFFICIENT_INVENTORY",
790
+ /** 409. `details.states: [{ variant_id, state, quantity }]`. */
791
+ STATE_NEGATIVE: "INVENTORY_STATE_NEGATIVE",
792
+ /** 404. `details.variant_ids: number[]`. */
793
+ VARIANT_NOT_IN_STORE: "INVENTORY_VARIANT_NOT_IN_STORE",
794
+ /** 400. `details.variant_ids: number[]`. */
795
+ DUPLICATE_VARIANT: "INVENTORY_DUPLICATE_VARIANT",
796
+ /** 409. `details: SetQuantitiesResponse`; the non-stale items WERE applied. */
797
+ QUANTITY_STALE: "INVENTORY_QUANTITY_STALE",
798
+ /** 400. More than 5,000 data rows. */
799
+ IMPORT_TOO_LARGE: "INVENTORY_IMPORT_TOO_LARGE",
800
+ /** 400. `details.missing_columns?: string[]`. */
801
+ IMPORT_INVALID_FILE: "INVENTORY_IMPORT_INVALID_FILE"
802
+ };
803
+ function onHand(level) {
804
+ return level.available + level.committed + level.damaged + level.quality_control + level.safety_stock + level.other;
805
+ }
806
+ function unavailable(level) {
807
+ return level.damaged + level.quality_control + level.safety_stock + level.other;
808
+ }
809
+
810
+ // src/types/product.ts
811
+ var productSchema = z9.object({
812
+ id: idSchema,
813
+ name: z9.string().min(1),
814
+ slug: z9.string().max(255).optional().nullable(),
815
+ description: z9.string().optional().nullable(),
816
+ status: productStatusSchema.default("active"),
817
+ category_id: idSchema.optional().nullable(),
818
+ is_featured: z9.boolean().default(false),
819
+ min_price: moneySchema.optional().nullable(),
820
+ max_price: moneySchema.optional().nullable(),
821
+ variant_mode: z9.string(),
822
+ external_id: z9.string().optional().nullable(),
823
+ images: jsonSchema
824
+ // Array of image objects
825
+ }).extend(timestampSchema.shape);
826
+ var productVariantSchema = z9.object({
827
+ id: idSchema,
828
+ product_id: idSchema,
829
+ sku_id: idSchema,
830
+ seller_sku: z9.string().optional().nullable(),
831
+ external_id: z9.string().optional().nullable(),
832
+ price: moneySchema,
833
+ inventory: z9.int32().default(0),
834
+ track_inventory: z9.boolean().default(true),
835
+ inventory_policy: z9.enum(INVENTORY_POLICIES).default("deny"),
836
+ // z.number(), not moneySchema: unit costs carry up to 4 decimals, and
837
+ // moneySchema (2 decimals) would reject a valid cost.
838
+ cost_per_item: z9.number().nonnegative().nullable().optional(),
839
+ weight: decimalSchema.optional().nullable(),
840
+ dimensions: dimensionsSchema,
841
+ is_default: z9.boolean().default(false),
842
+ status: variantStatusSchema.default("active")
843
+ }).extend(timestampSchema.shape);
844
+ var variantOptionSchema = z9.object({
845
+ id: idSchema,
846
+ name: z9.string().min(1),
847
+ sort_order: positionOrderSchema
848
+ }).extend(timestampSchema.shape);
849
+ var variantOptionValueSchema = z9.object({
850
+ id: idSchema,
851
+ option_id: idSchema,
852
+ value: z9.string().min(1),
853
+ display_value: z9.string().min(1),
854
+ image_url: z9.string().default(""),
855
+ sort_order: positionOrderSchema,
856
+ swatch_type: z9.enum(["none", "color", "image"]).default("none"),
857
+ swatch_value: z9.string().default("")
858
+ }).extend(timestampSchema.shape);
859
+ var productVariantCombinationSchema = z9.object({
860
+ id: idSchema,
861
+ variant_id: idSchema,
862
+ option_id: idSchema,
863
+ option_value_id: idSchema,
864
+ created_at: z9.iso.datetime()
865
+ });
866
+ var createProductSchema = productSchema.omit({
867
+ id: true,
868
+ created_at: true,
869
+ updated_at: true
870
+ });
871
+ var updateProductSchema = productSchema.omit({
872
+ id: true,
873
+ created_at: true,
874
+ updated_at: true
875
+ }).partial();
876
+ var createProductVariantSchema = productVariantSchema.omit({
877
+ id: true,
878
+ sku_id: true,
879
+ created_at: true,
880
+ updated_at: true
881
+ });
882
+ var updateProductVariantSchema = productVariantSchema.omit({
883
+ id: true,
884
+ sku_id: true,
885
+ created_at: true,
886
+ updated_at: true
887
+ }).partial().omit({
888
+ product_id: true
889
+ });
890
+ var createVariantOptionSchema = variantOptionSchema.omit({
891
+ id: true,
892
+ created_at: true,
893
+ updated_at: true
894
+ });
895
+ var updateVariantOptionSchema = variantOptionSchema.omit({
896
+ id: true,
897
+ created_at: true,
898
+ updated_at: true
899
+ }).partial();
900
+ var createVariantOptionValueSchema = variantOptionValueSchema.omit({
901
+ id: true,
902
+ created_at: true,
903
+ updated_at: true
904
+ });
905
+ var updateVariantOptionValueSchema = variantOptionValueSchema.omit({
906
+ id: true,
907
+ created_at: true,
908
+ updated_at: true
909
+ }).partial().omit({
910
+ option_id: true
911
+ });
912
+ var productVariantCombinationEntrySchema = z9.object({
913
+ attributes: variantOptionSchema,
914
+ attribute_values: variantOptionValueSchema
915
+ });
916
+ var productVariantWithCombinationsSchema = productVariantSchema.extend(
917
+ {
918
+ combinations: z9.array(productVariantCombinationEntrySchema).optional()
919
+ }
920
+ );
921
+ var attributeLinkValueSchema = z9.object({
922
+ key: z9.string(),
923
+ display: z9.string(),
924
+ swatch_type: z9.enum(["none", "color", "image"]),
925
+ swatch_value: z9.string(),
926
+ attribute_value_id: z9.number().nullable()
927
+ });
928
+ var attributeLinkSchema = z9.object({
929
+ id: z9.number(),
930
+ position: z9.number(),
931
+ group: z9.string().nullable(),
932
+ is_visible: z9.boolean(),
933
+ is_variation: z9.boolean(),
934
+ attribute_id: z9.number().nullable(),
935
+ custom_name: z9.string().nullable(),
936
+ name: z9.string(),
937
+ values: z9.array(attributeLinkValueSchema)
938
+ });
939
+ var productWithVariantsSchema = productSchema.extend({
940
+ variants: z9.array(productVariantWithCombinationsSchema).optional()
941
+ });
942
+ var productWithReviewStatsSchema = productSchema.extend({
943
+ review_stats: productReviewStatsSchema.optional().nullable()
944
+ });
945
+ var productWithVariantsAndReviewStatsSchema = productWithVariantsSchema.extend({
946
+ review_stats: productReviewStatsSchema.optional().nullable()
947
+ });
948
+
949
+ // src/types/category.ts
950
+ import { z as z10 } from "zod";
951
+ var categorySchema = z10.object({
952
+ id: idSchema,
953
+ name: z10.string().min(1),
954
+ slug: z10.string().optional().nullable(),
955
+ description: z10.string().optional().nullable(),
956
+ image_url: urlSchema,
957
+ parent_id: idSchema.optional().nullable(),
958
+ sort_order: positionOrderSchema,
959
+ is_active: z10.boolean().default(true),
960
+ external_cat_id: z10.string().optional().nullable()
961
+ }).extend(optionalTimestampSchema.shape);
962
+ var createCategorySchema = categorySchema.omit({
963
+ id: true,
964
+ created_at: true,
965
+ updated_at: true
966
+ });
967
+ var updateCategorySchema = createCategorySchema.partial();
968
+ var categoryWithChildrenSchema = categorySchema.extend({
969
+ children: z10.array(z10.lazy(() => categoryWithChildrenSchema)).optional()
970
+ });
971
+ var categoryTreeSchema = z10.array(
972
+ categoryWithChildrenSchema
973
+ );
974
+
975
+ // src/types/order.ts
976
+ import { z as z11 } from "zod";
977
+ var ORDER_SOURCES = ["online", "pos", "phone", "admin"];
978
+ var ADMIN_ORDER_SOURCES = ["pos", "phone", "admin"];
979
+ var appliedPromotionSchema = z11.object({
980
+ promotion_id: idSchema,
981
+ promotion_name: z11.string().optional().nullable(),
982
+ discount_amount: moneySchema.optional().nullable(),
983
+ shipping_discount: moneySchema.optional().nullable()
984
+ });
985
+ var orderItemSchema = z11.object({
986
+ id: idSchema,
987
+ order_id: idSchema.optional().nullable(),
988
+ product_id: idSchema.optional().nullable(),
989
+ product_name: z11.string().min(1),
990
+ product_image: z11.string().optional().nullable(),
991
+ quantity: z11.int32().min(1).default(1),
992
+ price: moneySchema,
993
+ original_price: moneySchema.optional().nullable(),
994
+ total: moneySchema,
995
+ discount: moneySchema.optional().nullable(),
996
+ applied_promotions: z11.array(appliedPromotionSchema).optional(),
997
+ variant_id: idSchema.optional().nullable(),
998
+ variant_name: z11.string().optional().nullable(),
999
+ created_at: z11.iso.datetime().optional().nullable()
1000
+ });
1001
+ var orderSchema = z11.object({
1002
+ id: idSchema,
1003
+ user_id: uuidSchema.optional().nullable(),
1004
+ customer_name: z11.string().min(1),
1005
+ customer_email: emailSchema.nullable(),
1006
+ customer_phone: phoneSchema,
1007
+ customer_avatar: z11.string().optional().nullable(),
1008
+ // DEPRECATED: Legacy status field for backward compatibility
1009
+ status: z11.string().optional().nullable(),
1010
+ // NEW: Separate status fields managed by state machines
1011
+ order_status: orderStatusSchema,
1012
+ fulfillment_status: fulfillmentStatusSchema,
1013
+ shipping_status: shippingStatusSchema,
1014
+ payment_status: paymentStatusSchema,
1015
+ payment_method: paymentMethodSchema.nullable().optional(),
1016
+ subtotal: moneySchema.default(0),
1017
+ original_subtotal: moneySchema.default(0),
1018
+ shipping_fee: moneySchema.default(0),
1019
+ original_shipping_fee: moneySchema.default(0),
1020
+ shipping_discount: moneySchema.default(0),
1021
+ tax: moneySchema.default(0),
1022
+ discount: moneySchema.default(0),
1023
+ total: moneySchema.default(0),
1024
+ shipping_street: z11.string().min(1),
1025
+ shipping_city: z11.string().min(1),
1026
+ shipping_district: z11.string().optional().nullable(),
1027
+ shipping_ward: z11.string().optional().nullable(),
1028
+ shipping_postal_code: z11.string().optional().nullable(),
1029
+ tracking_number: z11.string().optional().nullable(),
1030
+ notes: z11.string().optional().nullable(),
1031
+ order_number: idSchema,
1032
+ order_code: z11.string(),
1033
+ items: z11.array(orderItemSchema).optional(),
1034
+ applied_promotions: z11.array(appliedPromotionSchema).optional(),
1035
+ shipping_method_name: z11.string().optional().nullable(),
1036
+ shipping_city_name: z11.string().optional().nullable(),
1037
+ shipping_ward_name: z11.string().optional().nullable(),
1038
+ source: z11.enum(ORDER_SOURCES).default("online"),
1039
+ created_by: z11.object({
1040
+ id: uuidSchema,
1041
+ name: z11.string().nullable(),
1042
+ email: z11.string().nullable()
1043
+ }).nullable().optional()
1044
+ }).extend(optionalTimestampSchema.shape);
1045
+ var createOrderSchema = orderSchema.omit({
1046
+ id: true,
1047
+ order_number: true,
1048
+ order_code: true,
1049
+ created_at: true,
1050
+ updated_at: true,
1051
+ applied_promotions: true,
1052
+ shipping_method_name: true,
1053
+ shipping_city_name: true,
1054
+ shipping_ward_name: true,
1055
+ tax: true,
1056
+ source: true,
1057
+ created_by: true
1058
+ }).extend({
1059
+ // Write-only: not part of the order response.
1060
+ shipping_method_id: idSchema.optional().nullable(),
1061
+ shipping_rate_id: idSchema.optional().nullable()
1062
+ });
1063
+ var updateOrderSchema = orderSchema.omit({
1064
+ id: true,
1065
+ order_number: true,
1066
+ order_code: true,
1067
+ created_at: true,
1068
+ updated_at: true,
1069
+ applied_promotions: true,
1070
+ shipping_method_name: true,
1071
+ shipping_city_name: true,
1072
+ shipping_ward_name: true,
1073
+ source: true,
1074
+ created_by: true
1075
+ }).partial();
1076
+ var createOrderItemSchema = orderItemSchema.omit({
1077
+ id: true,
1078
+ created_at: true,
1079
+ discount: true,
1080
+ applied_promotions: true
1081
+ }).partial({
1082
+ price: true,
1083
+ total: true
1084
+ });
1085
+ var updateOrderItemSchema = orderItemSchema.omit({
1086
+ id: true,
1087
+ created_at: true,
1088
+ discount: true,
1089
+ applied_promotions: true
1090
+ }).partial().omit({
1091
+ order_id: true
1092
+ });
1093
+ var orderWithItemsSchema = orderSchema.extend({
1094
+ items: z11.array(orderItemSchema).optional()
1095
+ });
1096
+ var customerOrderSummarySchema = z11.object({
1097
+ customer_email: emailSchema,
1098
+ customer_name: z11.string(),
1099
+ total_orders: z11.int32(),
1100
+ total_spent: moneySchema,
1101
+ last_order_date: z11.iso.datetime().optional().nullable()
1102
+ });
1103
+
1104
+ // src/types/order-timeline.ts
1105
+ var ORDER_EVENT_TYPES = [
1106
+ "placed",
1107
+ "order_status_changed",
1108
+ "fulfillment_status_changed",
1109
+ "shipping_status_changed",
1110
+ "payment_status_changed",
1111
+ "tracking_number_updated"
1112
+ ];
1113
+ var ORDER_ACTOR_TYPES = [
1114
+ "staff",
1115
+ "customer",
1116
+ "api_key",
1117
+ "gateway",
1118
+ "system"
1119
+ ];
1120
+
1121
+ // src/types/promotion.ts
1122
+ import { z as z12 } from "zod";
1123
+ var PromotionModeSchema = z12.enum(["DISCOUNT_CODE", "AUTOMATIC"]);
1124
+ var PromotionTypeSchema = z12.enum([
1125
+ "PRODUCT_DISCOUNT",
1126
+ "CART_DISCOUNT",
1127
+ "FREE_SHIPPING",
1128
+ "FIXED_PRICE",
1129
+ "GIFT"
1130
+ ]);
1131
+ var DiscountMethodSchema = z12.enum(["PERCENTAGE", "FIXED_AMOUNT"]);
1132
+ var ConditionTypeSchema = z12.enum([
1133
+ "PRODUCT",
1134
+ "CATEGORY",
1135
+ "VARIANT",
1136
+ "NONE"
1137
+ ]);
1138
+ var PromotionStatusSchema = z12.enum([
1139
+ "DRAFT",
1140
+ "ACTIVE",
1141
+ "EXPIRED",
1142
+ "DISABLED"
1143
+ ]);
1144
+ var PromotionMode = {
1145
+ DISCOUNT_CODE: "DISCOUNT_CODE",
1146
+ AUTOMATIC: "AUTOMATIC"
1147
+ };
1148
+ var PromotionType = {
1149
+ PRODUCT_DISCOUNT: "PRODUCT_DISCOUNT",
1150
+ CART_DISCOUNT: "CART_DISCOUNT",
1151
+ FREE_SHIPPING: "FREE_SHIPPING",
1152
+ FIXED_PRICE: "FIXED_PRICE",
1153
+ GIFT: "GIFT"
1154
+ };
1155
+ var DiscountMethod = {
1156
+ PERCENTAGE: "PERCENTAGE",
1157
+ FIXED_AMOUNT: "FIXED_AMOUNT"
1158
+ };
1159
+ var ConditionType = {
1160
+ PRODUCT: "PRODUCT",
1161
+ CATEGORY: "CATEGORY",
1162
+ VARIANT: "VARIANT",
1163
+ NONE: "NONE"
1164
+ };
1165
+ var PromotionStatus = {
1166
+ DRAFT: "DRAFT",
1167
+ ACTIVE: "ACTIVE",
1168
+ EXPIRED: "EXPIRED",
1169
+ DISABLED: "DISABLED"
1170
+ };
1171
+ var PromotionSchema = z12.object({
1172
+ id: z12.number().int().positive(),
1173
+ name: z12.string().min(1).max(255),
1174
+ mode: PromotionModeSchema,
1175
+ code: z12.string().min(1).max(50).optional(),
1176
+ description: z12.string().max(1e3).optional(),
1177
+ start_at: z12.string().datetime(),
1178
+ end_at: z12.string().datetime().optional(),
1179
+ status: PromotionStatusSchema,
1180
+ type: PromotionTypeSchema,
1181
+ condition_type: ConditionTypeSchema,
1182
+ target_ids: z12.array(z12.string().uuid()).optional(),
1183
+ min_amount: z12.number().positive().optional(),
1184
+ min_quantity: z12.number().int().positive().optional(),
1185
+ discount_method: DiscountMethodSchema.optional(),
1186
+ discount_value: z12.number().nonnegative().optional(),
1187
+ max_discount_amount: z12.number().nonnegative().optional(),
1188
+ fixed_price: z12.number().nonnegative().optional(),
1189
+ gift_product_ids: z12.array(z12.string().uuid()),
1190
+ gift_quantity: z12.number().int().positive().optional(),
1191
+ usage_limit: z12.number().int().positive().optional(),
1192
+ usage_limit_per_user: z12.number().int().positive().optional(),
1193
+ checkout_suggestion_enabled: z12.boolean().optional(),
1194
+ created_at: z12.string().datetime(),
1195
+ updated_at: z12.string().datetime(),
1196
+ created_by: z12.string().uuid().optional(),
1197
+ updated_by: z12.string().uuid().optional()
1198
+ });
1199
+ var CreatePromotionSchema = z12.object({
1200
+ name: z12.string().min(1, "T\xEAn khuy\u1EBFn m\xE3i l\xE0 b\u1EAFt bu\u1ED9c").max(255),
1201
+ mode: PromotionModeSchema,
1202
+ code: z12.string().min(1).max(50).optional(),
1203
+ description: z12.string().max(1e3).optional(),
1204
+ start_at: z12.iso.datetime(),
1205
+ end_at: z12.iso.datetime().optional(),
1206
+ type: PromotionTypeSchema,
1207
+ condition_type: ConditionTypeSchema,
1208
+ target_ids: z12.array(z12.uuid()).optional().superRefine((ids, ctx) => {
1209
+ const conditionType = ctx.parent?.condition_type;
1210
+ if (conditionType === "NONE") {
1211
+ return true;
1212
+ }
1213
+ return ids && ids.length > 0;
1214
+ }),
1215
+ min_amount: z12.number().positive().optional(),
1216
+ min_quantity: z12.number().int().positive().optional(),
1217
+ discount_method: DiscountMethodSchema.optional(),
1218
+ discount_value: z12.number().nonnegative().optional(),
1219
+ max_discount_amount: z12.number().nonnegative().optional(),
1220
+ fixed_price: z12.number().nonnegative().optional(),
1221
+ gift_product_ids: z12.array(z12.uuid()).optional(),
1222
+ gift_quantity: z12.number().int().positive().optional(),
1223
+ usage_limit: z12.number().int().positive().optional(),
1224
+ usage_limit_per_user: z12.number().int().positive().optional(),
1225
+ checkout_suggestion_enabled: z12.boolean().optional()
1226
+ });
1227
+ var UpdatePromotionSchema = CreatePromotionSchema.partial().extend({
1228
+ status: PromotionStatusSchema.optional()
1229
+ });
1230
+ var PromotionWithDiscountSchema = PromotionSchema.extend({
1231
+ discount_amount: z12.number().optional()
1232
+ });
1233
+ var PromotionStatisticsSchema = z12.object({
1234
+ total_promotions: z12.number().int().nonnegative(),
1235
+ active_promotions: z12.number().int().nonnegative(),
1236
+ draft_promotions: z12.number().int().nonnegative(),
1237
+ expired_promotions: z12.number().int().nonnegative(),
1238
+ disabled_promotions: z12.number().int().nonnegative(),
1239
+ total_usage: z12.number().int().nonnegative(),
1240
+ total_discount_amount: z12.number().nonnegative(),
1241
+ top_promotions: z12.array(PromotionSchema)
1242
+ });
1243
+ var PaginatedPromotionsResponseSchema = z12.object({
1244
+ data: z12.array(PromotionSchema),
1245
+ meta: paginationMetaSchema
1246
+ });
1247
+ var PromotionQueryParamsSchema = z12.object({
1248
+ limit: z12.number().int().positive().optional(),
1249
+ offset: z12.number().int().nonnegative().optional(),
1250
+ order: z12.enum(["asc", "desc"]).optional(),
1251
+ sort: z12.enum([
1252
+ "name",
1253
+ "start_at",
1254
+ "end_at",
1255
+ "status",
1256
+ "type",
1257
+ "created_at",
1258
+ "updated_at"
1259
+ ]).optional(),
1260
+ search: z12.string().max(255).optional(),
1261
+ status: z12.union([PromotionStatusSchema, z12.literal("all")]).optional(),
1262
+ type: z12.union([PromotionTypeSchema, z12.literal("all")]).optional(),
1263
+ mode: z12.union([PromotionModeSchema, z12.literal("all")]).optional()
1264
+ });
1265
+ var PROMOTION_MODE_LABELS = {
1266
+ DISCOUNT_CODE: "M\xE3 gi\u1EA3m gi\xE1",
1267
+ AUTOMATIC: "T\u1EF1 \u0111\u1ED9ng \xE1p d\u1EE5ng"
1268
+ };
1269
+ var PROMOTION_TYPE_LABELS = {
1270
+ PRODUCT_DISCOUNT: "Gi\u1EA3m gi\xE1 s\u1EA3n ph\u1EA9m",
1271
+ CART_DISCOUNT: "Gi\u1EA3m gi\xE1 gi\u1ECF h\xE0ng",
1272
+ FREE_SHIPPING: "Mi\u1EC5n ph\xED v\u1EADn chuy\u1EC3n",
1273
+ FIXED_PRICE: "Gi\xE1 c\u1ED1 \u0111\u1ECBnh",
1274
+ GIFT: "Qu\xE0 t\u1EB7ng"
1275
+ };
1276
+ var DISCOUNT_METHOD_LABELS = {
1277
+ PERCENTAGE: "Ph\u1EA7n tr\u0103m",
1278
+ FIXED_AMOUNT: "S\u1ED1 ti\u1EC1n c\u1ED1 \u0111\u1ECBnh"
1279
+ };
1280
+ var CONDITION_TYPE_LABELS = {
1281
+ PRODUCT: "S\u1EA3n ph\u1EA9m",
1282
+ CATEGORY: "Danh m\u1EE5c",
1283
+ VARIANT: "Bi\u1EBFn th\u1EC3",
1284
+ NONE: "T\u1EA5t c\u1EA3 s\u1EA3n ph\u1EA9m"
1285
+ };
1286
+ var PROMOTION_STATUS_LABELS = {
1287
+ DRAFT: "Nh\xE1p",
1288
+ ACTIVE: "\u0110ang ho\u1EA1t \u0111\u1ED9ng",
1289
+ EXPIRED: "\u0110\xE3 h\u1EBFt h\u1EA1n",
1290
+ DISABLED: "\u0110\xE3 t\u1EAFt"
1291
+ };
1292
+ var PROMOTION_STATUS_COLORS = {
1293
+ DRAFT: "bg-gray-100 text-gray-800",
1294
+ ACTIVE: "bg-green-100 text-green-800",
1295
+ EXPIRED: "bg-red-100 text-red-800",
1296
+ DISABLED: "bg-yellow-100 text-yellow-800"
1297
+ };
1298
+ var PROMOTION_TYPE_COLORS = {
1299
+ PRODUCT_DISCOUNT: "bg-blue-100 text-blue-800",
1300
+ CART_DISCOUNT: "bg-purple-100 text-purple-800",
1301
+ FREE_SHIPPING: "bg-green-100 text-green-800",
1302
+ FIXED_PRICE: "bg-orange-100 text-orange-800",
1303
+ GIFT: "bg-pink-100 text-pink-800"
1304
+ };
1305
+ var PROMOTION_MODE_COLORS = {
1306
+ DISCOUNT_CODE: "bg-indigo-100 text-indigo-800",
1307
+ AUTOMATIC: "bg-emerald-100 text-emerald-800"
1308
+ };
1309
+
1310
+ // src/types/blog.ts
1311
+ import { z as z13 } from "zod";
1312
+ var tocItemSchema = z13.object({
1313
+ id: z13.string(),
1314
+ level: z13.number().int().min(1).max(6),
1315
+ textContent: z13.string(),
1316
+ pos: z13.number().int()
1317
+ });
1318
+ var blogCategorySchema = z13.object({
1319
+ id: idSchema,
1320
+ name: z13.string().min(1).max(100),
1321
+ slug: slugSchema.max(100),
1322
+ description: z13.string().optional().nullable(),
1323
+ color: colorSchema,
1324
+ sort_order: positionOrderSchema
1325
+ }).extend(optionalTimestampSchema.shape);
1326
+ var blogTagSchema = z13.object({
1327
+ id: idSchema,
1328
+ name: z13.string().min(1).max(50),
1329
+ slug: slugSchema.max(50)
1330
+ }).extend(optionalTimestampSchema.shape);
1331
+ var blogPostSchema = z13.object({
1332
+ id: idSchema,
1333
+ title: z13.string().min(1).max(255),
1334
+ slug: slugSchema.max(255),
1335
+ content: z13.string().optional().nullable(),
1336
+ toc: z13.array(tocItemSchema).optional().nullable(),
1337
+ excerpt: z13.string().optional().nullable(),
1338
+ featured_image_url: urlSchema,
1339
+ status: blogPostStatusSchema.default("draft"),
1340
+ is_featured: z13.boolean().default(false),
1341
+ scheduled_at: z13.iso.datetime().optional().nullable(),
1342
+ published_at: z13.iso.datetime().optional().nullable(),
1343
+ author_id: uuidSchema.optional().nullable(),
1344
+ view_count: z13.int32().default(0),
1345
+ reading_time: z13.int32().default(0)
1346
+ }).extend(optionalTimestampSchema.shape);
1347
+ var blogCommentSchema = z13.object({
1348
+ id: idSchema,
1349
+ blog_post_id: idSchema.optional().nullable(),
1350
+ parent_comment_id: idSchema.optional().nullable(),
1351
+ author_name: z13.string().min(1).max(100),
1352
+ author_email: emailSchema,
1353
+ author_website: z13.url().max(255).optional().nullable(),
1354
+ content: z13.string().min(1),
1355
+ is_approved: z13.boolean().default(false),
1356
+ created_at: z13.iso.datetime().optional().nullable()
1357
+ });
1358
+ var blogSettingsSchema = z13.object({
1359
+ id: idSchema,
1360
+ is_enabled: z13.boolean().default(true),
1361
+ blog_title: z13.string().max(255).default("Blog"),
1362
+ blog_description: z13.string().optional().nullable(),
1363
+ posts_per_page: z13.int32().default(10),
1364
+ allow_comments: z13.boolean().default(true),
1365
+ moderate_comments: z13.boolean().default(true),
1366
+ show_author: z13.boolean().default(true),
1367
+ show_reading_time: z13.boolean().default(true),
1368
+ enable_rss: z13.boolean().default(true),
1369
+ custom_css: z13.string().optional().nullable()
1370
+ }).extend(optionalTimestampSchema.shape);
1371
+ var blogPostCategorySchema = z13.object({
1372
+ blog_post_id: idSchema,
1373
+ blog_category_id: idSchema
1374
+ });
1375
+ var blogPostTagSchema = z13.object({
1376
+ blog_post_id: idSchema,
1377
+ blog_tag_id: idSchema
1378
+ });
1379
+ var createBlogCategorySchema = blogCategorySchema.omit({
1380
+ id: true,
1381
+ created_at: true,
1382
+ updated_at: true
1383
+ });
1384
+ var createBlogTagSchema = blogTagSchema.omit({
1385
+ id: true,
1386
+ created_at: true,
1387
+ updated_at: true
1388
+ });
1389
+ var createBlogPostSchema = blogPostSchema.omit({
1390
+ id: true,
1391
+ view_count: true,
1392
+ created_at: true,
1393
+ updated_at: true
1394
+ });
1395
+ var createBlogCommentSchema = blogCommentSchema.omit({
1396
+ id: true,
1397
+ created_at: true
1398
+ });
1399
+ var createBlogSettingsSchema = blogSettingsSchema.omit({
1400
+ id: true,
1401
+ created_at: true,
1402
+ updated_at: true
1403
+ });
1404
+ var updateBlogCategorySchema = createBlogCategorySchema.partial();
1405
+ var updateBlogTagSchema = createBlogTagSchema.partial();
1406
+ var updateBlogPostSchema = createBlogPostSchema.partial();
1407
+ var updateBlogCommentSchema = createBlogCommentSchema.partial().omit({
1408
+ blog_post_id: true
1409
+ });
1410
+ var updateBlogSettingsSchema = createBlogSettingsSchema.partial();
1411
+ var blogPostWithRelationsSchema = blogPostSchema.extend({
1412
+ blog_categories: z13.array(blogCategorySchema).optional(),
1413
+ blog_tags: z13.array(blogTagSchema).optional(),
1414
+ blog_comments: z13.array(blogCommentSchema).optional()
1415
+ });
1416
+ var blogCommentWithRepliesSchemaInner = z13.lazy(
1417
+ () => blogCommentSchema.extend({
1418
+ replies: z13.array(blogCommentWithRepliesSchemaInner).optional()
1419
+ })
1420
+ );
1421
+ var blogCommentWithRepliesSchema = blogCommentWithRepliesSchemaInner;
1422
+
1423
+ // src/types/banner.ts
1424
+ import { z as z14 } from "zod";
1425
+ var bannerSchema = z14.object({
1426
+ id: idSchema,
1427
+ title: z14.string().min(1),
1428
+ subtitle: z14.string().optional().nullable(),
1429
+ image_url: strictUrlSchema,
1430
+ link_url: urlSchema,
1431
+ button_text: z14.string().optional().nullable(),
1432
+ position: positionOrderSchema,
1433
+ is_active: z14.boolean().default(true),
1434
+ metadata: z14.any()
1435
+ }).extend(optionalTimestampSchema.shape);
1436
+ var createBannerSchema = bannerSchema.omit({
1437
+ id: true,
1438
+ created_at: true,
1439
+ updated_at: true
1440
+ });
1441
+ var updateBannerSchema = createBannerSchema.partial();
1442
+ var updateBannerPositionSchema = z14.object({
1443
+ id: idSchema,
1444
+ position: z14.int32()
1445
+ });
1446
+
1447
+ // src/types/content.ts
1448
+ import { z as z15 } from "zod";
1449
+ var contentPageSchema = z15.object({
1450
+ id: idSchema,
1451
+ title: z15.string().min(1),
1452
+ content: z15.string().optional().nullable(),
1453
+ is_published: z15.boolean().default(false),
1454
+ page_type: z15.string().optional().nullable(),
1455
+ sort_order: positionOrderSchema,
1456
+ slug: slugSchema.max(255)
1457
+ }).extend(timestampSchema.shape);
1458
+ var createContentPageSchema = contentPageSchema.omit({
1459
+ id: true,
1460
+ created_at: true,
1461
+ updated_at: true
1462
+ });
1463
+ var updateContentPageSchema = contentPageSchema.omit({
1464
+ id: true,
1465
+ created_at: true,
1466
+ updated_at: true
1467
+ }).partial();
1468
+
1469
+ // src/modules/storage/image-transform.ts
1470
+ var OBJECT_PREFIX = "/storage/v1/object/public/";
1471
+ var RENDER_PREFIX = "/storage/v1/render/image/public/";
1472
+ var DEFAULT_BUCKET = "public-cdn";
1473
+ function getEnv(key) {
1474
+ if (typeof window === "undefined") {
1475
+ return process.env[key];
1476
+ }
1477
+ return window?.process?.env?.[key] ?? void 0;
1478
+ }
1479
+ function assetBaseUrl() {
1480
+ return (getEnv("NEXT_PUBLIC_ASSET_BASE_URL") || getEnv("ASSET_BASE_URL") || "").replace(/\/$/, "");
1481
+ }
1482
+ function transformationsEnabled() {
1483
+ const flag = getEnv("NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS");
1484
+ if (typeof flag === "string" && flag !== "") {
1485
+ return ["1", "true", "yes", "on"].includes(flag.toLowerCase());
1486
+ }
1487
+ return !/localhost|127\.0\.0\.1/.test(assetBaseUrl());
1488
+ }
1489
+ function buildTransformQuery(opts) {
1490
+ if (!opts) return "";
1491
+ const params = new URLSearchParams();
1492
+ if (opts.width && Number.isFinite(opts.width))
1493
+ params.set("width", String(opts.width));
1494
+ if (opts.height && Number.isFinite(opts.height))
1495
+ params.set("height", String(opts.height));
1496
+ if (opts.resize) params.set("resize", opts.resize);
1497
+ if (opts.quality && Number.isFinite(opts.quality))
1498
+ params.set("quality", String(opts.quality));
1499
+ if (opts.format) params.set("format", opts.format);
1500
+ const qs = params.toString();
1501
+ return qs ? `?${qs}` : "";
1502
+ }
1503
+ function toRenderUrl(baseUrl, bucket, path, opts) {
1504
+ const query = buildTransformQuery({ resize: "cover", quality: 80, ...opts });
1505
+ const normalizedPath = path.replace(/^\//, "");
1506
+ return `${baseUrl.replace(/\/$/, "")}${RENDER_PREFIX}${bucket}/${normalizedPath}${query}`;
1507
+ }
1508
+ function toObjectUrl(baseUrl, bucket, path) {
1509
+ const normalizedPath = path.replace(/^\//, "");
1510
+ return `${baseUrl.replace(/\/$/, "")}${OBJECT_PREFIX}${bucket}/${normalizedPath}`;
1511
+ }
1512
+ function parseStorageUrl(url) {
1513
+ try {
1514
+ const { pathname } = new URL(url);
1515
+ const prefix = [OBJECT_PREFIX, RENDER_PREFIX].find(
1516
+ (p) => pathname.includes(p)
1517
+ );
1518
+ if (!prefix) return null;
1519
+ const parts = pathname.split(prefix)[1].split("/");
1520
+ const bucket = parts.shift();
1521
+ if (!bucket || parts.length === 0) return null;
1522
+ return { bucket, path: parts.join("/") };
1523
+ } catch {
1524
+ return null;
1525
+ }
1526
+ }
1527
+ function fromObjectPublicUrlToRender(publicUrl, opts, baseUrl = assetBaseUrl()) {
1528
+ const parsed = parseStorageUrl(publicUrl);
1529
+ if (!parsed || !baseUrl) return null;
1530
+ return toRenderUrl(baseUrl, parsed.bucket, parsed.path, opts);
1531
+ }
1532
+ function resolveAssetUrl(imagePathOrUrl, opts, bucket = DEFAULT_BUCKET, baseUrl = assetBaseUrl()) {
1533
+ if (!imagePathOrUrl) return null;
1534
+ const build = (b, p) => transformationsEnabled() ? toRenderUrl(baseUrl, b, p, opts) : toObjectUrl(baseUrl, b, p);
1535
+ if (/^https?:\/\//i.test(imagePathOrUrl)) {
1536
+ const parsed = parseStorageUrl(imagePathOrUrl);
1537
+ if (!parsed) return imagePathOrUrl;
1538
+ return baseUrl ? build(parsed.bucket, parsed.path) : imagePathOrUrl;
1539
+ }
1540
+ if (imagePathOrUrl.startsWith("/")) return imagePathOrUrl;
1541
+ return baseUrl ? build(bucket, imagePathOrUrl) : null;
1542
+ }
1543
+ function rewriteSupabaseUrl(url, opts) {
1544
+ return resolveAssetUrl(url, opts) ?? url;
1545
+ }
1546
+
1547
+ // src/core/stringify.ts
1548
+ function stringify(obj) {
1549
+ const params = new URLSearchParams();
1550
+ for (const [key, value] of Object.entries(obj)) {
1551
+ if (value === null || value === void 0) continue;
1552
+ if (Array.isArray(value)) {
1553
+ for (const item of value) {
1554
+ params.append(key, String(item));
1555
+ }
1556
+ } else {
1557
+ params.append(key, String(value));
1558
+ }
1559
+ }
1560
+ return params.toString();
1561
+ }
1562
+
1563
+ // src/modules/products/api.ts
1564
+ var ProductsApi = class {
1565
+ constructor(http) {
1566
+ this.http = http;
1567
+ }
1568
+ async getById(storeRef, productId, query) {
1569
+ const queryString = stringify(query ?? {});
1570
+ const res = await this.http.get(
1571
+ `/public/stores/${storeRef}/products/${productId}${queryString ? "?" + queryString : ""}`
1572
+ );
1573
+ return unwrapOrNull(res);
1574
+ }
1575
+ async getBySlug(storeRef, slug, query) {
1576
+ const normalizedSlug = slug.normalize("NFC");
1577
+ const encodedSlug = encodeURIComponent(normalizedSlug);
1578
+ const queryString = stringify(query ?? {});
1579
+ const res = await this.http.get(
1580
+ `/public/stores/${storeRef}/products/slug/${encodedSlug}${queryString ? "?" + queryString : ""}`
1581
+ );
1582
+ return unwrapOrNull(res);
1583
+ }
1584
+ };
1585
+
1586
+ // src/modules/collections/api.ts
1587
+ var CollectionsApi = class {
1588
+ constructor(http) {
1589
+ this.http = http;
1590
+ }
1591
+ async getAllPaginated(storeRef, params) {
1592
+ const queryString = stringify(params ?? {});
1593
+ const res = await this.http.get(
1594
+ `/public/stores/${storeRef}/collections${queryString ? "?" + queryString : ""}`
1595
+ );
1596
+ return unwrap(res);
1597
+ }
1598
+ async getAll(storeRef, ids) {
1599
+ const result = await this.getAllPaginated(storeRef, {
1600
+ ids,
1601
+ limit: ids && ids.length > 0 ? Math.min(ids.length, 100) : 100
1602
+ });
1603
+ return result.data;
1604
+ }
1605
+ async getBySlug(storeRef, slug, query) {
1606
+ const queryString = query ? stringify(query) : "";
1607
+ const res = await this.http.get(
1608
+ `/public/stores/${storeRef}/collections/slug/${slug}${queryString ? "?" + queryString : ""}`
1609
+ );
1610
+ return unwrapOrNull(res);
1611
+ }
1612
+ };
1613
+
1614
+ // src/modules/categories/api.ts
1615
+ var CategoriesApi = class {
1616
+ constructor(http) {
1617
+ this.http = http;
1618
+ }
1619
+ async getAllPaginated(storeRef, params) {
1620
+ const queryString = stringify(params ?? {});
1621
+ const res = await this.http.get(
1622
+ `/public/stores/${storeRef}/categories${queryString ? "?" + queryString : ""}`
1623
+ );
1624
+ return unwrap(res);
1625
+ }
1626
+ async getAll(storeRef, activeOnly = true) {
1627
+ const result = await this.getAllPaginated(storeRef, {
1628
+ is_active: activeOnly,
1629
+ limit: 1e3
1630
+ });
1631
+ return result.data;
1632
+ }
1633
+ async getById(storeRef, categoryId) {
1634
+ const res = await this.http.get(
1635
+ `/public/stores/${storeRef}/categories/${categoryId}`
1636
+ );
1637
+ return unwrapOrNull(res);
1638
+ }
1639
+ async getBySlug(storeRef, slug) {
1640
+ const res = await this.http.get(
1641
+ `/public/stores/${storeRef}/categories/${encodeURIComponent(slug)}`
1642
+ );
1643
+ return unwrapOrNull(res);
1644
+ }
1645
+ };
1646
+
1647
+ // src/modules/cart/api.ts
1648
+ var CartApi = class {
1649
+ constructor(publicHttp, authHttp) {
1650
+ this.publicHttp = publicHttp;
1651
+ this.authHttp = authHttp;
1652
+ }
1653
+ client(isAuth) {
1654
+ return isAuth ? this.authHttp : this.publicHttp;
1655
+ }
1656
+ basePath(isAuth) {
1657
+ return isAuth ? "stores" : "public/stores";
1658
+ }
1659
+ async getCart(storeRef, sessionId, isAuth) {
1660
+ const res = await this.client(isAuth).get(
1661
+ `/${this.basePath(isAuth)}/${storeRef}/cart`,
1662
+ { headers: { "x-session-id": sessionId } }
1663
+ );
1664
+ return unwrapOrNull(res);
1665
+ }
1666
+ async addItem(storeRef, data, sessionId, isAuth) {
1667
+ const res = await this.client(isAuth).post(`/${this.basePath(isAuth)}/${storeRef}/cart/items`, data, {
1668
+ headers: { "x-session-id": sessionId }
1669
+ });
1670
+ return unwrap(res);
1671
+ }
1672
+ async updateItem(storeRef, itemId, data, sessionId, isAuth) {
1673
+ const res = await this.client(isAuth).put(`/${this.basePath(isAuth)}/${storeRef}/cart/items/${itemId}`, data, {
1674
+ headers: { "x-session-id": sessionId }
1675
+ });
1676
+ return unwrap(res);
1677
+ }
1678
+ async removeItem(storeRef, itemId, sessionId, isAuth) {
1679
+ const res = await this.client(isAuth).delete(`/${this.basePath(isAuth)}/${storeRef}/cart/items/${itemId}`, {
1680
+ headers: { "x-session-id": sessionId }
1681
+ });
1682
+ return unwrap(res);
1683
+ }
1684
+ async clear(storeRef, sessionId, isAuth) {
1685
+ const res = await this.client(isAuth).delete(
1686
+ `/${this.basePath(isAuth)}/${storeRef}/cart`,
1687
+ { headers: { "x-session-id": sessionId } }
1688
+ );
1689
+ return unwrap(res);
1690
+ }
1691
+ async merge(storeRef, sessionId) {
1692
+ const res = await this.authHttp.post(
1693
+ `/stores/${storeRef}/cart/merge`,
1694
+ {},
1695
+ { headers: { "x-session-id": sessionId } }
1696
+ );
1697
+ return unwrap(res);
1698
+ }
1699
+ };
1700
+
1701
+ // src/modules/orders/api.ts
1702
+ var OrdersApi = class {
1703
+ constructor(publicHttp, authHttp) {
1704
+ this.publicHttp = publicHttp;
1705
+ this.authHttp = authHttp;
1706
+ }
1707
+ async lookupGuest(storeRef, params) {
1708
+ const query = stringify({
1709
+ order_code: params.order_code,
1710
+ order_number: params.order_number,
1711
+ customer_email: params.customer_email,
1712
+ customer_phone: params.customer_phone
1713
+ });
1714
+ const res = await this.publicHttp.get(
1715
+ `/public/stores/${storeRef}/orders/lookup?${query}`
1716
+ );
1717
+ return unwrap(res);
1718
+ }
1719
+ async create(storeRef, data, isAuth) {
1720
+ if (isAuth) {
1721
+ const res2 = await this.authHttp.post(
1722
+ `/tenant/stores/${storeRef}/customers/orders`,
1723
+ data
1724
+ );
1725
+ return unwrap(res2);
1726
+ }
1727
+ const res = await this.publicHttp.post(
1728
+ `/public/stores/${storeRef}/orders`,
1729
+ data
1730
+ );
1731
+ return unwrap(res);
1732
+ }
1733
+ async listCustomerOrders(storeRef, params = {}) {
1734
+ const limit = params.limit ?? 10;
1735
+ const page = params.page ?? (params.offset ? Math.floor(params.offset / limit) + 1 : 1);
1736
+ const offset = params.offset ?? (page - 1) * limit;
1737
+ const query = stringify({
1738
+ search: params.search || void 0,
1739
+ status: params.status || void 0,
1740
+ limit,
1741
+ offset,
1742
+ include_items: true,
1743
+ sort_by: params.sort_by ?? "created_at",
1744
+ sort_order: params.sort_order ?? "desc"
1745
+ });
1746
+ const res = await this.authHttp.get(
1747
+ `/tenant/stores/${storeRef}/customers/orders${query ? `?${query}` : ""}`
1748
+ );
1749
+ return unwrap(res);
1750
+ }
1751
+ /**
1752
+ * Full detail for one of the authenticated customer's orders. The API
1753
+ * verifies ownership and returns 404 — not 403 — for someone else's order.
1754
+ */
1755
+ async getCustomerOrder(storeRef, orderId) {
1756
+ const res = await this.authHttp.get(
1757
+ `/tenant/stores/${storeRef}/customers/orders/${orderId}`
1758
+ );
1759
+ return unwrap(res);
1760
+ }
1761
+ /**
1762
+ * Customers may only cancel orders that are still pending, confirmed or
1763
+ * processing; the API rejects anything else with ORDER_NOT_CANCELLABLE.
1764
+ */
1765
+ async cancelCustomerOrder(storeRef, orderId) {
1766
+ const res = await this.authHttp.delete(
1767
+ `/tenant/stores/${storeRef}/customers/orders/${orderId}`
1768
+ );
1769
+ return unwrap(res);
1770
+ }
1771
+ };
1772
+
1773
+ // src/modules/blog/api.ts
1774
+ var BlogApi = class {
1775
+ constructor(publicHttp, authHttp) {
1776
+ this.publicHttp = publicHttp;
1777
+ this.authHttp = authHttp;
1778
+ }
1779
+ async getPosts(storeRef, query = {}) {
1780
+ const qsStr = stringify(query);
1781
+ const res = await this.publicHttp.get(
1782
+ `/public/stores/${storeRef}/blog/posts${qsStr ? "?" + qsStr : ""}`
1783
+ );
1784
+ return unwrap(res);
1785
+ }
1786
+ async getPostBySlug(storeRef, slug, options = {}) {
1787
+ const query = stringify({
1788
+ increment_view: options.incrementView,
1789
+ include_seo_metadata: options.include_seo_metadata,
1790
+ include_products: options.include_products
1791
+ });
1792
+ const res = await this.publicHttp.get(
1793
+ `/public/stores/${storeRef}/blog/posts/slug/${encodeURIComponent(slug)}${query ? `?${query}` : ""}`
1794
+ );
1795
+ return unwrapOrNull(res);
1796
+ }
1797
+ async getCategories(storeRef, query = {}) {
1798
+ const qsStr = stringify(query);
1799
+ const res = await this.publicHttp.get(
1800
+ `/public/stores/${storeRef}/blog/categories${qsStr ? "?" + qsStr : ""}`
1801
+ );
1802
+ return unwrap(res);
1803
+ }
1804
+ async getTags(storeRef, query = {}) {
1805
+ const qsStr = stringify(query);
1806
+ const res = await this.publicHttp.get(
1807
+ `/public/stores/${storeRef}/blog/tags${qsStr ? "?" + qsStr : ""}`
1808
+ );
1809
+ return unwrap(res);
1810
+ }
1811
+ async getPostComments(storeRef, postId) {
1812
+ const res = await this.publicHttp.get(
1813
+ `/public/stores/${storeRef}/blog/posts/${postId}/comments`
1814
+ );
1815
+ return unwrap(res);
1816
+ }
1817
+ async getPostCommentsAuth(storeRef, postId) {
1818
+ const res = await this.authHttp.get(
1819
+ `/public/stores/${storeRef}/blog/posts/${postId}/comments`
1820
+ );
1821
+ return unwrap(res);
1822
+ }
1823
+ async submitComment(storeRef, postId, data) {
1824
+ const res = await this.authHttp.post(
1825
+ `/public/stores/${storeRef}/blog/posts/${postId}/comments`,
1826
+ data
1827
+ );
1828
+ return unwrap(res);
1829
+ }
1830
+ };
1831
+
1832
+ // src/modules/stores/api.ts
1833
+ var StoresApi = class {
1834
+ constructor(http) {
1835
+ this.http = http;
1836
+ }
1837
+ async getById(storeRef, options) {
1838
+ const params = new URLSearchParams();
1839
+ if (options?.includeConfig ?? true) params.set("include_config", "1");
1840
+ if (options?.includeSettings ?? true) params.set("include_settings", "1");
1841
+ if (options?.includeEmbeddedScripts ?? true)
1842
+ params.set("include_embedded_scripts", "1");
1843
+ const qs = params.toString();
1844
+ const res = await this.http.get(
1845
+ `/public/stores/${storeRef}${qs ? `?${qs}` : ""}`
1846
+ );
1847
+ return unwrapOrNull(res);
1848
+ }
1849
+ async getBySubdomain(subdomain) {
1850
+ const res = await this.http.get(
1851
+ `/public/stores/exists/subdomain/${subdomain}`
1852
+ );
1853
+ return unwrapOrNull(res);
1854
+ }
1855
+ async getByDomain(domain) {
1856
+ const res = await this.http.get(
1857
+ `/public/stores/domain/${domain}`
1858
+ );
1859
+ return unwrapOrNull(res);
1860
+ }
1861
+ };
1862
+
1863
+ // src/modules/search/api.ts
1864
+ var SearchApi = class {
1865
+ constructor(http) {
1866
+ this.http = http;
1867
+ }
1868
+ async searchCatalog(storeRef, params) {
1869
+ const queryString = stringify(params);
1870
+ const res = await this.http.get(
1871
+ `/public/stores/${storeRef}/search/catalog${queryString ? "?" + queryString : ""}`
1872
+ );
1873
+ return unwrap(res);
1874
+ }
1875
+ async autocompleteCatalog(storeRef, params) {
1876
+ const queryString = stringify(params);
1877
+ const res = await this.http.get(
1878
+ `/public/stores/${storeRef}/search/catalog/autocomplete${queryString ? "?" + queryString : ""}`
1879
+ );
1880
+ return unwrap(res);
1881
+ }
1882
+ async searchBlog(storeRef, params) {
1883
+ const queryString = stringify(params);
1884
+ const res = await this.http.get(
1885
+ `/public/stores/${storeRef}/search/blog${queryString ? "?" + queryString : ""}`
1886
+ );
1887
+ return unwrap(res);
1888
+ }
1889
+ };
1890
+
1891
+ // src/modules/banners/api.ts
1892
+ var BannersApi = class {
1893
+ constructor(http) {
1894
+ this.http = http;
1895
+ }
1896
+ async getPaginated(storeRef, query) {
1897
+ const queryString = stringify(query ?? {});
1898
+ const res = await this.http.get(
1899
+ `/public/stores/${storeRef}/banners${queryString ? "?" + queryString : ""}`
1900
+ );
1901
+ return unwrap(res);
1902
+ }
1903
+ };
1904
+
1905
+ // src/modules/shipping/api.ts
1906
+ var ShippingApi = class {
1907
+ constructor(http) {
1908
+ this.http = http;
1909
+ }
1910
+ /**
1911
+ * List administrative areas. Pass `level` for one tier or `parent_code`
1912
+ * for one area's children; passing neither returns every area, which for
1913
+ * Vietnam is 3,355 rows and about 900 KB. Prefer a filter.
1914
+ */
1915
+ async listLocationAreas(storeRef, query = {}) {
1916
+ const params = new URLSearchParams();
1917
+ if (query.level !== void 0) params.set("level", String(query.level));
1918
+ if (query.parent_code) params.set("parent_code", query.parent_code);
1919
+ const qs = params.toString();
1920
+ const res = await this.http.get(
1921
+ `/public/stores/${storeRef}/shipping/locations${qs ? `?${qs}` : ""}`
1922
+ );
1923
+ return unwrap(res);
1924
+ }
1925
+ async calculate(storeRef, data) {
1926
+ const res = await this.http.post(
1927
+ `/public/stores/${storeRef}/shipping/calculate`,
1928
+ data
1929
+ );
1930
+ return unwrap(res);
1931
+ }
1932
+ };
1933
+
1934
+ // src/modules/promotions/api.ts
1935
+ var PromotionsApi = class {
1936
+ constructor(http) {
1937
+ this.http = http;
1938
+ }
1939
+ async validate(storeRef, data) {
1940
+ const res = await this.http.post(
1941
+ `/public/stores/${storeRef}/promotions/validate`,
1942
+ data
1943
+ );
1944
+ return unwrap(res);
1945
+ }
1946
+ async getSuggestions(storeRef, subtotal) {
1947
+ const params = new URLSearchParams();
1948
+ if (subtotal !== void 0) params.append("subtotal", subtotal.toString());
1949
+ const res = await this.http.get(
1950
+ `/public/stores/${storeRef}/promotions/suggestions?${params.toString()}`
1951
+ );
1952
+ return unwrap(res);
1953
+ }
1954
+ };
1955
+
1956
+ // src/modules/payment-methods/api.ts
1957
+ var PaymentMethodsApi = class {
1958
+ constructor(http) {
1959
+ this.http = http;
1960
+ }
1961
+ async getEnabled(storeRef) {
1962
+ const res = await this.http.get(
1963
+ `/public/stores/${storeRef}/payment-methods`
1964
+ );
1965
+ return unwrap(res);
1966
+ }
1967
+ };
1968
+
1969
+ // src/modules/payments/api.ts
1970
+ var PaymentsApi = class {
1971
+ constructor(publicHttp, authHttp) {
1972
+ this.publicHttp = publicHttp;
1973
+ this.authHttp = authHttp;
1974
+ }
1975
+ /**
1976
+ * Start a gateway charge attempt for an order. Keyed by `order_code`,
1977
+ * never `order_id` — the API route was deliberately re-keyed away from a
1978
+ * sequential id, since StorefrontApiKeyGuard authenticates the store
1979
+ * rather than the shopper and a raw id would let anyone enumerate a
1980
+ * store's orders.
1981
+ */
1982
+ async initiate(storeRef, input) {
1983
+ const res = await this.publicHttp.post(
1984
+ `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,
1985
+ { order_code: input.order_code, provider_code: input.provider_code }
1986
+ );
1987
+ return unwrap(res);
1988
+ }
1989
+ /**
1990
+ * Poll payment/order status for an order while waiting on a gateway
1991
+ * redirect or callback. `order_code` is URL-encoded: order codes contain
1992
+ * `#` by default in this system, and an unencoded `#` truncates the URL.
1993
+ */
1994
+ async getPaymentState(storeRef, order_code) {
1995
+ const res = await this.publicHttp.get(
1996
+ `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`
1997
+ );
1998
+ return unwrap(res);
1999
+ }
2000
+ };
2001
+
2002
+ // src/modules/reviews/api.ts
2003
+ var ReviewsApi = class {
2004
+ constructor(http) {
2005
+ this.http = http;
2006
+ }
2007
+ async getProductReviews(storeRef, productId, query) {
2008
+ const queryString = stringify(query ?? {});
2009
+ const res = await this.http.get(
2010
+ `public/stores/${storeRef}/products/${productId}/reviews${queryString ? `?${queryString}` : ""}`
2011
+ );
2012
+ return unwrap(res);
2013
+ }
2014
+ async getReviewInvitation(storeRef, token) {
2015
+ const res = await this.http.get(
2016
+ `public/stores/${storeRef}/review-invitations/${token}`
2017
+ );
2018
+ return unwrap(res);
2019
+ }
2020
+ async getOrderReviewInvitations(storeRef, orderNumber, email) {
2021
+ const queryString = stringify({ order_number: orderNumber, email });
2022
+ const res = await this.http.get(
2023
+ `public/stores/${storeRef}/review-invitations/by-order?${queryString}`
2024
+ );
2025
+ return unwrap(res);
2026
+ }
2027
+ async getBatchOrderReviewInvitations(storeRef, orderNumbers, email) {
2028
+ const queryString = stringify({ order_numbers: orderNumbers.join(","), email });
2029
+ const res = await this.http.get(
2030
+ `public/stores/${storeRef}/review-invitations/by-orders?${queryString}`
2031
+ );
2032
+ return unwrap(res);
2033
+ }
2034
+ async submitReviewInvitation(storeRef, token, payload) {
2035
+ const res = await this.http.post(
2036
+ `public/stores/${storeRef}/review-invitations/${token}/submit`,
2037
+ payload
2038
+ );
2039
+ return unwrap(res);
2040
+ }
2041
+ };
2042
+
2043
+ // src/modules/customers/api.ts
2044
+ var CustomersApi = class {
2045
+ constructor(http) {
2046
+ this.http = http;
2047
+ }
2048
+ async upsertForAuth(storeRef, payload) {
2049
+ return this.http.post(
2050
+ `/stores/${storeRef}/customers/auth/upsert`,
2051
+ payload
2052
+ );
2053
+ }
2054
+ };
2055
+
2056
+ // src/modules/addresses/api.ts
2057
+ var AddressesApi = class {
2058
+ constructor(http) {
2059
+ this.http = http;
2060
+ }
2061
+ async list(storeRef) {
2062
+ const res = await this.http.get(
2063
+ `/tenant/stores/${storeRef}/customers/address`
2064
+ );
2065
+ return unwrapOrNull(res);
2066
+ }
2067
+ async getById(storeRef, addressId) {
2068
+ const res = await this.http.get(
2069
+ `/tenant/stores/${storeRef}/customers/address/${addressId}`
2070
+ );
2071
+ return unwrapOrNull(res);
2072
+ }
2073
+ async create(storeRef, data) {
2074
+ const res = await this.http.post(
2075
+ `/tenant/stores/${storeRef}/customers/address`,
2076
+ data
2077
+ );
2078
+ return unwrapOrNull(res);
2079
+ }
2080
+ async update(storeRef, addressId, data) {
2081
+ const res = await this.http.patch(
2082
+ `/tenant/stores/${storeRef}/customers/address/${addressId}`,
2083
+ data
2084
+ );
2085
+ return unwrapOrNull(res);
2086
+ }
2087
+ async delete(storeRef, addressId) {
2088
+ const res = await this.http.delete(
2089
+ `/tenant/stores/${storeRef}/customers/address/${addressId}`
2090
+ );
2091
+ return res.success;
2092
+ }
2093
+ async setDefault(storeRef, addressId) {
2094
+ const res = await this.http.patch(
2095
+ `/tenant/stores/${storeRef}/customers/address/${addressId}/set-default`
2096
+ );
2097
+ return unwrapOrNull(res);
2098
+ }
2099
+ };
2100
+
2101
+ // src/modules/content-pages/api.ts
2102
+ var ContentPagesApi = class {
2103
+ constructor(http) {
2104
+ this.http = http;
2105
+ }
2106
+ async getPublished(storeRef) {
2107
+ const res = await this.http.get(
2108
+ `/public/stores/${storeRef}/content-pages`
2109
+ );
2110
+ return unwrap(res);
2111
+ }
2112
+ async getBySlug(storeRef, slug, query) {
2113
+ const queryString = query ? stringify(query) : "";
2114
+ const res = await this.http.get(
2115
+ `/public/stores/${storeRef}/content-pages/${encodeURIComponent(slug)}${queryString ? "?" + queryString : ""}`
2116
+ );
2117
+ return unwrap(res);
2118
+ }
2119
+ };
2120
+
2121
+ // src/modules/menus/api.ts
2122
+ var MenusApi = class {
2123
+ constructor(http) {
2124
+ this.http = http;
2125
+ }
2126
+ async getByRef(storeRef, ref, includeItems = true) {
2127
+ const query = includeItems ? "?include_items=true" : "";
2128
+ const res = await this.http.get(
2129
+ `/public/stores/${storeRef}/menus/ref/${encodeURIComponent(ref)}${query}`
2130
+ );
2131
+ return unwrapOrNull(res);
2132
+ }
2133
+ };
2134
+
2135
+ // src/modules/redirects/api.ts
2136
+ var RedirectsApi = class {
2137
+ constructor(http) {
2138
+ this.http = http;
2139
+ }
2140
+ async lookup(storeRef, path) {
2141
+ const params = new URLSearchParams();
2142
+ params.set("path", path);
2143
+ const res = await this.http.get(
2144
+ `/public/stores/${storeRef}/url-redirects/lookup?${params.toString()}`
2145
+ );
2146
+ const result = unwrapOrNull(res);
2147
+ return result?.data ?? null;
2148
+ }
2149
+ };
2150
+
2151
+ // src/modules/auth/api.ts
2152
+ var AuthApi = class {
2153
+ constructor(http, storeRef) {
2154
+ this.http = http;
2155
+ this.storeRef = storeRef;
2156
+ }
2157
+ publicPath(suffix) {
2158
+ return `/public/stores/${encodeURIComponent(this.storeRef)}/auth/${suffix}`;
2159
+ }
2160
+ tenantPath(suffix) {
2161
+ return `/tenant/stores/${encodeURIComponent(this.storeRef)}/auth/${suffix}`;
2162
+ }
2163
+ auth(access_token) {
2164
+ return { headers: { Authorization: `Bearer ${access_token}` } };
2165
+ }
2166
+ // ---- unauthenticated -------------------------------------------------
2167
+ /** Never returns tokens: a new email and an existing one respond identically. */
2168
+ async register(payload) {
2169
+ return this.http.post(this.publicPath("register"), payload, void 0);
2170
+ }
2171
+ async login(payload) {
2172
+ return this.http.post(this.publicPath("login"), payload, void 0);
2173
+ }
2174
+ async refresh(refresh_token) {
2175
+ return this.http.post(
2176
+ this.publicPath("refresh"),
2177
+ { refresh_token },
2178
+ void 0
2179
+ );
2180
+ }
2181
+ async verifyEmail(token) {
2182
+ return this.http.post(
2183
+ this.publicPath("verify-email"),
2184
+ { token },
2185
+ void 0
2186
+ );
2187
+ }
2188
+ async resendVerification(email) {
2189
+ return this.http.post(
2190
+ this.publicPath("resend-verification"),
2191
+ { email },
2192
+ void 0
2193
+ );
2194
+ }
2195
+ async forgotPassword(email) {
2196
+ return this.http.post(
2197
+ this.publicPath("forgot-password"),
2198
+ { email },
2199
+ void 0
2200
+ );
2201
+ }
2202
+ async resetPassword(payload) {
2203
+ return this.http.post(
2204
+ this.publicPath("reset-password"),
2205
+ payload,
2206
+ void 0
2207
+ );
2208
+ }
2209
+ async confirmEmailChange(token) {
2210
+ return this.http.post(
2211
+ this.publicPath("change-email/confirm"),
2212
+ { token },
2213
+ void 0
2214
+ );
2215
+ }
2216
+ async requestOtp(email) {
2217
+ return this.http.post(
2218
+ this.publicPath("otp/request"),
2219
+ { email },
2220
+ void 0
2221
+ );
2222
+ }
2223
+ async verifyOtp(payload) {
2224
+ return this.http.post(
2225
+ this.publicPath("otp/verify"),
2226
+ payload,
2227
+ void 0
2228
+ );
2229
+ }
2230
+ async anonymous() {
2231
+ return this.http.post(this.publicPath("anonymous"), void 0, void 0);
2232
+ }
2233
+ async getGoogleUrl(redirect_to = "/") {
2234
+ const query = `?redirect_to=${encodeURIComponent(redirect_to)}`;
2235
+ return this.http.get(
2236
+ `${this.publicPath("google/url")}${query}`,
2237
+ void 0
2238
+ );
2239
+ }
2240
+ async exchangeGoogleCode(code) {
2241
+ return this.http.post(
2242
+ this.publicPath("google/exchange"),
2243
+ { code },
2244
+ void 0
2245
+ );
2246
+ }
2247
+ async getAuthConfig() {
2248
+ return this.http.get(this.publicPath("config"), void 0);
2249
+ }
2250
+ // ---- access token required -------------------------------------------
2251
+ async me(access_token) {
2252
+ return this.http.get(
2253
+ this.tenantPath("me"),
2254
+ this.auth(access_token)
2255
+ );
2256
+ }
2257
+ /** Revokes one session. The refresh token identifies which. */
2258
+ async logout(access_token, refresh_token) {
2259
+ return this.http.post(
2260
+ this.tenantPath("logout"),
2261
+ { refresh_token },
2262
+ this.auth(access_token)
2263
+ );
2264
+ }
2265
+ async logoutAll(access_token) {
2266
+ return this.http.post(
2267
+ this.tenantPath("logout-all"),
2268
+ void 0,
2269
+ this.auth(access_token)
2270
+ );
2271
+ }
2272
+ async changePassword(access_token, payload) {
2273
+ return this.http.post(
2274
+ this.tenantPath("change-password"),
2275
+ payload,
2276
+ this.auth(access_token)
2277
+ );
2278
+ }
2279
+ async changeEmail(access_token, payload) {
2280
+ return this.http.post(
2281
+ this.tenantPath("change-email"),
2282
+ payload,
2283
+ this.auth(access_token)
2284
+ );
2285
+ }
2286
+ };
2287
+
2288
+ // src/modules/auth/token-storage.ts
2289
+ var MemoryTokenStorage = class {
2290
+ constructor(initial = null) {
2291
+ this.tokens = initial;
2292
+ }
2293
+ async get() {
2294
+ return this.tokens;
2295
+ }
2296
+ async set(tokens) {
2297
+ this.tokens = tokens;
2298
+ }
2299
+ async clear() {
2300
+ this.tokens = null;
2301
+ }
2302
+ };
2303
+
2304
+ // src/modules/auth/refresh-client.ts
2305
+ function createAuthAwareHttpClient(inner, { storage, auth }) {
2306
+ let inFlight = null;
2307
+ async function refreshOnce() {
2308
+ if (inFlight) return inFlight;
2309
+ inFlight = (async () => {
2310
+ try {
2311
+ const current = await storage.get();
2312
+ if (!current?.refresh_token) return false;
2313
+ const response = await auth.refresh(current.refresh_token);
2314
+ const data = response.success ? response.data : null;
2315
+ if (!data?.access_token || !data.refresh_token) {
2316
+ await storage.clear();
2317
+ return false;
2318
+ }
2319
+ await storage.set({
2320
+ access_token: data.access_token,
2321
+ refresh_token: data.refresh_token
2322
+ });
2323
+ return true;
2324
+ } catch {
2325
+ await storage.clear();
2326
+ return false;
2327
+ } finally {
2328
+ inFlight = null;
2329
+ }
2330
+ })();
2331
+ return inFlight;
2332
+ }
2333
+ async function withRetry(send) {
2334
+ const first = await send();
2335
+ if (first.success || first.error?.statusCode !== 401) return first;
2336
+ const refreshed = await refreshOnce();
2337
+ if (!refreshed) return first;
2338
+ return send();
2339
+ }
2340
+ return {
2341
+ get: (url, options) => withRetry(() => inner.get(url, options)),
2342
+ post: (url, data, options) => withRetry(() => inner.post(url, data, options)),
2343
+ put: (url, data, options) => withRetry(() => inner.put(url, data, options)),
2344
+ patch: (url, data, options) => withRetry(() => inner.patch(url, data, options)),
2345
+ delete: (url, options) => withRetry(() => inner.delete(url, options))
2346
+ };
2347
+ }
2348
+
2349
+ // src/modules/collections/rule-set.ts
2350
+ var COLLECTION_RULE_MATRIX = {
2351
+ title: {
2352
+ operators: {
2353
+ equals: { value_kind: "text" }
2354
+ }
2355
+ },
2356
+ sku: {
2357
+ operators: {
2358
+ equals: { value_kind: "text" }
2359
+ }
2360
+ },
2361
+ tag: {
2362
+ operators: {
2363
+ any_of: { value_kind: "number_list" },
2364
+ all_of: { value_kind: "number_list" },
2365
+ none_of: { value_kind: "number_list" }
2366
+ }
2367
+ },
2368
+ category: {
2369
+ operators: {
2370
+ equals: { value_kind: "string" },
2371
+ not_equals: { value_kind: "string" },
2372
+ any_of: { value_kind: "string_list" },
2373
+ // Matches the category and everything beneath it. Compiles against the
2374
+ // materialized ancestor paths, so "all apparel" no longer means
2375
+ // enumerating every leaf.
2376
+ in_subtree: { value_kind: "string" }
2377
+ }
2378
+ },
2379
+ attribute: {
2380
+ operators: {
2381
+ any_of: { value_kind: "attr_token_list" },
2382
+ none_of: { value_kind: "attr_token_list" }
2383
+ }
2384
+ },
2385
+ price: {
2386
+ operators: {
2387
+ gt: { value_kind: "number" },
2388
+ gte: { value_kind: "number" },
2389
+ lt: { value_kind: "number" },
2390
+ lte: { value_kind: "number" },
2391
+ between: { value_kind: "number_pair" }
2392
+ }
2393
+ },
2394
+ rating: {
2395
+ operators: {
2396
+ gte: { value_kind: "number" },
2397
+ lte: { value_kind: "number" }
2398
+ }
2399
+ },
2400
+ stock: {
2401
+ operators: {
2402
+ is_true: { value_kind: "none" },
2403
+ is_false: { value_kind: "none" }
2404
+ }
2405
+ },
2406
+ promotion: {
2407
+ operators: {
2408
+ is_true: { value_kind: "none" },
2409
+ is_false: { value_kind: "none" }
2410
+ }
2411
+ },
2412
+ discount: {
2413
+ operators: {
2414
+ gte: { value_kind: "number" }
2415
+ }
2416
+ },
2417
+ video: {
2418
+ operators: {
2419
+ is_true: { value_kind: "none" },
2420
+ is_false: { value_kind: "none" }
2421
+ }
2422
+ },
2423
+ sales: {
2424
+ operators: {
2425
+ gte: { value_kind: "number" },
2426
+ lte: { value_kind: "number" }
2427
+ }
2428
+ },
2429
+ sales_30d: {
2430
+ operators: {
2431
+ gte: { value_kind: "number" },
2432
+ lte: { value_kind: "number" }
2433
+ }
2434
+ },
2435
+ status: {
2436
+ operators: {
2437
+ equals: { value_kind: "string" },
2438
+ not_equals: { value_kind: "string" }
2439
+ },
2440
+ allowed_values: ["active", "draft", "archived"]
2441
+ }
2442
+ };
2443
+ var RULE_FIELDS = [
2444
+ "title",
2445
+ "sku",
2446
+ "tag",
2447
+ "category",
2448
+ "attribute",
2449
+ "price",
2450
+ "rating",
2451
+ "stock",
2452
+ "promotion",
2453
+ "discount",
2454
+ "video",
2455
+ "sales",
2456
+ "sales_30d",
2457
+ "status"
2458
+ ];
2459
+ var MAX_RULES_PER_SET = 25;
2460
+ var MAX_RULE_VALUE_ENTRIES = 100;
2461
+ function isRuleField(name) {
2462
+ return Object.prototype.hasOwnProperty.call(COLLECTION_RULE_MATRIX, name);
2463
+ }
2464
+ function operatorsForField(field) {
2465
+ if (!isRuleField(field)) return [];
2466
+ return Object.keys(
2467
+ COLLECTION_RULE_MATRIX[field].operators
2468
+ );
2469
+ }
2470
+ function valueKindFor(field, op) {
2471
+ if (!isRuleField(field)) return void 0;
2472
+ const operators = COLLECTION_RULE_MATRIX[field].operators;
2473
+ return Object.prototype.hasOwnProperty.call(operators, op) ? operators[op].value_kind : void 0;
2474
+ }
2475
+ function allowedValuesFor(field) {
2476
+ if (!isRuleField(field)) return void 0;
2477
+ return COLLECTION_RULE_MATRIX[field].allowed_values;
2478
+ }
2479
+
2480
+ // src/modules/shipping/types.ts
2481
+ var LEVEL_PROVINCE = 1;
2482
+ var LEVEL_WARD = 2;
2483
+ var SHIPPING_DELIVERY_TYPES = [
2484
+ "STANDARD",
2485
+ "EXPRESS",
2486
+ "SAME_DAY",
2487
+ "ECONOMY",
2488
+ "PICKUP"
2489
+ ];
2490
+ var SHIPPING_RATE_TYPES = ["FIXED", "CARRIER_QUOTE"];
2491
+ var SHIPPING_CONDITION_TYPES = [
2492
+ "NONE",
2493
+ "ORDER_VALUE",
2494
+ "WEIGHT"
2495
+ ];
2496
+
2497
+ // src/index.ts
2498
+ function createEcomwebSdk(options) {
2499
+ const { publicHttp, authHttp } = options;
2500
+ return {
2501
+ products: new ProductsApi(publicHttp),
2502
+ collections: new CollectionsApi(publicHttp),
2503
+ categories: new CategoriesApi(publicHttp),
2504
+ cart: new CartApi(publicHttp, authHttp),
2505
+ orders: new OrdersApi(publicHttp, authHttp),
2506
+ blog: new BlogApi(publicHttp, authHttp),
2507
+ stores: new StoresApi(publicHttp),
2508
+ search: new SearchApi(publicHttp),
2509
+ banners: new BannersApi(publicHttp),
2510
+ shipping: new ShippingApi(publicHttp),
2511
+ promotions: new PromotionsApi(publicHttp),
2512
+ paymentMethods: new PaymentMethodsApi(publicHttp),
2513
+ payments: new PaymentsApi(publicHttp, authHttp),
2514
+ reviews: new ReviewsApi(publicHttp),
2515
+ customers: new CustomersApi(authHttp),
2516
+ addresses: new AddressesApi(authHttp),
2517
+ contentPages: new ContentPagesApi(publicHttp),
2518
+ menus: new MenusApi(publicHttp),
2519
+ redirects: new RedirectsApi(publicHttp)
2520
+ };
2521
+ }
2522
+ export {
2523
+ ADJUSTABLE_STATES,
2524
+ ADMIN_ORDER_SOURCES,
2525
+ AddressesApi,
2526
+ ApiClientError,
2527
+ AuthApi,
2528
+ BannersApi,
2529
+ BlogApi,
2530
+ COLLECTION_RULE_MATRIX,
2531
+ CONDITION_TYPE_LABELS,
2532
+ CartApi,
2533
+ CategoriesApi,
2534
+ CollectionsApi,
2535
+ ConditionType,
2536
+ ConditionTypeSchema,
2537
+ ContentPagesApi,
2538
+ CreatePromotionSchema,
2539
+ CustomersApi,
2540
+ DEFAULT_BUCKET,
2541
+ DISCOUNT_METHOD_LABELS,
2542
+ DiscountMethod,
2543
+ DiscountMethodSchema,
2544
+ EMAIL_COLOR_PATTERN,
2545
+ EMAIL_PALETTE_DEFAULTS,
2546
+ INVENTORY_ADJUSTMENT_REASONS,
2547
+ INVENTORY_ERROR_CODES,
2548
+ INVENTORY_POLICIES,
2549
+ INVENTORY_STATES,
2550
+ INVENTORY_STATUS_LABELS,
2551
+ InventoryStatus,
2552
+ KNOWN_PAYMENT_METHODS,
2553
+ LEGACY_STATUS_MIGRATION_MAP,
2554
+ LEVEL_PROVINCE,
2555
+ LEVEL_WARD,
2556
+ MAX_RULES_PER_SET,
2557
+ MAX_RULE_VALUE_ENTRIES,
2558
+ MERCHANT_ADJUSTMENT_REASONS,
2559
+ MemoryTokenStorage,
2560
+ MenusApi,
2561
+ OBJECT_PREFIX,
2562
+ ORDER_ACTOR_TYPES,
2563
+ ORDER_EVENT_TYPES,
2564
+ ORDER_SOURCES,
2565
+ OrdersApi,
2566
+ PAGINATION_DEFAULTS,
2567
+ PRODUCT_STATUS_LABELS,
2568
+ PROMOTION_MODE_COLORS,
2569
+ PROMOTION_MODE_LABELS,
2570
+ PROMOTION_STATUS_COLORS,
2571
+ PROMOTION_STATUS_LABELS,
2572
+ PROMOTION_TYPE_COLORS,
2573
+ PROMOTION_TYPE_LABELS,
2574
+ PaginatedPromotionsResponseSchema,
2575
+ PaymentMethodsApi,
2576
+ PaymentsApi,
2577
+ ProductStatus,
2578
+ ProductsApi,
2579
+ PromotionMode,
2580
+ PromotionModeSchema,
2581
+ PromotionQueryParamsSchema,
2582
+ PromotionSchema,
2583
+ PromotionStatisticsSchema,
2584
+ PromotionStatus,
2585
+ PromotionStatusSchema,
2586
+ PromotionType,
2587
+ PromotionTypeSchema,
2588
+ PromotionWithDiscountSchema,
2589
+ PromotionsApi,
2590
+ RENDER_PREFIX,
2591
+ RULE_FIELDS,
2592
+ RedirectsApi,
2593
+ ReviewsApi,
2594
+ SECTION_CONFIG_SCHEMAS,
2595
+ SHIPPING_CONDITION_TYPES,
2596
+ SHIPPING_DELIVERY_TYPES,
2597
+ SHIPPING_RATE_TYPES,
2598
+ SearchApi,
2599
+ ShippingApi,
2600
+ StoresApi,
2601
+ UNAVAILABLE_STATES,
2602
+ UpdatePromotionSchema,
2603
+ WIDGET_REGISTRY,
2604
+ allowedValuesFor,
2605
+ appliedPromotionSchema,
2606
+ assetBaseUrl,
2607
+ attributeLinkSchema,
2608
+ attributeLinkValueSchema,
2609
+ bannerSchema,
2610
+ baseDeleteOptionsSchema,
2611
+ baseDeleteResultSchema,
2612
+ baseQueryParamsSchema,
2613
+ blogCategorySchema,
2614
+ blogCommentSchema,
2615
+ blogCommentWithRepliesSchema,
2616
+ blogPostCategorySchema,
2617
+ blogPostSchema,
2618
+ blogPostStatusSchema,
2619
+ blogPostTagSchema,
2620
+ blogPostWithRelationsSchema,
2621
+ blogSettingsSchema,
2622
+ blogTagSchema,
2623
+ buildTransformQuery,
2624
+ builderSectionSchema,
2625
+ builderThemeConfigSchema,
2626
+ categoryGridConfigSchema,
2627
+ categorySchema,
2628
+ categoryTreeSchema,
2629
+ categoryWithChildrenSchema,
2630
+ collectionGridConfigSchema,
2631
+ colorSchema,
2632
+ contentPageSchema,
2633
+ createAuthAwareHttpClient,
2634
+ createBannerSchema,
2635
+ createBlogCategorySchema,
2636
+ createBlogCommentSchema,
2637
+ createBlogPostSchema,
2638
+ createBlogSettingsSchema,
2639
+ createBlogTagSchema,
2640
+ createCategorySchema,
2641
+ createContentPageSchema,
2642
+ createEcomwebSdk,
2643
+ createEmbeddedScriptSchema,
2644
+ createOrderItemSchema,
2645
+ createOrderSchema,
2646
+ createProductReviewReplySchema,
2647
+ createProductReviewSchema,
2648
+ createProductSchema,
2649
+ createProductVariantSchema,
2650
+ createStoreConfigSchema,
2651
+ createStoreSchema,
2652
+ createStoreSettingsSchema,
2653
+ createVariantOptionSchema,
2654
+ createVariantOptionValueSchema,
2655
+ customerOrderSummarySchema,
2656
+ decimalSchema,
2657
+ deletedAtSchema,
2658
+ dimensionsSchema,
2659
+ emailBrandingSchema,
2660
+ emailBrandingShape,
2661
+ emailSchema,
2662
+ embeddedScriptPlacementSchema,
2663
+ embeddedScriptSchema,
2664
+ ensureSuccess,
2665
+ featuredProductsConfigSchema,
2666
+ footerConfigSchema,
2667
+ fromObjectPublicUrlToRender,
2668
+ fulfillmentStatusSchema,
2669
+ headerConfigSchema,
2670
+ heroBannerConfigSchema,
2671
+ heroBannerItemSchema,
2672
+ idSchema,
2673
+ integrationStatusSchema,
2674
+ inventoryStatusSchema,
2675
+ isEditableStatus,
2676
+ isPublishableStatus,
2677
+ isRuleField,
2678
+ isUnpublishedStatus,
2679
+ jsonSchema,
2680
+ legacyOrderStatusSchema,
2681
+ legacyProductStatusSchema,
2682
+ messageOutboxStatusSchema,
2683
+ moneySchema,
2684
+ newsletterSignupConfigSchema,
2685
+ onHand,
2686
+ operatorsForField,
2687
+ optionalTimestampSchema,
2688
+ optionalUrlSchema,
2689
+ orderItemSchema,
2690
+ orderSchema,
2691
+ orderStatusSchema,
2692
+ orderWithItemsSchema,
2693
+ paginatedResponseSchema,
2694
+ paginationMetaSchema,
2695
+ paginationSchema,
2696
+ parseSectionContent,
2697
+ parseStorageUrl,
2698
+ paymentMethodSchema,
2699
+ paymentStatusSchema,
2700
+ phoneSchema,
2701
+ positionOrderSchema,
2702
+ productReviewFiltersSchema,
2703
+ productReviewReplyFiltersSchema,
2704
+ productReviewReplySchema,
2705
+ productReviewSchema,
2706
+ productReviewStatsSchema,
2707
+ productReviewWithRepliesSchema,
2708
+ productSchema,
2709
+ productStatusSchema,
2710
+ productVariantCombinationEntrySchema,
2711
+ productVariantCombinationSchema,
2712
+ productVariantSchema,
2713
+ productVariantWithCombinationsSchema,
2714
+ productWithReviewStatsSchema,
2715
+ productWithVariantsAndReviewStatsSchema,
2716
+ productWithVariantsSchema,
2717
+ resolveAssetUrl,
2718
+ reviewStatusSchema,
2719
+ rewriteSupabaseUrl,
2720
+ richTextConfigSchema,
2721
+ safeParseBaseQueryParams,
2722
+ safeParsePaginationMeta,
2723
+ sectionConfigSchema,
2724
+ sectionStyleSchema,
2725
+ sectionTypeSchema,
2726
+ shippingStatusSchema,
2727
+ slugSchema,
2728
+ sortOrderSchema,
2729
+ storeConfigSchema,
2730
+ storeIdSchema,
2731
+ storeSchema,
2732
+ storeSettingsSchema,
2733
+ storeStatusSchema,
2734
+ storeWithRelationsSchema,
2735
+ strictUrlSchema,
2736
+ textWithImageConfigSchema,
2737
+ themeConfigSchema,
2738
+ themeVersionSchema,
2739
+ timestampSchema,
2740
+ toObjectUrl,
2741
+ toRenderUrl,
2742
+ tocItemSchema,
2743
+ transformationsEnabled,
2744
+ unavailable,
2745
+ unwrap,
2746
+ unwrapOrNull,
2747
+ updateBannerPositionSchema,
2748
+ updateBannerSchema,
2749
+ updateBlogCategorySchema,
2750
+ updateBlogCommentSchema,
2751
+ updateBlogPostSchema,
2752
+ updateBlogSettingsSchema,
2753
+ updateBlogTagSchema,
2754
+ updateCategorySchema,
2755
+ updateContentPageSchema,
2756
+ updateEmbeddedScriptSchema,
2757
+ updateOrderItemSchema,
2758
+ updateOrderSchema,
2759
+ updateProductReviewReplySchema,
2760
+ updateProductReviewSchema,
2761
+ updateProductSchema,
2762
+ updateProductVariantSchema,
2763
+ updateStoreConfigSchema,
2764
+ updateStoreSchema,
2765
+ updateStoreSettingsSchema,
2766
+ updateVariantOptionSchema,
2767
+ updateVariantOptionValueSchema,
2768
+ urlSchema,
2769
+ uuidSchema,
2770
+ validatePaginationMeta,
2771
+ valueKindFor,
2772
+ variantOptionSchema,
2773
+ variantOptionValueSchema,
2774
+ variantStatusSchema
2775
+ };
2776
+ //# sourceMappingURL=index.js.map