@fayz-ai/sdk 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +20 -1
  2. package/dist/chunk-2N36RVVE.js +620 -0
  3. package/dist/chunk-2N36RVVE.js.map +1 -0
  4. package/dist/chunk-74AXXWNN.cjs +50 -0
  5. package/dist/chunk-74AXXWNN.cjs.map +1 -0
  6. package/dist/chunk-AFBFMBTK.js +45 -0
  7. package/dist/chunk-AFBFMBTK.js.map +1 -0
  8. package/dist/{chunk-REGBJXXB.cjs → chunk-MCB2L25R.cjs} +60 -2
  9. package/dist/chunk-MCB2L25R.cjs.map +1 -0
  10. package/dist/chunk-MPJDNWQY.cjs +623 -0
  11. package/dist/chunk-MPJDNWQY.cjs.map +1 -0
  12. package/dist/{chunk-O6XSRB3Q.js → chunk-R4XVCBFG.js} +60 -2
  13. package/dist/chunk-R4XVCBFG.js.map +1 -0
  14. package/dist/client.cjs +4 -4
  15. package/dist/client.d.ts +54 -0
  16. package/dist/client.d.ts.map +1 -1
  17. package/dist/client.js +1 -1
  18. package/dist/index.cjs +30 -4
  19. package/dist/index.d.ts +5 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +3 -1
  22. package/dist/release-channels.cjs +24 -0
  23. package/dist/release-channels.cjs.map +1 -0
  24. package/dist/release-channels.d.ts +10 -0
  25. package/dist/release-channels.d.ts.map +1 -0
  26. package/dist/release-channels.js +3 -0
  27. package/dist/release-channels.js.map +1 -0
  28. package/dist/shop.cjs +16 -0
  29. package/dist/shop.cjs.map +1 -0
  30. package/dist/shop.d.ts +394 -0
  31. package/dist/shop.d.ts.map +1 -0
  32. package/dist/shop.js +3 -0
  33. package/dist/shop.js.map +1 -0
  34. package/package.json +23 -10
  35. package/src/client.test.ts +135 -0
  36. package/src/client.ts +126 -0
  37. package/src/index.ts +36 -1
  38. package/src/release-channels.json +13 -0
  39. package/src/release-channels.test.ts +42 -0
  40. package/src/release-channels.ts +41 -0
  41. package/src/runtime.test.ts +4 -4
  42. package/src/shop.test.ts +114 -0
  43. package/src/shop.ts +860 -0
  44. package/dist/chunk-O6XSRB3Q.js.map +0 -1
  45. package/dist/chunk-REGBJXXB.cjs.map +0 -1
package/src/shop.ts ADDED
@@ -0,0 +1,860 @@
1
+ export interface FayzShopProviderOptions {
2
+ supabaseUrl?: string
3
+ publishableKey?: string
4
+ storeId?: string
5
+ apiBaseUrl?: string
6
+ projectId?: string
7
+ mode?: 'broker' | 'supabase'
8
+ productMetadata?: FayzShopProductMetadataOverlay[]
9
+ fetcher?: typeof fetch
10
+ }
11
+
12
+ export interface FayzShopProductMetadataOverlay {
13
+ sku?: string | null
14
+ slug?: string | null
15
+ metadata: Record<string, unknown>
16
+ }
17
+
18
+ export type FayzShopProductStatus = 'draft' | 'active' | 'archived'
19
+ export type FayzShopOrderStatus = 'open' | 'archived' | 'cancelled'
20
+ export type FayzShopFinancialStatus = 'pending' | 'paid' | 'partially_paid' | 'refunded' | 'partially_refunded' | 'voided'
21
+ export type FayzShopFulfillmentStatus = 'unfulfilled' | 'partially_fulfilled' | 'fulfilled'
22
+
23
+ export interface FayzShopListProductsOptions {
24
+ status?: FayzShopProductStatus
25
+ categoryId?: string
26
+ search?: string
27
+ slug?: string
28
+ limit?: number
29
+ offset?: number
30
+ orderBy?: 'name' | 'price' | 'created_at' | 'sort_order'
31
+ order?: 'asc' | 'desc'
32
+ }
33
+
34
+ export interface FayzShopListOrdersOptions {
35
+ status?: FayzShopOrderStatus
36
+ financialStatus?: FayzShopFinancialStatus
37
+ fulfillmentStatus?: FayzShopFulfillmentStatus
38
+ customerId?: string
39
+ customerEmail?: string
40
+ search?: string
41
+ limit?: number
42
+ offset?: number
43
+ }
44
+
45
+ export interface FayzShopListCustomersOptions {
46
+ search?: string
47
+ limit?: number
48
+ offset?: number
49
+ }
50
+
51
+ export interface FayzShopListDiscountsOptions {
52
+ status?: string
53
+ type?: string
54
+ search?: string
55
+ limit?: number
56
+ offset?: number
57
+ }
58
+
59
+ interface ProductImageRow {
60
+ id: string
61
+ product_id: string
62
+ url: string
63
+ alt_text?: string | null
64
+ sort_order?: number | null
65
+ is_primary?: boolean | null
66
+ created_at?: string | null
67
+ }
68
+
69
+ interface ProductRow {
70
+ id: string
71
+ tenant_id: string
72
+ name: string
73
+ slug?: string | null
74
+ description?: string | null
75
+ price?: number | null
76
+ compare_at_price?: number | null
77
+ currency?: string | null
78
+ status?: FayzShopProductStatus | null
79
+ inventory_count?: number | null
80
+ sku?: string | null
81
+ sort_order?: number | null
82
+ metadata?: Record<string, unknown> | null
83
+ images?: ProductImageRow[] | null
84
+ category_id?: string | null
85
+ category?: { name?: string | null } | null
86
+ is_physical?: boolean | null
87
+ weight?: number | null
88
+ weight_unit?: string | null
89
+ created_at?: string | null
90
+ updated_at?: string | null
91
+ }
92
+
93
+ interface StoreCategoryMetadata {
94
+ id?: string | null
95
+ name?: string | null
96
+ slug?: string | null
97
+ description?: string | null
98
+ imageUrl?: string | null
99
+ sortOrder?: number | null
100
+ }
101
+
102
+ interface CategoryRow {
103
+ id: string
104
+ tenant_id?: string | null
105
+ name: string
106
+ slug?: string | null
107
+ description?: string | null
108
+ parent_id?: string | null
109
+ sort_order?: number | null
110
+ image_url?: string | null
111
+ created_at?: string | null
112
+ }
113
+
114
+ interface OrderItemRow {
115
+ id: string
116
+ order_id: string
117
+ product_id?: string | null
118
+ name: string
119
+ sku?: string | null
120
+ quantity?: number | null
121
+ unit_price?: number | null
122
+ total?: number | null
123
+ image_url?: string | null
124
+ }
125
+
126
+ interface OrderRow {
127
+ id: string
128
+ tenant_id: string
129
+ order_number?: number | null
130
+ status?: FayzShopOrderStatus | null
131
+ financial_status?: FayzShopFinancialStatus | null
132
+ fulfillment_status?: FayzShopFulfillmentStatus | null
133
+ currency?: string | null
134
+ subtotal?: number | null
135
+ tax_total?: number | null
136
+ discount_total?: number | null
137
+ shipping_total?: number | null
138
+ total?: number | null
139
+ customer_id?: string | null
140
+ customer_name?: string | null
141
+ customer_email?: string | null
142
+ discount_code?: string | null
143
+ notes?: string | null
144
+ items?: OrderItemRow[] | null
145
+ created_at?: string | null
146
+ updated_at?: string | null
147
+ }
148
+
149
+ interface CustomerRow {
150
+ id: string
151
+ tenant_id: string
152
+ first_name: string
153
+ last_name?: string | null
154
+ email?: string | null
155
+ phone?: string | null
156
+ notes?: string | null
157
+ orders_count?: number | null
158
+ total_spent?: number | null
159
+ created_at?: string | null
160
+ updated_at?: string | null
161
+ }
162
+
163
+ interface DiscountRow {
164
+ id: string
165
+ tenant_id: string
166
+ title: string
167
+ code?: string | null
168
+ type: string
169
+ method?: string | null
170
+ value?: number | null
171
+ usage_limit?: number | null
172
+ once_per_customer?: boolean | null
173
+ starts_at?: string | null
174
+ ends_at?: string | null
175
+ status?: string | null
176
+ times_used?: number | null
177
+ created_at?: string | null
178
+ updated_at?: string | null
179
+ }
180
+
181
+ export class FayzShopError extends Error {
182
+ constructor(
183
+ message: string,
184
+ readonly status: number,
185
+ readonly responseBody?: unknown,
186
+ ) {
187
+ super(message)
188
+ this.name = 'FayzShopError'
189
+ }
190
+ }
191
+
192
+ function normalizeBaseUrl(url: string): string {
193
+ return url.replace(/\/+$/, '')
194
+ }
195
+
196
+ function slugify(name: string): string {
197
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
198
+ }
199
+
200
+ function nowIso(): string {
201
+ return new Date().toISOString()
202
+ }
203
+
204
+ function present<T>(value: T | null | undefined, fallback: T): T {
205
+ return value == null ? fallback : value
206
+ }
207
+
208
+ function productMetadataKey(kind: 'sku' | 'slug', value: string): string {
209
+ return `${kind}:${value.toLowerCase()}`
210
+ }
211
+
212
+ function buildProductMetadataOverlay(overlays: FayzShopProductMetadataOverlay[] | undefined) {
213
+ const map = new Map<string, Record<string, unknown>>()
214
+ for (const overlay of overlays ?? []) {
215
+ if (overlay.sku) map.set(productMetadataKey('sku', overlay.sku), overlay.metadata)
216
+ if (overlay.slug) map.set(productMetadataKey('slug', overlay.slug), overlay.metadata)
217
+ }
218
+ return map
219
+ }
220
+
221
+ function asUuid(value: string | null | undefined): string | null {
222
+ if (!value) return null
223
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
224
+ ? value
225
+ : null
226
+ }
227
+
228
+ function rowToImage(row: ProductImageRow) {
229
+ return {
230
+ id: row.id,
231
+ productId: row.product_id,
232
+ url: row.url,
233
+ altText: row.alt_text ?? null,
234
+ sortOrder: row.sort_order ?? 0,
235
+ isPrimary: row.is_primary ?? false,
236
+ createdAt: row.created_at ?? nowIso(),
237
+ }
238
+ }
239
+
240
+ function getProductMetadata(row: ProductRow, overlay?: Map<string, Record<string, unknown>>): Record<string, unknown> {
241
+ const metadata = row.metadata ?? {}
242
+ const bySlug = overlay?.get(productMetadataKey('slug', row.slug ?? slugify(row.name)))
243
+ const bySku = row.sku ? overlay?.get(productMetadataKey('sku', row.sku)) : undefined
244
+ return { ...(bySlug ?? {}), ...(bySku ?? {}), ...metadata }
245
+ }
246
+
247
+ function getStoreCategory(row: ProductRow, overlay?: Map<string, Record<string, unknown>>): StoreCategoryMetadata | null {
248
+ const raw = getProductMetadata(row, overlay).fayzStoreCategory
249
+ return raw && typeof raw === 'object' ? raw as StoreCategoryMetadata : null
250
+ }
251
+
252
+ function rowToProduct(row: ProductRow, overlay?: Map<string, Record<string, unknown>>) {
253
+ const metadata = getProductMetadata(row, overlay)
254
+ const storeCategory = getStoreCategory(row, overlay)
255
+ return {
256
+ id: row.id,
257
+ tenantId: row.tenant_id,
258
+ name: row.name,
259
+ slug: row.slug ?? slugify(row.name),
260
+ description: row.description ?? null,
261
+ price: row.price ?? 0,
262
+ compareAtPrice: row.compare_at_price ?? null,
263
+ currency: row.currency ?? 'BRL',
264
+ status: row.status ?? 'active',
265
+ inventoryCount: row.inventory_count ?? 0,
266
+ sku: row.sku ?? null,
267
+ sortOrder: row.sort_order ?? 0,
268
+ metadata,
269
+ images: Array.isArray(row.images) ? row.images.map(rowToImage) : [],
270
+ categoryId: storeCategory?.id ?? row.category_id ?? null,
271
+ categoryName: storeCategory?.name ?? row.category?.name ?? null,
272
+ isPhysical: row.is_physical ?? true,
273
+ weight: row.weight ?? null,
274
+ weightUnit: row.weight_unit ?? 'kg',
275
+ createdAt: row.created_at ?? nowIso(),
276
+ updatedAt: row.updated_at ?? row.created_at ?? nowIso(),
277
+ }
278
+ }
279
+
280
+ function rowToCategory(row: CategoryRow) {
281
+ return {
282
+ id: row.id,
283
+ tenantId: row.tenant_id ?? 'global',
284
+ name: row.name,
285
+ slug: row.slug ?? slugify(row.name),
286
+ description: row.description ?? null,
287
+ parentId: row.parent_id ?? null,
288
+ sortOrder: row.sort_order ?? 0,
289
+ imageUrl: row.image_url ?? null,
290
+ createdAt: row.created_at ?? nowIso(),
291
+ }
292
+ }
293
+
294
+ function storeCategoryToCategory(category: StoreCategoryMetadata, tenantId: string) {
295
+ const name = category.name ?? 'Category'
296
+ return {
297
+ id: category.id ?? slugify(name),
298
+ tenantId,
299
+ name,
300
+ slug: category.slug ?? slugify(name),
301
+ description: category.description ?? null,
302
+ parentId: null,
303
+ sortOrder: category.sortOrder ?? 0,
304
+ imageUrl: category.imageUrl ?? null,
305
+ createdAt: nowIso(),
306
+ }
307
+ }
308
+
309
+ function deriveStoreCategories(products: ProductRow[], tenantId: string) {
310
+ const categories = new Map<string, ReturnType<typeof storeCategoryToCategory>>()
311
+ for (const product of products) {
312
+ const category = getStoreCategory(product)
313
+ if (!category?.name && !category?.id) continue
314
+ const mapped = storeCategoryToCategory(category, tenantId)
315
+ categories.set(mapped.id, mapped)
316
+ }
317
+ return [...categories.values()].sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name))
318
+ }
319
+
320
+ function rowToOrder(row: OrderRow) {
321
+ return {
322
+ id: row.id,
323
+ tenantId: row.tenant_id,
324
+ orderNumber: row.order_number ?? 0,
325
+ status: row.status ?? 'open',
326
+ financialStatus: row.financial_status ?? 'pending',
327
+ fulfillmentStatus: row.fulfillment_status ?? 'unfulfilled',
328
+ currency: row.currency ?? 'BRL',
329
+ subtotal: row.subtotal ?? 0,
330
+ taxTotal: row.tax_total ?? 0,
331
+ discountTotal: row.discount_total ?? 0,
332
+ shippingTotal: row.shipping_total ?? 0,
333
+ total: row.total ?? 0,
334
+ customerId: row.customer_id ?? null,
335
+ customerName: row.customer_name ?? null,
336
+ customerEmail: row.customer_email ?? null,
337
+ discountCode: row.discount_code ?? null,
338
+ notes: row.notes ?? null,
339
+ items: Array.isArray(row.items) ? row.items.map(rowToOrderItem) : [],
340
+ createdAt: row.created_at ?? nowIso(),
341
+ updatedAt: row.updated_at ?? row.created_at ?? nowIso(),
342
+ }
343
+ }
344
+
345
+ function rowToOrderItem(row: OrderItemRow) {
346
+ return {
347
+ id: row.id,
348
+ orderId: row.order_id,
349
+ productId: row.product_id ?? null,
350
+ name: row.name,
351
+ sku: row.sku ?? null,
352
+ quantity: row.quantity ?? 0,
353
+ unitPrice: row.unit_price ?? 0,
354
+ total: row.total ?? 0,
355
+ imageUrl: row.image_url ?? null,
356
+ }
357
+ }
358
+
359
+ function rowToCustomer(row: CustomerRow) {
360
+ return {
361
+ id: row.id,
362
+ tenantId: row.tenant_id,
363
+ firstName: row.first_name,
364
+ lastName: row.last_name ?? '',
365
+ email: row.email ?? null,
366
+ phone: row.phone ?? null,
367
+ notes: row.notes ?? null,
368
+ ordersCount: row.orders_count ?? 0,
369
+ totalSpent: row.total_spent ?? 0,
370
+ createdAt: row.created_at ?? nowIso(),
371
+ updatedAt: row.updated_at ?? row.created_at ?? nowIso(),
372
+ }
373
+ }
374
+
375
+ function rowToDiscount(row: DiscountRow) {
376
+ return {
377
+ id: row.id,
378
+ tenantId: row.tenant_id,
379
+ title: row.title,
380
+ code: row.code ?? null,
381
+ type: row.type,
382
+ method: row.method ?? 'code',
383
+ value: row.value ?? 0,
384
+ usageLimit: row.usage_limit ?? null,
385
+ oncePerCustomer: row.once_per_customer ?? false,
386
+ startsAt: row.starts_at ?? nowIso(),
387
+ endsAt: row.ends_at ?? null,
388
+ status: row.status ?? 'active',
389
+ timesUsed: row.times_used ?? 0,
390
+ createdAt: row.created_at ?? nowIso(),
391
+ updatedAt: row.updated_at ?? row.created_at ?? nowIso(),
392
+ }
393
+ }
394
+
395
+ function updateOrderPayload(input: {
396
+ status?: FayzShopOrderStatus
397
+ financialStatus?: FayzShopFinancialStatus
398
+ fulfillmentStatus?: FayzShopFulfillmentStatus
399
+ notes?: string
400
+ }) {
401
+ const updates: Record<string, unknown> = {}
402
+ if (input.status !== undefined) updates.status = input.status
403
+ if (input.financialStatus !== undefined) updates.financial_status = input.financialStatus
404
+ if (input.fulfillmentStatus !== undefined) updates.fulfillment_status = input.fulfillmentStatus
405
+ if (input.notes !== undefined) updates.notes = input.notes
406
+ return updates
407
+ }
408
+
409
+ export function createFayzShopProvider(options: FayzShopProviderOptions) {
410
+ if (options.mode === 'broker' || options.apiBaseUrl || options.projectId) {
411
+ return createBrokerShopProvider(options)
412
+ }
413
+
414
+ if (!options.supabaseUrl || !options.publishableKey || !options.storeId) {
415
+ throw new FayzShopError('Fayz Shop provider requires either broker apiBaseUrl/projectId or legacy supabaseUrl/publishableKey/storeId.', 400)
416
+ }
417
+
418
+ const baseUrl = `${normalizeBaseUrl(options.supabaseUrl)}/rest/v1`
419
+ const fetcher = options.fetcher ?? fetch
420
+ const key = options.publishableKey
421
+ const storeId = options.storeId
422
+ const productMetadataOverlay = buildProductMetadataOverlay(options.productMetadata)
423
+
424
+ async function request<T>(table: string, init: RequestInit & { query?: URLSearchParams } = {}): Promise<T> {
425
+ const query = init.query?.toString()
426
+ const response = await fetcher(`${baseUrl}/${table}${query ? `?${query}` : ''}`, {
427
+ ...init,
428
+ headers: {
429
+ apikey: key,
430
+ Authorization: `Bearer ${key}`,
431
+ ...(init.body ? { 'Content-Type': 'application/json', Prefer: 'return=representation' } : {}),
432
+ ...init.headers,
433
+ },
434
+ })
435
+ const text = await response.text()
436
+ let body: unknown
437
+ try {
438
+ body = text ? JSON.parse(text) : undefined
439
+ } catch {
440
+ body = text
441
+ }
442
+ if (!response.ok) {
443
+ const message = typeof body === 'object' && body
444
+ ? String((body as { message?: unknown; error?: unknown }).message ?? (body as { error?: unknown }).error ?? `Fayz Shop request failed with status ${response.status}`)
445
+ : `Fayz Shop request failed with status ${response.status}`
446
+ throw new FayzShopError(message, response.status, body)
447
+ }
448
+ return body as T
449
+ }
450
+
451
+ const tenantQuery = () => {
452
+ const query = new URLSearchParams()
453
+ query.set('tenant_id', `eq.${storeId}`)
454
+ return query
455
+ }
456
+
457
+ const singleById = (id: string) => {
458
+ const query = tenantQuery()
459
+ query.set('id', `eq.${id}`)
460
+ query.set('limit', '1')
461
+ return query
462
+ }
463
+
464
+ return {
465
+ async listProducts(options?: FayzShopListProductsOptions) {
466
+ const query = tenantQuery()
467
+ query.set('select', '*,images:product_images(*),category:categories(name)')
468
+ if (options?.status) query.set('status', `eq.${options.status}`)
469
+ if (options?.slug) query.set('slug', `eq.${options.slug}`)
470
+ if (options?.search) query.set('name', `ilike.*${options.search}*`)
471
+ query.set('order', `${options?.orderBy ?? 'sort_order'}.${options?.order ?? 'asc'}`)
472
+ if (options?.limit) query.set('limit', String(options.limit))
473
+ if (options?.offset) query.set('offset', String(options.offset))
474
+ const products = (await request<ProductRow[]>('products', { query })).map((row) => rowToProduct(row, productMetadataOverlay))
475
+ return options?.categoryId ? products.filter((product) => product.categoryId === options.categoryId) : products
476
+ },
477
+ async getProduct(id: string) {
478
+ const query = singleById(id)
479
+ query.set('select', '*,images:product_images(*),category:categories(name)')
480
+ const rows = await request<ProductRow[]>('products', { query })
481
+ return rows[0] ? rowToProduct(rows[0], productMetadataOverlay) : null
482
+ },
483
+ async createProduct() {
484
+ throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)
485
+ },
486
+ async updateProduct() {
487
+ throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)
488
+ },
489
+ async deleteProduct() {
490
+ throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)
491
+ },
492
+ async uploadProductImage() {
493
+ throw new FayzShopError('Product image uploads require the Fayz admin/broker API.', 501)
494
+ },
495
+ async deleteProductImage() {
496
+ throw new FayzShopError('Product image deletes require the Fayz admin/broker API.', 501)
497
+ },
498
+ async listCategories() {
499
+ const productQuery = tenantQuery()
500
+ productQuery.set('select', 'metadata')
501
+ productQuery.set('order', 'sort_order.asc')
502
+ const products = await request<ProductRow[]>('products', { query: productQuery })
503
+ const storeCategories = deriveStoreCategories(products, storeId)
504
+ if (storeCategories.length > 0) return storeCategories
505
+
506
+ const query = new URLSearchParams()
507
+ query.set('select', '*')
508
+ query.set('order', 'sort_order.asc')
509
+ return (await request<CategoryRow[]>('categories', { query })).map(rowToCategory)
510
+ },
511
+ async createCategory() {
512
+ throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)
513
+ },
514
+ async updateCategory() {
515
+ throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)
516
+ },
517
+ async deleteCategory() {
518
+ throw new FayzShopError('Category deletes require the Fayz admin/broker API.', 501)
519
+ },
520
+ async listOrders(options?: FayzShopListOrdersOptions) {
521
+ const query = tenantQuery()
522
+ query.set('select', '*,items:order_items(*)')
523
+ if (options?.status) query.set('status', `eq.${options.status}`)
524
+ if (options?.financialStatus) query.set('financial_status', `eq.${options.financialStatus}`)
525
+ if (options?.fulfillmentStatus) query.set('fulfillment_status', `eq.${options.fulfillmentStatus}`)
526
+ if (options?.customerId) query.set('customer_id', `eq.${options.customerId}`)
527
+ if (options?.customerEmail) query.set('customer_email', `eq.${options.customerEmail}`)
528
+ if (options?.search) query.set('or', `(customer_name.ilike.*${options.search}*,customer_email.ilike.*${options.search}*)`)
529
+ query.set('order', 'created_at.desc')
530
+ if (options?.limit) query.set('limit', String(options.limit))
531
+ if (options?.offset) query.set('offset', String(options.offset))
532
+ return (await request<OrderRow[]>('orders', { query })).map(rowToOrder)
533
+ },
534
+ async getOrder(id: string) {
535
+ const query = singleById(id)
536
+ query.set('select', '*,items:order_items(*)')
537
+ const rows = await request<OrderRow[]>('orders', { query })
538
+ return rows[0] ? rowToOrder(rows[0]) : null
539
+ },
540
+ async createOrder(input: {
541
+ customerId?: string
542
+ customerName?: string
543
+ customerEmail?: string
544
+ currency?: string
545
+ notes?: string
546
+ discountCode?: string
547
+ discountTotal?: number
548
+ shippingTotal?: number
549
+ items: Array<{ productId?: string; name: string; sku?: string; quantity: number; unitPrice: number; imageUrl?: string }>
550
+ }) {
551
+ const subtotal = input.items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0)
552
+ const discountTotal = input.discountTotal ?? 0
553
+ const shippingTotal = input.shippingTotal ?? 0
554
+ const total = Math.round((subtotal - discountTotal + shippingTotal) * 100) / 100
555
+ const [order] = await request<OrderRow[]>('orders', {
556
+ method: 'POST',
557
+ body: JSON.stringify({
558
+ tenant_id: storeId,
559
+ customer_id: input.customerId ?? null,
560
+ customer_name: input.customerName ?? null,
561
+ customer_email: input.customerEmail ?? null,
562
+ currency: input.currency ?? 'BRL',
563
+ notes: input.notes ?? null,
564
+ subtotal,
565
+ discount_total: discountTotal,
566
+ shipping_total: shippingTotal,
567
+ discount_code: input.discountCode ?? null,
568
+ total,
569
+ status: 'open',
570
+ financial_status: 'pending',
571
+ fulfillment_status: 'unfulfilled',
572
+ }),
573
+ })
574
+ if (!order) throw new FayzShopError('Order insert did not return a row.', 500)
575
+ if (input.items.length) {
576
+ await request<OrderItemRow[]>('order_items', {
577
+ method: 'POST',
578
+ body: JSON.stringify(input.items.map((item) => ({
579
+ order_id: order.id,
580
+ product_id: asUuid(item.productId),
581
+ name: item.name,
582
+ sku: item.sku ?? null,
583
+ quantity: item.quantity,
584
+ unit_price: item.unitPrice,
585
+ total: item.quantity * item.unitPrice,
586
+ image_url: item.imageUrl ?? null,
587
+ }))),
588
+ })
589
+ }
590
+ return this.getOrder(order.id)
591
+ },
592
+ async updateOrder(id: string, input: Parameters<typeof updateOrderPayload>[0]) {
593
+ await request<OrderRow[]>('orders', {
594
+ method: 'PATCH',
595
+ query: singleById(id),
596
+ body: JSON.stringify(updateOrderPayload(input)),
597
+ })
598
+ return this.getOrder(id)
599
+ },
600
+ async listCustomers(options?: FayzShopListCustomersOptions) {
601
+ const query = tenantQuery()
602
+ query.set('select', '*')
603
+ query.set('order', 'first_name.asc')
604
+ if (options?.search) query.set('or', `(first_name.ilike.*${options.search}*,last_name.ilike.*${options.search}*,email.ilike.*${options.search}*)`)
605
+ if (options?.limit) query.set('limit', String(options.limit))
606
+ if (options?.offset) query.set('offset', String(options.offset))
607
+ return (await request<CustomerRow[]>('customers', { query })).map(rowToCustomer)
608
+ },
609
+ async getCustomer(id: string) {
610
+ const rows = await request<CustomerRow[]>('customers', { query: singleById(id) })
611
+ return rows[0] ? rowToCustomer(rows[0]) : null
612
+ },
613
+ async createCustomer(input: { firstName: string; lastName?: string; email?: string; phone?: string; notes?: string }) {
614
+ const [customer] = await request<CustomerRow[]>('customers', {
615
+ method: 'POST',
616
+ body: JSON.stringify({
617
+ tenant_id: storeId,
618
+ first_name: input.firstName,
619
+ last_name: input.lastName ?? '',
620
+ email: input.email ?? null,
621
+ phone: input.phone ?? null,
622
+ notes: input.notes ?? null,
623
+ }),
624
+ })
625
+ if (!customer) throw new FayzShopError('Customer insert did not return a row.', 500)
626
+ return rowToCustomer(customer)
627
+ },
628
+ async updateCustomer(id: string, input: { firstName?: string; lastName?: string; email?: string | null; phone?: string | null; notes?: string | null }) {
629
+ const updates: Record<string, unknown> = {}
630
+ if (input.firstName !== undefined) updates.first_name = input.firstName
631
+ if (input.lastName !== undefined) updates.last_name = input.lastName
632
+ if (input.email !== undefined) updates.email = input.email
633
+ if (input.phone !== undefined) updates.phone = input.phone
634
+ if (input.notes !== undefined) updates.notes = input.notes
635
+ const [customer] = await request<CustomerRow[]>('customers', {
636
+ method: 'PATCH',
637
+ query: singleById(id),
638
+ body: JSON.stringify(updates),
639
+ })
640
+ if (!customer) throw new FayzShopError('Customer update did not return a row.', 500)
641
+ return rowToCustomer(customer)
642
+ },
643
+ async deleteCustomer(id: string) {
644
+ await request<unknown>('customers', { method: 'DELETE', query: singleById(id) })
645
+ },
646
+ async listDiscounts(options?: FayzShopListDiscountsOptions) {
647
+ const query = tenantQuery()
648
+ query.set('select', '*')
649
+ query.set('order', 'created_at.desc')
650
+ if (options?.status) query.set('status', `eq.${options.status}`)
651
+ if (options?.type) query.set('type', `eq.${options.type}`)
652
+ if (options?.search) query.set('title', `ilike.*${options.search}*`)
653
+ if (options?.limit) query.set('limit', String(options.limit))
654
+ if (options?.offset) query.set('offset', String(options.offset))
655
+ return (await request<DiscountRow[]>('discounts', { query })).map(rowToDiscount)
656
+ },
657
+ async getDiscount(id: string) {
658
+ const rows = await request<DiscountRow[]>('discounts', { query: singleById(id) })
659
+ return rows[0] ? rowToDiscount(rows[0]) : null
660
+ },
661
+ async createDiscount() {
662
+ throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)
663
+ },
664
+ async updateDiscount() {
665
+ throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)
666
+ },
667
+ async deleteDiscount() {
668
+ throw new FayzShopError('Discount deletes require the Fayz admin/broker API.', 501)
669
+ },
670
+ }
671
+ }
672
+
673
+ function appendQuery(url: string, values: Record<string, string | number | undefined>): string {
674
+ const query = new URLSearchParams()
675
+ for (const [key, value] of Object.entries(values)) {
676
+ if (value !== undefined) query.set(key, String(value))
677
+ }
678
+ const serialized = query.toString()
679
+ return serialized ? `${url}?${serialized}` : url
680
+ }
681
+
682
+ function normalizeBrokerProduct(product: Record<string, unknown>, overlay?: Map<string, Record<string, unknown>>) {
683
+ const category = product.category && typeof product.category === 'object'
684
+ ? product.category as Record<string, unknown>
685
+ : null
686
+ const row = {
687
+ id: product.id as string,
688
+ tenant_id: product.tenantId as string,
689
+ name: product.name as string,
690
+ slug: product.slug as string | undefined,
691
+ description: product.description as string | null | undefined,
692
+ price: product.price as number | null | undefined,
693
+ compare_at_price: product.compareAtPrice as number | null | undefined,
694
+ currency: product.currency as string | null | undefined,
695
+ status: product.status as FayzShopProductStatus | null | undefined,
696
+ inventory_count: product.inventoryCount as number | null | undefined,
697
+ sku: product.sku as string | null | undefined,
698
+ sort_order: product.sortOrder as number | null | undefined,
699
+ metadata: product.metadata as Record<string, unknown> | null | undefined,
700
+ images: Array.isArray(product.images)
701
+ ? product.images.map((image): ProductImageRow => {
702
+ const row = image as Record<string, unknown>
703
+ return {
704
+ id: String(row.id ?? ''),
705
+ product_id: String(row.productId ?? product.id ?? ''),
706
+ url: String(row.url ?? ''),
707
+ alt_text: (row.altText as string | null | undefined) ?? null,
708
+ sort_order: (row.sortOrder as number | null | undefined) ?? 0,
709
+ is_primary: (row.isPrimary as boolean | null | undefined) ?? false,
710
+ created_at: (row.createdAt as string | null | undefined) ?? null,
711
+ }
712
+ })
713
+ : [],
714
+ category_id: (product.categoryId ?? category?.id) as string | null | undefined,
715
+ category: category ? { name: category.name as string | null | undefined } : null,
716
+ is_physical: product.isPhysical as boolean | null | undefined,
717
+ weight: product.weight as number | null | undefined,
718
+ weight_unit: product.weightUnit as string | null | undefined,
719
+ created_at: product.createdAt as string | null | undefined,
720
+ updated_at: product.updatedAt as string | null | undefined,
721
+ } satisfies ProductRow
722
+ return rowToProduct(row, overlay)
723
+ }
724
+
725
+ function normalizeBrokerCategory(category: Record<string, unknown>) {
726
+ return {
727
+ id: category.id as string,
728
+ tenantId: (category.tenantId as string | undefined) ?? 'global',
729
+ name: category.name as string,
730
+ slug: (category.slug as string | undefined) ?? slugify(category.name as string),
731
+ description: (category.description as string | null | undefined) ?? null,
732
+ parentId: (category.parentId as string | null | undefined) ?? null,
733
+ sortOrder: (category.sortOrder as number | null | undefined) ?? 0,
734
+ imageUrl: (category.imageUrl as string | null | undefined) ?? null,
735
+ createdAt: (category.createdAt as string | null | undefined) ?? nowIso(),
736
+ }
737
+ }
738
+
739
+ function createBrokerShopProvider(options: FayzShopProviderOptions) {
740
+ if (!options.apiBaseUrl || !options.projectId) {
741
+ throw new FayzShopError('Fayz Shop broker mode requires apiBaseUrl and projectId.', 400)
742
+ }
743
+
744
+ const fetcher = options.fetcher ?? fetch
745
+ const apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl)
746
+ const projectId = encodeURIComponent(options.projectId)
747
+ const productMetadataOverlay = buildProductMetadataOverlay(options.productMetadata)
748
+
749
+ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
750
+ const response = await fetcher(`${apiBaseUrl}/public/projects/${projectId}/shop${path}`, init)
751
+ const text = await response.text()
752
+ let body: unknown
753
+ try {
754
+ body = text ? JSON.parse(text) : undefined
755
+ } catch {
756
+ body = text
757
+ }
758
+ if (!response.ok) {
759
+ const message = typeof body === 'object' && body
760
+ ? String((body as { message?: unknown; error?: unknown }).message ?? (body as { error?: unknown }).error ?? `Fayz Shop broker request failed with status ${response.status}`)
761
+ : `Fayz Shop broker request failed with status ${response.status}`
762
+ throw new FayzShopError(message, response.status, body)
763
+ }
764
+ return body as T
765
+ }
766
+
767
+ return {
768
+ async listProducts(options?: FayzShopListProductsOptions) {
769
+ if (options?.slug) {
770
+ const product = await this.getProduct(options.slug)
771
+ return product ? [product] : []
772
+ }
773
+
774
+ const response = await request<{ products?: Array<Record<string, unknown>> }>(appendQuery('/products', {
775
+ status: options?.status,
776
+ categoryId: options?.categoryId,
777
+ search: options?.search,
778
+ limit: options?.limit,
779
+ offset: options?.offset,
780
+ orderBy: options?.orderBy,
781
+ order: options?.order,
782
+ }))
783
+ return (response.products ?? []).map((product) => normalizeBrokerProduct(product, productMetadataOverlay))
784
+ },
785
+ async getProduct(id: string) {
786
+ const response = await request<{ product?: Record<string, unknown> | null }>(`/products/${encodeURIComponent(id)}`)
787
+ return response.product ? normalizeBrokerProduct(response.product, productMetadataOverlay) : null
788
+ },
789
+ async createProduct() {
790
+ throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)
791
+ },
792
+ async updateProduct() {
793
+ throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)
794
+ },
795
+ async deleteProduct() {
796
+ throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)
797
+ },
798
+ async uploadProductImage() {
799
+ throw new FayzShopError('Product image uploads require the Fayz admin/broker API.', 501)
800
+ },
801
+ async deleteProductImage() {
802
+ throw new FayzShopError('Product image deletes require the Fayz admin/broker API.', 501)
803
+ },
804
+ async listCategories() {
805
+ const response = await request<{ categories?: Array<Record<string, unknown>> }>('/categories')
806
+ return (response.categories ?? []).map(normalizeBrokerCategory)
807
+ },
808
+ async createCategory() {
809
+ throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)
810
+ },
811
+ async updateCategory() {
812
+ throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)
813
+ },
814
+ async deleteCategory() {
815
+ throw new FayzShopError('Category deletes require the Fayz admin/broker API.', 501)
816
+ },
817
+ async listOrders() {
818
+ throw new FayzShopError('Order reads require the Fayz admin/broker API.', 501)
819
+ },
820
+ async getOrder() {
821
+ throw new FayzShopError('Order reads require the Fayz admin/broker API.', 501)
822
+ },
823
+ async createOrder() {
824
+ throw new FayzShopError('Order writes require the Fayz admin/broker API.', 501)
825
+ },
826
+ async updateOrder() {
827
+ throw new FayzShopError('Order writes require the Fayz admin/broker API.', 501)
828
+ },
829
+ async listCustomers() {
830
+ throw new FayzShopError('Customer reads require the Fayz admin/broker API.', 501)
831
+ },
832
+ async getCustomer() {
833
+ throw new FayzShopError('Customer reads require the Fayz admin/broker API.', 501)
834
+ },
835
+ async createCustomer() {
836
+ throw new FayzShopError('Customer writes require the Fayz admin/broker API.', 501)
837
+ },
838
+ async updateCustomer() {
839
+ throw new FayzShopError('Customer writes require the Fayz admin/broker API.', 501)
840
+ },
841
+ async deleteCustomer() {
842
+ throw new FayzShopError('Customer writes require the Fayz admin/broker API.', 501)
843
+ },
844
+ async listDiscounts() {
845
+ throw new FayzShopError('Discount reads require the Fayz admin/broker API.', 501)
846
+ },
847
+ async getDiscount() {
848
+ throw new FayzShopError('Discount reads require the Fayz admin/broker API.', 501)
849
+ },
850
+ async createDiscount() {
851
+ throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)
852
+ },
853
+ async updateDiscount() {
854
+ throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)
855
+ },
856
+ async deleteDiscount() {
857
+ throw new FayzShopError('Discount deletes require the Fayz admin/broker API.', 501)
858
+ },
859
+ }
860
+ }