@fayz-ai/sdk 0.8.1 → 0.8.3

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 (42) hide show
  1. package/dist/agent.cjs +16 -0
  2. package/dist/agent.cjs.map +1 -0
  3. package/dist/agent.d.ts +114 -0
  4. package/dist/agent.d.ts.map +1 -0
  5. package/dist/agent.js +3 -0
  6. package/dist/agent.js.map +1 -0
  7. package/dist/{chunk-3UTEZ2QL.cjs → chunk-746EA3BV.cjs} +95 -4
  8. package/dist/chunk-746EA3BV.cjs.map +1 -0
  9. package/dist/chunk-7UZH4XEV.cjs +66 -0
  10. package/dist/chunk-7UZH4XEV.cjs.map +1 -0
  11. package/dist/{chunk-PRCW5CVJ.js → chunk-7ZHG7XTA.js} +95 -5
  12. package/dist/chunk-7ZHG7XTA.js.map +1 -0
  13. package/dist/{chunk-MCB2L25R.cjs → chunk-DK3ZA6NA.cjs} +3 -3
  14. package/dist/{chunk-MCB2L25R.cjs.map → chunk-DK3ZA6NA.cjs.map} +1 -1
  15. package/dist/{chunk-ZTJ2BJ3I.js → chunk-SKARZBEH.js} +26 -26
  16. package/dist/{chunk-ZTJ2BJ3I.js.map → chunk-SKARZBEH.js.map} +1 -1
  17. package/dist/{chunk-R4XVCBFG.js → chunk-UWOQAD5A.js} +3 -3
  18. package/dist/{chunk-R4XVCBFG.js.map → chunk-UWOQAD5A.js.map} +1 -1
  19. package/dist/chunk-VPMRURSI.js +63 -0
  20. package/dist/chunk-VPMRURSI.js.map +1 -0
  21. package/dist/{chunk-6OWKU36M.cjs → chunk-WMH7SIER.cjs} +26 -26
  22. package/dist/{chunk-6OWKU36M.cjs.map → chunk-WMH7SIER.cjs.map} +1 -1
  23. package/dist/client.cjs +5 -5
  24. package/dist/client.js +2 -2
  25. package/dist/index.cjs +30 -21
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +5 -4
  29. package/dist/release-channels.cjs +5 -5
  30. package/dist/release-channels.js +1 -1
  31. package/dist/shop.cjs +7 -3
  32. package/dist/shop.d.ts +76 -0
  33. package/dist/shop.d.ts.map +1 -1
  34. package/dist/shop.js +1 -1
  35. package/package.json +7 -1
  36. package/src/agent.test.ts +114 -0
  37. package/src/agent.ts +188 -0
  38. package/src/index.ts +11 -0
  39. package/src/release-channels.json +24 -24
  40. package/src/shop.ts +174 -2
  41. package/dist/chunk-3UTEZ2QL.cjs.map +0 -1
  42. package/dist/chunk-PRCW5CVJ.js.map +0 -1
package/dist/agent.cjs ADDED
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ var chunk7UZH4XEV_cjs = require('./chunk-7UZH4XEV.cjs');
4
+
5
+
6
+
7
+ Object.defineProperty(exports, "FayzAgentError", {
8
+ enumerable: true,
9
+ get: function () { return chunk7UZH4XEV_cjs.FayzAgentError; }
10
+ });
11
+ Object.defineProperty(exports, "createFayzAgentClient", {
12
+ enumerable: true,
13
+ get: function () { return chunk7UZH4XEV_cjs.createFayzAgentClient; }
14
+ });
15
+ //# sourceMappingURL=agent.cjs.map
16
+ //# sourceMappingURL=agent.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent.cjs"}
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Client for the Fayz agent broker — the runtime surface a generated app uses
3
+ * to reach the AI agent configured for its project in Fayz.
4
+ *
5
+ * Mirrors `createFayzShopProvider`: the app holds a publishable key, Fayz holds
6
+ * the model credentials. The key ships in the bundle the same way a Supabase
7
+ * anon key does; it only ever resolves to the one agent its web channel belongs
8
+ * to, and the broker rate-limits per project.
9
+ *
10
+ * Tools are client-plane. The app declares what it can do (`tools`), the model
11
+ * decides what to call, and the app executes the calls against its own session
12
+ * before handing results back. Fayz never needs the app's data credentials.
13
+ */
14
+ export interface FayzAgentClientOptions {
15
+ /** Fayz API base, e.g. https://fayz.ai/api */
16
+ baseUrl: string;
17
+ projectId: string;
18
+ /** Publishable key of the project's WEB agent channel. */
19
+ publishableKey: string;
20
+ fetcher?: typeof fetch;
21
+ }
22
+ export interface FayzAgentTool {
23
+ name: string;
24
+ description: string;
25
+ /** JSON Schema for the tool's arguments. */
26
+ parameters?: Record<string, unknown>;
27
+ }
28
+ export interface FayzAgentToolCall {
29
+ id: string;
30
+ name: string;
31
+ arguments: Record<string, unknown>;
32
+ }
33
+ export interface FayzAgentToolResult {
34
+ toolCallId: string;
35
+ content: string;
36
+ }
37
+ export interface FayzAgentChatInput {
38
+ /** New end-user message. Omit when replying with tool results. */
39
+ message?: string;
40
+ conversationId?: string;
41
+ /** Identity of the end user, required by channels with an INTERNAL audience. */
42
+ externalUserId?: string;
43
+ /** Human label for that user, so the owner's dashboard shows a name. */
44
+ externalUserName?: string;
45
+ tools?: FayzAgentTool[];
46
+ toolResults?: FayzAgentToolResult[];
47
+ /** Decision for a server-parked write (broker PENDING_CONFIRMATION step). */
48
+ confirmAction?: {
49
+ id: string;
50
+ approved: boolean;
51
+ };
52
+ /** Runtime context the agent should know about (page, locale, tenant). */
53
+ context?: Record<string, unknown>;
54
+ signal?: AbortSignal;
55
+ }
56
+ /** A server-plane write the broker parked pending human confirmation. */
57
+ export interface FayzAgentPendingAction {
58
+ id: string;
59
+ toolName: string;
60
+ title?: string;
61
+ params?: Record<string, unknown>;
62
+ }
63
+ export interface FayzAgentChatResponse {
64
+ conversationId: string;
65
+ content: string;
66
+ toolCalls: FayzAgentToolCall[];
67
+ /** Present when the broker is waiting on a confirmAction for this write. */
68
+ pendingAction?: FayzAgentPendingAction;
69
+ }
70
+ export interface FayzAgentInfo {
71
+ id: string;
72
+ name: string;
73
+ description: string | null;
74
+ icon: string | null;
75
+ }
76
+ export declare class FayzAgentError extends Error {
77
+ readonly status: number;
78
+ constructor(message: string, status: number);
79
+ }
80
+ export interface FayzAgentConversationSummary {
81
+ id: string;
82
+ title: string | null;
83
+ /** Last activity — the field the list is ordered by. */
84
+ updatedAt: string;
85
+ }
86
+ export interface FayzAgentConversationMessage {
87
+ id: string;
88
+ role: string;
89
+ content: string;
90
+ createdAt: string;
91
+ /** Tool calls this reply made, with their results — so a resumed thread shows
92
+ * the same trace and record links it showed live. */
93
+ toolCalls?: Array<{
94
+ name: string;
95
+ arguments?: Record<string, unknown>;
96
+ result?: string;
97
+ }>;
98
+ }
99
+ export interface FayzAgentConversationDetail {
100
+ id: string;
101
+ title: string | null;
102
+ messages: FayzAgentConversationMessage[];
103
+ }
104
+ export interface FayzAgentClient {
105
+ /** Identity of the agent behind the key, for rendering its name/icon. */
106
+ getInfo(signal?: AbortSignal): Promise<FayzAgentInfo>;
107
+ chat(input: FayzAgentChatInput): Promise<FayzAgentChatResponse>;
108
+ /** The signed-in user's own threads, most-recently-active first. */
109
+ listConversations(externalUserId?: string, signal?: AbortSignal): Promise<FayzAgentConversationSummary[]>;
110
+ /** One thread with its transcript — 404s on another user's thread. */
111
+ getConversation(conversationId: string, externalUserId?: string, signal?: AbortSignal): Promise<FayzAgentConversationDetail>;
112
+ }
113
+ export declare function createFayzAgentClient(options: FayzAgentClientOptions): FayzAgentClient;
114
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,sBAAsB;IACrC,8CAA8C;IAC9C,OAAO,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,0DAA0D;IAC1D,cAAc,EAAE,MAAM,CAAA;IACtB,OAAO,CAAC,EAAE,OAAO,KAAK,CAAA;CACvB;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,EAAE,MAAM,CAAA;IACnB,4CAA4C;IAC5C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACrC;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,E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AAC,EAAE,MAAM,EACvB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,2BAA2B,CAAC,CAAA;CACxC;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,sBAAsB,GAAG,eAAe,CAuDtF"}
package/dist/agent.js ADDED
@@ -0,0 +1,3 @@
1
+ export { FayzAgentError, createFayzAgentClient } from './chunk-VPMRURSI.js';
2
+ //# sourceMappingURL=agent.js.map
3
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"agent.js"}
@@ -1,6 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  // src/shop.ts
4
+ var _accessTokenResolver = null;
5
+ function setShopAccessTokenResolver(resolver) {
6
+ _accessTokenResolver = resolver;
7
+ }
4
8
  var FayzShopError = class extends Error {
5
9
  constructor(message, status, responseBody) {
6
10
  super(message);
@@ -137,6 +141,9 @@ function rowToOrder(row) {
137
141
  customerEmail: row.customer_email ?? null,
138
142
  discountCode: row.discount_code ?? null,
139
143
  notes: row.notes ?? null,
144
+ shippingAddress: row.shipping_address ?? null,
145
+ paymentMethodKind: row.payment_method_kind ?? null,
146
+ paidAt: row.paid_at ?? null,
140
147
  items: Array.isArray(row.items) ? row.items.map(rowToOrderItem) : [],
141
148
  createdAt: row.created_at ?? nowIso(),
142
149
  updatedAt: row.updated_at ?? row.created_at ?? nowIso()
@@ -215,7 +222,15 @@ function createFayzShopProvider(options) {
215
222
  ...init,
216
223
  headers: {
217
224
  apikey: key,
218
- Authorization: `Bearer ${key}`,
225
+ // Declares which store this read is for. Until 0020 tenant isolation was
226
+ // a client-side convention (a tenant_id filter the caller could simply
227
+ // omit, returning every merchant's catalogue); the RLS policy now reads
228
+ // this header, so the scope is enforced server-side.
229
+ "x-fayz-store": storeId,
230
+ // The shopper's JWT when signed in, the publishable key otherwise. The
231
+ // apikey header stays the publishable key either way — Supabase uses it
232
+ // to route the project, not to authenticate.
233
+ Authorization: `Bearer ${_accessTokenResolver?.() || key}`,
219
234
  ...init.body ? { "Content-Type": "application/json", Prefer: "return=representation" } : {},
220
235
  ...init.headers
221
236
  }
@@ -312,7 +327,19 @@ function createFayzShopProvider(options) {
312
327
  query.set("order", "created_at.desc");
313
328
  if (options2?.limit) query.set("limit", String(options2.limit));
314
329
  if (options2?.offset) query.set("offset", String(options2.offset));
315
- return (await request("plg_shop_orders", { query })).map(rowToOrder);
330
+ try {
331
+ return (await request("plg_shop_orders", { query })).map(rowToOrder);
332
+ } catch (err) {
333
+ if (!options2?.customerId) throw err;
334
+ const rows = await request("rpc/shop_list_orders", {
335
+ method: "POST",
336
+ body: JSON.stringify({
337
+ p_customer_id: options2.customerId,
338
+ p_limit: options2.limit ?? 50
339
+ })
340
+ });
341
+ return (rows ?? []).map(rowToOrder);
342
+ }
316
343
  },
317
344
  async getOrder(id) {
318
345
  const query = singleById(id);
@@ -406,6 +433,22 @@ function createFayzShopProvider(options) {
406
433
  p_currency: input.currency ?? "BRL",
407
434
  p_discount_code: input.discountCode ?? null,
408
435
  p_shipping_total: input.shippingTotal ?? 0,
436
+ // snake_case keys on purpose: the RPC freezes this jsonb onto the
437
+ // order and public.addresses uses these exact column names.
438
+ p_shipping_address: input.shippingAddress ? {
439
+ postal_code: input.shippingAddress.postalCode,
440
+ street: input.shippingAddress.street,
441
+ number: input.shippingAddress.number ?? null,
442
+ complement: input.shippingAddress.complement ?? null,
443
+ district: input.shippingAddress.district ?? null,
444
+ city: input.shippingAddress.city,
445
+ state: input.shippingAddress.state,
446
+ country: input.shippingAddress.country ?? "BR",
447
+ recipient: input.shippingAddress.recipient ?? null,
448
+ phone: input.shippingAddress.phone ?? null,
449
+ label: input.shippingAddress.label ?? null
450
+ } : null,
451
+ p_payment_method: input.paymentMethod ?? null,
409
452
  p_notes: input.notes ?? null
410
453
  })
411
454
  });
@@ -439,6 +482,53 @@ function createFayzShopProvider(options) {
439
482
  if (!customer) throw new FayzShopError("shop_resolve_customer returned no row.", 500);
440
483
  return rowToCustomer(customer);
441
484
  },
485
+ async quoteShipping(postalCode, subtotal) {
486
+ const digits = (postalCode || "").replace(/\D/g, "");
487
+ if (digits.length !== 8) return [];
488
+ const rows = await request("rpc/shop_quote_shipping", {
489
+ method: "POST",
490
+ body: JSON.stringify({
491
+ p_tenant_id: storeId,
492
+ p_postal_code: digits,
493
+ p_subtotal: subtotal
494
+ })
495
+ });
496
+ return (rows ?? []).map((row) => ({
497
+ zoneId: row.zone_id,
498
+ name: row.name,
499
+ carrier: row.carrier ?? void 0,
500
+ rate: Number(row.rate ?? 0),
501
+ baseRate: Number(row.base_rate ?? row.rate ?? 0),
502
+ freeAbove: row.free_above == null ? null : Number(row.free_above),
503
+ etaMinDays: row.eta_min_days ?? void 0,
504
+ etaMaxDays: row.eta_max_days ?? void 0,
505
+ free: Boolean(row.free)
506
+ }));
507
+ },
508
+ async listCustomerAddresses(customerId) {
509
+ if (!asUuid(customerId)) return [];
510
+ const query = new URLSearchParams();
511
+ query.set("select", "id,label,recipient,phone,postal_code,street,number,complement,district,city,state,country,is_default");
512
+ query.set("owner_type", "eq.shop_customer");
513
+ query.set("owner_id", `eq.${customerId}`);
514
+ query.set("order", "is_default.desc,created_at.desc");
515
+ const rows = await request("addresses", { query }).catch(() => []);
516
+ return rows.map((row) => ({
517
+ id: row.id,
518
+ label: row.label ?? void 0,
519
+ recipient: row.recipient ?? void 0,
520
+ phone: row.phone ?? void 0,
521
+ postalCode: row.postal_code ?? "",
522
+ street: row.street ?? "",
523
+ number: row.number ?? void 0,
524
+ complement: row.complement ?? void 0,
525
+ district: row.district ?? void 0,
526
+ city: row.city ?? "",
527
+ state: row.state ?? "",
528
+ country: row.country ?? void 0,
529
+ isDefault: row.is_default ?? false
530
+ }));
531
+ },
442
532
  async createCustomer(input) {
443
533
  const [customer] = await request("plg_shop_customers", {
444
534
  method: "POST",
@@ -679,5 +769,6 @@ function createBrokerShopProvider(options) {
679
769
 
680
770
  exports.FayzShopError = FayzShopError;
681
771
  exports.createFayzShopProvider = createFayzShopProvider;
682
- //# sourceMappingURL=chunk-3UTEZ2QL.cjs.map
683
- //# sourceMappingURL=chunk-3UTEZ2QL.cjs.map
772
+ exports.setShopAccessTokenResolver = setShopAccessTokenResolver;
773
+ //# sourceMappingURL=chunk-746EA3BV.cjs.map
774
+ //# sourceMappingURL=chunk-746EA3BV.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shop.ts"],"names":["options","row"],"mappings":";;;AA2BA,IAAI,oBAAA,GAAmD,IAAA;AAEhD,SAAS,2BAA2B,QAAA,EAA4C;AACrF,EAAA,oBAAA,GAAuB,QAAA;AACzB;AA4MO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,OAAA,EACS,MAAA,EACA,YAAA,EACT;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHJ,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AAGT,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF;AAEA,SAAS,iBAAiB,GAAA,EAAqB;AAC7C,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC/B;AAEA,SAAS,QAAQ,IAAA,EAAsB;AACrC,EAAA,OAAO,IAAA,CAAK,aAAY,CAAE,OAAA,CAAQ,eAAe,GAAG,CAAA,CAAE,OAAA,CAAQ,QAAA,EAAU,EAAE,CAAA;AAC5E;AAEA,SAAS,MAAA,GAAiB;AACxB,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC;AAMA,SAAS,kBAAA,CAAmB,MAAsB,KAAA,EAAuB;AACvE,EAAA,OAAO,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,KAAA,CAAM,aAAa,CAAA,CAAA;AACvC;AAEA,SAAS,4BAA4B,QAAA,EAAwD;AAC3F,EAAA,MAAM,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A,CAAc,oDAAA,EAAsD,GAAG,CAAA;AAAA,IACnF,CAAA;AAAA,IACA,MAAM,cAAA,GAAiB;AACrB,MAAA,MAAM,IAAI,aAAA,CAAc,oDAAA,EAAsD,GAAG,CAAA;AAAA,IACnF,CAAA;AAAA,IACA,MAAM,cAAA,GAAiB;AACrB,MAAA,MAAM,IAAI,aAAA,CAAc,qDAAA,EAAuD,GAAG,CAAA;AAAA,IACpF;AAAA,GACF;AACF","file":"chunk-746EA3BV.cjs","sourcesContent":["export interface FayzShopProviderOptions {\n supabaseUrl?: string\n publishableKey?: string\n storeId?: string\n apiBaseUrl?: string\n projectId?: string\n mode?: 'broker' | 'supabase'\n productMetadata?: FayzShopProductMetadataOverlay[]\n fetcher?: typeof fetch\n}\n\n/**\n * The signed-in shopper's access token, when there is one.\n *\n * PostgREST decides who you are from the Authorization bearer, and this client\n * used to send the publishable key unconditionally — so every request arrived\n * as `anon` even with a customer logged in. auth.uid() was therefore always\n * null, which is why shop_resolve_customer never linked auth_user_id (0 of 519\n * customers in the pool) and why the self-read policy on public.addresses could\n * never match a row.\n *\n * A module-level resolver rather than a per-app option on purpose: the wiring\n * is done once by initStorefrontRuntime, so a storefront cannot forget it and\n * silently fall back to anonymous. Mirrors setShopTenantResolver in plugin-shop.\n */\ntype AccessTokenResolver = () => string | null | undefined\n\nlet _accessTokenResolver: AccessTokenResolver | null = null\n\nexport function setShopAccessTokenResolver(resolver: AccessTokenResolver | null): void {\n _accessTokenResolver = resolver\n}\n\nexport interface FayzShopProductMetadataOverlay {\n sku?: string | null\n slug?: string | null\n metadata: Record<string, unknown>\n}\n\nexport type FayzShopProductStatus = 'draft' | 'active' | 'archived'\nexport type FayzShopOrderStatus = 'open' | 'archived' | 'cancelled'\nexport type FayzShopFinancialStatus = 'pending' | 'paid' | 'partially_paid' | 'refunded' | 'partially_refunded' | 'voided'\nexport type FayzShopFulfillmentStatus = 'unfulfilled' | 'partially_fulfilled' | 'fulfilled'\n\nexport interface FayzShopListProductsOptions {\n status?: FayzShopProductStatus\n categoryId?: string\n search?: string\n slug?: string\n limit?: number\n offset?: number\n orderBy?: 'name' | 'price' | 'created_at' | 'sort_order'\n order?: 'asc' | 'desc'\n}\n\nexport interface FayzShopListOrdersOptions {\n status?: FayzShopOrderStatus\n financialStatus?: FayzShopFinancialStatus\n fulfillmentStatus?: FayzShopFulfillmentStatus\n customerId?: string\n customerEmail?: string\n search?: string\n limit?: number\n offset?: number\n}\n\nexport interface FayzShopListCustomersOptions {\n search?: string\n limit?: number\n offset?: number\n}\n\nexport interface FayzShopListDiscountsOptions {\n status?: string\n type?: string\n search?: string\n limit?: number\n offset?: number\n}\n\ninterface ProductImageRow {\n id: string\n product_id: string\n url: string\n alt_text?: string | null\n sort_order?: number | null\n is_primary?: boolean | null\n created_at?: string | null\n}\n\ninterface ProductRow {\n id: string\n tenant_id: string\n name: string\n slug?: string | null\n description?: string | null\n price?: number | null\n compare_at_price?: number | null\n currency?: string | null\n status?: FayzShopProductStatus | null\n inventory_count?: number | null\n sku?: string | null\n sort_order?: number | null\n metadata?: Record<string, unknown> | null\n images?: ProductImageRow[] | null\n category_id?: string | null\n category?: { name?: string | null } | null\n is_physical?: boolean | null\n weight?: number | null\n weight_unit?: string | null\n created_at?: string | null\n updated_at?: string | null\n}\n\ninterface StoreCategoryMetadata {\n id?: string | null\n name?: string | null\n slug?: string | null\n description?: string | null\n imageUrl?: string | null\n sortOrder?: number | null\n}\n\ninterface CategoryRow {\n id: string\n tenant_id?: string | null\n name: string\n slug?: string | null\n description?: string | null\n parent_id?: string | null\n sort_order?: number | null\n image_url?: string | null\n created_at?: string | null\n}\n\ninterface OrderItemRow {\n id: string\n order_id: string\n product_id?: string | null\n name: string\n sku?: string | null\n quantity?: number | null\n unit_price?: number | null\n total?: number | null\n image_url?: string | null\n}\n\ninterface OrderRow {\n id: string\n tenant_id: string\n order_number?: number | null\n status?: FayzShopOrderStatus | null\n financial_status?: FayzShopFinancialStatus | null\n fulfillment_status?: FayzShopFulfillmentStatus | null\n currency?: string | null\n subtotal?: number | null\n tax_total?: number | null\n discount_total?: number | null\n shipping_total?: number | null\n total?: number | null\n customer_id?: string | null\n customer_name?: string | null\n customer_email?: string | null\n discount_code?: string | null\n notes?: string | null\n shipping_address?: Record<string, string | undefined> | null\n payment_method_kind?: string | null\n paid_at?: string | null\n items?: OrderItemRow[] | null\n created_at?: string | null\n updated_at?: string | null\n}\n\n/** One row of shop_quote_shipping's result set. */\ninterface ShippingQuoteRow {\n zone_id: string\n name: string\n carrier: string | null\n rate: number | string | null\n base_rate: number | string | null\n free_above: number | string | null\n eta_min_days: number | null\n eta_max_days: number | null\n free: boolean | null\n}\n\n/** public.addresses, as PostgREST returns it. */\ninterface AddressRow {\n id: string\n label: string | null\n recipient: string | null\n phone: string | null\n postal_code: string | null\n street: string | null\n number: string | null\n complement: string | null\n district: string | null\n city: string | null\n state: string | null\n country: string | null\n is_default: boolean | null\n}\n\ninterface CustomerRow {\n id: string\n tenant_id: string\n first_name: string\n last_name?: string | null\n email?: string | null\n phone?: string | null\n notes?: string | null\n orders_count?: number | null\n total_spent?: number | null\n created_at?: string | null\n updated_at?: string | null\n}\n\ninterface DiscountRow {\n id: string\n tenant_id: string\n title: string\n code?: string | null\n type: string\n method?: string | null\n value?: number | null\n usage_limit?: number | null\n once_per_customer?: boolean | null\n starts_at?: string | null\n ends_at?: string | null\n status?: string | null\n times_used?: number | null\n created_at?: string | null\n updated_at?: string | null\n}\n\nexport class FayzShopError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly responseBody?: unknown,\n ) {\n super(message)\n this.name = 'FayzShopError'\n }\n}\n\nfunction normalizeBaseUrl(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\nfunction slugify(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n}\n\nfunction nowIso(): string {\n return new Date().toISOString()\n}\n\nfunction present<T>(value: T | null | undefined, fallback: T): T {\n return value == null ? fallback : value\n}\n\nfunction productMetadataKey(kind: 'sku' | 'slug', value: string): string {\n return `${kind}:${value.toLowerCase()}`\n}\n\nfunction buildProductMetadataOverlay(overlays: FayzShopProductMetadataOverlay[] | undefined) {\n const map = new Map<string, Record<string, unknown>>()\n for (const overlay of overlays ?? []) {\n if (overlay.sku) map.set(productMetadataKey('sku', overlay.sku), overlay.metadata)\n if (overlay.slug) map.set(productMetadataKey('slug', overlay.slug), overlay.metadata)\n }\n return map\n}\n\nfunction asUuid(value: string | null | undefined): string | null {\n if (!value) return null\n 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)\n ? value\n : null\n}\n\nfunction rowToImage(row: ProductImageRow) {\n return {\n id: row.id,\n productId: row.product_id,\n url: row.url,\n altText: row.alt_text ?? null,\n sortOrder: row.sort_order ?? 0,\n isPrimary: row.is_primary ?? false,\n createdAt: row.created_at ?? nowIso(),\n }\n}\n\nfunction getProductMetadata(row: ProductRow, overlay?: Map<string, Record<string, unknown>>): Record<string, unknown> {\n const metadata = row.metadata ?? {}\n const bySlug = overlay?.get(productMetadataKey('slug', row.slug ?? slugify(row.name)))\n const bySku = row.sku ? overlay?.get(productMetadataKey('sku', row.sku)) : undefined\n return { ...(bySlug ?? {}), ...(bySku ?? {}), ...metadata }\n}\n\nfunction getStoreCategory(row: ProductRow, overlay?: Map<string, Record<string, unknown>>): StoreCategoryMetadata | null {\n const raw = getProductMetadata(row, overlay).fayzStoreCategory\n return raw && typeof raw === 'object' ? raw as StoreCategoryMetadata : null\n}\n\nfunction rowToProduct(row: ProductRow, overlay?: Map<string, Record<string, unknown>>) {\n const metadata = getProductMetadata(row, overlay)\n const storeCategory = getStoreCategory(row, overlay)\n return {\n id: row.id,\n tenantId: row.tenant_id,\n name: row.name,\n slug: row.slug ?? slugify(row.name),\n description: row.description ?? null,\n price: row.price ?? 0,\n compareAtPrice: row.compare_at_price ?? null,\n currency: row.currency ?? 'BRL',\n status: row.status ?? 'active',\n inventoryCount: row.inventory_count ?? 0,\n sku: row.sku ?? null,\n sortOrder: row.sort_order ?? 0,\n metadata,\n images: Array.isArray(row.images) ? row.images.map(rowToImage) : [],\n categoryId: storeCategory?.id ?? row.category_id ?? null,\n categoryName: storeCategory?.name ?? row.category?.name ?? null,\n isPhysical: row.is_physical ?? true,\n weight: row.weight ?? null,\n weightUnit: row.weight_unit ?? 'kg',\n createdAt: row.created_at ?? nowIso(),\n updatedAt: row.updated_at ?? row.created_at ?? nowIso(),\n }\n}\n\nfunction rowToCategory(row: CategoryRow) {\n return {\n id: row.id,\n tenantId: row.tenant_id ?? 'global',\n name: row.name,\n slug: row.slug ?? slugify(row.name),\n description: row.description ?? null,\n parentId: row.parent_id ?? null,\n sortOrder: row.sort_order ?? 0,\n imageUrl: row.image_url ?? null,\n createdAt: row.created_at ?? nowIso(),\n }\n}\n\nfunction storeCategoryToCategory(category: StoreCategoryMetadata, tenantId: string) {\n const name = category.name ?? 'Category'\n return {\n id: category.id ?? slugify(name),\n tenantId,\n name,\n slug: category.slug ?? slugify(name),\n description: category.description ?? null,\n parentId: null,\n sortOrder: category.sortOrder ?? 0,\n imageUrl: category.imageUrl ?? null,\n createdAt: nowIso(),\n }\n}\n\nfunction deriveStoreCategories(products: ProductRow[], tenantId: string) {\n const categories = new Map<string, ReturnType<typeof storeCategoryToCategory>>()\n for (const product of products) {\n const category = getStoreCategory(product)\n if (!category?.name && !category?.id) continue\n const mapped = storeCategoryToCategory(category, tenantId)\n categories.set(mapped.id, mapped)\n }\n return [...categories.values()].sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name))\n}\n\nfunction rowToOrder(row: OrderRow) {\n return {\n id: row.id,\n tenantId: row.tenant_id,\n orderNumber: row.order_number ?? 0,\n status: row.status ?? 'open',\n financialStatus: row.financial_status ?? 'pending',\n fulfillmentStatus: row.fulfillment_status ?? 'unfulfilled',\n currency: row.currency ?? 'BRL',\n subtotal: row.subtotal ?? 0,\n taxTotal: row.tax_total ?? 0,\n discountTotal: row.discount_total ?? 0,\n shippingTotal: row.shipping_total ?? 0,\n total: row.total ?? 0,\n customerId: row.customer_id ?? null,\n customerName: row.customer_name ?? null,\n customerEmail: row.customer_email ?? null,\n discountCode: row.discount_code ?? null,\n notes: row.notes ?? null,\n shippingAddress: row.shipping_address ?? null,\n paymentMethodKind: row.payment_method_kind ?? null,\n paidAt: row.paid_at ?? null,\n items: Array.isArray(row.items) ? row.items.map(rowToOrderItem) : [],\n createdAt: row.created_at ?? nowIso(),\n updatedAt: row.updated_at ?? row.created_at ?? nowIso(),\n }\n}\n\nfunction rowToOrderItem(row: OrderItemRow) {\n return {\n id: row.id,\n orderId: row.order_id,\n productId: row.product_id ?? null,\n name: row.name,\n sku: row.sku ?? null,\n quantity: row.quantity ?? 0,\n unitPrice: row.unit_price ?? 0,\n total: row.total ?? 0,\n imageUrl: row.image_url ?? null,\n }\n}\n\nfunction rowToCustomer(row: CustomerRow) {\n return {\n id: row.id,\n tenantId: row.tenant_id,\n firstName: row.first_name,\n lastName: row.last_name ?? '',\n email: row.email ?? null,\n phone: row.phone ?? null,\n notes: row.notes ?? null,\n ordersCount: row.orders_count ?? 0,\n totalSpent: row.total_spent ?? 0,\n createdAt: row.created_at ?? nowIso(),\n updatedAt: row.updated_at ?? row.created_at ?? nowIso(),\n }\n}\n\nfunction rowToDiscount(row: DiscountRow) {\n return {\n id: row.id,\n tenantId: row.tenant_id,\n title: row.title,\n code: row.code ?? null,\n type: row.type,\n method: row.method ?? 'code',\n value: row.value ?? 0,\n usageLimit: row.usage_limit ?? null,\n oncePerCustomer: row.once_per_customer ?? false,\n startsAt: row.starts_at ?? nowIso(),\n endsAt: row.ends_at ?? null,\n status: row.status ?? 'active',\n timesUsed: row.times_used ?? 0,\n createdAt: row.created_at ?? nowIso(),\n updatedAt: row.updated_at ?? row.created_at ?? nowIso(),\n }\n}\n\nfunction updateOrderPayload(input: {\n status?: FayzShopOrderStatus\n financialStatus?: FayzShopFinancialStatus\n fulfillmentStatus?: FayzShopFulfillmentStatus\n notes?: string\n}) {\n const updates: Record<string, unknown> = {}\n if (input.status !== undefined) updates.status = input.status\n if (input.financialStatus !== undefined) updates.financial_status = input.financialStatus\n if (input.fulfillmentStatus !== undefined) updates.fulfillment_status = input.fulfillmentStatus\n if (input.notes !== undefined) updates.notes = input.notes\n return updates\n}\n\nexport function createFayzShopProvider(options: FayzShopProviderOptions) {\n if (options.mode === 'broker' || options.apiBaseUrl || options.projectId) {\n return createBrokerShopProvider(options)\n }\n\n if (!options.supabaseUrl || !options.publishableKey || !options.storeId) {\n throw new FayzShopError('Fayz Shop provider requires either broker apiBaseUrl/projectId or legacy supabaseUrl/publishableKey/storeId.', 400)\n }\n\n const baseUrl = `${normalizeBaseUrl(options.supabaseUrl)}/rest/v1`\n const fetcher = options.fetcher ?? fetch\n const key = options.publishableKey\n const storeId = options.storeId\n const productMetadataOverlay = buildProductMetadataOverlay(options.productMetadata)\n\n async function request<T>(table: string, init: RequestInit & { query?: URLSearchParams } = {}): Promise<T> {\n const query = init.query?.toString()\n const response = await fetcher(`${baseUrl}/${table}${query ? `?${query}` : ''}`, {\n ...init,\n headers: {\n apikey: key,\n // Declares which store this read is for. Until 0020 tenant isolation was\n // a client-side convention (a tenant_id filter the caller could simply\n // omit, returning every merchant's catalogue); the RLS policy now reads\n // this header, so the scope is enforced server-side.\n 'x-fayz-store': storeId,\n // The shopper's JWT when signed in, the publishable key otherwise. The\n // apikey header stays the publishable key either way — Supabase uses it\n // to route the project, not to authenticate.\n Authorization: `Bearer ${_accessTokenResolver?.() || key}`,\n ...(init.body ? { 'Content-Type': 'application/json', Prefer: 'return=representation' } : {}),\n ...init.headers,\n },\n })\n const text = await response.text()\n let body: unknown\n try {\n body = text ? JSON.parse(text) : undefined\n } catch {\n body = text\n }\n if (!response.ok) {\n const message = typeof body === 'object' && body\n ? String((body as { message?: unknown; error?: unknown }).message ?? (body as { error?: unknown }).error ?? `Fayz Shop request failed with status ${response.status}`)\n : `Fayz Shop request failed with status ${response.status}`\n throw new FayzShopError(message, response.status, body)\n }\n return body as T\n }\n\n const tenantQuery = () => {\n const query = new URLSearchParams()\n query.set('tenant_id', `eq.${storeId}`)\n return query\n }\n\n const singleById = (id: string) => {\n const query = tenantQuery()\n query.set('id', `eq.${id}`)\n query.set('limit', '1')\n return query\n }\n\n return {\n async listProducts(options?: FayzShopListProductsOptions) {\n const query = tenantQuery()\n query.set('select', '*,images:plg_shop_product_images(*),category:plg_shop_categories(name)')\n if (options?.status) query.set('status', `eq.${options.status}`)\n if (options?.slug) query.set('slug', `eq.${options.slug}`)\n if (options?.search) query.set('name', `ilike.*${options.search}*`)\n query.set('order', `${options?.orderBy ?? 'sort_order'}.${options?.order ?? 'asc'}`)\n if (options?.limit) query.set('limit', String(options.limit))\n if (options?.offset) query.set('offset', String(options.offset))\n const products = (await request<ProductRow[]>('plg_shop_products', { query })).map((row) => rowToProduct(row, productMetadataOverlay))\n return options?.categoryId ? products.filter((product) => product.categoryId === options.categoryId) : products\n },\n async getProduct(id: string) {\n // Cart lines can carry non-uuid ids (mock catalog, or a cart persisted in\n // an earlier mock-mode session). PostgREST would 400 on `id=eq.p-05`\n // (invalid uuid), so treat any non-uuid id as \"not found\" instead.\n if (!asUuid(id)) return null\n const query = singleById(id)\n query.set('select', '*,images:plg_shop_product_images(*),category:plg_shop_categories(name)')\n const rows = await request<ProductRow[]>('plg_shop_products', { query })\n return rows[0] ? rowToProduct(rows[0], productMetadataOverlay) : null\n },\n async createProduct() {\n throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)\n },\n async updateProduct() {\n throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)\n },\n async deleteProduct() {\n throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)\n },\n async uploadProductImage() {\n throw new FayzShopError('Product image uploads require the Fayz admin/broker API.', 501)\n },\n async deleteProductImage() {\n throw new FayzShopError('Product image deletes require the Fayz admin/broker API.', 501)\n },\n async listCategories() {\n const productQuery = tenantQuery()\n productQuery.set('select', 'metadata')\n productQuery.set('order', 'sort_order.asc')\n const products = await request<ProductRow[]>('plg_shop_products', { query: productQuery })\n const storeCategories = deriveStoreCategories(products, storeId)\n if (storeCategories.length > 0) return storeCategories\n\n const query = new URLSearchParams()\n query.set('select', '*')\n query.set('order', 'sort_order.asc')\n return (await request<CategoryRow[]>('plg_shop_categories', { query })).map(rowToCategory)\n },\n async createCategory() {\n throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)\n },\n async updateCategory() {\n throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)\n },\n async deleteCategory() {\n throw new FayzShopError('Category deletes require the Fayz admin/broker API.', 501)\n },\n async listOrders(options?: FayzShopListOrdersOptions) {\n const query = tenantQuery()\n query.set('select', '*,items:plg_shop_order_items(*)')\n if (options?.status) query.set('status', `eq.${options.status}`)\n if (options?.financialStatus) query.set('financial_status', `eq.${options.financialStatus}`)\n if (options?.fulfillmentStatus) query.set('fulfillment_status', `eq.${options.fulfillmentStatus}`)\n if (options?.customerId) query.set('customer_id', `eq.${options.customerId}`)\n if (options?.customerEmail) query.set('customer_email', `eq.${options.customerEmail}`)\n if (options?.search) query.set('or', `(customer_name.ilike.*${options.search}*,customer_email.ilike.*${options.search}*)`)\n query.set('order', 'created_at.desc')\n if (options?.limit) query.set('limit', String(options.limit))\n if (options?.offset) query.set('offset', String(options.offset))\n\n // Same shape as getOrder above: an anon storefront has no table grant, so\n // the direct read throws 401 and must fall through instead of surfacing as\n // \"you have no orders\". This is what made \"Minhas compras\" empty after a\n // guest checkout — the order was there, the read just wasn't allowed.\n try {\n return (await request<OrderRow[]>('plg_shop_orders', { query })).map(rowToOrder)\n } catch (err) {\n // Only the customer-scoped query has an RPC counterpart: shop_list_orders\n // treats the customer uuid as the read capability, exactly like\n // shop_get_order treats the order uuid. Any other filter combination has\n // no anon-safe equivalent, so the original error stands.\n if (!options?.customerId) throw err\n const rows = await request<OrderRow[]>('rpc/shop_list_orders', {\n method: 'POST',\n body: JSON.stringify({\n p_customer_id: options.customerId,\n p_limit: options.limit ?? 50,\n }),\n })\n return (rows ?? []).map(rowToOrder)\n }\n },\n async getOrder(id: string) {\n const query = singleById(id)\n query.set('select', '*,items:plg_shop_order_items(*)')\n // Anon storefronts have no table grant at all — the direct read throws\n // (401) rather than returning empty, so it must not short-circuit the\n // RPC fallback below.\n let rows: OrderRow[] = []\n try {\n rows = await request<OrderRow[]>('plg_shop_orders', { query })\n } catch {\n /* fall through to shop_get_order */\n }\n if (rows[0]) return rowToOrder(rows[0])\n // Anon storefronts can't SELECT plg_shop_orders (RLS); the order uuid acts\n // as the read capability through the whitelisted RPC.\n try {\n const row = await request<OrderRow | null>('rpc/shop_get_order', {\n method: 'POST',\n body: JSON.stringify({ p_order_id: id }),\n })\n return row ? rowToOrder(row) : null\n } catch {\n return null\n }\n },\n async confirmPayment(id: string, reference?: string) {\n // Mock/dev payment seam: anon has no UPDATE grant on plg_shop_orders,\n // so the pending->paid transition goes through the whitelisted RPC\n // (order uuid = capability, same contract as shop_get_order).\n const row = await request<OrderRow | null>('rpc/shop_confirm_payment', {\n method: 'POST',\n body: JSON.stringify({ p_order_id: id, p_reference: reference ?? null }),\n })\n return row ? rowToOrder(row) : null\n },\n async createOrder(input: {\n customerId?: string\n customerName?: string\n customerEmail?: string\n currency?: string\n notes?: string\n discountCode?: string\n discountTotal?: number\n shippingTotal?: number\n items: Array<{ productId?: string; name: string; sku?: string; quantity: number; unitPrice: number; imageUrl?: string }>\n }) {\n const subtotal = input.items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0)\n const discountTotal = input.discountTotal ?? 0\n const shippingTotal = input.shippingTotal ?? 0\n const total = Math.round((subtotal - discountTotal + shippingTotal) * 100) / 100\n const [order] = await request<OrderRow[]>('plg_shop_orders', {\n method: 'POST',\n body: JSON.stringify({\n tenant_id: storeId,\n customer_id: input.customerId ?? null,\n customer_name: input.customerName ?? null,\n customer_email: input.customerEmail ?? null,\n currency: input.currency ?? 'BRL',\n notes: input.notes ?? null,\n subtotal,\n discount_total: discountTotal,\n shipping_total: shippingTotal,\n discount_code: input.discountCode ?? null,\n total,\n status: 'open',\n financial_status: 'pending',\n fulfillment_status: 'unfulfilled',\n }),\n })\n if (!order) throw new FayzShopError('Order insert did not return a row.', 500)\n if (input.items.length) {\n await request<OrderItemRow[]>('plg_shop_order_items', {\n method: 'POST',\n body: JSON.stringify(input.items.map((item) => ({\n order_id: order.id,\n product_id: asUuid(item.productId),\n name: item.name,\n sku: item.sku ?? null,\n quantity: item.quantity,\n unit_price: item.unitPrice,\n total: item.quantity * item.unitPrice,\n image_url: item.imageUrl ?? null,\n }))),\n })\n }\n return this.getOrder(order.id)\n },\n async updateOrder(id: string, input: Parameters<typeof updateOrderPayload>[0]) {\n await request<OrderRow[]>('plg_shop_orders', {\n method: 'PATCH',\n query: singleById(id),\n body: JSON.stringify(updateOrderPayload(input)),\n })\n return this.getOrder(id)\n },\n async placeOrder(input: {\n tenantId?: string\n customerId?: string\n customer?: { name?: string; email?: string }\n currency?: string\n notes?: string\n discountCode?: string\n shippingTotal?: number\n /** Structured delivery address; frozen on the order and saved to the\n * customer's address book by the RPC. */\n shippingAddress?: {\n postalCode: string\n street: string\n number?: string\n complement?: string\n district?: string\n city: string\n state: string\n country?: string\n recipient?: string\n phone?: string\n label?: string\n }\n paymentMethod?: 'pix' | 'credit_card' | 'debit_card' | 'boleto' | 'cash' | 'other'\n items: Array<{ productId: string; quantity: number; optionsLabel?: string }>\n }) {\n // Trusted placement: the shop_place_order SECURITY DEFINER RPC re-reads\n // prices, validates discount/stock and writes order+items atomically.\n // Direct INSERTs are blocked for anon by RLS on the shared FayzApi.\n const orderId = await request<string>('rpc/shop_place_order', {\n method: 'POST',\n body: JSON.stringify({\n p_tenant_id: input.tenantId ?? storeId,\n p_items: input.items.map((line) => ({\n product_id: line.productId,\n quantity: line.quantity,\n options_label: line.optionsLabel ?? null,\n })),\n p_customer_id: asUuid(input.customerId ?? undefined),\n p_customer_name: input.customer?.name ?? null,\n p_customer_email: input.customer?.email ?? null,\n p_currency: input.currency ?? 'BRL',\n p_discount_code: input.discountCode ?? null,\n p_shipping_total: input.shippingTotal ?? 0,\n // snake_case keys on purpose: the RPC freezes this jsonb onto the\n // order and public.addresses uses these exact column names.\n p_shipping_address: input.shippingAddress\n ? {\n postal_code: input.shippingAddress.postalCode,\n street: input.shippingAddress.street,\n number: input.shippingAddress.number ?? null,\n complement: input.shippingAddress.complement ?? null,\n district: input.shippingAddress.district ?? null,\n city: input.shippingAddress.city,\n state: input.shippingAddress.state,\n country: input.shippingAddress.country ?? 'BR',\n recipient: input.shippingAddress.recipient ?? null,\n phone: input.shippingAddress.phone ?? null,\n label: input.shippingAddress.label ?? null,\n }\n : null,\n p_payment_method: input.paymentMethod ?? null,\n p_notes: input.notes ?? null,\n }),\n })\n const order = await this.getOrder(orderId)\n if (!order) throw new FayzShopError('Order was placed but could not be read back.', 500)\n return order\n },\n async listCustomers(options?: FayzShopListCustomersOptions) {\n const query = tenantQuery()\n query.set('select', '*')\n query.set('order', 'first_name.asc')\n if (options?.search) query.set('or', `(first_name.ilike.*${options.search}*,last_name.ilike.*${options.search}*,email.ilike.*${options.search}*)`)\n if (options?.limit) query.set('limit', String(options.limit))\n if (options?.offset) query.set('offset', String(options.offset))\n return (await request<CustomerRow[]>('plg_shop_customers', { query })).map(rowToCustomer)\n },\n async getCustomer(id: string) {\n const rows = await request<CustomerRow[]>('plg_shop_customers', { query: singleById(id) })\n return rows[0] ? rowToCustomer(rows[0]) : null\n },\n async resolveCustomer(input: { email: string; name?: string }) {\n const row = await request<CustomerRow | CustomerRow[]>('rpc/shop_resolve_customer', {\n method: 'POST',\n body: JSON.stringify({\n p_tenant_id: storeId,\n p_email: input.email,\n p_name: input.name ?? null,\n }),\n })\n const customer = Array.isArray(row) ? row[0] : row\n if (!customer) throw new FayzShopError('shop_resolve_customer returned no row.', 500)\n return rowToCustomer(customer)\n },\n async quoteShipping(postalCode: string, subtotal: number) {\n const digits = (postalCode || '').replace(/\\D/g, '')\n if (digits.length !== 8) return []\n const rows = await request<ShippingQuoteRow[]>('rpc/shop_quote_shipping', {\n method: 'POST',\n body: JSON.stringify({\n p_tenant_id: storeId,\n p_postal_code: digits,\n p_subtotal: subtotal,\n }),\n })\n return (rows ?? []).map((row) => ({\n zoneId: row.zone_id,\n name: row.name,\n carrier: row.carrier ?? undefined,\n rate: Number(row.rate ?? 0),\n baseRate: Number(row.base_rate ?? row.rate ?? 0),\n freeAbove: row.free_above == null ? null : Number(row.free_above),\n etaMinDays: row.eta_min_days ?? undefined,\n etaMaxDays: row.eta_max_days ?? undefined,\n free: Boolean(row.free),\n }))\n },\n async listCustomerAddresses(customerId: string) {\n if (!asUuid(customerId)) return []\n const query = new URLSearchParams()\n query.set('select', 'id,label,recipient,phone,postal_code,street,number,complement,district,city,state,country,is_default')\n query.set('owner_type', 'eq.shop_customer')\n query.set('owner_id', `eq.${customerId}`)\n query.set('order', 'is_default.desc,created_at.desc')\n // RLS (addresses_self_read) is the real filter — it matches only rows\n // whose customer is linked to auth.uid(). An anonymous or mismatched\n // caller gets [] rather than an error, so guest checkout just sees an\n // empty address book instead of a failure it cannot act on.\n const rows = await request<AddressRow[]>('addresses', { query }).catch(() => [] as AddressRow[])\n return rows.map((row) => ({\n id: row.id,\n label: row.label ?? undefined,\n recipient: row.recipient ?? undefined,\n phone: row.phone ?? undefined,\n postalCode: row.postal_code ?? '',\n street: row.street ?? '',\n number: row.number ?? undefined,\n complement: row.complement ?? undefined,\n district: row.district ?? undefined,\n city: row.city ?? '',\n state: row.state ?? '',\n country: row.country ?? undefined,\n isDefault: row.is_default ?? false,\n }))\n },\n async createCustomer(input: { firstName: string; lastName?: string; email?: string; phone?: string; notes?: string }) {\n const [customer] = await request<CustomerRow[]>('plg_shop_customers', {\n method: 'POST',\n body: JSON.stringify({\n tenant_id: storeId,\n first_name: input.firstName,\n last_name: input.lastName ?? '',\n email: input.email ?? null,\n phone: input.phone ?? null,\n notes: input.notes ?? null,\n }),\n })\n if (!customer) throw new FayzShopError('Customer insert did not return a row.', 500)\n return rowToCustomer(customer)\n },\n async updateCustomer(id: string, input: { firstName?: string; lastName?: string; email?: string | null; phone?: string | null; notes?: string | null }) {\n const updates: Record<string, unknown> = {}\n if (input.firstName !== undefined) updates.first_name = input.firstName\n if (input.lastName !== undefined) updates.last_name = input.lastName\n if (input.email !== undefined) updates.email = input.email\n if (input.phone !== undefined) updates.phone = input.phone\n if (input.notes !== undefined) updates.notes = input.notes\n const [customer] = await request<CustomerRow[]>('plg_shop_customers', {\n method: 'PATCH',\n query: singleById(id),\n body: JSON.stringify(updates),\n })\n if (!customer) throw new FayzShopError('Customer update did not return a row.', 500)\n return rowToCustomer(customer)\n },\n async deleteCustomer(id: string) {\n await request<unknown>('plg_shop_customers', { method: 'DELETE', query: singleById(id) })\n },\n async listDiscounts(options?: FayzShopListDiscountsOptions) {\n const query = tenantQuery()\n query.set('select', '*')\n query.set('order', 'created_at.desc')\n if (options?.status) query.set('status', `eq.${options.status}`)\n if (options?.type) query.set('type', `eq.${options.type}`)\n if (options?.search) query.set('title', `ilike.*${options.search}*`)\n if (options?.limit) query.set('limit', String(options.limit))\n if (options?.offset) query.set('offset', String(options.offset))\n return (await request<DiscountRow[]>('plg_shop_discounts', { query })).map(rowToDiscount)\n },\n async getDiscount(id: string) {\n const rows = await request<DiscountRow[]>('plg_shop_discounts', { query: singleById(id) })\n return rows[0] ? rowToDiscount(rows[0]) : null\n },\n async createDiscount() {\n throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)\n },\n async updateDiscount() {\n throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)\n },\n async deleteDiscount() {\n throw new FayzShopError('Discount deletes require the Fayz admin/broker API.', 501)\n },\n }\n}\n\nfunction appendQuery(url: string, values: Record<string, string | number | undefined>): string {\n const query = new URLSearchParams()\n for (const [key, value] of Object.entries(values)) {\n if (value !== undefined) query.set(key, String(value))\n }\n const serialized = query.toString()\n return serialized ? `${url}?${serialized}` : url\n}\n\nfunction normalizeBrokerProduct(product: Record<string, unknown>, overlay?: Map<string, Record<string, unknown>>) {\n const category = product.category && typeof product.category === 'object'\n ? product.category as Record<string, unknown>\n : null\n const row = {\n id: product.id as string,\n tenant_id: product.tenantId as string,\n name: product.name as string,\n slug: product.slug as string | undefined,\n description: product.description as string | null | undefined,\n price: product.price as number | null | undefined,\n compare_at_price: product.compareAtPrice as number | null | undefined,\n currency: product.currency as string | null | undefined,\n status: product.status as FayzShopProductStatus | null | undefined,\n inventory_count: product.inventoryCount as number | null | undefined,\n sku: product.sku as string | null | undefined,\n sort_order: product.sortOrder as number | null | undefined,\n metadata: product.metadata as Record<string, unknown> | null | undefined,\n images: Array.isArray(product.images)\n ? product.images.map((image): ProductImageRow => {\n const row = image as Record<string, unknown>\n return {\n id: String(row.id ?? ''),\n product_id: String(row.productId ?? product.id ?? ''),\n url: String(row.url ?? ''),\n alt_text: (row.altText as string | null | undefined) ?? null,\n sort_order: (row.sortOrder as number | null | undefined) ?? 0,\n is_primary: (row.isPrimary as boolean | null | undefined) ?? false,\n created_at: (row.createdAt as string | null | undefined) ?? null,\n }\n })\n : [],\n category_id: (product.categoryId ?? category?.id) as string | null | undefined,\n category: category ? { name: category.name as string | null | undefined } : null,\n is_physical: product.isPhysical as boolean | null | undefined,\n weight: product.weight as number | null | undefined,\n weight_unit: product.weightUnit as string | null | undefined,\n created_at: product.createdAt as string | null | undefined,\n updated_at: product.updatedAt as string | null | undefined,\n } satisfies ProductRow\n return rowToProduct(row, overlay)\n}\n\nfunction normalizeBrokerCategory(category: Record<string, unknown>) {\n return {\n id: category.id as string,\n tenantId: (category.tenantId as string | undefined) ?? 'global',\n name: category.name as string,\n slug: (category.slug as string | undefined) ?? slugify(category.name as string),\n description: (category.description as string | null | undefined) ?? null,\n parentId: (category.parentId as string | null | undefined) ?? null,\n sortOrder: (category.sortOrder as number | null | undefined) ?? 0,\n imageUrl: (category.imageUrl as string | null | undefined) ?? null,\n createdAt: (category.createdAt as string | null | undefined) ?? nowIso(),\n }\n}\n\nfunction createBrokerShopProvider(options: FayzShopProviderOptions) {\n if (!options.apiBaseUrl || !options.projectId) {\n throw new FayzShopError('Fayz Shop broker mode requires apiBaseUrl and projectId.', 400)\n }\n\n const fetcher = options.fetcher ?? fetch\n const apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl)\n const projectId = encodeURIComponent(options.projectId)\n const productMetadataOverlay = buildProductMetadataOverlay(options.productMetadata)\n\n async function request<T>(path: string, init: RequestInit = {}): Promise<T> {\n const response = await fetcher(`${apiBaseUrl}/public/projects/${projectId}/shop${path}`, init)\n const text = await response.text()\n let body: unknown\n try {\n body = text ? JSON.parse(text) : undefined\n } catch {\n body = text\n }\n if (!response.ok) {\n const message = typeof body === 'object' && body\n ? String((body as { message?: unknown; error?: unknown }).message ?? (body as { error?: unknown }).error ?? `Fayz Shop broker request failed with status ${response.status}`)\n : `Fayz Shop broker request failed with status ${response.status}`\n throw new FayzShopError(message, response.status, body)\n }\n return body as T\n }\n\n return {\n async listProducts(options?: FayzShopListProductsOptions) {\n if (options?.slug) {\n const product = await this.getProduct(options.slug)\n return product ? [product] : []\n }\n\n const response = await request<{ products?: Array<Record<string, unknown>> }>(appendQuery('/products', {\n status: options?.status,\n categoryId: options?.categoryId,\n search: options?.search,\n limit: options?.limit,\n offset: options?.offset,\n orderBy: options?.orderBy,\n order: options?.order,\n }))\n return (response.products ?? []).map((product) => normalizeBrokerProduct(product, productMetadataOverlay))\n },\n async getProduct(id: string) {\n const response = await request<{ product?: Record<string, unknown> | null }>(`/products/${encodeURIComponent(id)}`)\n return response.product ? normalizeBrokerProduct(response.product, productMetadataOverlay) : null\n },\n async createProduct() {\n throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)\n },\n async updateProduct() {\n throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)\n },\n async deleteProduct() {\n throw new FayzShopError('Product writes require the Fayz admin/broker API.', 501)\n },\n async uploadProductImage() {\n throw new FayzShopError('Product image uploads require the Fayz admin/broker API.', 501)\n },\n async deleteProductImage() {\n throw new FayzShopError('Product image deletes require the Fayz admin/broker API.', 501)\n },\n async listCategories() {\n const response = await request<{ categories?: Array<Record<string, unknown>> }>('/categories')\n return (response.categories ?? []).map(normalizeBrokerCategory)\n },\n async createCategory() {\n throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)\n },\n async updateCategory() {\n throw new FayzShopError('Category writes require the Fayz admin/broker API.', 501)\n },\n async deleteCategory() {\n throw new FayzShopError('Category deletes require the Fayz admin/broker API.', 501)\n },\n async listOrders() {\n throw new FayzShopError('Order reads require the Fayz admin/broker API.', 501)\n },\n async getOrder() {\n throw new FayzShopError('Order reads require the Fayz admin/broker API.', 501)\n },\n async createOrder() {\n throw new FayzShopError('Order writes require the Fayz admin/broker API.', 501)\n },\n async updateOrder() {\n throw new FayzShopError('Order writes require the Fayz admin/broker API.', 501)\n },\n async placeOrder() {\n throw new FayzShopError('Order placement requires the Fayz admin/broker API.', 501)\n },\n async listCustomers() {\n throw new FayzShopError('Customer reads require the Fayz admin/broker API.', 501)\n },\n async getCustomer() {\n throw new FayzShopError('Customer reads require the Fayz admin/broker API.', 501)\n },\n async createCustomer() {\n throw new FayzShopError('Customer writes require the Fayz admin/broker API.', 501)\n },\n async updateCustomer() {\n throw new FayzShopError('Customer writes require the Fayz admin/broker API.', 501)\n },\n async deleteCustomer() {\n throw new FayzShopError('Customer writes require the Fayz admin/broker API.', 501)\n },\n async listDiscounts() {\n throw new FayzShopError('Discount reads require the Fayz admin/broker API.', 501)\n },\n async getDiscount() {\n throw new FayzShopError('Discount reads require the Fayz admin/broker API.', 501)\n },\n async createDiscount() {\n throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)\n },\n async updateDiscount() {\n throw new FayzShopError('Discount writes require the Fayz admin/broker API.', 501)\n },\n async deleteDiscount() {\n throw new FayzShopError('Discount deletes require the Fayz admin/broker API.', 501)\n },\n }\n}\n"]}
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ // src/agent.ts
4
+ var FayzAgentError = class extends Error {
5
+ constructor(message, status) {
6
+ super(message);
7
+ this.status = status;
8
+ this.name = "FayzAgentError";
9
+ }
10
+ };
11
+ function createFayzAgentClient(options) {
12
+ const fetcher = options.fetcher ?? globalThis.fetch;
13
+ const base = `${options.baseUrl.replace(/\/+$/, "")}/public/projects/${options.projectId}/agents`;
14
+ const headers = {
15
+ "Content-Type": "application/json",
16
+ "x-fayz-agent-key": options.publishableKey
17
+ };
18
+ async function request(path, init) {
19
+ const response = await fetcher(`${base}${path}`, { ...init, headers });
20
+ if (!response.ok) {
21
+ const body = await response.json().catch(() => null);
22
+ throw new FayzAgentError(body?.error ?? `Agent request failed (${response.status})`, response.status);
23
+ }
24
+ return await response.json();
25
+ }
26
+ return {
27
+ async getInfo(signal) {
28
+ const body = await request("/config", { method: "GET", signal });
29
+ return body.agent;
30
+ },
31
+ async chat({ signal, ...input }) {
32
+ const body = await request("/chat", {
33
+ method: "POST",
34
+ body: JSON.stringify(input),
35
+ signal
36
+ });
37
+ return {
38
+ conversationId: body.conversationId ?? "",
39
+ content: body.content ?? "",
40
+ toolCalls: body.toolCalls ?? [],
41
+ ...body.pendingAction ? { pendingAction: body.pendingAction } : {}
42
+ };
43
+ },
44
+ async listConversations(externalUserId, signal) {
45
+ const query = externalUserId ? `?externalUserId=${encodeURIComponent(externalUserId)}` : "";
46
+ const body = await request(
47
+ `/conversations${query}`,
48
+ { method: "GET", signal }
49
+ );
50
+ return body.conversations ?? [];
51
+ },
52
+ async getConversation(conversationId, externalUserId, signal) {
53
+ const query = externalUserId ? `?externalUserId=${encodeURIComponent(externalUserId)}` : "";
54
+ const body = await request(
55
+ `/conversations/${encodeURIComponent(conversationId)}${query}`,
56
+ { method: "GET", signal }
57
+ );
58
+ return body.conversation;
59
+ }
60
+ };
61
+ }
62
+
63
+ exports.FayzAgentError = FayzAgentError;
64
+ exports.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C5D,MAAA,MAAM,QAAQ,cAAA,GAAiB,CAAA,gBAAA,EAAmB,kBAAA,CAAmB,cAAc,CAAC,CAAA,CAAA,GAAK,EAAA;AACzF,MAAA,MAAM,OAAO,MAAM,OAAA;AAAA,QACjB,CAAA,eAAA,EAAkB,kBAAA,CAAmB,cAAc,CAAC,GAAG,KAAK,CAAA,CAAA;AAAA,QAC5D,EAAE,MAAA,EAAQ,KAAA,EAAO,MAAA;AAAO,OAC1B;AACA,MAAA,OAAO,IAAA,CAAK,YAAA;AAAA,IACd;AAAA,GACF;AACF","file":"chunk-7UZH4XEV.cjs","sourcesContent":["/**\n * Client for the Fayz agent broker — the runtime surface a generated app uses\n * to reach the AI agent configured for its project in Fayz.\n *\n * Mirrors `createFayzShopProvider`: the app holds a publishable key, Fayz holds\n * the model credentials. The key ships in the bundle the same way a Supabase\n * anon key does; it only ever resolves to the one agent its web channel belongs\n * to, and the broker rate-limits per project.\n *\n * Tools are client-plane. The app declares what it can do (`tools`), the model\n * decides what to call, and the app executes the calls against its own session\n * before handing results back. Fayz never needs the app's data credentials.\n */\n\nexport interface FayzAgentClientOptions {\n /** Fayz API base, e.g. https://fayz.ai/api */\n baseUrl: string\n projectId: string\n /** Publishable key of the project's WEB agent channel. */\n publishableKey: string\n fetcher?: typeof fetch\n}\n\nexport interface FayzAgentTool {\n name: string\n description: string\n /** JSON Schema for the tool's arguments. */\n parameters?: Record<string, unknown>\n}\n\nexport interface FayzAgentToolCall {\n id: string\n name: string\n arguments: Record<string, unknown>\n}\n\nexport interface FayzAgentToolResult {\n toolCallId: string\n content: string\n}\n\nexport interface FayzAgentChatInput {\n /** New end-user message. Omit when replying with tool results. */\n message?: string\n conversationId?: string\n /** Identity of the end user, required by channels with an INTERNAL audience. */\n externalUserId?: string\n /** Human label for that user, so the owner's dashboard shows a name. */\n externalUserName?: string\n tools?: FayzAgentTool[]\n toolResults?: FayzAgentToolResult[]\n /** Decision for a server-parked write (broker PENDING_CONFIRMATION step). */\n confirmAction?: { id: string; approved: boolean }\n /** Runtime context the agent should know about (page, locale, tenant). */\n context?: Record<string, unknown>\n signal?: AbortSignal\n}\n\n/** A server-plane write the broker parked pending human confirmation. */\nexport interface FayzAgentPendingAction {\n id: string\n toolName: string\n title?: string\n params?: Record<string, unknown>\n}\n\nexport interface FayzAgentChatResponse {\n conversationId: string\n content: string\n toolCalls: FayzAgentToolCall[]\n /** Present when the broker is waiting on a confirmAction for this write. */\n pendingAction?: FayzAgentPendingAction\n}\n\nexport interface FayzAgentInfo {\n id: string\n name: string\n description: string | null\n icon: string | null\n}\n\nexport class FayzAgentError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n this.name = 'FayzAgentError'\n }\n}\n\nexport interface FayzAgentConversationSummary {\n id: string\n title: string | null\n /** Last activity — the field the list is ordered by. */\n updatedAt: string\n}\n\nexport interface FayzAgentConversationMessage {\n id: string\n role: string\n content: string\n createdAt: string\n /** Tool calls this reply made, with their results — so a resumed thread shows\n * the same trace and record links it showed live. */\n toolCalls?: Array<{\n name: string\n arguments?: Record<string, unknown>\n result?: string\n }>\n}\n\nexport interface FayzAgentConversationDetail {\n id: string\n title: string | null\n messages: FayzAgentConversationMessage[]\n}\n\nexport interface FayzAgentClient {\n /** Identity of the agent behind the key, for rendering its name/icon. */\n getInfo(signal?: AbortSignal): Promise<FayzAgentInfo>\n chat(input: FayzAgentChatInput): Promise<FayzAgentChatResponse>\n /** The signed-in user's own threads, most-recently-active first. */\n listConversations(externalUserId?: string, signal?: AbortSignal): Promise<FayzAgentConversationSummary[]>\n /** One thread with its transcript — 404s on another user's thread. */\n getConversation(\n conversationId: string,\n externalUserId?: string,\n signal?: AbortSignal,\n ): Promise<FayzAgentConversationDetail>\n}\n\nexport function createFayzAgentClient(options: FayzAgentClientOptions): FayzAgentClient {\n const fetcher = options.fetcher ?? globalThis.fetch\n const base = `${options.baseUrl.replace(/\\/+$/, '')}/public/projects/${options.projectId}/agents`\n const headers = {\n 'Content-Type': 'application/json',\n 'x-fayz-agent-key': options.publishableKey,\n }\n\n async function request<T>(path: string, init: RequestInit): Promise<T> {\n const response = await fetcher(`${base}${path}`, { ...init, headers })\n if (!response.ok) {\n const body = (await response.json().catch(() => null)) as { error?: string } | null\n throw new FayzAgentError(body?.error ?? `Agent request failed (${response.status})`, response.status)\n }\n return (await response.json()) as T\n }\n\n return {\n async getInfo(signal) {\n const body = await request<{ agent: FayzAgentInfo }>('/config', { method: 'GET', signal })\n return body.agent\n },\n\n async chat({ signal, ...input }) {\n const body = await request<Partial<FayzAgentChatResponse>>('/chat', {\n method: 'POST',\n body: JSON.stringify(input),\n signal,\n })\n return {\n conversationId: body.conversationId ?? '',\n content: body.content ?? '',\n toolCalls: body.toolCalls ?? [],\n ...(body.pendingAction ? { pendingAction: body.pendingAction } : {}),\n }\n },\n\n async listConversations(externalUserId, signal) {\n const query = externalUserId ? `?externalUserId=${encodeURIComponent(externalUserId)}` : ''\n const body = await request<{ conversations?: FayzAgentConversationSummary[] }>(\n `/conversations${query}`,\n { method: 'GET', signal },\n )\n return body.conversations ?? []\n },\n\n async getConversation(conversationId, externalUserId, signal) {\n const query = externalUserId ? `?externalUserId=${encodeURIComponent(externalUserId)}` : ''\n const body = await request<{ conversation: FayzAgentConversationDetail }>(\n `/conversations/${encodeURIComponent(conversationId)}${query}`,\n { method: 'GET', signal },\n )\n return body.conversation\n },\n }\n}\n"]}