@ecomweb/sdk 0.14.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/dist/index.d.ts +189 -69
- package/dist/index.js +230 -126
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/client-info.ts","../src/core/response.ts","../src/types/common.ts","../src/types/product-status.ts","../src/types/email-branding.ts","../src/types/store.ts","../src/types/embedded-script.ts","../src/types/product.ts","../src/types/product-review.ts","../src/types/pagination.ts","../src/types/inventory.ts","../src/types/category.ts","../src/types/order.ts","../src/types/shipment.ts","../src/types/order-timeline.ts","../src/types/promotion.ts","../src/types/blog.ts","../src/types/content.ts","../src/types/theme-schema.ts","../src/types/metafield-engine.ts","../src/modules/storage/image-transform.ts","../src/core/stringify.ts","../src/modules/products/api.ts","../src/modules/collections/api.ts","../src/modules/categories/api.ts","../src/modules/cart/api.ts","../src/modules/orders/api.ts","../src/modules/blog/api.ts","../src/modules/stores/api.ts","../src/modules/themes/api.ts","../src/modules/metaobjects/api.ts","../src/modules/search/api.ts","../src/modules/shipping/api.ts","../src/modules/promotions/api.ts","../src/modules/payment-methods/api.ts","../src/modules/payments/api.ts","../src/modules/reviews/api.ts","../src/modules/customers/api.ts","../src/modules/addresses/api.ts","../src/modules/content-pages/api.ts","../src/modules/menus/api.ts","../src/modules/redirects/api.ts","../src/modules/auth/api.ts","../src/modules/auth/token-storage.ts","../src/modules/auth/refresh-client.ts","../src/modules/collections/rule-set.ts","../src/modules/shipping/types.ts","../src/index.ts"],"sourcesContent":["import type { IHttpClient, RequestOptions } from \"./types\";\n\n// Replaced at build time (tsup `define`, and the workspace's Next and vitest\n// configs) with this package's version from package.json.\ndeclare const __ECOMWEB_SDK_VERSION__: string | undefined;\n\n/**\n * This package's version, baked in at build time. `dev` when the source runs\n * without the define (the API ignores a version that isn't semver).\n */\nexport const SDK_VERSION: string =\n typeof __ECOMWEB_SDK_VERSION__ === \"string\" ? __ECOMWEB_SDK_VERSION__ : \"dev\";\n\n/** Sent on every SDK request: space-separated `name/version` tokens. */\nexport const CLIENT_HEADER = \"X-Ecomweb-Client\";\n\n/** This SDK's own token, `@ecomweb/sdk/<version>`. */\nexport const SDK_CLIENT_TOKEN = `@ecomweb/sdk/${SDK_VERSION}`;\n\n/**\n * The `X-Ecomweb-Client` value: `clientInfo` (a caller's own tokens, such as\n * `@ecomweb/storefront-kit/0.14.0`) followed by this SDK's token.\n */\nexport function clientHeaderValue(clientInfo?: string): string {\n const prefix = clientInfo?.trim();\n return prefix ? `${prefix} ${SDK_CLIENT_TOKEN}` : SDK_CLIENT_TOKEN;\n}\n\nconst WRAPPED = Symbol.for(\"ecomweb.sdk.clientHeader\");\n\nfunction withHeader(\n options: RequestOptions | undefined,\n value: string\n): RequestOptions {\n const headers = options?.headers ?? {};\n const present = Object.keys(headers).some(\n name => name.toLowerCase() === CLIENT_HEADER.toLowerCase()\n );\n return {\n ...options,\n headers: present ? headers : { [CLIENT_HEADER]: value, ...headers },\n };\n}\n\n/**\n * Wraps an HTTP client so every request carries `X-Ecomweb-Client`. A header\n * the caller already set wins, and a client wrapped once is not wrapped again.\n */\nexport function withClientHeader(\n http: IHttpClient,\n clientInfo?: string\n): IHttpClient {\n if ((http as { [WRAPPED]?: true })[WRAPPED]) return http;\n const value = clientHeaderValue(clientInfo);\n const wrapped: IHttpClient & { [WRAPPED]: true } = {\n [WRAPPED]: true,\n get: (url, options) => http.get(url, withHeader(options, value)),\n post: (url, data, options) =>\n http.post(url, data, withHeader(options, value)),\n put: (url, data, options) => http.put(url, data, withHeader(options, value)),\n patch: (url, data, options) =>\n http.patch(url, data, withHeader(options, value)),\n delete: (url, options) => http.delete(url, withHeader(options, value)),\n };\n return wrapped;\n}\n","import type { ApiResponse } from \"./types\";\n\n/**\n * The error thrown when the API answers with an error. Carries the HTTP status and the API's error code.\n */\nexport class ApiClientError extends Error {\n /**\n * The HTTP status code, or `0` when there was no response.\n */\n statusCode: number;\n /**\n * The API's machine-readable error code, when it sent one.\n */\n code?: string;\n /** The business error's structured `details`, when the backend sent any. */\n details?: unknown;\n constructor(message: string, statusCode = 0, code?: string, details?: unknown) {\n super(message);\n this.name = \"ApiClientError\";\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\nfunction toClientError(response: ApiResponse<unknown>): ApiClientError {\n return new ApiClientError(\n response.error?.message || \"Request failed\",\n response.error?.statusCode || 0,\n response.error?.error,\n response.error?.details,\n );\n}\n\n/**\n * Returns the data of a successful response and throws on an error response.\n *\n * @param response - the response to read\n * @returns The response data; throws {@link ApiClientError} when the API answers with an error\n */\nexport function unwrap<T>(response: ApiResponse<T>): T {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n throw toClientError(response);\n}\n\n/**\n * Like {@link unwrap}, but resolves `null` for the statuses that mean \"not found\".\n *\n * @param response - the response to read\n * @param nullStatusCodes - the statuses that resolve `null`, `[404]` by default\n * @returns The response data, or `null` when the status is in `nullStatusCodes`; throws {@link ApiClientError} on any other API error\n */\nexport function unwrapOrNull<T>(\n response: ApiResponse<T>,\n nullStatusCodes: number[] = [404]\n): T | null {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n if (\n !response.success &&\n response.error &&\n nullStatusCodes.includes(response.error.statusCode)\n ) {\n return null;\n }\n throw toClientError(response);\n}\n\n/**\n * Throws on an error response and returns nothing on success. Use it when you do not need the data.\n *\n * @param response - the response to check\n */\nexport function ensureSuccess(response: ApiResponse<any>): void {\n if (response.success) return;\n throw toClientError(response);\n}\n","import { z } from \"zod\";\n\n/**\n * Common schemas and validators used across all entities\n * Updated for Zod v4 syntax with explicit TypeScript types\n */\n\n// Re-export product status schemas from dedicated module (single source of truth)\nexport {\n productStatusSchema,\n ProductStatus,\n inventoryStatusSchema,\n InventoryStatus,\n PRODUCT_STATUS_LABELS,\n INVENTORY_STATUS_LABELS,\n isPublishableStatus,\n isUnpublishedStatus,\n isEditableStatus,\n} from \"./product-status\";\n\n// Base timestamp interface\ninterface Timestamp {\n created_at: string;\n updated_at: string;\n}\n\n// Optional timestamp interface\ninterface OptionalTimestamp {\n created_at?: string | null;\n updated_at?: string | null;\n}\n\n// Deleted timestamp interface\ninterface DeletedAt {\n deleted_at?: string | null;\n}\n\n// Base timestamp schema for created_at/updated_at fields\nexport const timestampSchema = z.object({\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n});\n\n// Optional timestamp schema for entities that might not have timestamps\nexport const optionalTimestampSchema = z.object({\n created_at: z.iso.datetime().optional().nullable(),\n updated_at: z.iso.datetime().optional().nullable(),\n});\n\n// Deleted timestamp for soft deletes\nexport const deletedAtSchema = z.object({\n deleted_at: z.iso.datetime().optional().nullable(),\n});\n\n// UUID schema using v4 syntax\nexport const uuidSchema = z.uuidv4();\n\n// ID schemas using v4 syntax\nexport const idSchema = z.int32().positive();\nexport const storeIdSchema = z.int32().positive();\n\n// Status enums\nexport const storeStatusSchema = z.enum([\"pending\", \"active\", \"disabled\"]);\nexport type StoreStatus = \"pending\" | \"active\" | \"disabled\";\n\n/**\n * @deprecated Use productStatusSchema and ProductStatus from './product-status' instead\n * This legacy definition will be removed in a future version.\n * Migration: \"inactive\" → \"archived\", inventory statuses moved to inventoryStatusSchema\n */\nexport const legacyProductStatusSchema = z.enum([\n \"active\",\n \"inactive\",\n \"draft\",\n]);\nexport type LegacyProductStatus = \"active\" | \"inactive\" | \"draft\";\n\n// NEW: Separate status enums for state machine management\nexport const orderStatusSchema = z.enum([\n \"pending\",\n \"confirmed\",\n \"processing\",\n \"cancelled\",\n \"on_hold\",\n \"completed\",\n]);\nexport type OrderStatus =\n | \"pending\"\n | \"confirmed\"\n | \"processing\"\n | \"cancelled\"\n | \"on_hold\"\n | \"completed\";\n\nexport const fulfillmentStatusSchema = z.enum([\n \"unfulfilled\",\n \"fulfilled\",\n \"returned\",\n \"return_requested\",\n]);\nexport type FulfillmentStatus =\n | \"unfulfilled\"\n | \"fulfilled\"\n | \"returned\"\n | \"return_requested\";\n\nexport const shippingStatusSchema = z.enum([\n \"not_shipped\",\n \"shipped\",\n \"in_transit\",\n \"out_for_delivery\",\n \"delivered\",\n \"delivery_failed\",\n]);\nexport type ShippingStatus =\n | \"not_shipped\"\n | \"shipped\"\n | \"in_transit\"\n | \"out_for_delivery\"\n | \"delivered\"\n | \"delivery_failed\";\n\nexport const paymentStatusSchema = z.enum([\n \"pending\",\n \"authorized\",\n \"paid\",\n \"captured\",\n \"failed\",\n \"refunded\",\n \"voided\",\n \"expired\",\n]);\nexport type PaymentStatus =\n | \"pending\"\n | \"authorized\"\n | \"paid\"\n | \"captured\"\n | \"failed\"\n | \"refunded\"\n | \"voided\"\n | \"expired\";\n\n// DEPRECATED: Legacy order status for backward compatibility\nexport const legacyOrderStatusSchema = z.enum([\n \"pending\",\n \"confirmed\",\n \"processing\",\n \"shipped\",\n \"delivered\",\n \"cancelled\",\n \"completed\",\n]);\nexport type LegacyOrderStatus =\n | \"pending\"\n | \"confirmed\"\n | \"processing\"\n | \"shipped\"\n | \"delivered\"\n | \"cancelled\"\n | \"completed\";\n\n/**\n * The set of payment methods this SDK has shipped labels for. It is a hint for\n * UI, NOT a constraint: each store defines its own enabled methods, and the API\n * validates a submitted method against that store's configuration. Adding a\n * gateway must not require an SDK release.\n */\nexport const KNOWN_PAYMENT_METHODS = [\n \"cod\",\n \"bank_transfer\",\n \"e_wallet\",\n \"credit_card\",\n \"momo\",\n \"zalopay\",\n \"vnpay\",\n \"onepay\",\n] as const;\n\nexport const paymentMethodSchema = z.string().min(1);\nexport type PaymentMethod = string;\n\nexport const blogPostStatusSchema = z.enum([\n \"draft\",\n \"published\",\n \"scheduled\",\n \"unlisted\",\n]);\nexport type BlogPostStatus = \"draft\" | \"published\" | \"scheduled\" | \"unlisted\";\n\nexport const integrationStatusSchema = z.enum([\"active\", \"inactive\", \"error\"]);\nexport type IntegrationStatus = \"active\" | \"inactive\" | \"error\";\n\nexport const variantStatusSchema = z.enum([\n \"active\",\n \"inactive\",\n \"out_of_stock\",\n]);\nexport type VariantStatus = \"active\" | \"inactive\" | \"out_of_stock\";\n\nexport const messageOutboxStatusSchema = z.enum([\n \"PENDING\",\n \"PUBLISHED\",\n \"FAILED\",\n]);\nexport type MessageOutboxStatus = \"PENDING\" | \"PUBLISHED\" | \"FAILED\";\n\n// Common type aliases for better readability\nexport type Id = number;\n\n// Export interfaces for reuse\nexport type { Timestamp, OptionalTimestamp, DeletedAt };\n\n// Common validation patterns using v4 syntax\nexport const emailSchema = z.email();\nexport const phoneSchema = z\n .string()\n .regex(/^[0-9+\\-\\s()]+$/)\n .optional()\n .nullable();\nexport const urlSchema = z.url().optional().nullable();\nexport const strictUrlSchema = z.url(); // For required URLs\nexport const slugSchema = z\n .string()\n .min(1)\n .regex(/^[a-z0-9-]+$/);\nexport const colorSchema = z\n .string()\n .regex(/^#[0-9A-Fa-f]{6}$/)\n .optional()\n .nullable();\n\n// Optional URL that allows empty string\nexport const optionalUrlSchema = z.url().optional().or(z.literal(\"\"));\n\n// Decimal/money values\nexport const moneySchema = z.float64().multipleOf(0.01);\nexport const decimalSchema = z.float64();\n\n// JSON field schema\nexport const jsonSchema = z.record(z.string(), z.any());\n\n// Pagination schema\nexport const paginationSchema = z.object({\n page: z.int32().min(1).default(1),\n limit: z.int32().min(1).max(100).default(20),\n});\n\n// Sort order schema\nexport const positionOrderSchema = z.int32().default(0);\n\nexport const sortOrderSchema = z.enum([\"asc\", \"desc\"]);\n\n// Image dimensions schema\nexport const dimensionsSchema = z\n .object({\n width: z.float64(),\n height: z.float64(),\n length: z.float64().optional(),\n })\n .optional()\n .nullable();\n","import { z } from \"zod\";\n\n/**\n * Product Status Schema - Single Source of Truth\n *\n * This schema standardizes product status across the entire e-commerce system,\n * following industry best practices from Shopify, WooCommerce, and Magento.\n *\n * IMPORTANT: Product status (lifecycle/publishing) is separate from inventory status.\n * - Product Status: Controls visibility and publishing state\n * - Inventory Status: Computed from stock quantity (not a product attribute)\n */\n\n// ============================================================================\n// Product Status (Lifecycle/Publishing)\n// ============================================================================\n\n/**\n * Product lifecycle and publishing status\n *\n * Status Flow:\n * draft → active → unlisted\n *\n * State transitions are enforced by the product state machine:\n * @see apps/api/src/modules/catalog/domain/validators/product-status-state-machine.ts\n */\nexport const productStatusSchema = z.enum([\n \"draft\", // Work in progress, not visible to customers\n \"active\", // Published and visible to customers\n \"unlisted\", // Hidden from public view, can be restored\n]);\n\n/**\n * TypeScript type inferred from product status schema\n */\nexport type ProductStatus = z.infer<typeof productStatusSchema>;\n\n/**\n * Product status enum for use in application code\n * Provides autocomplete and type safety\n */\n// eslint-disable-next-line no-redeclare -- intentional TS type + value pair (ProductStatus type above); base rule is not TS-aware\nexport const ProductStatus = {\n DRAFT: \"draft\" as const,\n ACTIVE: \"active\" as const,\n UNLISTED: \"unlisted\" as const,\n} as const;\n\n// ============================================================================\n// Inventory Status (Computed - NOT a Product Attribute)\n// ============================================================================\n\n/**\n * Inventory availability status - COMPUTED from stock quantity\n *\n * IMPORTANT: This is NOT stored as a product field!\n * It is dynamically calculated based on:\n * - variant.quantity\n * - store.low_stock_threshold\n * - variant.backorder_allowed\n *\n * Historical Note:\n * Previously, \"out_of_stock\" and \"low_stock\" were incorrectly stored as\n * product status values. They are now computed inventory states.\n */\nexport const inventoryStatusSchema = z.enum([\n \"in_stock\", // Quantity > low_stock_threshold\n \"low_stock\", // Quantity <= low_stock_threshold && quantity > 0\n \"out_of_stock\", // Quantity = 0 && !backorder_allowed\n \"backordered\", // Quantity = 0 && backorder_allowed\n]);\n\n/**\n * TypeScript type inferred from inventory status schema\n */\nexport type InventoryStatus = z.infer<typeof inventoryStatusSchema>;\n\n/**\n * Inventory status enum for use in application code\n */\n// eslint-disable-next-line no-redeclare -- intentional TS type + value pair (InventoryStatus type above); base rule is not TS-aware\nexport const InventoryStatus = {\n IN_STOCK: \"in_stock\" as const,\n LOW_STOCK: \"low_stock\" as const,\n OUT_OF_STOCK: \"out_of_stock\" as const,\n BACKORDERED: \"backordered\" as const,\n} as const;\n\n// ============================================================================\n// Migration Helpers\n// ============================================================================\n\n/**\n * Maps legacy product status values to new standardized values\n * Used during data migration and backward compatibility\n */\nexport const LEGACY_STATUS_MIGRATION_MAP = {\n active: ProductStatus.ACTIVE,\n inactive: ProductStatus.UNLISTED, // inactive → unlisted\n archived: ProductStatus.UNLISTED, // archived → unlisted (old status)\n pending: ProductStatus.DRAFT, // pending → draft (removed approval workflow)\n scheduled: ProductStatus.DRAFT, // scheduled → draft (removed scheduling)\n draft: ProductStatus.DRAFT,\n out_of_stock: ProductStatus.ACTIVE, // Was inventory status, map to active\n low_stock: ProductStatus.ACTIVE, // Was inventory status, map to active\n} as const;\n\n/**\n * Product status labels for UI display (Vietnamese)\n */\nexport const PRODUCT_STATUS_LABELS: Record<ProductStatus, string> = {\n draft: \"Nháp\",\n active: \"Hoạt động\",\n unlisted: \"Không công khai\",\n};\n\n/**\n * Inventory status labels for UI display (Vietnamese)\n */\nexport const INVENTORY_STATUS_LABELS: Record<InventoryStatus, string> = {\n in_stock: \"Còn hàng\",\n low_stock: \"Sắp hết hàng\",\n out_of_stock: \"Hết hàng\",\n backordered: \"Cho phép đặt trước\",\n};\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Check if a product status is publishable (visible to customers)\n */\nexport function isPublishableStatus(status: ProductStatus): boolean {\n return status === ProductStatus.ACTIVE;\n}\n\n/**\n * Check if a product status represents a non-published state\n */\nexport function isUnpublishedStatus(status: ProductStatus): boolean {\n return status === ProductStatus.DRAFT || status === ProductStatus.UNLISTED;\n}\n\n/**\n * Check if a product status allows editing\n */\nexport function isEditableStatus(status: ProductStatus): boolean {\n return status === ProductStatus.DRAFT;\n}\n","import { z } from \"zod\";\nimport { urlSchema } from \"./common\";\n\n/**\n * Email branding vocabulary, mirrored from the API.\n *\n * The API owns these values (src/modules/templates/domain/email-palette.ts)\n * and pins this file with a tripwire test. It cannot import this package —\n * the SDK is a client OF that API, and depending on it would invert the\n * relationship. So the two are kept in step by hand.\n *\n * If you change anything here, change it there in the same PR, or the\n * dashboard will show merchants a default swatch the emails do not render.\n */\nexport const EMAIL_PALETTE_DEFAULTS = {\n accent: \"#f4644f\",\n bg: \"#FFFFFF\",\n bodyBg: \"#FFFFFF\",\n text: \"#1A1A1A\",\n footerText: \"#6B7280\",\n} as const;\n\n/**\n * Matches the API's DTO validation exactly: #RRGGBB, nothing else. 3-digit\n * hex, named colours and rgb() are rejected at the edge so the render path\n * never has to parse anything.\n */\nexport const EMAIL_COLOR_PATTERN = /^#[0-9A-Fa-f]{6}$/;\n\nconst emailColorSchema = z\n .string()\n .regex(EMAIL_COLOR_PATTERN, \"Must be a 6-digit hex colour, e.g. #1D4ED8\")\n .optional()\n .nullable();\n\n/**\n * The nine store_settings columns a merchant can set for email branding.\n * Every one is nullable: NULL means \"use the house default\", which is what\n * lets an unconfigured store render exactly as it did before the feature.\n */\nexport const emailBrandingShape = {\n email_accent_color: emailColorSchema,\n email_bg_color: emailColorSchema,\n email_body_bg_color: emailColorSchema,\n email_text_color: emailColorSchema,\n email_footer_text_color: emailColorSchema,\n email_logo_url: urlSchema,\n email_header_tagline: z.string().max(120).optional().nullable(),\n email_footer_address: z.string().max(255).optional().nullable(),\n email_footer_phone: z.string().max(32).optional().nullable(),\n};\n\nexport const emailBrandingSchema = z.object(emailBrandingShape);\n\nexport type StoreEmailBrandingSettings = z.infer<typeof emailBrandingSchema>;\n","import { z } from \"zod\";\nimport {\n timestampSchema,\n deletedAtSchema,\n storeStatusSchema,\n uuidSchema,\n urlSchema,\n optionalTimestampSchema,\n idSchema,\n StoreStatus,\n} from \"./common\";\nimport { emailBrandingShape } from \"./email-branding\";\nimport { embeddedScriptSchema, type EmbeddedScript } from \"./embedded-script\";\n\n/**\n * Store-related schemas based on Prisma models\n */\n// Store main entity\nexport const storeSchema = z\n .object({\n id: idSchema,\n // The public store endpoints no longer send it.\n user_id: uuidSchema.optional(),\n name: z.string().min(1),\n description: z.string().optional().nullable(),\n status: storeStatusSchema.default(\"pending\"),\n })\n .extend(timestampSchema.shape)\n .extend(deletedAtSchema.shape);\n\n// Store configuration for domains\nexport const storeConfigSchema = z\n .object({\n id: idSchema,\n store_id: idSchema,\n subdomain: z.string().optional().nullable(),\n custom_domain: z.string().optional().nullable(),\n /**\n * True once the custom domain's DNS works. The storefront redirects the\n * free subdomain to the custom domain only then.\n */\n verified: z.boolean().optional().nullable(),\n })\n .extend(timestampSchema.shape);\n\n/** Checkout and register links: a store path or an absolute URL each. */\nexport const legalLinksSchema = z\n .object({\n terms: z.string().optional().nullable(),\n privacy: z.string().optional().nullable(),\n })\n .optional()\n .nullable();\n\n// Store settings (includes blog fields decorated from blog_settings)\nexport const storeSettingsSchema = z\n .object({\n id: idSchema,\n store_id: idSchema,\n logo_url: urlSchema,\n favicon_url: urlSchema,\n featured_image: urlSchema,\n tiktok_link: urlSchema,\n shopee_link: urlSchema,\n facebook_link: urlSchema,\n instagram_link: urlSchema,\n google_analytics_key: z.string().optional().nullable(),\n tagline: z.string().optional().nullable(),\n blog_title: z.string().optional().nullable(),\n is_blog_enabled: z.boolean().optional().nullable(),\n /**\n * The rest of blog_settings the storefront renders. Absent from older\n * APIs: readers fall back to the platform defaults (built-in blurb, 12\n * posts a page, comments on).\n */\n blog_description: z.string().optional().nullable(),\n posts_per_page: z.int32().optional().nullable(),\n allow_comments: z.boolean().optional().nullable(),\n currency_code: z\n .string()\n .min(3)\n .max(3)\n .default(\"VND\")\n .optional()\n .nullable(),\n review_requests_enabled: z.boolean().optional().nullable(),\n /**\n * Wrap the order sequence to form Order.order_code. A null prefix means\n * the store never configured one and takes the default \"#\"; an empty\n * string means the merchant deliberately cleared it.\n */\n order_number_prefix: z.string().optional().nullable(),\n order_number_suffix: z.string().optional().nullable(),\n legal_links: legalLinksSchema,\n })\n .extend(emailBrandingShape)\n .extend(optionalTimestampSchema.shape);\n\n// Create store input\nexport const createStoreSchema = storeSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n deleted_at: true,\n});\n\n// Update store input\nexport const updateStoreSchema = createStoreSchema.partial();\n\n// Create store config input\nexport const createStoreConfigSchema = storeConfigSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update store config input\nexport const updateStoreConfigSchema = createStoreConfigSchema.partial().omit({\n store_id: true,\n});\n\n// Create store settings input\nexport const createStoreSettingsSchema = storeSettingsSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update store settings input\nexport const updateStoreSettingsSchema = createStoreSettingsSchema\n .partial()\n .omit({\n store_id: true,\n });\n\n// Store with relations\nexport const storeWithRelationsSchema = storeSchema.extend({\n store_config: storeConfigSchema.optional().nullable(),\n store_settings: storeSettingsSchema.optional().nullable(),\n embedded_scripts: z.array(embeddedScriptSchema).optional(),\n});\n\n// Export types\nexport type Store = {\n ref: string;\n /** @deprecated Public store endpoints no longer send it; do not rely on it. */\n user_id?: string;\n name: string;\n description: string | null;\n status: StoreStatus;\n created_at: string;\n updated_at: string;\n deleted_at: string | null;\n embedded_scripts?: EmbeddedScript[];\n /** Contract \"Storefront\": true until the merchant opens the store. Absent on older APIs. */\n coming_soon?: boolean;\n /** Contract \"Storefront\": when the store first opened, null if never. Absent on older APIs. */\n first_opened_at?: string | null;\n};\nexport type StoreConfig = z.infer<typeof storeConfigSchema>;\nexport type StoreSettings = z.infer<typeof storeSettingsSchema>;\nexport type CreateStore = z.infer<typeof createStoreSchema>;\nexport type UpdateStore = z.infer<typeof updateStoreSchema>;\nexport type CreateStoreConfig = z.infer<typeof createStoreConfigSchema>;\nexport type UpdateStoreConfig = z.infer<typeof updateStoreConfigSchema>;\nexport type CreateStoreSettings = z.infer<typeof createStoreSettingsSchema>;\nexport type UpdateStoreSettings = z.infer<typeof updateStoreSettingsSchema>;\nexport type StoreWithRelations = z.infer<typeof storeWithRelationsSchema>;\n","import { z } from \"zod\";\nimport { idSchema } from \"./common\";\n\n/**\n * Embedded scripts schema - custom tracking/analytics scripts for stores\n */\n\n// Placement enum - where the script should be injected\nexport const embeddedScriptPlacementSchema = z.enum([\n \"head\",\n \"body_start\",\n \"body_end\",\n]);\n\nexport type EmbeddedScriptPlacement = z.infer<\n typeof embeddedScriptPlacementSchema\n>;\n\n// Full embedded script schema\nexport const embeddedScriptSchema = z.object({\n id: idSchema,\n name: z.string().min(1).max(255),\n code: z.string().min(1),\n placement: embeddedScriptPlacementSchema,\n created_at: z.iso.datetime().optional().nullable(),\n updated_at: z.iso.datetime().optional().nullable(),\n});\n\nexport type EmbeddedScript = z.infer<typeof embeddedScriptSchema>;\n\n// Create schema (omits generated fields)\nexport const createEmbeddedScriptSchema = embeddedScriptSchema.pick({\n name: true,\n code: true,\n placement: true,\n});\n\nexport type CreateEmbeddedScript = z.infer<typeof createEmbeddedScriptSchema>;\n\n// Update schema (all fields optional)\nexport const updateEmbeddedScriptSchema = createEmbeddedScriptSchema.partial();\n\nexport type UpdateEmbeddedScript = z.infer<typeof updateEmbeddedScriptSchema>;\n","import { z } from \"zod\";\nimport {\n productReviewStatsSchema,\n ProductReviewStats,\n} from \"./product-review\";\nimport {\n timestampSchema,\n productStatusSchema,\n variantStatusSchema,\n moneySchema,\n decimalSchema,\n jsonSchema,\n dimensionsSchema,\n positionOrderSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n ProductStatus,\n VariantStatus,\n} from \"./common\";\nimport { INVENTORY_POLICIES, type InventoryPolicy } from \"./inventory\";\n\n/**\n * Product-related schemas based on Prisma models\n */\n\n// Product interface\nexport interface Product extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string | null;\n description: string | null;\n status: ProductStatus;\n category_id: Id | null;\n is_featured: boolean;\n min_price: number | null;\n max_price: number | null;\n variant_mode: string;\n external_id: string | null;\n images: Array<any>; // Array of image objects\n videos?: ProductVideo[]; // Product videos\n}\n\n// Infer dimensions type from dimensionsSchema\ntype Dimensions = z.infer<typeof dimensionsSchema>;\n\n// Product variant interface\nexport interface ProductVariant extends OptionalTimestamp {\n id: Id;\n product_id: Id;\n sku_id: Id;\n seller_sku: string | null;\n external_id: string | null;\n price: number;\n inventory: number;\n /**\n * false: never reserved or blocked at checkout. Admin and public responses.\n * A response from an API predating this field never omits it, but if one\n * ever did, treat the missing value as `true` (tracked) per contract\n * section 7, so an old response can never make everything look\n * purchasable.\n */\n track_inventory: boolean;\n /**\n * deny: checkout rejects when stock is short. continue: sells past zero.\n * Per contract section 7, a missing value falls back to `\"deny\"`, the same\n * fail-safe reasoning as `track_inventory` above.\n */\n inventory_policy: InventoryPolicy;\n /** Unit cost to the store. Admin responses only: any store member, or an API key holding read:inventory. Never in public responses. */\n cost_per_item?: number | null;\n weight: number | null;\n dimensions: Dimensions;\n is_default: boolean;\n status: VariantStatus;\n}\n\n// Variant option interface\nexport interface VariantOption extends OptionalTimestamp {\n id: Id;\n name: string;\n sort_order: number;\n}\n\n// Variant option value interface\nexport interface VariantOptionValue extends OptionalTimestamp {\n id: Id;\n option_id: Id;\n value: string;\n display_value: string;\n image_url: string;\n sort_order: number;\n swatch_type: \"none\" | \"color\" | \"image\";\n swatch_value: string;\n}\n\n// Product variant combination interface\nexport interface ProductVariantCombination {\n id: Id;\n variant_id: Id;\n option_id: Id;\n option_value_id: Id;\n created_at: string;\n}\n\n// A single `combinations[]` entry as emitted by the API's\n// `mapVariantCombination` (variant-combination.mapper.ts). The legacy\n// `option`/`value` and `variant_options`/`variant_option_values` aliases\n// were retired in Phase E (spec §12 step 18 / issue #182) — only\n// `attributes`/`attribute_values` are emitted now.\nexport interface ProductVariantCombinationEntry {\n attributes: VariantOption;\n attribute_values: VariantOptionValue;\n}\n\n// Create/Update types\nexport type CreateProduct = Omit<Product, \"id\" | keyof OptionalTimestamp>;\nexport type UpdateProduct = Partial<CreateProduct>;\n\nexport type CreateProductVariant = Omit<\n ProductVariant,\n | \"id\"\n | \"sku_id\"\n | keyof OptionalTimestamp\n | \"track_inventory\"\n | \"inventory_policy\"\n> & {\n /** Optional on input: the API defaults it to true. */\n track_inventory?: boolean;\n /** Optional on input: the API defaults it to \"deny\". */\n inventory_policy?: InventoryPolicy;\n};\nexport type UpdateProductVariant = Partial<\n Omit<CreateProductVariant, \"product_id\">\n>;\n\nexport type CreateVariantOption = Omit<\n VariantOption,\n \"id\" | keyof OptionalTimestamp\n>;\nexport type UpdateVariantOption = Partial<CreateVariantOption>;\n\nexport type CreateVariantOptionValue = Omit<\n VariantOptionValue,\n \"id\" | keyof OptionalTimestamp\n>;\nexport type UpdateVariantOptionValue = Partial<CreateVariantOptionValue>;\n\n// Extended types for relationships\nexport interface ProductWithVariants extends Product {\n variants?: ProductVariantWithCombinations[];\n}\n\nexport interface ProductVariantWithCombinations extends ProductVariant {\n combinations?: ProductVariantCombinationEntry[];\n}\n\n// Product response extended with optional per-product review_stats\nexport interface ProductWithReviewStats extends Product {\n review_stats?: ProductReviewStats | null;\n}\n\n// Product main entity\nexport const productSchema = z\n .object({\n id: idSchema,\n name: z.string().min(1),\n slug: z.string().max(255).optional().nullable(),\n description: z.string().optional().nullable(),\n status: productStatusSchema.default(\"active\"),\n category_id: idSchema.optional().nullable(),\n is_featured: z.boolean().default(false),\n min_price: moneySchema.optional().nullable(),\n max_price: moneySchema.optional().nullable(),\n variant_mode: z.string(),\n external_id: z.string().optional().nullable(),\n images: jsonSchema, // Array of image objects\n })\n .extend(timestampSchema.shape);\n\n// Product variant\nexport const productVariantSchema = z\n .object({\n id: idSchema,\n product_id: idSchema,\n sku_id: idSchema,\n seller_sku: z.string().optional().nullable(),\n external_id: z.string().optional().nullable(),\n price: moneySchema,\n inventory: z.int32().default(0),\n track_inventory: z.boolean().default(true),\n inventory_policy: z.enum(INVENTORY_POLICIES).default(\"deny\"),\n // z.number(), not moneySchema: unit costs carry up to 4 decimals, and\n // moneySchema (2 decimals) would reject a valid cost.\n cost_per_item: z.number().nonnegative().nullable().optional(),\n weight: decimalSchema.optional().nullable(),\n dimensions: dimensionsSchema,\n is_default: z.boolean().default(false),\n status: variantStatusSchema.default(\"active\"),\n })\n .extend(timestampSchema.shape);\n\n// Variant options (like Color, Size)\nexport const variantOptionSchema = z\n .object({\n id: idSchema,\n name: z.string().min(1),\n sort_order: positionOrderSchema,\n })\n .extend(timestampSchema.shape);\n\n// Variant option values (like Red, Blue for Color)\nexport const variantOptionValueSchema = z\n .object({\n id: idSchema,\n option_id: idSchema,\n value: z.string().min(1),\n display_value: z.string().min(1),\n image_url: z.string().default(\"\"),\n sort_order: positionOrderSchema,\n swatch_type: z.enum([\"none\", \"color\", \"image\"]).default(\"none\"),\n swatch_value: z.string().default(\"\"),\n })\n .extend(timestampSchema.shape);\n\n// Product variant combinations (which options/values belong to which variant)\nexport const productVariantCombinationSchema = z.object({\n id: idSchema,\n variant_id: idSchema,\n option_id: idSchema,\n option_value_id: idSchema,\n created_at: z.iso.datetime(),\n});\n\n// Create product schema\nexport const createProductSchema = productSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateProduct>;\n\n// Update product schema\nexport const updateProductSchema = productSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial() as unknown as z.ZodType<UpdateProduct>;\n\n// Create product variant schema\nexport const createProductVariantSchema = productVariantSchema.omit({\n id: true,\n sku_id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateProductVariant>;\n\n// Update product variant schema\nexport const updateProductVariantSchema = productVariantSchema\n .omit({\n id: true,\n sku_id: true,\n created_at: true,\n updated_at: true,\n })\n .partial()\n .omit({\n product_id: true,\n }) as unknown as z.ZodType<UpdateProductVariant>;\n\n// Create variant option schema\nexport const createVariantOptionSchema = variantOptionSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateVariantOption>;\n\n// Update variant option schema\nexport const updateVariantOptionSchema = variantOptionSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial() as unknown as z.ZodType<UpdateVariantOption>;\n\n// Create variant option value schema\nexport const createVariantOptionValueSchema = variantOptionValueSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateVariantOptionValue>;\n\n// Update variant option value schema\nexport const updateVariantOptionValueSchema = variantOptionValueSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial()\n .omit({\n option_id: true,\n }) as unknown as z.ZodType<UpdateVariantOptionValue>;\n\n// A single `combinations[]` entry, matching the exact two keys emitted by\n// the API's `mapVariantCombination` — NOT the write-DTO shape in\n// `productVariantCombinationSchema` (which describes `POST`/`PATCH` bodies,\n// not this read payload). The legacy `option`/`value` and\n// `variant_options`/`variant_option_values` aliases were retired in Phase E\n// (spec §12 step 18 / issue #182).\nexport const productVariantCombinationEntrySchema = z.object({\n attributes: variantOptionSchema,\n attribute_values: variantOptionValueSchema,\n});\n\n// Product variant with combinations schema\nexport const productVariantWithCombinationsSchema = productVariantSchema.extend(\n {\n combinations: z.array(productVariantCombinationEntrySchema).optional(),\n },\n);\n\n// Per-product attribute link value (e.g. a specific color/size choice)\nexport const attributeLinkValueSchema = z.object({\n key: z.string(),\n display: z.string(),\n swatch_type: z.enum([\"none\", \"color\", \"image\"]),\n swatch_value: z.string(),\n attribute_value_id: z.number().nullable(),\n});\n\n// Per-product attribute link (product_attributes on the API)\nexport const attributeLinkSchema = z.object({\n id: z.number(),\n position: z.number(),\n group: z.string().nullable(),\n is_visible: z.boolean(),\n is_variation: z.boolean(),\n attribute_id: z.number().nullable(),\n custom_name: z.string().nullable(),\n name: z.string(),\n values: z.array(attributeLinkValueSchema),\n});\nexport type AttributeLink = z.infer<typeof attributeLinkSchema>;\n\n// Product with variants schema\nexport const productWithVariantsSchema = productSchema.extend({\n variants: z.array(productVariantWithCombinationsSchema).optional(),\n});\n\n// Product schema extended with optional review_stats\nexport const productWithReviewStatsSchema = productSchema.extend({\n review_stats: productReviewStatsSchema.optional().nullable(),\n});\n\n// Product with variants + optional review_stats\nexport const productWithVariantsAndReviewStatsSchema =\n productWithVariantsSchema.extend({\n review_stats: productReviewStatsSchema.optional().nullable(),\n }) as unknown as z.ZodType<ProductWithVariants & ProductWithReviewStats>;\n\nexport interface ProductImage {\n url: string;\n design_id?: string;\n design_edit_url?: string;\n canva_asset_id?: string;\n created_at?: string;\n updated_at?: string;\n // Additional metadata fields\n alt?: string;\n caption?: string;\n sort_order?: number;\n is_primary?: boolean;\n}\n\n// Product Video interface\nexport interface ProductVideo {\n id: string; // Asset ID\n url: string; // Public video URL\n thumbnail_url?: string; // Video thumbnail\n duration?: number; // Duration in seconds\n width?: number; // Video width\n height?: number; // Video height\n file_size?: number; // File size in bytes\n status?: \"processing\" | \"active\" | \"failed\";\n}\n","import { z } from \"zod\";\nimport {\n idSchema,\n uuidSchema,\n emailSchema,\n timestampSchema,\n deletedAtSchema,\n} from \"./common\";\nimport { baseQueryParamsSchema } from \"./pagination\";\n\n// Review status enum (matches Prisma enum ReviewStatus)\nexport const reviewStatusSchema = z.enum([\n \"PENDING\",\n \"APPROVED\",\n \"REJECTED\",\n \"HIDDEN\",\n]);\nexport type ReviewStatus = z.infer<typeof reviewStatusSchema>;\n\n// Product review reply\nexport const productReviewReplySchema = z\n .object({\n id: uuidSchema,\n review_id: uuidSchema,\n content: z.string().min(1),\n author_id: uuidSchema,\n author_name: z.string().min(1),\n is_visible: z.boolean().default(true),\n })\n .extend(timestampSchema.shape)\n .extend(deletedAtSchema.shape);\n\nexport const createProductReviewReplySchema = productReviewReplySchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n deleted_at: true,\n});\n\nexport const updateProductReviewReplySchema = productReviewReplySchema\n .partial()\n .omit({ id: true, review_id: true, created_at: true });\n\n// Product review\nexport const productReviewSchema = z\n .object({\n id: uuidSchema,\n product_id: z.bigint(),\n product_name: z.string().min(1),\n variant_id: z.bigint().optional().nullable(),\n variant_name: z.string().optional().nullable(),\n order_id: z.bigint().optional().nullable(),\n order_number: z.bigint().optional().nullable(),\n user_id: uuidSchema.optional().nullable(),\n reviewer_name: z.string().min(1),\n reviewer_email: emailSchema,\n reviewer_avatar: z.string().url().optional().nullable(),\n is_verified_buyer: z.boolean().default(false),\n rating: z.int32().min(1).max(5),\n title: z.string().max(200).optional().nullable(),\n content: z.string().min(1),\n pros: z.array(z.string()).default([]),\n cons: z.array(z.string()).default([]),\n media: z.array(z.any()).default([]),\n status: reviewStatusSchema.default(\"PENDING\"),\n moderation_notes: z.string().optional().nullable(),\n approved_by: uuidSchema.optional().nullable(),\n approved_at: z.iso.datetime().optional().nullable(),\n rejected_reason: z.string().optional().nullable(),\n is_featured: z.boolean().default(false),\n is_pinned: z.boolean().default(false),\n display_order: z.int32().optional().nullable(),\n review_date: z.iso.datetime().optional().nullable(),\n })\n .extend(timestampSchema.shape)\n .extend(deletedAtSchema.shape);\n\nexport const createProductReviewSchema = productReviewSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n deleted_at: true,\n});\n\nexport const updateProductReviewSchema = productReviewSchema\n .partial()\n .omit({ id: true, created_at: true });\n\n// Product review with replies (hydrated relation)\nexport const productReviewWithRepliesSchema = productReviewSchema.extend({\n review_replies: z.array(productReviewReplySchema).optional(),\n});\n\n// Review statistics per product\nexport const productReviewStatsSchema = z.object({\n id: idSchema,\n product_id: z.bigint(),\n total_reviews: z.int32().default(0),\n verified_reviews: z.int32().default(0),\n reviews_with_media: z.int32().default(0),\n reviews_with_reply: z.int32().default(0),\n average_rating: z.float64().default(0),\n rating_1_count: z.int32().default(0),\n rating_2_count: z.int32().default(0),\n rating_3_count: z.int32().default(0),\n rating_4_count: z.int32().default(0),\n rating_5_count: z.int32().default(0),\n last_review_at: z.iso.datetime().optional().nullable(),\n last_calculated_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n});\n\n// Query filter schemas\nexport const productReviewFiltersSchema = baseQueryParamsSchema.extend({\n id: uuidSchema.optional(),\n product_id: z.bigint().optional(),\n user_id: uuidSchema.optional(),\n rating: z.int32().min(1).max(5).optional(),\n min_rating: z.int32().min(1).max(5).optional(),\n max_rating: z.int32().min(1).max(5).optional(),\n status: reviewStatusSchema.optional(),\n is_verified_buyer: z.boolean().optional(),\n reviewer_email: emailSchema.optional(),\n reviewer_name: z.string().optional(),\n has_media: z.boolean().optional(),\n include_replies: z.boolean().optional(),\n});\n\nexport const productReviewReplyFiltersSchema = baseQueryParamsSchema.extend({\n id: uuidSchema.optional(),\n review_id: uuidSchema.optional(),\n is_visible: z.boolean().optional(),\n author_id: uuidSchema.optional(),\n});\n\n// Types\nexport type ProductReview = z.infer<typeof productReviewSchema>;\nexport type CreateProductReview = z.infer<typeof createProductReviewSchema>;\nexport type UpdateProductReview = z.infer<typeof updateProductReviewSchema>;\nexport type ProductReviewWithReplies = z.infer<\n typeof productReviewWithRepliesSchema\n>;\nexport type ProductReviewReply = z.infer<typeof productReviewReplySchema>;\nexport type CreateProductReviewReply = z.infer<\n typeof createProductReviewReplySchema\n>;\nexport type UpdateProductReviewReply = z.infer<\n typeof updateProductReviewReplySchema\n>;\nexport type ProductReviewStats = z.infer<typeof productReviewStatsSchema>;\nexport type ProductReviewFilters = z.infer<typeof productReviewFiltersSchema>;\nexport type ProductReviewReplyFilters = z.infer<\n typeof productReviewReplyFiltersSchema\n>;\n","import { z } from \"zod\";\nimport { timestampSchema, sortOrderSchema } from \"./common\";\n\n// Pagination meta schema\nexport const paginationMetaSchema = z.object({\n total: z.uint32(),\n limit: z.int32().positive(),\n offset: z.uint32(),\n page: z.int32().positive(),\n totalPages: z.uint32(),\n hasNext: z.boolean(),\n hasPrev: z.boolean(),\n});\n\n// Generic paginated response schema\nexport const paginatedResponseSchema = <T extends z.ZodTypeAny>(\n itemSchema: T,\n) =>\n z.object({\n data: z.array(itemSchema),\n meta: paginationMetaSchema,\n });\n\n// Base query parameters schema\nexport const baseQueryParamsSchema = z.object({\n limit: z.int32().min(1).max(100).optional(),\n offset: z.uint32().optional(),\n search: z.string().optional(),\n sort_by: z.string().optional(),\n sort_order: sortOrderSchema.optional(),\n created_after: timestampSchema.optional(),\n created_before: timestampSchema.optional(),\n updated_after: timestampSchema.optional(),\n updated_before: timestampSchema.optional(),\n});\n\n// Base delete options schema\nexport const baseDeleteOptionsSchema = z.object({\n soft_delete: z.boolean().optional(),\n reason: z.string().optional(),\n force: z.boolean().optional(),\n});\n\n// Base delete result schema\nexport const baseDeleteResultSchema = z.object({\n success: z.boolean(),\n type: z.enum([\"soft\", \"hard\"]),\n message: z.string(),\n entity_id: z.union([z.number(), z.string()]),\n deleted_at: timestampSchema.optional(),\n});\n\n// Pagination defaults\nexport const PAGINATION_DEFAULTS = {\n LIMIT: 20,\n MAX_LIMIT: 100,\n MIN_LIMIT: 1,\n DEFAULT_OFFSET: 0,\n DEFAULT_ORDER: \"desc\" as const,\n} as const;\n\n// Inferred types\nexport type PaginationMeta = z.infer<typeof paginationMetaSchema>;\nexport type PaginatedResponse<T> = {\n data: T[];\n meta: PaginationMeta;\n};\nexport type BaseQueryParams = z.infer<typeof baseQueryParamsSchema>;\nexport type BaseDeleteOptions = z.infer<typeof baseDeleteOptionsSchema>;\nexport type BaseDeleteResult = z.infer<typeof baseDeleteResultSchema>;\n\n// Utility type for creating paginated API functions\nexport type PaginatedApiFunction<\n T,\n Q extends BaseQueryParams = BaseQueryParams,\n> = (query?: Q) => Promise<PaginatedResponse<T>>;\n\n// Utility type for creating single entity API functions\nexport type SingleEntityApiFunction<T, Q = any> = (\n query: Q,\n) => Promise<T | null>;\n\n// Utility type for create/update operations\nexport type MutationApiFunction<TData, TInput> = (\n input: TInput,\n) => Promise<TData>;\n\n// Utility type for delete operations\nexport type DeleteApiFunction<\n TResult extends BaseDeleteResult = BaseDeleteResult,\n> = (id: number, options?: BaseDeleteOptions) => Promise<TResult>;\n\n// Validation functions\nexport const validatePaginationMeta = (data: unknown) => {\n try {\n return paginationMetaSchema.parse(data);\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(z.prettifyError(error));\n }\n throw error;\n }\n};\n\n// Safe validation functions\nexport const safeParsePaginationMeta = (data: unknown) =>\n paginationMetaSchema.safeParse(data);\nexport const safeParseBaseQueryParams = (data: unknown) =>\n baseQueryParamsSchema.safeParse(data);\n","import type { OrderActorType } from \"./order-timeline\";\n\n/**\n * Inventory: stock states per variant and location, served to admin clients\n * under `stores/:storeRef/inventory` (contract:\n * ecomweb-project/archive/2026-09-15-inventory-purchase-orders/2026-09-15-inventory-contracts.md in the api repo).\n *\n * This SDK owns the vocabulary; the API pins it with\n * inventory-vocabulary.contract.spec.ts because the API cannot import the SDK.\n * Types only: the dashboard calls the admin routes through its own client.\n *\n * This module's vocabulary (`InventoryState`, `INVENTORY_STATES`, and the\n * related state lists below) is the set of ledger buckets a unit of stock can\n * sit in: available, committed, damaged, and so on. It is unrelated to\n * `InventoryStatus` in `./product-status`, which is a different, display-level\n * concept: a computed status (`in_stock` / `low_stock` / `out_of_stock` /\n * `backordered`) derived from a quantity threshold, with Vietnamese UI\n * labels. Do not wire a stock badge or filter to the wrong one.\n */\nexport const INVENTORY_STATES = [\n \"available\",\n \"committed\",\n \"damaged\",\n \"quality_control\",\n \"safety_stock\",\n \"other\",\n \"incoming\",\n] as const;\nexport type InventoryState = (typeof INVENTORY_STATES)[number];\n\n/** Shown together as \"Unavailable\". */\nexport const UNAVAILABLE_STATES = [\n \"damaged\",\n \"quality_control\",\n \"safety_stock\",\n \"other\",\n] as const satisfies readonly InventoryState[];\nexport type UnavailableState = (typeof UNAVAILABLE_STATES)[number];\n\n/** States a merchant may set, adjust or move between. `committed` and `incoming` are system-managed. */\nexport const ADJUSTABLE_STATES = [\n \"available\",\n \"damaged\",\n \"quality_control\",\n \"safety_stock\",\n \"other\",\n] as const satisfies readonly InventoryState[];\nexport type AdjustableState = (typeof ADJUSTABLE_STATES)[number];\n\n/** deny: checkout rejects when available is short. continue: available may go negative. */\nexport const INVENTORY_POLICIES = [\"deny\", \"continue\"] as const;\nexport type InventoryPolicy = (typeof INVENTORY_POLICIES)[number];\n\nexport const INVENTORY_ADJUSTMENT_REASONS = [\n // Reasons a merchant picks\n \"correction\",\n \"count\",\n \"received\",\n \"return_restock\",\n \"damaged\",\n \"theft_or_loss\",\n \"promotion_or_donation\",\n \"other\",\n // Reasons the system records\n \"initial_stock\",\n \"order_reserved\",\n \"order_fulfilled\",\n \"order_released\",\n \"order_restocked\",\n \"cancelled_not_restocked\",\n \"migration_backfill\",\n \"purchase_order_ordered\",\n \"purchase_order_edited\",\n \"purchase_order_cancelled\",\n \"purchase_order_closed\",\n] as const;\nexport type InventoryAdjustmentReason =\n (typeof INVENTORY_ADJUSTMENT_REASONS)[number];\n\nexport const MERCHANT_ADJUSTMENT_REASONS = [\n \"correction\",\n \"count\",\n \"received\",\n \"return_restock\",\n \"damaged\",\n \"theft_or_loss\",\n \"promotion_or_donation\",\n \"other\",\n] as const;\nexport type MerchantAdjustmentReason =\n (typeof MERCHANT_ADJUSTMENT_REASONS)[number];\n\n/** `code` values of inventory business errors. Localise from these, never from `message`. */\nexport const INVENTORY_ERROR_CODES = {\n /** 409. `details.items: InsufficientInventoryItem[]`. */\n INSUFFICIENT_INVENTORY: \"INSUFFICIENT_INVENTORY\",\n /** 409. `details.states: [{ variant_id, state, quantity }]`. */\n STATE_NEGATIVE: \"INVENTORY_STATE_NEGATIVE\",\n /** 404. `details.variant_ids: number[]`. */\n VARIANT_NOT_IN_STORE: \"INVENTORY_VARIANT_NOT_IN_STORE\",\n /** 400. `details.variant_ids: number[]`. */\n DUPLICATE_VARIANT: \"INVENTORY_DUPLICATE_VARIANT\",\n /** 409. `details: SetQuantitiesResponse`; the non-stale items WERE applied. */\n QUANTITY_STALE: \"INVENTORY_QUANTITY_STALE\",\n /** 400. More than 5,000 data rows. */\n IMPORT_TOO_LARGE: \"INVENTORY_IMPORT_TOO_LARGE\",\n /** 400. `details.missing_columns?: string[]`. */\n IMPORT_INVALID_FILE: \"INVENTORY_IMPORT_INVALID_FILE\",\n} as const;\nexport type InventoryErrorCode =\n (typeof INVENTORY_ERROR_CODES)[keyof typeof INVENTORY_ERROR_CODES];\n\n/** One entry of an `INSUFFICIENT_INVENTORY` error's `details.items`. */\nexport interface InsufficientInventoryItem {\n variant_id: number;\n requested: number;\n available: number;\n}\n\nexport interface InventoryQuantities {\n available: number;\n committed: number;\n damaged: number;\n quality_control: number;\n safety_stock: number;\n other: number;\n}\n\n/** What is physically held: everything except incoming. */\nexport function onHand(level: InventoryQuantities): number {\n return (\n level.available +\n level.committed +\n level.damaged +\n level.quality_control +\n level.safety_stock +\n level.other\n );\n}\n\n/**\n * Adds up the stock that cannot be sold: damaged, quality control, safety stock and other.\n *\n * @param level - the quantities of one variant at one location\n * @returns The total unavailable quantity\n */\nexport function unavailable(\n level: Pick<InventoryQuantities, UnavailableState>,\n): number {\n return (\n level.damaged + level.quality_control + level.safety_stock + level.other\n );\n}\n\n/** One row of `GET /inventory/levels`: a variant at a location. */\nexport interface InventoryLevelRow extends InventoryQuantities {\n variant_id: number;\n product_id: number;\n product_name: string;\n product_image: string | null;\n /** Option values joined with \" / \", null for a default-only product. */\n variant_title: string | null;\n /** product_variants.seller_sku */\n sku: string | null;\n location_id: number;\n track_inventory: boolean;\n inventory_policy: InventoryPolicy;\n unavailable: number;\n on_hand: number;\n incoming: number;\n /** ISO 8601. */\n updated_at: string;\n}\n\nexport interface StaleQuantity {\n variant_id: number;\n state: \"available\" | \"on_hand\";\n expected_quantity: number;\n current_quantity: number;\n}\n\nexport interface SetQuantitiesRequest {\n /** 1 to 250 items. */\n items: Array<{\n variant_id: number;\n state: \"available\" | \"on_hand\";\n quantity: number;\n /** Omit for last-write-wins; send the value you displayed to detect a concurrent edit. */\n expected_quantity?: number | null;\n }>;\n reason: MerchantAdjustmentReason;\n /** Max 500. */\n note?: string | null;\n /** Max 100. A replay returns `replayed: true` and writes nothing. */\n idempotency_key?: string | null;\n}\n\n/** 200 when `stale` is empty; otherwise the `details` of a 409 `INVENTORY_QUANTITY_STALE`. */\nexport interface SetQuantitiesResponse {\n applied: InventoryLevelRow[];\n stale: StaleQuantity[];\n replayed: boolean;\n}\n\nexport interface AdjustQuantitiesRequest {\n /** 1 to 250 items, `delta` never 0. */\n items: Array<{ variant_id: number; state: AdjustableState; delta: number }>;\n reason: MerchantAdjustmentReason;\n note?: string | null;\n idempotency_key?: string | null;\n}\n\nexport interface MoveQuantitiesRequest {\n /** 1 to 250 items, `from !== to`, `quantity > 0`. */\n items: Array<{\n variant_id: number;\n from: AdjustableState;\n to: AdjustableState;\n quantity: number;\n }>;\n /** Defaults to \"correction\". */\n reason?: MerchantAdjustmentReason;\n note?: string | null;\n idempotency_key?: string | null;\n}\n\nexport interface QuantitiesResponse {\n applied: InventoryLevelRow[];\n replayed: boolean;\n}\n\nexport interface InventoryActor {\n type: OrderActorType;\n id: string | null;\n name: string | null;\n}\n\n/** One adjustment group of `GET /inventory/variants/:variantId/history`, newest first. */\nexport interface InventoryHistoryEntry {\n id: number;\n /** ISO 8601. */\n created_at: string;\n reason: InventoryAdjustmentReason;\n note: string | null;\n actor: InventoryActor;\n /** `label` is the order code, or \"PO1042\". */\n reference: { type: \"order\" | \"purchase_order\"; id: number; label: string } | null;\n changes: Array<{ state: InventoryState; delta: number; quantity_after: number }>;\n}\n\nexport interface InventoryImportResponse {\n applied: number;\n unchanged: number;\n skipped: Array<{\n /** 1-based data row, header excluded. */\n row: number;\n variant_id: string | null;\n reason:\n | \"stale\"\n | \"not_found\"\n | \"invalid_quantity\"\n | \"missing_variant_id\"\n /** The second and later rows repeating a Variant ID; the first one applied. */\n | \"duplicate_variant_id\";\n current_on_hand: number | null;\n }>;\n}\n\nexport interface InventoryLocation {\n id: number;\n name: string;\n is_default: boolean;\n}\n","import { z } from \"zod\";\nimport {\n optionalTimestampSchema,\n urlSchema,\n positionOrderSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n} from \"./common\";\n\n/**\n * Category-related schemas based on Prisma models\n */\n\n// Category interface\nexport interface Category extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string | null;\n description: string | null;\n image_url: string | null;\n parent_id: Id | null;\n sort_order: number;\n is_active: boolean;\n external_cat_id: string | null;\n}\n\n// Category with children interface\nexport interface CategoryWithChildren extends Category {\n children?: CategoryWithChildren[];\n}\n\n// Category tree type\nexport type CategoryTree = CategoryWithChildren[];\n\n// Create category input type\nexport type CreateCategory = Omit<Category, \"id\" | keyof OptionalTimestamp>;\n\n// Update category input type\nexport type UpdateCategory = Partial<CreateCategory>;\n\n// Category main entity\nexport const categorySchema = z\n .object({\n id: idSchema,\n name: z.string().min(1),\n slug: z.string().optional().nullable(),\n description: z.string().optional().nullable(),\n image_url: urlSchema,\n parent_id: idSchema.optional().nullable(),\n sort_order: positionOrderSchema,\n is_active: z.boolean().default(true),\n external_cat_id: z.string().optional().nullable(),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Create category input\nexport const createCategorySchema = categorySchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update category input\nexport const updateCategorySchema = createCategorySchema.partial();\n\n// Category with children (using explicit interface)\nexport const categoryWithChildrenSchema = categorySchema.extend({\n children: z.array(z.lazy(() => categoryWithChildrenSchema)).optional(),\n}) as unknown as z.ZodType<CategoryWithChildren>;\n\n// Category tree structure\nexport const categoryTreeSchema = z.array(\n categoryWithChildrenSchema,\n) as unknown as z.ZodType<CategoryTree>;\n","import { z } from \"zod\";\nimport {\n optionalTimestampSchema,\n orderStatusSchema,\n fulfillmentStatusSchema,\n shippingStatusSchema,\n paymentStatusSchema,\n paymentMethodSchema,\n emailSchema,\n phoneSchema,\n moneySchema,\n uuidSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n OrderStatus,\n FulfillmentStatus,\n ShippingStatus,\n PaymentStatus,\n LegacyOrderStatus,\n PaymentMethod,\n} from \"./common\";\nimport type { OrderShipmentSummary } from \"./shipment\";\n\n/**\n * Order-related schemas based on Prisma models\n */\n\n/**\n * A promotion applied to an order or one of its items.\n *\n * `promotion_name` is resolved server-side from the promotions module and is\n * null when that lookup fails or the promotion was deleted — render the\n * amount without a name in that case, never a blank label.\n */\nexport interface AppliedPromotion {\n promotion_id: number;\n promotion_name?: string | null;\n /** Item-level rows carry a real amount; order-level rows are always null. */\n discount_amount?: number | null;\n shipping_discount?: number | null;\n}\n\n/**\n * Where an order came from. This SDK owns the vocabulary; the API pins it with\n * a contract test (collection rule_set precedent) because the API cannot import\n * the SDK — the SDK is a client OF the API, and depending on it would invert\n * that relationship.\n */\nexport const ORDER_SOURCES = [\"online\", \"pos\", \"phone\", \"admin\"] as const;\nexport type OrderSource = (typeof ORDER_SOURCES)[number];\n\n/**\n * What an admin may set on a keyed-in order. 'online' is deliberately absent:\n * only the two checkout routes can produce it, and they produce nothing else.\n */\nexport const ADMIN_ORDER_SOURCES = [\"pos\", \"phone\", \"admin\"] as const;\nexport type AdminOrderSource = (typeof ADMIN_ORDER_SOURCES)[number];\n\n/** The staff member who keyed an order in. Admin responses only. */\nexport interface OrderCreatedBy {\n id: string; // UUID\n name: string | null;\n email: string | null;\n}\n\n// Order interface\nexport interface Order extends OptionalTimestamp {\n id: Id;\n user_id: string | null; // UUID\n customer_name: string;\n customer_email: string | null; // null for a walk-in order with no email\n customer_phone: string;\n customer_avatar: string | null;\n // DEPRECATED: Legacy status field for backward compatibility\n status?: LegacyOrderStatus | string | null;\n // NEW: Separate status fields managed by state machines\n order_status: OrderStatus;\n fulfillment_status: FulfillmentStatus;\n shipping_status: ShippingStatus;\n payment_status: PaymentStatus;\n payment_method: PaymentMethod;\n subtotal: number;\n original_subtotal: number | null;\n shipping_fee: number;\n original_shipping_fee: number | null;\n shipping_discount: number | null;\n tax: number;\n discount: number;\n total: number;\n shipping_street: string;\n shipping_city: string;\n shipping_district: string | null;\n shipping_ward: string | null;\n shipping_postal_code: string | null;\n tracking_number: string | null;\n notes: string | null;\n order_number: Id;\n /**\n * The customer-facing identifier, e.g. \"#1042\" or \"DH-1042-26\". Built from\n * the store's configured order prefix/suffix (defaulting to \"#\") and frozen\n * at placement, so changing the setting never renames an existing order.\n *\n * This is the field to show customers and to look orders up by — the\n * equivalent of Shopify's Order.name. `order_number` is the underlying\n * sequence and should be treated as an implementation detail.\n */\n order_code: string;\n items?: OrderItem[];\n applied_promotions?: AppliedPromotion[];\n /** Snapshot from order_shippings; present when the API includes shipping. */\n shipping_method_name?: string | null;\n /** Display names resolved server-side from the shippings module. */\n shipping_city_name?: string | null;\n shipping_ward_name?: string | null;\n /** Carrier name chosen at checkout, when a carrier option was picked. */\n shipping_carrier?: string | null;\n /**\n * The buyer-facing shipment (carrier, tracking, events). Present on the\n * customer detail and guest lookup responses.\n */\n shipment?: OrderShipmentSummary | null;\n /**\n * Whether the buyer may still cancel this order. Present on the customer\n * detail and guest lookup responses.\n */\n can_cancel?: boolean;\n source: OrderSource;\n /**\n * The staff member who keyed this order in. Present on the detail\n * response only — resolving it is a profiles lookup per row, which the\n * list response omits to avoid an N+1. Null for shopper-placed orders.\n */\n created_by?: OrderCreatedBy | null;\n}\n\n// Order item interface\nexport interface OrderItem {\n id: Id;\n order_id: Id | null;\n product_id: Id | null;\n product_name: string;\n product_image: string | null;\n quantity: number;\n price: number;\n original_price: number | null; // Original price before promotions/discounts\n total: number;\n /** Total discount applied to this line. */\n discount?: number | null;\n applied_promotions?: AppliedPromotion[];\n variant_id: Id | null;\n variant_name: string | null;\n created_at: string | null; // ISO datetime string\n}\n\n// Order with items interface\nexport interface OrderWithItems extends Order {\n items?: OrderItem[];\n}\n\n// Customer order summary interface\nexport interface CustomerOrderSummary {\n customer_email: string;\n customer_name: string;\n total_orders: number;\n total_spent: number;\n last_order_date: string | null; // ISO datetime string\n}\n\n/**\n * Money fields the API always recomputes from the catalog, the promotion\n * engine and the shipping rules. They are accepted for backwards\n * compatibility but ignored — never rely on a value sent here.\n */\nexport type ServerComputedOrderAmounts =\n | \"subtotal\"\n | \"original_subtotal\"\n | \"shipping_fee\"\n | \"original_shipping_fee\"\n | \"shipping_discount\"\n | \"discount\"\n | \"total\";\n\n// Create order input type\n// Note: applied_promotions/shipping_*_name are response-only (computed/joined\n// server-side) and must never be accepted as write input — mirrors the\n// createOrderSchema/updateOrderSchema .omit() lists below.\nexport type CreateOrder = Omit<\n Order,\n | \"id\"\n | \"order_number\"\n | \"order_code\"\n | keyof OptionalTimestamp\n | \"applied_promotions\"\n | \"shipping_method_name\"\n | \"shipping_city_name\"\n | \"shipping_ward_name\"\n | \"shipping_carrier\"\n | \"shipment\"\n | \"can_cancel\"\n // Server-owned: 0 until store-level tax settings exist. Never write input.\n | \"tax\"\n | ServerComputedOrderAmounts\n // Response-only: resolved server-side. Never write input — the admin\n // write surface for source is AdminOrderSource, defined separately.\n | \"source\"\n | \"created_by\"\n> &\n Partial<Pick<Order, ServerComputedOrderAmounts>> & {\n /**\n * Which shipping method the shopper picked. Write-only: the API prices it\n * from the store's shipping rules and rejects a method with no available\n * rate for the address. Omit to let the server choose the best option.\n */\n shipping_method_id?: Id | null;\n shipping_rate_id?: Id | null;\n };\n\n// Update order input type\nexport type UpdateOrder = Partial<CreateOrder>;\n\n// Create order item input type\n// Note: discount/applied_promotions are response-only (computed server-side)\n// and must never be accepted as write input — mirrors createOrderItemSchema.\n// price/total are accepted but ignored: the API resolves the unit price from\n// the catalog so a client cannot choose what it pays.\nexport type CreateOrderItem = Omit<\n OrderItem,\n | \"id\"\n | \"created_at\"\n | \"discount\"\n | \"applied_promotions\"\n | \"price\"\n | \"total\"\n> &\n Partial<Pick<OrderItem, \"price\" | \"total\">>;\n\n// Update order item input type\nexport type UpdateOrderItem = Partial<Omit<CreateOrderItem, \"order_id\">>;\n\n// A promotion applied to an order or one of its items\nexport const appliedPromotionSchema = z.object({\n promotion_id: idSchema,\n promotion_name: z.string().optional().nullable(),\n discount_amount: moneySchema.optional().nullable(),\n shipping_discount: moneySchema.optional().nullable(),\n}) as unknown as z.ZodType<AppliedPromotion>;\n\n// Order item\nexport const orderItemSchema = z.object({\n id: idSchema,\n order_id: idSchema.optional().nullable(),\n product_id: idSchema.optional().nullable(),\n product_name: z.string().min(1),\n product_image: z.string().optional().nullable(),\n quantity: z.int32().min(1).default(1),\n price: moneySchema,\n original_price: moneySchema.optional().nullable(),\n total: moneySchema,\n discount: moneySchema.optional().nullable(),\n applied_promotions: z.array(appliedPromotionSchema).optional(),\n variant_id: idSchema.optional().nullable(),\n variant_name: z.string().optional().nullable(),\n created_at: z.iso.datetime().optional().nullable(),\n});\n\n// Order main entity\nexport const orderSchema = z\n .object({\n id: idSchema,\n user_id: uuidSchema.optional().nullable(),\n customer_name: z.string().min(1),\n customer_email: emailSchema.nullable(),\n customer_phone: phoneSchema,\n customer_avatar: z.string().optional().nullable(),\n // DEPRECATED: Legacy status field for backward compatibility\n status: z.string().optional().nullable(),\n // NEW: Separate status fields managed by state machines\n order_status: orderStatusSchema,\n fulfillment_status: fulfillmentStatusSchema,\n shipping_status: shippingStatusSchema,\n payment_status: paymentStatusSchema,\n payment_method: paymentMethodSchema.nullable().optional(),\n subtotal: moneySchema.default(0),\n original_subtotal: moneySchema.default(0),\n shipping_fee: moneySchema.default(0),\n original_shipping_fee: moneySchema.default(0),\n shipping_discount: moneySchema.default(0),\n tax: moneySchema.default(0),\n discount: moneySchema.default(0),\n total: moneySchema.default(0),\n shipping_street: z.string().min(1),\n shipping_city: z.string().min(1),\n shipping_district: z.string().optional().nullable(),\n shipping_ward: z.string().optional().nullable(),\n shipping_postal_code: z.string().optional().nullable(),\n tracking_number: z.string().optional().nullable(),\n notes: z.string().optional().nullable(),\n order_number: idSchema,\n order_code: z.string(),\n items: z.array(orderItemSchema).optional(),\n applied_promotions: z.array(appliedPromotionSchema).optional(),\n shipping_method_name: z.string().optional().nullable(),\n shipping_city_name: z.string().optional().nullable(),\n shipping_ward_name: z.string().optional().nullable(),\n source: z.enum(ORDER_SOURCES).default(\"online\"),\n created_by: z\n .object({\n id: uuidSchema,\n name: z.string().nullable(),\n email: z.string().nullable(),\n })\n .nullable()\n .optional(),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Create order schema\n// Note: applied_promotions/shipping_*_name are response-only (computed/joined\n// server-side) and must never be accepted as write input.\nexport const createOrderSchema = orderSchema\n .omit({\n id: true,\n order_number: true,\n order_code: true,\n created_at: true,\n updated_at: true,\n applied_promotions: true,\n shipping_method_name: true,\n shipping_city_name: true,\n shipping_ward_name: true,\n tax: true,\n source: true,\n created_by: true,\n })\n .extend({\n // Write-only: not part of the order response.\n shipping_method_id: idSchema.optional().nullable(),\n shipping_rate_id: idSchema.optional().nullable(),\n }) as unknown as z.ZodType<CreateOrder>;\n\n// Update order schema\nexport const updateOrderSchema = orderSchema\n .omit({\n id: true,\n order_number: true,\n order_code: true,\n created_at: true,\n updated_at: true,\n applied_promotions: true,\n shipping_method_name: true,\n shipping_city_name: true,\n shipping_ward_name: true,\n source: true,\n created_by: true,\n })\n .partial() as unknown as z.ZodType<UpdateOrder>;\n\n// Create order item schema\n// Note: discount/applied_promotions are response-only (computed server-side)\n// and must never be accepted as write input.\nexport const createOrderItemSchema = orderItemSchema\n .omit({\n id: true,\n created_at: true,\n discount: true,\n applied_promotions: true,\n })\n .partial({\n price: true,\n total: true,\n }) as unknown as z.ZodType<CreateOrderItem>;\n\n// Update order item schema\nexport const updateOrderItemSchema = orderItemSchema\n .omit({\n id: true,\n created_at: true,\n discount: true,\n applied_promotions: true,\n })\n .partial()\n .omit({\n order_id: true,\n }) as unknown as z.ZodType<UpdateOrderItem>;\n\n// Order with items schema\nexport const orderWithItemsSchema = orderSchema.extend({\n items: z.array(orderItemSchema).optional(),\n}) as unknown as z.ZodType<OrderWithItems>;\n\n// Customer order summary schema\nexport const customerOrderSummarySchema = z.object({\n customer_email: emailSchema,\n customer_name: z.string(),\n total_orders: z.int32(),\n total_spent: moneySchema,\n last_order_date: z.iso.datetime().optional().nullable(),\n}) as unknown as z.ZodType<CustomerOrderSummary>;\n","/**\n * The buyer-facing shipment summary carried on an order, plus its error codes.\n * The API builds it from the carrier booking; this is the wire shape only.\n */\nexport const SHIPMENT_STATUSES = [\n \"booked\",\n \"picked_up\",\n \"in_transit\",\n \"out_for_delivery\",\n \"delivered\",\n \"failed\",\n \"returned\",\n \"cancelled\",\n] as const;\nexport type ShipmentStatus = (typeof SHIPMENT_STATUSES)[number];\n\n/** One tracking event on a shipment. */\nexport interface OrderShipmentEvent {\n /** ISO 8601. */\n occurred_at: string;\n /** Carrier status text, ready to show. */\n label: string;\n location: string | null;\n}\n\n/** What a buyer sees of their shipment. */\nexport interface OrderShipmentSummary {\n carrier_name: string | null;\n carrier_logo_url: string | null;\n service_name: string | null;\n tracking_number: string | null;\n track_link: string | null;\n status: ShipmentStatus | null;\n events: OrderShipmentEvent[];\n}\n\n/** Error codes the order endpoints return for shipment-related refusals. */\nexport const ORDER_SHIPMENT_ERROR_CODES = {\n /** Cancelling is refused because a carrier shipment is already in progress. */\n CANCEL_BLOCKED_BY_SHIPMENT: \"ORDER_CANCEL_BLOCKED_BY_SHIPMENT\",\n} as const;\n","/**\n * The order timeline: status history plus internal staff comments, served to\n * admin clients by `GET stores/:storeRef/orders/:id/timeline`.\n *\n * The vocabulary is owned by `ecomweb-contracts/src/types/order-timeline.ts`;\n * this copy is kept in parity, and the API pins it in\n * `order-event-type-vocabulary.contract.spec.ts`. Types only: the dashboard calls the admin routes through its own\n * client.\n */\nexport const ORDER_EVENT_TYPES = [\n \"placed\",\n \"order_status_changed\",\n \"fulfillment_status_changed\",\n \"shipping_status_changed\",\n \"payment_status_changed\",\n \"tracking_number_updated\",\n \"shipment_booked\",\n \"shipment_cancelled\",\n \"shipment_failed\",\n] as const;\nexport type OrderEventType = (typeof ORDER_EVENT_TYPES)[number];\n\nexport const ORDER_ACTOR_TYPES = [\n \"staff\",\n \"customer\",\n \"api_key\",\n \"gateway\",\n \"system\",\n \"carrier\",\n] as const;\nexport type OrderActorType = (typeof ORDER_ACTOR_TYPES)[number];\n\nexport interface OrderTimelineActor {\n type: OrderActorType;\n /** Staff UUID, customer id, or API key id. Null for gateway, system, and guests. */\n id: string | null;\n /** Resolved display name, or null when unknown (a gateway reads `arguments.gateway`). */\n name: string | null;\n /**\n * The staff member's email, for showing a current staff member who has no\n * display name. Null for every other actor type, and for staff who have\n * left the store. Absent from APIs older than this field.\n */\n email?: string | null;\n}\n\nexport interface OrderTimelineEvent {\n kind: \"event\";\n id: string;\n event_type: OrderEventType;\n /**\n * Changed values only. Status and tracking events carry `{ from, to }`;\n * `placed` carries `{ source }`, plus `backfilled: true` for orders that\n * predate history tracking; gateway-attributed events add `gateway`.\n */\n arguments: Record<string, unknown> | null;\n reason: string | null;\n actor: OrderTimelineActor;\n /** ISO 8601. */\n created_at: string;\n}\n\nexport interface OrderTimelineCommentAuthor {\n id: string;\n name: string | null;\n email: string | null;\n /** Resolved from the staff member's profile; null when they have none. */\n avatar_url: string | null;\n}\n\nexport interface OrderTimelineComment {\n kind: \"comment\";\n id: string;\n /** Plain text. Never render as HTML. */\n body: string;\n author: OrderTimelineCommentAuthor;\n edited: boolean;\n /** Computed by the server for the requesting user; do not re-derive from a local clock. */\n can_edit: boolean;\n can_delete: boolean;\n /** ISO 8601. */\n created_at: string;\n}\n\nexport type OrderTimelineEntry = OrderTimelineEvent | OrderTimelineComment;\n\nexport interface OrderTimelineResponse {\n /** Newest first. */\n entries: OrderTimelineEntry[];\n /** True when more than 500 events or 500 comments exist; the oldest are omitted. */\n truncated: boolean;\n}\n\n/** What POST, PATCH, and DELETE on a comment return. Refetch the timeline after. */\nexport interface OrderCommentMutationResult {\n id: string;\n}\n","import { z } from \"zod\";\nimport { paginationMetaSchema } from \"./pagination\";\n\n// Promotion Enums\nexport const PromotionModeSchema = z.enum([\"DISCOUNT_CODE\", \"AUTOMATIC\"]);\nexport const PromotionTypeSchema = z.enum([\n \"PRODUCT_DISCOUNT\",\n \"CART_DISCOUNT\",\n \"FREE_SHIPPING\",\n \"FIXED_PRICE\",\n \"GIFT\",\n]);\nexport const DiscountMethodSchema = z.enum([\"PERCENTAGE\", \"FIXED_AMOUNT\"]);\nexport const ConditionTypeSchema = z.enum([\n \"PRODUCT\",\n \"CATEGORY\",\n \"VARIANT\",\n \"NONE\",\n]);\nexport const PromotionStatusSchema = z.enum([\n \"DRAFT\",\n \"ACTIVE\",\n \"EXPIRED\",\n \"DISABLED\",\n]);\n\n// Export enum values for runtime use\nexport const PromotionMode = {\n DISCOUNT_CODE: \"DISCOUNT_CODE\",\n AUTOMATIC: \"AUTOMATIC\",\n} as const;\n\nexport const PromotionType = {\n PRODUCT_DISCOUNT: \"PRODUCT_DISCOUNT\",\n CART_DISCOUNT: \"CART_DISCOUNT\",\n FREE_SHIPPING: \"FREE_SHIPPING\",\n FIXED_PRICE: \"FIXED_PRICE\",\n GIFT: \"GIFT\",\n} as const;\n\nexport const DiscountMethod = {\n PERCENTAGE: \"PERCENTAGE\",\n FIXED_AMOUNT: \"FIXED_AMOUNT\",\n} as const;\n\nexport const ConditionType = {\n PRODUCT: \"PRODUCT\",\n CATEGORY: \"CATEGORY\",\n VARIANT: \"VARIANT\",\n NONE: \"NONE\",\n} as const;\n\nexport const PromotionStatus = {\n DRAFT: \"DRAFT\",\n ACTIVE: \"ACTIVE\",\n EXPIRED: \"EXPIRED\",\n DISABLED: \"DISABLED\",\n} as const;\n\n// Export enum types\nexport type PromotionModeType =\n (typeof PromotionMode)[keyof typeof PromotionMode];\nexport type PromotionTypeType =\n (typeof PromotionType)[keyof typeof PromotionType];\nexport type DiscountMethodType =\n (typeof DiscountMethod)[keyof typeof DiscountMethod];\nexport type ConditionTypeType =\n (typeof ConditionType)[keyof typeof ConditionType];\nexport type PromotionStatusType =\n (typeof PromotionStatus)[keyof typeof PromotionStatus];\n\n// Core Promotion Schema\nexport const PromotionSchema = z.object({\n id: z.number().int().positive(),\n name: z.string().min(1).max(255),\n mode: PromotionModeSchema,\n code: z.string().min(1).max(50).optional(),\n description: z.string().max(1000).optional(),\n start_at: z.string().datetime(),\n end_at: z.string().datetime().optional(),\n status: PromotionStatusSchema,\n type: PromotionTypeSchema,\n condition_type: ConditionTypeSchema,\n target_ids: z.array(z.string().uuid()).optional(),\n min_amount: z.number().positive().optional(),\n min_quantity: z.number().int().positive().optional(),\n discount_method: DiscountMethodSchema.optional(),\n discount_value: z.number().nonnegative().optional(),\n max_discount_amount: z.number().nonnegative().optional(),\n fixed_price: z.number().nonnegative().optional(),\n gift_product_ids: z.array(z.string().uuid()),\n gift_quantity: z.number().int().positive().optional(),\n usage_limit: z.number().int().positive().optional(),\n usage_limit_per_user: z.number().int().positive().optional(),\n checkout_suggestion_enabled: z.boolean().optional(),\n created_at: z.string().datetime(),\n updated_at: z.string().datetime(),\n created_by: z.string().uuid().optional(),\n updated_by: z.string().uuid().optional(),\n});\n\n// Create Promotion Schema\nexport const CreatePromotionSchema = z.object({\n name: z.string().min(1, \"Tên khuyến mãi là bắt buộc\").max(255),\n mode: PromotionModeSchema,\n code: z.string().min(1).max(50).optional(),\n description: z.string().max(1000).optional(),\n start_at: z.iso.datetime(),\n end_at: z.iso.datetime().optional(),\n type: PromotionTypeSchema,\n condition_type: ConditionTypeSchema,\n target_ids: z\n .array(z.uuid())\n .optional()\n .superRefine((ids: any, ctx: any) => {\n const conditionType = ctx.parent?.condition_type;\n if (conditionType === \"NONE\") {\n return true; // Allow empty array for NONE condition\n }\n return ids && ids.length > 0;\n }),\n min_amount: z.number().positive().optional(),\n min_quantity: z.number().int().positive().optional(),\n discount_method: DiscountMethodSchema.optional(),\n discount_value: z.number().nonnegative().optional(),\n max_discount_amount: z.number().nonnegative().optional(),\n fixed_price: z.number().nonnegative().optional(),\n gift_product_ids: z.array(z.uuid()).optional(),\n gift_quantity: z.number().int().positive().optional(),\n usage_limit: z.number().int().positive().optional(),\n usage_limit_per_user: z.number().int().positive().optional(),\n checkout_suggestion_enabled: z.boolean().optional(),\n});\n\n// Update Promotion Schema\nexport const UpdatePromotionSchema = CreatePromotionSchema.partial().extend({\n status: PromotionStatusSchema.optional(),\n});\n\n// Promotion with calculated discount amount (for API responses)\nexport const PromotionWithDiscountSchema = PromotionSchema.extend({\n discount_amount: z.number().optional(),\n});\n\n// Promotion Statistics Schema\nexport const PromotionStatisticsSchema = z.object({\n total_promotions: z.number().int().nonnegative(),\n active_promotions: z.number().int().nonnegative(),\n draft_promotions: z.number().int().nonnegative(),\n expired_promotions: z.number().int().nonnegative(),\n disabled_promotions: z.number().int().nonnegative(),\n total_usage: z.number().int().nonnegative(),\n total_discount_amount: z.number().nonnegative(),\n top_promotions: z.array(PromotionSchema),\n});\n\n// Pagination Schema\nexport const PaginatedPromotionsResponseSchema = z.object({\n data: z.array(PromotionSchema),\n meta: paginationMetaSchema,\n});\n\n// Query Parameters Schema\nexport const PromotionQueryParamsSchema = z.object({\n limit: z.number().int().positive().optional(),\n offset: z.number().int().nonnegative().optional(),\n order: z.enum([\"asc\", \"desc\"]).optional(),\n sort: z\n .enum([\n \"name\",\n \"start_at\",\n \"end_at\",\n \"status\",\n \"type\",\n \"created_at\",\n \"updated_at\",\n ])\n .optional(),\n search: z.string().max(255).optional(),\n status: z.union([PromotionStatusSchema, z.literal(\"all\")]).optional(),\n type: z.union([PromotionTypeSchema, z.literal(\"all\")]).optional(),\n mode: z.union([PromotionModeSchema, z.literal(\"all\")]).optional(),\n});\n\n// Export types\nexport type Promotion = z.infer<typeof PromotionSchema>;\nexport type CreatePromotion = z.infer<typeof CreatePromotionSchema>;\nexport type UpdatePromotion = z.infer<typeof UpdatePromotionSchema>;\nexport type PromotionWithDiscount = z.infer<typeof PromotionWithDiscountSchema>;\nexport type PromotionStatistics = z.infer<typeof PromotionStatisticsSchema>;\nexport type PaginatedPromotionsResponse = z.infer<\n typeof PaginatedPromotionsResponseSchema\n>;\nexport type PromotionQueryParams = z.infer<typeof PromotionQueryParamsSchema>;\n\n// UI Constants\nexport const PROMOTION_MODE_LABELS: Record<PromotionModeType, string> = {\n DISCOUNT_CODE: \"Mã giảm giá\",\n AUTOMATIC: \"Tự động áp dụng\",\n};\n\nexport const PROMOTION_TYPE_LABELS: Record<PromotionTypeType, string> = {\n PRODUCT_DISCOUNT: \"Giảm giá sản phẩm\",\n CART_DISCOUNT: \"Giảm giá giỏ hàng\",\n FREE_SHIPPING: \"Miễn phí vận chuyển\",\n FIXED_PRICE: \"Giá cố định\",\n GIFT: \"Quà tặng\",\n};\n\nexport const DISCOUNT_METHOD_LABELS: Record<DiscountMethodType, string> = {\n PERCENTAGE: \"Phần trăm\",\n FIXED_AMOUNT: \"Số tiền cố định\",\n};\n\nexport const CONDITION_TYPE_LABELS: Record<ConditionTypeType, string> = {\n PRODUCT: \"Sản phẩm\",\n CATEGORY: \"Danh mục\",\n VARIANT: \"Biến thể\",\n NONE: \"Tất cả sản phẩm\",\n};\n\nexport const PROMOTION_STATUS_LABELS: Record<PromotionStatusType, string> = {\n DRAFT: \"Nháp\",\n ACTIVE: \"Đang hoạt động\",\n EXPIRED: \"Đã hết hạn\",\n DISABLED: \"Đã tắt\",\n};\n\nexport const PROMOTION_STATUS_COLORS: Record<PromotionStatusType, string> = {\n DRAFT: \"bg-gray-100 text-gray-800\",\n ACTIVE: \"bg-green-100 text-green-800\",\n EXPIRED: \"bg-red-100 text-red-800\",\n DISABLED: \"bg-yellow-100 text-yellow-800\",\n};\n\nexport const PROMOTION_TYPE_COLORS: Record<PromotionTypeType, string> = {\n PRODUCT_DISCOUNT: \"bg-blue-100 text-blue-800\",\n CART_DISCOUNT: \"bg-purple-100 text-purple-800\",\n FREE_SHIPPING: \"bg-green-100 text-green-800\",\n FIXED_PRICE: \"bg-orange-100 text-orange-800\",\n GIFT: \"bg-pink-100 text-pink-800\",\n};\n\nexport const PROMOTION_MODE_COLORS: Record<PromotionModeType, string> = {\n DISCOUNT_CODE: \"bg-indigo-100 text-indigo-800\",\n AUTOMATIC: \"bg-emerald-100 text-emerald-800\",\n};\n","import { z } from \"zod\";\nimport {\n optionalTimestampSchema,\n blogPostStatusSchema,\n slugSchema,\n colorSchema,\n urlSchema,\n emailSchema,\n positionOrderSchema,\n uuidSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n BlogPostStatus,\n} from \"./common\";\n\n/**\n * Blog-related schemas based on Prisma models\n */\n\n// Table of Contents item interface\nexport interface TocItem {\n id: string;\n level: number;\n textContent: string;\n pos: number;\n}\n\n// Table of Contents item schema\nexport const tocItemSchema = z.object({\n id: z.string(),\n level: z.number().int().min(1).max(6),\n textContent: z.string(),\n pos: z.number().int(),\n});\n\n// Blog category interface\nexport interface BlogCategory extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string;\n description: string | null;\n color: string | null;\n sort_order: number;\n}\n\n// Blog tag interface\nexport interface BlogTag extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string;\n}\n\n// Blog post interface\nexport interface BlogPost extends OptionalTimestamp {\n id: Id;\n title: string;\n slug: string;\n content: string | null;\n toc: TocItem[] | null;\n excerpt: string | null;\n featured_image_url: string | null;\n status: BlogPostStatus;\n is_featured: boolean;\n scheduled_at: string | null;\n published_at: string | null;\n author_id: string | null;\n view_count: number;\n reading_time: number;\n created_at: string;\n}\n\n// Blog comment interface\nexport interface BlogComment {\n id: Id;\n blog_post_id: Id | null;\n parent_comment_id: Id | null;\n author_name: string;\n /** Never on public reads (the API hides commenter emails); admin reads only. */\n author_email?: string;\n author_website: string | null;\n content: string;\n is_approved: boolean;\n created_at: string | null;\n}\n\n// Blog settings interface\nexport interface BlogSettings extends OptionalTimestamp {\n id: Id;\n is_enabled: boolean;\n blog_title: string;\n blog_description: string | null;\n posts_per_page: number;\n allow_comments: boolean;\n moderate_comments: boolean;\n show_author: boolean;\n show_reading_time: boolean;\n enable_rss: boolean;\n custom_css: string | null;\n}\n\n// Blog post category (many-to-many) interface\nexport interface BlogPostCategory {\n blog_post_id: Id;\n blog_category_id: Id;\n}\n\n// Blog post tag (many-to-many) interface\nexport interface BlogPostTag {\n blog_post_id: Id;\n blog_tag_id: Id;\n}\n\n// Blog category\nexport const blogCategorySchema = z\n .object({\n id: idSchema,\n name: z.string().min(1).max(100),\n slug: slugSchema.max(100),\n description: z.string().optional().nullable(),\n color: colorSchema,\n sort_order: positionOrderSchema,\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog tag\nexport const blogTagSchema = z\n .object({\n id: idSchema,\n name: z.string().min(1).max(50),\n slug: slugSchema.max(50),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog post\nexport const blogPostSchema = z\n .object({\n id: idSchema,\n title: z.string().min(1).max(255),\n slug: slugSchema.max(255),\n content: z.string().optional().nullable(),\n toc: z.array(tocItemSchema).optional().nullable(),\n excerpt: z.string().optional().nullable(),\n featured_image_url: urlSchema,\n status: blogPostStatusSchema.default(\"draft\"),\n is_featured: z.boolean().default(false),\n scheduled_at: z.iso.datetime().optional().nullable(),\n published_at: z.iso.datetime().optional().nullable(),\n author_id: uuidSchema.optional().nullable(),\n view_count: z.int32().default(0),\n reading_time: z.int32().default(0),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog comment\nexport const blogCommentSchema = z.object({\n id: idSchema,\n blog_post_id: idSchema.optional().nullable(),\n parent_comment_id: idSchema.optional().nullable(),\n author_name: z.string().min(1).max(100),\n // Optional on reads: the public comment list no longer returns it.\n author_email: emailSchema.optional(),\n author_website: z.url().max(255).optional().nullable(),\n content: z.string().min(1),\n is_approved: z.boolean().default(false),\n created_at: z.iso.datetime().optional().nullable(),\n});\n\n// Blog settings\nexport const blogSettingsSchema = z\n .object({\n id: idSchema,\n is_enabled: z.boolean().default(true),\n blog_title: z.string().max(255).default(\"Blog\"),\n blog_description: z.string().optional().nullable(),\n posts_per_page: z.int32().default(10),\n allow_comments: z.boolean().default(true),\n moderate_comments: z.boolean().default(true),\n show_author: z.boolean().default(true),\n show_reading_time: z.boolean().default(true),\n enable_rss: z.boolean().default(true),\n custom_css: z.string().optional().nullable(),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog post categories (many-to-many)\nexport const blogPostCategorySchema = z.object({\n blog_post_id: idSchema,\n blog_category_id: idSchema,\n});\n\n// Blog post tags (many-to-many)\nexport const blogPostTagSchema = z.object({\n blog_post_id: idSchema,\n blog_tag_id: idSchema,\n});\n\n// Create schemas\nexport const createBlogCategorySchema = blogCategorySchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\nexport const createBlogTagSchema = blogTagSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\nexport const createBlogPostSchema = blogPostSchema.omit({\n id: true,\n view_count: true,\n created_at: true,\n updated_at: true,\n});\n\n// Posting a comment still needs an email, even though reads omit it.\nexport const createBlogCommentSchema = blogCommentSchema\n .omit({\n id: true,\n created_at: true,\n })\n .extend({ author_email: emailSchema });\n\nexport const createBlogSettingsSchema = blogSettingsSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update schemas\nexport const updateBlogCategorySchema = createBlogCategorySchema.partial();\n\nexport const updateBlogTagSchema = createBlogTagSchema.partial();\n\nexport const updateBlogPostSchema = createBlogPostSchema.partial();\n\nexport const updateBlogCommentSchema = createBlogCommentSchema.partial().omit({\n blog_post_id: true,\n});\n\nexport const updateBlogSettingsSchema = createBlogSettingsSchema.partial();\n\n// Blog post with relations\nexport interface BlogPostWithRelations\n extends Omit<BlogPost, \"blog_categories\" | \"blog_tags\" | \"blog_comments\"> {\n blog_categories?: BlogCategory[];\n blog_tags?: BlogTag[];\n blog_comments?: BlogComment[];\n}\n\nexport const blogPostWithRelationsSchema = blogPostSchema.extend({\n blog_categories: z.array(blogCategorySchema).optional(),\n blog_tags: z.array(blogTagSchema).optional(),\n blog_comments: z.array(blogCommentSchema).optional(),\n}) as unknown as z.ZodType<BlogPostWithRelations>;\n\n// Blog comment with replies\nexport interface BlogCommentWithReplies extends Omit<BlogComment, \"replies\"> {\n replies?: BlogCommentWithReplies[];\n}\n\nconst blogCommentWithRepliesSchemaInner = z.lazy(() =>\n blogCommentSchema.extend({\n replies: z.array(blogCommentWithRepliesSchemaInner).optional(),\n }),\n) as z.ZodType<BlogCommentWithReplies>;\n\nexport const blogCommentWithRepliesSchema = blogCommentWithRepliesSchemaInner;\n\n// Create types\nexport type CreateBlogCategory = Omit<\n BlogCategory,\n \"id\" | keyof OptionalTimestamp\n>;\nexport type CreateBlogTag = Omit<BlogTag, \"id\" | keyof OptionalTimestamp>;\nexport type CreateBlogPost = Omit<\n BlogPost,\n \"id\" | \"view_count\" | keyof OptionalTimestamp\n>;\nexport type CreateBlogComment = Omit<\n BlogComment,\n \"id\" | \"created_at\" | \"author_email\"\n> & { author_email: string };\nexport type CreateBlogSettings = Omit<\n BlogSettings,\n \"id\" | keyof OptionalTimestamp\n>;\n\n// Update types\nexport type UpdateBlogCategory = Partial<CreateBlogCategory>;\nexport type UpdateBlogTag = Partial<CreateBlogTag>;\nexport type UpdateBlogPost = Partial<CreateBlogPost>;\nexport type UpdateBlogComment = Partial<\n Omit<CreateBlogComment, \"blog_post_id\">\n>;\nexport type UpdateBlogSettings = Partial<CreateBlogSettings>;\n","import { z } from \"zod\";\nimport {\n timestampSchema,\n slugSchema,\n positionOrderSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n} from \"./common\";\n\n/**\n * Content-related schemas based on Prisma models\n */\n\n// Content page interface\nexport interface ContentPage extends OptionalTimestamp {\n id: Id;\n title: string;\n content: string | null;\n is_published: boolean;\n page_type: string | null;\n sort_order: number;\n slug: string;\n}\n\n// Create content page input type\nexport type CreateContentPage = Omit<\n ContentPage,\n \"id\" | keyof OptionalTimestamp\n>;\n\n// Update content page input type\nexport type UpdateContentPage = Partial<CreateContentPage>;\n\n// Content page\nexport const contentPageSchema = z\n .object({\n id: idSchema,\n title: z.string().min(1),\n content: z.string().optional().nullable(),\n is_published: z.boolean().default(false),\n page_type: z.string().optional().nullable(),\n sort_order: positionOrderSchema,\n slug: slugSchema.max(255),\n })\n .extend(timestampSchema.shape);\n\n// Create content page schema\nexport const createContentPageSchema = contentPageSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update content page schema\nexport const updateContentPageSchema = contentPageSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial();\n","import { z } from \"zod\";\n\n/**\n * Theme settings: a theme declares its own settings (spec: schema-driven\n * themes §5.2), merchants fill in values, and the storefront reads them.\n * The types below are the authoring shape; `themeSchemaSchema` checks the same\n * shape at runtime (schemas uploaded by deploys, published by CI).\n */\n\n/** Hex only: theme colors are interpolated into a <style> tag. */\nexport const THEME_HEX_COLOR =\n /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;\n\nconst SETTING_ID = /^[a-z][a-z0-9_]*$/;\n\ntype Primitive = string | number | boolean;\n\nexport interface ThemeVisibleIf {\n readonly setting: string;\n readonly equals?: Primitive;\n readonly not_equals?: Primitive;\n readonly is_set?: boolean;\n}\n\ninterface SettingBase<T extends string> {\n readonly type: T;\n readonly id: string;\n readonly label: string;\n readonly info?: string;\n readonly visible_if?: ThemeVisibleIf;\n}\n\nexport type ThemeSetting =\n | (SettingBase<\"text\" | \"textarea\"> & {\n readonly default?: string;\n readonly placeholder?: string;\n })\n | (SettingBase<\"richtext\" | \"url\" | \"color\" | \"menu\"> & {\n readonly default?: string;\n })\n | SettingBase<\n | \"image_picker\"\n | \"collection\"\n | \"page\"\n | \"blog_post\"\n | \"blog_category\"\n | \"blog_tag\"\n | \"product\"\n >\n | (SettingBase<\"checkbox\"> & { readonly default?: boolean })\n | (SettingBase<\"number\"> & {\n readonly default?: number;\n readonly min?: number;\n readonly max?: number;\n })\n | (SettingBase<\"range\"> & {\n readonly min: number;\n readonly max: number;\n readonly step: number;\n readonly unit?: string;\n readonly default: number;\n })\n | (SettingBase<\"select\"> & {\n readonly options: readonly {\n readonly value: string;\n readonly label: string;\n }[];\n readonly default?: string;\n });\n\nexport type ThemeSettingType = ThemeSetting[\"type\"];\n\nexport interface ThemeDisplayItem {\n readonly type: \"header\" | \"paragraph\";\n readonly content: string;\n}\n\nexport type ThemeSchemaItem = ThemeSetting | ThemeDisplayItem;\n\nexport interface ThemeSchemaGroup {\n readonly name: string;\n readonly settings: readonly ThemeSchemaItem[];\n}\n\nexport type ThemeSchema = readonly ThemeSchemaGroup[];\n\nexport type ThemeValue = string | number | boolean;\nexport type ThemeValues = Record<string, ThemeValue | null>;\n\nexport interface ThemeValueError {\n key: string;\n message: string;\n}\n\ntype ValueOf<T extends ThemeSettingType> = T extends \"checkbox\"\n ? boolean\n : T extends \"number\" | \"range\"\n ? number\n : string;\n\ntype SettingsIn<S extends ThemeSchema> = Extract<\n S[number][\"settings\"][number],\n ThemeSetting\n>;\n\n/** The values a schema produces: settings with a default are never null. */\nexport type ThemeSettingsOf<S extends ThemeSchema> = {\n [K in SettingsIn<S> as K[\"id\"]]: K extends { readonly default: unknown }\n ? ValueOf<K[\"type\"]>\n : ValueOf<K[\"type\"]> | null;\n};\n\n// ─── Runtime schema ─────────────────────────────────────────────\n\nconst primitive = z.union([z.string(), z.number(), z.boolean()]);\n\nconst visibleIfSchema = z\n .object({\n setting: z.string().regex(SETTING_ID),\n equals: primitive.optional(),\n not_equals: primitive.optional(),\n is_set: z.boolean().optional(),\n })\n .refine(\n v =>\n [v.equals, v.not_equals, v.is_set].filter(x => x !== undefined).length ===\n 1,\n { message: \"visible_if needs exactly one of equals, not_equals, is_set\" }\n );\n\nconst base = {\n id: z.string().regex(SETTING_ID, \"setting ids are snake_case\"),\n label: z.string().min(1),\n info: z.string().optional(),\n visible_if: visibleIfSchema.optional(),\n};\n\nconst itemSchema = z.discriminatedUnion(\"type\", [\n z.object({\n ...base,\n type: z.literal(\"text\"),\n default: z.string().optional(),\n placeholder: z.string().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"textarea\"),\n default: z.string().optional(),\n placeholder: z.string().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"richtext\"),\n default: z.string().optional(),\n }),\n z.object({ ...base, type: z.literal(\"url\"), default: z.string().optional() }),\n z.object({\n ...base,\n type: z.literal(\"color\"),\n default: z.string().regex(THEME_HEX_COLOR).optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"menu\"),\n default: z.string().optional(),\n }),\n z.object({ ...base, type: z.literal(\"image_picker\") }),\n z.object({ ...base, type: z.literal(\"collection\") }),\n z.object({ ...base, type: z.literal(\"page\") }),\n z.object({ ...base, type: z.literal(\"blog_post\") }),\n z.object({ ...base, type: z.literal(\"blog_category\") }),\n z.object({ ...base, type: z.literal(\"blog_tag\") }),\n z.object({ ...base, type: z.literal(\"product\") }),\n z.object({\n ...base,\n type: z.literal(\"checkbox\"),\n default: z.boolean().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"number\"),\n default: z.number().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"range\"),\n min: z.number(),\n max: z.number(),\n step: z.number().positive(),\n unit: z.string().optional(),\n default: z.number(),\n }),\n z.object({\n ...base,\n type: z.literal(\"select\"),\n options: z\n .array(z.object({ value: z.string(), label: z.string().min(1) }))\n .min(1),\n default: z.string().optional(),\n }),\n z.object({ type: z.literal(\"header\"), content: z.string().min(1) }),\n z.object({ type: z.literal(\"paragraph\"), content: z.string().min(1) }),\n]);\n\nexport const themeSchemaSchema = z\n .array(z.object({ name: z.string().min(1), settings: z.array(itemSchema) }))\n .superRefine((groups, ctx) => {\n const settings = groups.flatMap(g => g.settings).filter(isSetting);\n const ids = new Set<string>();\n for (const s of settings) {\n if (ids.has(s.id)) {\n ctx.addIssue({\n code: \"custom\",\n message: `duplicate setting id \"${s.id}\"`,\n });\n }\n ids.add(s.id);\n }\n for (const s of settings) {\n if (\"default\" in s && s.default !== undefined && s.default !== \"\") {\n const problem = checkValue(s as ThemeSetting, s.default);\n if (problem) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default ${JSON.stringify(s.default)} ${problem}`,\n });\n }\n }\n if (s.visible_if && !ids.has(s.visible_if.setting)) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: visible_if names unknown setting \"${s.visible_if.setting}\"`,\n });\n }\n if (\n s.type === \"select\" &&\n s.default !== undefined &&\n !s.options.some(o => o.value === s.default)\n ) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default \"${s.default}\" is not one of its options`,\n });\n }\n if (s.type === \"range\") {\n if (s.min >= s.max) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: min must be below max`,\n });\n } else if (s.default < s.min || s.default > s.max) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default ${s.default} is outside ${s.min}–${s.max}`,\n });\n }\n }\n if (\n s.type === \"number\" &&\n s.default !== undefined &&\n ((s.min !== undefined && s.default < s.min) ||\n (s.max !== undefined && s.default > s.max))\n ) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default ${s.default} is outside its bounds`,\n });\n }\n }\n });\n\nfunction isSetting<T extends { type: string }>(\n item: T\n): item is Exclude<T, { type: \"header\" | \"paragraph\" }> {\n return item.type !== \"header\" && item.type !== \"paragraph\";\n}\n\n/**\n * Validates a schema from outside the code (CI upload, deploy upload). Throws\n * an Error whose message lists every problem, readable in a build log.\n */\nexport function parseThemeSchema(input: unknown): ThemeSchema {\n const result = themeSchemaSchema.safeParse(input);\n if (!result.success) {\n throw new Error(`Invalid theme schema:\\n${z.prettifyError(result.error)}`);\n }\n return result.data as ThemeSchema;\n}\n\n// ─── Values ─────────────────────────────────────────────────────\n\n/**\n * Lists every setting in a theme schema, across all groups, leaving out headers and other non-setting entries.\n *\n * @param schema - the theme schema\n * @returns The settings in schema order\n */\nexport function themeSettings(schema: ThemeSchema): ThemeSetting[] {\n return schema.flatMap(g => g.settings.filter(isSetting));\n}\n\n/**\n * Builds the default value of every setting in a theme schema.\n *\n * @param schema - the theme schema\n * @returns A map from setting id to its default, or `null` when a setting has none\n */\nexport function themeDefaults(schema: ThemeSchema): ThemeValues {\n const out: ThemeValues = {};\n for (const s of themeSettings(schema)) {\n out[s.id] = \"default\" in s && s.default !== undefined ? s.default : null;\n }\n return out;\n}\n\n/** Types whose empty string is a real value rather than \"unset\". */\nconst TEXT_TYPES = new Set<ThemeSettingType>([\"text\", \"textarea\", \"richtext\"]);\n\n/**\n * An absolute http(s) URL, or a path on this site (\"/x\", never \"//x\"). No\n * backslashes anywhere: browsers read \"/\\\\host\" as \"//host\".\n */\nconst SAFE_URL = /^(?:https?:\\/\\/[^\\s\\\\]+|\\/(?![/\\\\])[^\\s\\\\]*)$/i;\n\nfunction checkValue(setting: ThemeSetting, value: unknown): string | null {\n switch (setting.type) {\n case \"checkbox\":\n return typeof value === \"boolean\" ? null : \"must be true or false\";\n case \"number\":\n case \"range\": {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return \"must be a number\";\n }\n if (setting.min !== undefined && value < setting.min) {\n return `must be at least ${setting.min}`;\n }\n if (setting.max !== undefined && value > setting.max) {\n return `must be at most ${setting.max}`;\n }\n return null;\n }\n }\n if (typeof value !== \"string\") return \"must be text\";\n switch (setting.type) {\n case \"color\":\n return THEME_HEX_COLOR.test(value)\n ? null\n : \"must be a hex color such as #1a2b3c\";\n case \"url\":\n case \"image_picker\":\n return SAFE_URL.test(value)\n ? null\n : \"must be an http(s) URL or a path starting with /\";\n case \"select\":\n return setting.options.some(o => o.value === value)\n ? null\n : `must be one of ${setting.options.map(o => o.value).join(\", \")}`;\n default:\n return null;\n }\n}\n\n/**\n * Checks a set of saved theme values against a theme schema. Settings with no value are skipped.\n *\n * @param schema - the theme schema\n * @param input - the values to check, as an object keyed by setting id\n * @returns The accepted values and a list of per-setting errors\n */\nexport function validateThemeValues(\n schema: ThemeSchema,\n input: unknown\n): { values: Record<string, ThemeValue>; errors: ThemeValueError[] } {\n const raw =\n input && typeof input === \"object\" && !Array.isArray(input)\n ? (input as Record<string, unknown>)\n : {};\n const values: Record<string, ThemeValue> = {};\n const errors: ThemeValueError[] = [];\n for (const s of themeSettings(schema)) {\n const value = raw[s.id];\n if (value === undefined || value === null) continue;\n // A cleared text field is a value (it can blank out a default); for\n // every other type \"\" means the merchant left the setting unset.\n if (value === \"\" && !TEXT_TYPES.has(s.type)) continue;\n const problem = checkValue(s, value);\n if (problem) errors.push({ key: s.id, message: `${s.label} ${problem}` });\n else values[s.id] = value as ThemeValue;\n }\n return { values, errors };\n}\n\n/** Defaults under the valid values; invalid values fall back to defaults. */\nexport function resolveThemeSettings(\n schema: ThemeSchema,\n input: unknown\n): { settings: ThemeValues; errors: ThemeValueError[] } {\n const { values, errors } = validateThemeValues(schema, input);\n return { settings: { ...themeDefaults(schema), ...values }, errors };\n}\n\n/** \"Set\" means not null, not \"\" and not false. */\nexport function isSettingVisible(\n setting: ThemeSetting,\n values: ThemeValues\n): boolean {\n const rule = setting.visible_if;\n if (!rule) return true;\n const value = values[rule.setting] ?? null;\n if (rule.is_set !== undefined) {\n const isSet = value !== null && value !== \"\" && value !== false;\n return rule.is_set === isSet;\n }\n if (rule.equals !== undefined) return value === rule.equals;\n return value !== rule.not_equals;\n}\n\n/** The major of a release version (\"1.4.2\" → 1); null for anything else. */\nexport function themeMajor(version: string | null | undefined): number | null {\n const match = /^(\\d+)\\.\\d+\\.\\d+$/.exec(version ?? \"\");\n return match ? Number(match[1]) : null;\n}\n\n/**\n * How a theme's settings values move to a new major (theme majors spec):\n * declared as data in the new major's manifest, run in order by the API\n * when a merchant upgrades.\n */\nexport type ThemeMigrationStep =\n | { readonly op: \"rename\"; readonly from: string; readonly to: string }\n | { readonly op: \"remove\"; readonly key: string }\n | {\n readonly op: \"map\";\n readonly key: string;\n readonly values: Readonly<Record<string, ThemeValue>>;\n }\n | { readonly op: \"copy\"; readonly from: string; readonly to: string }\n | {\n readonly op: \"default\";\n readonly key: string;\n readonly value: ThemeValue;\n };\n\nexport interface ThemeMigration {\n /** The major these steps upgrade from: the new major minus one. */\n readonly from: number;\n readonly steps: readonly ThemeMigrationStep[];\n}\n\nexport interface ThemeMigrationReport {\n renamed: { from: string; to: string }[];\n removed: string[];\n mapped: { key: string; from: string; to: ThemeValue }[];\n copied: { from: string; to: string }[];\n defaulted: string[];\n}\n\nconst migrationValue = z.union([z.string(), z.number(), z.boolean()]);\nconst migrationKey = z.string().regex(SETTING_ID);\n\nexport const themeMigrationSchema = z\n .object({\n from: z.number().int().min(1),\n steps: z\n .array(\n z.discriminatedUnion(\"op\", [\n z\n .object({\n op: z.literal(\"rename\"),\n from: migrationKey,\n to: migrationKey,\n })\n .strict(),\n z.object({ op: z.literal(\"remove\"), key: migrationKey }).strict(),\n z\n .object({\n op: z.literal(\"map\"),\n key: migrationKey,\n values: z.record(z.string(), migrationValue),\n })\n .strict(),\n z\n .object({\n op: z.literal(\"copy\"),\n from: migrationKey,\n to: migrationKey,\n })\n .strict(),\n z\n .object({\n op: z.literal(\"default\"),\n key: migrationKey,\n value: migrationValue,\n })\n .strict(),\n ])\n )\n .max(500),\n })\n .strict();\n\n/**\n * Parses and validates a theme migration definition.\n *\n * @param input - the unparsed migration\n * @returns The validated migration; throws an `Error` listing the problems when it is invalid\n */\nexport function parseThemeMigration(input: unknown): ThemeMigration {\n const result = themeMigrationSchema.safeParse(input);\n if (!result.success) {\n const issues = result.error.issues\n .map(i => `${i.path.join(\".\") || \"(root)\"}: ${i.message}`)\n .join(\"; \");\n throw new Error(`Invalid theme migration: ${issues}`);\n }\n return result.data as ThemeMigration;\n}\n\nfunction present(values: Record<string, unknown>, key: string): boolean {\n return (\n Object.prototype.hasOwnProperty.call(values, key) &&\n values[key] !== undefined\n );\n}\n\n/** Runs the steps in order over a copy of `input`. */\nexport function applyThemeMigration(\n input: Record<string, unknown>,\n migration: ThemeMigration\n): { values: Record<string, unknown>; report: ThemeMigrationReport } {\n const values: Record<string, unknown> = { ...input };\n const report: ThemeMigrationReport = {\n renamed: [],\n removed: [],\n mapped: [],\n copied: [],\n defaulted: [],\n };\n for (const step of migration.steps) {\n switch (step.op) {\n case \"rename\":\n if (step.from === step.to || !present(values, step.from)) break;\n values[step.to] = values[step.from];\n delete values[step.from];\n report.renamed.push({ from: step.from, to: step.to });\n break;\n case \"remove\":\n if (!present(values, step.key)) break;\n delete values[step.key];\n report.removed.push(step.key);\n break;\n case \"map\": {\n const value = values[step.key];\n if (\n typeof value === \"string\" &&\n Object.prototype.hasOwnProperty.call(step.values, value)\n ) {\n values[step.key] = step.values[value];\n report.mapped.push({\n key: step.key,\n from: value,\n to: step.values[value],\n });\n }\n break;\n }\n case \"copy\":\n if (step.from === step.to || !present(values, step.from)) break;\n values[step.to] = values[step.from];\n report.copied.push({ from: step.from, to: step.to });\n break;\n case \"default\":\n if (present(values, step.key) && values[step.key] !== null) break;\n values[step.key] = step.value;\n report.defaulted.push(step.key);\n break;\n }\n }\n return { values, report };\n}\n","/**\n * Metafields and metaobjects: the type engine (spec 2026-10-05\n * metafields-metaobjects §5). Plain TypeScript with no imports and no I/O, so\n * it runs unchanged in the API, the dashboard and storefronts.\n *\n * ecomweb-api (src/modules/metafields/domain/metafield-engine.ts) and\n * ecomweb-dashboard (lib/metafields/engine.ts) keep VERBATIM copies of\n * everything below the marker line. To change the engine: edit it here, update\n * ENGINE_BODY_SHA256 in metafield-engine.body-hash.spec.ts, then re-copy the\n * body into both repos with the new hash in their headers.\n */\n// The body below is a verbatim, hash-checked copy, so lint exceptions live here:\n// UNSAFE_URL_CHARS matches control characters on purpose, to reject them in URLs.\n/* eslint-disable no-control-regex */\n// @engine-body\n\n// ─── Vocabulary ─────────────────────────────────────────────────\n\nexport const METAFIELD_OWNER_TYPES = [\n \"product\",\n \"variant\",\n \"collection\",\n \"customer\",\n \"order\",\n \"page\",\n \"blog_post\",\n \"location\",\n \"shop\",\n] as const;\nexport type MetafieldOwnerType = (typeof METAFIELD_OWNER_TYPES)[number];\n\nexport const METAFIELD_BASE_TYPES = [\n \"single_line_text\",\n \"multi_line_text\",\n \"rich_text\",\n \"email\",\n \"integer\",\n \"decimal\",\n \"date\",\n \"date_time\",\n \"url\",\n \"link\",\n \"weight\",\n \"volume\",\n \"dimension\",\n \"boolean\",\n \"color\",\n \"rating\",\n \"money\",\n \"language\",\n \"json\",\n \"file\",\n \"image\",\n \"video\",\n \"product\",\n \"variant\",\n \"collection\",\n \"page\",\n \"blog_post\",\n \"customer\",\n \"order\",\n \"metaobject_reference\",\n \"mixed_reference\",\n] as const;\nexport type MetafieldBaseType = (typeof METAFIELD_BASE_TYPES)[number];\nexport type MetafieldListType = `list.${MetafieldBaseType}`;\nexport type MetafieldType = MetafieldBaseType | MetafieldListType;\n\nconst BASE_TYPE_SET: ReadonlySet<string> = new Set(METAFIELD_BASE_TYPES);\n\nexport function isMetafieldType(value: unknown): value is MetafieldType {\n if (typeof value !== \"string\") return false;\n const base = value.startsWith(\"list.\") ? value.slice(5) : value;\n return BASE_TYPE_SET.has(base);\n}\n\nexport function isListType(type: MetafieldType): type is MetafieldListType {\n return type.startsWith(\"list.\");\n}\n\nexport function baseTypeOf(type: MetafieldType): MetafieldBaseType {\n return (isListType(type) ? type.slice(5) : type) as MetafieldBaseType;\n}\n\nexport type MetafieldTypeGroup =\n | \"text\"\n | \"media\"\n | \"reference\"\n | \"link\"\n | \"date_time\"\n | \"number\"\n | \"measurement\"\n | \"other\"\n | \"advanced\";\n\n/** Type picker groups in display order (spec §7.2). Labels are the consumer's. */\nexport const METAFIELD_TYPE_GROUPS: readonly {\n readonly group: MetafieldTypeGroup;\n readonly types: readonly MetafieldBaseType[];\n}[] = [\n {\n group: \"text\",\n types: [\"single_line_text\", \"multi_line_text\", \"rich_text\", \"email\"],\n },\n { group: \"media\", types: [\"file\", \"image\", \"video\"] },\n {\n group: \"reference\",\n types: [\n \"blog_post\",\n \"collection\",\n \"customer\",\n \"metaobject_reference\",\n \"order\",\n \"page\",\n \"product\",\n \"variant\",\n ],\n },\n { group: \"link\", types: [\"link\", \"url\"] },\n { group: \"date_time\", types: [\"date\", \"date_time\"] },\n { group: \"number\", types: [\"integer\", \"decimal\", \"rating\", \"money\"] },\n { group: \"measurement\", types: [\"weight\", \"volume\", \"dimension\"] },\n { group: \"other\", types: [\"boolean\", \"color\", \"language\"] },\n { group: \"advanced\", types: [\"json\", \"mixed_reference\"] },\n];\n\nexport const RESOURCE_REFERENCE_TYPES = [\n \"product\",\n \"variant\",\n \"collection\",\n \"page\",\n \"blog_post\",\n \"customer\",\n \"order\",\n] as const;\nexport const METAOBJECT_REFERENCE_TYPES = [\n \"metaobject_reference\",\n \"mixed_reference\",\n] as const;\nexport const MEDIA_TYPES = [\"file\", \"image\", \"video\"] as const;\n/** Never resolved outside the admin (spec §6.5). */\nexport const PRIVATE_REFERENCE_TYPES = [\"customer\", \"order\"] as const;\n\nexport const METAFIELD_LIMITS = {\n definitions_per_owner_type: 100,\n pinned_per_owner_type: 20,\n metaobject_definitions: 100,\n fields_per_metaobject: 40,\n filter_keys: 5,\n value_bytes: 65_536,\n list_items: 128,\n choices: 128,\n allowed_domains: 20,\n regex_length: 200,\n regex_value_length: 500,\n single_line_text_length: 5_000,\n multi_line_text_length: 65_000,\n link_text_length: 255,\n email_length: 254,\n name_length: 255,\n description_length: 5_000,\n mixed_reference_definitions_min: 2,\n mixed_reference_definitions_max: 10,\n} as const;\n\n// ─── Issues and results ─────────────────────────────────────────\n\nexport type MetafieldIssueCode =\n | \"blank\"\n | \"required\"\n | \"unknown_key\"\n | \"duplicate\"\n | \"immutable\"\n | \"not_allowed\"\n | \"invalid_type\"\n | \"invalid_format\"\n | \"too_short\"\n | \"too_long\"\n | \"too_small\"\n | \"too_big\"\n | \"too_large\"\n | \"pattern_mismatch\"\n | \"not_a_choice\"\n | \"precision_exceeded\"\n | \"domain_not_allowed\"\n | \"invalid_unit\"\n | \"scale_mismatch\"\n | \"currency_mismatch\"\n | \"list_too_short\"\n | \"list_too_long\"\n | \"invalid_node\"\n | \"unsafe_url\"\n | \"invalid_validation\"\n | \"unsafe_regex\";\n\n/** `path` is relative to the validated input: \"\", \"[2]\", \"[2].amount\", \"fields[0].type\". */\nexport interface MetafieldIssue {\n path: string;\n code: MetafieldIssueCode;\n message: string;\n}\n\n/** `errors` and `value` are optional-undefined on the other arm so both read cleanly without strictNullChecks. */\nexport type EngineResult<T> =\n | { ok: true; value: T; errors?: undefined }\n | { ok: false; errors: MetafieldIssue[]; value?: undefined };\n\nfunction issue(\n path: string,\n code: MetafieldIssueCode,\n message: string\n): MetafieldIssue {\n return { path, code, message };\n}\n\nfunction ok<T>(value: T): EngineResult<T> {\n return { ok: true, value };\n}\n\nfunction fail<T = never>(\n path: string,\n code: MetafieldIssueCode,\n message: string\n): EngineResult<T> {\n return { ok: false, errors: [issue(path, code, message)] };\n}\n\nfunction joinPath(base: string, segment: string | number): string {\n if (typeof segment === \"number\") return `${base}[${segment}]`;\n return base ? `${base}.${segment}` : segment;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasOwn(object: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(object, key);\n}\n\nfunction unknownKeys(\n object: Record<string, unknown>,\n allowed: readonly string[],\n path: string\n): MetafieldIssue[] {\n return Object.keys(object)\n .filter(key => !allowed.includes(key))\n .map(key => issue(joinPath(path, key), \"unknown_key\", `unknown key \"${key}\"`));\n}\n\nfunction codePoints(text: string): number {\n return [...text].length;\n}\n\n// ─── Value shapes and validations ───────────────────────────────\n\nexport type FileKind = \"image\" | \"video\" | \"document\";\n\nexport interface MeasurementValue {\n value: string;\n unit: string;\n}\n\nexport interface LinkValue {\n url: string;\n text: string;\n}\n\nexport interface RatingValue {\n value: string;\n scale_min: string;\n scale_max: string;\n}\n\nexport interface MoneyValue {\n amount: string;\n currency_code: string;\n}\n\n/** integer: number; decimal: decimal string; date/date_time: canonical string; measurements: MeasurementValue. */\nexport type MetafieldBound = number | string | MeasurementValue;\n\n/** Canonical validations, as validateValidations returns them (spec §5.2). */\nexport interface MetafieldValidations {\n min_length?: number;\n max_length?: number;\n regex?: string;\n choices?: string[];\n min?: MetafieldBound;\n max?: MetafieldBound;\n max_precision?: number;\n allowed_domains?: string[];\n scale_min?: string;\n scale_max?: string;\n file_types?: FileKind[];\n metaobject_definition_id?: string;\n metaobject_definition_ids?: string[];\n list_min?: number;\n list_max?: number;\n}\n\n/** Store facts a value check needs. The engine never looks anything up. */\nexport interface MetafieldContext {\n currency_code: string;\n}\n\n// ─── Keys, handles and identifiers ──────────────────────────────\n\nexport const METAFIELD_KEY_PATTERN = /^[a-z0-9_]{2,64}$/;\nexport const METAOBJECT_TYPE_PATTERN = /^[a-z0-9_-]{2,64}$/;\nexport const ENTRY_HANDLE_PATTERN = /^[a-z0-9-]{1,255}$/;\n\n/** Strips accents; NFD does not decompose đ, so it is mapped by hand. */\nfunction asciiFold(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/\\u0111/g, \"d\")\n .replace(/\\u0110/g, \"D\");\n}\n\nfunction slugify(text: string, separator: string, max: number): string {\n const edge = new RegExp(`^${separator}+|${separator}+$`, \"g\");\n return asciiFold(text)\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, separator)\n .replace(edge, \"\")\n .slice(0, max)\n .replace(edge, \"\");\n}\n\n/** \"Đánh giá khách hàng\" → \"danh_gia_khach_hang\". \"\" when nothing usable remains. */\nexport function toMetafieldKey(text: string): string {\n return slugify(text, \"_\", 64);\n}\n\n/** \"Lan Anh – Hà Nội\" → \"lan-anh-ha-noi\". \"\" when nothing usable remains. */\nexport function toEntryHandle(text: string): string {\n const handle = slugify(text, \"-\", 255);\n return RESERVED_KEYS.includes(handle) ? \"\" : handle;\n}\n\n/** True for a well-formed entry handle that is not a reserved name. */\nexport function isValidEntryHandle(handle: string): boolean {\n return ENTRY_HANDLE_PATTERN.test(handle) && !RESERVED_KEYS.includes(handle);\n}\n\nexport function metafieldIdentifier(namespace: string, key: string): string {\n return `${namespace}.${key}`;\n}\n\n/** Names that collide with Object.prototype members; never valid as a key. */\nconst RESERVED_KEYS: readonly string[] = [\"__proto__\", \"constructor\", \"prototype\"];\n\nexport function parseMetafieldIdentifier(\n identifier: string\n): { namespace: string; key: string } | null {\n const parts = identifier.split(\".\");\n if (parts.length !== 2) return null;\n const [namespace, key] = parts;\n if (!METAFIELD_KEY_PATTERN.test(namespace) || !METAFIELD_KEY_PATTERN.test(key)) {\n return null;\n }\n if (RESERVED_KEYS.includes(namespace) || RESERVED_KEYS.includes(key)) return null;\n return { namespace, key };\n}\n\n// ─── Values: scalars ────────────────────────────────────────────\n\ntype Checker = (\n value: unknown,\n validations: MetafieldValidations,\n ctx: MetafieldContext,\n path: string\n) => EngineResult<unknown>;\n\nfunction matchesPattern(pattern: string, text: string): boolean {\n try {\n return new RegExp(\"^(?:\" + pattern + \")$\", \"u\").test(text);\n } catch {\n return false;\n }\n}\n\nfunction textChecker(limit: number, singleLine: boolean): Checker {\n return (value, v, _ctx, path) => {\n if (typeof value !== \"string\") return fail(path, \"invalid_type\", \"must be text\");\n if (singleLine && /[\\r\\n]/.test(value)) {\n return fail(path, \"invalid_format\", \"must be a single line\");\n }\n const length = codePoints(value);\n const cap = v.regex !== undefined ? Math.min(limit, METAFIELD_LIMITS.regex_value_length) : limit;\n const max = Math.min(cap, v.max_length ?? cap);\n if (length > max) return fail(path, \"too_long\", `must be at most ${max} characters`);\n if (v.min_length !== undefined && length < v.min_length) {\n return fail(path, \"too_short\", `must be at least ${v.min_length} characters`);\n }\n if (v.regex !== undefined && !matchesPattern(v.regex, value)) {\n return fail(path, \"pattern_mismatch\", \"does not match the required pattern\");\n }\n if (v.choices !== undefined && !v.choices.includes(value)) {\n return fail(path, \"not_a_choice\", `must be one of: ${v.choices.join(\", \")}`);\n }\n return ok(value);\n };\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst checkEmail: Checker = (value, _v, _ctx, path) => {\n if (typeof value !== \"string\") return fail(path, \"invalid_type\", \"must be text\");\n const email = value.trim().toLowerCase();\n if (email.length > METAFIELD_LIMITS.email_length || !EMAIL.test(email)) {\n return fail(path, \"invalid_format\", \"must be an email address\");\n }\n return ok(email);\n};\n\nconst checkInteger: Checker = (value, v, _ctx, path) => {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value)) {\n return fail(path, \"invalid_type\", \"must be a whole number\");\n }\n if (typeof v.min === \"number\" && value < v.min) {\n return fail(path, \"too_small\", `must be at least ${v.min}`);\n }\n if (typeof v.max === \"number\" && value > v.max) {\n return fail(path, \"too_big\", `must be at most ${v.max}`);\n }\n return ok(value === 0 ? 0 : value);\n};\n\nconst DECIMAL_INPUT = /^[+-]?\\d+(\\.\\d+)?$/;\n\n/**\n * A canonical decimal string (\"7.5\", \"-0.25\", \"0\"), or null when the input is not a plain decimal.\n * Numbers JS prints in exponent form (1e-7, 1e21) are rejected; send them as decimal strings.\n */\nexport function normalizeDecimal(input: unknown): string | null {\n let text: string;\n if (typeof input === \"number\") {\n if (!Number.isFinite(input)) return null;\n text = String(input);\n } else if (typeof input === \"string\") {\n text = input.trim();\n } else {\n return null;\n }\n if (text.length > 40 || !DECIMAL_INPUT.test(text)) return null;\n const negative = text.startsWith(\"-\");\n if (text[0] === \"-\" || text[0] === \"+\") text = text.slice(1);\n const [whole, fraction = \"\"] = text.split(\".\");\n const integer = whole.replace(/^0+(?=\\d)/, \"\");\n const decimals = fraction.replace(/0+$/, \"\");\n const magnitude = decimals ? `${integer}.${decimals}` : integer;\n return magnitude === \"0\" ? \"0\" : `${negative ? \"-\" : \"\"}${magnitude}`;\n}\n\n/** Compares two canonical decimal strings exactly. */\nexport function compareDecimal(a: string, b: string): -1 | 0 | 1 {\n const aNegative = a.startsWith(\"-\");\n const bNegative = b.startsWith(\"-\");\n if (aNegative !== bNegative) return aNegative ? -1 : 1;\n const sign = aNegative ? -1 : 1;\n const [aWhole, aFraction = \"\"] = (aNegative ? a.slice(1) : a).split(\".\");\n const [bWhole, bFraction = \"\"] = (bNegative ? b.slice(1) : b).split(\".\");\n let order: number;\n if (aWhole.length !== bWhole.length) {\n order = aWhole.length > bWhole.length ? 1 : -1;\n } else if (aWhole !== bWhole) {\n order = aWhole > bWhole ? 1 : -1;\n } else {\n const width = Math.max(aFraction.length, bFraction.length);\n const aPadded = aFraction.padEnd(width, \"0\");\n const bPadded = bFraction.padEnd(width, \"0\");\n order = aPadded === bPadded ? 0 : aPadded > bPadded ? 1 : -1;\n }\n // order * sign would give -0 for two equal negatives; return a clean 0.\n return order === 0 ? 0 : ((order * sign) as -1 | 1);\n}\n\nconst checkDecimal: Checker = (value, v, _ctx, path) => {\n const decimal = normalizeDecimal(value);\n if (decimal === null) return fail(path, \"invalid_type\", \"must be a decimal number\");\n const fraction = decimal.split(\".\")[1] ?? \"\";\n if (v.max_precision !== undefined && fraction.length > v.max_precision) {\n return fail(path, \"precision_exceeded\", `must have at most ${v.max_precision} decimal places`);\n }\n if (typeof v.min === \"string\" && compareDecimal(decimal, v.min) < 0) {\n return fail(path, \"too_small\", `must be at least ${v.min}`);\n }\n if (typeof v.max === \"string\" && compareDecimal(decimal, v.max) > 0) {\n return fail(path, \"too_big\", `must be at most ${v.max}`);\n }\n return ok(decimal);\n};\n\nconst checkBoolean: Checker = (value, _v, _ctx, path) =>\n typeof value === \"boolean\" ? ok(value) : fail(path, \"invalid_type\", \"must be true or false\");\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\n\nconst checkColor: Checker = (value, _v, _ctx, path) =>\n typeof value === \"string\" && COLOR.test(value)\n ? ok(value.toLowerCase())\n : fail(path, \"invalid_format\", \"must be a hex color such as #1a2b3c\");\n\n/** setUTCFullYear, unlike Date.UTC, does not map years 0–99 to 1900–1999. */\nfunction isCalendarDate(year: number, month: number, day: number): boolean {\n const date = new Date(0);\n date.setUTCFullYear(year, month - 1, day);\n return (\n date.getUTCFullYear() === year &&\n date.getUTCMonth() === month - 1 &&\n date.getUTCDate() === day\n );\n}\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** \"YYYY-MM-DD\" when the input is a real calendar date, else null. */\nexport function normalizeDate(input: unknown): string | null {\n if (typeof input !== \"string\") return null;\n const match = DATE.exec(input);\n if (!match || !isCalendarDate(+match[1], +match[2], +match[3])) return null;\n return input;\n}\n\nconst DATE_TIME =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d{1,3})?)?(Z|[+-](\\d{2}):(\\d{2}))$/;\n\n/** \"YYYY-MM-DDTHH:mm:ssZ\" in UTC, or null. Milliseconds are dropped. */\nexport function normalizeDateTime(input: unknown): string | null {\n if (typeof input !== \"string\") return null;\n const match = DATE_TIME.exec(input);\n if (!match || !isCalendarDate(+match[1], +match[2], +match[3])) return null;\n if (+match[4] > 23 || +match[5] > 59 || +(match[6] ?? \"0\") > 59) return null;\n if (match[8] !== undefined && (+match[8] > 23 || +match[9] > 59)) return null;\n const ms = Date.parse(input);\n if (Number.isNaN(ms)) return null;\n const iso = new Date(ms).toISOString();\n return /^\\d{4}-/.test(iso) ? `${iso.slice(0, 19)}Z` : null;\n}\n\nfunction dateChecker(normalize: (input: unknown) => string | null, format: string): Checker {\n return (value, v, _ctx, path) => {\n const normalized = normalize(value);\n if (normalized === null) return fail(path, \"invalid_format\", `must be ${format}`);\n if (typeof v.min === \"string\" && normalized < v.min) {\n return fail(path, \"too_small\", `must be on or after ${v.min}`);\n }\n if (typeof v.max === \"string\" && normalized > v.max) {\n return fail(path, \"too_big\", `must be on or before ${v.max}`);\n }\n return ok(normalized);\n };\n}\n\nconst MAX_URL_LENGTH = 2048;\n\n/** Control characters and the quote, angle, backtick and backslash characters never belong in a stored URL. */\nconst UNSAFE_URL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f\"<>`\\\\]/;\n\nfunction parseHttpUrl(value: unknown): URL | null {\n if (\n typeof value !== \"string\" ||\n value.length > MAX_URL_LENGTH ||\n /\\s/.test(value) ||\n UNSAFE_URL_CHARS.test(value)\n ) {\n return null;\n }\n try {\n const url = new URL(value);\n return url.protocol === \"http:\" || url.protocol === \"https:\" ? url : null;\n } catch {\n return null;\n }\n}\n\nfunction hostAllowed(url: URL, domains: readonly string[] | undefined): boolean {\n if (!domains) return true;\n const host = url.hostname.toLowerCase();\n return domains.some(domain => host === domain || host.endsWith(`.${domain}`));\n}\n\nconst checkUrl: Checker = (value, v, _ctx, path) => {\n const url = parseHttpUrl(value);\n if (!url) return fail(path, \"invalid_format\", \"must be an http(s) URL\");\n if (!hostAllowed(url, v.allowed_domains)) {\n return fail(path, \"domain_not_allowed\", `must be on ${(v.allowed_domains ?? []).join(\", \")}`);\n }\n return ok(value as string);\n};\n\nconst checkLink: Checker = (value, v, ctx, path) => {\n if (!isPlainObject(value)) {\n return fail(path, \"invalid_type\", \"must be an object with url and text\");\n }\n const extra = unknownKeys(value, [\"url\", \"text\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const url = checkUrl(value.url, v, ctx, joinPath(path, \"url\"));\n if (!url.ok) return url;\n const text = value.text ?? \"\";\n if (typeof text !== \"string\") return fail(joinPath(path, \"text\"), \"invalid_type\", \"must be text\");\n if (codePoints(text) > METAFIELD_LIMITS.link_text_length) {\n return fail(\n joinPath(path, \"text\"),\n \"too_long\",\n `must be at most ${METAFIELD_LIMITS.link_text_length} characters`\n );\n }\n return ok({ url: url.value as string, text });\n};\n\nconst LANGUAGE = /^([a-zA-Z]{2,3})(?:-([a-zA-Z]{4}))?(?:-([a-zA-Z]{2}|\\d{3}))?$/;\n\nconst checkLanguage: Checker = (value, _v, _ctx, path) => {\n const match = typeof value === \"string\" ? LANGUAGE.exec(value) : null;\n if (!match) {\n return fail(path, \"invalid_format\", \"must be a language tag such as vi or en-US\");\n }\n const script = match[2]\n ? match[2][0].toUpperCase() + match[2].slice(1).toLowerCase()\n : undefined;\n return ok([match[1].toLowerCase(), script, match[3]?.toUpperCase()].filter(Boolean).join(\"-\"));\n};\n\nconst checkJson: Checker = (value, _v, _ctx, path) => {\n let text: string | undefined;\n let nonFinite = false;\n try {\n text = JSON.stringify(value, (_key, item) => {\n if (typeof item === \"number\" && !Number.isFinite(item)) nonFinite = true;\n return item;\n });\n } catch {\n text = undefined;\n }\n if (nonFinite) return fail(path, \"invalid_format\", \"must not contain NaN or Infinity\");\n return text === undefined ? fail(path, \"invalid_type\", \"must be JSON\") : ok(JSON.parse(text));\n};\n\n// ─── Values: rich text ──────────────────────────────────────────\n\nexport interface RichTextText {\n type: \"text\";\n value: string;\n bold?: boolean;\n italic?: boolean;\n}\n\nexport interface RichTextLink {\n type: \"link\";\n url: string;\n title?: string;\n children: RichTextText[];\n}\n\nexport type RichTextInline = RichTextText | RichTextLink;\n\nexport interface RichTextParagraph {\n type: \"paragraph\";\n children: RichTextInline[];\n}\n\nexport interface RichTextHeading {\n type: \"heading\";\n level: 1 | 2 | 3 | 4 | 5 | 6;\n children: RichTextInline[];\n}\n\nexport interface RichTextListItem {\n type: \"list-item\";\n children: RichTextInline[];\n}\n\nexport interface RichTextList {\n type: \"list\";\n listType: \"ordered\" | \"unordered\";\n children: RichTextListItem[];\n}\n\nexport type RichTextBlock = RichTextParagraph | RichTextHeading | RichTextList;\n\nexport interface RichTextRoot {\n type: \"root\";\n children: RichTextBlock[];\n}\n\nexport type RichTextNode =\n | RichTextRoot\n | RichTextBlock\n | RichTextListItem\n | RichTextInline;\n\n/** A malformed document reports its first 100 problems, not thousands. */\nconst MAX_RICH_ERRORS = 100;\n\nconst MAILTO = /^mailto:[^\\s@?&#,]+@[^\\s@?&#,]+$/i;\n\nfunction richChildren<T>(\n children: unknown,\n path: string,\n errors: MetafieldIssue[],\n each: (child: unknown, path: string) => T | null\n): T[] {\n if (!Array.isArray(children)) {\n errors.push(issue(path, \"invalid_type\", \"must be a list of nodes\"));\n return [];\n }\n const out: T[] = [];\n for (let index = 0; index < children.length; index++) {\n if (errors.length >= MAX_RICH_ERRORS) break;\n const node = each(children[index], joinPath(path, index));\n if (node) out.push(node);\n }\n return out;\n}\n\nfunction richText(node: Record<string, unknown>, path: string, errors: MetafieldIssue[]): RichTextText | null {\n errors.push(...unknownKeys(node, [\"type\", \"value\", \"bold\", \"italic\"], path));\n if (typeof node.value !== \"string\") {\n errors.push(issue(joinPath(path, \"value\"), \"invalid_type\", \"must be text\"));\n return null;\n }\n for (const mark of [\"bold\", \"italic\"] as const) {\n if (node[mark] !== undefined && typeof node[mark] !== \"boolean\") {\n errors.push(issue(joinPath(path, mark), \"invalid_type\", \"must be true or false\"));\n }\n }\n const out: RichTextText = { type: \"text\", value: node.value };\n if (node.bold === true) out.bold = true;\n if (node.italic === true) out.italic = true;\n return out;\n}\n\nfunction richInline(\n node: unknown,\n path: string,\n errors: MetafieldIssue[]\n): RichTextInline | null {\n if (!isPlainObject(node)) {\n errors.push(issue(path, \"invalid_node\", \"must be a text or link node\"));\n return null;\n }\n if (node.type === \"text\") return richText(node, path, errors);\n if (node.type === \"link\") {\n errors.push(...unknownKeys(node, [\"type\", \"url\", \"title\", \"children\"], path));\n const url = typeof node.url === \"string\" ? node.url : \"\";\n if (!parseHttpUrl(url) && !(url.length <= MAX_URL_LENGTH && MAILTO.test(url) && !UNSAFE_URL_CHARS.test(url))) {\n errors.push(issue(joinPath(path, \"url\"), \"unsafe_url\", \"must be an http(s) or mailto link\"));\n }\n if (node.title !== undefined && typeof node.title !== \"string\") {\n errors.push(issue(joinPath(path, \"title\"), \"invalid_type\", \"must be text\"));\n }\n const children = richChildren(node.children, joinPath(path, \"children\"), errors, (child, at) => {\n if (isPlainObject(child) && child.type === \"text\") return richText(child, at, errors);\n errors.push(issue(joinPath(at, \"type\"), \"invalid_node\", \"a link may only contain text\"));\n return null;\n });\n const out: RichTextLink = { type: \"link\", url, children };\n if (typeof node.title === \"string\") out.title = node.title;\n return out;\n }\n errors.push(\n issue(joinPath(path, \"type\"), \"invalid_node\", `unexpected node type ${JSON.stringify(String(node.type).slice(0, 40))}`)\n );\n return null;\n}\n\nfunction richBlock(node: unknown, path: string, errors: MetafieldIssue[]): RichTextBlock | null {\n if (!isPlainObject(node)) {\n errors.push(issue(path, \"invalid_node\", \"must be a paragraph, heading or list node\"));\n return null;\n }\n const inline = (child: unknown, at: string) => richInline(child, at, errors);\n const children = (at: string, from: unknown) => richChildren(from, joinPath(at, \"children\"), errors, inline);\n switch (node.type) {\n case \"paragraph\":\n errors.push(...unknownKeys(node, [\"type\", \"children\"], path));\n return { type: \"paragraph\", children: children(path, node.children) };\n case \"heading\": {\n errors.push(...unknownKeys(node, [\"type\", \"level\", \"children\"], path));\n const level = node.level;\n if (typeof level !== \"number\" || !Number.isInteger(level) || level < 1 || level > 6) {\n errors.push(issue(joinPath(path, \"level\"), \"invalid_format\", \"must be 1 to 6\"));\n }\n return { type: \"heading\", level: level as RichTextHeading[\"level\"], children: children(path, node.children) };\n }\n case \"list\": {\n errors.push(...unknownKeys(node, [\"type\", \"listType\", \"children\"], path));\n if (node.listType !== \"ordered\" && node.listType !== \"unordered\") {\n errors.push(issue(joinPath(path, \"listType\"), \"invalid_format\", \"must be ordered or unordered\"));\n }\n const items = richChildren(node.children, joinPath(path, \"children\"), errors, (child, at) => {\n if (!isPlainObject(child) || child.type !== \"list-item\") {\n errors.push(issue(at, \"invalid_node\", \"must be a list-item node\"));\n return null;\n }\n errors.push(...unknownKeys(child, [\"type\", \"children\"], at));\n return { type: \"list-item\" as const, children: children(at, child.children) };\n });\n return { type: \"list\", listType: node.listType as RichTextList[\"listType\"], children: items };\n }\n default:\n errors.push(\n issue(joinPath(path, \"type\"), \"invalid_node\", `unexpected node type ${JSON.stringify(String(node.type).slice(0, 40))}`)\n );\n return null;\n }\n}\n\nconst MAX_RICH_TOP_NODES = 2000;\n\n/** Validates a rich-text tree (spec §5.3). There is no HTML anywhere in it. */\nexport function validateRichText(input: unknown, path = \"\"): EngineResult<RichTextRoot> {\n if (!isPlainObject(input) || input.type !== \"root\") {\n return fail(path, \"invalid_node\", \"must be a rich-text root node\");\n }\n if (Array.isArray(input.children) && input.children.length > MAX_RICH_TOP_NODES) {\n return fail(path, \"too_large\", \"has too many nodes\");\n }\n const errors = unknownKeys(input, [\"type\", \"children\"], path);\n const children = richChildren(input.children, joinPath(path, \"children\"), errors, (child, at) =>\n richBlock(child, at, errors)\n );\n return errors.length\n ? { ok: false, errors: errors.slice(0, MAX_RICH_ERRORS) }\n : ok({ type: \"root\", children });\n}\n\n/** Characters of text in the tree, links and list items included. */\nexport function richTextLength(root: RichTextRoot): number {\n let count = 0;\n const visit = (node: RichTextInline) => {\n if (node.type === \"text\") count += codePoints(node.value);\n else node.children.forEach(visit);\n };\n for (const block of root.children) {\n if (block.type === \"list\") block.children.forEach(item => item.children.forEach(visit));\n else block.children.forEach(visit);\n }\n return count;\n}\n\nconst checkRichText: Checker = (value, v, _ctx, path) => {\n const tree = validateRichText(value, path);\n if (!tree.ok) return tree;\n if (v.max_length !== undefined && richTextLength(tree.value) > v.max_length) {\n return fail(path, \"too_long\", `must be at most ${v.max_length} characters`);\n }\n return tree;\n};\n\n// ─── Values: measurements, money, media, references ─────────────\n\n/** Conversion factors to the first unit of each type (g, ml, mm). */\nexport const MEASUREMENT_UNITS = {\n weight: { g: 1, kg: 1000, oz: 28.349523125, lb: 453.59237 },\n volume: {\n ml: 1,\n cl: 10,\n l: 1000,\n m3: 1_000_000,\n fl_oz: 29.5735295625,\n pt: 473.176473,\n qt: 946.352946,\n gal: 3785.411784,\n },\n dimension: { mm: 1, cm: 10, m: 1000, in: 25.4, ft: 304.8, yd: 914.4 },\n} as const;\nexport type MeasurementType = keyof typeof MEASUREMENT_UNITS;\n\n/** The value in g, ml or mm, or null for an unknown unit. For bounds only: it uses floats. */\nexport function measurementInBaseUnit(\n measurement: MeasurementValue,\n type: MeasurementType\n): number | null {\n const units = MEASUREMENT_UNITS[type] as Record<string, number>;\n return hasOwn(units, measurement.unit) ? Number(measurement.value) * units[measurement.unit] : null;\n}\n\nfunction measurementChecker(type: MeasurementType): Checker {\n const unitList = Object.keys(MEASUREMENT_UNITS[type]).join(\", \");\n return (value, v, _ctx, path) => {\n if (!isPlainObject(value)) return fail(path, \"invalid_type\", \"must be an object with value and unit\");\n const extra = unknownKeys(value, [\"value\", \"unit\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const amount = normalizeDecimal(value.value);\n if (amount === null) return fail(joinPath(path, \"value\"), \"invalid_type\", \"must be a decimal number\");\n if (typeof value.unit !== \"string\" || !hasOwn(MEASUREMENT_UNITS[type], value.unit)) {\n return fail(joinPath(path, \"unit\"), \"invalid_unit\", `must be one of: ${unitList}`);\n }\n const measurement = { value: amount, unit: value.unit };\n const base = measurementInBaseUnit(measurement, type) as number;\n if (typeof v.min === \"object\" && v.min !== null) {\n const min = measurementInBaseUnit(v.min, type);\n if (min !== null && base < min) {\n return fail(path, \"too_small\", `must be at least ${v.min.value} ${v.min.unit}`);\n }\n }\n if (typeof v.max === \"object\" && v.max !== null) {\n const max = measurementInBaseUnit(v.max, type);\n if (max !== null && base > max) {\n return fail(path, \"too_big\", `must be at most ${v.max.value} ${v.max.unit}`);\n }\n }\n return ok(measurement);\n };\n}\n\nconst checkRating: Checker = (value, v, _ctx, path) => {\n if (!isPlainObject(value)) {\n return fail(path, \"invalid_type\", \"must be an object with value, scale_min and scale_max\");\n }\n const extra = unknownKeys(value, [\"value\", \"scale_min\", \"scale_max\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const parts: Record<\"value\" | \"scale_min\" | \"scale_max\", string> = { value: \"\", scale_min: \"\", scale_max: \"\" };\n for (const key of [\"value\", \"scale_min\", \"scale_max\"] as const) {\n const decimal = normalizeDecimal(value[key]);\n if (decimal === null) return fail(joinPath(path, key), \"invalid_type\", \"must be a decimal number\");\n parts[key] = decimal;\n }\n if (\n (v.scale_min !== undefined && compareDecimal(parts.scale_min, v.scale_min) !== 0) ||\n (v.scale_max !== undefined && compareDecimal(parts.scale_max, v.scale_max) !== 0)\n ) {\n return fail(path, \"scale_mismatch\", `must use the scale ${v.scale_min} to ${v.scale_max}`);\n }\n if (compareDecimal(parts.value, parts.scale_min) < 0) {\n return fail(joinPath(path, \"value\"), \"too_small\", `must be at least ${parts.scale_min}`);\n }\n if (compareDecimal(parts.value, parts.scale_max) > 0) {\n return fail(joinPath(path, \"value\"), \"too_big\", `must be at most ${parts.scale_max}`);\n }\n return ok(parts);\n};\n\nconst checkMoney: Checker = (value, _v, ctx, path) => {\n if (!isPlainObject(value)) return fail(path, \"invalid_type\", \"must be an object with amount and currency_code\");\n const extra = unknownKeys(value, [\"amount\", \"currency_code\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const amount = normalizeDecimal(value.amount);\n if (amount === null) return fail(joinPath(path, \"amount\"), \"invalid_type\", \"must be a decimal number\");\n const currency = typeof value.currency_code === \"string\" ? value.currency_code.toUpperCase() : \"\";\n const expected = ctx.currency_code.toUpperCase();\n if (currency !== expected) {\n return fail(joinPath(path, \"currency_code\"), \"currency_mismatch\", `must be ${expected}`);\n }\n return ok({ amount, currency_code: currency });\n};\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst checkAsset: Checker = (value, _v, _ctx, path) =>\n typeof value === \"string\" && UUID.test(value)\n ? ok(value.toLowerCase())\n : fail(path, \"invalid_format\", \"must be an asset id\");\n\n/** File kinds a media value may point at; null means any kind (or not a media type). */\nexport function allowedFileKinds(\n type: MetafieldType,\n validations: MetafieldValidations\n): readonly FileKind[] | null {\n switch (baseTypeOf(type)) {\n case \"image\":\n return [\"image\"];\n case \"video\":\n return [\"video\"];\n case \"file\":\n return validations.file_types ?? null;\n default:\n return null;\n }\n}\n\nconst ID = /^[1-9]\\d{0,18}$/;\nconst MAX_BIGINT = \"9223372036854775807\";\n\n/** A positive bigint id as a string, or null. */\nexport function normalizeId(input: unknown): string | null {\n if (typeof input === \"number\") {\n return Number.isSafeInteger(input) && input > 0 ? String(input) : null;\n }\n if (typeof input !== \"string\" || !ID.test(input)) return null;\n if (input.length === MAX_BIGINT.length && input > MAX_BIGINT) return null;\n return input;\n}\n\nconst checkId: Checker = (value, _v, _ctx, path) => {\n const id = normalizeId(value);\n return id === null ? fail(path, \"invalid_format\", \"must be a record id\") : ok(id);\n};\n\n// ─── Values: dispatch ───────────────────────────────────────────\n// Keep this section last: CHECKERS reads the checker constants above it.\n\nconst CHECKERS: Record<MetafieldBaseType, Checker> = {\n single_line_text: textChecker(METAFIELD_LIMITS.single_line_text_length, true),\n multi_line_text: textChecker(METAFIELD_LIMITS.multi_line_text_length, false),\n rich_text: checkRichText,\n email: checkEmail,\n integer: checkInteger,\n decimal: checkDecimal,\n date: dateChecker(normalizeDate, \"a date (YYYY-MM-DD)\"),\n date_time: dateChecker(normalizeDateTime, \"a date and time (YYYY-MM-DDTHH:mm:ssZ)\"),\n url: checkUrl,\n link: checkLink,\n weight: measurementChecker(\"weight\"),\n volume: measurementChecker(\"volume\"),\n dimension: measurementChecker(\"dimension\"),\n boolean: checkBoolean,\n color: checkColor,\n rating: checkRating,\n money: checkMoney,\n language: checkLanguage,\n json: checkJson,\n file: checkAsset,\n image: checkAsset,\n video: checkAsset,\n product: checkId,\n variant: checkId,\n collection: checkId,\n page: checkId,\n blog_post: checkId,\n customer: checkId,\n order: checkId,\n metaobject_reference: checkId,\n mixed_reference: checkId,\n};\n\n/**\n * Values a caller without a type should treat as \"clear this field\": null,\n * undefined, \"\" and []. Use isBlankValueFor when the field's type is known.\n */\nexport function isBlankValue(value: unknown): boolean {\n return (\n value === null ||\n value === undefined ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0)\n );\n}\n\nconst TEXT_BASE_TYPES: readonly MetafieldBaseType[] = [\"single_line_text\", \"multi_line_text\", \"email\", \"url\"];\n\n/** One value (a list item, for list types) of the given base type. */\nfunction isBlankScalar(base: MetafieldBaseType, value: unknown): boolean {\n if (isBlankValue(value)) return true;\n if (typeof value === \"string\") return TEXT_BASE_TYPES.includes(base) && value.trim() === \"\";\n return (\n base === \"rich_text\" &&\n isPlainObject(value) &&\n value.type === \"root\" &&\n Array.isArray(value.children) &&\n value.children.length === 0\n );\n}\n\n/**\n * Type-aware blank check: whitespace-only text is blank for text types, an\n * empty root is blank for rich_text, and neither is blank for json.\n */\nexport function isBlankValueFor(type: MetafieldType, value: unknown): boolean {\n if (!isMetafieldType(type)) return isBlankValue(value);\n if (isListType(type)) return isBlankValue(value);\n return isBlankScalar(baseTypeOf(type), value);\n}\n\nfunction checkList(\n base: MetafieldBaseType,\n checker: Checker,\n value: unknown,\n v: MetafieldValidations,\n ctx: MetafieldContext,\n path: string\n): EngineResult<unknown[]> {\n if (!Array.isArray(value)) return fail(path, \"invalid_type\", \"must be a list\");\n const max = Math.min(METAFIELD_LIMITS.list_items, v.list_max ?? METAFIELD_LIMITS.list_items);\n if (value.length > max) return fail(path, \"list_too_long\", `must have at most ${max} items`);\n if (v.list_min !== undefined && value.length < v.list_min) {\n return fail(path, \"list_too_short\", `must have at least ${v.list_min} items`);\n }\n const items: unknown[] = [];\n const errors: MetafieldIssue[] = [];\n for (let index = 0; index < value.length; index++) {\n const item: unknown = value[index];\n const at = joinPath(path, index);\n const result = isBlankScalar(base, item) ? fail(at, \"blank\", \"is empty\") : checker(item, v, ctx, at);\n if (result.ok) items.push(result.value);\n else errors.push(...result.errors);\n }\n return errors.length ? { ok: false, errors } : ok(items);\n}\n\n/** Postgres jsonb rejects NUL and lone surrogates; JSON.stringify escapes both as \\\\uXXXX. */\nfunction isStorableJson(json: string): boolean {\n for (const match of json.matchAll(/\\\\(?:u([0-9a-f]{4})|[^u])/g)) {\n const code = match[1] === undefined ? -1 : parseInt(match[1], 16);\n if (code === 0 || (code >= 0xd800 && code <= 0xdfff)) return false;\n }\n return true;\n}\n\nfunction byteLength(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\n/**\n * Validates one value against its type and its definition's (already\n * validated) validations, returning the canonical value. Blank values fail\n * with \"blank\": callers decide whether blank means \"delete\" or \"required\".\n */\nexport function validateMetafieldValue(\n type: MetafieldType,\n validations: MetafieldValidations,\n value: unknown,\n ctx: MetafieldContext,\n path = \"\"\n): EngineResult<unknown> {\n if (!isMetafieldType(type)) return fail(path, \"invalid_type\", \"is not a metafield type\");\n if (!isPlainObject(validations)) validations = {};\n if (isBlankValueFor(type, value)) return fail(path, \"blank\", \"is empty; send null to clear it\");\n if (isListType(type) && Array.isArray(value) && value.length > 4 * METAFIELD_LIMITS.list_items) {\n return fail(path, \"list_too_long\", `must have at most ${METAFIELD_LIMITS.list_items} items`);\n }\n const base = baseTypeOf(type);\n const checker = hasOwn(CHECKERS, base) ? CHECKERS[base] : undefined;\n if (!checker) return fail(path, \"invalid_type\", `type ${String(type).slice(0, 40)} is not supported`);\n const result = isListType(type)\n ? checkList(base, checker, value, validations, ctx, path)\n : checker(value, validations, ctx, path);\n if (!result.ok) return result;\n const json = JSON.stringify(result.value);\n if (!isStorableJson(json)) {\n return fail(path, \"invalid_format\", \"contains characters that cannot be stored\");\n }\n if (byteLength(json) > METAFIELD_LIMITS.value_bytes) {\n return fail(path, \"too_large\", `must be at most ${METAFIELD_LIMITS.value_bytes} bytes`);\n }\n return result;\n}\n\n// ─── Definitions: validations ───────────────────────────────────\n\nexport type MetafieldValidationKey = keyof MetafieldValidations;\n\nexport const VALIDATION_KEYS: Readonly<Record<MetafieldBaseType, readonly MetafieldValidationKey[]>> = {\n single_line_text: [\"min_length\", \"max_length\", \"regex\", \"choices\"],\n multi_line_text: [\"min_length\", \"max_length\"],\n rich_text: [\"max_length\"],\n email: [],\n integer: [\"min\", \"max\"],\n decimal: [\"min\", \"max\", \"max_precision\"],\n date: [\"min\", \"max\"],\n date_time: [\"min\", \"max\"],\n url: [\"allowed_domains\"],\n link: [\"allowed_domains\"],\n weight: [\"min\", \"max\"],\n volume: [\"min\", \"max\"],\n dimension: [\"min\", \"max\"],\n boolean: [],\n color: [],\n rating: [\"scale_min\", \"scale_max\"],\n money: [],\n language: [],\n json: [],\n file: [\"file_types\"],\n image: [],\n video: [],\n product: [],\n variant: [],\n collection: [],\n page: [],\n blog_post: [],\n customer: [],\n order: [],\n metaobject_reference: [\"metaobject_definition_id\"],\n mixed_reference: [\"metaobject_definition_ids\"],\n};\n\n/**\n * Restricts merchant regexes to a dialect whose work is bounded: no\n * backreferences or lookaround, nothing but \"?\" after a group, at most two\n * quantifiers (*, +, ?, {n,}, {n,m}; a lazy \"?\" is part of its quantifier,\n * exact {n} is free) and at most four alternatives. Deliberately conservative.\n */\nexport function isSafeRegex(pattern: string): boolean {\n if (/\\\\[1-9]|\\\\k</.test(pattern)) return false;\n if (/\\(\\?<?[=!]/.test(pattern)) return false;\n let quantifiers = 0;\n let bars = 0;\n let afterQuantifier = false;\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n const wasQuantifier = afterQuantifier;\n afterQuantifier = false;\n if (char === \"\\\\\") {\n const escaped = pattern[i + 1];\n i++;\n if ((escaped === \"u\" || escaped === \"p\" || escaped === \"P\") && pattern[i + 1] === \"{\") {\n const close = pattern.indexOf(\"}\", i + 1);\n i = close === -1 ? pattern.length : close;\n }\n continue;\n }\n if (char === \"[\") {\n i++;\n while (i < pattern.length && pattern[i] !== \"]\") {\n if (pattern[i] === \"\\\\\") i++;\n i++;\n }\n continue;\n }\n if (char === \"(\") {\n if (pattern[i + 1] === \"?\") i++;\n continue;\n }\n if (char === \")\") {\n const next = pattern[i + 1];\n if (next === \"*\" || next === \"+\") return false;\n if (next === \"{\" && /^\\{\\d+(,\\d*)?\\}/.test(pattern.slice(i + 1))) return false;\n continue;\n }\n if (char === \"|\") {\n bars++;\n } else if (char === \"*\" || char === \"+\" || char === \"?\") {\n if (!(char === \"?\" && wasQuantifier)) {\n quantifiers++;\n afterQuantifier = true;\n }\n } else if (char === \"{\") {\n const match = /^\\{\\d+(,\\d*)?\\}/.exec(pattern.slice(i));\n if (match) {\n if (match[1] !== undefined) quantifiers++;\n afterQuantifier = true;\n i += match[0].length - 1;\n }\n }\n }\n return quantifiers <= 2 && bars <= 4;\n}\n\nconst HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/;\nconst FILE_KINDS: readonly FileKind[] = [\"image\", \"video\", \"document\"];\n\nfunction normalizeBound(base: MetafieldBaseType, input: unknown): MetafieldBound | null {\n switch (base) {\n case \"integer\":\n return typeof input === \"number\" && Number.isSafeInteger(input) ? input : null;\n case \"decimal\":\n return normalizeDecimal(input);\n case \"date\":\n return normalizeDate(input);\n case \"date_time\":\n return normalizeDateTime(input);\n case \"weight\":\n case \"volume\":\n case \"dimension\": {\n if (!isPlainObject(input) || Object.keys(input).some(k => k !== \"value\" && k !== \"unit\")) return null;\n const amount = normalizeDecimal(input.value);\n if (amount === null || typeof input.unit !== \"string\" || !hasOwn(MEASUREMENT_UNITS[base], input.unit)) {\n return null;\n }\n return { value: amount, unit: input.unit };\n }\n default:\n return null;\n }\n}\n\nfunction compareBound(base: MetafieldBaseType, a: MetafieldBound, b: MetafieldBound): number {\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (typeof a === \"object\" && typeof b === \"object\") {\n const type = base as MeasurementType;\n return (measurementInBaseUnit(a, type) ?? 0) - (measurementInBaseUnit(b, type) ?? 0);\n }\n if (base === \"decimal\") return compareDecimal(a as string, b as string);\n return (a as string) < (b as string) ? -1 : (a as string) > (b as string) ? 1 : 0;\n}\n\nfunction isWholeNumber(value: unknown, min: number, max: number): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max;\n}\n\n/**\n * Validates and canonicalises a definition's `validations` for its type\n * (spec §5.2). Unknown keys, unsafe regexes and contradictory bounds fail.\n */\nexport function validateValidations(\n type: MetafieldType,\n input: unknown,\n path = \"validations\"\n): EngineResult<MetafieldValidations> {\n if (!isMetafieldType(type)) return fail(path, \"invalid_type\", \"is not a metafield type\");\n const raw = input === undefined || input === null ? {} : input;\n if (!isPlainObject(raw)) return fail(path, \"invalid_type\", \"must be an object\");\n const base = baseTypeOf(type);\n const allowed: MetafieldValidationKey[] = [\n ...VALIDATION_KEYS[base],\n ...(isListType(type) ? ([\"list_min\", \"list_max\"] as const) : []),\n ];\n const errors = unknownKeys(raw, allowed, path);\n const out: MetafieldValidations = {};\n const has = (key: MetafieldValidationKey) => allowed.includes(key) && raw[key] !== undefined;\n const bad = (key: MetafieldValidationKey, message: string, code: MetafieldIssueCode = \"invalid_validation\") =>\n errors.push(issue(joinPath(path, key), code, message));\n\n for (const key of [\"min_length\", \"max_length\"] as const) {\n if (!has(key)) continue;\n const cap =\n base === \"single_line_text\" ? METAFIELD_LIMITS.single_line_text_length : METAFIELD_LIMITS.multi_line_text_length;\n if (isWholeNumber(raw[key], 0, cap)) out[key] = raw[key] as number;\n else bad(key, \"must be a whole number of 0 or more\");\n }\n\n if (has(\"regex\")) {\n const pattern = raw.regex;\n if (typeof pattern !== \"string\" || pattern.length === 0 || pattern.length > METAFIELD_LIMITS.regex_length) {\n bad(\"regex\", `must be 1 to ${METAFIELD_LIMITS.regex_length} characters`);\n } else if (!isSafeRegex(pattern)) {\n bad(\"regex\", \"is too complex: no backreferences or lookaround, no repetition after a group, at most 2 optional or repeated parts and 4 alternatives\", \"unsafe_regex\");\n } else {\n try {\n new RegExp(pattern, \"u\");\n out.regex = pattern;\n } catch {\n bad(\"regex\", \"is not a valid pattern\");\n }\n }\n }\n\n if (has(\"regex\")) {\n const limit = METAFIELD_LIMITS.regex_value_length;\n if (out.max_length !== undefined && out.max_length > limit) {\n bad(\"max_length\", `must be at most ${limit} when a pattern applies`);\n } else if (out.regex !== undefined && out.max_length === undefined) {\n out.max_length = limit;\n }\n }\n\n if (out.min_length !== undefined && out.max_length !== undefined && out.min_length > out.max_length) {\n bad(\"min_length\", \"must not exceed max_length\");\n }\n\n if (has(\"choices\")) {\n const choices = raw.choices;\n if (!Array.isArray(choices) || choices.length === 0 || choices.length > METAFIELD_LIMITS.choices) {\n bad(\"choices\", `must list 1 to ${METAFIELD_LIMITS.choices} values`);\n } else if (\n choices.some(\n c =>\n typeof c !== \"string\" ||\n c === \"\" ||\n /[\\r\\n]/.test(c) ||\n codePoints(c) > METAFIELD_LIMITS.single_line_text_length\n )\n ) {\n bad(\"choices\", \"must be non-empty single-line text\");\n } else if (new Set(choices).size !== choices.length) {\n bad(\"choices\", \"must not repeat a value\");\n } else if (\n (choices as string[]).some(c => {\n // Length first, so the regex never runs on an oversized choice.\n const length = codePoints(c);\n if (length > METAFIELD_LIMITS.regex_value_length && out.regex !== undefined) return true;\n if (out.max_length !== undefined && length > out.max_length) return true;\n if (out.min_length !== undefined && length < out.min_length) return true;\n return out.regex !== undefined && !matchesPattern(out.regex, c);\n })\n ) {\n bad(\"choices\", \"includes a value the pattern or length rules reject\");\n } else {\n out.choices = [...(choices as string[])];\n }\n }\n\n for (const key of [\"min\", \"max\"] as const) {\n if (!has(key)) continue;\n const bound = normalizeBound(base, raw[key]);\n if (bound === null) bad(key, `is not a valid ${base} bound`);\n else out[key] = bound;\n }\n if (out.min !== undefined && out.max !== undefined && compareBound(base, out.min, out.max) > 0) {\n bad(\"min\", \"must not exceed max\");\n }\n\n if (has(\"max_precision\")) {\n if (isWholeNumber(raw.max_precision, 0, 9)) out.max_precision = raw.max_precision as number;\n else bad(\"max_precision\", \"must be a whole number from 0 to 9\");\n }\n\n if (has(\"allowed_domains\")) {\n const domains = raw.allowed_domains;\n const lowered = Array.isArray(domains)\n ? domains.map(d => (typeof d === \"string\" ? d.toLowerCase() : \"\"))\n : [];\n if (\n !Array.isArray(domains) ||\n domains.length === 0 ||\n domains.length > METAFIELD_LIMITS.allowed_domains ||\n lowered.some(d => !HOSTNAME.test(d))\n ) {\n bad(\"allowed_domains\", `must list 1 to ${METAFIELD_LIMITS.allowed_domains} domains such as youtube.com`);\n } else {\n out.allowed_domains = [...new Set(lowered)];\n }\n }\n\n if (base === \"rating\") {\n for (const key of [\"scale_min\", \"scale_max\"] as const) {\n if (raw[key] === undefined) {\n bad(key, \"is required for a rating\", \"required\");\n continue;\n }\n const decimal = normalizeDecimal(raw[key]);\n if (decimal === null) bad(key, \"must be a decimal number\");\n else out[key] = decimal;\n }\n if (out.scale_min !== undefined && out.scale_max !== undefined && compareDecimal(out.scale_min, out.scale_max) >= 0) {\n bad(\"scale_min\", \"must be below scale_max\");\n }\n }\n\n if (has(\"file_types\")) {\n const kinds = raw.file_types;\n if (\n !Array.isArray(kinds) ||\n kinds.length === 0 ||\n kinds.some(k => !FILE_KINDS.includes(k as FileKind)) ||\n new Set(kinds).size !== kinds.length\n ) {\n bad(\"file_types\", \"must list image, video and/or document\");\n } else {\n out.file_types = [...(kinds as FileKind[])];\n }\n }\n\n if (base === \"metaobject_reference\") {\n const id = normalizeId(raw.metaobject_definition_id);\n if (raw.metaobject_definition_id === undefined) {\n bad(\"metaobject_definition_id\", \"is required\", \"required\");\n } else if (id === null) {\n bad(\"metaobject_definition_id\", \"must be a metaobject definition id\");\n } else {\n out.metaobject_definition_id = id;\n }\n }\n\n if (base === \"mixed_reference\") {\n const ids = Array.isArray(raw.metaobject_definition_ids)\n ? raw.metaobject_definition_ids.map(normalizeId)\n : null;\n if (raw.metaobject_definition_ids === undefined) {\n bad(\"metaobject_definition_ids\", \"is required\", \"required\");\n } else if (\n !ids ||\n ids.length < METAFIELD_LIMITS.mixed_reference_definitions_min ||\n ids.length > METAFIELD_LIMITS.mixed_reference_definitions_max ||\n ids.some(id => id === null) ||\n new Set(ids).size !== ids.length\n ) {\n bad(\n \"metaobject_definition_ids\",\n `must list ${METAFIELD_LIMITS.mixed_reference_definitions_min} to ${METAFIELD_LIMITS.mixed_reference_definitions_max} different definition ids`\n );\n } else {\n out.metaobject_definition_ids = ids as string[];\n }\n }\n\n for (const key of [\"list_min\", \"list_max\"] as const) {\n if (!has(key)) continue;\n if (isWholeNumber(raw[key], 0, METAFIELD_LIMITS.list_items)) out[key] = raw[key] as number;\n else bad(key, `must be a whole number from 0 to ${METAFIELD_LIMITS.list_items}`);\n }\n if (out.list_min !== undefined && out.list_max !== undefined && out.list_min > out.list_max) {\n bad(\"list_min\", \"must not exceed list_max\");\n }\n\n return errors.length ? { ok: false, errors } : ok(out);\n}\n\n// --- Definitions: metafields, metaobjects, entries ---\n\nexport type CustomerAccess = \"none\" | \"read\" | \"read_write\";\n\n/** Customer, order and location data never reaches the public storefront (spec s.4.1). */\nexport function storefrontAccessAllowed(owner: MetafieldOwnerType): boolean {\n return owner !== \"customer\" && owner !== \"order\" && owner !== \"location\";\n}\n\nexport function allowedCustomerAccess(owner: MetafieldOwnerType): readonly CustomerAccess[] {\n if (owner === \"customer\") return [\"none\", \"read\", \"read_write\"];\n if (owner === \"order\") return [\"none\", \"read\"];\n return [\"none\"];\n}\n\nexport interface MetafieldDefinitionShape {\n owner_type: MetafieldOwnerType;\n namespace: string;\n key: string;\n name: string;\n description: string | null;\n type: MetafieldType;\n validations: MetafieldValidations;\n storefront_access: boolean;\n customer_access: CustomerAccess;\n}\n\nconst METAFIELD_DEFINITION_KEYS = [\n \"owner_type\",\n \"namespace\",\n \"key\",\n \"name\",\n \"description\",\n \"type\",\n \"validations\",\n \"storefront_access\",\n \"customer_access\",\n] as const;\n\nfunction readName(value: unknown, path: string, errors: MetafieldIssue[]): string {\n const name = typeof value === \"string\" ? value.trim() : \"\";\n if (!name || codePoints(name) > METAFIELD_LIMITS.name_length) {\n errors.push(issue(path, \"invalid_format\", `must be 1 to ${METAFIELD_LIMITS.name_length} characters`));\n }\n return name;\n}\n\nfunction readDescription(value: unknown, path: string, errors: MetafieldIssue[]): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value !== \"string\" || codePoints(value) > METAFIELD_LIMITS.description_length) {\n errors.push(issue(path, \"invalid_format\", `must be text of at most ${METAFIELD_LIMITS.description_length} characters`));\n return null;\n }\n return value.trim() || null;\n}\n\nfunction readKey(value: unknown, path: string, errors: MetafieldIssue[], pattern = METAFIELD_KEY_PATTERN): string {\n if (typeof value !== \"string\" || !pattern.test(value)) {\n errors.push(issue(path, \"invalid_format\", \"must be 2 to 64 lowercase letters, digits or underscores\"));\n return \"\";\n }\n if (RESERVED_KEYS.includes(value)) {\n errors.push(issue(path, \"invalid_format\", \"is a reserved name\"));\n return \"\";\n }\n return value;\n}\n\nfunction readBoolean(value: unknown, fallback: boolean, path: string, errors: MetafieldIssue[]): boolean {\n if (value === undefined) return fallback;\n if (typeof value !== \"boolean\") {\n errors.push(issue(path, \"invalid_type\", \"must be true or false\"));\n return fallback;\n }\n return value;\n}\n\nfunction readTypeAndValidations(\n input: Record<string, unknown>,\n path: string,\n errors: MetafieldIssue[]\n): { type: MetafieldType; validations: MetafieldValidations } | null {\n if (!isMetafieldType(input.type)) {\n errors.push(issue(joinPath(path, \"type\"), \"invalid_format\", \"is not a metafield type\"));\n return null;\n }\n const validations = validateValidations(input.type, input.validations, joinPath(path, \"validations\"));\n if (!validations.ok) {\n errors.push(...validations.errors);\n return null;\n }\n return { type: input.type, validations: validations.value };\n}\n\n/** Validates a full metafield definition; the API merges a PATCH into the stored row first. */\nexport function validateMetafieldDefinition(input: unknown): EngineResult<MetafieldDefinitionShape> {\n if (!isPlainObject(input)) return fail(\"\", \"invalid_type\", \"must be an object\");\n const errors = unknownKeys(input, METAFIELD_DEFINITION_KEYS, \"\");\n const owner = input.owner_type as MetafieldOwnerType;\n if (!METAFIELD_OWNER_TYPES.includes(owner)) {\n errors.push(issue(\"owner_type\", \"invalid_format\", `must be one of: ${METAFIELD_OWNER_TYPES.join(\", \")}`));\n }\n const namespace = readKey(input.namespace ?? \"custom\", \"namespace\", errors);\n const key = readKey(input.key, \"key\", errors);\n const name = readName(input.name, \"name\", errors);\n const description = readDescription(input.description, \"description\", errors);\n const typed = readTypeAndValidations(input, \"\", errors);\n const storefront = readBoolean(input.storefront_access, false, \"storefront_access\", errors);\n if (storefront && METAFIELD_OWNER_TYPES.includes(owner) && !storefrontAccessAllowed(owner)) {\n errors.push(issue(\"storefront_access\", \"not_allowed\", `is not available for ${owner} metafields`));\n }\n const customer = (input.customer_access ?? \"none\") as CustomerAccess;\n if (!allowedCustomerAccess(owner).includes(customer)) {\n errors.push(issue(\"customer_access\", \"not_allowed\", `must be one of: ${allowedCustomerAccess(owner).join(\", \")}`));\n }\n if (errors.length || !typed) return { ok: false, errors };\n const out: MetafieldDefinitionShape = {\n owner_type: owner,\n namespace,\n key,\n name,\n description,\n type: typed.type,\n validations: typed.validations,\n storefront_access: storefront,\n customer_access: customer,\n };\n return storable(out);\n}\n\n/** Definitions persist as jsonb too: refuse NUL and lone surrogates anywhere in them. */\nfunction storable<T>(out: T): EngineResult<T> {\n if (!isStorableJson(JSON.stringify(out))) {\n return fail(\"\", \"invalid_format\", \"contains characters that cannot be stored\");\n }\n return ok(out);\n}\n\nexport interface MetaobjectFieldShape {\n key: string;\n name: string;\n description: string | null;\n type: MetafieldType;\n required: boolean;\n validations: MetafieldValidations;\n}\n\n/** Field types usable as filter keys (spec s.4.3). List types never are. */\nexport const FILTERABLE_TYPES: readonly MetafieldBaseType[] = [\"single_line_text\", \"boolean\", \"integer\", \"date\"];\n\nexport interface MetaobjectDefinitionShape {\n type: string;\n name: string;\n description: string | null;\n fields: MetaobjectFieldShape[];\n display_name_key: string | null;\n filter_keys: string[];\n has_status: boolean;\n storefront_access: boolean;\n customer_access: \"none\" | \"read\";\n}\n\nconst METAOBJECT_DEFINITION_KEYS = [\n \"type\",\n \"name\",\n \"description\",\n \"fields\",\n \"display_name_key\",\n \"filter_keys\",\n \"has_status\",\n \"storefront_access\",\n \"customer_access\",\n] as const;\n\nconst FIELD_KEYS = [\"key\", \"name\", \"description\", \"type\", \"required\", \"validations\"] as const;\n\nfunction readField(input: unknown, path: string, errors: MetafieldIssue[]): MetaobjectFieldShape | null {\n if (!isPlainObject(input)) {\n errors.push(issue(path, \"invalid_type\", \"must be an object\"));\n return null;\n }\n errors.push(...unknownKeys(input, FIELD_KEYS, path));\n const key = readKey(input.key, joinPath(path, \"key\"), errors);\n const name = readName(input.name, joinPath(path, \"name\"), errors);\n const description = readDescription(input.description, joinPath(path, \"description\"), errors);\n const required = readBoolean(input.required, false, joinPath(path, \"required\"), errors);\n const typed = readTypeAndValidations(input, path, errors);\n return typed ? { key, name, description, type: typed.type, required, validations: typed.validations } : null;\n}\n\n/** Validates a full metaobject definition; the API merges a PATCH into the stored row first. */\nexport function validateMetaobjectDefinition(input: unknown): EngineResult<MetaobjectDefinitionShape> {\n if (!isPlainObject(input)) return fail(\"\", \"invalid_type\", \"must be an object\");\n const errors = unknownKeys(input, METAOBJECT_DEFINITION_KEYS, \"\");\n const type = typeof input.type === \"string\" && METAOBJECT_TYPE_PATTERN.test(input.type) ? input.type : \"\";\n if (!type) {\n errors.push(issue(\"type\", \"invalid_format\", \"must be 2 to 64 lowercase letters, digits, underscores or hyphens\"));\n } else if (RESERVED_KEYS.includes(type)) {\n errors.push(issue(\"type\", \"invalid_format\", \"is a reserved name\"));\n }\n const name = readName(input.name, \"name\", errors);\n const description = readDescription(input.description, \"description\", errors);\n\n const fields: MetaobjectFieldShape[] = [];\n if (!Array.isArray(input.fields)) {\n errors.push(issue(\"fields\", \"invalid_type\", \"must be a list of fields\"));\n } else if (input.fields.length === 0) {\n errors.push(issue(\"fields\", \"too_short\", \"must have at least 1 field\"));\n } else if (input.fields.length > METAFIELD_LIMITS.fields_per_metaobject) {\n errors.push(issue(\"fields\", \"too_long\", `must have at most ${METAFIELD_LIMITS.fields_per_metaobject} fields`));\n } else {\n const seen = new Set<string>();\n input.fields.forEach((raw, index) => {\n const path = joinPath(\"fields\", index);\n const field = readField(raw, path, errors);\n if (!field) return;\n if (seen.has(field.key)) errors.push(issue(joinPath(path, \"key\"), \"duplicate\", `\"${field.key}\" is used twice`));\n seen.add(field.key);\n fields.push(field);\n });\n }\n const byKey = new Map(fields.map(field => [field.key, field]));\n const isSingleLine = (key: string) => byKey.get(key)?.type === \"single_line_text\";\n\n let displayNameKey: string | null;\n if (input.display_name_key === undefined) {\n displayNameKey = fields.find(field => field.type === \"single_line_text\")?.key ?? null;\n } else if (input.display_name_key === null) {\n displayNameKey = null;\n } else if (typeof input.display_name_key === \"string\" && isSingleLine(input.display_name_key)) {\n displayNameKey = input.display_name_key;\n } else {\n displayNameKey = null;\n errors.push(issue(\"display_name_key\", \"invalid_format\", \"must name a single line text field\"));\n }\n\n const filterKeys: string[] = [];\n const rawFilters = input.filter_keys ?? [];\n if (!Array.isArray(rawFilters)) {\n errors.push(issue(\"filter_keys\", \"invalid_type\", \"must be a list of field keys\"));\n } else if (rawFilters.length > METAFIELD_LIMITS.filter_keys) {\n errors.push(issue(\"filter_keys\", \"too_long\", `must have at most ${METAFIELD_LIMITS.filter_keys} keys`));\n } else {\n rawFilters.forEach((key, index) => {\n const path = joinPath(\"filter_keys\", index);\n const field = typeof key === \"string\" ? byKey.get(key) : undefined;\n if (!field) errors.push(issue(path, \"invalid_format\", \"must name a field of this definition\"));\n else if (!FILTERABLE_TYPES.includes(field.type as MetafieldBaseType)) {\n errors.push(issue(path, \"not_allowed\", \"only single line text, true or false, integer and date fields can be filters\"));\n } else if (filterKeys.includes(field.key)) errors.push(issue(path, \"duplicate\", `\"${field.key}\" is listed twice`));\n else filterKeys.push(field.key);\n });\n }\n\n const hasStatus = readBoolean(input.has_status, true, \"has_status\", errors);\n const storefront = readBoolean(input.storefront_access, false, \"storefront_access\", errors);\n const customer = input.customer_access ?? \"none\";\n if (customer !== \"none\" && customer !== \"read\") {\n errors.push(issue(\"customer_access\", \"not_allowed\", \"must be none or read\"));\n }\n\n if (errors.length) return { ok: false, errors };\n return storable<MetaobjectDefinitionShape>({\n type,\n name,\n description,\n fields,\n display_name_key: displayNameKey,\n filter_keys: filterKeys,\n has_status: hasStatus,\n storefront_access: storefront,\n customer_access: customer as \"none\" | \"read\",\n });\n}\n\n/** Validates an entry's field values against its definition; blank optional fields are omitted. */\nexport function validateMetaobjectEntry(\n fields: readonly MetaobjectFieldShape[],\n input: unknown,\n ctx: MetafieldContext\n): EngineResult<Record<string, unknown>> {\n if (!Array.isArray(fields)) return fail(\"\", \"invalid_type\", \"fields must be a list\");\n if (!isPlainObject(input)) return fail(\"\", \"invalid_type\", \"must be an object of field values\");\n const errors = unknownKeys(input, fields.map(field => field.key), \"\");\n const out: Record<string, unknown> = {};\n for (const field of fields) {\n const raw = hasOwn(input, field.key) ? input[field.key] : undefined;\n if (isBlankValueFor(field.type, raw)) {\n if (field.required) errors.push(issue(field.key, \"required\", \"is required\"));\n continue;\n }\n const result = validateMetafieldValue(field.type, field.validations, raw, ctx, field.key);\n if (result.ok) {\n Object.defineProperty(out, field.key, { value: result.value, enumerable: true, writable: true, configurable: true });\n }\n else errors.push(...result.errors);\n }\n if (!errors.length && byteLength(JSON.stringify(out)) > METAFIELD_LIMITS.value_bytes) {\n return fail(\"\", \"too_large\", `must be at most ${METAFIELD_LIMITS.value_bytes} bytes`);\n }\n return errors.length ? { ok: false, errors } : ok(out);\n}\n\n/** The display-name field's text, else the handle (spec s.4.4). */\nexport function entryDisplayName(\n definition: Pick<MetaobjectDefinitionShape, \"display_name_key\">,\n fields: Record<string, unknown>,\n handle: string\n): string {\n const value = definition.display_name_key ? fields[definition.display_name_key] : undefined;\n return typeof value === \"string\" && value.trim() ? [...value.trim()].slice(0, METAFIELD_LIMITS.name_length).join(\"\") : handle;\n}\n\n/**\n * A field's type is fixed once saved (spec s.4.5). Reports removed keys so the\n * API can strip them from entries. Assumes `after` already passed\n * validateMetaobjectDefinition (unique keys).\n */\nexport function checkMetaobjectFieldChanges(\n before: readonly MetaobjectFieldShape[],\n after: readonly MetaobjectFieldShape[]\n): EngineResult<{ removed: string[]; added: string[] }> {\n const prior = new Map(before.map(field => [field.key, field]));\n const errors = after.flatMap((field, index) => {\n const old = prior.get(field.key);\n return old && old.type !== field.type\n ? [issue(joinPath(joinPath(\"fields\", index), \"type\"), \"immutable\", `cannot change the type of \"${field.key}\"`)]\n : [];\n });\n if (errors.length) return { ok: false, errors };\n const kept = new Set(after.map(field => field.key));\n return ok({\n removed: before.filter(field => !kept.has(field.key)).map(field => field.key),\n added: after.filter(field => !prior.has(field.key)).map(field => field.key),\n });\n}\n","import type { ImageTransformOptions } from \"./types\";\n\n/**\n * Storage URL helpers.\n *\n * Object URLs are plain strings, so no storage client is required — these only\n * ever concatenated base + bucket + path. URLs are built against\n * NEXT_PUBLIC_ASSET_BASE_URL (or ASSET_BASE_URL on the server), which points at\n * the API that serves `/storage/v1/...`.\n *\n * A stored URL's ORIGIN is deliberately ignored and rebuilt: rows written\n * before the storage migration carry whatever host was configured at the time,\n * and those hosts no longer serve anything. Rebuilding is what lets old and new\n * rows resolve identically with no database backfill.\n */\n\nexport const OBJECT_PREFIX = \"/storage/v1/object/public/\";\nexport const RENDER_PREFIX = \"/storage/v1/render/image/public/\";\n\nexport const DEFAULT_BUCKET = \"public-cdn\";\n\nfunction getEnv(key: string): string | undefined {\n if (typeof window === \"undefined\") {\n return process.env[key];\n }\n return (\n (window as unknown as Record<string, any>)?.process?.env?.[key] ?? undefined\n );\n}\n\n/**\n * Origin serving storage objects. Callers in a bundler that inlines\n * `process.env.NEXT_PUBLIC_*` should pass the value explicitly to the\n * `baseUrl` parameters below rather than relying on this lookup, since a\n * dynamic `process.env[key]` read is not inlined.\n */\nexport function assetBaseUrl(): string {\n return (\n getEnv(\"NEXT_PUBLIC_ASSET_BASE_URL\") ||\n getEnv(\"ASSET_BASE_URL\") ||\n \"\"\n ).replace(/\\/$/, \"\");\n}\n\n/**\n * Tells whether image resizing is on. Controlled by `NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS`; when unset it is on, except for a local asset host.\n *\n * @returns `true` when image URLs should use the resizing endpoint\n */\nexport function transformationsEnabled(): boolean {\n const flag = getEnv(\"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\");\n if (typeof flag === \"string\" && flag !== \"\") {\n return [\"1\", \"true\", \"yes\", \"on\"].includes(flag.toLowerCase());\n }\n // Local stacks may not run the image renderer, so serve originals.\n return !/localhost|127\\.0\\.0\\.1/.test(assetBaseUrl());\n}\n\n/**\n * Builds the query string for an image resize request.\n *\n * @param opts - the resize options; unset or non-finite values are left out\n * @returns The query string including the leading `?`, or an empty string when there is nothing to add\n */\nexport function buildTransformQuery(opts?: ImageTransformOptions): string {\n if (!opts) return \"\";\n const params = new URLSearchParams();\n if (opts.width && Number.isFinite(opts.width))\n params.set(\"width\", String(opts.width));\n if (opts.height && Number.isFinite(opts.height))\n params.set(\"height\", String(opts.height));\n if (opts.resize) params.set(\"resize\", opts.resize);\n if (opts.quality && Number.isFinite(opts.quality))\n params.set(\"quality\", String(opts.quality));\n if (opts.format) params.set(\"format\", opts.format);\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\n/**\n * Builds the URL of a resized version of a stored image. Defaults to `resize=cover` and `quality=80`.\n *\n * @param baseUrl - the origin that serves storage objects\n * @param bucket - the storage bucket\n * @param path - the object path inside the bucket\n * @param opts - resize options that override the defaults\n * @returns The resized image URL\n */\nexport function toRenderUrl(\n baseUrl: string,\n bucket: string,\n path: string,\n opts?: ImageTransformOptions\n): string {\n const query = buildTransformQuery({ resize: \"cover\", quality: 80, ...opts });\n const normalizedPath = path.replace(/^\\//, \"\");\n return `${baseUrl.replace(/\\/$/, \"\")}${RENDER_PREFIX}${bucket}/${normalizedPath}${query}`;\n}\n\n/**\n * Builds the URL of the original, unresized stored image.\n *\n * @param baseUrl - the origin that serves storage objects\n * @param bucket - the storage bucket\n * @param path - the object path inside the bucket\n * @returns The original image URL\n */\nexport function toObjectUrl(\n baseUrl: string,\n bucket: string,\n path: string\n): string {\n const normalizedPath = path.replace(/^\\//, \"\");\n return `${baseUrl.replace(/\\/$/, \"\")}${OBJECT_PREFIX}${bucket}/${normalizedPath}`;\n}\n\n/**\n * Pull bucket + object path out of a storage URL, whatever host it names.\n * Accepts both the object and render path shapes. Returns null for URLs that\n * are not storage URLs at all.\n */\nexport function parseStorageUrl(\n url: string\n): { bucket: string; path: string } | null {\n try {\n const { pathname } = new URL(url);\n const prefix = [OBJECT_PREFIX, RENDER_PREFIX].find((p) =>\n pathname.includes(p)\n );\n if (!prefix) return null;\n\n const parts = pathname.split(prefix)[1].split(\"/\");\n const bucket = parts.shift();\n if (!bucket || parts.length === 0) return null;\n\n return { bucket, path: parts.join(\"/\") };\n } catch {\n return null;\n }\n}\n\n/**\n * Rewrite a storage object URL to the render endpoint, rebuilding it against\n * `baseUrl` (defaulting to the configured asset origin). Returns the URL\n * unchanged when it is not a storage URL, when transformations are disabled,\n * or when no base URL is configured.\n */\nexport function fromObjectPublicUrlToRender(\n publicUrl: string,\n opts?: ImageTransformOptions,\n baseUrl: string = assetBaseUrl()\n): string | null {\n const parsed = parseStorageUrl(publicUrl);\n if (!parsed || !baseUrl) return null;\n return toRenderUrl(baseUrl, parsed.bucket, parsed.path, opts);\n}\n\n/**\n * Resolve any image reference — a full URL or a bare storage object path — to\n * a URL served by the configured asset origin.\n *\n * - A full http(s) URL that is not a storage URL is returned as-is.\n * - A storage URL is rebuilt against `baseUrl`, ignoring its stored host.\n * - A bare object path is resolved within `bucket`.\n */\nexport function resolveAssetUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions,\n bucket: string = DEFAULT_BUCKET,\n baseUrl: string = assetBaseUrl()\n): string | null {\n if (!imagePathOrUrl) return null;\n\n const build = (b: string, p: string) =>\n transformationsEnabled()\n ? toRenderUrl(baseUrl, b, p, opts)\n : toObjectUrl(baseUrl, b, p);\n\n if (/^https?:\\/\\//i.test(imagePathOrUrl)) {\n const parsed = parseStorageUrl(imagePathOrUrl);\n if (!parsed) return imagePathOrUrl;\n return baseUrl ? build(parsed.bucket, parsed.path) : imagePathOrUrl;\n }\n\n // Starts with / -> a local app asset, not storage. Leave untouched.\n if (imagePathOrUrl.startsWith(\"/\")) return imagePathOrUrl;\n\n return baseUrl ? build(bucket, imagePathOrUrl) : null;\n}\n\n/**\n * Resolves a stored image URL to the asset host, resized when options are given.\n *\n * @deprecated Renamed to {@link resolveAssetUrl}. The old name described a\n * Supabase-specific rewrite; the implementation is no longer Supabase-aware.\n * Kept so existing callers keep compiling.\n */\nexport function rewriteSupabaseUrl(\n url: string,\n opts?: ImageTransformOptions\n): string {\n return resolveAssetUrl(url, opts) ?? url;\n}\n","export function stringify(obj: object): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(obj)) {\n if (value === null || value === undefined) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n params.append(key, String(item));\n }\n } else {\n params.append(key, String(value));\n }\n }\n return params.toString();\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { ProductDetail, ProductQueryParams } from \"./types\";\n\n/**\n * Products of a store, reached through `sdk.products`.\n */\nexport class ProductsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Gets one product by id.\n *\n * @param storeRef - the store's ref or handle\n * @param productId - the product id\n * @param query - optional fields to include\n * @returns The product, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(\n storeRef: string,\n productId: number,\n query?: ProductQueryParams\n ): Promise<ProductDetail | null> {\n const queryString = stringify(query ?? {});\n const res = await this.http.get<ProductDetail>(\n `/public/stores/${storeRef}/products/${productId}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Gets one product by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the product slug\n * @param query - optional fields to include\n * @returns The product, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySlug(\n storeRef: string,\n slug: string,\n query?: ProductQueryParams\n ): Promise<ProductDetail | null> {\n const normalizedSlug = slug.normalize(\"NFC\");\n const encodedSlug = encodeURIComponent(normalizedSlug);\n const queryString = stringify(query ?? {});\n const res = await this.http.get<ProductDetail>(\n `/public/stores/${storeRef}/products/slug/${encodedSlug}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrapOrNull(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { Collection, CollectionQueryParams } from \"./types\";\nimport type { PaginatedResponse } from \"../../types\";\n\n/**\n * Product collections of a store, reached through `sdk.collections`.\n */\nexport class CollectionsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists collections, one page at a time.\n *\n * @param storeRef - the store's ref or handle\n * @param params - filters, sorting and paging\n * @returns A page of collections; throws {@link ApiClientError} when the API answers with an error\n */\n async getAllPaginated(\n storeRef: string,\n params?: CollectionQueryParams\n ): Promise<PaginatedResponse<Collection>> {\n const queryString = stringify(params ?? {});\n const res = await this.http.get<PaginatedResponse<Collection>>(\n `/public/stores/${storeRef}/collections${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists up to 100 collections in one call.\n *\n * @param storeRef - the store's ref or handle\n * @param ids - limit the result to these collection ids\n * @returns The collections; throws {@link ApiClientError} when the API answers with an error\n */\n async getAll(storeRef: string, ids?: number[]): Promise<Collection[]> {\n const result = await this.getAllPaginated(storeRef, {\n ids,\n limit: ids && ids.length > 0 ? Math.min(ids.length, 100) : 100,\n });\n return result.data;\n }\n\n /**\n * Gets one collection by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the collection slug\n * @param query - `include_seo_metadata` adds the SEO fields\n * @returns The collection, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySlug(\n storeRef: string,\n slug: string,\n query?: { include_seo_metadata?: boolean }\n ): Promise<Collection | null> {\n const queryString = query ? stringify(query) : \"\";\n const res = await this.http.get<Collection>(\n `/public/stores/${storeRef}/collections/slug/${slug}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrapOrNull(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { Category, CategoryQueryParams } from \"./types\";\nimport type { PaginatedResponse } from \"../../types\";\n\n/**\n * Product categories of a store, reached through `sdk.categories`.\n */\nexport class CategoriesApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists categories, one page at a time.\n *\n * @param storeRef - the store's ref or handle\n * @param params - filters, sorting and paging\n * @returns A page of categories; throws {@link ApiClientError} when the API answers with an error\n */\n async getAllPaginated(\n storeRef: string,\n params?: CategoryQueryParams\n ): Promise<PaginatedResponse<Category>> {\n const queryString = stringify(params ?? {});\n const res = await this.http.get<PaginatedResponse<Category>>(\n `/public/stores/${storeRef}/categories${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists up to 1,000 categories in one call.\n *\n * @param storeRef - the store's ref or handle\n * @param activeOnly - `true` (the default) returns only active categories\n * @returns The categories; throws {@link ApiClientError} when the API answers with an error\n */\n async getAll(storeRef: string, activeOnly = true): Promise<Category[]> {\n const result = await this.getAllPaginated(storeRef, {\n is_active: activeOnly,\n limit: 1000,\n });\n return result.data;\n }\n\n /**\n * Gets one category by id.\n *\n * @param storeRef - the store's ref or handle\n * @param categoryId - the category id\n * @returns The category, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(\n storeRef: string,\n categoryId: number\n ): Promise<Category | null> {\n const res = await this.http.get<Category>(\n `/public/stores/${storeRef}/categories/${categoryId}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Gets one category by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the category slug\n * @returns The category, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySlug(storeRef: string, slug: string): Promise<Category | null> {\n const res = await this.http.get<Category>(\n `/public/stores/${storeRef}/categories/${encodeURIComponent(slug)}`\n );\n return unwrapOrNull(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type {\n CartApiResponse,\n CartApiItem,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"./types\";\n\n/**\n * A shopper's cart: a guest cart keyed by a session id, or the signed-in customer's cart, reached through `sdk.cart`.\n */\nexport class CartApi {\n constructor(\n private publicHttp: IHttpClient,\n private authHttp: IHttpClient\n ) {}\n\n private client(isAuth: boolean) {\n return isAuth ? this.authHttp : this.publicHttp;\n }\n\n private basePath(isAuth: boolean) {\n return isAuth ? \"stores\" : \"public/stores\";\n }\n\n /**\n * Gets the shopper's cart.\n *\n * @param storeRef - the store's ref or handle\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getCart(\n storeRef: string,\n sessionId: string,\n isAuth: boolean\n ): Promise<CartApiResponse | null> {\n const res = await this.client(isAuth).get<CartApiResponse>(\n `/${this.basePath(isAuth)}/${storeRef}/cart`,\n { headers: { \"x-session-id\": sessionId } }\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Adds a product variant to the cart.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the variant and the quantity\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id and the added item; throws {@link ApiClientError} when the API answers with an error\n */\n async addItem(\n storeRef: string,\n data: AddToCartRequest,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cart_id: string; item: CartApiItem }> {\n const res = await this.client(isAuth).post<{\n cart_id: string;\n item: CartApiItem;\n }>(`/${this.basePath(isAuth)}/${storeRef}/cart/items`, data, {\n headers: { \"x-session-id\": sessionId },\n });\n return unwrap(res);\n }\n\n /**\n * Changes the quantity of a cart line.\n *\n * @param storeRef - the store's ref or handle\n * @param itemId - the cart line id\n * @param data - the new quantity\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id and the updated item (`null` when the line was removed); throws {@link ApiClientError} when the API answers with an error\n */\n async updateItem(\n storeRef: string,\n itemId: string,\n data: UpdateCartItemRequest,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cart_id: string; item: CartApiItem | null }> {\n const res = await this.client(isAuth).put<{\n cart_id: string;\n item: CartApiItem | null;\n }>(`/${this.basePath(isAuth)}/${storeRef}/cart/items/${itemId}`, data, {\n headers: { \"x-session-id\": sessionId },\n });\n return unwrap(res);\n }\n\n /**\n * Removes a line from the cart.\n *\n * @param storeRef - the store's ref or handle\n * @param itemId - the cart line id\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id and the removed line's id; throws {@link ApiClientError} when the API answers with an error\n */\n async removeItem(\n storeRef: string,\n itemId: string,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cartId: string; itemId: string }> {\n const res = await this.client(isAuth).delete<{\n cartId: string;\n itemId: string;\n }>(`/${this.basePath(isAuth)}/${storeRef}/cart/items/${itemId}`, {\n headers: { \"x-session-id\": sessionId },\n });\n return unwrap(res);\n }\n\n /**\n * Empties the cart.\n *\n * @param storeRef - the store's ref or handle\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id; throws {@link ApiClientError} when the API answers with an error\n */\n async clear(\n storeRef: string,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cart_id: string }> {\n const res = await this.client(isAuth).delete<{ cart_id: string }>(\n `/${this.basePath(isAuth)}/${storeRef}/cart`,\n { headers: { \"x-session-id\": sessionId } }\n );\n return unwrap(res);\n }\n\n /**\n * Merge the guest cart into the signed-in cart. Resolves to\n * `{ merged: false }` when neither cart exists.\n */\n async merge(\n storeRef: string,\n sessionId: string\n ): Promise<CartApiResponse | { merged: false }> {\n const res = await this.authHttp.post<CartApiResponse | { merged: false }>(\n `/stores/${storeRef}/cart/merge`,\n {},\n { headers: { \"x-session-id\": sessionId } }\n );\n return unwrap(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { PaginatedResponse, Id, WithMetafields } from \"../../types\";\nimport type {\n Order,\n OrderWithItems,\n CustomerOrderFilter,\n CreateOrderRequest,\n GuestOrderLookupParams,\n} from \"./types\";\n\n/**\n * Placing orders, and reading them back as a guest or as the signed-in customer, reached through `sdk.orders`.\n */\nexport class OrdersApi {\n constructor(\n private publicHttp: IHttpClient,\n private authHttp: IHttpClient\n ) {}\n\n /**\n * Look up a guest order. The API answers with the bare order when it\n * matches and `{ message }` (HTTP 200) when it does not; a 404 is treated\n * the same way. Returns null for \"not found\".\n */\n async lookupGuest(\n storeRef: string,\n params: GuestOrderLookupParams\n ): Promise<OrderWithItems | null> {\n const query = stringify({\n order_code: params.order_code,\n order_number: params.order_number,\n customer_email: params.customer_email,\n customer_phone: params.customer_phone,\n });\n const res = await this.publicHttp.get<OrderWithItems | { message: string }>(\n `/public/stores/${storeRef}/orders/lookup?${query}`\n );\n const data = unwrapOrNull(res);\n if (!data || !(\"id\" in data) || data.id == null) return null;\n return data as OrderWithItems;\n }\n\n /**\n * Places an order.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the order details\n * @param isAuth - `true` to place it as the signed-in customer, `false` as a guest\n * @returns The created order with its items; throws {@link ApiClientError} when the API answers with an error\n */\n async create(\n storeRef: string,\n data: CreateOrderRequest,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n if (isAuth) {\n const res = await this.authHttp.post<OrderWithItems>(\n `/tenant/stores/${storeRef}/customers/orders`,\n data\n );\n return unwrap(res);\n }\n const res = await this.publicHttp.post<OrderWithItems>(\n `/public/stores/${storeRef}/orders`,\n data\n );\n return unwrap(res);\n }\n\n /**\n * Lists the signed-in customer's orders, newest first by default.\n *\n * @param storeRef - the store's ref or handle\n * @param params - search, status filter, sorting and paging (`page`, or `limit` and `offset`)\n * @returns A page of orders; throws {@link ApiClientError} when the API answers with an error\n */\n async listCustomerOrders(\n storeRef: string,\n params: Partial<CustomerOrderFilter> & { page?: number } = {}\n ): Promise<PaginatedResponse<Order>> {\n const limit = params.limit ?? 10;\n const page =\n params.page ??\n (params.offset ? Math.floor((params.offset as number) / limit) + 1 : 1);\n const offset = params.offset ?? (page - 1) * limit;\n const query = stringify({\n search: params.search || undefined,\n status: params.status || undefined,\n limit,\n offset,\n include_items: true,\n sort_by: params.sort_by ?? \"created_at\",\n sort_order: params.sort_order ?? \"desc\",\n });\n const res = await this.authHttp.get<PaginatedResponse<Order>>(\n `/tenant/stores/${storeRef}/customers/orders${query ? `?${query}` : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Full detail for one of the authenticated customer's orders. The API\n * verifies ownership and returns 404 — not 403 — for someone else's order.\n */\n async getCustomerOrder(\n storeRef: string,\n orderId: Id\n ): Promise<OrderWithItems & WithMetafields> {\n const res = await this.authHttp.get<OrderWithItems & WithMetafields>(\n `/tenant/stores/${storeRef}/customers/orders/${orderId}`\n );\n return unwrap(res);\n }\n\n /**\n * Customers may only cancel orders that are still pending, confirmed or\n * processing; the API rejects anything else with ORDER_NOT_CANCELLABLE.\n */\n async cancelCustomerOrder(storeRef: string, orderId: Id): Promise<Order> {\n const res = await this.authHttp.delete<Order>(\n `/tenant/stores/${storeRef}/customers/orders/${orderId}`\n );\n return unwrap(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { PaginatedResponse } from \"../../types\";\nimport type {\n BlogPost,\n BlogCategory,\n BlogTag,\n BlogPostQueryParams,\n BlogCategoryQueryParams,\n BlogTagQueryParams,\n} from \"./types\";\n\n/**\n * Published blog posts, categories, tags and comments of a store, reached through `sdk.blog`.\n */\nexport class BlogApi {\n constructor(\n private publicHttp: IHttpClient,\n private authHttp: IHttpClient\n ) {}\n\n /**\n * Lists published blog posts.\n *\n * @param storeRef - the store's ref or handle\n * @param query - filters, sorting and paging\n * @returns A page of posts; throws {@link ApiClientError} when the API answers with an error\n */\n async getPosts(\n storeRef: string,\n query: Partial<BlogPostQueryParams> = {}\n ): Promise<PaginatedResponse<BlogPost>> {\n const qsStr = stringify(query);\n const res = await this.publicHttp.get<PaginatedResponse<BlogPost>>(\n `/public/stores/${storeRef}/blog/posts${qsStr ? \"?\" + qsStr : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Gets one published blog post by its slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the post slug\n * @param options - `incrementView` counts a view; `include_seo_metadata` and `include_products` add those fields\n * @returns The post, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getPostBySlug(\n storeRef: string,\n slug: string,\n options: {\n incrementView?: boolean;\n include_seo_metadata?: boolean;\n include_products?: boolean;\n } = {}\n ): Promise<BlogPost | null> {\n const query = stringify({\n increment_view: options.incrementView,\n include_seo_metadata: options.include_seo_metadata,\n include_products: options.include_products,\n });\n const res = await this.publicHttp.get<BlogPost>(\n `/public/stores/${storeRef}/blog/posts/slug/${encodeURIComponent(slug)}${query ? `?${query}` : \"\"}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Lists blog categories.\n *\n * @param storeRef - the store's ref or handle\n * @param query - filters and paging\n * @returns A page of categories; throws {@link ApiClientError} when the API answers with an error\n */\n async getCategories(\n storeRef: string,\n query: BlogCategoryQueryParams = {}\n ): Promise<PaginatedResponse<BlogCategory>> {\n const qsStr = stringify(query);\n const res = await this.publicHttp.get<PaginatedResponse<BlogCategory>>(\n `/public/stores/${storeRef}/blog/categories${qsStr ? \"?\" + qsStr : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists blog tags.\n *\n * @param storeRef - the store's ref or handle\n * @param query - filters and paging\n * @returns A page of tags; throws {@link ApiClientError} when the API answers with an error\n */\n async getTags(\n storeRef: string,\n query: BlogTagQueryParams = {}\n ): Promise<PaginatedResponse<BlogTag>> {\n const qsStr = stringify(query);\n const res = await this.publicHttp.get<PaginatedResponse<BlogTag>>(\n `/public/stores/${storeRef}/blog/tags${qsStr ? \"?\" + qsStr : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the approved comments of a post, as an anonymous visitor.\n *\n * @param storeRef - the store's ref or handle\n * @param postId - the post id\n * @returns The comments; throws {@link ApiClientError} when the API answers with an error\n */\n async getPostComments(storeRef: string, postId: number): Promise<any[]> {\n const res = await this.publicHttp.get<any[]>(\n `/public/stores/${storeRef}/blog/posts/${postId}/comments`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the approved comments of a post, sending the signed-in customer's credentials.\n *\n * @param storeRef - the store's ref or handle\n * @param postId - the post id\n * @returns The comments; throws {@link ApiClientError} when the API answers with an error\n */\n async getPostCommentsAuth(storeRef: string, postId: number): Promise<any[]> {\n const res = await this.authHttp.get<any[]>(\n `/public/stores/${storeRef}/blog/posts/${postId}/comments`\n );\n return unwrap(res);\n }\n\n /**\n * Submits a comment on a post, as the signed-in customer. It may wait for moderation.\n *\n * @param storeRef - the store's ref or handle\n * @param postId - the post id\n * @param data - the author name, the text, and optionally a website and the parent comment id\n * @returns The created comment; throws {@link ApiClientError} when the API answers with an error\n */\n async submitComment(\n storeRef: string,\n postId: number,\n data: {\n author_name: string;\n content: string;\n author_website?: string;\n parent_comment_id?: number;\n }\n ): Promise<any> {\n const res = await this.authHttp.post<any>(\n `/public/stores/${storeRef}/blog/posts/${postId}/comments`,\n data\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient, RequestOptions } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { Store, StoreByDomainInfo, StoreConfigurationInfo } from \"./types\";\n\n/**\n * Looking up a store and its public configuration, reached through `sdk.stores`.\n */\nexport class StoresApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Gets a store's public information, by default with its configuration, settings and embedded scripts.\n *\n * @param storeRef - the store's ref or handle\n * @param options - set `includeConfig`, `includeSettings` or `includeEmbeddedScripts` to `false` to leave that part out\n * @param requestOptions - extra request options, passed to the HTTP client only when given\n * @returns The store information, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(\n storeRef: string,\n options?: {\n includeConfig?: boolean;\n includeSettings?: boolean;\n includeEmbeddedScripts?: boolean;\n },\n requestOptions?: RequestOptions\n ): Promise<StoreConfigurationInfo | null> {\n const params = new URLSearchParams();\n if (options?.includeConfig ?? true) params.set(\"include_config\", \"1\");\n if (options?.includeSettings ?? true) params.set(\"include_settings\", \"1\");\n if (options?.includeEmbeddedScripts ?? true)\n params.set(\"include_embedded_scripts\", \"1\");\n const qs = params.toString();\n const url = `/public/stores/${storeRef}${qs ? `?${qs}` : \"\"}`;\n // Request options (as for getByDomain) reach the client only when given.\n const res = requestOptions\n ? await this.http.get<StoreConfigurationInfo>(url, requestOptions)\n : await this.http.get<StoreConfigurationInfo>(url);\n return unwrapOrNull(res);\n }\n\n /**\n * Gets a store by its subdomain.\n *\n * @param subdomain - the store's subdomain\n * @returns The store, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySubdomain(subdomain: string): Promise<Store | null> {\n const res = await this.http.get<Store>(\n `/public/stores/exists/subdomain/${subdomain}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * The store `domain` serves. `options` (e.g. an `x-store-preview` header,\n * which opens a coming soon store) is passed to the client only when given.\n */\n async getByDomain(\n domain: string,\n options?: RequestOptions\n ): Promise<StoreByDomainInfo | null> {\n const url = `/public/stores/domain/${domain}`;\n const res = options\n ? await this.http.get<StoreByDomainInfo>(url, options)\n : await this.http.get<StoreByDomainInfo>(url);\n return unwrapOrNull(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { PublishedStoreTheme } from \"../stores/types\";\n\n/** Refusals that mean \"no preview\": bad, expired or foreign token, or previews off. */\nconst NO_PREVIEW = [400, 401, 403, 404, 503];\n\n/**\n * Theme previews opened from the dashboard, reached through `sdk.themes`.\n */\nexport class ThemesApi {\n constructor(private http: IHttpClient) {}\n\n /** The store theme a dashboard preview link points to; null if refused. */\n async getPreview(\n storeRef: string,\n token: string\n ): Promise<PublishedStoreTheme | null> {\n const res = await this.http.get<PublishedStoreTheme>(\n `/public/stores/${storeRef}/theme-preview?token=${encodeURIComponent(token)}`\n );\n return unwrapOrNull(res, NO_PREVIEW);\n }\n\n /** The theme on a preview host, p-<slug>, with its saved values. */\n async getPreviewBySlug(\n storeRef: string,\n slug: string\n ): Promise<PublishedStoreTheme | null> {\n const res = await this.http.get<PublishedStoreTheme>(\n `/public/stores/${storeRef}/theme-preview?slug=${encodeURIComponent(slug)}`\n );\n return unwrapOrNull(res, NO_PREVIEW);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { StorefrontMetaobjectEntry } from \"../../types/metafields\";\nimport type { MetaobjectListParams, MetaobjectListResult } from \"./types\";\n\nconst EMPTY: MetaobjectListResult = { items: [], next_cursor: null };\n\n/**\n * Custom structured content (metaobject entries) a store publishes, reached through `sdk.metaobjects`.\n */\nexport class MetaobjectsApi {\n constructor(\n private publicHttp: IHttpClient,\n private authHttp: IHttpClient\n ) {}\n\n /**\n * Active entries of a metaobject type. A type that is unknown or hidden\n * from this reader lists as empty: the API answers 404 for both, the same\n * as a missing type, so it never reveals which types exist.\n */\n async list(\n storeRef: string,\n type: string,\n params: MetaobjectListParams = {}\n ): Promise<MetaobjectListResult> {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(params.filter ?? {})) {\n query.append(`filter[${key}]`, String(value));\n }\n if (params.cursor) query.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) query.set(\"limit\", String(params.limit));\n const search = query.toString();\n const http = params.as_customer ? this.authHttp : this.publicHttp;\n const res = await http.get<MetaobjectListResult>(\n `/public/stores/${storeRef}/metaobjects/${encodeURIComponent(type)}${search ? `?${search}` : \"\"}`\n );\n return unwrapOrNull(res, [404]) ?? EMPTY;\n }\n\n /** One active entry by handle; null when it, or its type, is missing or hidden. */\n async get(\n storeRef: string,\n type: string,\n handle: string,\n options: { as_customer?: boolean } = {}\n ): Promise<StorefrontMetaobjectEntry | null> {\n const http = options.as_customer ? this.authHttp : this.publicHttp;\n const res = await http.get<StorefrontMetaobjectEntry>(\n `/public/stores/${storeRef}/metaobjects/${encodeURIComponent(type)}/${encodeURIComponent(handle)}`\n );\n return unwrapOrNull(res, [404]);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n ProductSearchParams,\n AutocompleteParams,\n ProductSearchResponse,\n BlogSearchParams,\n BlogSearchResponse,\n} from \"./types\";\n\n/**\n * Search over a store's products and blog posts, reached through `sdk.search`.\n */\nexport class SearchApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Searches products.\n *\n * @param storeRef - the store's ref or handle\n * @param params - the query, filters and paging\n * @returns The matching products; throws {@link ApiClientError} when the API answers with an error\n */\n async searchCatalog(\n storeRef: string,\n params: ProductSearchParams\n ): Promise<ProductSearchResponse> {\n const queryString = stringify(params);\n const res = await this.http.get<ProductSearchResponse>(\n `/public/stores/${storeRef}/search/catalog${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Suggests product matches while the shopper is typing.\n *\n * @param storeRef - the store's ref or handle\n * @param params - the partial query and the suggestion limit\n * @returns The suggestions; throws {@link ApiClientError} when the API answers with an error\n */\n async autocompleteCatalog<T>(\n storeRef: string,\n params: AutocompleteParams\n ): Promise<T> {\n const queryString = stringify(params);\n const res = await this.http.get<T>(\n `/public/stores/${storeRef}/search/catalog/autocomplete${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Searches published blog posts.\n *\n * @param storeRef - the store's ref or handle\n * @param params - the query and paging\n * @returns The matching posts; throws {@link ApiClientError} when the API answers with an error\n */\n async searchBlog(\n storeRef: string,\n params: BlogSearchParams\n ): Promise<BlogSearchResponse> {\n const queryString = stringify(params);\n const res = await this.http.get<BlogSearchResponse>(\n `/public/stores/${storeRef}/search/blog${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n LocationAreaQuery,\n LocationAreasResponse,\n ShippingCalculationRequest,\n ShippingOption,\n} from \"./types\";\n\n/**\n * Shipping areas and shipping rates for a store, reached through `sdk.shipping`.\n */\nexport class ShippingApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * List administrative areas. Pass `level` for one tier or `parent_code`\n * for one area's children; passing neither returns every area, which for\n * Vietnam is 3,355 rows and about 900 KB. Prefer a filter.\n */\n async listLocationAreas(\n storeRef: string,\n query: LocationAreaQuery = {}\n ): Promise<LocationAreasResponse> {\n const params = new URLSearchParams();\n if (query.level !== undefined) params.set(\"level\", String(query.level));\n if (query.parent_code) params.set(\"parent_code\", query.parent_code);\n const qs = params.toString();\n\n const res = await this.http.get<LocationAreasResponse>(\n `/public/stores/${storeRef}/shipping/locations${qs ? `?${qs}` : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Works out the shipping options and prices for a cart and a destination.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the destination and the cart contents\n * @returns The available shipping options; throws {@link ApiClientError} when the API answers with an error\n */\n async calculate(\n storeRef: string,\n data: ShippingCalculationRequest\n ): Promise<ShippingOption[]> {\n const res = await this.http.post<ShippingOption[]>(\n `/public/stores/${storeRef}/shipping/calculate`,\n data\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n ValidatePromotionCodeRequest,\n ValidatePromotionCodeResponse,\n PromotionSuggestionsResponse,\n} from \"./types\";\n\n/**\n * Promotion codes and offers of a store, reached through `sdk.promotions`.\n */\nexport class PromotionsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Checks a promotion code against a cart.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the code and the cart details\n * @returns The validation result; throws {@link ApiClientError} when the API answers with an error\n */\n async validate(\n storeRef: string,\n data: ValidatePromotionCodeRequest\n ): Promise<ValidatePromotionCodeResponse> {\n const res = await this.http.post<ValidatePromotionCodeResponse>(\n `/public/stores/${storeRef}/promotions/validate`,\n data\n );\n return unwrap(res);\n }\n\n /**\n * Lists promotions the shopper could use, optionally for a given cart subtotal.\n *\n * @param storeRef - the store's ref or handle\n * @param subtotal - the cart subtotal in the store's currency\n * @returns The suggested promotions; throws {@link ApiClientError} when the API answers with an error\n */\n async getSuggestions(\n storeRef: string,\n subtotal?: number\n ): Promise<PromotionSuggestionsResponse> {\n const params = new URLSearchParams();\n if (subtotal !== undefined) params.append(\"subtotal\", subtotal.toString());\n const res = await this.http.get<PromotionSuggestionsResponse>(\n `/public/stores/${storeRef}/promotions/suggestions?${params.toString()}`\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { PaymentMethod } from \"./types\";\n\n/**\n * The payment methods a store accepts, reached through `sdk.paymentMethods`.\n */\nexport class PaymentMethodsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists the payment methods the store has turned on.\n *\n * @param storeRef - the store's ref or handle\n * @returns The enabled payment methods; throws {@link ApiClientError} when the API answers with an error\n */\n async getEnabled(storeRef: string): Promise<PaymentMethod[]> {\n const res = await this.http.get<PaymentMethod[]>(\n `/public/stores/${storeRef}/payment-methods`\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { InitiatePaymentResult, PaymentStateResult } from \"./types\";\n\n/**\n * Storefront-facing payment operations — starting a gateway charge and\n * polling its outcome. Deliberately separate from `PaymentMethodsApi`\n * (method listing) and from anything credential-related: the admin\n * credential surface is typed here (see ./types) but has no client method,\n * since the dashboard talks to it directly and this SDK must never carry a\n * plaintext credential shape.\n *\n * Both endpoints sit behind StorefrontApiKeyGuard, so both go through the\n * public HTTP client — the same one `PaymentMethodsApi` uses — never the\n * authenticated one.\n */\nexport class PaymentsApi {\n constructor(\n private publicHttp: IHttpClient,\n private authHttp: IHttpClient,\n ) {}\n\n /**\n * Start a gateway charge attempt for an order. Keyed by `order_code`,\n * never `order_id` — the API route was deliberately re-keyed away from a\n * sequential id, since StorefrontApiKeyGuard authenticates the store\n * rather than the shopper and a raw id would let anyone enumerate a\n * store's orders.\n */\n async initiate(\n storeRef: string,\n input: { order_code: string; provider_code: string },\n ): Promise<InitiatePaymentResult> {\n const res = await this.publicHttp.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code },\n );\n return unwrap(res);\n }\n\n /**\n * Poll payment/order status for an order while waiting on a gateway\n * redirect or callback. `order_code` is URL-encoded: order codes contain\n * `#` by default in this system, and an unencoded `#` truncates the URL.\n */\n async getPaymentState(\n storeRef: string,\n order_code: string,\n ): Promise<PaymentStateResult> {\n const res = await this.publicHttp.get<PaymentStateResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`,\n );\n return unwrap(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n PaginatedReviewsResponse,\n ProductReviewFilters,\n ReviewInvitationPublicData,\n SubmitReviewInvitationPayload,\n OrderReviewInvitationSummary,\n BatchOrderReviewInvitationsResult,\n} from \"./types\";\n\n/**\n * Product reviews and the invitations that ask customers to write them, reached through `sdk.reviews`.\n */\nexport class ReviewsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists the published reviews of a product.\n *\n * @param storeRef - the store's ref or handle\n * @param productId - the product id\n * @param query - filters and paging\n * @returns A page of reviews; throws {@link ApiClientError} when the API answers with an error\n */\n async getProductReviews(\n storeRef: string,\n productId: string | number,\n query?: Omit<ProductReviewFilters, \"product_id\">\n ): Promise<PaginatedReviewsResponse> {\n const queryString = stringify(query ?? {});\n const res = await this.http.get<PaginatedReviewsResponse>(\n `public/stores/${storeRef}/products/${productId}/reviews${queryString ? `?${queryString}` : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Gets the public details behind a review invitation link.\n *\n * @param storeRef - the store's ref or handle\n * @param token - the token from the invitation link\n * @returns The invitation details; throws {@link ApiClientError} when the API answers with an error\n */\n async getReviewInvitation(\n storeRef: string,\n token: string\n ): Promise<ReviewInvitationPublicData> {\n const res = await this.http.get<ReviewInvitationPublicData>(\n `public/stores/${storeRef}/review-invitations/${token}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the review invitations for one order.\n *\n * @param storeRef - the store's ref or handle\n * @param orderNumber - the order number\n * @param email - the email address on the order\n * @returns The invitation summaries; throws {@link ApiClientError} when the API answers with an error\n */\n async getOrderReviewInvitations(\n storeRef: string,\n orderNumber: number | string,\n email: string\n ): Promise<OrderReviewInvitationSummary[]> {\n const queryString = stringify({ order_number: orderNumber, email });\n const res = await this.http.get<OrderReviewInvitationSummary[]>(\n `public/stores/${storeRef}/review-invitations/by-order?${queryString}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the review invitations for several orders at once.\n *\n * @param storeRef - the store's ref or handle\n * @param orderNumbers - the order numbers\n * @param email - the email address on the orders\n * @returns The invitations grouped by order; throws {@link ApiClientError} when the API answers with an error\n */\n async getBatchOrderReviewInvitations(\n storeRef: string,\n orderNumbers: (number | string)[],\n email: string\n ): Promise<BatchOrderReviewInvitationsResult> {\n const queryString = stringify({ order_numbers: orderNumbers.join(\",\"), email });\n const res = await this.http.get<BatchOrderReviewInvitationsResult>(\n `public/stores/${storeRef}/review-invitations/by-orders?${queryString}`\n );\n return unwrap(res);\n }\n\n /**\n * Submits a review through an invitation link.\n *\n * @param storeRef - the store's ref or handle\n * @param token - the token from the invitation link\n * @param payload - the rating and review text\n * @returns The API's answer; throws {@link ApiClientError} when the API answers with an error\n */\n async submitReviewInvitation(\n storeRef: string,\n token: string,\n payload: SubmitReviewInvitationPayload\n ): Promise<any> {\n const res = await this.http.post(\n `public/stores/${storeRef}/review-invitations/${token}/submit`,\n payload\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient, ApiResponse } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { MetafieldWrite, StorefrontMetafields } from \"../../types/metafields\";\nimport type { Customer, UpsertCustomerForAuthPayload } from \"./types\";\n\n/**\n * The signed-in customer's profile record, reached through `sdk.customers`.\n */\nexport class CustomersApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Creates the customer record for a newly signed-in user, or updates it when it exists.\n *\n * @param storeRef - the store's ref or handle\n * @param payload - the identity fields to store\n * @returns The customer, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async upsertForAuth(\n storeRef: string,\n payload: UpsertCustomerForAuthPayload\n ): Promise<ApiResponse<Customer>> {\n return this.http.post<Customer>(\n `/stores/${storeRef}/customers/auth/upsert`,\n payload\n );\n }\n\n /** The signed-in customer's metafields with customer access (spec §6.6). */\n async getMetafields(storeRef: string): Promise<StorefrontMetafields> {\n const res = await this.http.get<StorefrontMetafields>(\n `/tenant/stores/${storeRef}/customers/metafields`\n );\n return unwrap(res);\n }\n\n /**\n * Writes read_write metafields; `value: null` clears one. Throws\n * METAFIELD_VALUE_INVALID (details.errors[] by path) or METAFIELD_NOT_WRITABLE.\n */\n async updateMetafields(\n storeRef: string,\n values: MetafieldWrite[]\n ): Promise<StorefrontMetafields> {\n const res = await this.http.put<StorefrontMetafields>(\n `/tenant/stores/${storeRef}/customers/metafields`,\n { values }\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { Address, CreateAddressDto, UpdateAddressDto } from \"./types\";\n\n/**\n * Saved delivery addresses of the signed-in customer, reached through `sdk.addresses`.\n */\nexport class AddressesApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @returns The addresses, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async list(storeRef: string): Promise<Address[] | null> {\n const res = await this.http.get<Address[]>(\n `/tenant/stores/${storeRef}/customers/address`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Gets one of the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @returns The address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(storeRef: string, addressId: number): Promise<Address | null> {\n const res = await this.http.get<Address>(\n `/tenant/stores/${storeRef}/customers/address/${addressId}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Saves a new address for the signed-in customer.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the address fields\n * @returns The created address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async create(\n storeRef: string,\n data: CreateAddressDto\n ): Promise<Address | null> {\n const res = await this.http.post<Address>(\n `/tenant/stores/${storeRef}/customers/address`,\n data\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Updates one of the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @param data - the fields to change\n * @returns The updated address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async update(\n storeRef: string,\n addressId: number,\n data: UpdateAddressDto\n ): Promise<Address | null> {\n const res = await this.http.patch<Address>(\n `/tenant/stores/${storeRef}/customers/address/${addressId}`,\n data\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Deletes one of the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @returns `true` when the API accepted the deletion, `false` otherwise; it does not throw\n */\n async delete(storeRef: string, addressId: number): Promise<boolean> {\n const res = await this.http.delete(\n `/tenant/stores/${storeRef}/customers/address/${addressId}`\n );\n return res.success;\n }\n\n /**\n * Makes a saved address the customer's default.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @returns The updated address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async setDefault(\n storeRef: string,\n addressId: number\n ): Promise<Address | null> {\n const res = await this.http.patch<Address>(\n `/tenant/stores/${storeRef}/customers/address/${addressId}/set-default`\n );\n return unwrapOrNull(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { PaginatedResponse } from \"../../types\";\nimport type { ContentPage } from \"./types\";\n\n/**\n * Static content pages of a store, such as About or Shipping policy, reached through `sdk.contentPages`.\n */\nexport class ContentPagesApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists the published content pages.\n *\n * @param storeRef - the store's ref or handle\n * @returns A page of content pages; throws {@link ApiClientError} when the API answers with an error\n */\n async getPublished(\n storeRef: string\n ): Promise<PaginatedResponse<ContentPage>> {\n const res = await this.http.get<PaginatedResponse<ContentPage>>(\n `/public/stores/${storeRef}/content-pages`\n );\n return unwrap(res);\n }\n\n /**\n * Gets one published content page by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the page slug\n * @param query - `include_seo_metadata` adds the SEO fields\n * @returns The page; throws {@link ApiClientError} when the API answers with an error\n */\n async getBySlug(\n storeRef: string,\n slug: string,\n query?: { include_seo_metadata?: boolean }\n ): Promise<ContentPage> {\n const queryString = query ? stringify(query) : \"\";\n const res = await this.http.get<ContentPage>(\n `/public/stores/${storeRef}/content-pages/${encodeURIComponent(slug)}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { StoreMenu } from \"./types\";\n\n/**\n * Navigation menus of a store, reached through `sdk.menus`.\n */\nexport class MenusApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Gets a navigation menu by its ref.\n *\n * @param storeRef - the store's ref or handle\n * @param ref - the menu ref\n * @param includeItems - `true` (the default) includes the menu items\n * @returns The menu, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getByRef(\n storeRef: string,\n ref: string,\n includeItems = true\n ): Promise<StoreMenu | null> {\n const query = includeItems ? \"?include_items=true\" : \"\";\n const res = await this.http.get<StoreMenu>(\n `/public/stores/${storeRef}/menus/ref/${encodeURIComponent(ref)}${query}`\n );\n return unwrapOrNull(res);\n }\n}\n","import type { IHttpClient, RequestOptions } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { UrlRedirect } from \"./types\";\n\n/**\n * URL redirects a store has set up, reached through `sdk.redirects`.\n */\nexport class RedirectsApi {\n constructor(private http: IHttpClient) {}\n\n /** `options` (request options) are passed to the client only when given. */\n async lookup(\n storeRef: string,\n path: string,\n options?: RequestOptions\n ): Promise<UrlRedirect | null> {\n const params = new URLSearchParams();\n params.set(\"path\", path);\n const url = `/public/stores/${storeRef}/url-redirects/lookup?${params.toString()}`;\n const res = options\n ? await this.http.get<{ data: UrlRedirect | null }>(url, options)\n : await this.http.get<{ data: UrlRedirect | null }>(url);\n const result = unwrapOrNull(res);\n return result?.data ?? null;\n }\n}\n","import type { ApiResponse, IHttpClient, RequestOptions } from \"../../core/types\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangeEmailResult,\n ChangePasswordPayload,\n ChangedResult,\n CurrentIdentity,\n GoogleAuthUrl,\n LoginPayload,\n PublicAuthConfig,\n RegisterPayload,\n RegisterResult,\n ResetPasswordPayload,\n ResetResult,\n SentResult,\n VerifiedResult,\n VerifyOtpPayload,\n} from \"./types\";\n\n/**\n * One store's auth surface.\n *\n * Two prefixes, not one: `public/` routes are unauthenticated and throttled,\n * `tenant/` routes require an access token and assert that the token's\n * store_id matches the route's store.\n *\n * This class does not supply `x-storefront-api-key` — StorefrontApiKeyGuard\n * requires it on every route, and the injected IHttpClient owns that header.\n */\nexport class AuthApi {\n constructor(\n private http: IHttpClient,\n private storeRef: string,\n ) {}\n\n private publicPath(suffix: string): string {\n return `/public/stores/${encodeURIComponent(this.storeRef)}/auth/${suffix}`;\n }\n\n private tenantPath(suffix: string): string {\n return `/tenant/stores/${encodeURIComponent(this.storeRef)}/auth/${suffix}`;\n }\n\n private auth(access_token: string): RequestOptions {\n return { headers: { Authorization: `Bearer ${access_token}` } };\n }\n\n // ---- unauthenticated -------------------------------------------------\n\n /** Never returns tokens: a new email and an existing one respond identically. */\n async register(payload: RegisterPayload): Promise<ApiResponse<RegisterResult>> {\n return this.http.post<RegisterResult>(this.publicPath(\"register\"), payload, undefined);\n }\n\n /**\n * Signs a customer in with email and password.\n *\n * @param payload - the login credentials\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async login(payload: LoginPayload): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(this.publicPath(\"login\"), payload, undefined);\n }\n\n /**\n * Exchanges a refresh token for a new token pair. The old refresh token stops working.\n *\n * @param refresh_token - the customer's current refresh token\n * @returns The new token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async refresh(refresh_token: string): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(\n this.publicPath(\"refresh\"),\n { refresh_token },\n undefined,\n );\n }\n\n /**\n * `binding` is the register response's `verification_binding`, when this\n * client still has it. Omitted, the address is verified but the password\n * set at registration is dropped.\n */\n async verifyEmail(\n token: string,\n binding?: string,\n ): Promise<ApiResponse<VerifiedResult>> {\n return this.http.post<VerifiedResult>(\n this.publicPath(\"verify-email\"),\n binding ? { token, binding } : { token },\n undefined,\n );\n }\n\n /**\n * Sends the email-verification message again.\n *\n * @param email - the address to verify\n * @returns The send result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async resendVerification(email: string): Promise<ApiResponse<SentResult>> {\n return this.http.post<SentResult>(\n this.publicPath(\"resend-verification\"),\n { email },\n undefined,\n );\n }\n\n /**\n * Starts a password reset by emailing a reset link.\n *\n * @param email - the account's email address\n * @returns The send result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async forgotPassword(email: string): Promise<ApiResponse<SentResult>> {\n return this.http.post<SentResult>(\n this.publicPath(\"forgot-password\"),\n { email },\n undefined,\n );\n }\n\n /**\n * Sets a new password using the token from the reset email.\n *\n * @param payload - the reset token and the new password\n * @returns The reset result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async resetPassword(\n payload: ResetPasswordPayload,\n ): Promise<ApiResponse<ResetResult>> {\n return this.http.post<ResetResult>(\n this.publicPath(\"reset-password\"),\n payload,\n undefined,\n );\n }\n\n /** `binding` is the change-email response's `confirmation_binding`. */\n async confirmEmailChange(\n token: string,\n binding?: string,\n ): Promise<ApiResponse<ChangedResult>> {\n return this.http.post<ChangedResult>(\n this.publicPath(\"change-email/confirm\"),\n binding ? { token, binding } : { token },\n undefined,\n );\n }\n\n /**\n * Emails a one-time sign-in code.\n *\n * @param email - the account's email address\n * @returns The send result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async requestOtp(email: string): Promise<ApiResponse<SentResult>> {\n return this.http.post<SentResult>(\n this.publicPath(\"otp/request\"),\n { email },\n undefined,\n );\n }\n\n /**\n * Signs a customer in with the one-time code from the email.\n *\n * @param payload - the email and the code\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async verifyOtp(payload: VerifyOtpPayload): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(\n this.publicPath(\"otp/verify\"),\n payload,\n undefined,\n );\n }\n\n /**\n * Starts an anonymous (guest) session.\n *\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async anonymous(): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(this.publicPath(\"anonymous\"), undefined, undefined);\n }\n\n /**\n * Gets the URL that starts Google sign-in.\n *\n * @param redirect_to - where to send the customer after sign-in, `/` by default\n * @returns The Google sign-in URL, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async getGoogleUrl(redirect_to = \"/\"): Promise<ApiResponse<GoogleAuthUrl>> {\n const query = `?redirect_to=${encodeURIComponent(redirect_to)}`;\n return this.http.get<GoogleAuthUrl>(\n `${this.publicPath(\"google/url\")}${query}`,\n undefined,\n );\n }\n\n /**\n * Completes Google sign-in by exchanging the authorization code.\n *\n * @param code - the authorization code Google returned\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async exchangeGoogleCode(code: string): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(\n this.publicPath(\"google/exchange\"),\n { code },\n undefined,\n );\n }\n\n /**\n * Reads which sign-in methods this store has turned on.\n *\n * @returns The public auth configuration, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async getAuthConfig(): Promise<ApiResponse<PublicAuthConfig>> {\n return this.http.get<PublicAuthConfig>(this.publicPath(\"config\"), undefined);\n }\n\n // ---- access token required -------------------------------------------\n\n /**\n * Reads the signed-in customer's identity.\n *\n * @param access_token - the signed-in customer's access token\n * @returns The current identity, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async me(access_token: string): Promise<ApiResponse<CurrentIdentity | null>> {\n return this.http.get<CurrentIdentity | null>(\n this.tenantPath(\"me\"),\n this.auth(access_token),\n );\n }\n\n /** Revokes one session. The refresh token identifies which. */\n async logout(\n access_token: string,\n refresh_token: string,\n ): Promise<ApiResponse<unknown>> {\n return this.http.post<unknown>(\n this.tenantPath(\"logout\"),\n { refresh_token },\n this.auth(access_token),\n );\n }\n\n /**\n * Signs the customer out of every session.\n *\n * @param access_token - the signed-in customer's access token\n * @returns The API's answer, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async logoutAll(access_token: string): Promise<ApiResponse<unknown>> {\n return this.http.post<unknown>(\n this.tenantPath(\"logout-all\"),\n undefined,\n this.auth(access_token),\n );\n }\n\n /**\n * Changes the signed-in customer's password.\n *\n * @param access_token - the signed-in customer's access token\n * @param payload - the current and the new password\n * @returns The API's answer, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async changePassword(\n access_token: string,\n payload: ChangePasswordPayload,\n ): Promise<ApiResponse<unknown>> {\n return this.http.post<unknown>(\n this.tenantPath(\"change-password\"),\n payload,\n this.auth(access_token),\n );\n }\n\n /**\n * Starts an email change; the new address must be confirmed from the message sent to it.\n *\n * @param access_token - the signed-in customer's access token\n * @param payload - the new email address and the current password\n * @returns The change-email result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async changeEmail(\n access_token: string,\n payload: ChangeEmailPayload,\n ): Promise<ApiResponse<ChangeEmailResult>> {\n return this.http.post<ChangeEmailResult>(\n this.tenantPath(\"change-email\"),\n payload,\n this.auth(access_token),\n );\n }\n}\n","import type { AuthTokens } from \"./types\";\n\n/**\n * Where a consumer keeps the token pair.\n *\n * Supplied by the consumer, not chosen by the SDK: the three runtimes the SDK\n * targets (server components, route handlers, browser) each need a different\n * mechanism, and two of the three break under any hardcoded choice.\n */\nexport interface TokenStorage {\n get(): Promise<AuthTokens | null>;\n set(tokens: AuthTokens): Promise<void>;\n clear(): Promise<void>;\n}\n\n/** Process-local. Suitable for tests and for a single server-side request. */\nexport class MemoryTokenStorage implements TokenStorage {\n private tokens: AuthTokens | null;\n\n constructor(initial: AuthTokens | null = null) {\n this.tokens = initial;\n }\n\n /**\n * Reads the stored token pair.\n *\n * @returns The stored tokens, or `null` when none are stored\n */\n async get(): Promise<AuthTokens | null> {\n return this.tokens;\n }\n\n /**\n * Stores a token pair, replacing any earlier one.\n *\n * @param tokens - the access and refresh tokens\n */\n async set(tokens: AuthTokens): Promise<void> {\n this.tokens = tokens;\n }\n\n /**\n * Forgets the stored token pair.\n */\n async clear(): Promise<void> {\n this.tokens = null;\n }\n}\n","import type { ApiResponse, IHttpClient, RequestOptions } from \"../../core/types\";\nimport type { AuthApi } from \"./api\";\nimport type { TokenStorage } from \"./token-storage\";\n\ninterface Options {\n storage: TokenStorage;\n auth: AuthApi;\n}\n\n/**\n * Wraps an IHttpClient so a 401 triggers one refresh and one retry.\n *\n * The single-flight promise is the point of the whole file. Without it, a page\n * that fires five requests behind an expired access token performs five\n * refreshes; the first rotates and revokes the refresh token, and the other\n * four present a token that no longer exists — logging the user out on load.\n */\nexport function createAuthAwareHttpClient(\n inner: IHttpClient,\n { storage, auth }: Options,\n): IHttpClient {\n let inFlight: Promise<boolean> | null = null;\n\n /** Resolves true when storage holds a freshly rotated pair. */\n async function refreshOnce(): Promise<boolean> {\n if (inFlight) return inFlight;\n\n inFlight = (async () => {\n try {\n const current = await storage.get();\n\n // No refresh token means there is nothing to rotate. Clearing here\n // would be wrong: there may be no session at all, and clear() on an\n // empty store is a no-op that hides the distinction.\n if (!current?.refresh_token) return false;\n\n const response = await auth.refresh(current.refresh_token);\n const data = response.success ? response.data : null;\n\n if (!data?.access_token || !data.refresh_token) {\n await storage.clear();\n return false;\n }\n\n await storage.set({\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n });\n\n return true;\n } catch {\n // A network failure mid-refresh leaves the stored pair in an unknown\n // state. Clearing is the safe read: the caller re-authenticates.\n await storage.clear();\n return false;\n } finally {\n inFlight = null;\n }\n })();\n\n return inFlight;\n }\n\n async function withRetry<T>(\n send: () => Promise<ApiResponse<T>>,\n ): Promise<ApiResponse<T>> {\n const first = await send();\n\n if (first.success || first.error?.statusCode !== 401) return first;\n\n const refreshed = await refreshOnce();\n\n if (!refreshed) return first;\n\n // Exactly one retry. A second 401 means the new token is also rejected,\n // which refreshing again cannot fix.\n return send();\n }\n\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n withRetry<T>(() => inner.get<T>(url, options)),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n withRetry<T>(() => inner.post<T>(url, data, options)),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n withRetry<T>(() => inner.put<T>(url, data, options)),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n withRetry<T>(() => inner.patch<T>(url, data, options)),\n delete: <T>(url: string, options?: RequestOptions) =>\n withRetry<T>(() => inner.delete<T>(url, options)),\n };\n}\n","/**\n * Smart collection rule vocabulary — the shared contract between the API and\n * every client that renders or builds collection rules.\n *\n * This is the SINGLE declaration of which fields a merchant may write a rule\n * against and which operators each field accepts. The dashboard renders its\n * field and operator dropdowns from it; the API validates incoming rule sets\n * against its own mirror and rejects anything outside this vocabulary.\n *\n * Deliberately absent: how each field maps onto the search index. That is\n * server implementation detail (a price rule inverts across two index fields,\n * for instance) and must not leak into a client.\n *\n * If you change this, change the API's RULE_MATRIX in\n * src/modules/search/application/utils/collection-rule-set.utils.ts to match.\n * The API cannot import this package (it is a client OF that API, so the\n * dependency would be inverted), so it pins this vocabulary in\n * collection-rule-vocabulary.contract.spec.ts instead: changing RULE_MATRIX\n * fails that test until the change is mirrored here.\n */\n\nexport type RuleField =\n | \"title\"\n | \"sku\"\n | \"tag\"\n | \"category\"\n | \"attribute\"\n | \"price\"\n | \"rating\"\n | \"stock\"\n | \"promotion\"\n | \"discount\"\n | \"video\"\n | \"sales\"\n | \"sales_30d\"\n | \"status\";\n\nexport type RuleOperator =\n | \"equals\"\n | \"not_equals\"\n | \"any_of\"\n | \"all_of\"\n | \"none_of\"\n | \"in_subtree\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"between\"\n | \"is_true\"\n | \"is_false\";\n\n/** What shape of `value` an operator expects. \"none\" means the operator\n * carries its meaning entirely in its name (is_true / is_false). */\nexport type RuleValueKind =\n | \"none\"\n | \"number\"\n | \"number_pair\"\n | \"number_list\"\n | \"string\"\n | \"string_list\"\n | \"attr_token_list\"\n | \"text\";\n\nexport interface RuleOperatorSpec {\n value_kind: RuleValueKind;\n}\n\nexport interface RuleFieldSpec {\n operators: Readonly<Record<string, RuleOperatorSpec>>;\n /** When present, a string value must be one of these. */\n allowed_values?: readonly string[];\n}\n\nexport interface CollectionRule {\n field: RuleField;\n op: RuleOperator;\n value?: string | number | string[] | number[];\n}\n\nexport interface CollectionRuleSet {\n /** \"all\" ANDs the rules, \"any\" ORs them. Defaults to \"all\". */\n match: \"all\" | \"any\";\n /** An empty list means every product. */\n rules: CollectionRule[];\n}\n\n/** A collection's search_criteria once it carries rule-model criteria. */\nexport interface CollectionRuleSetCriteria {\n rule_set: CollectionRuleSet;\n}\n\n/**\n * `title` and `sku` offer `equals` only — no `contains`, `ends_with`, or\n * `starts_with`. Verified against Typesense 29.0: filter_by on a string field\n * does case-insensitive TOKEN CONTAINMENT, not prefix matching, and a\n * trailing `*` is silently ignored (`` name:`jeans*` `` returns the same rows\n * as `` name:`jeans` ``, while `` name:`jean*` `` returns nothing). Offering\n * `starts_with` would show a merchant an operator whose label lies about what\n * the server actually does.\n */\nexport const COLLECTION_RULE_MATRIX = {\n title: {\n operators: {\n equals: { value_kind: \"text\" },\n },\n },\n sku: {\n operators: {\n equals: { value_kind: \"text\" },\n },\n },\n tag: {\n operators: {\n any_of: { value_kind: \"number_list\" },\n all_of: { value_kind: \"number_list\" },\n none_of: { value_kind: \"number_list\" },\n },\n },\n category: {\n operators: {\n equals: { value_kind: \"string\" },\n not_equals: { value_kind: \"string\" },\n any_of: { value_kind: \"string_list\" },\n // Matches the category and everything beneath it. Compiles against the\n // materialized ancestor paths, so \"all apparel\" no longer means\n // enumerating every leaf.\n in_subtree: { value_kind: \"string\" },\n },\n },\n attribute: {\n operators: {\n any_of: { value_kind: \"attr_token_list\" },\n none_of: { value_kind: \"attr_token_list\" },\n },\n },\n price: {\n operators: {\n gt: { value_kind: \"number\" },\n gte: { value_kind: \"number\" },\n lt: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n between: { value_kind: \"number_pair\" },\n },\n },\n rating: {\n operators: {\n gte: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n },\n },\n stock: {\n operators: {\n is_true: { value_kind: \"none\" },\n is_false: { value_kind: \"none\" },\n },\n },\n promotion: {\n operators: {\n is_true: { value_kind: \"none\" },\n is_false: { value_kind: \"none\" },\n },\n },\n discount: {\n operators: {\n gte: { value_kind: \"number\" },\n },\n },\n video: {\n operators: {\n is_true: { value_kind: \"none\" },\n is_false: { value_kind: \"none\" },\n },\n },\n sales: {\n operators: {\n gte: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n },\n },\n sales_30d: {\n operators: {\n gte: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n },\n },\n status: {\n operators: {\n equals: { value_kind: \"string\" },\n not_equals: { value_kind: \"string\" },\n },\n allowed_values: [\"active\", \"draft\", \"archived\"],\n },\n} as const satisfies Record<string, RuleFieldSpec>;\n\n/** Display order for the field selector. */\nexport const RULE_FIELDS: readonly RuleField[] = [\n \"title\",\n \"sku\",\n \"tag\",\n \"category\",\n \"attribute\",\n \"price\",\n \"rating\",\n \"stock\",\n \"promotion\",\n \"discount\",\n \"video\",\n \"sales\",\n \"sales_30d\",\n \"status\",\n];\n\n/** Caps the API enforces. Clients should mirror them so a merchant is told\n * before the request rather than after it is rejected. */\nexport const MAX_RULES_PER_SET = 25;\nexport const MAX_RULE_VALUE_ENTRIES = 100;\n\n/**\n * Tells whether a name is a field that smart collection rules can use.\n *\n * @param name - the name to test\n * @returns `true` when it is a rule field\n */\nexport function isRuleField(name: string): name is RuleField {\n return Object.prototype.hasOwnProperty.call(COLLECTION_RULE_MATRIX, name);\n}\n\n/** The operators a field accepts, in display order. Empty for unknown fields. */\nexport function operatorsForField(field: string): RuleOperator[] {\n if (!isRuleField(field)) return [];\n return Object.keys(\n COLLECTION_RULE_MATRIX[field].operators\n ) as RuleOperator[];\n}\n\n/** The value shape a given field/operator pair expects, or undefined if the\n * field does not accept that operator. */\nexport function valueKindFor(\n field: string,\n op: string\n): RuleValueKind | undefined {\n if (!isRuleField(field)) return undefined;\n const operators = COLLECTION_RULE_MATRIX[field].operators as Record<\n string,\n RuleOperatorSpec\n >;\n return Object.prototype.hasOwnProperty.call(operators, op)\n ? operators[op].value_kind\n : undefined;\n}\n\n/** Values a string-valued field is restricted to, if any. */\nexport function allowedValuesFor(field: string): readonly string[] | undefined {\n if (!isRuleField(field)) return undefined;\n return (\n COLLECTION_RULE_MATRIX[field] as RuleFieldSpec\n ).allowed_values;\n}\n","/**\n * One administrative area, at any depth, for any country. Replaces the\n * old Province/Ward pair: they differed only by which fields were\n * populated, and `level` now carries that distinction (for Vietnam,\n * 1 = province, 2 = ward).\n *\n * The old `id` was the source JSON object's own key, never a stable\n * identifier. Areas are addressed by `code`.\n */\nexport interface LocationArea {\n level: number;\n code: string;\n parent_code: string | null;\n name: string;\n name_with_type: string;\n type: string;\n slug: string;\n /** Null for a top-level area: a province has no path through parents. */\n path: string | null;\n path_with_type: string | null;\n}\n\nexport const LEVEL_PROVINCE = 1;\nexport const LEVEL_WARD = 2;\n\nexport interface LocationAreaQuery {\n /** 1 = province, 2 = ward. */\n level?: number;\n /** Return this area's children, e.g. \"11\" for Ha Noi's wards. */\n parent_code?: string;\n}\n\nexport interface LocationAreasResponse {\n country_code: string;\n areas: LocationArea[];\n}\n\nexport interface ShippingCalculationRequest {\n province_id?: string;\n ward_id?: string;\n province?: string;\n district?: string;\n postal_code?: string;\n subtotal: number;\n currency: string;\n weight_gr: number;\n method?: \"standard\" | \"express\" | \"pickup\" | \"cod\";\n distance_km?: number;\n tags?: string[];\n /** Opt in to live carrier rates alongside fixed ones. Not defaulted by the SDK. */\n include_carrier_options?: boolean;\n}\n\nexport const SHIPPING_DELIVERY_TYPES = [\n \"STANDARD\",\n \"EXPRESS\",\n \"SAME_DAY\",\n \"ECONOMY\",\n \"PICKUP\",\n] as const;\nexport type ShippingDeliveryType = (typeof SHIPPING_DELIVERY_TYPES)[number];\n\n/** FREE is deliberately absent: a free rate is amount 0. */\nexport const SHIPPING_RATE_TYPES = [\"FIXED\", \"CARRIER_QUOTE\"] as const;\nexport type ShippingRateType = (typeof SHIPPING_RATE_TYPES)[number];\n\nexport const SHIPPING_CONDITION_TYPES = [\n \"NONE\",\n \"ORDER_VALUE\",\n \"WEIGHT\",\n] as const;\nexport type ShippingConditionType = (typeof SHIPPING_CONDITION_TYPES)[number];\n\nexport interface ShippingZone {\n id: number;\n code: string;\n name: string;\n provinces: string[];\n wards: string[];\n is_catch_all: boolean;\n}\n\nexport interface ShippingRate {\n id: number;\n zone_id: number;\n delivery_type: ShippingDeliveryType;\n display_name: string;\n rate_type: ShippingRateType;\n amount: number;\n condition_type: ShippingConditionType;\n min_value: number | null;\n max_value: number | null;\n estimated_days_min: number | null;\n estimated_days_max: number | null;\n is_active: boolean;\n sort_order: number;\n}\n\nexport interface ShippingOption {\n amount: number;\n currency: string;\n rate_id: number;\n /** `<rate_id>` for fixed, `<rate_id>:<service_id>` for carrier; absent from APIs before carrier rates. */\n option_id?: string;\n delivery_type: ShippingDeliveryType;\n display_name: string;\n estimated_days_min?: number | null;\n estimated_days_max?: number | null;\n /** Set on carrier-quoted options only. */\n carrier_code?: \"allingo\";\n /** The carrier's own id for the chosen service. */\n carrier_service_id?: string;\n /** Carrier display name, e.g. for a label beside the price. */\n carrier_name?: string;\n /** The carrier's service, e.g. \"Giao chuẩn\"; tells two options of one carrier apart. */\n carrier_service_name?: string;\n /** Carrier logo, or null when the carrier has none. */\n carrier_logo_url?: string | null;\n /** Human-readable delivery estimate from the carrier, or null. */\n estimated_label?: string | null;\n /** Populated only when the caller asks for debug output. */\n zone_id?: number;\n zone_name?: string;\n shadowed_zones?: Array<{ id: number; name: string; rank: number }>;\n}\n\n/** Error codes the shipping endpoints and order creation can return. */\nexport const SHIPPING_ERROR_CODES = {\n QUOTE_CHANGED: \"SHIPPING_QUOTE_CHANGED\",\n RATE_UNAVAILABLE: \"ORDER_SHIPPING_RATE_UNAVAILABLE\",\n} as const;\n\n/** `details` of a SHIPPING_QUOTE_CHANGED error: the options now on offer. */\nexport interface ShippingQuoteChangedDetails {\n options: ShippingOption[];\n}\n","/**\n * The EcomWeb storefront SDK: a typed client for a store's public API.\n *\n * Call {@link createEcomwebSdk} with two HTTP clients and use the returned\n * object, for example `sdk.products.getBySlug(storeRef, slug)`. The package\n * also exports the schema and DTO types the API uses, the image URL helpers,\n * and {@link ApiClientError}, which the client methods throw when the API\n * answers with an error.\n *\n * @packageDocumentation\n */\n\n// Core\nexport type {\n IHttpClient,\n ApiResponse,\n ApiError,\n RequestOptions,\n} from \"./core/types\";\nexport {\n CLIENT_HEADER,\n SDK_CLIENT_TOKEN,\n SDK_VERSION,\n clientHeaderValue,\n withClientHeader,\n} from \"./core/client-info\";\nexport {\n ApiClientError,\n unwrap,\n unwrapOrNull,\n ensureSuccess,\n} from \"./core/response\";\n\n// Schema and contract types\nexport * from \"./types\";\n\n// Storage — URL helpers only. Objects are uploaded through the API's asset\n// endpoints; there is no storage client here and no Supabase dependency.\nexport {\n assetBaseUrl,\n buildTransformQuery,\n parseStorageUrl,\n resolveAssetUrl,\n toObjectUrl,\n toRenderUrl,\n fromObjectPublicUrlToRender,\n rewriteSupabaseUrl,\n transformationsEnabled,\n OBJECT_PREFIX,\n RENDER_PREFIX,\n DEFAULT_BUCKET,\n} from \"./modules/storage/image-transform\";\nexport type {\n ImageTransformOptions,\n ResizeMode,\n ImageFormat,\n} from \"./modules/storage/types\";\n\n// Modules — API classes\nexport { ProductsApi } from \"./modules/products/api\";\nexport { CollectionsApi } from \"./modules/collections/api\";\nexport { CategoriesApi } from \"./modules/categories/api\";\nexport { CartApi } from \"./modules/cart/api\";\nexport { OrdersApi } from \"./modules/orders/api\";\nexport { BlogApi } from \"./modules/blog/api\";\nexport { StoresApi } from \"./modules/stores/api\";\nexport { ThemesApi } from \"./modules/themes/api\";\nexport { MetaobjectsApi } from \"./modules/metaobjects/api\";\nexport { SearchApi } from \"./modules/search/api\";\nexport { ShippingApi } from \"./modules/shipping/api\";\nexport { PromotionsApi } from \"./modules/promotions/api\";\nexport { PaymentMethodsApi } from \"./modules/payment-methods/api\";\nexport { PaymentsApi } from \"./modules/payments/api\";\nexport { ReviewsApi } from \"./modules/reviews/api\";\nexport { CustomersApi } from \"./modules/customers/api\";\nexport { AddressesApi } from \"./modules/addresses/api\";\nexport { ContentPagesApi } from \"./modules/content-pages/api\";\nexport { MenusApi } from \"./modules/menus/api\";\nexport { RedirectsApi } from \"./modules/redirects/api\";\nexport { AuthApi } from \"./modules/auth/api\";\nexport { MemoryTokenStorage } from \"./modules/auth/token-storage\";\nexport { createAuthAwareHttpClient } from \"./modules/auth/refresh-client\";\n\n// Modules — Types\nexport type {\n ProductDetail,\n ProductQueryParams,\n ProductService,\n PromotionData,\n WithSeoMetadata,\n SeoMetadata,\n Product,\n ProductWithVariants,\n ProductVariant,\n VariantOption,\n VariantOptionValue,\n ProductImage,\n ProductVideo,\n} from \"./modules/products/types\";\n\nexport type {\n Collection,\n CollectionQueryParams,\n CollectionSearchCriteria,\n} from \"./modules/collections/types\";\n\n// Smart collection rule vocabulary — the shared field/operator contract.\nexport type {\n RuleField,\n RuleOperator,\n RuleValueKind,\n RuleOperatorSpec,\n RuleFieldSpec,\n CollectionRule,\n CollectionRuleSet,\n CollectionRuleSetCriteria,\n} from \"./modules/collections/rule-set\";\nexport {\n COLLECTION_RULE_MATRIX,\n RULE_FIELDS,\n MAX_RULES_PER_SET,\n MAX_RULE_VALUE_ENTRIES,\n isRuleField,\n operatorsForField,\n valueKindFor,\n allowedValuesFor,\n} from \"./modules/collections/rule-set\";\n\nexport type { Category, CategoryQueryParams } from \"./modules/categories/types\";\n\nexport type {\n CartApiItem,\n CartApiResponse,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"./modules/cart/types\";\n\nexport type {\n Order,\n OrderItem,\n OrderWithItems,\n CreateOrderRequest,\n CreateOrderItemRequest,\n CustomerOrderFilter,\n GuestOrderLookupParams,\n PaymentMethod as OrderPaymentMethod,\n} from \"./modules/orders/types\";\n\nexport type {\n BlogPost,\n BlogCategory,\n BlogTag,\n BlogPostStatus,\n BlogSettings,\n BlogPostQueryParams,\n BlogCategoryQueryParams,\n BlogTagQueryParams,\n} from \"./modules/blog/types\";\n\nexport type {\n Store,\n StoreConfig,\n StoreSettings,\n StoreConfigurationInfo,\n StoreByDomainInfo,\n PublishedStoreTheme,\n StoreStatus,\n} from \"./modules/stores/types\";\n\nexport type {\n ProductSearchParams,\n AutocompleteParams,\n SearchProduct,\n SearchCategory,\n ProductSearchResponse,\n CategorySearchResponse,\n BlogSearchParams,\n BlogSearchResponse,\n} from \"./modules/search/types\";\n\nexport type {\n LocationArea,\n LocationAreaQuery,\n LocationAreasResponse,\n ShippingCalculationRequest,\n ShippingDeliveryType,\n ShippingRateType,\n ShippingConditionType,\n ShippingZone,\n ShippingRate,\n ShippingOption,\n ShippingQuoteChangedDetails,\n} from \"./modules/shipping/types\";\nexport {\n SHIPPING_DELIVERY_TYPES,\n SHIPPING_RATE_TYPES,\n SHIPPING_CONDITION_TYPES,\n SHIPPING_ERROR_CODES,\n LEVEL_PROVINCE,\n LEVEL_WARD,\n} from \"./modules/shipping/types\";\n\nexport type {\n ValidatePromotionCodeRequest,\n ValidatePromotionCodeResponse,\n PromotionSuggestion,\n PromotionSuggestionsResponse,\n} from \"./modules/promotions/types\";\n\nexport type {\n PaymentMethod as StorePaymentMethod,\n BankAccount,\n} from \"./modules/payment-methods/types\";\n\nexport type {\n InitiatePaymentResult,\n PaymentStateResult,\n PaymentCredentialStatus,\n} from \"./modules/payments/types\";\n\nexport type {\n ProductReview,\n ProductReviewWithReplies,\n ProductReviewFilters,\n PaginatedReviewsResponse,\n ReviewInvitationPublicData,\n SubmitReviewInvitationPayload,\n OrderReviewInvitationSummary,\n BatchOrderReviewInvitationsResult,\n} from \"./modules/reviews/types\";\n\nexport type {\n Customer,\n UpsertCustomerForAuthPayload,\n} from \"./modules/customers/types\";\n\nexport type {\n Address,\n CreateAddressDto,\n UpdateAddressDto,\n} from \"./modules/addresses/types\";\n\nexport type { ContentPage } from \"./modules/content-pages/types\";\n\nexport type { StoreMenu, StoreMenuItem } from \"./modules/menus/types\";\n\nexport type {\n MetaobjectListParams,\n MetaobjectListResult,\n} from \"./modules/metaobjects/types\";\n\nexport type { UrlRedirect } from \"./modules/redirects/types\";\n\nexport type {\n AuthResult,\n AuthIdentity,\n AuthTokens,\n CurrentIdentity,\n PasswordPolicy,\n PublicAuthConfig,\n GoogleAuthUrl,\n RegisterPayload,\n RegisterResult,\n LoginPayload,\n ChangePasswordPayload,\n ChangeEmailPayload,\n ChangeEmailResult,\n ResetPasswordPayload,\n VerifyOtpPayload,\n SentResult,\n VerifiedResult,\n ResetResult,\n ChangedResult,\n AuthErrorCode,\n} from \"./modules/auth/types\";\nexport type { TokenStorage } from \"./modules/auth/token-storage\";\n\n// SDK factory\nimport type { IHttpClient } from \"./core/types\";\nimport { withClientHeader } from \"./core/client-info\";\nimport { ProductsApi } from \"./modules/products/api\";\nimport { CollectionsApi } from \"./modules/collections/api\";\nimport { CategoriesApi } from \"./modules/categories/api\";\nimport { CartApi } from \"./modules/cart/api\";\nimport { OrdersApi } from \"./modules/orders/api\";\nimport { BlogApi } from \"./modules/blog/api\";\nimport { StoresApi } from \"./modules/stores/api\";\nimport { ThemesApi } from \"./modules/themes/api\";\nimport { MetaobjectsApi } from \"./modules/metaobjects/api\";\nimport { SearchApi } from \"./modules/search/api\";\nimport { ShippingApi } from \"./modules/shipping/api\";\nimport { PromotionsApi } from \"./modules/promotions/api\";\nimport { PaymentMethodsApi } from \"./modules/payment-methods/api\";\nimport { PaymentsApi } from \"./modules/payments/api\";\nimport { ReviewsApi } from \"./modules/reviews/api\";\nimport { CustomersApi } from \"./modules/customers/api\";\nimport { AddressesApi } from \"./modules/addresses/api\";\nimport { ContentPagesApi } from \"./modules/content-pages/api\";\nimport { MenusApi } from \"./modules/menus/api\";\nimport { RedirectsApi } from \"./modules/redirects/api\";\n\n/** What {@link createEcomwebSdk} needs: the two HTTP clients, and optional client info. */\nexport interface EcomwebSdkOptions {\n /** Client for the public API routes, used for anonymous shoppers. */\n publicHttp: IHttpClient;\n /** Client for the routes that need the signed-in customer's credentials. */\n authHttp: IHttpClient;\n /**\n * Tokens put before this SDK's own in the `X-Ecomweb-Client` header\n * (space-separated `name/version`, e.g. `@ecomweb/storefront-kit/0.14.0`).\n */\n clientInfo?: string;\n}\n\n/**\n * Creates the SDK client. Each property of the result is one API resource, and\n * each method on it makes one request to the store's API.\n *\n * @example\n * ```ts\n * const sdk = createEcomwebSdk({ publicHttp, authHttp });\n * const product = await sdk.products.getBySlug(\"my-store\", \"blue-shirt\");\n * ```\n *\n * @param options - the HTTP clients, and optional client info for the `X-Ecomweb-Client` header\n * @returns An object with one API class per resource: `products`, `collections`, `categories`, `cart`, `orders`, `blog`, `stores`, `themes`, `metaobjects`, `search`, `shipping`, `promotions`, `paymentMethods`, `payments`, `reviews`, `customers`, `addresses`, `contentPages`, `menus` and `redirects`\n */\nexport function createEcomwebSdk(options: EcomwebSdkOptions) {\n const publicHttp = withClientHeader(options.publicHttp, options.clientInfo);\n const authHttp = withClientHeader(options.authHttp, options.clientInfo);\n return {\n products: new ProductsApi(publicHttp),\n collections: new CollectionsApi(publicHttp),\n categories: new CategoriesApi(publicHttp),\n cart: new CartApi(publicHttp, authHttp),\n orders: new OrdersApi(publicHttp, authHttp),\n blog: new BlogApi(publicHttp, authHttp),\n stores: new StoresApi(publicHttp),\n themes: new ThemesApi(publicHttp),\n metaobjects: new MetaobjectsApi(publicHttp, authHttp),\n search: new SearchApi(publicHttp),\n shipping: new ShippingApi(publicHttp),\n promotions: new PromotionsApi(publicHttp),\n paymentMethods: new PaymentMethodsApi(publicHttp),\n payments: new PaymentsApi(publicHttp, authHttp),\n reviews: new ReviewsApi(publicHttp),\n customers: new CustomersApi(authHttp),\n addresses: new AddressesApi(authHttp),\n contentPages: new ContentPagesApi(publicHttp),\n menus: new MenusApi(publicHttp),\n redirects: new RedirectsApi(publicHttp),\n };\n}\n\n/** The object {@link createEcomwebSdk} returns. */\nexport type EcomwebSdk = ReturnType<typeof createEcomwebSdk>;\n"],"mappings":";AAUO,IAAM,cACX,OAA8C,WAA0B;AAGnE,IAAM,gBAAgB;AAGtB,IAAM,mBAAmB,gBAAgB,WAAW;AAMpD,SAAS,kBAAkB,YAA6B;AAC7D,QAAM,SAAS,YAAY,KAAK;AAChC,SAAO,SAAS,GAAG,MAAM,IAAI,gBAAgB,KAAK;AACpD;AAEA,IAAM,UAAU,uBAAO,IAAI,0BAA0B;AAErD,SAAS,WACP,SACA,OACgB;AAChB,QAAM,UAAU,SAAS,WAAW,CAAC;AACrC,QAAMA,WAAU,OAAO,KAAK,OAAO,EAAE;AAAA,IACnC,UAAQ,KAAK,YAAY,MAAM,cAAc,YAAY;AAAA,EAC3D;AACA,SAAO;AAAA,IACL,GA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IACpC,aAAa,IAAI,eAAe,UAAU;AAAA,IAC1C,YAAY,IAAI,cAAc,UAAU;AAAA,IACxC,MAAM,IAAI,QAAQ,YAAY,QAAQ;AAAA,IACtC,QAAQ,IAAI,UAAU,YAAY,QAAQ;AAAA,IAC1C,MAAM,IAAI,QAAQ,YAAY,QAAQ;AAAA,IACtC,QAAQ,IAAI,UAAU,UAAU;AAAA,IAChC,QAAQ,IAAI,UAAU,UAAU;AAAA,IAChC,aAAa,IAAI,eAAe,YAAY,QAAQ;AAAA,IACpD,QAAQ,IAAI,UAAU,UAAU;AAAA,IAChC,UAAU,IAAI,YAAY,UAAU;AAAA,IACpC,YAAY,IAAI,cAAc,UAAU;AAAA,IACxC,gBAAgB,IAAI,kBAAkB,UAAU;AAAA,IAChD,UAAU,IAAI,YAAY,YAAY,QAAQ;AAAA,IAC9C,SAAS,IAAI,WAAW,UAAU;AAAA,IAClC,WAAW,IAAI,aAAa,QAAQ;AAAA,IACpC,WAAW,IAAI,aAAa,QAAQ;AAAA,IACpC,cAAc,IAAI,gBAAgB,UAAU;AAAA,IAC5C,OAAO,IAAI,SAAS,UAAU;AAAA,IAC9B,WAAW,IAAI,aAAa,UAAU;AAAA,EACxC;AACF;","names":["present","z","z","z","z","z","z","z","z","z","z","z","z","itemSchema","z","z","z","z","z","z","z","z","z","z","z","z","z","base","res"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/client-info.ts","../src/core/response.ts","../src/types/common.ts","../src/types/product-status.ts","../src/types/email-branding.ts","../src/types/store.ts","../src/types/embedded-script.ts","../src/types/product.ts","../src/types/product-review.ts","../src/types/pagination.ts","../src/types/inventory.ts","../src/types/category.ts","../src/types/order.ts","../src/types/shipment.ts","../src/types/order-timeline.ts","../src/types/promotion.ts","../src/types/blog.ts","../src/types/content.ts","../src/types/theme-schema.ts","../src/types/metafield-engine.ts","../src/modules/storage/image-transform.ts","../src/core/stringify.ts","../src/modules/products/api.ts","../src/modules/collections/api.ts","../src/modules/categories/api.ts","../src/modules/cart/api.ts","../src/modules/orders/api.ts","../src/modules/blog/api.ts","../src/modules/stores/api.ts","../src/modules/themes/api.ts","../src/modules/metaobjects/api.ts","../src/modules/search/api.ts","../src/modules/shipping/api.ts","../src/modules/promotions/api.ts","../src/modules/payment-methods/api.ts","../src/modules/payments/api.ts","../src/modules/reviews/api.ts","../src/modules/customers/api.ts","../src/modules/addresses/api.ts","../src/modules/content-pages/api.ts","../src/modules/menus/api.ts","../src/modules/redirects/api.ts","../src/modules/auth/api.ts","../src/modules/auth/token-storage.ts","../src/modules/auth/refresh-client.ts","../src/modules/collections/rule-set.ts","../src/modules/shipping/types.ts","../src/core/storefront-key.ts","../src/factory.ts"],"sourcesContent":["import type { IHttpClient, RequestOptions } from \"./types\";\n\n// Replaced at build time (tsup `define`, and the workspace's Next and vitest\n// configs) with this package's version from package.json.\ndeclare const __ECOMWEB_SDK_VERSION__: string | undefined;\n\n/**\n * This package's version, baked in at build time. `dev` when the source runs\n * without the define (the API ignores a version that isn't semver).\n */\nexport const SDK_VERSION: string =\n typeof __ECOMWEB_SDK_VERSION__ === \"string\" ? __ECOMWEB_SDK_VERSION__ : \"dev\";\n\n/** Sent on every SDK request: space-separated `name/version` tokens. */\nexport const CLIENT_HEADER = \"X-Ecomweb-Client\";\n\n/** This SDK's own token, `@ecomweb/sdk/<version>`. */\nexport const SDK_CLIENT_TOKEN = `@ecomweb/sdk/${SDK_VERSION}`;\n\n/**\n * The `X-Ecomweb-Client` value: `clientInfo` (a caller's own tokens, such as\n * `@ecomweb/storefront-kit/0.14.0`) followed by this SDK's token.\n */\nexport function clientHeaderValue(clientInfo?: string): string {\n const prefix = clientInfo?.trim();\n return prefix ? `${prefix} ${SDK_CLIENT_TOKEN}` : SDK_CLIENT_TOKEN;\n}\n\nconst WRAPPED = Symbol.for(\"ecomweb.sdk.clientHeader\");\n\nfunction withHeader(\n options: RequestOptions | undefined,\n value: string\n): RequestOptions {\n const headers = options?.headers ?? {};\n const present = Object.keys(headers).some(\n name => name.toLowerCase() === CLIENT_HEADER.toLowerCase()\n );\n return {\n ...options,\n headers: present ? headers : { [CLIENT_HEADER]: value, ...headers },\n };\n}\n\n/**\n * Wraps an HTTP client so every request carries `X-Ecomweb-Client`. A header\n * the caller already set wins, and a client wrapped once is not wrapped again.\n */\nexport function withClientHeader(\n http: IHttpClient,\n clientInfo?: string\n): IHttpClient {\n if ((http as { [WRAPPED]?: true })[WRAPPED]) return http;\n const value = clientHeaderValue(clientInfo);\n const wrapped: IHttpClient & { [WRAPPED]: true } = {\n [WRAPPED]: true,\n get: (url, options) => http.get(url, withHeader(options, value)),\n post: (url, data, options) =>\n http.post(url, data, withHeader(options, value)),\n put: (url, data, options) => http.put(url, data, withHeader(options, value)),\n patch: (url, data, options) =>\n http.patch(url, data, withHeader(options, value)),\n delete: (url, options) => http.delete(url, withHeader(options, value)),\n };\n return wrapped;\n}\n","import type { ApiResponse } from \"./types\";\n\n/**\n * The error thrown when the API answers with an error. Carries the HTTP status and the API's error code.\n */\nexport class ApiClientError extends Error {\n /**\n * The HTTP status code, or `0` when there was no response.\n */\n statusCode: number;\n /**\n * The API's machine-readable error code, when it sent one.\n */\n code?: string;\n /** The business error's structured `details`, when the backend sent any. */\n details?: unknown;\n constructor(message: string, statusCode = 0, code?: string, details?: unknown) {\n super(message);\n this.name = \"ApiClientError\";\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\nfunction toClientError(response: ApiResponse<unknown>): ApiClientError {\n return new ApiClientError(\n response.error?.message || \"Request failed\",\n response.error?.statusCode || 0,\n response.error?.error,\n response.error?.details,\n );\n}\n\n/**\n * Returns the data of a successful response and throws on an error response.\n *\n * @param response - the response to read\n * @returns The response data; throws {@link ApiClientError} when the API answers with an error\n */\nexport function unwrap<T>(response: ApiResponse<T>): T {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n throw toClientError(response);\n}\n\n/**\n * Like {@link unwrap}, but resolves `null` for the statuses that mean \"not found\".\n *\n * @param response - the response to read\n * @param nullStatusCodes - the statuses that resolve `null`, `[404]` by default\n * @returns The response data, or `null` when the status is in `nullStatusCodes`; throws {@link ApiClientError} on any other API error\n */\nexport function unwrapOrNull<T>(\n response: ApiResponse<T>,\n nullStatusCodes: number[] = [404]\n): T | null {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n if (\n !response.success &&\n response.error &&\n nullStatusCodes.includes(response.error.statusCode)\n ) {\n return null;\n }\n throw toClientError(response);\n}\n\n/**\n * Throws on an error response and returns nothing on success. Use it when you do not need the data.\n *\n * @param response - the response to check\n */\nexport function ensureSuccess(response: ApiResponse<any>): void {\n if (response.success) return;\n throw toClientError(response);\n}\n","import { z } from \"zod\";\n\n/**\n * Common schemas and validators used across all entities\n * Updated for Zod v4 syntax with explicit TypeScript types\n */\n\n// Re-export product status schemas from dedicated module (single source of truth)\nexport {\n productStatusSchema,\n ProductStatus,\n inventoryStatusSchema,\n InventoryStatus,\n PRODUCT_STATUS_LABELS,\n INVENTORY_STATUS_LABELS,\n isPublishableStatus,\n isUnpublishedStatus,\n isEditableStatus,\n} from \"./product-status\";\n\n// Base timestamp interface\ninterface Timestamp {\n created_at: string;\n updated_at: string;\n}\n\n// Optional timestamp interface\ninterface OptionalTimestamp {\n created_at?: string | null;\n updated_at?: string | null;\n}\n\n// Deleted timestamp interface\ninterface DeletedAt {\n deleted_at?: string | null;\n}\n\n// Base timestamp schema for created_at/updated_at fields\nexport const timestampSchema = z.object({\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n});\n\n// Optional timestamp schema for entities that might not have timestamps\nexport const optionalTimestampSchema = z.object({\n created_at: z.iso.datetime().optional().nullable(),\n updated_at: z.iso.datetime().optional().nullable(),\n});\n\n// Deleted timestamp for soft deletes\nexport const deletedAtSchema = z.object({\n deleted_at: z.iso.datetime().optional().nullable(),\n});\n\n// UUID schema using v4 syntax\nexport const uuidSchema = z.uuidv4();\n\n// ID schemas using v4 syntax\nexport const idSchema = z.int32().positive();\nexport const storeIdSchema = z.int32().positive();\n\n// Status enums\nexport const storeStatusSchema = z.enum([\"pending\", \"active\", \"disabled\"]);\nexport type StoreStatus = \"pending\" | \"active\" | \"disabled\";\n\n/**\n * @deprecated Use productStatusSchema and ProductStatus from './product-status' instead\n * This legacy definition will be removed in a future version.\n * Migration: \"inactive\" → \"archived\", inventory statuses moved to inventoryStatusSchema\n */\nexport const legacyProductStatusSchema = z.enum([\n \"active\",\n \"inactive\",\n \"draft\",\n]);\nexport type LegacyProductStatus = \"active\" | \"inactive\" | \"draft\";\n\n// NEW: Separate status enums for state machine management\nexport const orderStatusSchema = z.enum([\n \"pending\",\n \"confirmed\",\n \"processing\",\n \"cancelled\",\n \"on_hold\",\n \"completed\",\n]);\nexport type OrderStatus =\n | \"pending\"\n | \"confirmed\"\n | \"processing\"\n | \"cancelled\"\n | \"on_hold\"\n | \"completed\";\n\nexport const fulfillmentStatusSchema = z.enum([\n \"unfulfilled\",\n \"fulfilled\",\n \"returned\",\n \"return_requested\",\n]);\nexport type FulfillmentStatus =\n | \"unfulfilled\"\n | \"fulfilled\"\n | \"returned\"\n | \"return_requested\";\n\nexport const shippingStatusSchema = z.enum([\n \"not_shipped\",\n \"shipped\",\n \"in_transit\",\n \"out_for_delivery\",\n \"delivered\",\n \"delivery_failed\",\n]);\nexport type ShippingStatus =\n | \"not_shipped\"\n | \"shipped\"\n | \"in_transit\"\n | \"out_for_delivery\"\n | \"delivered\"\n | \"delivery_failed\";\n\nexport const paymentStatusSchema = z.enum([\n \"pending\",\n \"authorized\",\n \"paid\",\n \"captured\",\n \"failed\",\n \"refunded\",\n \"voided\",\n \"expired\",\n]);\nexport type PaymentStatus =\n | \"pending\"\n | \"authorized\"\n | \"paid\"\n | \"captured\"\n | \"failed\"\n | \"refunded\"\n | \"voided\"\n | \"expired\";\n\n// DEPRECATED: Legacy order status for backward compatibility\nexport const legacyOrderStatusSchema = z.enum([\n \"pending\",\n \"confirmed\",\n \"processing\",\n \"shipped\",\n \"delivered\",\n \"cancelled\",\n \"completed\",\n]);\nexport type LegacyOrderStatus =\n | \"pending\"\n | \"confirmed\"\n | \"processing\"\n | \"shipped\"\n | \"delivered\"\n | \"cancelled\"\n | \"completed\";\n\n/**\n * The set of payment methods this SDK has shipped labels for. It is a hint for\n * UI, NOT a constraint: each store defines its own enabled methods, and the API\n * validates a submitted method against that store's configuration. Adding a\n * gateway must not require an SDK release.\n */\nexport const KNOWN_PAYMENT_METHODS = [\n \"cod\",\n \"bank_transfer\",\n \"e_wallet\",\n \"credit_card\",\n \"momo\",\n \"zalopay\",\n \"vnpay\",\n \"onepay\",\n] as const;\n\nexport const paymentMethodSchema = z.string().min(1);\nexport type PaymentMethod = string;\n\nexport const blogPostStatusSchema = z.enum([\n \"draft\",\n \"published\",\n \"scheduled\",\n \"unlisted\",\n]);\nexport type BlogPostStatus = \"draft\" | \"published\" | \"scheduled\" | \"unlisted\";\n\nexport const integrationStatusSchema = z.enum([\"active\", \"inactive\", \"error\"]);\nexport type IntegrationStatus = \"active\" | \"inactive\" | \"error\";\n\nexport const variantStatusSchema = z.enum([\n \"active\",\n \"inactive\",\n \"out_of_stock\",\n]);\nexport type VariantStatus = \"active\" | \"inactive\" | \"out_of_stock\";\n\nexport const messageOutboxStatusSchema = z.enum([\n \"PENDING\",\n \"PUBLISHED\",\n \"FAILED\",\n]);\nexport type MessageOutboxStatus = \"PENDING\" | \"PUBLISHED\" | \"FAILED\";\n\n// Common type aliases for better readability\nexport type Id = number;\n\n// Export interfaces for reuse\nexport type { Timestamp, OptionalTimestamp, DeletedAt };\n\n// Common validation patterns using v4 syntax\nexport const emailSchema = z.email();\nexport const phoneSchema = z\n .string()\n .regex(/^[0-9+\\-\\s()]+$/)\n .optional()\n .nullable();\nexport const urlSchema = z.url().optional().nullable();\nexport const strictUrlSchema = z.url(); // For required URLs\nexport const slugSchema = z\n .string()\n .min(1)\n .regex(/^[a-z0-9-]+$/);\nexport const colorSchema = z\n .string()\n .regex(/^#[0-9A-Fa-f]{6}$/)\n .optional()\n .nullable();\n\n// Optional URL that allows empty string\nexport const optionalUrlSchema = z.url().optional().or(z.literal(\"\"));\n\n// Decimal/money values\nexport const moneySchema = z.float64().multipleOf(0.01);\nexport const decimalSchema = z.float64();\n\n// JSON field schema\nexport const jsonSchema = z.record(z.string(), z.any());\n\n// Pagination schema\nexport const paginationSchema = z.object({\n page: z.int32().min(1).default(1),\n limit: z.int32().min(1).max(100).default(20),\n});\n\n// Sort order schema\nexport const positionOrderSchema = z.int32().default(0);\n\nexport const sortOrderSchema = z.enum([\"asc\", \"desc\"]);\n\n// Image dimensions schema\nexport const dimensionsSchema = z\n .object({\n width: z.float64(),\n height: z.float64(),\n length: z.float64().optional(),\n })\n .optional()\n .nullable();\n","import { z } from \"zod\";\n\n/**\n * Product Status Schema - Single Source of Truth\n *\n * This schema standardizes product status across the entire e-commerce system,\n * following industry best practices from Shopify, WooCommerce, and Magento.\n *\n * IMPORTANT: Product status (lifecycle/publishing) is separate from inventory status.\n * - Product Status: Controls visibility and publishing state\n * - Inventory Status: Computed from stock quantity (not a product attribute)\n */\n\n// ============================================================================\n// Product Status (Lifecycle/Publishing)\n// ============================================================================\n\n/**\n * Product lifecycle and publishing status\n *\n * Status Flow:\n * draft → active → unlisted\n *\n * State transitions are enforced by the product state machine:\n * @see apps/api/src/modules/catalog/domain/validators/product-status-state-machine.ts\n */\nexport const productStatusSchema = z.enum([\n \"draft\", // Work in progress, not visible to customers\n \"active\", // Published and visible to customers\n \"unlisted\", // Hidden from public view, can be restored\n]);\n\n/**\n * TypeScript type inferred from product status schema\n */\nexport type ProductStatus = z.infer<typeof productStatusSchema>;\n\n/**\n * Product status enum for use in application code\n * Provides autocomplete and type safety\n */\n// eslint-disable-next-line no-redeclare -- intentional TS type + value pair (ProductStatus type above); base rule is not TS-aware\nexport const ProductStatus = {\n DRAFT: \"draft\" as const,\n ACTIVE: \"active\" as const,\n UNLISTED: \"unlisted\" as const,\n} as const;\n\n// ============================================================================\n// Inventory Status (Computed - NOT a Product Attribute)\n// ============================================================================\n\n/**\n * Inventory availability status - COMPUTED from stock quantity\n *\n * IMPORTANT: This is NOT stored as a product field!\n * It is dynamically calculated based on:\n * - variant.quantity\n * - store.low_stock_threshold\n * - variant.backorder_allowed\n *\n * Historical Note:\n * Previously, \"out_of_stock\" and \"low_stock\" were incorrectly stored as\n * product status values. They are now computed inventory states.\n */\nexport const inventoryStatusSchema = z.enum([\n \"in_stock\", // Quantity > low_stock_threshold\n \"low_stock\", // Quantity <= low_stock_threshold && quantity > 0\n \"out_of_stock\", // Quantity = 0 && !backorder_allowed\n \"backordered\", // Quantity = 0 && backorder_allowed\n]);\n\n/**\n * TypeScript type inferred from inventory status schema\n */\nexport type InventoryStatus = z.infer<typeof inventoryStatusSchema>;\n\n/**\n * Inventory status enum for use in application code\n */\n// eslint-disable-next-line no-redeclare -- intentional TS type + value pair (InventoryStatus type above); base rule is not TS-aware\nexport const InventoryStatus = {\n IN_STOCK: \"in_stock\" as const,\n LOW_STOCK: \"low_stock\" as const,\n OUT_OF_STOCK: \"out_of_stock\" as const,\n BACKORDERED: \"backordered\" as const,\n} as const;\n\n// ============================================================================\n// Migration Helpers\n// ============================================================================\n\n/**\n * Maps legacy product status values to new standardized values\n * Used during data migration and backward compatibility\n */\nexport const LEGACY_STATUS_MIGRATION_MAP = {\n active: ProductStatus.ACTIVE,\n inactive: ProductStatus.UNLISTED, // inactive → unlisted\n archived: ProductStatus.UNLISTED, // archived → unlisted (old status)\n pending: ProductStatus.DRAFT, // pending → draft (removed approval workflow)\n scheduled: ProductStatus.DRAFT, // scheduled → draft (removed scheduling)\n draft: ProductStatus.DRAFT,\n out_of_stock: ProductStatus.ACTIVE, // Was inventory status, map to active\n low_stock: ProductStatus.ACTIVE, // Was inventory status, map to active\n} as const;\n\n/**\n * Product status labels for UI display (Vietnamese)\n */\nexport const PRODUCT_STATUS_LABELS: Record<ProductStatus, string> = {\n draft: \"Nháp\",\n active: \"Hoạt động\",\n unlisted: \"Không công khai\",\n};\n\n/**\n * Inventory status labels for UI display (Vietnamese)\n */\nexport const INVENTORY_STATUS_LABELS: Record<InventoryStatus, string> = {\n in_stock: \"Còn hàng\",\n low_stock: \"Sắp hết hàng\",\n out_of_stock: \"Hết hàng\",\n backordered: \"Cho phép đặt trước\",\n};\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Check if a product status is publishable (visible to customers)\n */\nexport function isPublishableStatus(status: ProductStatus): boolean {\n return status === ProductStatus.ACTIVE;\n}\n\n/**\n * Check if a product status represents a non-published state\n */\nexport function isUnpublishedStatus(status: ProductStatus): boolean {\n return status === ProductStatus.DRAFT || status === ProductStatus.UNLISTED;\n}\n\n/**\n * Check if a product status allows editing\n */\nexport function isEditableStatus(status: ProductStatus): boolean {\n return status === ProductStatus.DRAFT;\n}\n","import { z } from \"zod\";\nimport { urlSchema } from \"./common\";\n\n/**\n * Email branding vocabulary, mirrored from the API.\n *\n * The API owns these values (src/modules/templates/domain/email-palette.ts)\n * and pins this file with a tripwire test. It cannot import this package —\n * the SDK is a client OF that API, and depending on it would invert the\n * relationship. So the two are kept in step by hand.\n *\n * If you change anything here, change it there in the same PR, or the\n * dashboard will show merchants a default swatch the emails do not render.\n */\nexport const EMAIL_PALETTE_DEFAULTS = {\n accent: \"#f4644f\",\n bg: \"#FFFFFF\",\n bodyBg: \"#FFFFFF\",\n text: \"#1A1A1A\",\n footerText: \"#6B7280\",\n} as const;\n\n/**\n * Matches the API's DTO validation exactly: #RRGGBB, nothing else. 3-digit\n * hex, named colours and rgb() are rejected at the edge so the render path\n * never has to parse anything.\n */\nexport const EMAIL_COLOR_PATTERN = /^#[0-9A-Fa-f]{6}$/;\n\nconst emailColorSchema = z\n .string()\n .regex(EMAIL_COLOR_PATTERN, \"Must be a 6-digit hex colour, e.g. #1D4ED8\")\n .optional()\n .nullable();\n\n/**\n * The nine store_settings columns a merchant can set for email branding.\n * Every one is nullable: NULL means \"use the house default\", which is what\n * lets an unconfigured store render exactly as it did before the feature.\n */\nexport const emailBrandingShape = {\n email_accent_color: emailColorSchema,\n email_bg_color: emailColorSchema,\n email_body_bg_color: emailColorSchema,\n email_text_color: emailColorSchema,\n email_footer_text_color: emailColorSchema,\n email_logo_url: urlSchema,\n email_header_tagline: z.string().max(120).optional().nullable(),\n email_footer_address: z.string().max(255).optional().nullable(),\n email_footer_phone: z.string().max(32).optional().nullable(),\n};\n\nexport const emailBrandingSchema = z.object(emailBrandingShape);\n\nexport type StoreEmailBrandingSettings = z.infer<typeof emailBrandingSchema>;\n","import { z } from \"zod\";\nimport {\n timestampSchema,\n deletedAtSchema,\n storeStatusSchema,\n uuidSchema,\n urlSchema,\n optionalTimestampSchema,\n idSchema,\n StoreStatus,\n} from \"./common\";\nimport { emailBrandingShape } from \"./email-branding\";\nimport { embeddedScriptSchema, type EmbeddedScript } from \"./embedded-script\";\n\n/**\n * Store-related schemas based on Prisma models\n */\n// Store main entity\nexport const storeSchema = z\n .object({\n id: idSchema,\n // The public store endpoints no longer send it.\n user_id: uuidSchema.optional(),\n name: z.string().min(1),\n description: z.string().optional().nullable(),\n status: storeStatusSchema.default(\"pending\"),\n })\n .extend(timestampSchema.shape)\n .extend(deletedAtSchema.shape);\n\n// Store configuration for domains\nexport const storeConfigSchema = z\n .object({\n id: idSchema,\n store_id: idSchema,\n subdomain: z.string().optional().nullable(),\n custom_domain: z.string().optional().nullable(),\n /**\n * True once the custom domain's DNS works. The storefront redirects the\n * free subdomain to the custom domain only then.\n */\n verified: z.boolean().optional().nullable(),\n })\n .extend(timestampSchema.shape);\n\n/** Checkout and register links: a store path or an absolute URL each. */\nexport const legalLinksSchema = z\n .object({\n terms: z.string().optional().nullable(),\n privacy: z.string().optional().nullable(),\n })\n .optional()\n .nullable();\n\n// Store settings (includes blog fields decorated from blog_settings)\nexport const storeSettingsSchema = z\n .object({\n id: idSchema,\n store_id: idSchema,\n logo_url: urlSchema,\n favicon_url: urlSchema,\n featured_image: urlSchema,\n tiktok_link: urlSchema,\n shopee_link: urlSchema,\n facebook_link: urlSchema,\n instagram_link: urlSchema,\n google_analytics_key: z.string().optional().nullable(),\n tagline: z.string().optional().nullable(),\n blog_title: z.string().optional().nullable(),\n is_blog_enabled: z.boolean().optional().nullable(),\n /**\n * The rest of blog_settings the storefront renders. Absent from older\n * APIs: readers fall back to the platform defaults (built-in blurb, 12\n * posts a page, comments on).\n */\n blog_description: z.string().optional().nullable(),\n posts_per_page: z.int32().optional().nullable(),\n allow_comments: z.boolean().optional().nullable(),\n currency_code: z\n .string()\n .min(3)\n .max(3)\n .default(\"VND\")\n .optional()\n .nullable(),\n review_requests_enabled: z.boolean().optional().nullable(),\n /**\n * Wrap the order sequence to form Order.order_code. A null prefix means\n * the store never configured one and takes the default \"#\"; an empty\n * string means the merchant deliberately cleared it.\n */\n order_number_prefix: z.string().optional().nullable(),\n order_number_suffix: z.string().optional().nullable(),\n legal_links: legalLinksSchema,\n })\n .extend(emailBrandingShape)\n .extend(optionalTimestampSchema.shape);\n\n// Create store input\nexport const createStoreSchema = storeSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n deleted_at: true,\n});\n\n// Update store input\nexport const updateStoreSchema = createStoreSchema.partial();\n\n// Create store config input\nexport const createStoreConfigSchema = storeConfigSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update store config input\nexport const updateStoreConfigSchema = createStoreConfigSchema.partial().omit({\n store_id: true,\n});\n\n// Create store settings input\nexport const createStoreSettingsSchema = storeSettingsSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update store settings input\nexport const updateStoreSettingsSchema = createStoreSettingsSchema\n .partial()\n .omit({\n store_id: true,\n });\n\n// Store with relations\nexport const storeWithRelationsSchema = storeSchema.extend({\n store_config: storeConfigSchema.optional().nullable(),\n store_settings: storeSettingsSchema.optional().nullable(),\n embedded_scripts: z.array(embeddedScriptSchema).optional(),\n});\n\n// Export types\nexport type Store = {\n ref: string;\n /** @deprecated Public store endpoints no longer send it; do not rely on it. */\n user_id?: string;\n name: string;\n description: string | null;\n status: StoreStatus;\n created_at: string;\n updated_at: string;\n deleted_at: string | null;\n embedded_scripts?: EmbeddedScript[];\n /** Contract \"Storefront\": true until the merchant opens the store. Absent on older APIs. */\n coming_soon?: boolean;\n /** Contract \"Storefront\": when the store first opened, null if never. Absent on older APIs. */\n first_opened_at?: string | null;\n};\nexport type StoreConfig = z.infer<typeof storeConfigSchema>;\nexport type StoreSettings = z.infer<typeof storeSettingsSchema>;\nexport type CreateStore = z.infer<typeof createStoreSchema>;\nexport type UpdateStore = z.infer<typeof updateStoreSchema>;\nexport type CreateStoreConfig = z.infer<typeof createStoreConfigSchema>;\nexport type UpdateStoreConfig = z.infer<typeof updateStoreConfigSchema>;\nexport type CreateStoreSettings = z.infer<typeof createStoreSettingsSchema>;\nexport type UpdateStoreSettings = z.infer<typeof updateStoreSettingsSchema>;\nexport type StoreWithRelations = z.infer<typeof storeWithRelationsSchema>;\n","import { z } from \"zod\";\nimport { idSchema } from \"./common\";\n\n/**\n * Embedded scripts schema - custom tracking/analytics scripts for stores\n */\n\n// Placement enum - where the script should be injected\nexport const embeddedScriptPlacementSchema = z.enum([\n \"head\",\n \"body_start\",\n \"body_end\",\n]);\n\nexport type EmbeddedScriptPlacement = z.infer<\n typeof embeddedScriptPlacementSchema\n>;\n\n// Full embedded script schema\nexport const embeddedScriptSchema = z.object({\n id: idSchema,\n name: z.string().min(1).max(255),\n code: z.string().min(1),\n placement: embeddedScriptPlacementSchema,\n created_at: z.iso.datetime().optional().nullable(),\n updated_at: z.iso.datetime().optional().nullable(),\n});\n\nexport type EmbeddedScript = z.infer<typeof embeddedScriptSchema>;\n\n// Create schema (omits generated fields)\nexport const createEmbeddedScriptSchema = embeddedScriptSchema.pick({\n name: true,\n code: true,\n placement: true,\n});\n\nexport type CreateEmbeddedScript = z.infer<typeof createEmbeddedScriptSchema>;\n\n// Update schema (all fields optional)\nexport const updateEmbeddedScriptSchema = createEmbeddedScriptSchema.partial();\n\nexport type UpdateEmbeddedScript = z.infer<typeof updateEmbeddedScriptSchema>;\n","import { z } from \"zod\";\nimport {\n productReviewStatsSchema,\n ProductReviewStats,\n} from \"./product-review\";\nimport {\n timestampSchema,\n productStatusSchema,\n variantStatusSchema,\n moneySchema,\n decimalSchema,\n jsonSchema,\n dimensionsSchema,\n positionOrderSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n ProductStatus,\n VariantStatus,\n} from \"./common\";\nimport { INVENTORY_POLICIES, type InventoryPolicy } from \"./inventory\";\n\n/**\n * Product-related schemas based on Prisma models\n */\n\n// Product interface\nexport interface Product extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string | null;\n description: string | null;\n status: ProductStatus;\n category_id: Id | null;\n is_featured: boolean;\n min_price: number | null;\n max_price: number | null;\n variant_mode: string;\n external_id: string | null;\n images: Array<any>; // Array of image objects\n videos?: ProductVideo[]; // Product videos\n}\n\n// Infer dimensions type from dimensionsSchema\ntype Dimensions = z.infer<typeof dimensionsSchema>;\n\n// Product variant interface\nexport interface ProductVariant extends OptionalTimestamp {\n id: Id;\n product_id: Id;\n sku_id: Id;\n seller_sku: string | null;\n external_id: string | null;\n price: number;\n inventory: number;\n /**\n * false: never reserved or blocked at checkout. Admin and public responses.\n * A response from an API predating this field never omits it, but if one\n * ever did, treat the missing value as `true` (tracked) per contract\n * section 7, so an old response can never make everything look\n * purchasable.\n */\n track_inventory: boolean;\n /**\n * deny: checkout rejects when stock is short. continue: sells past zero.\n * Per contract section 7, a missing value falls back to `\"deny\"`, the same\n * fail-safe reasoning as `track_inventory` above.\n */\n inventory_policy: InventoryPolicy;\n /** Unit cost to the store. Admin responses only: any store member, or an API key holding read:inventory. Never in public responses. */\n cost_per_item?: number | null;\n weight: number | null;\n dimensions: Dimensions;\n is_default: boolean;\n status: VariantStatus;\n}\n\n// Variant option interface\nexport interface VariantOption extends OptionalTimestamp {\n id: Id;\n name: string;\n sort_order: number;\n}\n\n// Variant option value interface\nexport interface VariantOptionValue extends OptionalTimestamp {\n id: Id;\n option_id: Id;\n value: string;\n display_value: string;\n image_url: string;\n sort_order: number;\n swatch_type: \"none\" | \"color\" | \"image\";\n swatch_value: string;\n}\n\n// Product variant combination interface\nexport interface ProductVariantCombination {\n id: Id;\n variant_id: Id;\n option_id: Id;\n option_value_id: Id;\n created_at: string;\n}\n\n// A single `combinations[]` entry as emitted by the API's\n// `mapVariantCombination` (variant-combination.mapper.ts). The legacy\n// `option`/`value` and `variant_options`/`variant_option_values` aliases\n// were retired in Phase E (spec §12 step 18 / issue #182) — only\n// `attributes`/`attribute_values` are emitted now.\nexport interface ProductVariantCombinationEntry {\n attributes: VariantOption;\n attribute_values: VariantOptionValue;\n}\n\n// Create/Update types\nexport type CreateProduct = Omit<Product, \"id\" | keyof OptionalTimestamp>;\nexport type UpdateProduct = Partial<CreateProduct>;\n\nexport type CreateProductVariant = Omit<\n ProductVariant,\n | \"id\"\n | \"sku_id\"\n | keyof OptionalTimestamp\n | \"track_inventory\"\n | \"inventory_policy\"\n> & {\n /** Optional on input: the API defaults it to true. */\n track_inventory?: boolean;\n /** Optional on input: the API defaults it to \"deny\". */\n inventory_policy?: InventoryPolicy;\n};\nexport type UpdateProductVariant = Partial<\n Omit<CreateProductVariant, \"product_id\">\n>;\n\nexport type CreateVariantOption = Omit<\n VariantOption,\n \"id\" | keyof OptionalTimestamp\n>;\nexport type UpdateVariantOption = Partial<CreateVariantOption>;\n\nexport type CreateVariantOptionValue = Omit<\n VariantOptionValue,\n \"id\" | keyof OptionalTimestamp\n>;\nexport type UpdateVariantOptionValue = Partial<CreateVariantOptionValue>;\n\n// Extended types for relationships\nexport interface ProductWithVariants extends Product {\n variants?: ProductVariantWithCombinations[];\n}\n\nexport interface ProductVariantWithCombinations extends ProductVariant {\n combinations?: ProductVariantCombinationEntry[];\n}\n\n// Product response extended with optional per-product review_stats\nexport interface ProductWithReviewStats extends Product {\n review_stats?: ProductReviewStats | null;\n}\n\n// Product main entity\nexport const productSchema = z\n .object({\n id: idSchema,\n name: z.string().min(1),\n slug: z.string().max(255).optional().nullable(),\n description: z.string().optional().nullable(),\n status: productStatusSchema.default(\"active\"),\n category_id: idSchema.optional().nullable(),\n is_featured: z.boolean().default(false),\n min_price: moneySchema.optional().nullable(),\n max_price: moneySchema.optional().nullable(),\n variant_mode: z.string(),\n external_id: z.string().optional().nullable(),\n images: jsonSchema, // Array of image objects\n })\n .extend(timestampSchema.shape);\n\n// Product variant\nexport const productVariantSchema = z\n .object({\n id: idSchema,\n product_id: idSchema,\n sku_id: idSchema,\n seller_sku: z.string().optional().nullable(),\n external_id: z.string().optional().nullable(),\n price: moneySchema,\n inventory: z.int32().default(0),\n track_inventory: z.boolean().default(true),\n inventory_policy: z.enum(INVENTORY_POLICIES).default(\"deny\"),\n // z.number(), not moneySchema: unit costs carry up to 4 decimals, and\n // moneySchema (2 decimals) would reject a valid cost.\n cost_per_item: z.number().nonnegative().nullable().optional(),\n weight: decimalSchema.optional().nullable(),\n dimensions: dimensionsSchema,\n is_default: z.boolean().default(false),\n status: variantStatusSchema.default(\"active\"),\n })\n .extend(timestampSchema.shape);\n\n// Variant options (like Color, Size)\nexport const variantOptionSchema = z\n .object({\n id: idSchema,\n name: z.string().min(1),\n sort_order: positionOrderSchema,\n })\n .extend(timestampSchema.shape);\n\n// Variant option values (like Red, Blue for Color)\nexport const variantOptionValueSchema = z\n .object({\n id: idSchema,\n option_id: idSchema,\n value: z.string().min(1),\n display_value: z.string().min(1),\n image_url: z.string().default(\"\"),\n sort_order: positionOrderSchema,\n swatch_type: z.enum([\"none\", \"color\", \"image\"]).default(\"none\"),\n swatch_value: z.string().default(\"\"),\n })\n .extend(timestampSchema.shape);\n\n// Product variant combinations (which options/values belong to which variant)\nexport const productVariantCombinationSchema = z.object({\n id: idSchema,\n variant_id: idSchema,\n option_id: idSchema,\n option_value_id: idSchema,\n created_at: z.iso.datetime(),\n});\n\n// Create product schema\nexport const createProductSchema = productSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateProduct>;\n\n// Update product schema\nexport const updateProductSchema = productSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial() as unknown as z.ZodType<UpdateProduct>;\n\n// Create product variant schema\nexport const createProductVariantSchema = productVariantSchema.omit({\n id: true,\n sku_id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateProductVariant>;\n\n// Update product variant schema\nexport const updateProductVariantSchema = productVariantSchema\n .omit({\n id: true,\n sku_id: true,\n created_at: true,\n updated_at: true,\n })\n .partial()\n .omit({\n product_id: true,\n }) as unknown as z.ZodType<UpdateProductVariant>;\n\n// Create variant option schema\nexport const createVariantOptionSchema = variantOptionSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateVariantOption>;\n\n// Update variant option schema\nexport const updateVariantOptionSchema = variantOptionSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial() as unknown as z.ZodType<UpdateVariantOption>;\n\n// Create variant option value schema\nexport const createVariantOptionValueSchema = variantOptionValueSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n}) as unknown as z.ZodType<CreateVariantOptionValue>;\n\n// Update variant option value schema\nexport const updateVariantOptionValueSchema = variantOptionValueSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial()\n .omit({\n option_id: true,\n }) as unknown as z.ZodType<UpdateVariantOptionValue>;\n\n// A single `combinations[]` entry, matching the exact two keys emitted by\n// the API's `mapVariantCombination` — NOT the write-DTO shape in\n// `productVariantCombinationSchema` (which describes `POST`/`PATCH` bodies,\n// not this read payload). The legacy `option`/`value` and\n// `variant_options`/`variant_option_values` aliases were retired in Phase E\n// (spec §12 step 18 / issue #182).\nexport const productVariantCombinationEntrySchema = z.object({\n attributes: variantOptionSchema,\n attribute_values: variantOptionValueSchema,\n});\n\n// Product variant with combinations schema\nexport const productVariantWithCombinationsSchema = productVariantSchema.extend(\n {\n combinations: z.array(productVariantCombinationEntrySchema).optional(),\n },\n);\n\n// Per-product attribute link value (e.g. a specific color/size choice)\nexport const attributeLinkValueSchema = z.object({\n key: z.string(),\n display: z.string(),\n swatch_type: z.enum([\"none\", \"color\", \"image\"]),\n swatch_value: z.string(),\n attribute_value_id: z.number().nullable(),\n});\n\n// Per-product attribute link (product_attributes on the API)\nexport const attributeLinkSchema = z.object({\n id: z.number(),\n position: z.number(),\n group: z.string().nullable(),\n is_visible: z.boolean(),\n is_variation: z.boolean(),\n attribute_id: z.number().nullable(),\n custom_name: z.string().nullable(),\n name: z.string(),\n values: z.array(attributeLinkValueSchema),\n});\nexport type AttributeLink = z.infer<typeof attributeLinkSchema>;\n\n// Product with variants schema\nexport const productWithVariantsSchema = productSchema.extend({\n variants: z.array(productVariantWithCombinationsSchema).optional(),\n});\n\n// Product schema extended with optional review_stats\nexport const productWithReviewStatsSchema = productSchema.extend({\n review_stats: productReviewStatsSchema.optional().nullable(),\n});\n\n// Product with variants + optional review_stats\nexport const productWithVariantsAndReviewStatsSchema =\n productWithVariantsSchema.extend({\n review_stats: productReviewStatsSchema.optional().nullable(),\n }) as unknown as z.ZodType<ProductWithVariants & ProductWithReviewStats>;\n\nexport interface ProductImage {\n url: string;\n design_id?: string;\n design_edit_url?: string;\n canva_asset_id?: string;\n created_at?: string;\n updated_at?: string;\n // Additional metadata fields\n alt?: string;\n caption?: string;\n sort_order?: number;\n is_primary?: boolean;\n}\n\n// Product Video interface\nexport interface ProductVideo {\n id: string; // Asset ID\n url: string; // Public video URL\n thumbnail_url?: string; // Video thumbnail\n duration?: number; // Duration in seconds\n width?: number; // Video width\n height?: number; // Video height\n file_size?: number; // File size in bytes\n status?: \"processing\" | \"active\" | \"failed\";\n}\n","import { z } from \"zod\";\nimport {\n idSchema,\n uuidSchema,\n emailSchema,\n timestampSchema,\n deletedAtSchema,\n} from \"./common\";\nimport { baseQueryParamsSchema } from \"./pagination\";\n\n// Review status enum (matches Prisma enum ReviewStatus)\nexport const reviewStatusSchema = z.enum([\n \"PENDING\",\n \"APPROVED\",\n \"REJECTED\",\n \"HIDDEN\",\n]);\nexport type ReviewStatus = z.infer<typeof reviewStatusSchema>;\n\n// Product review reply\nexport const productReviewReplySchema = z\n .object({\n id: uuidSchema,\n review_id: uuidSchema,\n content: z.string().min(1),\n author_id: uuidSchema,\n author_name: z.string().min(1),\n is_visible: z.boolean().default(true),\n })\n .extend(timestampSchema.shape)\n .extend(deletedAtSchema.shape);\n\nexport const createProductReviewReplySchema = productReviewReplySchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n deleted_at: true,\n});\n\nexport const updateProductReviewReplySchema = productReviewReplySchema\n .partial()\n .omit({ id: true, review_id: true, created_at: true });\n\n// Product review\nexport const productReviewSchema = z\n .object({\n id: uuidSchema,\n product_id: z.bigint(),\n product_name: z.string().min(1),\n variant_id: z.bigint().optional().nullable(),\n variant_name: z.string().optional().nullable(),\n order_id: z.bigint().optional().nullable(),\n order_number: z.bigint().optional().nullable(),\n user_id: uuidSchema.optional().nullable(),\n reviewer_name: z.string().min(1),\n reviewer_email: emailSchema,\n reviewer_avatar: z.string().url().optional().nullable(),\n is_verified_buyer: z.boolean().default(false),\n rating: z.int32().min(1).max(5),\n title: z.string().max(200).optional().nullable(),\n content: z.string().min(1),\n pros: z.array(z.string()).default([]),\n cons: z.array(z.string()).default([]),\n media: z.array(z.any()).default([]),\n status: reviewStatusSchema.default(\"PENDING\"),\n moderation_notes: z.string().optional().nullable(),\n approved_by: uuidSchema.optional().nullable(),\n approved_at: z.iso.datetime().optional().nullable(),\n rejected_reason: z.string().optional().nullable(),\n is_featured: z.boolean().default(false),\n is_pinned: z.boolean().default(false),\n display_order: z.int32().optional().nullable(),\n review_date: z.iso.datetime().optional().nullable(),\n })\n .extend(timestampSchema.shape)\n .extend(deletedAtSchema.shape);\n\nexport const createProductReviewSchema = productReviewSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n deleted_at: true,\n});\n\nexport const updateProductReviewSchema = productReviewSchema\n .partial()\n .omit({ id: true, created_at: true });\n\n// Product review with replies (hydrated relation)\nexport const productReviewWithRepliesSchema = productReviewSchema.extend({\n review_replies: z.array(productReviewReplySchema).optional(),\n});\n\n// Review statistics per product\nexport const productReviewStatsSchema = z.object({\n id: idSchema,\n product_id: z.bigint(),\n total_reviews: z.int32().default(0),\n verified_reviews: z.int32().default(0),\n reviews_with_media: z.int32().default(0),\n reviews_with_reply: z.int32().default(0),\n average_rating: z.float64().default(0),\n rating_1_count: z.int32().default(0),\n rating_2_count: z.int32().default(0),\n rating_3_count: z.int32().default(0),\n rating_4_count: z.int32().default(0),\n rating_5_count: z.int32().default(0),\n last_review_at: z.iso.datetime().optional().nullable(),\n last_calculated_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n});\n\n// Query filter schemas\nexport const productReviewFiltersSchema = baseQueryParamsSchema.extend({\n id: uuidSchema.optional(),\n product_id: z.bigint().optional(),\n user_id: uuidSchema.optional(),\n rating: z.int32().min(1).max(5).optional(),\n min_rating: z.int32().min(1).max(5).optional(),\n max_rating: z.int32().min(1).max(5).optional(),\n status: reviewStatusSchema.optional(),\n is_verified_buyer: z.boolean().optional(),\n reviewer_email: emailSchema.optional(),\n reviewer_name: z.string().optional(),\n has_media: z.boolean().optional(),\n include_replies: z.boolean().optional(),\n});\n\nexport const productReviewReplyFiltersSchema = baseQueryParamsSchema.extend({\n id: uuidSchema.optional(),\n review_id: uuidSchema.optional(),\n is_visible: z.boolean().optional(),\n author_id: uuidSchema.optional(),\n});\n\n// Types\nexport type ProductReview = z.infer<typeof productReviewSchema>;\nexport type CreateProductReview = z.infer<typeof createProductReviewSchema>;\nexport type UpdateProductReview = z.infer<typeof updateProductReviewSchema>;\nexport type ProductReviewWithReplies = z.infer<\n typeof productReviewWithRepliesSchema\n>;\nexport type ProductReviewReply = z.infer<typeof productReviewReplySchema>;\nexport type CreateProductReviewReply = z.infer<\n typeof createProductReviewReplySchema\n>;\nexport type UpdateProductReviewReply = z.infer<\n typeof updateProductReviewReplySchema\n>;\nexport type ProductReviewStats = z.infer<typeof productReviewStatsSchema>;\nexport type ProductReviewFilters = z.infer<typeof productReviewFiltersSchema>;\nexport type ProductReviewReplyFilters = z.infer<\n typeof productReviewReplyFiltersSchema\n>;\n","import { z } from \"zod\";\nimport { timestampSchema, sortOrderSchema } from \"./common\";\n\n// Pagination meta schema\nexport const paginationMetaSchema = z.object({\n total: z.uint32(),\n limit: z.int32().positive(),\n offset: z.uint32(),\n page: z.int32().positive(),\n totalPages: z.uint32(),\n hasNext: z.boolean(),\n hasPrev: z.boolean(),\n});\n\n// Generic paginated response schema\nexport const paginatedResponseSchema = <T extends z.ZodTypeAny>(\n itemSchema: T,\n) =>\n z.object({\n data: z.array(itemSchema),\n meta: paginationMetaSchema,\n });\n\n// Base query parameters schema\nexport const baseQueryParamsSchema = z.object({\n limit: z.int32().min(1).max(100).optional(),\n offset: z.uint32().optional(),\n search: z.string().optional(),\n sort_by: z.string().optional(),\n sort_order: sortOrderSchema.optional(),\n created_after: timestampSchema.optional(),\n created_before: timestampSchema.optional(),\n updated_after: timestampSchema.optional(),\n updated_before: timestampSchema.optional(),\n});\n\n// Base delete options schema\nexport const baseDeleteOptionsSchema = z.object({\n soft_delete: z.boolean().optional(),\n reason: z.string().optional(),\n force: z.boolean().optional(),\n});\n\n// Base delete result schema\nexport const baseDeleteResultSchema = z.object({\n success: z.boolean(),\n type: z.enum([\"soft\", \"hard\"]),\n message: z.string(),\n entity_id: z.union([z.number(), z.string()]),\n deleted_at: timestampSchema.optional(),\n});\n\n// Pagination defaults\nexport const PAGINATION_DEFAULTS = {\n LIMIT: 20,\n MAX_LIMIT: 100,\n MIN_LIMIT: 1,\n DEFAULT_OFFSET: 0,\n DEFAULT_ORDER: \"desc\" as const,\n} as const;\n\n// Inferred types\nexport type PaginationMeta = z.infer<typeof paginationMetaSchema>;\nexport type PaginatedResponse<T> = {\n data: T[];\n meta: PaginationMeta;\n};\nexport type BaseQueryParams = z.infer<typeof baseQueryParamsSchema>;\nexport type BaseDeleteOptions = z.infer<typeof baseDeleteOptionsSchema>;\nexport type BaseDeleteResult = z.infer<typeof baseDeleteResultSchema>;\n\n// Utility type for creating paginated API functions\nexport type PaginatedApiFunction<\n T,\n Q extends BaseQueryParams = BaseQueryParams,\n> = (query?: Q) => Promise<PaginatedResponse<T>>;\n\n// Utility type for creating single entity API functions\nexport type SingleEntityApiFunction<T, Q = any> = (\n query: Q,\n) => Promise<T | null>;\n\n// Utility type for create/update operations\nexport type MutationApiFunction<TData, TInput> = (\n input: TInput,\n) => Promise<TData>;\n\n// Utility type for delete operations\nexport type DeleteApiFunction<\n TResult extends BaseDeleteResult = BaseDeleteResult,\n> = (id: number, options?: BaseDeleteOptions) => Promise<TResult>;\n\n// Validation functions\nexport const validatePaginationMeta = (data: unknown) => {\n try {\n return paginationMetaSchema.parse(data);\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(z.prettifyError(error));\n }\n throw error;\n }\n};\n\n// Safe validation functions\nexport const safeParsePaginationMeta = (data: unknown) =>\n paginationMetaSchema.safeParse(data);\nexport const safeParseBaseQueryParams = (data: unknown) =>\n baseQueryParamsSchema.safeParse(data);\n","import type { OrderActorType } from \"./order-timeline\";\n\n/**\n * Inventory: stock states per variant and location, served to admin clients\n * under `stores/:storeRef/inventory` (contract:\n * ecomweb-project/archive/2026-09-15-inventory-purchase-orders/2026-09-15-inventory-contracts.md in the api repo).\n *\n * This SDK owns the vocabulary; the API pins it with\n * inventory-vocabulary.contract.spec.ts because the API cannot import the SDK.\n * Types only: the dashboard calls the admin routes through its own client.\n *\n * This module's vocabulary (`InventoryState`, `INVENTORY_STATES`, and the\n * related state lists below) is the set of ledger buckets a unit of stock can\n * sit in: available, committed, damaged, and so on. It is unrelated to\n * `InventoryStatus` in `./product-status`, which is a different, display-level\n * concept: a computed status (`in_stock` / `low_stock` / `out_of_stock` /\n * `backordered`) derived from a quantity threshold, with Vietnamese UI\n * labels. Do not wire a stock badge or filter to the wrong one.\n */\nexport const INVENTORY_STATES = [\n \"available\",\n \"committed\",\n \"damaged\",\n \"quality_control\",\n \"safety_stock\",\n \"other\",\n \"incoming\",\n] as const;\nexport type InventoryState = (typeof INVENTORY_STATES)[number];\n\n/** Shown together as \"Unavailable\". */\nexport const UNAVAILABLE_STATES = [\n \"damaged\",\n \"quality_control\",\n \"safety_stock\",\n \"other\",\n] as const satisfies readonly InventoryState[];\nexport type UnavailableState = (typeof UNAVAILABLE_STATES)[number];\n\n/** States a merchant may set, adjust or move between. `committed` and `incoming` are system-managed. */\nexport const ADJUSTABLE_STATES = [\n \"available\",\n \"damaged\",\n \"quality_control\",\n \"safety_stock\",\n \"other\",\n] as const satisfies readonly InventoryState[];\nexport type AdjustableState = (typeof ADJUSTABLE_STATES)[number];\n\n/** deny: checkout rejects when available is short. continue: available may go negative. */\nexport const INVENTORY_POLICIES = [\"deny\", \"continue\"] as const;\nexport type InventoryPolicy = (typeof INVENTORY_POLICIES)[number];\n\nexport const INVENTORY_ADJUSTMENT_REASONS = [\n // Reasons a merchant picks\n \"correction\",\n \"count\",\n \"received\",\n \"return_restock\",\n \"damaged\",\n \"theft_or_loss\",\n \"promotion_or_donation\",\n \"other\",\n // Reasons the system records\n \"initial_stock\",\n \"order_reserved\",\n \"order_fulfilled\",\n \"order_released\",\n \"order_restocked\",\n \"cancelled_not_restocked\",\n \"migration_backfill\",\n \"purchase_order_ordered\",\n \"purchase_order_edited\",\n \"purchase_order_cancelled\",\n \"purchase_order_closed\",\n] as const;\nexport type InventoryAdjustmentReason =\n (typeof INVENTORY_ADJUSTMENT_REASONS)[number];\n\nexport const MERCHANT_ADJUSTMENT_REASONS = [\n \"correction\",\n \"count\",\n \"received\",\n \"return_restock\",\n \"damaged\",\n \"theft_or_loss\",\n \"promotion_or_donation\",\n \"other\",\n] as const;\nexport type MerchantAdjustmentReason =\n (typeof MERCHANT_ADJUSTMENT_REASONS)[number];\n\n/** `code` values of inventory business errors. Localise from these, never from `message`. */\nexport const INVENTORY_ERROR_CODES = {\n /** 409. `details.items: InsufficientInventoryItem[]`. */\n INSUFFICIENT_INVENTORY: \"INSUFFICIENT_INVENTORY\",\n /** 409. `details.states: [{ variant_id, state, quantity }]`. */\n STATE_NEGATIVE: \"INVENTORY_STATE_NEGATIVE\",\n /** 404. `details.variant_ids: number[]`. */\n VARIANT_NOT_IN_STORE: \"INVENTORY_VARIANT_NOT_IN_STORE\",\n /** 400. `details.variant_ids: number[]`. */\n DUPLICATE_VARIANT: \"INVENTORY_DUPLICATE_VARIANT\",\n /** 409. `details: SetQuantitiesResponse`; the non-stale items WERE applied. */\n QUANTITY_STALE: \"INVENTORY_QUANTITY_STALE\",\n /** 400. More than 5,000 data rows. */\n IMPORT_TOO_LARGE: \"INVENTORY_IMPORT_TOO_LARGE\",\n /** 400. `details.missing_columns?: string[]`. */\n IMPORT_INVALID_FILE: \"INVENTORY_IMPORT_INVALID_FILE\",\n} as const;\nexport type InventoryErrorCode =\n (typeof INVENTORY_ERROR_CODES)[keyof typeof INVENTORY_ERROR_CODES];\n\n/** One entry of an `INSUFFICIENT_INVENTORY` error's `details.items`. */\nexport interface InsufficientInventoryItem {\n variant_id: number;\n requested: number;\n available: number;\n}\n\nexport interface InventoryQuantities {\n available: number;\n committed: number;\n damaged: number;\n quality_control: number;\n safety_stock: number;\n other: number;\n}\n\n/** What is physically held: everything except incoming. */\nexport function onHand(level: InventoryQuantities): number {\n return (\n level.available +\n level.committed +\n level.damaged +\n level.quality_control +\n level.safety_stock +\n level.other\n );\n}\n\n/**\n * Adds up the stock that cannot be sold: damaged, quality control, safety stock and other.\n *\n * @param level - the quantities of one variant at one location\n * @returns The total unavailable quantity\n */\nexport function unavailable(\n level: Pick<InventoryQuantities, UnavailableState>,\n): number {\n return (\n level.damaged + level.quality_control + level.safety_stock + level.other\n );\n}\n\n/** One row of `GET /inventory/levels`: a variant at a location. */\nexport interface InventoryLevelRow extends InventoryQuantities {\n variant_id: number;\n product_id: number;\n product_name: string;\n product_image: string | null;\n /** Option values joined with \" / \", null for a default-only product. */\n variant_title: string | null;\n /** product_variants.seller_sku */\n sku: string | null;\n location_id: number;\n track_inventory: boolean;\n inventory_policy: InventoryPolicy;\n unavailable: number;\n on_hand: number;\n incoming: number;\n /** ISO 8601. */\n updated_at: string;\n}\n\nexport interface StaleQuantity {\n variant_id: number;\n state: \"available\" | \"on_hand\";\n expected_quantity: number;\n current_quantity: number;\n}\n\nexport interface SetQuantitiesRequest {\n /** 1 to 250 items. */\n items: Array<{\n variant_id: number;\n state: \"available\" | \"on_hand\";\n quantity: number;\n /** Omit for last-write-wins; send the value you displayed to detect a concurrent edit. */\n expected_quantity?: number | null;\n }>;\n reason: MerchantAdjustmentReason;\n /** Max 500. */\n note?: string | null;\n /** Max 100. A replay returns `replayed: true` and writes nothing. */\n idempotency_key?: string | null;\n}\n\n/** 200 when `stale` is empty; otherwise the `details` of a 409 `INVENTORY_QUANTITY_STALE`. */\nexport interface SetQuantitiesResponse {\n applied: InventoryLevelRow[];\n stale: StaleQuantity[];\n replayed: boolean;\n}\n\nexport interface AdjustQuantitiesRequest {\n /** 1 to 250 items, `delta` never 0. */\n items: Array<{ variant_id: number; state: AdjustableState; delta: number }>;\n reason: MerchantAdjustmentReason;\n note?: string | null;\n idempotency_key?: string | null;\n}\n\nexport interface MoveQuantitiesRequest {\n /** 1 to 250 items, `from !== to`, `quantity > 0`. */\n items: Array<{\n variant_id: number;\n from: AdjustableState;\n to: AdjustableState;\n quantity: number;\n }>;\n /** Defaults to \"correction\". */\n reason?: MerchantAdjustmentReason;\n note?: string | null;\n idempotency_key?: string | null;\n}\n\nexport interface QuantitiesResponse {\n applied: InventoryLevelRow[];\n replayed: boolean;\n}\n\nexport interface InventoryActor {\n type: OrderActorType;\n id: string | null;\n name: string | null;\n}\n\n/** One adjustment group of `GET /inventory/variants/:variantId/history`, newest first. */\nexport interface InventoryHistoryEntry {\n id: number;\n /** ISO 8601. */\n created_at: string;\n reason: InventoryAdjustmentReason;\n note: string | null;\n actor: InventoryActor;\n /** `label` is the order code, or \"PO1042\". */\n reference: { type: \"order\" | \"purchase_order\"; id: number; label: string } | null;\n changes: Array<{ state: InventoryState; delta: number; quantity_after: number }>;\n}\n\nexport interface InventoryImportResponse {\n applied: number;\n unchanged: number;\n skipped: Array<{\n /** 1-based data row, header excluded. */\n row: number;\n variant_id: string | null;\n reason:\n | \"stale\"\n | \"not_found\"\n | \"invalid_quantity\"\n | \"missing_variant_id\"\n /** The second and later rows repeating a Variant ID; the first one applied. */\n | \"duplicate_variant_id\";\n current_on_hand: number | null;\n }>;\n}\n\nexport interface InventoryLocation {\n id: number;\n name: string;\n is_default: boolean;\n}\n","import { z } from \"zod\";\nimport {\n optionalTimestampSchema,\n urlSchema,\n positionOrderSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n} from \"./common\";\n\n/**\n * Category-related schemas based on Prisma models\n */\n\n// Category interface\nexport interface Category extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string | null;\n description: string | null;\n image_url: string | null;\n parent_id: Id | null;\n sort_order: number;\n is_active: boolean;\n external_cat_id: string | null;\n}\n\n// Category with children interface\nexport interface CategoryWithChildren extends Category {\n children?: CategoryWithChildren[];\n}\n\n// Category tree type\nexport type CategoryTree = CategoryWithChildren[];\n\n// Create category input type\nexport type CreateCategory = Omit<Category, \"id\" | keyof OptionalTimestamp>;\n\n// Update category input type\nexport type UpdateCategory = Partial<CreateCategory>;\n\n// Category main entity\nexport const categorySchema = z\n .object({\n id: idSchema,\n name: z.string().min(1),\n slug: z.string().optional().nullable(),\n description: z.string().optional().nullable(),\n image_url: urlSchema,\n parent_id: idSchema.optional().nullable(),\n sort_order: positionOrderSchema,\n is_active: z.boolean().default(true),\n external_cat_id: z.string().optional().nullable(),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Create category input\nexport const createCategorySchema = categorySchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update category input\nexport const updateCategorySchema = createCategorySchema.partial();\n\n// Category with children (using explicit interface)\nexport const categoryWithChildrenSchema = categorySchema.extend({\n children: z.array(z.lazy(() => categoryWithChildrenSchema)).optional(),\n}) as unknown as z.ZodType<CategoryWithChildren>;\n\n// Category tree structure\nexport const categoryTreeSchema = z.array(\n categoryWithChildrenSchema,\n) as unknown as z.ZodType<CategoryTree>;\n","import { z } from \"zod\";\nimport {\n optionalTimestampSchema,\n orderStatusSchema,\n fulfillmentStatusSchema,\n shippingStatusSchema,\n paymentStatusSchema,\n paymentMethodSchema,\n emailSchema,\n phoneSchema,\n moneySchema,\n uuidSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n OrderStatus,\n FulfillmentStatus,\n ShippingStatus,\n PaymentStatus,\n LegacyOrderStatus,\n PaymentMethod,\n} from \"./common\";\nimport type { OrderShipmentSummary } from \"./shipment\";\n\n/**\n * Order-related schemas based on Prisma models\n */\n\n/**\n * A promotion applied to an order or one of its items.\n *\n * `promotion_name` is resolved server-side from the promotions module and is\n * null when that lookup fails or the promotion was deleted — render the\n * amount without a name in that case, never a blank label.\n */\nexport interface AppliedPromotion {\n promotion_id: number;\n promotion_name?: string | null;\n /** Item-level rows carry a real amount; order-level rows are always null. */\n discount_amount?: number | null;\n shipping_discount?: number | null;\n}\n\n/**\n * Where an order came from. This SDK owns the vocabulary; the API pins it with\n * a contract test (collection rule_set precedent) because the API cannot import\n * the SDK — the SDK is a client OF the API, and depending on it would invert\n * that relationship.\n */\nexport const ORDER_SOURCES = [\"online\", \"pos\", \"phone\", \"admin\"] as const;\nexport type OrderSource = (typeof ORDER_SOURCES)[number];\n\n/**\n * What an admin may set on a keyed-in order. 'online' is deliberately absent:\n * only the two checkout routes can produce it, and they produce nothing else.\n */\nexport const ADMIN_ORDER_SOURCES = [\"pos\", \"phone\", \"admin\"] as const;\nexport type AdminOrderSource = (typeof ADMIN_ORDER_SOURCES)[number];\n\n/** The staff member who keyed an order in. Admin responses only. */\nexport interface OrderCreatedBy {\n id: string; // UUID\n name: string | null;\n email: string | null;\n}\n\n// Order interface\nexport interface Order extends OptionalTimestamp {\n id: Id;\n user_id: string | null; // UUID\n customer_name: string;\n customer_email: string | null; // null for a walk-in order with no email\n customer_phone: string;\n customer_avatar: string | null;\n // DEPRECATED: Legacy status field for backward compatibility\n status?: LegacyOrderStatus | string | null;\n // NEW: Separate status fields managed by state machines\n order_status: OrderStatus;\n fulfillment_status: FulfillmentStatus;\n shipping_status: ShippingStatus;\n payment_status: PaymentStatus;\n payment_method: PaymentMethod;\n subtotal: number;\n original_subtotal: number | null;\n shipping_fee: number;\n original_shipping_fee: number | null;\n shipping_discount: number | null;\n tax: number;\n discount: number;\n total: number;\n shipping_street: string;\n shipping_city: string;\n shipping_district: string | null;\n shipping_ward: string | null;\n shipping_postal_code: string | null;\n tracking_number: string | null;\n notes: string | null;\n order_number: Id;\n /**\n * The customer-facing identifier, e.g. \"#1042\" or \"DH-1042-26\". Built from\n * the store's configured order prefix/suffix (defaulting to \"#\") and frozen\n * at placement, so changing the setting never renames an existing order.\n *\n * This is the field to show customers and to look orders up by — the\n * equivalent of Shopify's Order.name. `order_number` is the underlying\n * sequence and should be treated as an implementation detail.\n */\n order_code: string;\n items?: OrderItem[];\n applied_promotions?: AppliedPromotion[];\n /** Snapshot from order_shippings; present when the API includes shipping. */\n shipping_method_name?: string | null;\n /** Display names resolved server-side from the shippings module. */\n shipping_city_name?: string | null;\n shipping_ward_name?: string | null;\n /** Carrier name chosen at checkout, when a carrier option was picked. */\n shipping_carrier?: string | null;\n /**\n * The buyer-facing shipment (carrier, tracking, events). Present on the\n * customer detail and guest lookup responses.\n */\n shipment?: OrderShipmentSummary | null;\n /**\n * Whether the buyer may still cancel this order. Present on the customer\n * detail and guest lookup responses.\n */\n can_cancel?: boolean;\n source: OrderSource;\n /**\n * The staff member who keyed this order in. Present on the detail\n * response only — resolving it is a profiles lookup per row, which the\n * list response omits to avoid an N+1. Null for shopper-placed orders.\n */\n created_by?: OrderCreatedBy | null;\n}\n\n// Order item interface\nexport interface OrderItem {\n id: Id;\n order_id: Id | null;\n product_id: Id | null;\n product_name: string;\n product_image: string | null;\n quantity: number;\n price: number;\n original_price: number | null; // Original price before promotions/discounts\n total: number;\n /** Total discount applied to this line. */\n discount?: number | null;\n applied_promotions?: AppliedPromotion[];\n variant_id: Id | null;\n variant_name: string | null;\n created_at: string | null; // ISO datetime string\n}\n\n// Order with items interface\nexport interface OrderWithItems extends Order {\n items?: OrderItem[];\n}\n\n// Customer order summary interface\nexport interface CustomerOrderSummary {\n customer_email: string;\n customer_name: string;\n total_orders: number;\n total_spent: number;\n last_order_date: string | null; // ISO datetime string\n}\n\n/**\n * Money fields the API always recomputes from the catalog, the promotion\n * engine and the shipping rules. They are accepted for backwards\n * compatibility but ignored — never rely on a value sent here.\n */\nexport type ServerComputedOrderAmounts =\n | \"subtotal\"\n | \"original_subtotal\"\n | \"shipping_fee\"\n | \"original_shipping_fee\"\n | \"shipping_discount\"\n | \"discount\"\n | \"total\";\n\n// Create order input type\n// Note: applied_promotions/shipping_*_name are response-only (computed/joined\n// server-side) and must never be accepted as write input — mirrors the\n// createOrderSchema/updateOrderSchema .omit() lists below.\nexport type CreateOrder = Omit<\n Order,\n | \"id\"\n | \"order_number\"\n | \"order_code\"\n | keyof OptionalTimestamp\n | \"applied_promotions\"\n | \"shipping_method_name\"\n | \"shipping_city_name\"\n | \"shipping_ward_name\"\n | \"shipping_carrier\"\n | \"shipment\"\n | \"can_cancel\"\n // Server-owned: 0 until store-level tax settings exist. Never write input.\n | \"tax\"\n | ServerComputedOrderAmounts\n // Response-only: resolved server-side. Never write input — the admin\n // write surface for source is AdminOrderSource, defined separately.\n | \"source\"\n | \"created_by\"\n> &\n Partial<Pick<Order, ServerComputedOrderAmounts>> & {\n /**\n * Which shipping method the shopper picked. Write-only: the API prices it\n * from the store's shipping rules and rejects a method with no available\n * rate for the address. Omit to let the server choose the best option.\n */\n shipping_method_id?: Id | null;\n shipping_rate_id?: Id | null;\n };\n\n// Update order input type\nexport type UpdateOrder = Partial<CreateOrder>;\n\n// Create order item input type\n// Note: discount/applied_promotions are response-only (computed server-side)\n// and must never be accepted as write input — mirrors createOrderItemSchema.\n// price/total are accepted but ignored: the API resolves the unit price from\n// the catalog so a client cannot choose what it pays.\nexport type CreateOrderItem = Omit<\n OrderItem,\n | \"id\"\n | \"created_at\"\n | \"discount\"\n | \"applied_promotions\"\n | \"price\"\n | \"total\"\n> &\n Partial<Pick<OrderItem, \"price\" | \"total\">>;\n\n// Update order item input type\nexport type UpdateOrderItem = Partial<Omit<CreateOrderItem, \"order_id\">>;\n\n// A promotion applied to an order or one of its items\nexport const appliedPromotionSchema = z.object({\n promotion_id: idSchema,\n promotion_name: z.string().optional().nullable(),\n discount_amount: moneySchema.optional().nullable(),\n shipping_discount: moneySchema.optional().nullable(),\n}) as unknown as z.ZodType<AppliedPromotion>;\n\n// Order item\nexport const orderItemSchema = z.object({\n id: idSchema,\n order_id: idSchema.optional().nullable(),\n product_id: idSchema.optional().nullable(),\n product_name: z.string().min(1),\n product_image: z.string().optional().nullable(),\n quantity: z.int32().min(1).default(1),\n price: moneySchema,\n original_price: moneySchema.optional().nullable(),\n total: moneySchema,\n discount: moneySchema.optional().nullable(),\n applied_promotions: z.array(appliedPromotionSchema).optional(),\n variant_id: idSchema.optional().nullable(),\n variant_name: z.string().optional().nullable(),\n created_at: z.iso.datetime().optional().nullable(),\n});\n\n// Order main entity\nexport const orderSchema = z\n .object({\n id: idSchema,\n user_id: uuidSchema.optional().nullable(),\n customer_name: z.string().min(1),\n customer_email: emailSchema.nullable(),\n customer_phone: phoneSchema,\n customer_avatar: z.string().optional().nullable(),\n // DEPRECATED: Legacy status field for backward compatibility\n status: z.string().optional().nullable(),\n // NEW: Separate status fields managed by state machines\n order_status: orderStatusSchema,\n fulfillment_status: fulfillmentStatusSchema,\n shipping_status: shippingStatusSchema,\n payment_status: paymentStatusSchema,\n payment_method: paymentMethodSchema.nullable().optional(),\n subtotal: moneySchema.default(0),\n original_subtotal: moneySchema.default(0),\n shipping_fee: moneySchema.default(0),\n original_shipping_fee: moneySchema.default(0),\n shipping_discount: moneySchema.default(0),\n tax: moneySchema.default(0),\n discount: moneySchema.default(0),\n total: moneySchema.default(0),\n shipping_street: z.string().min(1),\n shipping_city: z.string().min(1),\n shipping_district: z.string().optional().nullable(),\n shipping_ward: z.string().optional().nullable(),\n shipping_postal_code: z.string().optional().nullable(),\n tracking_number: z.string().optional().nullable(),\n notes: z.string().optional().nullable(),\n order_number: idSchema,\n order_code: z.string(),\n items: z.array(orderItemSchema).optional(),\n applied_promotions: z.array(appliedPromotionSchema).optional(),\n shipping_method_name: z.string().optional().nullable(),\n shipping_city_name: z.string().optional().nullable(),\n shipping_ward_name: z.string().optional().nullable(),\n source: z.enum(ORDER_SOURCES).default(\"online\"),\n created_by: z\n .object({\n id: uuidSchema,\n name: z.string().nullable(),\n email: z.string().nullable(),\n })\n .nullable()\n .optional(),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Create order schema\n// Note: applied_promotions/shipping_*_name are response-only (computed/joined\n// server-side) and must never be accepted as write input.\nexport const createOrderSchema = orderSchema\n .omit({\n id: true,\n order_number: true,\n order_code: true,\n created_at: true,\n updated_at: true,\n applied_promotions: true,\n shipping_method_name: true,\n shipping_city_name: true,\n shipping_ward_name: true,\n tax: true,\n source: true,\n created_by: true,\n })\n .extend({\n // Write-only: not part of the order response.\n shipping_method_id: idSchema.optional().nullable(),\n shipping_rate_id: idSchema.optional().nullable(),\n }) as unknown as z.ZodType<CreateOrder>;\n\n// Update order schema\nexport const updateOrderSchema = orderSchema\n .omit({\n id: true,\n order_number: true,\n order_code: true,\n created_at: true,\n updated_at: true,\n applied_promotions: true,\n shipping_method_name: true,\n shipping_city_name: true,\n shipping_ward_name: true,\n source: true,\n created_by: true,\n })\n .partial() as unknown as z.ZodType<UpdateOrder>;\n\n// Create order item schema\n// Note: discount/applied_promotions are response-only (computed server-side)\n// and must never be accepted as write input.\nexport const createOrderItemSchema = orderItemSchema\n .omit({\n id: true,\n created_at: true,\n discount: true,\n applied_promotions: true,\n })\n .partial({\n price: true,\n total: true,\n }) as unknown as z.ZodType<CreateOrderItem>;\n\n// Update order item schema\nexport const updateOrderItemSchema = orderItemSchema\n .omit({\n id: true,\n created_at: true,\n discount: true,\n applied_promotions: true,\n })\n .partial()\n .omit({\n order_id: true,\n }) as unknown as z.ZodType<UpdateOrderItem>;\n\n// Order with items schema\nexport const orderWithItemsSchema = orderSchema.extend({\n items: z.array(orderItemSchema).optional(),\n}) as unknown as z.ZodType<OrderWithItems>;\n\n// Customer order summary schema\nexport const customerOrderSummarySchema = z.object({\n customer_email: emailSchema,\n customer_name: z.string(),\n total_orders: z.int32(),\n total_spent: moneySchema,\n last_order_date: z.iso.datetime().optional().nullable(),\n}) as unknown as z.ZodType<CustomerOrderSummary>;\n","/**\n * The buyer-facing shipment summary carried on an order, plus its error codes.\n * The API builds it from the carrier booking; this is the wire shape only.\n */\nexport const SHIPMENT_STATUSES = [\n \"booked\",\n \"picked_up\",\n \"in_transit\",\n \"out_for_delivery\",\n \"delivered\",\n \"failed\",\n \"returned\",\n \"cancelled\",\n] as const;\nexport type ShipmentStatus = (typeof SHIPMENT_STATUSES)[number];\n\n/** One tracking event on a shipment. */\nexport interface OrderShipmentEvent {\n /** ISO 8601. */\n occurred_at: string;\n /** Carrier status text, ready to show. */\n label: string;\n location: string | null;\n}\n\n/** What a buyer sees of their shipment. */\nexport interface OrderShipmentSummary {\n carrier_name: string | null;\n carrier_logo_url: string | null;\n service_name: string | null;\n tracking_number: string | null;\n track_link: string | null;\n status: ShipmentStatus | null;\n events: OrderShipmentEvent[];\n}\n\n/** Error codes the order endpoints return for shipment-related refusals. */\nexport const ORDER_SHIPMENT_ERROR_CODES = {\n /** Cancelling is refused because a carrier shipment is already in progress. */\n CANCEL_BLOCKED_BY_SHIPMENT: \"ORDER_CANCEL_BLOCKED_BY_SHIPMENT\",\n} as const;\n","/**\n * The order timeline: status history plus internal staff comments, served to\n * admin clients by `GET stores/:storeRef/orders/:id/timeline`.\n *\n * The vocabulary is owned by `ecomweb-contracts/src/types/order-timeline.ts`;\n * this copy is kept in parity, and the API pins it in\n * `order-event-type-vocabulary.contract.spec.ts`. Types only: the dashboard calls the admin routes through its own\n * client.\n */\nexport const ORDER_EVENT_TYPES = [\n \"placed\",\n \"order_status_changed\",\n \"fulfillment_status_changed\",\n \"shipping_status_changed\",\n \"payment_status_changed\",\n \"tracking_number_updated\",\n \"shipment_booked\",\n \"shipment_cancelled\",\n \"shipment_failed\",\n] as const;\nexport type OrderEventType = (typeof ORDER_EVENT_TYPES)[number];\n\nexport const ORDER_ACTOR_TYPES = [\n \"staff\",\n \"customer\",\n \"api_key\",\n \"gateway\",\n \"system\",\n \"carrier\",\n] as const;\nexport type OrderActorType = (typeof ORDER_ACTOR_TYPES)[number];\n\nexport interface OrderTimelineActor {\n type: OrderActorType;\n /** Staff UUID, customer id, or API key id. Null for gateway, system, and guests. */\n id: string | null;\n /** Resolved display name, or null when unknown (a gateway reads `arguments.gateway`). */\n name: string | null;\n /**\n * The staff member's email, for showing a current staff member who has no\n * display name. Null for every other actor type, and for staff who have\n * left the store. Absent from APIs older than this field.\n */\n email?: string | null;\n}\n\nexport interface OrderTimelineEvent {\n kind: \"event\";\n id: string;\n event_type: OrderEventType;\n /**\n * Changed values only. Status and tracking events carry `{ from, to }`;\n * `placed` carries `{ source }`, plus `backfilled: true` for orders that\n * predate history tracking; gateway-attributed events add `gateway`.\n */\n arguments: Record<string, unknown> | null;\n reason: string | null;\n actor: OrderTimelineActor;\n /** ISO 8601. */\n created_at: string;\n}\n\nexport interface OrderTimelineCommentAuthor {\n id: string;\n name: string | null;\n email: string | null;\n /** Resolved from the staff member's profile; null when they have none. */\n avatar_url: string | null;\n}\n\nexport interface OrderTimelineComment {\n kind: \"comment\";\n id: string;\n /** Plain text. Never render as HTML. */\n body: string;\n author: OrderTimelineCommentAuthor;\n edited: boolean;\n /** Computed by the server for the requesting user; do not re-derive from a local clock. */\n can_edit: boolean;\n can_delete: boolean;\n /** ISO 8601. */\n created_at: string;\n}\n\nexport type OrderTimelineEntry = OrderTimelineEvent | OrderTimelineComment;\n\nexport interface OrderTimelineResponse {\n /** Newest first. */\n entries: OrderTimelineEntry[];\n /** True when more than 500 events or 500 comments exist; the oldest are omitted. */\n truncated: boolean;\n}\n\n/** What POST, PATCH, and DELETE on a comment return. Refetch the timeline after. */\nexport interface OrderCommentMutationResult {\n id: string;\n}\n","import { z } from \"zod\";\nimport { paginationMetaSchema } from \"./pagination\";\n\n// Promotion Enums\nexport const PromotionModeSchema = z.enum([\"DISCOUNT_CODE\", \"AUTOMATIC\"]);\nexport const PromotionTypeSchema = z.enum([\n \"PRODUCT_DISCOUNT\",\n \"CART_DISCOUNT\",\n \"FREE_SHIPPING\",\n \"FIXED_PRICE\",\n \"GIFT\",\n]);\nexport const DiscountMethodSchema = z.enum([\"PERCENTAGE\", \"FIXED_AMOUNT\"]);\nexport const ConditionTypeSchema = z.enum([\n \"PRODUCT\",\n \"CATEGORY\",\n \"VARIANT\",\n \"NONE\",\n]);\nexport const PromotionStatusSchema = z.enum([\n \"DRAFT\",\n \"ACTIVE\",\n \"EXPIRED\",\n \"DISABLED\",\n]);\n\n// Export enum values for runtime use\nexport const PromotionMode = {\n DISCOUNT_CODE: \"DISCOUNT_CODE\",\n AUTOMATIC: \"AUTOMATIC\",\n} as const;\n\nexport const PromotionType = {\n PRODUCT_DISCOUNT: \"PRODUCT_DISCOUNT\",\n CART_DISCOUNT: \"CART_DISCOUNT\",\n FREE_SHIPPING: \"FREE_SHIPPING\",\n FIXED_PRICE: \"FIXED_PRICE\",\n GIFT: \"GIFT\",\n} as const;\n\nexport const DiscountMethod = {\n PERCENTAGE: \"PERCENTAGE\",\n FIXED_AMOUNT: \"FIXED_AMOUNT\",\n} as const;\n\nexport const ConditionType = {\n PRODUCT: \"PRODUCT\",\n CATEGORY: \"CATEGORY\",\n VARIANT: \"VARIANT\",\n NONE: \"NONE\",\n} as const;\n\nexport const PromotionStatus = {\n DRAFT: \"DRAFT\",\n ACTIVE: \"ACTIVE\",\n EXPIRED: \"EXPIRED\",\n DISABLED: \"DISABLED\",\n} as const;\n\n// Export enum types\nexport type PromotionModeType =\n (typeof PromotionMode)[keyof typeof PromotionMode];\nexport type PromotionTypeType =\n (typeof PromotionType)[keyof typeof PromotionType];\nexport type DiscountMethodType =\n (typeof DiscountMethod)[keyof typeof DiscountMethod];\nexport type ConditionTypeType =\n (typeof ConditionType)[keyof typeof ConditionType];\nexport type PromotionStatusType =\n (typeof PromotionStatus)[keyof typeof PromotionStatus];\n\n// Core Promotion Schema\nexport const PromotionSchema = z.object({\n id: z.number().int().positive(),\n name: z.string().min(1).max(255),\n mode: PromotionModeSchema,\n code: z.string().min(1).max(50).optional(),\n description: z.string().max(1000).optional(),\n start_at: z.string().datetime(),\n end_at: z.string().datetime().optional(),\n status: PromotionStatusSchema,\n type: PromotionTypeSchema,\n condition_type: ConditionTypeSchema,\n target_ids: z.array(z.string().uuid()).optional(),\n min_amount: z.number().positive().optional(),\n min_quantity: z.number().int().positive().optional(),\n discount_method: DiscountMethodSchema.optional(),\n discount_value: z.number().nonnegative().optional(),\n max_discount_amount: z.number().nonnegative().optional(),\n fixed_price: z.number().nonnegative().optional(),\n gift_product_ids: z.array(z.string().uuid()),\n gift_quantity: z.number().int().positive().optional(),\n usage_limit: z.number().int().positive().optional(),\n usage_limit_per_user: z.number().int().positive().optional(),\n checkout_suggestion_enabled: z.boolean().optional(),\n created_at: z.string().datetime(),\n updated_at: z.string().datetime(),\n created_by: z.string().uuid().optional(),\n updated_by: z.string().uuid().optional(),\n});\n\n// Create Promotion Schema\nexport const CreatePromotionSchema = z.object({\n name: z.string().min(1, \"Tên khuyến mãi là bắt buộc\").max(255),\n mode: PromotionModeSchema,\n code: z.string().min(1).max(50).optional(),\n description: z.string().max(1000).optional(),\n start_at: z.iso.datetime(),\n end_at: z.iso.datetime().optional(),\n type: PromotionTypeSchema,\n condition_type: ConditionTypeSchema,\n target_ids: z\n .array(z.uuid())\n .optional()\n .superRefine((ids: any, ctx: any) => {\n const conditionType = ctx.parent?.condition_type;\n if (conditionType === \"NONE\") {\n return true; // Allow empty array for NONE condition\n }\n return ids && ids.length > 0;\n }),\n min_amount: z.number().positive().optional(),\n min_quantity: z.number().int().positive().optional(),\n discount_method: DiscountMethodSchema.optional(),\n discount_value: z.number().nonnegative().optional(),\n max_discount_amount: z.number().nonnegative().optional(),\n fixed_price: z.number().nonnegative().optional(),\n gift_product_ids: z.array(z.uuid()).optional(),\n gift_quantity: z.number().int().positive().optional(),\n usage_limit: z.number().int().positive().optional(),\n usage_limit_per_user: z.number().int().positive().optional(),\n checkout_suggestion_enabled: z.boolean().optional(),\n});\n\n// Update Promotion Schema\nexport const UpdatePromotionSchema = CreatePromotionSchema.partial().extend({\n status: PromotionStatusSchema.optional(),\n});\n\n// Promotion with calculated discount amount (for API responses)\nexport const PromotionWithDiscountSchema = PromotionSchema.extend({\n discount_amount: z.number().optional(),\n});\n\n// Promotion Statistics Schema\nexport const PromotionStatisticsSchema = z.object({\n total_promotions: z.number().int().nonnegative(),\n active_promotions: z.number().int().nonnegative(),\n draft_promotions: z.number().int().nonnegative(),\n expired_promotions: z.number().int().nonnegative(),\n disabled_promotions: z.number().int().nonnegative(),\n total_usage: z.number().int().nonnegative(),\n total_discount_amount: z.number().nonnegative(),\n top_promotions: z.array(PromotionSchema),\n});\n\n// Pagination Schema\nexport const PaginatedPromotionsResponseSchema = z.object({\n data: z.array(PromotionSchema),\n meta: paginationMetaSchema,\n});\n\n// Query Parameters Schema\nexport const PromotionQueryParamsSchema = z.object({\n limit: z.number().int().positive().optional(),\n offset: z.number().int().nonnegative().optional(),\n order: z.enum([\"asc\", \"desc\"]).optional(),\n sort: z\n .enum([\n \"name\",\n \"start_at\",\n \"end_at\",\n \"status\",\n \"type\",\n \"created_at\",\n \"updated_at\",\n ])\n .optional(),\n search: z.string().max(255).optional(),\n status: z.union([PromotionStatusSchema, z.literal(\"all\")]).optional(),\n type: z.union([PromotionTypeSchema, z.literal(\"all\")]).optional(),\n mode: z.union([PromotionModeSchema, z.literal(\"all\")]).optional(),\n});\n\n// Export types\nexport type Promotion = z.infer<typeof PromotionSchema>;\nexport type CreatePromotion = z.infer<typeof CreatePromotionSchema>;\nexport type UpdatePromotion = z.infer<typeof UpdatePromotionSchema>;\nexport type PromotionWithDiscount = z.infer<typeof PromotionWithDiscountSchema>;\nexport type PromotionStatistics = z.infer<typeof PromotionStatisticsSchema>;\nexport type PaginatedPromotionsResponse = z.infer<\n typeof PaginatedPromotionsResponseSchema\n>;\nexport type PromotionQueryParams = z.infer<typeof PromotionQueryParamsSchema>;\n\n// UI Constants\nexport const PROMOTION_MODE_LABELS: Record<PromotionModeType, string> = {\n DISCOUNT_CODE: \"Mã giảm giá\",\n AUTOMATIC: \"Tự động áp dụng\",\n};\n\nexport const PROMOTION_TYPE_LABELS: Record<PromotionTypeType, string> = {\n PRODUCT_DISCOUNT: \"Giảm giá sản phẩm\",\n CART_DISCOUNT: \"Giảm giá giỏ hàng\",\n FREE_SHIPPING: \"Miễn phí vận chuyển\",\n FIXED_PRICE: \"Giá cố định\",\n GIFT: \"Quà tặng\",\n};\n\nexport const DISCOUNT_METHOD_LABELS: Record<DiscountMethodType, string> = {\n PERCENTAGE: \"Phần trăm\",\n FIXED_AMOUNT: \"Số tiền cố định\",\n};\n\nexport const CONDITION_TYPE_LABELS: Record<ConditionTypeType, string> = {\n PRODUCT: \"Sản phẩm\",\n CATEGORY: \"Danh mục\",\n VARIANT: \"Biến thể\",\n NONE: \"Tất cả sản phẩm\",\n};\n\nexport const PROMOTION_STATUS_LABELS: Record<PromotionStatusType, string> = {\n DRAFT: \"Nháp\",\n ACTIVE: \"Đang hoạt động\",\n EXPIRED: \"Đã hết hạn\",\n DISABLED: \"Đã tắt\",\n};\n\nexport const PROMOTION_STATUS_COLORS: Record<PromotionStatusType, string> = {\n DRAFT: \"bg-gray-100 text-gray-800\",\n ACTIVE: \"bg-green-100 text-green-800\",\n EXPIRED: \"bg-red-100 text-red-800\",\n DISABLED: \"bg-yellow-100 text-yellow-800\",\n};\n\nexport const PROMOTION_TYPE_COLORS: Record<PromotionTypeType, string> = {\n PRODUCT_DISCOUNT: \"bg-blue-100 text-blue-800\",\n CART_DISCOUNT: \"bg-purple-100 text-purple-800\",\n FREE_SHIPPING: \"bg-green-100 text-green-800\",\n FIXED_PRICE: \"bg-orange-100 text-orange-800\",\n GIFT: \"bg-pink-100 text-pink-800\",\n};\n\nexport const PROMOTION_MODE_COLORS: Record<PromotionModeType, string> = {\n DISCOUNT_CODE: \"bg-indigo-100 text-indigo-800\",\n AUTOMATIC: \"bg-emerald-100 text-emerald-800\",\n};\n","import { z } from \"zod\";\nimport {\n optionalTimestampSchema,\n blogPostStatusSchema,\n slugSchema,\n colorSchema,\n urlSchema,\n emailSchema,\n positionOrderSchema,\n uuidSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n BlogPostStatus,\n} from \"./common\";\n\n/**\n * Blog-related schemas based on Prisma models\n */\n\n// Table of Contents item interface\nexport interface TocItem {\n id: string;\n level: number;\n textContent: string;\n pos: number;\n}\n\n// Table of Contents item schema\nexport const tocItemSchema = z.object({\n id: z.string(),\n level: z.number().int().min(1).max(6),\n textContent: z.string(),\n pos: z.number().int(),\n});\n\n// Blog category interface\nexport interface BlogCategory extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string;\n description: string | null;\n color: string | null;\n sort_order: number;\n}\n\n// Blog tag interface\nexport interface BlogTag extends OptionalTimestamp {\n id: Id;\n name: string;\n slug: string;\n}\n\n// Blog post interface\nexport interface BlogPost extends OptionalTimestamp {\n id: Id;\n title: string;\n slug: string;\n content: string | null;\n toc: TocItem[] | null;\n excerpt: string | null;\n featured_image_url: string | null;\n status: BlogPostStatus;\n is_featured: boolean;\n scheduled_at: string | null;\n published_at: string | null;\n author_id: string | null;\n view_count: number;\n reading_time: number;\n created_at: string;\n}\n\n// Blog comment interface\nexport interface BlogComment {\n id: Id;\n blog_post_id: Id | null;\n parent_comment_id: Id | null;\n author_name: string;\n /** Never on public reads (the API hides commenter emails); admin reads only. */\n author_email?: string;\n author_website: string | null;\n content: string;\n is_approved: boolean;\n created_at: string | null;\n}\n\n// Blog settings interface\nexport interface BlogSettings extends OptionalTimestamp {\n id: Id;\n is_enabled: boolean;\n blog_title: string;\n blog_description: string | null;\n posts_per_page: number;\n allow_comments: boolean;\n moderate_comments: boolean;\n show_author: boolean;\n show_reading_time: boolean;\n enable_rss: boolean;\n custom_css: string | null;\n}\n\n// Blog post category (many-to-many) interface\nexport interface BlogPostCategory {\n blog_post_id: Id;\n blog_category_id: Id;\n}\n\n// Blog post tag (many-to-many) interface\nexport interface BlogPostTag {\n blog_post_id: Id;\n blog_tag_id: Id;\n}\n\n// Blog category\nexport const blogCategorySchema = z\n .object({\n id: idSchema,\n name: z.string().min(1).max(100),\n slug: slugSchema.max(100),\n description: z.string().optional().nullable(),\n color: colorSchema,\n sort_order: positionOrderSchema,\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog tag\nexport const blogTagSchema = z\n .object({\n id: idSchema,\n name: z.string().min(1).max(50),\n slug: slugSchema.max(50),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog post\nexport const blogPostSchema = z\n .object({\n id: idSchema,\n title: z.string().min(1).max(255),\n slug: slugSchema.max(255),\n content: z.string().optional().nullable(),\n toc: z.array(tocItemSchema).optional().nullable(),\n excerpt: z.string().optional().nullable(),\n featured_image_url: urlSchema,\n status: blogPostStatusSchema.default(\"draft\"),\n is_featured: z.boolean().default(false),\n scheduled_at: z.iso.datetime().optional().nullable(),\n published_at: z.iso.datetime().optional().nullable(),\n author_id: uuidSchema.optional().nullable(),\n view_count: z.int32().default(0),\n reading_time: z.int32().default(0),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog comment\nexport const blogCommentSchema = z.object({\n id: idSchema,\n blog_post_id: idSchema.optional().nullable(),\n parent_comment_id: idSchema.optional().nullable(),\n author_name: z.string().min(1).max(100),\n // Optional on reads: the public comment list no longer returns it.\n author_email: emailSchema.optional(),\n author_website: z.url().max(255).optional().nullable(),\n content: z.string().min(1),\n is_approved: z.boolean().default(false),\n created_at: z.iso.datetime().optional().nullable(),\n});\n\n// Blog settings\nexport const blogSettingsSchema = z\n .object({\n id: idSchema,\n is_enabled: z.boolean().default(true),\n blog_title: z.string().max(255).default(\"Blog\"),\n blog_description: z.string().optional().nullable(),\n posts_per_page: z.int32().default(10),\n allow_comments: z.boolean().default(true),\n moderate_comments: z.boolean().default(true),\n show_author: z.boolean().default(true),\n show_reading_time: z.boolean().default(true),\n enable_rss: z.boolean().default(true),\n custom_css: z.string().optional().nullable(),\n })\n .extend(optionalTimestampSchema.shape);\n\n// Blog post categories (many-to-many)\nexport const blogPostCategorySchema = z.object({\n blog_post_id: idSchema,\n blog_category_id: idSchema,\n});\n\n// Blog post tags (many-to-many)\nexport const blogPostTagSchema = z.object({\n blog_post_id: idSchema,\n blog_tag_id: idSchema,\n});\n\n// Create schemas\nexport const createBlogCategorySchema = blogCategorySchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\nexport const createBlogTagSchema = blogTagSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\nexport const createBlogPostSchema = blogPostSchema.omit({\n id: true,\n view_count: true,\n created_at: true,\n updated_at: true,\n});\n\n// Posting a comment still needs an email, even though reads omit it.\nexport const createBlogCommentSchema = blogCommentSchema\n .omit({\n id: true,\n created_at: true,\n })\n .extend({ author_email: emailSchema });\n\nexport const createBlogSettingsSchema = blogSettingsSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update schemas\nexport const updateBlogCategorySchema = createBlogCategorySchema.partial();\n\nexport const updateBlogTagSchema = createBlogTagSchema.partial();\n\nexport const updateBlogPostSchema = createBlogPostSchema.partial();\n\nexport const updateBlogCommentSchema = createBlogCommentSchema.partial().omit({\n blog_post_id: true,\n});\n\nexport const updateBlogSettingsSchema = createBlogSettingsSchema.partial();\n\n// Blog post with relations\nexport interface BlogPostWithRelations\n extends Omit<BlogPost, \"blog_categories\" | \"blog_tags\" | \"blog_comments\"> {\n blog_categories?: BlogCategory[];\n blog_tags?: BlogTag[];\n blog_comments?: BlogComment[];\n}\n\nexport const blogPostWithRelationsSchema = blogPostSchema.extend({\n blog_categories: z.array(blogCategorySchema).optional(),\n blog_tags: z.array(blogTagSchema).optional(),\n blog_comments: z.array(blogCommentSchema).optional(),\n}) as unknown as z.ZodType<BlogPostWithRelations>;\n\n// Blog comment with replies\nexport interface BlogCommentWithReplies extends Omit<BlogComment, \"replies\"> {\n replies?: BlogCommentWithReplies[];\n}\n\nconst blogCommentWithRepliesSchemaInner = z.lazy(() =>\n blogCommentSchema.extend({\n replies: z.array(blogCommentWithRepliesSchemaInner).optional(),\n }),\n) as z.ZodType<BlogCommentWithReplies>;\n\nexport const blogCommentWithRepliesSchema = blogCommentWithRepliesSchemaInner;\n\n// Create types\nexport type CreateBlogCategory = Omit<\n BlogCategory,\n \"id\" | keyof OptionalTimestamp\n>;\nexport type CreateBlogTag = Omit<BlogTag, \"id\" | keyof OptionalTimestamp>;\nexport type CreateBlogPost = Omit<\n BlogPost,\n \"id\" | \"view_count\" | keyof OptionalTimestamp\n>;\nexport type CreateBlogComment = Omit<\n BlogComment,\n \"id\" | \"created_at\" | \"author_email\"\n> & { author_email: string };\nexport type CreateBlogSettings = Omit<\n BlogSettings,\n \"id\" | keyof OptionalTimestamp\n>;\n\n// Update types\nexport type UpdateBlogCategory = Partial<CreateBlogCategory>;\nexport type UpdateBlogTag = Partial<CreateBlogTag>;\nexport type UpdateBlogPost = Partial<CreateBlogPost>;\nexport type UpdateBlogComment = Partial<\n Omit<CreateBlogComment, \"blog_post_id\">\n>;\nexport type UpdateBlogSettings = Partial<CreateBlogSettings>;\n","import { z } from \"zod\";\nimport {\n timestampSchema,\n slugSchema,\n positionOrderSchema,\n idSchema,\n OptionalTimestamp,\n Id,\n} from \"./common\";\n\n/**\n * Content-related schemas based on Prisma models\n */\n\n// Content page interface\nexport interface ContentPage extends OptionalTimestamp {\n id: Id;\n title: string;\n content: string | null;\n is_published: boolean;\n page_type: string | null;\n sort_order: number;\n slug: string;\n}\n\n// Create content page input type\nexport type CreateContentPage = Omit<\n ContentPage,\n \"id\" | keyof OptionalTimestamp\n>;\n\n// Update content page input type\nexport type UpdateContentPage = Partial<CreateContentPage>;\n\n// Content page\nexport const contentPageSchema = z\n .object({\n id: idSchema,\n title: z.string().min(1),\n content: z.string().optional().nullable(),\n is_published: z.boolean().default(false),\n page_type: z.string().optional().nullable(),\n sort_order: positionOrderSchema,\n slug: slugSchema.max(255),\n })\n .extend(timestampSchema.shape);\n\n// Create content page schema\nexport const createContentPageSchema = contentPageSchema.omit({\n id: true,\n created_at: true,\n updated_at: true,\n});\n\n// Update content page schema\nexport const updateContentPageSchema = contentPageSchema\n .omit({\n id: true,\n created_at: true,\n updated_at: true,\n })\n .partial();\n","import { z } from \"zod\";\n\n/**\n * Theme settings: a theme declares its own settings (spec: schema-driven\n * themes §5.2), merchants fill in values, and the storefront reads them.\n * The types below are the authoring shape; `themeSchemaSchema` checks the same\n * shape at runtime (schemas uploaded by deploys, published by CI).\n */\n\n/** Hex only: theme colors are interpolated into a <style> tag. */\nexport const THEME_HEX_COLOR =\n /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;\n\nconst SETTING_ID = /^[a-z][a-z0-9_]*$/;\n\ntype Primitive = string | number | boolean;\n\nexport interface ThemeVisibleIf {\n readonly setting: string;\n readonly equals?: Primitive;\n readonly not_equals?: Primitive;\n readonly is_set?: boolean;\n}\n\ninterface SettingBase<T extends string> {\n readonly type: T;\n readonly id: string;\n readonly label: string;\n readonly info?: string;\n readonly visible_if?: ThemeVisibleIf;\n}\n\nexport type ThemeSetting =\n | (SettingBase<\"text\" | \"textarea\"> & {\n readonly default?: string;\n readonly placeholder?: string;\n })\n | (SettingBase<\"richtext\" | \"url\" | \"color\" | \"menu\"> & {\n readonly default?: string;\n })\n | SettingBase<\n | \"image_picker\"\n | \"collection\"\n | \"page\"\n | \"blog_post\"\n | \"blog_category\"\n | \"blog_tag\"\n | \"product\"\n >\n | (SettingBase<\"checkbox\"> & { readonly default?: boolean })\n | (SettingBase<\"number\"> & {\n readonly default?: number;\n readonly min?: number;\n readonly max?: number;\n })\n | (SettingBase<\"range\"> & {\n readonly min: number;\n readonly max: number;\n readonly step: number;\n readonly unit?: string;\n readonly default: number;\n })\n | (SettingBase<\"select\"> & {\n readonly options: readonly {\n readonly value: string;\n readonly label: string;\n }[];\n readonly default?: string;\n });\n\nexport type ThemeSettingType = ThemeSetting[\"type\"];\n\nexport interface ThemeDisplayItem {\n readonly type: \"header\" | \"paragraph\";\n readonly content: string;\n}\n\nexport type ThemeSchemaItem = ThemeSetting | ThemeDisplayItem;\n\nexport interface ThemeSchemaGroup {\n readonly name: string;\n readonly settings: readonly ThemeSchemaItem[];\n}\n\nexport type ThemeSchema = readonly ThemeSchemaGroup[];\n\nexport type ThemeValue = string | number | boolean;\nexport type ThemeValues = Record<string, ThemeValue | null>;\n\nexport interface ThemeValueError {\n key: string;\n message: string;\n}\n\ntype ValueOf<T extends ThemeSettingType> = T extends \"checkbox\"\n ? boolean\n : T extends \"number\" | \"range\"\n ? number\n : string;\n\ntype SettingsIn<S extends ThemeSchema> = Extract<\n S[number][\"settings\"][number],\n ThemeSetting\n>;\n\n/** The values a schema produces: settings with a default are never null. */\nexport type ThemeSettingsOf<S extends ThemeSchema> = {\n [K in SettingsIn<S> as K[\"id\"]]: K extends { readonly default: unknown }\n ? ValueOf<K[\"type\"]>\n : ValueOf<K[\"type\"]> | null;\n};\n\n// ─── Runtime schema ─────────────────────────────────────────────\n\nconst primitive = z.union([z.string(), z.number(), z.boolean()]);\n\nconst visibleIfSchema = z\n .object({\n setting: z.string().regex(SETTING_ID),\n equals: primitive.optional(),\n not_equals: primitive.optional(),\n is_set: z.boolean().optional(),\n })\n .refine(\n v =>\n [v.equals, v.not_equals, v.is_set].filter(x => x !== undefined).length ===\n 1,\n { message: \"visible_if needs exactly one of equals, not_equals, is_set\" }\n );\n\nconst base = {\n id: z.string().regex(SETTING_ID, \"setting ids are snake_case\"),\n label: z.string().min(1),\n info: z.string().optional(),\n visible_if: visibleIfSchema.optional(),\n};\n\nconst itemSchema = z.discriminatedUnion(\"type\", [\n z.object({\n ...base,\n type: z.literal(\"text\"),\n default: z.string().optional(),\n placeholder: z.string().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"textarea\"),\n default: z.string().optional(),\n placeholder: z.string().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"richtext\"),\n default: z.string().optional(),\n }),\n z.object({ ...base, type: z.literal(\"url\"), default: z.string().optional() }),\n z.object({\n ...base,\n type: z.literal(\"color\"),\n default: z.string().regex(THEME_HEX_COLOR).optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"menu\"),\n default: z.string().optional(),\n }),\n z.object({ ...base, type: z.literal(\"image_picker\") }),\n z.object({ ...base, type: z.literal(\"collection\") }),\n z.object({ ...base, type: z.literal(\"page\") }),\n z.object({ ...base, type: z.literal(\"blog_post\") }),\n z.object({ ...base, type: z.literal(\"blog_category\") }),\n z.object({ ...base, type: z.literal(\"blog_tag\") }),\n z.object({ ...base, type: z.literal(\"product\") }),\n z.object({\n ...base,\n type: z.literal(\"checkbox\"),\n default: z.boolean().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"number\"),\n default: z.number().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n z.object({\n ...base,\n type: z.literal(\"range\"),\n min: z.number(),\n max: z.number(),\n step: z.number().positive(),\n unit: z.string().optional(),\n default: z.number(),\n }),\n z.object({\n ...base,\n type: z.literal(\"select\"),\n options: z\n .array(z.object({ value: z.string(), label: z.string().min(1) }))\n .min(1),\n default: z.string().optional(),\n }),\n z.object({ type: z.literal(\"header\"), content: z.string().min(1) }),\n z.object({ type: z.literal(\"paragraph\"), content: z.string().min(1) }),\n]);\n\nexport const themeSchemaSchema = z\n .array(z.object({ name: z.string().min(1), settings: z.array(itemSchema) }))\n .superRefine((groups, ctx) => {\n const settings = groups.flatMap(g => g.settings).filter(isSetting);\n const ids = new Set<string>();\n for (const s of settings) {\n if (ids.has(s.id)) {\n ctx.addIssue({\n code: \"custom\",\n message: `duplicate setting id \"${s.id}\"`,\n });\n }\n ids.add(s.id);\n }\n for (const s of settings) {\n if (\"default\" in s && s.default !== undefined && s.default !== \"\") {\n const problem = checkValue(s as ThemeSetting, s.default);\n if (problem) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default ${JSON.stringify(s.default)} ${problem}`,\n });\n }\n }\n if (s.visible_if && !ids.has(s.visible_if.setting)) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: visible_if names unknown setting \"${s.visible_if.setting}\"`,\n });\n }\n if (\n s.type === \"select\" &&\n s.default !== undefined &&\n !s.options.some(o => o.value === s.default)\n ) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default \"${s.default}\" is not one of its options`,\n });\n }\n if (s.type === \"range\") {\n if (s.min >= s.max) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: min must be below max`,\n });\n } else if (s.default < s.min || s.default > s.max) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default ${s.default} is outside ${s.min}–${s.max}`,\n });\n }\n }\n if (\n s.type === \"number\" &&\n s.default !== undefined &&\n ((s.min !== undefined && s.default < s.min) ||\n (s.max !== undefined && s.default > s.max))\n ) {\n ctx.addIssue({\n code: \"custom\",\n message: `${s.id}: default ${s.default} is outside its bounds`,\n });\n }\n }\n });\n\nfunction isSetting<T extends { type: string }>(\n item: T\n): item is Exclude<T, { type: \"header\" | \"paragraph\" }> {\n return item.type !== \"header\" && item.type !== \"paragraph\";\n}\n\n/**\n * Validates a schema from outside the code (CI upload, deploy upload). Throws\n * an Error whose message lists every problem, readable in a build log.\n */\nexport function parseThemeSchema(input: unknown): ThemeSchema {\n const result = themeSchemaSchema.safeParse(input);\n if (!result.success) {\n throw new Error(`Invalid theme schema:\\n${z.prettifyError(result.error)}`);\n }\n return result.data as ThemeSchema;\n}\n\n// ─── Values ─────────────────────────────────────────────────────\n\n/**\n * Lists every setting in a theme schema, across all groups, leaving out headers and other non-setting entries.\n *\n * @param schema - the theme schema\n * @returns The settings in schema order\n */\nexport function themeSettings(schema: ThemeSchema): ThemeSetting[] {\n return schema.flatMap(g => g.settings.filter(isSetting));\n}\n\n/**\n * Builds the default value of every setting in a theme schema.\n *\n * @param schema - the theme schema\n * @returns A map from setting id to its default, or `null` when a setting has none\n */\nexport function themeDefaults(schema: ThemeSchema): ThemeValues {\n const out: ThemeValues = {};\n for (const s of themeSettings(schema)) {\n out[s.id] = \"default\" in s && s.default !== undefined ? s.default : null;\n }\n return out;\n}\n\n/** Types whose empty string is a real value rather than \"unset\". */\nconst TEXT_TYPES = new Set<ThemeSettingType>([\"text\", \"textarea\", \"richtext\"]);\n\n/**\n * An absolute http(s) URL, or a path on this site (\"/x\", never \"//x\"). No\n * backslashes anywhere: browsers read \"/\\\\host\" as \"//host\".\n */\nconst SAFE_URL = /^(?:https?:\\/\\/[^\\s\\\\]+|\\/(?![/\\\\])[^\\s\\\\]*)$/i;\n\nfunction checkValue(setting: ThemeSetting, value: unknown): string | null {\n switch (setting.type) {\n case \"checkbox\":\n return typeof value === \"boolean\" ? null : \"must be true or false\";\n case \"number\":\n case \"range\": {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return \"must be a number\";\n }\n if (setting.min !== undefined && value < setting.min) {\n return `must be at least ${setting.min}`;\n }\n if (setting.max !== undefined && value > setting.max) {\n return `must be at most ${setting.max}`;\n }\n return null;\n }\n }\n if (typeof value !== \"string\") return \"must be text\";\n switch (setting.type) {\n case \"color\":\n return THEME_HEX_COLOR.test(value)\n ? null\n : \"must be a hex color such as #1a2b3c\";\n case \"url\":\n case \"image_picker\":\n return SAFE_URL.test(value)\n ? null\n : \"must be an http(s) URL or a path starting with /\";\n case \"select\":\n return setting.options.some(o => o.value === value)\n ? null\n : `must be one of ${setting.options.map(o => o.value).join(\", \")}`;\n default:\n return null;\n }\n}\n\n/**\n * Checks a set of saved theme values against a theme schema. Settings with no value are skipped.\n *\n * @param schema - the theme schema\n * @param input - the values to check, as an object keyed by setting id\n * @returns The accepted values and a list of per-setting errors\n */\nexport function validateThemeValues(\n schema: ThemeSchema,\n input: unknown\n): { values: Record<string, ThemeValue>; errors: ThemeValueError[] } {\n const raw =\n input && typeof input === \"object\" && !Array.isArray(input)\n ? (input as Record<string, unknown>)\n : {};\n const values: Record<string, ThemeValue> = {};\n const errors: ThemeValueError[] = [];\n for (const s of themeSettings(schema)) {\n const value = raw[s.id];\n if (value === undefined || value === null) continue;\n // A cleared text field is a value (it can blank out a default); for\n // every other type \"\" means the merchant left the setting unset.\n if (value === \"\" && !TEXT_TYPES.has(s.type)) continue;\n const problem = checkValue(s, value);\n if (problem) errors.push({ key: s.id, message: `${s.label} ${problem}` });\n else values[s.id] = value as ThemeValue;\n }\n return { values, errors };\n}\n\n/** Defaults under the valid values; invalid values fall back to defaults. */\nexport function resolveThemeSettings(\n schema: ThemeSchema,\n input: unknown\n): { settings: ThemeValues; errors: ThemeValueError[] } {\n const { values, errors } = validateThemeValues(schema, input);\n return { settings: { ...themeDefaults(schema), ...values }, errors };\n}\n\n/** \"Set\" means not null, not \"\" and not false. */\nexport function isSettingVisible(\n setting: ThemeSetting,\n values: ThemeValues\n): boolean {\n const rule = setting.visible_if;\n if (!rule) return true;\n const value = values[rule.setting] ?? null;\n if (rule.is_set !== undefined) {\n const isSet = value !== null && value !== \"\" && value !== false;\n return rule.is_set === isSet;\n }\n if (rule.equals !== undefined) return value === rule.equals;\n return value !== rule.not_equals;\n}\n\n/** The major of a release version (\"1.4.2\" → 1); null for anything else. */\nexport function themeMajor(version: string | null | undefined): number | null {\n const match = /^(\\d+)\\.\\d+\\.\\d+$/.exec(version ?? \"\");\n return match ? Number(match[1]) : null;\n}\n\n/**\n * How a theme's settings values move to a new major (theme majors spec):\n * declared as data in the new major's manifest, run in order by the API\n * when a merchant upgrades.\n */\nexport type ThemeMigrationStep =\n | { readonly op: \"rename\"; readonly from: string; readonly to: string }\n | { readonly op: \"remove\"; readonly key: string }\n | {\n readonly op: \"map\";\n readonly key: string;\n readonly values: Readonly<Record<string, ThemeValue>>;\n }\n | { readonly op: \"copy\"; readonly from: string; readonly to: string }\n | {\n readonly op: \"default\";\n readonly key: string;\n readonly value: ThemeValue;\n };\n\nexport interface ThemeMigration {\n /** The major these steps upgrade from: the new major minus one. */\n readonly from: number;\n readonly steps: readonly ThemeMigrationStep[];\n}\n\nexport interface ThemeMigrationReport {\n renamed: { from: string; to: string }[];\n removed: string[];\n mapped: { key: string; from: string; to: ThemeValue }[];\n copied: { from: string; to: string }[];\n defaulted: string[];\n}\n\nconst migrationValue = z.union([z.string(), z.number(), z.boolean()]);\nconst migrationKey = z.string().regex(SETTING_ID);\n\nexport const themeMigrationSchema = z\n .object({\n from: z.number().int().min(1),\n steps: z\n .array(\n z.discriminatedUnion(\"op\", [\n z\n .object({\n op: z.literal(\"rename\"),\n from: migrationKey,\n to: migrationKey,\n })\n .strict(),\n z.object({ op: z.literal(\"remove\"), key: migrationKey }).strict(),\n z\n .object({\n op: z.literal(\"map\"),\n key: migrationKey,\n values: z.record(z.string(), migrationValue),\n })\n .strict(),\n z\n .object({\n op: z.literal(\"copy\"),\n from: migrationKey,\n to: migrationKey,\n })\n .strict(),\n z\n .object({\n op: z.literal(\"default\"),\n key: migrationKey,\n value: migrationValue,\n })\n .strict(),\n ])\n )\n .max(500),\n })\n .strict();\n\n/**\n * Parses and validates a theme migration definition.\n *\n * @param input - the unparsed migration\n * @returns The validated migration; throws an `Error` listing the problems when it is invalid\n */\nexport function parseThemeMigration(input: unknown): ThemeMigration {\n const result = themeMigrationSchema.safeParse(input);\n if (!result.success) {\n const issues = result.error.issues\n .map(i => `${i.path.join(\".\") || \"(root)\"}: ${i.message}`)\n .join(\"; \");\n throw new Error(`Invalid theme migration: ${issues}`);\n }\n return result.data as ThemeMigration;\n}\n\nfunction present(values: Record<string, unknown>, key: string): boolean {\n return (\n Object.prototype.hasOwnProperty.call(values, key) &&\n values[key] !== undefined\n );\n}\n\n/** Runs the steps in order over a copy of `input`. */\nexport function applyThemeMigration(\n input: Record<string, unknown>,\n migration: ThemeMigration\n): { values: Record<string, unknown>; report: ThemeMigrationReport } {\n const values: Record<string, unknown> = { ...input };\n const report: ThemeMigrationReport = {\n renamed: [],\n removed: [],\n mapped: [],\n copied: [],\n defaulted: [],\n };\n for (const step of migration.steps) {\n switch (step.op) {\n case \"rename\":\n if (step.from === step.to || !present(values, step.from)) break;\n values[step.to] = values[step.from];\n delete values[step.from];\n report.renamed.push({ from: step.from, to: step.to });\n break;\n case \"remove\":\n if (!present(values, step.key)) break;\n delete values[step.key];\n report.removed.push(step.key);\n break;\n case \"map\": {\n const value = values[step.key];\n if (\n typeof value === \"string\" &&\n Object.prototype.hasOwnProperty.call(step.values, value)\n ) {\n values[step.key] = step.values[value];\n report.mapped.push({\n key: step.key,\n from: value,\n to: step.values[value],\n });\n }\n break;\n }\n case \"copy\":\n if (step.from === step.to || !present(values, step.from)) break;\n values[step.to] = values[step.from];\n report.copied.push({ from: step.from, to: step.to });\n break;\n case \"default\":\n if (present(values, step.key) && values[step.key] !== null) break;\n values[step.key] = step.value;\n report.defaulted.push(step.key);\n break;\n }\n }\n return { values, report };\n}\n","/**\n * Metafields and metaobjects: the type engine (spec 2026-10-05\n * metafields-metaobjects §5). Plain TypeScript with no imports and no I/O, so\n * it runs unchanged in the API, the dashboard and storefronts.\n *\n * ecomweb-api (src/modules/metafields/domain/metafield-engine.ts) and\n * ecomweb-dashboard (lib/metafields/engine.ts) keep VERBATIM copies of\n * everything below the marker line. To change the engine: edit it here, update\n * ENGINE_BODY_SHA256 in metafield-engine.body-hash.spec.ts, then re-copy the\n * body into both repos with the new hash in their headers.\n */\n// The body below is a verbatim, hash-checked copy, so lint exceptions live here:\n// UNSAFE_URL_CHARS matches control characters on purpose, to reject them in URLs.\n/* eslint-disable no-control-regex */\n// @engine-body\n\n// ─── Vocabulary ─────────────────────────────────────────────────\n\nexport const METAFIELD_OWNER_TYPES = [\n \"product\",\n \"variant\",\n \"collection\",\n \"customer\",\n \"order\",\n \"page\",\n \"blog_post\",\n \"location\",\n \"shop\",\n] as const;\nexport type MetafieldOwnerType = (typeof METAFIELD_OWNER_TYPES)[number];\n\nexport const METAFIELD_BASE_TYPES = [\n \"single_line_text\",\n \"multi_line_text\",\n \"rich_text\",\n \"email\",\n \"integer\",\n \"decimal\",\n \"date\",\n \"date_time\",\n \"url\",\n \"link\",\n \"weight\",\n \"volume\",\n \"dimension\",\n \"boolean\",\n \"color\",\n \"rating\",\n \"money\",\n \"language\",\n \"json\",\n \"file\",\n \"image\",\n \"video\",\n \"product\",\n \"variant\",\n \"collection\",\n \"page\",\n \"blog_post\",\n \"customer\",\n \"order\",\n \"metaobject_reference\",\n \"mixed_reference\",\n] as const;\nexport type MetafieldBaseType = (typeof METAFIELD_BASE_TYPES)[number];\nexport type MetafieldListType = `list.${MetafieldBaseType}`;\nexport type MetafieldType = MetafieldBaseType | MetafieldListType;\n\nconst BASE_TYPE_SET: ReadonlySet<string> = new Set(METAFIELD_BASE_TYPES);\n\nexport function isMetafieldType(value: unknown): value is MetafieldType {\n if (typeof value !== \"string\") return false;\n const base = value.startsWith(\"list.\") ? value.slice(5) : value;\n return BASE_TYPE_SET.has(base);\n}\n\nexport function isListType(type: MetafieldType): type is MetafieldListType {\n return type.startsWith(\"list.\");\n}\n\nexport function baseTypeOf(type: MetafieldType): MetafieldBaseType {\n return (isListType(type) ? type.slice(5) : type) as MetafieldBaseType;\n}\n\nexport type MetafieldTypeGroup =\n | \"text\"\n | \"media\"\n | \"reference\"\n | \"link\"\n | \"date_time\"\n | \"number\"\n | \"measurement\"\n | \"other\"\n | \"advanced\";\n\n/** Type picker groups in display order (spec §7.2). Labels are the consumer's. */\nexport const METAFIELD_TYPE_GROUPS: readonly {\n readonly group: MetafieldTypeGroup;\n readonly types: readonly MetafieldBaseType[];\n}[] = [\n {\n group: \"text\",\n types: [\"single_line_text\", \"multi_line_text\", \"rich_text\", \"email\"],\n },\n { group: \"media\", types: [\"file\", \"image\", \"video\"] },\n {\n group: \"reference\",\n types: [\n \"blog_post\",\n \"collection\",\n \"customer\",\n \"metaobject_reference\",\n \"order\",\n \"page\",\n \"product\",\n \"variant\",\n ],\n },\n { group: \"link\", types: [\"link\", \"url\"] },\n { group: \"date_time\", types: [\"date\", \"date_time\"] },\n { group: \"number\", types: [\"integer\", \"decimal\", \"rating\", \"money\"] },\n { group: \"measurement\", types: [\"weight\", \"volume\", \"dimension\"] },\n { group: \"other\", types: [\"boolean\", \"color\", \"language\"] },\n { group: \"advanced\", types: [\"json\", \"mixed_reference\"] },\n];\n\nexport const RESOURCE_REFERENCE_TYPES = [\n \"product\",\n \"variant\",\n \"collection\",\n \"page\",\n \"blog_post\",\n \"customer\",\n \"order\",\n] as const;\nexport const METAOBJECT_REFERENCE_TYPES = [\n \"metaobject_reference\",\n \"mixed_reference\",\n] as const;\nexport const MEDIA_TYPES = [\"file\", \"image\", \"video\"] as const;\n/** Never resolved outside the admin (spec §6.5). */\nexport const PRIVATE_REFERENCE_TYPES = [\"customer\", \"order\"] as const;\n\nexport const METAFIELD_LIMITS = {\n definitions_per_owner_type: 100,\n pinned_per_owner_type: 20,\n metaobject_definitions: 100,\n fields_per_metaobject: 40,\n filter_keys: 5,\n value_bytes: 65_536,\n list_items: 128,\n choices: 128,\n allowed_domains: 20,\n regex_length: 200,\n regex_value_length: 500,\n single_line_text_length: 5_000,\n multi_line_text_length: 65_000,\n link_text_length: 255,\n email_length: 254,\n name_length: 255,\n description_length: 5_000,\n mixed_reference_definitions_min: 2,\n mixed_reference_definitions_max: 10,\n} as const;\n\n// ─── Issues and results ─────────────────────────────────────────\n\nexport type MetafieldIssueCode =\n | \"blank\"\n | \"required\"\n | \"unknown_key\"\n | \"duplicate\"\n | \"immutable\"\n | \"not_allowed\"\n | \"invalid_type\"\n | \"invalid_format\"\n | \"too_short\"\n | \"too_long\"\n | \"too_small\"\n | \"too_big\"\n | \"too_large\"\n | \"pattern_mismatch\"\n | \"not_a_choice\"\n | \"precision_exceeded\"\n | \"domain_not_allowed\"\n | \"invalid_unit\"\n | \"scale_mismatch\"\n | \"currency_mismatch\"\n | \"list_too_short\"\n | \"list_too_long\"\n | \"invalid_node\"\n | \"unsafe_url\"\n | \"invalid_validation\"\n | \"unsafe_regex\";\n\n/** `path` is relative to the validated input: \"\", \"[2]\", \"[2].amount\", \"fields[0].type\". */\nexport interface MetafieldIssue {\n path: string;\n code: MetafieldIssueCode;\n message: string;\n}\n\n/** `errors` and `value` are optional-undefined on the other arm so both read cleanly without strictNullChecks. */\nexport type EngineResult<T> =\n | { ok: true; value: T; errors?: undefined }\n | { ok: false; errors: MetafieldIssue[]; value?: undefined };\n\nfunction issue(\n path: string,\n code: MetafieldIssueCode,\n message: string\n): MetafieldIssue {\n return { path, code, message };\n}\n\nfunction ok<T>(value: T): EngineResult<T> {\n return { ok: true, value };\n}\n\nfunction fail<T = never>(\n path: string,\n code: MetafieldIssueCode,\n message: string\n): EngineResult<T> {\n return { ok: false, errors: [issue(path, code, message)] };\n}\n\nfunction joinPath(base: string, segment: string | number): string {\n if (typeof segment === \"number\") return `${base}[${segment}]`;\n return base ? `${base}.${segment}` : segment;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasOwn(object: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(object, key);\n}\n\nfunction unknownKeys(\n object: Record<string, unknown>,\n allowed: readonly string[],\n path: string\n): MetafieldIssue[] {\n return Object.keys(object)\n .filter(key => !allowed.includes(key))\n .map(key => issue(joinPath(path, key), \"unknown_key\", `unknown key \"${key}\"`));\n}\n\nfunction codePoints(text: string): number {\n return [...text].length;\n}\n\n// ─── Value shapes and validations ───────────────────────────────\n\nexport type FileKind = \"image\" | \"video\" | \"document\";\n\nexport interface MeasurementValue {\n value: string;\n unit: string;\n}\n\nexport interface LinkValue {\n url: string;\n text: string;\n}\n\nexport interface RatingValue {\n value: string;\n scale_min: string;\n scale_max: string;\n}\n\nexport interface MoneyValue {\n amount: string;\n currency_code: string;\n}\n\n/** integer: number; decimal: decimal string; date/date_time: canonical string; measurements: MeasurementValue. */\nexport type MetafieldBound = number | string | MeasurementValue;\n\n/** Canonical validations, as validateValidations returns them (spec §5.2). */\nexport interface MetafieldValidations {\n min_length?: number;\n max_length?: number;\n regex?: string;\n choices?: string[];\n min?: MetafieldBound;\n max?: MetafieldBound;\n max_precision?: number;\n allowed_domains?: string[];\n scale_min?: string;\n scale_max?: string;\n file_types?: FileKind[];\n metaobject_definition_id?: string;\n metaobject_definition_ids?: string[];\n list_min?: number;\n list_max?: number;\n}\n\n/** Store facts a value check needs. The engine never looks anything up. */\nexport interface MetafieldContext {\n currency_code: string;\n}\n\n// ─── Keys, handles and identifiers ──────────────────────────────\n\nexport const METAFIELD_KEY_PATTERN = /^[a-z0-9_]{2,64}$/;\nexport const METAOBJECT_TYPE_PATTERN = /^[a-z0-9_-]{2,64}$/;\nexport const ENTRY_HANDLE_PATTERN = /^[a-z0-9-]{1,255}$/;\n\n/** Strips accents; NFD does not decompose đ, so it is mapped by hand. */\nfunction asciiFold(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/\\u0111/g, \"d\")\n .replace(/\\u0110/g, \"D\");\n}\n\nfunction slugify(text: string, separator: string, max: number): string {\n const edge = new RegExp(`^${separator}+|${separator}+$`, \"g\");\n return asciiFold(text)\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, separator)\n .replace(edge, \"\")\n .slice(0, max)\n .replace(edge, \"\");\n}\n\n/** \"Đánh giá khách hàng\" → \"danh_gia_khach_hang\". \"\" when nothing usable remains. */\nexport function toMetafieldKey(text: string): string {\n return slugify(text, \"_\", 64);\n}\n\n/** \"Lan Anh – Hà Nội\" → \"lan-anh-ha-noi\". \"\" when nothing usable remains. */\nexport function toEntryHandle(text: string): string {\n const handle = slugify(text, \"-\", 255);\n return RESERVED_KEYS.includes(handle) ? \"\" : handle;\n}\n\n/** True for a well-formed entry handle that is not a reserved name. */\nexport function isValidEntryHandle(handle: string): boolean {\n return ENTRY_HANDLE_PATTERN.test(handle) && !RESERVED_KEYS.includes(handle);\n}\n\nexport function metafieldIdentifier(namespace: string, key: string): string {\n return `${namespace}.${key}`;\n}\n\n/** Names that collide with Object.prototype members; never valid as a key. */\nconst RESERVED_KEYS: readonly string[] = [\"__proto__\", \"constructor\", \"prototype\"];\n\nexport function parseMetafieldIdentifier(\n identifier: string\n): { namespace: string; key: string } | null {\n const parts = identifier.split(\".\");\n if (parts.length !== 2) return null;\n const [namespace, key] = parts;\n if (!METAFIELD_KEY_PATTERN.test(namespace) || !METAFIELD_KEY_PATTERN.test(key)) {\n return null;\n }\n if (RESERVED_KEYS.includes(namespace) || RESERVED_KEYS.includes(key)) return null;\n return { namespace, key };\n}\n\n// ─── Values: scalars ────────────────────────────────────────────\n\ntype Checker = (\n value: unknown,\n validations: MetafieldValidations,\n ctx: MetafieldContext,\n path: string\n) => EngineResult<unknown>;\n\nfunction matchesPattern(pattern: string, text: string): boolean {\n try {\n return new RegExp(\"^(?:\" + pattern + \")$\", \"u\").test(text);\n } catch {\n return false;\n }\n}\n\nfunction textChecker(limit: number, singleLine: boolean): Checker {\n return (value, v, _ctx, path) => {\n if (typeof value !== \"string\") return fail(path, \"invalid_type\", \"must be text\");\n if (singleLine && /[\\r\\n]/.test(value)) {\n return fail(path, \"invalid_format\", \"must be a single line\");\n }\n const length = codePoints(value);\n const cap = v.regex !== undefined ? Math.min(limit, METAFIELD_LIMITS.regex_value_length) : limit;\n const max = Math.min(cap, v.max_length ?? cap);\n if (length > max) return fail(path, \"too_long\", `must be at most ${max} characters`);\n if (v.min_length !== undefined && length < v.min_length) {\n return fail(path, \"too_short\", `must be at least ${v.min_length} characters`);\n }\n if (v.regex !== undefined && !matchesPattern(v.regex, value)) {\n return fail(path, \"pattern_mismatch\", \"does not match the required pattern\");\n }\n if (v.choices !== undefined && !v.choices.includes(value)) {\n return fail(path, \"not_a_choice\", `must be one of: ${v.choices.join(\", \")}`);\n }\n return ok(value);\n };\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst checkEmail: Checker = (value, _v, _ctx, path) => {\n if (typeof value !== \"string\") return fail(path, \"invalid_type\", \"must be text\");\n const email = value.trim().toLowerCase();\n if (email.length > METAFIELD_LIMITS.email_length || !EMAIL.test(email)) {\n return fail(path, \"invalid_format\", \"must be an email address\");\n }\n return ok(email);\n};\n\nconst checkInteger: Checker = (value, v, _ctx, path) => {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value)) {\n return fail(path, \"invalid_type\", \"must be a whole number\");\n }\n if (typeof v.min === \"number\" && value < v.min) {\n return fail(path, \"too_small\", `must be at least ${v.min}`);\n }\n if (typeof v.max === \"number\" && value > v.max) {\n return fail(path, \"too_big\", `must be at most ${v.max}`);\n }\n return ok(value === 0 ? 0 : value);\n};\n\nconst DECIMAL_INPUT = /^[+-]?\\d+(\\.\\d+)?$/;\n\n/**\n * A canonical decimal string (\"7.5\", \"-0.25\", \"0\"), or null when the input is not a plain decimal.\n * Numbers JS prints in exponent form (1e-7, 1e21) are rejected; send them as decimal strings.\n */\nexport function normalizeDecimal(input: unknown): string | null {\n let text: string;\n if (typeof input === \"number\") {\n if (!Number.isFinite(input)) return null;\n text = String(input);\n } else if (typeof input === \"string\") {\n text = input.trim();\n } else {\n return null;\n }\n if (text.length > 40 || !DECIMAL_INPUT.test(text)) return null;\n const negative = text.startsWith(\"-\");\n if (text[0] === \"-\" || text[0] === \"+\") text = text.slice(1);\n const [whole, fraction = \"\"] = text.split(\".\");\n const integer = whole.replace(/^0+(?=\\d)/, \"\");\n const decimals = fraction.replace(/0+$/, \"\");\n const magnitude = decimals ? `${integer}.${decimals}` : integer;\n return magnitude === \"0\" ? \"0\" : `${negative ? \"-\" : \"\"}${magnitude}`;\n}\n\n/** Compares two canonical decimal strings exactly. */\nexport function compareDecimal(a: string, b: string): -1 | 0 | 1 {\n const aNegative = a.startsWith(\"-\");\n const bNegative = b.startsWith(\"-\");\n if (aNegative !== bNegative) return aNegative ? -1 : 1;\n const sign = aNegative ? -1 : 1;\n const [aWhole, aFraction = \"\"] = (aNegative ? a.slice(1) : a).split(\".\");\n const [bWhole, bFraction = \"\"] = (bNegative ? b.slice(1) : b).split(\".\");\n let order: number;\n if (aWhole.length !== bWhole.length) {\n order = aWhole.length > bWhole.length ? 1 : -1;\n } else if (aWhole !== bWhole) {\n order = aWhole > bWhole ? 1 : -1;\n } else {\n const width = Math.max(aFraction.length, bFraction.length);\n const aPadded = aFraction.padEnd(width, \"0\");\n const bPadded = bFraction.padEnd(width, \"0\");\n order = aPadded === bPadded ? 0 : aPadded > bPadded ? 1 : -1;\n }\n // order * sign would give -0 for two equal negatives; return a clean 0.\n return order === 0 ? 0 : ((order * sign) as -1 | 1);\n}\n\nconst checkDecimal: Checker = (value, v, _ctx, path) => {\n const decimal = normalizeDecimal(value);\n if (decimal === null) return fail(path, \"invalid_type\", \"must be a decimal number\");\n const fraction = decimal.split(\".\")[1] ?? \"\";\n if (v.max_precision !== undefined && fraction.length > v.max_precision) {\n return fail(path, \"precision_exceeded\", `must have at most ${v.max_precision} decimal places`);\n }\n if (typeof v.min === \"string\" && compareDecimal(decimal, v.min) < 0) {\n return fail(path, \"too_small\", `must be at least ${v.min}`);\n }\n if (typeof v.max === \"string\" && compareDecimal(decimal, v.max) > 0) {\n return fail(path, \"too_big\", `must be at most ${v.max}`);\n }\n return ok(decimal);\n};\n\nconst checkBoolean: Checker = (value, _v, _ctx, path) =>\n typeof value === \"boolean\" ? ok(value) : fail(path, \"invalid_type\", \"must be true or false\");\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\n\nconst checkColor: Checker = (value, _v, _ctx, path) =>\n typeof value === \"string\" && COLOR.test(value)\n ? ok(value.toLowerCase())\n : fail(path, \"invalid_format\", \"must be a hex color such as #1a2b3c\");\n\n/** setUTCFullYear, unlike Date.UTC, does not map years 0–99 to 1900–1999. */\nfunction isCalendarDate(year: number, month: number, day: number): boolean {\n const date = new Date(0);\n date.setUTCFullYear(year, month - 1, day);\n return (\n date.getUTCFullYear() === year &&\n date.getUTCMonth() === month - 1 &&\n date.getUTCDate() === day\n );\n}\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** \"YYYY-MM-DD\" when the input is a real calendar date, else null. */\nexport function normalizeDate(input: unknown): string | null {\n if (typeof input !== \"string\") return null;\n const match = DATE.exec(input);\n if (!match || !isCalendarDate(+match[1], +match[2], +match[3])) return null;\n return input;\n}\n\nconst DATE_TIME =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d{1,3})?)?(Z|[+-](\\d{2}):(\\d{2}))$/;\n\n/** \"YYYY-MM-DDTHH:mm:ssZ\" in UTC, or null. Milliseconds are dropped. */\nexport function normalizeDateTime(input: unknown): string | null {\n if (typeof input !== \"string\") return null;\n const match = DATE_TIME.exec(input);\n if (!match || !isCalendarDate(+match[1], +match[2], +match[3])) return null;\n if (+match[4] > 23 || +match[5] > 59 || +(match[6] ?? \"0\") > 59) return null;\n if (match[8] !== undefined && (+match[8] > 23 || +match[9] > 59)) return null;\n const ms = Date.parse(input);\n if (Number.isNaN(ms)) return null;\n const iso = new Date(ms).toISOString();\n return /^\\d{4}-/.test(iso) ? `${iso.slice(0, 19)}Z` : null;\n}\n\nfunction dateChecker(normalize: (input: unknown) => string | null, format: string): Checker {\n return (value, v, _ctx, path) => {\n const normalized = normalize(value);\n if (normalized === null) return fail(path, \"invalid_format\", `must be ${format}`);\n if (typeof v.min === \"string\" && normalized < v.min) {\n return fail(path, \"too_small\", `must be on or after ${v.min}`);\n }\n if (typeof v.max === \"string\" && normalized > v.max) {\n return fail(path, \"too_big\", `must be on or before ${v.max}`);\n }\n return ok(normalized);\n };\n}\n\nconst MAX_URL_LENGTH = 2048;\n\n/** Control characters and the quote, angle, backtick and backslash characters never belong in a stored URL. */\nconst UNSAFE_URL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f\"<>`\\\\]/;\n\nfunction parseHttpUrl(value: unknown): URL | null {\n if (\n typeof value !== \"string\" ||\n value.length > MAX_URL_LENGTH ||\n /\\s/.test(value) ||\n UNSAFE_URL_CHARS.test(value)\n ) {\n return null;\n }\n try {\n const url = new URL(value);\n return url.protocol === \"http:\" || url.protocol === \"https:\" ? url : null;\n } catch {\n return null;\n }\n}\n\nfunction hostAllowed(url: URL, domains: readonly string[] | undefined): boolean {\n if (!domains) return true;\n const host = url.hostname.toLowerCase();\n return domains.some(domain => host === domain || host.endsWith(`.${domain}`));\n}\n\nconst checkUrl: Checker = (value, v, _ctx, path) => {\n const url = parseHttpUrl(value);\n if (!url) return fail(path, \"invalid_format\", \"must be an http(s) URL\");\n if (!hostAllowed(url, v.allowed_domains)) {\n return fail(path, \"domain_not_allowed\", `must be on ${(v.allowed_domains ?? []).join(\", \")}`);\n }\n return ok(value as string);\n};\n\nconst checkLink: Checker = (value, v, ctx, path) => {\n if (!isPlainObject(value)) {\n return fail(path, \"invalid_type\", \"must be an object with url and text\");\n }\n const extra = unknownKeys(value, [\"url\", \"text\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const url = checkUrl(value.url, v, ctx, joinPath(path, \"url\"));\n if (!url.ok) return url;\n const text = value.text ?? \"\";\n if (typeof text !== \"string\") return fail(joinPath(path, \"text\"), \"invalid_type\", \"must be text\");\n if (codePoints(text) > METAFIELD_LIMITS.link_text_length) {\n return fail(\n joinPath(path, \"text\"),\n \"too_long\",\n `must be at most ${METAFIELD_LIMITS.link_text_length} characters`\n );\n }\n return ok({ url: url.value as string, text });\n};\n\nconst LANGUAGE = /^([a-zA-Z]{2,3})(?:-([a-zA-Z]{4}))?(?:-([a-zA-Z]{2}|\\d{3}))?$/;\n\nconst checkLanguage: Checker = (value, _v, _ctx, path) => {\n const match = typeof value === \"string\" ? LANGUAGE.exec(value) : null;\n if (!match) {\n return fail(path, \"invalid_format\", \"must be a language tag such as vi or en-US\");\n }\n const script = match[2]\n ? match[2][0].toUpperCase() + match[2].slice(1).toLowerCase()\n : undefined;\n return ok([match[1].toLowerCase(), script, match[3]?.toUpperCase()].filter(Boolean).join(\"-\"));\n};\n\nconst checkJson: Checker = (value, _v, _ctx, path) => {\n let text: string | undefined;\n let nonFinite = false;\n try {\n text = JSON.stringify(value, (_key, item) => {\n if (typeof item === \"number\" && !Number.isFinite(item)) nonFinite = true;\n return item;\n });\n } catch {\n text = undefined;\n }\n if (nonFinite) return fail(path, \"invalid_format\", \"must not contain NaN or Infinity\");\n return text === undefined ? fail(path, \"invalid_type\", \"must be JSON\") : ok(JSON.parse(text));\n};\n\n// ─── Values: rich text ──────────────────────────────────────────\n\nexport interface RichTextText {\n type: \"text\";\n value: string;\n bold?: boolean;\n italic?: boolean;\n}\n\nexport interface RichTextLink {\n type: \"link\";\n url: string;\n title?: string;\n children: RichTextText[];\n}\n\nexport type RichTextInline = RichTextText | RichTextLink;\n\nexport interface RichTextParagraph {\n type: \"paragraph\";\n children: RichTextInline[];\n}\n\nexport interface RichTextHeading {\n type: \"heading\";\n level: 1 | 2 | 3 | 4 | 5 | 6;\n children: RichTextInline[];\n}\n\nexport interface RichTextListItem {\n type: \"list-item\";\n children: RichTextInline[];\n}\n\nexport interface RichTextList {\n type: \"list\";\n listType: \"ordered\" | \"unordered\";\n children: RichTextListItem[];\n}\n\nexport type RichTextBlock = RichTextParagraph | RichTextHeading | RichTextList;\n\nexport interface RichTextRoot {\n type: \"root\";\n children: RichTextBlock[];\n}\n\nexport type RichTextNode =\n | RichTextRoot\n | RichTextBlock\n | RichTextListItem\n | RichTextInline;\n\n/** A malformed document reports its first 100 problems, not thousands. */\nconst MAX_RICH_ERRORS = 100;\n\nconst MAILTO = /^mailto:[^\\s@?&#,]+@[^\\s@?&#,]+$/i;\n\nfunction richChildren<T>(\n children: unknown,\n path: string,\n errors: MetafieldIssue[],\n each: (child: unknown, path: string) => T | null\n): T[] {\n if (!Array.isArray(children)) {\n errors.push(issue(path, \"invalid_type\", \"must be a list of nodes\"));\n return [];\n }\n const out: T[] = [];\n for (let index = 0; index < children.length; index++) {\n if (errors.length >= MAX_RICH_ERRORS) break;\n const node = each(children[index], joinPath(path, index));\n if (node) out.push(node);\n }\n return out;\n}\n\nfunction richText(node: Record<string, unknown>, path: string, errors: MetafieldIssue[]): RichTextText | null {\n errors.push(...unknownKeys(node, [\"type\", \"value\", \"bold\", \"italic\"], path));\n if (typeof node.value !== \"string\") {\n errors.push(issue(joinPath(path, \"value\"), \"invalid_type\", \"must be text\"));\n return null;\n }\n for (const mark of [\"bold\", \"italic\"] as const) {\n if (node[mark] !== undefined && typeof node[mark] !== \"boolean\") {\n errors.push(issue(joinPath(path, mark), \"invalid_type\", \"must be true or false\"));\n }\n }\n const out: RichTextText = { type: \"text\", value: node.value };\n if (node.bold === true) out.bold = true;\n if (node.italic === true) out.italic = true;\n return out;\n}\n\nfunction richInline(\n node: unknown,\n path: string,\n errors: MetafieldIssue[]\n): RichTextInline | null {\n if (!isPlainObject(node)) {\n errors.push(issue(path, \"invalid_node\", \"must be a text or link node\"));\n return null;\n }\n if (node.type === \"text\") return richText(node, path, errors);\n if (node.type === \"link\") {\n errors.push(...unknownKeys(node, [\"type\", \"url\", \"title\", \"children\"], path));\n const url = typeof node.url === \"string\" ? node.url : \"\";\n if (!parseHttpUrl(url) && !(url.length <= MAX_URL_LENGTH && MAILTO.test(url) && !UNSAFE_URL_CHARS.test(url))) {\n errors.push(issue(joinPath(path, \"url\"), \"unsafe_url\", \"must be an http(s) or mailto link\"));\n }\n if (node.title !== undefined && typeof node.title !== \"string\") {\n errors.push(issue(joinPath(path, \"title\"), \"invalid_type\", \"must be text\"));\n }\n const children = richChildren(node.children, joinPath(path, \"children\"), errors, (child, at) => {\n if (isPlainObject(child) && child.type === \"text\") return richText(child, at, errors);\n errors.push(issue(joinPath(at, \"type\"), \"invalid_node\", \"a link may only contain text\"));\n return null;\n });\n const out: RichTextLink = { type: \"link\", url, children };\n if (typeof node.title === \"string\") out.title = node.title;\n return out;\n }\n errors.push(\n issue(joinPath(path, \"type\"), \"invalid_node\", `unexpected node type ${JSON.stringify(String(node.type).slice(0, 40))}`)\n );\n return null;\n}\n\nfunction richBlock(node: unknown, path: string, errors: MetafieldIssue[]): RichTextBlock | null {\n if (!isPlainObject(node)) {\n errors.push(issue(path, \"invalid_node\", \"must be a paragraph, heading or list node\"));\n return null;\n }\n const inline = (child: unknown, at: string) => richInline(child, at, errors);\n const children = (at: string, from: unknown) => richChildren(from, joinPath(at, \"children\"), errors, inline);\n switch (node.type) {\n case \"paragraph\":\n errors.push(...unknownKeys(node, [\"type\", \"children\"], path));\n return { type: \"paragraph\", children: children(path, node.children) };\n case \"heading\": {\n errors.push(...unknownKeys(node, [\"type\", \"level\", \"children\"], path));\n const level = node.level;\n if (typeof level !== \"number\" || !Number.isInteger(level) || level < 1 || level > 6) {\n errors.push(issue(joinPath(path, \"level\"), \"invalid_format\", \"must be 1 to 6\"));\n }\n return { type: \"heading\", level: level as RichTextHeading[\"level\"], children: children(path, node.children) };\n }\n case \"list\": {\n errors.push(...unknownKeys(node, [\"type\", \"listType\", \"children\"], path));\n if (node.listType !== \"ordered\" && node.listType !== \"unordered\") {\n errors.push(issue(joinPath(path, \"listType\"), \"invalid_format\", \"must be ordered or unordered\"));\n }\n const items = richChildren(node.children, joinPath(path, \"children\"), errors, (child, at) => {\n if (!isPlainObject(child) || child.type !== \"list-item\") {\n errors.push(issue(at, \"invalid_node\", \"must be a list-item node\"));\n return null;\n }\n errors.push(...unknownKeys(child, [\"type\", \"children\"], at));\n return { type: \"list-item\" as const, children: children(at, child.children) };\n });\n return { type: \"list\", listType: node.listType as RichTextList[\"listType\"], children: items };\n }\n default:\n errors.push(\n issue(joinPath(path, \"type\"), \"invalid_node\", `unexpected node type ${JSON.stringify(String(node.type).slice(0, 40))}`)\n );\n return null;\n }\n}\n\nconst MAX_RICH_TOP_NODES = 2000;\n\n/** Validates a rich-text tree (spec §5.3). There is no HTML anywhere in it. */\nexport function validateRichText(input: unknown, path = \"\"): EngineResult<RichTextRoot> {\n if (!isPlainObject(input) || input.type !== \"root\") {\n return fail(path, \"invalid_node\", \"must be a rich-text root node\");\n }\n if (Array.isArray(input.children) && input.children.length > MAX_RICH_TOP_NODES) {\n return fail(path, \"too_large\", \"has too many nodes\");\n }\n const errors = unknownKeys(input, [\"type\", \"children\"], path);\n const children = richChildren(input.children, joinPath(path, \"children\"), errors, (child, at) =>\n richBlock(child, at, errors)\n );\n return errors.length\n ? { ok: false, errors: errors.slice(0, MAX_RICH_ERRORS) }\n : ok({ type: \"root\", children });\n}\n\n/** Characters of text in the tree, links and list items included. */\nexport function richTextLength(root: RichTextRoot): number {\n let count = 0;\n const visit = (node: RichTextInline) => {\n if (node.type === \"text\") count += codePoints(node.value);\n else node.children.forEach(visit);\n };\n for (const block of root.children) {\n if (block.type === \"list\") block.children.forEach(item => item.children.forEach(visit));\n else block.children.forEach(visit);\n }\n return count;\n}\n\nconst checkRichText: Checker = (value, v, _ctx, path) => {\n const tree = validateRichText(value, path);\n if (!tree.ok) return tree;\n if (v.max_length !== undefined && richTextLength(tree.value) > v.max_length) {\n return fail(path, \"too_long\", `must be at most ${v.max_length} characters`);\n }\n return tree;\n};\n\n// ─── Values: measurements, money, media, references ─────────────\n\n/** Conversion factors to the first unit of each type (g, ml, mm). */\nexport const MEASUREMENT_UNITS = {\n weight: { g: 1, kg: 1000, oz: 28.349523125, lb: 453.59237 },\n volume: {\n ml: 1,\n cl: 10,\n l: 1000,\n m3: 1_000_000,\n fl_oz: 29.5735295625,\n pt: 473.176473,\n qt: 946.352946,\n gal: 3785.411784,\n },\n dimension: { mm: 1, cm: 10, m: 1000, in: 25.4, ft: 304.8, yd: 914.4 },\n} as const;\nexport type MeasurementType = keyof typeof MEASUREMENT_UNITS;\n\n/** The value in g, ml or mm, or null for an unknown unit. For bounds only: it uses floats. */\nexport function measurementInBaseUnit(\n measurement: MeasurementValue,\n type: MeasurementType\n): number | null {\n const units = MEASUREMENT_UNITS[type] as Record<string, number>;\n return hasOwn(units, measurement.unit) ? Number(measurement.value) * units[measurement.unit] : null;\n}\n\nfunction measurementChecker(type: MeasurementType): Checker {\n const unitList = Object.keys(MEASUREMENT_UNITS[type]).join(\", \");\n return (value, v, _ctx, path) => {\n if (!isPlainObject(value)) return fail(path, \"invalid_type\", \"must be an object with value and unit\");\n const extra = unknownKeys(value, [\"value\", \"unit\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const amount = normalizeDecimal(value.value);\n if (amount === null) return fail(joinPath(path, \"value\"), \"invalid_type\", \"must be a decimal number\");\n if (typeof value.unit !== \"string\" || !hasOwn(MEASUREMENT_UNITS[type], value.unit)) {\n return fail(joinPath(path, \"unit\"), \"invalid_unit\", `must be one of: ${unitList}`);\n }\n const measurement = { value: amount, unit: value.unit };\n const base = measurementInBaseUnit(measurement, type) as number;\n if (typeof v.min === \"object\" && v.min !== null) {\n const min = measurementInBaseUnit(v.min, type);\n if (min !== null && base < min) {\n return fail(path, \"too_small\", `must be at least ${v.min.value} ${v.min.unit}`);\n }\n }\n if (typeof v.max === \"object\" && v.max !== null) {\n const max = measurementInBaseUnit(v.max, type);\n if (max !== null && base > max) {\n return fail(path, \"too_big\", `must be at most ${v.max.value} ${v.max.unit}`);\n }\n }\n return ok(measurement);\n };\n}\n\nconst checkRating: Checker = (value, v, _ctx, path) => {\n if (!isPlainObject(value)) {\n return fail(path, \"invalid_type\", \"must be an object with value, scale_min and scale_max\");\n }\n const extra = unknownKeys(value, [\"value\", \"scale_min\", \"scale_max\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const parts: Record<\"value\" | \"scale_min\" | \"scale_max\", string> = { value: \"\", scale_min: \"\", scale_max: \"\" };\n for (const key of [\"value\", \"scale_min\", \"scale_max\"] as const) {\n const decimal = normalizeDecimal(value[key]);\n if (decimal === null) return fail(joinPath(path, key), \"invalid_type\", \"must be a decimal number\");\n parts[key] = decimal;\n }\n if (\n (v.scale_min !== undefined && compareDecimal(parts.scale_min, v.scale_min) !== 0) ||\n (v.scale_max !== undefined && compareDecimal(parts.scale_max, v.scale_max) !== 0)\n ) {\n return fail(path, \"scale_mismatch\", `must use the scale ${v.scale_min} to ${v.scale_max}`);\n }\n if (compareDecimal(parts.value, parts.scale_min) < 0) {\n return fail(joinPath(path, \"value\"), \"too_small\", `must be at least ${parts.scale_min}`);\n }\n if (compareDecimal(parts.value, parts.scale_max) > 0) {\n return fail(joinPath(path, \"value\"), \"too_big\", `must be at most ${parts.scale_max}`);\n }\n return ok(parts);\n};\n\nconst checkMoney: Checker = (value, _v, ctx, path) => {\n if (!isPlainObject(value)) return fail(path, \"invalid_type\", \"must be an object with amount and currency_code\");\n const extra = unknownKeys(value, [\"amount\", \"currency_code\"], path);\n if (extra.length) return { ok: false, errors: extra };\n const amount = normalizeDecimal(value.amount);\n if (amount === null) return fail(joinPath(path, \"amount\"), \"invalid_type\", \"must be a decimal number\");\n const currency = typeof value.currency_code === \"string\" ? value.currency_code.toUpperCase() : \"\";\n const expected = ctx.currency_code.toUpperCase();\n if (currency !== expected) {\n return fail(joinPath(path, \"currency_code\"), \"currency_mismatch\", `must be ${expected}`);\n }\n return ok({ amount, currency_code: currency });\n};\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst checkAsset: Checker = (value, _v, _ctx, path) =>\n typeof value === \"string\" && UUID.test(value)\n ? ok(value.toLowerCase())\n : fail(path, \"invalid_format\", \"must be an asset id\");\n\n/** File kinds a media value may point at; null means any kind (or not a media type). */\nexport function allowedFileKinds(\n type: MetafieldType,\n validations: MetafieldValidations\n): readonly FileKind[] | null {\n switch (baseTypeOf(type)) {\n case \"image\":\n return [\"image\"];\n case \"video\":\n return [\"video\"];\n case \"file\":\n return validations.file_types ?? null;\n default:\n return null;\n }\n}\n\nconst ID = /^[1-9]\\d{0,18}$/;\nconst MAX_BIGINT = \"9223372036854775807\";\n\n/** A positive bigint id as a string, or null. */\nexport function normalizeId(input: unknown): string | null {\n if (typeof input === \"number\") {\n return Number.isSafeInteger(input) && input > 0 ? String(input) : null;\n }\n if (typeof input !== \"string\" || !ID.test(input)) return null;\n if (input.length === MAX_BIGINT.length && input > MAX_BIGINT) return null;\n return input;\n}\n\nconst checkId: Checker = (value, _v, _ctx, path) => {\n const id = normalizeId(value);\n return id === null ? fail(path, \"invalid_format\", \"must be a record id\") : ok(id);\n};\n\n// ─── Values: dispatch ───────────────────────────────────────────\n// Keep this section last: CHECKERS reads the checker constants above it.\n\nconst CHECKERS: Record<MetafieldBaseType, Checker> = {\n single_line_text: textChecker(METAFIELD_LIMITS.single_line_text_length, true),\n multi_line_text: textChecker(METAFIELD_LIMITS.multi_line_text_length, false),\n rich_text: checkRichText,\n email: checkEmail,\n integer: checkInteger,\n decimal: checkDecimal,\n date: dateChecker(normalizeDate, \"a date (YYYY-MM-DD)\"),\n date_time: dateChecker(normalizeDateTime, \"a date and time (YYYY-MM-DDTHH:mm:ssZ)\"),\n url: checkUrl,\n link: checkLink,\n weight: measurementChecker(\"weight\"),\n volume: measurementChecker(\"volume\"),\n dimension: measurementChecker(\"dimension\"),\n boolean: checkBoolean,\n color: checkColor,\n rating: checkRating,\n money: checkMoney,\n language: checkLanguage,\n json: checkJson,\n file: checkAsset,\n image: checkAsset,\n video: checkAsset,\n product: checkId,\n variant: checkId,\n collection: checkId,\n page: checkId,\n blog_post: checkId,\n customer: checkId,\n order: checkId,\n metaobject_reference: checkId,\n mixed_reference: checkId,\n};\n\n/**\n * Values a caller without a type should treat as \"clear this field\": null,\n * undefined, \"\" and []. Use isBlankValueFor when the field's type is known.\n */\nexport function isBlankValue(value: unknown): boolean {\n return (\n value === null ||\n value === undefined ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0)\n );\n}\n\nconst TEXT_BASE_TYPES: readonly MetafieldBaseType[] = [\"single_line_text\", \"multi_line_text\", \"email\", \"url\"];\n\n/** One value (a list item, for list types) of the given base type. */\nfunction isBlankScalar(base: MetafieldBaseType, value: unknown): boolean {\n if (isBlankValue(value)) return true;\n if (typeof value === \"string\") return TEXT_BASE_TYPES.includes(base) && value.trim() === \"\";\n return (\n base === \"rich_text\" &&\n isPlainObject(value) &&\n value.type === \"root\" &&\n Array.isArray(value.children) &&\n value.children.length === 0\n );\n}\n\n/**\n * Type-aware blank check: whitespace-only text is blank for text types, an\n * empty root is blank for rich_text, and neither is blank for json.\n */\nexport function isBlankValueFor(type: MetafieldType, value: unknown): boolean {\n if (!isMetafieldType(type)) return isBlankValue(value);\n if (isListType(type)) return isBlankValue(value);\n return isBlankScalar(baseTypeOf(type), value);\n}\n\nfunction checkList(\n base: MetafieldBaseType,\n checker: Checker,\n value: unknown,\n v: MetafieldValidations,\n ctx: MetafieldContext,\n path: string\n): EngineResult<unknown[]> {\n if (!Array.isArray(value)) return fail(path, \"invalid_type\", \"must be a list\");\n const max = Math.min(METAFIELD_LIMITS.list_items, v.list_max ?? METAFIELD_LIMITS.list_items);\n if (value.length > max) return fail(path, \"list_too_long\", `must have at most ${max} items`);\n if (v.list_min !== undefined && value.length < v.list_min) {\n return fail(path, \"list_too_short\", `must have at least ${v.list_min} items`);\n }\n const items: unknown[] = [];\n const errors: MetafieldIssue[] = [];\n for (let index = 0; index < value.length; index++) {\n const item: unknown = value[index];\n const at = joinPath(path, index);\n const result = isBlankScalar(base, item) ? fail(at, \"blank\", \"is empty\") : checker(item, v, ctx, at);\n if (result.ok) items.push(result.value);\n else errors.push(...result.errors);\n }\n return errors.length ? { ok: false, errors } : ok(items);\n}\n\n/** Postgres jsonb rejects NUL and lone surrogates; JSON.stringify escapes both as \\\\uXXXX. */\nfunction isStorableJson(json: string): boolean {\n for (const match of json.matchAll(/\\\\(?:u([0-9a-f]{4})|[^u])/g)) {\n const code = match[1] === undefined ? -1 : parseInt(match[1], 16);\n if (code === 0 || (code >= 0xd800 && code <= 0xdfff)) return false;\n }\n return true;\n}\n\nfunction byteLength(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\n/**\n * Validates one value against its type and its definition's (already\n * validated) validations, returning the canonical value. Blank values fail\n * with \"blank\": callers decide whether blank means \"delete\" or \"required\".\n */\nexport function validateMetafieldValue(\n type: MetafieldType,\n validations: MetafieldValidations,\n value: unknown,\n ctx: MetafieldContext,\n path = \"\"\n): EngineResult<unknown> {\n if (!isMetafieldType(type)) return fail(path, \"invalid_type\", \"is not a metafield type\");\n if (!isPlainObject(validations)) validations = {};\n if (isBlankValueFor(type, value)) return fail(path, \"blank\", \"is empty; send null to clear it\");\n if (isListType(type) && Array.isArray(value) && value.length > 4 * METAFIELD_LIMITS.list_items) {\n return fail(path, \"list_too_long\", `must have at most ${METAFIELD_LIMITS.list_items} items`);\n }\n const base = baseTypeOf(type);\n const checker = hasOwn(CHECKERS, base) ? CHECKERS[base] : undefined;\n if (!checker) return fail(path, \"invalid_type\", `type ${String(type).slice(0, 40)} is not supported`);\n const result = isListType(type)\n ? checkList(base, checker, value, validations, ctx, path)\n : checker(value, validations, ctx, path);\n if (!result.ok) return result;\n const json = JSON.stringify(result.value);\n if (!isStorableJson(json)) {\n return fail(path, \"invalid_format\", \"contains characters that cannot be stored\");\n }\n if (byteLength(json) > METAFIELD_LIMITS.value_bytes) {\n return fail(path, \"too_large\", `must be at most ${METAFIELD_LIMITS.value_bytes} bytes`);\n }\n return result;\n}\n\n// ─── Definitions: validations ───────────────────────────────────\n\nexport type MetafieldValidationKey = keyof MetafieldValidations;\n\nexport const VALIDATION_KEYS: Readonly<Record<MetafieldBaseType, readonly MetafieldValidationKey[]>> = {\n single_line_text: [\"min_length\", \"max_length\", \"regex\", \"choices\"],\n multi_line_text: [\"min_length\", \"max_length\"],\n rich_text: [\"max_length\"],\n email: [],\n integer: [\"min\", \"max\"],\n decimal: [\"min\", \"max\", \"max_precision\"],\n date: [\"min\", \"max\"],\n date_time: [\"min\", \"max\"],\n url: [\"allowed_domains\"],\n link: [\"allowed_domains\"],\n weight: [\"min\", \"max\"],\n volume: [\"min\", \"max\"],\n dimension: [\"min\", \"max\"],\n boolean: [],\n color: [],\n rating: [\"scale_min\", \"scale_max\"],\n money: [],\n language: [],\n json: [],\n file: [\"file_types\"],\n image: [],\n video: [],\n product: [],\n variant: [],\n collection: [],\n page: [],\n blog_post: [],\n customer: [],\n order: [],\n metaobject_reference: [\"metaobject_definition_id\"],\n mixed_reference: [\"metaobject_definition_ids\"],\n};\n\n/**\n * Restricts merchant regexes to a dialect whose work is bounded: no\n * backreferences or lookaround, nothing but \"?\" after a group, at most two\n * quantifiers (*, +, ?, {n,}, {n,m}; a lazy \"?\" is part of its quantifier,\n * exact {n} is free) and at most four alternatives. Deliberately conservative.\n */\nexport function isSafeRegex(pattern: string): boolean {\n if (/\\\\[1-9]|\\\\k</.test(pattern)) return false;\n if (/\\(\\?<?[=!]/.test(pattern)) return false;\n let quantifiers = 0;\n let bars = 0;\n let afterQuantifier = false;\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n const wasQuantifier = afterQuantifier;\n afterQuantifier = false;\n if (char === \"\\\\\") {\n const escaped = pattern[i + 1];\n i++;\n if ((escaped === \"u\" || escaped === \"p\" || escaped === \"P\") && pattern[i + 1] === \"{\") {\n const close = pattern.indexOf(\"}\", i + 1);\n i = close === -1 ? pattern.length : close;\n }\n continue;\n }\n if (char === \"[\") {\n i++;\n while (i < pattern.length && pattern[i] !== \"]\") {\n if (pattern[i] === \"\\\\\") i++;\n i++;\n }\n continue;\n }\n if (char === \"(\") {\n if (pattern[i + 1] === \"?\") i++;\n continue;\n }\n if (char === \")\") {\n const next = pattern[i + 1];\n if (next === \"*\" || next === \"+\") return false;\n if (next === \"{\" && /^\\{\\d+(,\\d*)?\\}/.test(pattern.slice(i + 1))) return false;\n continue;\n }\n if (char === \"|\") {\n bars++;\n } else if (char === \"*\" || char === \"+\" || char === \"?\") {\n if (!(char === \"?\" && wasQuantifier)) {\n quantifiers++;\n afterQuantifier = true;\n }\n } else if (char === \"{\") {\n const match = /^\\{\\d+(,\\d*)?\\}/.exec(pattern.slice(i));\n if (match) {\n if (match[1] !== undefined) quantifiers++;\n afterQuantifier = true;\n i += match[0].length - 1;\n }\n }\n }\n return quantifiers <= 2 && bars <= 4;\n}\n\nconst HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/;\nconst FILE_KINDS: readonly FileKind[] = [\"image\", \"video\", \"document\"];\n\nfunction normalizeBound(base: MetafieldBaseType, input: unknown): MetafieldBound | null {\n switch (base) {\n case \"integer\":\n return typeof input === \"number\" && Number.isSafeInteger(input) ? input : null;\n case \"decimal\":\n return normalizeDecimal(input);\n case \"date\":\n return normalizeDate(input);\n case \"date_time\":\n return normalizeDateTime(input);\n case \"weight\":\n case \"volume\":\n case \"dimension\": {\n if (!isPlainObject(input) || Object.keys(input).some(k => k !== \"value\" && k !== \"unit\")) return null;\n const amount = normalizeDecimal(input.value);\n if (amount === null || typeof input.unit !== \"string\" || !hasOwn(MEASUREMENT_UNITS[base], input.unit)) {\n return null;\n }\n return { value: amount, unit: input.unit };\n }\n default:\n return null;\n }\n}\n\nfunction compareBound(base: MetafieldBaseType, a: MetafieldBound, b: MetafieldBound): number {\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (typeof a === \"object\" && typeof b === \"object\") {\n const type = base as MeasurementType;\n return (measurementInBaseUnit(a, type) ?? 0) - (measurementInBaseUnit(b, type) ?? 0);\n }\n if (base === \"decimal\") return compareDecimal(a as string, b as string);\n return (a as string) < (b as string) ? -1 : (a as string) > (b as string) ? 1 : 0;\n}\n\nfunction isWholeNumber(value: unknown, min: number, max: number): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max;\n}\n\n/**\n * Validates and canonicalises a definition's `validations` for its type\n * (spec §5.2). Unknown keys, unsafe regexes and contradictory bounds fail.\n */\nexport function validateValidations(\n type: MetafieldType,\n input: unknown,\n path = \"validations\"\n): EngineResult<MetafieldValidations> {\n if (!isMetafieldType(type)) return fail(path, \"invalid_type\", \"is not a metafield type\");\n const raw = input === undefined || input === null ? {} : input;\n if (!isPlainObject(raw)) return fail(path, \"invalid_type\", \"must be an object\");\n const base = baseTypeOf(type);\n const allowed: MetafieldValidationKey[] = [\n ...VALIDATION_KEYS[base],\n ...(isListType(type) ? ([\"list_min\", \"list_max\"] as const) : []),\n ];\n const errors = unknownKeys(raw, allowed, path);\n const out: MetafieldValidations = {};\n const has = (key: MetafieldValidationKey) => allowed.includes(key) && raw[key] !== undefined;\n const bad = (key: MetafieldValidationKey, message: string, code: MetafieldIssueCode = \"invalid_validation\") =>\n errors.push(issue(joinPath(path, key), code, message));\n\n for (const key of [\"min_length\", \"max_length\"] as const) {\n if (!has(key)) continue;\n const cap =\n base === \"single_line_text\" ? METAFIELD_LIMITS.single_line_text_length : METAFIELD_LIMITS.multi_line_text_length;\n if (isWholeNumber(raw[key], 0, cap)) out[key] = raw[key] as number;\n else bad(key, \"must be a whole number of 0 or more\");\n }\n\n if (has(\"regex\")) {\n const pattern = raw.regex;\n if (typeof pattern !== \"string\" || pattern.length === 0 || pattern.length > METAFIELD_LIMITS.regex_length) {\n bad(\"regex\", `must be 1 to ${METAFIELD_LIMITS.regex_length} characters`);\n } else if (!isSafeRegex(pattern)) {\n bad(\"regex\", \"is too complex: no backreferences or lookaround, no repetition after a group, at most 2 optional or repeated parts and 4 alternatives\", \"unsafe_regex\");\n } else {\n try {\n new RegExp(pattern, \"u\");\n out.regex = pattern;\n } catch {\n bad(\"regex\", \"is not a valid pattern\");\n }\n }\n }\n\n if (has(\"regex\")) {\n const limit = METAFIELD_LIMITS.regex_value_length;\n if (out.max_length !== undefined && out.max_length > limit) {\n bad(\"max_length\", `must be at most ${limit} when a pattern applies`);\n } else if (out.regex !== undefined && out.max_length === undefined) {\n out.max_length = limit;\n }\n }\n\n if (out.min_length !== undefined && out.max_length !== undefined && out.min_length > out.max_length) {\n bad(\"min_length\", \"must not exceed max_length\");\n }\n\n if (has(\"choices\")) {\n const choices = raw.choices;\n if (!Array.isArray(choices) || choices.length === 0 || choices.length > METAFIELD_LIMITS.choices) {\n bad(\"choices\", `must list 1 to ${METAFIELD_LIMITS.choices} values`);\n } else if (\n choices.some(\n c =>\n typeof c !== \"string\" ||\n c === \"\" ||\n /[\\r\\n]/.test(c) ||\n codePoints(c) > METAFIELD_LIMITS.single_line_text_length\n )\n ) {\n bad(\"choices\", \"must be non-empty single-line text\");\n } else if (new Set(choices).size !== choices.length) {\n bad(\"choices\", \"must not repeat a value\");\n } else if (\n (choices as string[]).some(c => {\n // Length first, so the regex never runs on an oversized choice.\n const length = codePoints(c);\n if (length > METAFIELD_LIMITS.regex_value_length && out.regex !== undefined) return true;\n if (out.max_length !== undefined && length > out.max_length) return true;\n if (out.min_length !== undefined && length < out.min_length) return true;\n return out.regex !== undefined && !matchesPattern(out.regex, c);\n })\n ) {\n bad(\"choices\", \"includes a value the pattern or length rules reject\");\n } else {\n out.choices = [...(choices as string[])];\n }\n }\n\n for (const key of [\"min\", \"max\"] as const) {\n if (!has(key)) continue;\n const bound = normalizeBound(base, raw[key]);\n if (bound === null) bad(key, `is not a valid ${base} bound`);\n else out[key] = bound;\n }\n if (out.min !== undefined && out.max !== undefined && compareBound(base, out.min, out.max) > 0) {\n bad(\"min\", \"must not exceed max\");\n }\n\n if (has(\"max_precision\")) {\n if (isWholeNumber(raw.max_precision, 0, 9)) out.max_precision = raw.max_precision as number;\n else bad(\"max_precision\", \"must be a whole number from 0 to 9\");\n }\n\n if (has(\"allowed_domains\")) {\n const domains = raw.allowed_domains;\n const lowered = Array.isArray(domains)\n ? domains.map(d => (typeof d === \"string\" ? d.toLowerCase() : \"\"))\n : [];\n if (\n !Array.isArray(domains) ||\n domains.length === 0 ||\n domains.length > METAFIELD_LIMITS.allowed_domains ||\n lowered.some(d => !HOSTNAME.test(d))\n ) {\n bad(\"allowed_domains\", `must list 1 to ${METAFIELD_LIMITS.allowed_domains} domains such as youtube.com`);\n } else {\n out.allowed_domains = [...new Set(lowered)];\n }\n }\n\n if (base === \"rating\") {\n for (const key of [\"scale_min\", \"scale_max\"] as const) {\n if (raw[key] === undefined) {\n bad(key, \"is required for a rating\", \"required\");\n continue;\n }\n const decimal = normalizeDecimal(raw[key]);\n if (decimal === null) bad(key, \"must be a decimal number\");\n else out[key] = decimal;\n }\n if (out.scale_min !== undefined && out.scale_max !== undefined && compareDecimal(out.scale_min, out.scale_max) >= 0) {\n bad(\"scale_min\", \"must be below scale_max\");\n }\n }\n\n if (has(\"file_types\")) {\n const kinds = raw.file_types;\n if (\n !Array.isArray(kinds) ||\n kinds.length === 0 ||\n kinds.some(k => !FILE_KINDS.includes(k as FileKind)) ||\n new Set(kinds).size !== kinds.length\n ) {\n bad(\"file_types\", \"must list image, video and/or document\");\n } else {\n out.file_types = [...(kinds as FileKind[])];\n }\n }\n\n if (base === \"metaobject_reference\") {\n const id = normalizeId(raw.metaobject_definition_id);\n if (raw.metaobject_definition_id === undefined) {\n bad(\"metaobject_definition_id\", \"is required\", \"required\");\n } else if (id === null) {\n bad(\"metaobject_definition_id\", \"must be a metaobject definition id\");\n } else {\n out.metaobject_definition_id = id;\n }\n }\n\n if (base === \"mixed_reference\") {\n const ids = Array.isArray(raw.metaobject_definition_ids)\n ? raw.metaobject_definition_ids.map(normalizeId)\n : null;\n if (raw.metaobject_definition_ids === undefined) {\n bad(\"metaobject_definition_ids\", \"is required\", \"required\");\n } else if (\n !ids ||\n ids.length < METAFIELD_LIMITS.mixed_reference_definitions_min ||\n ids.length > METAFIELD_LIMITS.mixed_reference_definitions_max ||\n ids.some(id => id === null) ||\n new Set(ids).size !== ids.length\n ) {\n bad(\n \"metaobject_definition_ids\",\n `must list ${METAFIELD_LIMITS.mixed_reference_definitions_min} to ${METAFIELD_LIMITS.mixed_reference_definitions_max} different definition ids`\n );\n } else {\n out.metaobject_definition_ids = ids as string[];\n }\n }\n\n for (const key of [\"list_min\", \"list_max\"] as const) {\n if (!has(key)) continue;\n if (isWholeNumber(raw[key], 0, METAFIELD_LIMITS.list_items)) out[key] = raw[key] as number;\n else bad(key, `must be a whole number from 0 to ${METAFIELD_LIMITS.list_items}`);\n }\n if (out.list_min !== undefined && out.list_max !== undefined && out.list_min > out.list_max) {\n bad(\"list_min\", \"must not exceed list_max\");\n }\n\n return errors.length ? { ok: false, errors } : ok(out);\n}\n\n// --- Definitions: metafields, metaobjects, entries ---\n\nexport type CustomerAccess = \"none\" | \"read\" | \"read_write\";\n\n/** Customer, order and location data never reaches the public storefront (spec s.4.1). */\nexport function storefrontAccessAllowed(owner: MetafieldOwnerType): boolean {\n return owner !== \"customer\" && owner !== \"order\" && owner !== \"location\";\n}\n\nexport function allowedCustomerAccess(owner: MetafieldOwnerType): readonly CustomerAccess[] {\n if (owner === \"customer\") return [\"none\", \"read\", \"read_write\"];\n if (owner === \"order\") return [\"none\", \"read\"];\n return [\"none\"];\n}\n\nexport interface MetafieldDefinitionShape {\n owner_type: MetafieldOwnerType;\n namespace: string;\n key: string;\n name: string;\n description: string | null;\n type: MetafieldType;\n validations: MetafieldValidations;\n storefront_access: boolean;\n customer_access: CustomerAccess;\n}\n\nconst METAFIELD_DEFINITION_KEYS = [\n \"owner_type\",\n \"namespace\",\n \"key\",\n \"name\",\n \"description\",\n \"type\",\n \"validations\",\n \"storefront_access\",\n \"customer_access\",\n] as const;\n\nfunction readName(value: unknown, path: string, errors: MetafieldIssue[]): string {\n const name = typeof value === \"string\" ? value.trim() : \"\";\n if (!name || codePoints(name) > METAFIELD_LIMITS.name_length) {\n errors.push(issue(path, \"invalid_format\", `must be 1 to ${METAFIELD_LIMITS.name_length} characters`));\n }\n return name;\n}\n\nfunction readDescription(value: unknown, path: string, errors: MetafieldIssue[]): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value !== \"string\" || codePoints(value) > METAFIELD_LIMITS.description_length) {\n errors.push(issue(path, \"invalid_format\", `must be text of at most ${METAFIELD_LIMITS.description_length} characters`));\n return null;\n }\n return value.trim() || null;\n}\n\nfunction readKey(value: unknown, path: string, errors: MetafieldIssue[], pattern = METAFIELD_KEY_PATTERN): string {\n if (typeof value !== \"string\" || !pattern.test(value)) {\n errors.push(issue(path, \"invalid_format\", \"must be 2 to 64 lowercase letters, digits or underscores\"));\n return \"\";\n }\n if (RESERVED_KEYS.includes(value)) {\n errors.push(issue(path, \"invalid_format\", \"is a reserved name\"));\n return \"\";\n }\n return value;\n}\n\nfunction readBoolean(value: unknown, fallback: boolean, path: string, errors: MetafieldIssue[]): boolean {\n if (value === undefined) return fallback;\n if (typeof value !== \"boolean\") {\n errors.push(issue(path, \"invalid_type\", \"must be true or false\"));\n return fallback;\n }\n return value;\n}\n\nfunction readTypeAndValidations(\n input: Record<string, unknown>,\n path: string,\n errors: MetafieldIssue[]\n): { type: MetafieldType; validations: MetafieldValidations } | null {\n if (!isMetafieldType(input.type)) {\n errors.push(issue(joinPath(path, \"type\"), \"invalid_format\", \"is not a metafield type\"));\n return null;\n }\n const validations = validateValidations(input.type, input.validations, joinPath(path, \"validations\"));\n if (!validations.ok) {\n errors.push(...validations.errors);\n return null;\n }\n return { type: input.type, validations: validations.value };\n}\n\n/** Validates a full metafield definition; the API merges a PATCH into the stored row first. */\nexport function validateMetafieldDefinition(input: unknown): EngineResult<MetafieldDefinitionShape> {\n if (!isPlainObject(input)) return fail(\"\", \"invalid_type\", \"must be an object\");\n const errors = unknownKeys(input, METAFIELD_DEFINITION_KEYS, \"\");\n const owner = input.owner_type as MetafieldOwnerType;\n if (!METAFIELD_OWNER_TYPES.includes(owner)) {\n errors.push(issue(\"owner_type\", \"invalid_format\", `must be one of: ${METAFIELD_OWNER_TYPES.join(\", \")}`));\n }\n const namespace = readKey(input.namespace ?? \"custom\", \"namespace\", errors);\n const key = readKey(input.key, \"key\", errors);\n const name = readName(input.name, \"name\", errors);\n const description = readDescription(input.description, \"description\", errors);\n const typed = readTypeAndValidations(input, \"\", errors);\n const storefront = readBoolean(input.storefront_access, false, \"storefront_access\", errors);\n if (storefront && METAFIELD_OWNER_TYPES.includes(owner) && !storefrontAccessAllowed(owner)) {\n errors.push(issue(\"storefront_access\", \"not_allowed\", `is not available for ${owner} metafields`));\n }\n const customer = (input.customer_access ?? \"none\") as CustomerAccess;\n if (!allowedCustomerAccess(owner).includes(customer)) {\n errors.push(issue(\"customer_access\", \"not_allowed\", `must be one of: ${allowedCustomerAccess(owner).join(\", \")}`));\n }\n if (errors.length || !typed) return { ok: false, errors };\n const out: MetafieldDefinitionShape = {\n owner_type: owner,\n namespace,\n key,\n name,\n description,\n type: typed.type,\n validations: typed.validations,\n storefront_access: storefront,\n customer_access: customer,\n };\n return storable(out);\n}\n\n/** Definitions persist as jsonb too: refuse NUL and lone surrogates anywhere in them. */\nfunction storable<T>(out: T): EngineResult<T> {\n if (!isStorableJson(JSON.stringify(out))) {\n return fail(\"\", \"invalid_format\", \"contains characters that cannot be stored\");\n }\n return ok(out);\n}\n\nexport interface MetaobjectFieldShape {\n key: string;\n name: string;\n description: string | null;\n type: MetafieldType;\n required: boolean;\n validations: MetafieldValidations;\n}\n\n/** Field types usable as filter keys (spec s.4.3). List types never are. */\nexport const FILTERABLE_TYPES: readonly MetafieldBaseType[] = [\"single_line_text\", \"boolean\", \"integer\", \"date\"];\n\nexport interface MetaobjectDefinitionShape {\n type: string;\n name: string;\n description: string | null;\n fields: MetaobjectFieldShape[];\n display_name_key: string | null;\n filter_keys: string[];\n has_status: boolean;\n storefront_access: boolean;\n customer_access: \"none\" | \"read\";\n}\n\nconst METAOBJECT_DEFINITION_KEYS = [\n \"type\",\n \"name\",\n \"description\",\n \"fields\",\n \"display_name_key\",\n \"filter_keys\",\n \"has_status\",\n \"storefront_access\",\n \"customer_access\",\n] as const;\n\nconst FIELD_KEYS = [\"key\", \"name\", \"description\", \"type\", \"required\", \"validations\"] as const;\n\nfunction readField(input: unknown, path: string, errors: MetafieldIssue[]): MetaobjectFieldShape | null {\n if (!isPlainObject(input)) {\n errors.push(issue(path, \"invalid_type\", \"must be an object\"));\n return null;\n }\n errors.push(...unknownKeys(input, FIELD_KEYS, path));\n const key = readKey(input.key, joinPath(path, \"key\"), errors);\n const name = readName(input.name, joinPath(path, \"name\"), errors);\n const description = readDescription(input.description, joinPath(path, \"description\"), errors);\n const required = readBoolean(input.required, false, joinPath(path, \"required\"), errors);\n const typed = readTypeAndValidations(input, path, errors);\n return typed ? { key, name, description, type: typed.type, required, validations: typed.validations } : null;\n}\n\n/** Validates a full metaobject definition; the API merges a PATCH into the stored row first. */\nexport function validateMetaobjectDefinition(input: unknown): EngineResult<MetaobjectDefinitionShape> {\n if (!isPlainObject(input)) return fail(\"\", \"invalid_type\", \"must be an object\");\n const errors = unknownKeys(input, METAOBJECT_DEFINITION_KEYS, \"\");\n const type = typeof input.type === \"string\" && METAOBJECT_TYPE_PATTERN.test(input.type) ? input.type : \"\";\n if (!type) {\n errors.push(issue(\"type\", \"invalid_format\", \"must be 2 to 64 lowercase letters, digits, underscores or hyphens\"));\n } else if (RESERVED_KEYS.includes(type)) {\n errors.push(issue(\"type\", \"invalid_format\", \"is a reserved name\"));\n }\n const name = readName(input.name, \"name\", errors);\n const description = readDescription(input.description, \"description\", errors);\n\n const fields: MetaobjectFieldShape[] = [];\n if (!Array.isArray(input.fields)) {\n errors.push(issue(\"fields\", \"invalid_type\", \"must be a list of fields\"));\n } else if (input.fields.length === 0) {\n errors.push(issue(\"fields\", \"too_short\", \"must have at least 1 field\"));\n } else if (input.fields.length > METAFIELD_LIMITS.fields_per_metaobject) {\n errors.push(issue(\"fields\", \"too_long\", `must have at most ${METAFIELD_LIMITS.fields_per_metaobject} fields`));\n } else {\n const seen = new Set<string>();\n input.fields.forEach((raw, index) => {\n const path = joinPath(\"fields\", index);\n const field = readField(raw, path, errors);\n if (!field) return;\n if (seen.has(field.key)) errors.push(issue(joinPath(path, \"key\"), \"duplicate\", `\"${field.key}\" is used twice`));\n seen.add(field.key);\n fields.push(field);\n });\n }\n const byKey = new Map(fields.map(field => [field.key, field]));\n const isSingleLine = (key: string) => byKey.get(key)?.type === \"single_line_text\";\n\n let displayNameKey: string | null;\n if (input.display_name_key === undefined) {\n displayNameKey = fields.find(field => field.type === \"single_line_text\")?.key ?? null;\n } else if (input.display_name_key === null) {\n displayNameKey = null;\n } else if (typeof input.display_name_key === \"string\" && isSingleLine(input.display_name_key)) {\n displayNameKey = input.display_name_key;\n } else {\n displayNameKey = null;\n errors.push(issue(\"display_name_key\", \"invalid_format\", \"must name a single line text field\"));\n }\n\n const filterKeys: string[] = [];\n const rawFilters = input.filter_keys ?? [];\n if (!Array.isArray(rawFilters)) {\n errors.push(issue(\"filter_keys\", \"invalid_type\", \"must be a list of field keys\"));\n } else if (rawFilters.length > METAFIELD_LIMITS.filter_keys) {\n errors.push(issue(\"filter_keys\", \"too_long\", `must have at most ${METAFIELD_LIMITS.filter_keys} keys`));\n } else {\n rawFilters.forEach((key, index) => {\n const path = joinPath(\"filter_keys\", index);\n const field = typeof key === \"string\" ? byKey.get(key) : undefined;\n if (!field) errors.push(issue(path, \"invalid_format\", \"must name a field of this definition\"));\n else if (!FILTERABLE_TYPES.includes(field.type as MetafieldBaseType)) {\n errors.push(issue(path, \"not_allowed\", \"only single line text, true or false, integer and date fields can be filters\"));\n } else if (filterKeys.includes(field.key)) errors.push(issue(path, \"duplicate\", `\"${field.key}\" is listed twice`));\n else filterKeys.push(field.key);\n });\n }\n\n const hasStatus = readBoolean(input.has_status, true, \"has_status\", errors);\n const storefront = readBoolean(input.storefront_access, false, \"storefront_access\", errors);\n const customer = input.customer_access ?? \"none\";\n if (customer !== \"none\" && customer !== \"read\") {\n errors.push(issue(\"customer_access\", \"not_allowed\", \"must be none or read\"));\n }\n\n if (errors.length) return { ok: false, errors };\n return storable<MetaobjectDefinitionShape>({\n type,\n name,\n description,\n fields,\n display_name_key: displayNameKey,\n filter_keys: filterKeys,\n has_status: hasStatus,\n storefront_access: storefront,\n customer_access: customer as \"none\" | \"read\",\n });\n}\n\n/** Validates an entry's field values against its definition; blank optional fields are omitted. */\nexport function validateMetaobjectEntry(\n fields: readonly MetaobjectFieldShape[],\n input: unknown,\n ctx: MetafieldContext\n): EngineResult<Record<string, unknown>> {\n if (!Array.isArray(fields)) return fail(\"\", \"invalid_type\", \"fields must be a list\");\n if (!isPlainObject(input)) return fail(\"\", \"invalid_type\", \"must be an object of field values\");\n const errors = unknownKeys(input, fields.map(field => field.key), \"\");\n const out: Record<string, unknown> = {};\n for (const field of fields) {\n const raw = hasOwn(input, field.key) ? input[field.key] : undefined;\n if (isBlankValueFor(field.type, raw)) {\n if (field.required) errors.push(issue(field.key, \"required\", \"is required\"));\n continue;\n }\n const result = validateMetafieldValue(field.type, field.validations, raw, ctx, field.key);\n if (result.ok) {\n Object.defineProperty(out, field.key, { value: result.value, enumerable: true, writable: true, configurable: true });\n }\n else errors.push(...result.errors);\n }\n if (!errors.length && byteLength(JSON.stringify(out)) > METAFIELD_LIMITS.value_bytes) {\n return fail(\"\", \"too_large\", `must be at most ${METAFIELD_LIMITS.value_bytes} bytes`);\n }\n return errors.length ? { ok: false, errors } : ok(out);\n}\n\n/** The display-name field's text, else the handle (spec s.4.4). */\nexport function entryDisplayName(\n definition: Pick<MetaobjectDefinitionShape, \"display_name_key\">,\n fields: Record<string, unknown>,\n handle: string\n): string {\n const value = definition.display_name_key ? fields[definition.display_name_key] : undefined;\n return typeof value === \"string\" && value.trim() ? [...value.trim()].slice(0, METAFIELD_LIMITS.name_length).join(\"\") : handle;\n}\n\n/**\n * A field's type is fixed once saved (spec s.4.5). Reports removed keys so the\n * API can strip them from entries. Assumes `after` already passed\n * validateMetaobjectDefinition (unique keys).\n */\nexport function checkMetaobjectFieldChanges(\n before: readonly MetaobjectFieldShape[],\n after: readonly MetaobjectFieldShape[]\n): EngineResult<{ removed: string[]; added: string[] }> {\n const prior = new Map(before.map(field => [field.key, field]));\n const errors = after.flatMap((field, index) => {\n const old = prior.get(field.key);\n return old && old.type !== field.type\n ? [issue(joinPath(joinPath(\"fields\", index), \"type\"), \"immutable\", `cannot change the type of \"${field.key}\"`)]\n : [];\n });\n if (errors.length) return { ok: false, errors };\n const kept = new Set(after.map(field => field.key));\n return ok({\n removed: before.filter(field => !kept.has(field.key)).map(field => field.key),\n added: after.filter(field => !prior.has(field.key)).map(field => field.key),\n });\n}\n","import type { ImageTransformOptions } from \"./types\";\n\n/**\n * Storage URL helpers.\n *\n * Object URLs are plain strings, so no storage client is required — these only\n * ever concatenated base + bucket + path. URLs are built against\n * NEXT_PUBLIC_ASSET_BASE_URL (or ASSET_BASE_URL on the server), which points at\n * the API that serves `/storage/v1/...`.\n *\n * A stored URL's ORIGIN is deliberately ignored and rebuilt: rows written\n * before the storage migration carry whatever host was configured at the time,\n * and those hosts no longer serve anything. Rebuilding is what lets old and new\n * rows resolve identically with no database backfill.\n */\n\nexport const OBJECT_PREFIX = \"/storage/v1/object/public/\";\nexport const RENDER_PREFIX = \"/storage/v1/render/image/public/\";\n\nexport const DEFAULT_BUCKET = \"public-cdn\";\n\nfunction getEnv(key: string): string | undefined {\n if (typeof window === \"undefined\") {\n return process.env[key];\n }\n return (\n (window as unknown as Record<string, any>)?.process?.env?.[key] ?? undefined\n );\n}\n\n/**\n * Origin serving storage objects. Callers in a bundler that inlines\n * `process.env.NEXT_PUBLIC_*` should pass the value explicitly to the\n * `baseUrl` parameters below rather than relying on this lookup, since a\n * dynamic `process.env[key]` read is not inlined.\n */\nexport function assetBaseUrl(): string {\n return (\n getEnv(\"NEXT_PUBLIC_ASSET_BASE_URL\") ||\n getEnv(\"ASSET_BASE_URL\") ||\n \"\"\n ).replace(/\\/$/, \"\");\n}\n\n/**\n * Tells whether image resizing is on. Controlled by `NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS`; when unset it is on, except for a local asset host.\n *\n * @returns `true` when image URLs should use the resizing endpoint\n */\nexport function transformationsEnabled(): boolean {\n const flag = getEnv(\"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\");\n if (typeof flag === \"string\" && flag !== \"\") {\n return [\"1\", \"true\", \"yes\", \"on\"].includes(flag.toLowerCase());\n }\n // Local stacks may not run the image renderer, so serve originals.\n return !/localhost|127\\.0\\.0\\.1/.test(assetBaseUrl());\n}\n\n/**\n * Builds the query string for an image resize request.\n *\n * @param opts - the resize options; unset or non-finite values are left out\n * @returns The query string including the leading `?`, or an empty string when there is nothing to add\n */\nexport function buildTransformQuery(opts?: ImageTransformOptions): string {\n if (!opts) return \"\";\n const params = new URLSearchParams();\n if (opts.width && Number.isFinite(opts.width))\n params.set(\"width\", String(opts.width));\n if (opts.height && Number.isFinite(opts.height))\n params.set(\"height\", String(opts.height));\n if (opts.resize) params.set(\"resize\", opts.resize);\n if (opts.quality && Number.isFinite(opts.quality))\n params.set(\"quality\", String(opts.quality));\n if (opts.format) params.set(\"format\", opts.format);\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\n/**\n * Builds the URL of a resized version of a stored image. Defaults to `resize=cover` and `quality=80`.\n *\n * @param baseUrl - the origin that serves storage objects\n * @param bucket - the storage bucket\n * @param path - the object path inside the bucket\n * @param opts - resize options that override the defaults\n * @returns The resized image URL\n */\nexport function toRenderUrl(\n baseUrl: string,\n bucket: string,\n path: string,\n opts?: ImageTransformOptions\n): string {\n const query = buildTransformQuery({ resize: \"cover\", quality: 80, ...opts });\n const normalizedPath = path.replace(/^\\//, \"\");\n return `${baseUrl.replace(/\\/$/, \"\")}${RENDER_PREFIX}${bucket}/${normalizedPath}${query}`;\n}\n\n/**\n * Builds the URL of the original, unresized stored image.\n *\n * @param baseUrl - the origin that serves storage objects\n * @param bucket - the storage bucket\n * @param path - the object path inside the bucket\n * @returns The original image URL\n */\nexport function toObjectUrl(\n baseUrl: string,\n bucket: string,\n path: string\n): string {\n const normalizedPath = path.replace(/^\\//, \"\");\n return `${baseUrl.replace(/\\/$/, \"\")}${OBJECT_PREFIX}${bucket}/${normalizedPath}`;\n}\n\n/**\n * Pull bucket + object path out of a storage URL, whatever host it names.\n * Accepts both the object and render path shapes. Returns null for URLs that\n * are not storage URLs at all.\n */\nexport function parseStorageUrl(\n url: string\n): { bucket: string; path: string } | null {\n try {\n const { pathname } = new URL(url);\n const prefix = [OBJECT_PREFIX, RENDER_PREFIX].find((p) =>\n pathname.includes(p)\n );\n if (!prefix) return null;\n\n const parts = pathname.split(prefix)[1].split(\"/\");\n const bucket = parts.shift();\n if (!bucket || parts.length === 0) return null;\n\n return { bucket, path: parts.join(\"/\") };\n } catch {\n return null;\n }\n}\n\n/**\n * Rewrite a storage object URL to the render endpoint, rebuilding it against\n * `baseUrl` (defaulting to the configured asset origin). Returns the URL\n * unchanged when it is not a storage URL, when transformations are disabled,\n * or when no base URL is configured.\n */\nexport function fromObjectPublicUrlToRender(\n publicUrl: string,\n opts?: ImageTransformOptions,\n baseUrl: string = assetBaseUrl()\n): string | null {\n const parsed = parseStorageUrl(publicUrl);\n if (!parsed || !baseUrl) return null;\n return toRenderUrl(baseUrl, parsed.bucket, parsed.path, opts);\n}\n\n/**\n * Resolve any image reference — a full URL or a bare storage object path — to\n * a URL served by the configured asset origin.\n *\n * - A full http(s) URL that is not a storage URL is returned as-is.\n * - A storage URL is rebuilt against `baseUrl`, ignoring its stored host.\n * - A bare object path is resolved within `bucket`.\n */\nexport function resolveAssetUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions,\n bucket: string = DEFAULT_BUCKET,\n baseUrl: string = assetBaseUrl()\n): string | null {\n if (!imagePathOrUrl) return null;\n\n const build = (b: string, p: string) =>\n transformationsEnabled()\n ? toRenderUrl(baseUrl, b, p, opts)\n : toObjectUrl(baseUrl, b, p);\n\n if (/^https?:\\/\\//i.test(imagePathOrUrl)) {\n const parsed = parseStorageUrl(imagePathOrUrl);\n if (!parsed) return imagePathOrUrl;\n return baseUrl ? build(parsed.bucket, parsed.path) : imagePathOrUrl;\n }\n\n // Starts with / -> a local app asset, not storage. Leave untouched.\n if (imagePathOrUrl.startsWith(\"/\")) return imagePathOrUrl;\n\n return baseUrl ? build(bucket, imagePathOrUrl) : null;\n}\n\n/**\n * Resolves a stored image URL to the asset host, resized when options are given.\n *\n * @deprecated Renamed to {@link resolveAssetUrl}. The old name described a\n * Supabase-specific rewrite; the implementation is no longer Supabase-aware.\n * Kept so existing callers keep compiling.\n */\nexport function rewriteSupabaseUrl(\n url: string,\n opts?: ImageTransformOptions\n): string {\n return resolveAssetUrl(url, opts) ?? url;\n}\n","export function stringify(obj: object): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(obj)) {\n if (value === null || value === undefined) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n params.append(key, String(item));\n }\n } else {\n params.append(key, String(value));\n }\n }\n return params.toString();\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { ProductDetail, ProductQueryParams } from \"./types\";\n\n/**\n * Products of a store, reached through `sdk.products`.\n */\nexport class ProductsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Gets one product by id.\n *\n * @param storeRef - the store's ref or handle\n * @param productId - the product id\n * @param query - optional fields to include\n * @returns The product, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(\n storeRef: string,\n productId: number,\n query?: ProductQueryParams\n ): Promise<ProductDetail | null> {\n const queryString = stringify(query ?? {});\n const res = await this.http.get<ProductDetail>(\n `/storefront/stores/${storeRef}/products/${productId}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Gets one product by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the product slug\n * @param query - optional fields to include\n * @returns The product, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySlug(\n storeRef: string,\n slug: string,\n query?: ProductQueryParams\n ): Promise<ProductDetail | null> {\n const normalizedSlug = slug.normalize(\"NFC\");\n const encodedSlug = encodeURIComponent(normalizedSlug);\n const queryString = stringify(query ?? {});\n const res = await this.http.get<ProductDetail>(\n `/storefront/stores/${storeRef}/products/slug/${encodedSlug}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrapOrNull(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { Collection, CollectionQueryParams } from \"./types\";\nimport type { PaginatedResponse } from \"../../types\";\n\n/**\n * Product collections of a store, reached through `sdk.collections`.\n */\nexport class CollectionsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists collections, one page at a time.\n *\n * @param storeRef - the store's ref or handle\n * @param params - filters, sorting and paging\n * @returns A page of collections; throws {@link ApiClientError} when the API answers with an error\n */\n async getAllPaginated(\n storeRef: string,\n params?: CollectionQueryParams\n ): Promise<PaginatedResponse<Collection>> {\n const queryString = stringify(params ?? {});\n const res = await this.http.get<PaginatedResponse<Collection>>(\n `/storefront/stores/${storeRef}/collections${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists up to 100 collections in one call.\n *\n * @param storeRef - the store's ref or handle\n * @param ids - limit the result to these collection ids\n * @returns The collections; throws {@link ApiClientError} when the API answers with an error\n */\n async getAll(storeRef: string, ids?: number[]): Promise<Collection[]> {\n const result = await this.getAllPaginated(storeRef, {\n ids,\n limit: ids && ids.length > 0 ? Math.min(ids.length, 100) : 100,\n });\n return result.data;\n }\n\n /**\n * Gets one collection by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the collection slug\n * @param query - `include_seo_metadata` adds the SEO fields\n * @returns The collection, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySlug(\n storeRef: string,\n slug: string,\n query?: { include_seo_metadata?: boolean }\n ): Promise<Collection | null> {\n const queryString = query ? stringify(query) : \"\";\n const res = await this.http.get<Collection>(\n `/storefront/stores/${storeRef}/collections/slug/${slug}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrapOrNull(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { Category, CategoryQueryParams } from \"./types\";\nimport type { PaginatedResponse } from \"../../types\";\n\n/**\n * Product categories of a store, reached through `sdk.categories`.\n */\nexport class CategoriesApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists categories, one page at a time.\n *\n * @param storeRef - the store's ref or handle\n * @param params - filters, sorting and paging\n * @returns A page of categories; throws {@link ApiClientError} when the API answers with an error\n */\n async getAllPaginated(\n storeRef: string,\n params?: CategoryQueryParams\n ): Promise<PaginatedResponse<Category>> {\n const queryString = stringify(params ?? {});\n const res = await this.http.get<PaginatedResponse<Category>>(\n `/storefront/stores/${storeRef}/categories${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists up to 1,000 categories in one call.\n *\n * @param storeRef - the store's ref or handle\n * @param activeOnly - `true` (the default) returns only active categories\n * @returns The categories; throws {@link ApiClientError} when the API answers with an error\n */\n async getAll(storeRef: string, activeOnly = true): Promise<Category[]> {\n const result = await this.getAllPaginated(storeRef, {\n is_active: activeOnly,\n limit: 1000,\n });\n return result.data;\n }\n\n /**\n * Gets one category by id.\n *\n * @param storeRef - the store's ref or handle\n * @param categoryId - the category id\n * @returns The category, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(\n storeRef: string,\n categoryId: number\n ): Promise<Category | null> {\n const res = await this.http.get<Category>(\n `/storefront/stores/${storeRef}/categories/${categoryId}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Gets one category by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the category slug\n * @returns The category, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySlug(storeRef: string, slug: string): Promise<Category | null> {\n const res = await this.http.get<Category>(\n `/storefront/stores/${storeRef}/categories/${encodeURIComponent(slug)}`\n );\n return unwrapOrNull(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type {\n CartApiResponse,\n CartApiItem,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"./types\";\n\n/**\n * A shopper's cart: a guest cart keyed by a session id, or the signed-in customer's cart, reached through `sdk.cart`.\n */\nexport class CartApi {\n constructor(\n private privateHttp: IHttpClient,\n private shopperHttp: IHttpClient\n ) {}\n\n private client(isAuth: boolean) {\n return isAuth ? this.shopperHttp : this.privateHttp;\n }\n\n /** Guest cart: `/storefront/stores/:ref/cart`; signed-in: `.../customers/cart`. */\n private cartPath(isAuth: boolean, storeRef: string) {\n return isAuth\n ? `/storefront/stores/${storeRef}/customers/cart`\n : `/storefront/stores/${storeRef}/cart`;\n }\n\n /**\n * Gets the shopper's cart.\n *\n * @param storeRef - the store's ref or handle\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getCart(\n storeRef: string,\n sessionId: string,\n isAuth: boolean\n ): Promise<CartApiResponse | null> {\n const res = await this.client(isAuth).get<CartApiResponse>(\n this.cartPath(isAuth, storeRef),\n { headers: { \"x-session-id\": sessionId } }\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Adds a product variant to the cart.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the variant and the quantity\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id and the added item; throws {@link ApiClientError} when the API answers with an error\n */\n async addItem(\n storeRef: string,\n data: AddToCartRequest,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cart_id: string; item: CartApiItem }> {\n const res = await this.client(isAuth).post<{\n cart_id: string;\n item: CartApiItem;\n }>(`${this.cartPath(isAuth, storeRef)}/items`, data, {\n headers: { \"x-session-id\": sessionId },\n });\n return unwrap(res);\n }\n\n /**\n * Changes the quantity of a cart line.\n *\n * @param storeRef - the store's ref or handle\n * @param itemId - the cart line id\n * @param data - the new quantity\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id and the updated item (`null` when the line was removed); throws {@link ApiClientError} when the API answers with an error\n */\n async updateItem(\n storeRef: string,\n itemId: string,\n data: UpdateCartItemRequest,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cart_id: string; item: CartApiItem | null }> {\n const res = await this.client(isAuth).put<{\n cart_id: string;\n item: CartApiItem | null;\n }>(`${this.cartPath(isAuth, storeRef)}/items/${itemId}`, data, {\n headers: { \"x-session-id\": sessionId },\n });\n return unwrap(res);\n }\n\n /**\n * Removes a line from the cart.\n *\n * @param storeRef - the store's ref or handle\n * @param itemId - the cart line id\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id and the removed line's id; throws {@link ApiClientError} when the API answers with an error\n */\n async removeItem(\n storeRef: string,\n itemId: string,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cartId: string; itemId: string }> {\n const res = await this.client(isAuth).delete<{\n cartId: string;\n itemId: string;\n }>(`${this.cartPath(isAuth, storeRef)}/items/${itemId}`, {\n headers: { \"x-session-id\": sessionId },\n });\n return unwrap(res);\n }\n\n /**\n * Empties the cart.\n *\n * @param storeRef - the store's ref or handle\n * @param sessionId - the guest cart session id\n * @param isAuth - `true` for the signed-in customer's cart, `false` for the guest cart\n * @returns The cart id; throws {@link ApiClientError} when the API answers with an error\n */\n async clear(\n storeRef: string,\n sessionId: string,\n isAuth: boolean\n ): Promise<{ cart_id: string }> {\n const res = await this.client(isAuth).delete<{ cart_id: string }>(\n this.cartPath(isAuth, storeRef),\n { headers: { \"x-session-id\": sessionId } }\n );\n return unwrap(res);\n }\n\n /**\n * Merge the guest cart into the signed-in cart. Resolves to\n * `{ merged: false }` when neither cart exists.\n */\n async merge(\n storeRef: string,\n sessionId: string\n ): Promise<CartApiResponse | { merged: false }> {\n const res = await this.shopperHttp.post<CartApiResponse | { merged: false }>(\n `/storefront/stores/${storeRef}/customers/cart/merge`,\n {},\n { headers: { \"x-session-id\": sessionId } }\n );\n return unwrap(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { PaginatedResponse, Id, WithMetafields } from \"../../types\";\nimport type {\n Order,\n OrderWithItems,\n CustomerOrderFilter,\n CreateOrderRequest,\n GuestOrderLookupParams,\n} from \"./types\";\n\n/**\n * Placing orders, and reading them back as a guest or as the signed-in customer, reached through `sdk.orders`.\n */\nexport class OrdersApi {\n constructor(\n private privateHttp: IHttpClient,\n private shopperHttp: IHttpClient\n ) {}\n\n /**\n * Look up a guest order. The API answers with the bare order when it\n * matches and `{ message }` (HTTP 200) when it does not; a 404 is treated\n * the same way. Returns null for \"not found\".\n */\n async lookupGuest(\n storeRef: string,\n params: GuestOrderLookupParams\n ): Promise<OrderWithItems | null> {\n const query = stringify({\n order_code: params.order_code,\n order_number: params.order_number,\n customer_email: params.customer_email,\n customer_phone: params.customer_phone,\n });\n const res = await this.privateHttp.get<OrderWithItems | { message: string }>(\n `/storefront/stores/${storeRef}/orders/lookup?${query}`\n );\n const data = unwrapOrNull(res);\n if (!data || !(\"id\" in data) || data.id == null) return null;\n return data as OrderWithItems;\n }\n\n /**\n * Places an order.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the order details\n * @param isAuth - `true` to place it as the signed-in customer, `false` as a guest\n * @returns The created order with its items; throws {@link ApiClientError} when the API answers with an error\n */\n async create(\n storeRef: string,\n data: CreateOrderRequest,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n if (isAuth) {\n const res = await this.shopperHttp.post<OrderWithItems>(\n `/storefront/stores/${storeRef}/customers/orders`,\n data\n );\n return unwrap(res);\n }\n const res = await this.privateHttp.post<OrderWithItems>(\n `/storefront/stores/${storeRef}/orders`,\n data\n );\n return unwrap(res);\n }\n\n /**\n * Lists the signed-in customer's orders, newest first by default.\n *\n * @param storeRef - the store's ref or handle\n * @param params - search, status filter, sorting and paging (`page`, or `limit` and `offset`)\n * @returns A page of orders; throws {@link ApiClientError} when the API answers with an error\n */\n async listCustomerOrders(\n storeRef: string,\n params: Partial<CustomerOrderFilter> & { page?: number } = {}\n ): Promise<PaginatedResponse<Order>> {\n const limit = params.limit ?? 10;\n const page =\n params.page ??\n (params.offset ? Math.floor((params.offset as number) / limit) + 1 : 1);\n const offset = params.offset ?? (page - 1) * limit;\n const query = stringify({\n search: params.search || undefined,\n status: params.status || undefined,\n limit,\n offset,\n include_items: true,\n sort_by: params.sort_by ?? \"created_at\",\n sort_order: params.sort_order ?? \"desc\",\n });\n const res = await this.shopperHttp.get<PaginatedResponse<Order>>(\n `/storefront/stores/${storeRef}/customers/orders${query ? `?${query}` : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Full detail for one of the authenticated customer's orders. The API\n * verifies ownership and returns 404 — not 403 — for someone else's order.\n */\n async getCustomerOrder(\n storeRef: string,\n orderId: Id\n ): Promise<OrderWithItems & WithMetafields> {\n const res = await this.shopperHttp.get<OrderWithItems & WithMetafields>(\n `/storefront/stores/${storeRef}/customers/orders/${orderId}`\n );\n return unwrap(res);\n }\n\n /**\n * Customers may only cancel orders that are still pending, confirmed or\n * processing; the API rejects anything else with ORDER_NOT_CANCELLABLE.\n */\n async cancelCustomerOrder(storeRef: string, orderId: Id): Promise<Order> {\n const res = await this.shopperHttp.delete<Order>(\n `/storefront/stores/${storeRef}/customers/orders/${orderId}`\n );\n return unwrap(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap, unwrapOrNull } from \"../../core/response\";\nimport type { PaginatedResponse } from \"../../types\";\nimport type {\n BlogPost,\n BlogCategory,\n BlogTag,\n BlogPostQueryParams,\n BlogCategoryQueryParams,\n BlogTagQueryParams,\n} from \"./types\";\n\n/**\n * Published blog posts, categories, tags and comments of a store, reached through `sdk.blog`.\n */\nexport class BlogApi {\n /** Client for the public routes, sent with the publishable key. */\n protected publicHttp: IHttpClient;\n /** Client for the calls that read the shopper's session (comments), sent with the shopper's bearer. */\n protected authHttp: IHttpClient;\n\n constructor(publicHttp: IHttpClient, authHttp: IHttpClient) {\n this.publicHttp = publicHttp;\n this.authHttp = authHttp;\n }\n\n /**\n * Lists published blog posts.\n *\n * @param storeRef - the store's ref or handle\n * @param query - filters, sorting and paging\n * @returns A page of posts; throws {@link ApiClientError} when the API answers with an error\n */\n async getPosts(\n storeRef: string,\n query: Partial<BlogPostQueryParams> = {}\n ): Promise<PaginatedResponse<BlogPost>> {\n const qsStr = stringify(query);\n const res = await this.publicHttp.get<PaginatedResponse<BlogPost>>(\n `/storefront/stores/${storeRef}/blog/posts${qsStr ? \"?\" + qsStr : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Gets one published blog post by its slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the post slug\n * @param options - `incrementView` counts a view; `include_seo_metadata` and `include_products` add those fields\n * @returns The post, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getPostBySlug(\n storeRef: string,\n slug: string,\n options: {\n incrementView?: boolean;\n include_seo_metadata?: boolean;\n include_products?: boolean;\n } = {}\n ): Promise<BlogPost | null> {\n const query = stringify({\n increment_view: options.incrementView,\n include_seo_metadata: options.include_seo_metadata,\n include_products: options.include_products,\n });\n const res = await this.publicHttp.get<BlogPost>(\n `/storefront/stores/${storeRef}/blog/posts/slug/${encodeURIComponent(slug)}${query ? `?${query}` : \"\"}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Lists blog categories.\n *\n * @param storeRef - the store's ref or handle\n * @param query - filters and paging\n * @returns A page of categories; throws {@link ApiClientError} when the API answers with an error\n */\n async getCategories(\n storeRef: string,\n query: BlogCategoryQueryParams = {}\n ): Promise<PaginatedResponse<BlogCategory>> {\n const qsStr = stringify(query);\n const res = await this.publicHttp.get<PaginatedResponse<BlogCategory>>(\n `/storefront/stores/${storeRef}/blog/categories${qsStr ? \"?\" + qsStr : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists blog tags.\n *\n * @param storeRef - the store's ref or handle\n * @param query - filters and paging\n * @returns A page of tags; throws {@link ApiClientError} when the API answers with an error\n */\n async getTags(\n storeRef: string,\n query: BlogTagQueryParams = {}\n ): Promise<PaginatedResponse<BlogTag>> {\n const qsStr = stringify(query);\n const res = await this.publicHttp.get<PaginatedResponse<BlogTag>>(\n `/storefront/stores/${storeRef}/blog/tags${qsStr ? \"?\" + qsStr : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the approved comments of a post, as an anonymous visitor.\n *\n * @param storeRef - the store's ref or handle\n * @param postId - the post id\n * @returns The comments; throws {@link ApiClientError} when the API answers with an error\n */\n async getPostComments(storeRef: string, postId: number): Promise<any[]> {\n const res = await this.publicHttp.get<any[]>(\n `/storefront/stores/${storeRef}/blog/posts/${postId}/comments`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the approved comments of a post, sending the signed-in customer's credentials.\n *\n * @param storeRef - the store's ref or handle\n * @param postId - the post id\n * @returns The comments; throws {@link ApiClientError} when the API answers with an error\n */\n async getPostCommentsAuth(storeRef: string, postId: number): Promise<any[]> {\n const res = await this.authHttp.get<any[]>(\n `/storefront/stores/${storeRef}/blog/posts/${postId}/comments`\n );\n return unwrap(res);\n }\n}\n\n/**\n * Blog comment submission, reached through `sdk.blog` on the server and proxied SDKs.\n *\n * Needs a storefront secret key: available on `createEcomwebServerSdk` and `createEcomwebProxiedSdk`, never on `createEcomwebSdk`.\n */\nexport class BlogServerApi extends BlogApi {\n\n /**\n * Submits a comment on a post, as the signed-in customer. It may wait for moderation.\n *\n * @param storeRef - the store's ref or handle\n * @param postId - the post id\n * @param data - the author name, the text, and optionally a website and the parent comment id\n * @returns The created comment; throws {@link ApiClientError} when the API answers with an error\n */\n async submitComment(\n storeRef: string,\n postId: number,\n data: {\n author_name: string;\n content: string;\n author_website?: string;\n parent_comment_id?: number;\n }\n ): Promise<any> {\n const res = await this.authHttp.post<any>(\n `/storefront/stores/${storeRef}/blog/posts/${postId}/comments`,\n data\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient, RequestOptions } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { Store, StoreByDomainInfo, StoreConfigurationInfo } from \"./types\";\n\n/**\n * Looking up a store and its public configuration, reached through `sdk.stores`.\n */\nexport class StoresApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Gets a store's public information, by default with its configuration, settings and embedded scripts.\n *\n * @param storeRef - the store's ref or handle\n * @param options - set `includeConfig`, `includeSettings` or `includeEmbeddedScripts` to `false` to leave that part out\n * @param requestOptions - extra request options, passed to the HTTP client only when given\n * @returns The store information, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(\n storeRef: string,\n options?: {\n includeConfig?: boolean;\n includeSettings?: boolean;\n includeEmbeddedScripts?: boolean;\n },\n requestOptions?: RequestOptions\n ): Promise<StoreConfigurationInfo | null> {\n const params = new URLSearchParams();\n if (options?.includeConfig ?? true) params.set(\"include_config\", \"1\");\n if (options?.includeSettings ?? true) params.set(\"include_settings\", \"1\");\n if (options?.includeEmbeddedScripts ?? true)\n params.set(\"include_embedded_scripts\", \"1\");\n const qs = params.toString();\n const url = `/storefront/stores/${storeRef}${qs ? `?${qs}` : \"\"}`;\n // Request options (as for getByDomain) reach the client only when given.\n const res = requestOptions\n ? await this.http.get<StoreConfigurationInfo>(url, requestOptions)\n : await this.http.get<StoreConfigurationInfo>(url);\n return unwrapOrNull(res);\n }\n\n /**\n * Gets a store by its subdomain.\n *\n * @param subdomain - the store's subdomain\n * @returns The store, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getBySubdomain(subdomain: string): Promise<Store | null> {\n const res = await this.http.get<Store>(\n `/storefront/stores/exists/subdomain/${subdomain}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * The store `domain` serves. `options` (e.g. an `x-store-preview` header,\n * which opens a coming soon store) is passed to the client only when given.\n */\n async getByDomain(\n domain: string,\n options?: RequestOptions\n ): Promise<StoreByDomainInfo | null> {\n const url = `/storefront/stores/domain/${domain}`;\n const res = options\n ? await this.http.get<StoreByDomainInfo>(url, options)\n : await this.http.get<StoreByDomainInfo>(url);\n return unwrapOrNull(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { PublishedStoreTheme } from \"../stores/types\";\n\n/** Refusals that mean \"no preview\": bad, expired or foreign token, or previews off. */\nconst NO_PREVIEW = [400, 401, 403, 404, 503];\n\n/**\n * Theme previews opened from the dashboard, reached through `sdk.themes`.\n */\nexport class ThemesApi {\n constructor(private http: IHttpClient) {}\n\n /** The store theme a dashboard preview link points to; null if refused. */\n async getPreview(\n storeRef: string,\n token: string\n ): Promise<PublishedStoreTheme | null> {\n const res = await this.http.get<PublishedStoreTheme>(\n `/storefront/stores/${storeRef}/theme-preview?token=${encodeURIComponent(token)}`\n );\n return unwrapOrNull(res, NO_PREVIEW);\n }\n\n /** The theme on a preview host, p-<slug>, with its saved values. */\n async getPreviewBySlug(\n storeRef: string,\n slug: string\n ): Promise<PublishedStoreTheme | null> {\n const res = await this.http.get<PublishedStoreTheme>(\n `/storefront/stores/${storeRef}/theme-preview?slug=${encodeURIComponent(slug)}`\n );\n return unwrapOrNull(res, NO_PREVIEW);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { StorefrontMetaobjectEntry } from \"../../types/metafields\";\nimport type { MetaobjectListParams, MetaobjectListResult } from \"./types\";\n\nconst EMPTY: MetaobjectListResult = { items: [], next_cursor: null };\n\n/**\n * Custom structured content (metaobject entries) a store publishes, reached through `sdk.metaobjects`.\n */\nexport class MetaobjectsApi {\n constructor(\n private publicHttp: IHttpClient,\n private authHttp: IHttpClient\n ) {}\n\n /**\n * Active entries of a metaobject type. A type that is unknown or hidden\n * from this reader lists as empty: the API answers 404 for both, the same\n * as a missing type, so it never reveals which types exist.\n */\n async list(\n storeRef: string,\n type: string,\n params: MetaobjectListParams = {}\n ): Promise<MetaobjectListResult> {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(params.filter ?? {})) {\n query.append(`filter[${key}]`, String(value));\n }\n if (params.cursor) query.set(\"cursor\", params.cursor);\n if (params.limit !== undefined) query.set(\"limit\", String(params.limit));\n const search = query.toString();\n const http = params.as_customer ? this.authHttp : this.publicHttp;\n const res = await http.get<MetaobjectListResult>(\n `/storefront/stores/${storeRef}/metaobjects/${encodeURIComponent(type)}${search ? `?${search}` : \"\"}`\n );\n return unwrapOrNull(res, [404]) ?? EMPTY;\n }\n\n /** One active entry by handle; null when it, or its type, is missing or hidden. */\n async get(\n storeRef: string,\n type: string,\n handle: string,\n options: { as_customer?: boolean } = {}\n ): Promise<StorefrontMetaobjectEntry | null> {\n const http = options.as_customer ? this.authHttp : this.publicHttp;\n const res = await http.get<StorefrontMetaobjectEntry>(\n `/storefront/stores/${storeRef}/metaobjects/${encodeURIComponent(type)}/${encodeURIComponent(handle)}`\n );\n return unwrapOrNull(res, [404]);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n ProductSearchParams,\n AutocompleteParams,\n ProductSearchResponse,\n BlogSearchParams,\n BlogSearchResponse,\n} from \"./types\";\n\n/**\n * Search over a store's products and blog posts, reached through `sdk.search`.\n */\nexport class SearchApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Searches products.\n *\n * @param storeRef - the store's ref or handle\n * @param params - the query, filters and paging\n * @returns The matching products; throws {@link ApiClientError} when the API answers with an error\n */\n async searchCatalog(\n storeRef: string,\n params: ProductSearchParams\n ): Promise<ProductSearchResponse> {\n const queryString = stringify(params);\n const res = await this.http.get<ProductSearchResponse>(\n `/storefront/stores/${storeRef}/search/catalog${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Suggests product matches while the shopper is typing.\n *\n * @param storeRef - the store's ref or handle\n * @param params - the partial query and the suggestion limit\n * @returns The suggestions; throws {@link ApiClientError} when the API answers with an error\n */\n async autocompleteCatalog<T>(\n storeRef: string,\n params: AutocompleteParams\n ): Promise<T> {\n const queryString = stringify(params);\n const res = await this.http.get<T>(\n `/storefront/stores/${storeRef}/search/catalog/autocomplete${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n\n /**\n * Searches published blog posts.\n *\n * @param storeRef - the store's ref or handle\n * @param params - the query and paging\n * @returns The matching posts; throws {@link ApiClientError} when the API answers with an error\n */\n async searchBlog(\n storeRef: string,\n params: BlogSearchParams\n ): Promise<BlogSearchResponse> {\n const queryString = stringify(params);\n const res = await this.http.get<BlogSearchResponse>(\n `/storefront/stores/${storeRef}/search/blog${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n LocationAreaQuery,\n LocationAreasResponse,\n ShippingCalculationRequest,\n ShippingOption,\n} from \"./types\";\n\n/**\n * Shipping areas and shipping rates for a store, reached through `sdk.shipping`.\n */\nexport class ShippingApi {\n /** Client for the public routes, sent with the publishable key. */\n protected publicHttp: IHttpClient;\n\n constructor(publicHttp: IHttpClient) {\n this.publicHttp = publicHttp;\n }\n\n /**\n * List administrative areas. Pass `level` for one tier or `parent_code`\n * for one area's children; passing neither returns every area, which for\n * Vietnam is 3,355 rows and about 900 KB. Prefer a filter.\n */\n async listLocationAreas(\n storeRef: string,\n query: LocationAreaQuery = {}\n ): Promise<LocationAreasResponse> {\n const params = new URLSearchParams();\n if (query.level !== undefined) params.set(\"level\", String(query.level));\n if (query.parent_code) params.set(\"parent_code\", query.parent_code);\n const qs = params.toString();\n\n const res = await this.publicHttp.get<LocationAreasResponse>(\n `/storefront/stores/${storeRef}/shipping/locations${qs ? `?${qs}` : \"\"}`\n );\n return unwrap(res);\n }\n}\n\n/**\n * Shipping rates for a cart, reached through `sdk.shipping` on the server and proxied SDKs.\n *\n * Needs a storefront secret key: available on `createEcomwebServerSdk` and `createEcomwebProxiedSdk`, never on `createEcomwebSdk`.\n */\nexport class ShippingServerApi extends ShippingApi {\n constructor(publicHttp: IHttpClient, private privateHttp: IHttpClient) {\n super(publicHttp);\n }\n\n /**\n * Works out the shipping options and prices for a cart and a destination.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the destination and the cart contents\n * @returns The available shipping options; throws {@link ApiClientError} when the API answers with an error\n */\n async calculate(\n storeRef: string,\n data: ShippingCalculationRequest\n ): Promise<ShippingOption[]> {\n const res = await this.privateHttp.post<ShippingOption[]>(\n `/storefront/stores/${storeRef}/shipping/calculate`,\n data\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n ValidatePromotionCodeRequest,\n ValidatePromotionCodeResponse,\n PromotionSuggestionsResponse,\n} from \"./types\";\n\n/**\n * Promotion codes and offers of a store, reached through `sdk.promotions`.\n */\nexport class PromotionsApi {\n /** Client for the public routes, sent with the publishable key. */\n protected publicHttp: IHttpClient;\n\n constructor(publicHttp: IHttpClient) {\n this.publicHttp = publicHttp;\n }\n\n /**\n * Lists promotions the shopper could use, optionally for a given cart subtotal.\n *\n * @param storeRef - the store's ref or handle\n * @param subtotal - the cart subtotal in the store's currency\n * @returns The suggested promotions; throws {@link ApiClientError} when the API answers with an error\n */\n async getSuggestions(\n storeRef: string,\n subtotal?: number\n ): Promise<PromotionSuggestionsResponse> {\n const params = new URLSearchParams();\n if (subtotal !== undefined) params.append(\"subtotal\", subtotal.toString());\n const res = await this.publicHttp.get<PromotionSuggestionsResponse>(\n `/storefront/stores/${storeRef}/promotions/suggestions?${params.toString()}`\n );\n return unwrap(res);\n }\n}\n\n/**\n * Promotion code checks, reached through `sdk.promotions` on the server and proxied SDKs.\n *\n * Needs a storefront secret key: available on `createEcomwebServerSdk` and `createEcomwebProxiedSdk`, never on `createEcomwebSdk`.\n */\nexport class PromotionsServerApi extends PromotionsApi {\n constructor(publicHttp: IHttpClient, private privateHttp: IHttpClient) {\n super(publicHttp);\n }\n\n /**\n * Checks a promotion code against a cart.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the code and the cart details\n * @returns The validation result; throws {@link ApiClientError} when the API answers with an error\n */\n async validate(\n storeRef: string,\n data: ValidatePromotionCodeRequest\n ): Promise<ValidatePromotionCodeResponse> {\n const res = await this.privateHttp.post<ValidatePromotionCodeResponse>(\n `/storefront/stores/${storeRef}/promotions/validate`,\n data\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { PaymentMethod } from \"./types\";\n\n/**\n * The payment methods a store accepts, reached through `sdk.paymentMethods`.\n */\nexport class PaymentMethodsApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists the payment methods the store has turned on.\n *\n * @param storeRef - the store's ref or handle\n * @returns The enabled payment methods; throws {@link ApiClientError} when the API answers with an error\n */\n async getEnabled(storeRef: string): Promise<PaymentMethod[]> {\n const res = await this.http.get<PaymentMethod[]>(\n `/storefront/stores/${storeRef}/payment-methods`\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { InitiatePaymentResult, PaymentStateResult } from \"./types\";\n\n/**\n * Storefront-facing payment operations — starting a gateway charge and\n * polling its outcome. Deliberately separate from `PaymentMethodsApi`\n * (method listing) and from anything credential-related: the admin\n * credential surface is typed here (see ./types) but has no client method,\n * since the dashboard talks to it directly and this SDK must never carry a\n * plaintext credential shape.\n *\n * Both endpoints need a storefront secret key, so both go through the one\n * private HTTP client (the server SDK's, or the proxy's), never the public one.\n */\nexport class PaymentsApi {\n constructor(private privateHttp: IHttpClient) {}\n\n /**\n * Start a gateway charge attempt for an order. Keyed by `order_code`,\n * never `order_id` — the API route was deliberately re-keyed away from a\n * sequential id, since StorefrontApiKeyGuard authenticates the store\n * rather than the shopper and a raw id would let anyone enumerate a\n * store's orders.\n */\n async initiate(\n storeRef: string,\n input: { order_code: string; provider_code: string },\n ): Promise<InitiatePaymentResult> {\n const res = await this.privateHttp.post<InitiatePaymentResult>(\n `/storefront/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code },\n );\n return unwrap(res);\n }\n\n /**\n * Poll payment/order status for an order while waiting on a gateway\n * redirect or callback. `order_code` is URL-encoded: order codes contain\n * `#` by default in this system, and an unencoded `#` truncates the URL.\n */\n async getPaymentState(\n storeRef: string,\n order_code: string,\n ): Promise<PaymentStateResult> {\n const res = await this.privateHttp.get<PaymentStateResult>(\n `/storefront/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`,\n );\n return unwrap(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type {\n PaginatedReviewsResponse,\n ProductReviewFilters,\n ReviewInvitationPublicData,\n SubmitReviewInvitationPayload,\n OrderReviewInvitationSummary,\n BatchOrderReviewInvitationsResult,\n} from \"./types\";\n\n/**\n * Product reviews and the invitations that ask customers to write them, reached through `sdk.reviews`.\n */\nexport class ReviewsApi {\n /** Client for the public routes, sent with the publishable key. */\n protected publicHttp: IHttpClient;\n\n constructor(publicHttp: IHttpClient) {\n this.publicHttp = publicHttp;\n }\n\n /**\n * Lists the published reviews of a product.\n *\n * @param storeRef - the store's ref or handle\n * @param productId - the product id\n * @param query - filters and paging\n * @returns A page of reviews; throws {@link ApiClientError} when the API answers with an error\n */\n async getProductReviews(\n storeRef: string,\n productId: string | number,\n query?: Omit<ProductReviewFilters, \"product_id\">\n ): Promise<PaginatedReviewsResponse> {\n const queryString = stringify(query ?? {});\n const res = await this.publicHttp.get<PaginatedReviewsResponse>(\n `/storefront/stores/${storeRef}/products/${productId}/reviews${queryString ? `?${queryString}` : \"\"}`\n );\n return unwrap(res);\n }\n}\n\n/**\n * The review invitation calls, reached through `sdk.reviews` on the server and proxied SDKs.\n *\n * Needs a storefront secret key: available on `createEcomwebServerSdk` and `createEcomwebProxiedSdk`, never on `createEcomwebSdk`.\n */\nexport class ReviewsServerApi extends ReviewsApi {\n constructor(publicHttp: IHttpClient, private privateHttp: IHttpClient) {\n super(publicHttp);\n }\n\n /**\n * Gets the public details behind a review invitation link.\n *\n * @param storeRef - the store's ref or handle\n * @param token - the token from the invitation link\n * @returns The invitation details; throws {@link ApiClientError} when the API answers with an error\n */\n async getReviewInvitation(\n storeRef: string,\n token: string\n ): Promise<ReviewInvitationPublicData> {\n const res = await this.privateHttp.get<ReviewInvitationPublicData>(\n `/storefront/stores/${storeRef}/review-invitations/${token}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the review invitations for one order.\n *\n * @param storeRef - the store's ref or handle\n * @param orderNumber - the order number\n * @param email - the email address on the order\n * @returns The invitation summaries; throws {@link ApiClientError} when the API answers with an error\n */\n async getOrderReviewInvitations(\n storeRef: string,\n orderNumber: number | string,\n email: string\n ): Promise<OrderReviewInvitationSummary[]> {\n const queryString = stringify({ order_number: orderNumber, email });\n const res = await this.privateHttp.get<OrderReviewInvitationSummary[]>(\n `/storefront/stores/${storeRef}/review-invitations/by-order?${queryString}`\n );\n return unwrap(res);\n }\n\n /**\n * Lists the review invitations for several orders at once.\n *\n * @param storeRef - the store's ref or handle\n * @param orderNumbers - the order numbers\n * @param email - the email address on the orders\n * @returns The invitations grouped by order; throws {@link ApiClientError} when the API answers with an error\n */\n async getBatchOrderReviewInvitations(\n storeRef: string,\n orderNumbers: (number | string)[],\n email: string\n ): Promise<BatchOrderReviewInvitationsResult> {\n const queryString = stringify({ order_numbers: orderNumbers.join(\",\"), email });\n const res = await this.privateHttp.get<BatchOrderReviewInvitationsResult>(\n `/storefront/stores/${storeRef}/review-invitations/by-orders?${queryString}`\n );\n return unwrap(res);\n }\n\n /**\n * Submits a review through an invitation link.\n *\n * @param storeRef - the store's ref or handle\n * @param token - the token from the invitation link\n * @param payload - the rating and review text\n * @returns The API's answer; throws {@link ApiClientError} when the API answers with an error\n */\n async submitReviewInvitation(\n storeRef: string,\n token: string,\n payload: SubmitReviewInvitationPayload\n ): Promise<any> {\n const res = await this.privateHttp.post(\n `/storefront/stores/${storeRef}/review-invitations/${token}/submit`,\n payload\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient, ApiResponse } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { MetafieldWrite, StorefrontMetafields } from \"../../types/metafields\";\nimport type { Customer, UpsertCustomerForAuthPayload } from \"./types\";\n\n/**\n * The signed-in customer's profile record, reached through `sdk.customers`.\n */\nexport class CustomersApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Creates the customer record for a newly signed-in user, or updates it when it exists.\n *\n * @param storeRef - the store's ref or handle\n * @param payload - the identity fields to store\n * @returns The customer, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async upsertForAuth(\n storeRef: string,\n payload: UpsertCustomerForAuthPayload\n ): Promise<ApiResponse<Customer>> {\n return this.http.post<Customer>(\n `/storefront/stores/${storeRef}/customers/auth/upsert`,\n payload\n );\n }\n\n /** The signed-in customer's metafields with customer access (spec §6.6). */\n async getMetafields(storeRef: string): Promise<StorefrontMetafields> {\n const res = await this.http.get<StorefrontMetafields>(\n `/storefront/stores/${storeRef}/customers/metafields`\n );\n return unwrap(res);\n }\n\n /**\n * Writes read_write metafields; `value: null` clears one. Throws\n * METAFIELD_VALUE_INVALID (details.errors[] by path) or METAFIELD_NOT_WRITABLE.\n */\n async updateMetafields(\n storeRef: string,\n values: MetafieldWrite[]\n ): Promise<StorefrontMetafields> {\n const res = await this.http.put<StorefrontMetafields>(\n `/storefront/stores/${storeRef}/customers/metafields`,\n { values }\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { Address, CreateAddressDto, UpdateAddressDto } from \"./types\";\n\n/**\n * Saved delivery addresses of the signed-in customer, reached through `sdk.addresses`.\n */\nexport class AddressesApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @returns The addresses, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async list(storeRef: string): Promise<Address[] | null> {\n const res = await this.http.get<Address[]>(\n `/storefront/stores/${storeRef}/customers/address`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Gets one of the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @returns The address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getById(storeRef: string, addressId: number): Promise<Address | null> {\n const res = await this.http.get<Address>(\n `/storefront/stores/${storeRef}/customers/address/${addressId}`\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Saves a new address for the signed-in customer.\n *\n * @param storeRef - the store's ref or handle\n * @param data - the address fields\n * @returns The created address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async create(\n storeRef: string,\n data: CreateAddressDto\n ): Promise<Address | null> {\n const res = await this.http.post<Address>(\n `/storefront/stores/${storeRef}/customers/address`,\n data\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Updates one of the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @param data - the fields to change\n * @returns The updated address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async update(\n storeRef: string,\n addressId: number,\n data: UpdateAddressDto\n ): Promise<Address | null> {\n const res = await this.http.patch<Address>(\n `/storefront/stores/${storeRef}/customers/address/${addressId}`,\n data\n );\n return unwrapOrNull(res);\n }\n\n /**\n * Deletes one of the signed-in customer's saved addresses.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @returns `true` when the API accepted the deletion, `false` otherwise; it does not throw\n */\n async delete(storeRef: string, addressId: number): Promise<boolean> {\n const res = await this.http.delete(\n `/storefront/stores/${storeRef}/customers/address/${addressId}`\n );\n return res.success;\n }\n\n /**\n * Makes a saved address the customer's default.\n *\n * @param storeRef - the store's ref or handle\n * @param addressId - the address id\n * @returns The updated address, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async setDefault(\n storeRef: string,\n addressId: number\n ): Promise<Address | null> {\n const res = await this.http.patch<Address>(\n `/storefront/stores/${storeRef}/customers/address/${addressId}/set-default`\n );\n return unwrapOrNull(res);\n }\n}\n","import { stringify } from \"../../core/stringify\";\nimport type { IHttpClient } from \"../../core/types\";\nimport { unwrap } from \"../../core/response\";\nimport type { PaginatedResponse } from \"../../types\";\nimport type { ContentPage } from \"./types\";\n\n/**\n * Static content pages of a store, such as About or Shipping policy, reached through `sdk.contentPages`.\n */\nexport class ContentPagesApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Lists the published content pages.\n *\n * @param storeRef - the store's ref or handle\n * @returns A page of content pages; throws {@link ApiClientError} when the API answers with an error\n */\n async getPublished(\n storeRef: string\n ): Promise<PaginatedResponse<ContentPage>> {\n const res = await this.http.get<PaginatedResponse<ContentPage>>(\n `/storefront/stores/${storeRef}/content-pages`\n );\n return unwrap(res);\n }\n\n /**\n * Gets one published content page by slug.\n *\n * @param storeRef - the store's ref or handle\n * @param slug - the page slug\n * @param query - `include_seo_metadata` adds the SEO fields\n * @returns The page; throws {@link ApiClientError} when the API answers with an error\n */\n async getBySlug(\n storeRef: string,\n slug: string,\n query?: { include_seo_metadata?: boolean }\n ): Promise<ContentPage> {\n const queryString = query ? stringify(query) : \"\";\n const res = await this.http.get<ContentPage>(\n `/storefront/stores/${storeRef}/content-pages/${encodeURIComponent(slug)}${queryString ? \"?\" + queryString : \"\"}`\n );\n return unwrap(res);\n }\n}\n","import type { IHttpClient } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { StoreMenu } from \"./types\";\n\n/**\n * Navigation menus of a store, reached through `sdk.menus`.\n */\nexport class MenusApi {\n constructor(private http: IHttpClient) {}\n\n /**\n * Gets a navigation menu by its ref.\n *\n * @param storeRef - the store's ref or handle\n * @param ref - the menu ref\n * @param includeItems - `true` (the default) includes the menu items\n * @returns The menu, or `null` when it is not found; throws {@link ApiClientError} on any other API error\n */\n async getByRef(\n storeRef: string,\n ref: string,\n includeItems = true\n ): Promise<StoreMenu | null> {\n const query = includeItems ? \"?include_items=true\" : \"\";\n const res = await this.http.get<StoreMenu>(\n `/storefront/stores/${storeRef}/menus/ref/${encodeURIComponent(ref)}${query}`\n );\n return unwrapOrNull(res);\n }\n}\n","import type { IHttpClient, RequestOptions } from \"../../core/types\";\nimport { unwrapOrNull } from \"../../core/response\";\nimport type { UrlRedirect } from \"./types\";\n\n/**\n * URL redirects a store has set up, reached through `sdk.redirects`.\n */\nexport class RedirectsApi {\n constructor(private http: IHttpClient) {}\n\n /** `options` (request options) are passed to the client only when given. */\n async lookup(\n storeRef: string,\n path: string,\n options?: RequestOptions\n ): Promise<UrlRedirect | null> {\n const params = new URLSearchParams();\n params.set(\"path\", path);\n const url = `/storefront/stores/${storeRef}/url-redirects/lookup?${params.toString()}`;\n const res = options\n ? await this.http.get<{ data: UrlRedirect | null }>(url, options)\n : await this.http.get<{ data: UrlRedirect | null }>(url);\n const result = unwrapOrNull(res);\n return result?.data ?? null;\n }\n}\n","import type { ApiResponse, IHttpClient, RequestOptions } from \"../../core/types\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangeEmailResult,\n ChangePasswordPayload,\n ChangedResult,\n CurrentIdentity,\n GoogleAuthUrl,\n LoginPayload,\n PublicAuthConfig,\n RegisterPayload,\n RegisterResult,\n ResetPasswordPayload,\n ResetResult,\n SentResult,\n VerifiedResult,\n VerifyOtpPayload,\n} from \"./types\";\n\n/**\n * One store's auth surface.\n *\n * Every route lives under `/storefront/stores/<ref>/auth/`. Token routes\n * (`me`, `logout`, ...) require an access token and assert that the token's\n * store_id matches the route's store; the rest are unauthenticated and throttled.\n *\n * This class does not supply `x-storefront-api-key` — StorefrontApiKeyGuard\n * requires it on every route, and the injected IHttpClient owns that header.\n */\nexport class AuthApi {\n constructor(\n private http: IHttpClient,\n private storeRef: string,\n ) {}\n\n private publicPath(suffix: string): string {\n return `/storefront/stores/${encodeURIComponent(this.storeRef)}/auth/${suffix}`;\n }\n\n private tenantPath(suffix: string): string {\n return `/storefront/stores/${encodeURIComponent(this.storeRef)}/auth/${suffix}`;\n }\n\n private auth(access_token: string): RequestOptions {\n return { headers: { Authorization: `Bearer ${access_token}` } };\n }\n\n // ---- unauthenticated -------------------------------------------------\n\n /** Never returns tokens: a new email and an existing one respond identically. */\n async register(payload: RegisterPayload): Promise<ApiResponse<RegisterResult>> {\n return this.http.post<RegisterResult>(this.publicPath(\"register\"), payload, undefined);\n }\n\n /**\n * Signs a customer in with email and password.\n *\n * @param payload - the login credentials\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async login(payload: LoginPayload): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(this.publicPath(\"login\"), payload, undefined);\n }\n\n /**\n * Exchanges a refresh token for a new token pair. The old refresh token stops working.\n *\n * @param refresh_token - the customer's current refresh token\n * @returns The new token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async refresh(refresh_token: string): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(\n this.publicPath(\"refresh\"),\n { refresh_token },\n undefined,\n );\n }\n\n /**\n * `binding` is the register response's `verification_binding`, when this\n * client still has it. Omitted, the address is verified but the password\n * set at registration is dropped.\n */\n async verifyEmail(\n token: string,\n binding?: string,\n ): Promise<ApiResponse<VerifiedResult>> {\n return this.http.post<VerifiedResult>(\n this.publicPath(\"verify-email\"),\n binding ? { token, binding } : { token },\n undefined,\n );\n }\n\n /**\n * Sends the email-verification message again.\n *\n * @param email - the address to verify\n * @returns The send result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async resendVerification(email: string): Promise<ApiResponse<SentResult>> {\n return this.http.post<SentResult>(\n this.publicPath(\"resend-verification\"),\n { email },\n undefined,\n );\n }\n\n /**\n * Starts a password reset by emailing a reset link.\n *\n * @param email - the account's email address\n * @returns The send result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async forgotPassword(email: string): Promise<ApiResponse<SentResult>> {\n return this.http.post<SentResult>(\n this.publicPath(\"forgot-password\"),\n { email },\n undefined,\n );\n }\n\n /**\n * Sets a new password using the token from the reset email.\n *\n * @param payload - the reset token and the new password\n * @returns The reset result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async resetPassword(\n payload: ResetPasswordPayload,\n ): Promise<ApiResponse<ResetResult>> {\n return this.http.post<ResetResult>(\n this.publicPath(\"reset-password\"),\n payload,\n undefined,\n );\n }\n\n /** `binding` is the change-email response's `confirmation_binding`. */\n async confirmEmailChange(\n token: string,\n binding?: string,\n ): Promise<ApiResponse<ChangedResult>> {\n return this.http.post<ChangedResult>(\n this.publicPath(\"change-email/confirm\"),\n binding ? { token, binding } : { token },\n undefined,\n );\n }\n\n /**\n * Emails a one-time sign-in code.\n *\n * @param email - the account's email address\n * @returns The send result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async requestOtp(email: string): Promise<ApiResponse<SentResult>> {\n return this.http.post<SentResult>(\n this.publicPath(\"otp/request\"),\n { email },\n undefined,\n );\n }\n\n /**\n * Signs a customer in with the one-time code from the email.\n *\n * @param payload - the email and the code\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async verifyOtp(payload: VerifyOtpPayload): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(\n this.publicPath(\"otp/verify\"),\n payload,\n undefined,\n );\n }\n\n /**\n * Starts an anonymous (guest) session.\n *\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async anonymous(): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(this.publicPath(\"anonymous\"), undefined, undefined);\n }\n\n /**\n * Gets the URL that starts Google sign-in.\n *\n * @param redirect_to - where to send the customer after sign-in, `/` by default\n * @returns The Google sign-in URL, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async getGoogleUrl(redirect_to = \"/\"): Promise<ApiResponse<GoogleAuthUrl>> {\n const query = `?redirect_to=${encodeURIComponent(redirect_to)}`;\n return this.http.get<GoogleAuthUrl>(\n `${this.publicPath(\"google/url\")}${query}`,\n undefined,\n );\n }\n\n /**\n * Completes Google sign-in by exchanging the authorization code.\n *\n * @param code - the authorization code Google returned\n * @returns The auth result with the token pair, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async exchangeGoogleCode(code: string): Promise<ApiResponse<AuthResult>> {\n return this.http.post<AuthResult>(\n this.publicPath(\"google/exchange\"),\n { code },\n undefined,\n );\n }\n\n /**\n * Reads which sign-in methods this store has turned on.\n *\n * @returns The public auth configuration, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async getAuthConfig(): Promise<ApiResponse<PublicAuthConfig>> {\n return this.http.get<PublicAuthConfig>(this.publicPath(\"config\"), undefined);\n }\n\n // ---- access token required -------------------------------------------\n\n /**\n * Reads the signed-in customer's identity.\n *\n * @param access_token - the signed-in customer's access token\n * @returns The current identity, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async me(access_token: string): Promise<ApiResponse<CurrentIdentity | null>> {\n return this.http.get<CurrentIdentity | null>(\n this.tenantPath(\"me\"),\n this.auth(access_token),\n );\n }\n\n /** Revokes one session. The refresh token identifies which. */\n async logout(\n access_token: string,\n refresh_token: string,\n ): Promise<ApiResponse<unknown>> {\n return this.http.post<unknown>(\n this.tenantPath(\"logout\"),\n { refresh_token },\n this.auth(access_token),\n );\n }\n\n /**\n * Signs the customer out of every session.\n *\n * @param access_token - the signed-in customer's access token\n * @returns The API's answer, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async logoutAll(access_token: string): Promise<ApiResponse<unknown>> {\n return this.http.post<unknown>(\n this.tenantPath(\"logout-all\"),\n undefined,\n this.auth(access_token),\n );\n }\n\n /**\n * Changes the signed-in customer's password.\n *\n * @param access_token - the signed-in customer's access token\n * @param payload - the current and the new password\n * @returns The API's answer, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async changePassword(\n access_token: string,\n payload: ChangePasswordPayload,\n ): Promise<ApiResponse<unknown>> {\n return this.http.post<unknown>(\n this.tenantPath(\"change-password\"),\n payload,\n this.auth(access_token),\n );\n }\n\n /**\n * Starts an email change; the new address must be confirmed from the message sent to it.\n *\n * @param access_token - the signed-in customer's access token\n * @param payload - the new email address and the current password\n * @returns The change-email result, as the raw {@link ApiResponse}; it does not throw, so check `success`\n */\n async changeEmail(\n access_token: string,\n payload: ChangeEmailPayload,\n ): Promise<ApiResponse<ChangeEmailResult>> {\n return this.http.post<ChangeEmailResult>(\n this.tenantPath(\"change-email\"),\n payload,\n this.auth(access_token),\n );\n }\n}\n","import type { AuthTokens } from \"./types\";\n\n/**\n * Where a consumer keeps the token pair.\n *\n * Supplied by the consumer, not chosen by the SDK: the three runtimes the SDK\n * targets (server components, route handlers, browser) each need a different\n * mechanism, and two of the three break under any hardcoded choice.\n */\nexport interface TokenStorage {\n get(): Promise<AuthTokens | null>;\n set(tokens: AuthTokens): Promise<void>;\n clear(): Promise<void>;\n}\n\n/** Process-local. Suitable for tests and for a single server-side request. */\nexport class MemoryTokenStorage implements TokenStorage {\n private tokens: AuthTokens | null;\n\n constructor(initial: AuthTokens | null = null) {\n this.tokens = initial;\n }\n\n /**\n * Reads the stored token pair.\n *\n * @returns The stored tokens, or `null` when none are stored\n */\n async get(): Promise<AuthTokens | null> {\n return this.tokens;\n }\n\n /**\n * Stores a token pair, replacing any earlier one.\n *\n * @param tokens - the access and refresh tokens\n */\n async set(tokens: AuthTokens): Promise<void> {\n this.tokens = tokens;\n }\n\n /**\n * Forgets the stored token pair.\n */\n async clear(): Promise<void> {\n this.tokens = null;\n }\n}\n","import type { ApiResponse, IHttpClient, RequestOptions } from \"../../core/types\";\nimport type { AuthApi } from \"./api\";\nimport type { TokenStorage } from \"./token-storage\";\n\ninterface Options {\n storage: TokenStorage;\n auth: AuthApi;\n}\n\n/**\n * Wraps an IHttpClient so a 401 triggers one refresh and one retry.\n *\n * The single-flight promise is the point of the whole file. Without it, a page\n * that fires five requests behind an expired access token performs five\n * refreshes; the first rotates and revokes the refresh token, and the other\n * four present a token that no longer exists — logging the user out on load.\n */\nexport function createAuthAwareHttpClient(\n inner: IHttpClient,\n { storage, auth }: Options,\n): IHttpClient {\n let inFlight: Promise<boolean> | null = null;\n\n /** Resolves true when storage holds a freshly rotated pair. */\n async function refreshOnce(): Promise<boolean> {\n if (inFlight) return inFlight;\n\n inFlight = (async () => {\n try {\n const current = await storage.get();\n\n // No refresh token means there is nothing to rotate. Clearing here\n // would be wrong: there may be no session at all, and clear() on an\n // empty store is a no-op that hides the distinction.\n if (!current?.refresh_token) return false;\n\n const response = await auth.refresh(current.refresh_token);\n const data = response.success ? response.data : null;\n\n if (!data?.access_token || !data.refresh_token) {\n await storage.clear();\n return false;\n }\n\n await storage.set({\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n });\n\n return true;\n } catch {\n // A network failure mid-refresh leaves the stored pair in an unknown\n // state. Clearing is the safe read: the caller re-authenticates.\n await storage.clear();\n return false;\n } finally {\n inFlight = null;\n }\n })();\n\n return inFlight;\n }\n\n async function withRetry<T>(\n send: () => Promise<ApiResponse<T>>,\n ): Promise<ApiResponse<T>> {\n const first = await send();\n\n if (first.success || first.error?.statusCode !== 401) return first;\n\n const refreshed = await refreshOnce();\n\n if (!refreshed) return first;\n\n // Exactly one retry. A second 401 means the new token is also rejected,\n // which refreshing again cannot fix.\n return send();\n }\n\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n withRetry<T>(() => inner.get<T>(url, options)),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n withRetry<T>(() => inner.post<T>(url, data, options)),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n withRetry<T>(() => inner.put<T>(url, data, options)),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n withRetry<T>(() => inner.patch<T>(url, data, options)),\n delete: <T>(url: string, options?: RequestOptions) =>\n withRetry<T>(() => inner.delete<T>(url, options)),\n };\n}\n","/**\n * Smart collection rule vocabulary — the shared contract between the API and\n * every client that renders or builds collection rules.\n *\n * This is the SINGLE declaration of which fields a merchant may write a rule\n * against and which operators each field accepts. The dashboard renders its\n * field and operator dropdowns from it; the API validates incoming rule sets\n * against its own mirror and rejects anything outside this vocabulary.\n *\n * Deliberately absent: how each field maps onto the search index. That is\n * server implementation detail (a price rule inverts across two index fields,\n * for instance) and must not leak into a client.\n *\n * If you change this, change the API's RULE_MATRIX in\n * src/modules/search/application/utils/collection-rule-set.utils.ts to match.\n * The API cannot import this package (it is a client OF that API, so the\n * dependency would be inverted), so it pins this vocabulary in\n * collection-rule-vocabulary.contract.spec.ts instead: changing RULE_MATRIX\n * fails that test until the change is mirrored here.\n */\n\nexport type RuleField =\n | \"title\"\n | \"sku\"\n | \"tag\"\n | \"category\"\n | \"attribute\"\n | \"price\"\n | \"rating\"\n | \"stock\"\n | \"promotion\"\n | \"discount\"\n | \"video\"\n | \"sales\"\n | \"sales_30d\"\n | \"status\";\n\nexport type RuleOperator =\n | \"equals\"\n | \"not_equals\"\n | \"any_of\"\n | \"all_of\"\n | \"none_of\"\n | \"in_subtree\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"between\"\n | \"is_true\"\n | \"is_false\";\n\n/** What shape of `value` an operator expects. \"none\" means the operator\n * carries its meaning entirely in its name (is_true / is_false). */\nexport type RuleValueKind =\n | \"none\"\n | \"number\"\n | \"number_pair\"\n | \"number_list\"\n | \"string\"\n | \"string_list\"\n | \"attr_token_list\"\n | \"text\";\n\nexport interface RuleOperatorSpec {\n value_kind: RuleValueKind;\n}\n\nexport interface RuleFieldSpec {\n operators: Readonly<Record<string, RuleOperatorSpec>>;\n /** When present, a string value must be one of these. */\n allowed_values?: readonly string[];\n}\n\nexport interface CollectionRule {\n field: RuleField;\n op: RuleOperator;\n value?: string | number | string[] | number[];\n}\n\nexport interface CollectionRuleSet {\n /** \"all\" ANDs the rules, \"any\" ORs them. Defaults to \"all\". */\n match: \"all\" | \"any\";\n /** An empty list means every product. */\n rules: CollectionRule[];\n}\n\n/** A collection's search_criteria once it carries rule-model criteria. */\nexport interface CollectionRuleSetCriteria {\n rule_set: CollectionRuleSet;\n}\n\n/**\n * `title` and `sku` offer `equals` only — no `contains`, `ends_with`, or\n * `starts_with`. Verified against Typesense 29.0: filter_by on a string field\n * does case-insensitive TOKEN CONTAINMENT, not prefix matching, and a\n * trailing `*` is silently ignored (`` name:`jeans*` `` returns the same rows\n * as `` name:`jeans` ``, while `` name:`jean*` `` returns nothing). Offering\n * `starts_with` would show a merchant an operator whose label lies about what\n * the server actually does.\n */\nexport const COLLECTION_RULE_MATRIX = {\n title: {\n operators: {\n equals: { value_kind: \"text\" },\n },\n },\n sku: {\n operators: {\n equals: { value_kind: \"text\" },\n },\n },\n tag: {\n operators: {\n any_of: { value_kind: \"number_list\" },\n all_of: { value_kind: \"number_list\" },\n none_of: { value_kind: \"number_list\" },\n },\n },\n category: {\n operators: {\n equals: { value_kind: \"string\" },\n not_equals: { value_kind: \"string\" },\n any_of: { value_kind: \"string_list\" },\n // Matches the category and everything beneath it. Compiles against the\n // materialized ancestor paths, so \"all apparel\" no longer means\n // enumerating every leaf.\n in_subtree: { value_kind: \"string\" },\n },\n },\n attribute: {\n operators: {\n any_of: { value_kind: \"attr_token_list\" },\n none_of: { value_kind: \"attr_token_list\" },\n },\n },\n price: {\n operators: {\n gt: { value_kind: \"number\" },\n gte: { value_kind: \"number\" },\n lt: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n between: { value_kind: \"number_pair\" },\n },\n },\n rating: {\n operators: {\n gte: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n },\n },\n stock: {\n operators: {\n is_true: { value_kind: \"none\" },\n is_false: { value_kind: \"none\" },\n },\n },\n promotion: {\n operators: {\n is_true: { value_kind: \"none\" },\n is_false: { value_kind: \"none\" },\n },\n },\n discount: {\n operators: {\n gte: { value_kind: \"number\" },\n },\n },\n video: {\n operators: {\n is_true: { value_kind: \"none\" },\n is_false: { value_kind: \"none\" },\n },\n },\n sales: {\n operators: {\n gte: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n },\n },\n sales_30d: {\n operators: {\n gte: { value_kind: \"number\" },\n lte: { value_kind: \"number\" },\n },\n },\n status: {\n operators: {\n equals: { value_kind: \"string\" },\n not_equals: { value_kind: \"string\" },\n },\n allowed_values: [\"active\", \"draft\", \"archived\"],\n },\n} as const satisfies Record<string, RuleFieldSpec>;\n\n/** Display order for the field selector. */\nexport const RULE_FIELDS: readonly RuleField[] = [\n \"title\",\n \"sku\",\n \"tag\",\n \"category\",\n \"attribute\",\n \"price\",\n \"rating\",\n \"stock\",\n \"promotion\",\n \"discount\",\n \"video\",\n \"sales\",\n \"sales_30d\",\n \"status\",\n];\n\n/** Caps the API enforces. Clients should mirror them so a merchant is told\n * before the request rather than after it is rejected. */\nexport const MAX_RULES_PER_SET = 25;\nexport const MAX_RULE_VALUE_ENTRIES = 100;\n\n/**\n * Tells whether a name is a field that smart collection rules can use.\n *\n * @param name - the name to test\n * @returns `true` when it is a rule field\n */\nexport function isRuleField(name: string): name is RuleField {\n return Object.prototype.hasOwnProperty.call(COLLECTION_RULE_MATRIX, name);\n}\n\n/** The operators a field accepts, in display order. Empty for unknown fields. */\nexport function operatorsForField(field: string): RuleOperator[] {\n if (!isRuleField(field)) return [];\n return Object.keys(\n COLLECTION_RULE_MATRIX[field].operators\n ) as RuleOperator[];\n}\n\n/** The value shape a given field/operator pair expects, or undefined if the\n * field does not accept that operator. */\nexport function valueKindFor(\n field: string,\n op: string\n): RuleValueKind | undefined {\n if (!isRuleField(field)) return undefined;\n const operators = COLLECTION_RULE_MATRIX[field].operators as Record<\n string,\n RuleOperatorSpec\n >;\n return Object.prototype.hasOwnProperty.call(operators, op)\n ? operators[op].value_kind\n : undefined;\n}\n\n/** Values a string-valued field is restricted to, if any. */\nexport function allowedValuesFor(field: string): readonly string[] | undefined {\n if (!isRuleField(field)) return undefined;\n return (\n COLLECTION_RULE_MATRIX[field] as RuleFieldSpec\n ).allowed_values;\n}\n","/**\n * One administrative area, at any depth, for any country. Replaces the\n * old Province/Ward pair: they differed only by which fields were\n * populated, and `level` now carries that distinction (for Vietnam,\n * 1 = province, 2 = ward).\n *\n * The old `id` was the source JSON object's own key, never a stable\n * identifier. Areas are addressed by `code`.\n */\nexport interface LocationArea {\n level: number;\n code: string;\n parent_code: string | null;\n name: string;\n name_with_type: string;\n type: string;\n slug: string;\n /** Null for a top-level area: a province has no path through parents. */\n path: string | null;\n path_with_type: string | null;\n}\n\nexport const LEVEL_PROVINCE = 1;\nexport const LEVEL_WARD = 2;\n\nexport interface LocationAreaQuery {\n /** 1 = province, 2 = ward. */\n level?: number;\n /** Return this area's children, e.g. \"11\" for Ha Noi's wards. */\n parent_code?: string;\n}\n\nexport interface LocationAreasResponse {\n country_code: string;\n areas: LocationArea[];\n}\n\nexport interface ShippingCalculationRequest {\n province_id?: string;\n ward_id?: string;\n province?: string;\n district?: string;\n postal_code?: string;\n subtotal: number;\n currency: string;\n weight_gr: number;\n method?: \"standard\" | \"express\" | \"pickup\" | \"cod\";\n distance_km?: number;\n tags?: string[];\n /** Opt in to live carrier rates alongside fixed ones. Not defaulted by the SDK. */\n include_carrier_options?: boolean;\n}\n\nexport const SHIPPING_DELIVERY_TYPES = [\n \"STANDARD\",\n \"EXPRESS\",\n \"SAME_DAY\",\n \"ECONOMY\",\n \"PICKUP\",\n] as const;\nexport type ShippingDeliveryType = (typeof SHIPPING_DELIVERY_TYPES)[number];\n\n/** FREE is deliberately absent: a free rate is amount 0. */\nexport const SHIPPING_RATE_TYPES = [\"FIXED\", \"CARRIER_QUOTE\"] as const;\nexport type ShippingRateType = (typeof SHIPPING_RATE_TYPES)[number];\n\nexport const SHIPPING_CONDITION_TYPES = [\n \"NONE\",\n \"ORDER_VALUE\",\n \"WEIGHT\",\n] as const;\nexport type ShippingConditionType = (typeof SHIPPING_CONDITION_TYPES)[number];\n\nexport interface ShippingZone {\n id: number;\n code: string;\n name: string;\n provinces: string[];\n wards: string[];\n is_catch_all: boolean;\n}\n\nexport interface ShippingRate {\n id: number;\n zone_id: number;\n delivery_type: ShippingDeliveryType;\n display_name: string;\n rate_type: ShippingRateType;\n amount: number;\n condition_type: ShippingConditionType;\n min_value: number | null;\n max_value: number | null;\n estimated_days_min: number | null;\n estimated_days_max: number | null;\n is_active: boolean;\n sort_order: number;\n}\n\nexport interface ShippingOption {\n amount: number;\n currency: string;\n rate_id: number;\n /** `<rate_id>` for fixed, `<rate_id>:<service_id>` for carrier; absent from APIs before carrier rates. */\n option_id?: string;\n delivery_type: ShippingDeliveryType;\n display_name: string;\n estimated_days_min?: number | null;\n estimated_days_max?: number | null;\n /** Set on carrier-quoted options only. */\n carrier_code?: \"allingo\";\n /** The carrier's own id for the chosen service. */\n carrier_service_id?: string;\n /** Carrier display name, e.g. for a label beside the price. */\n carrier_name?: string;\n /** The carrier's service, e.g. \"Giao chuẩn\"; tells two options of one carrier apart. */\n carrier_service_name?: string;\n /** Carrier logo, or null when the carrier has none. */\n carrier_logo_url?: string | null;\n /** Human-readable delivery estimate from the carrier, or null. */\n estimated_label?: string | null;\n /** Populated only when the caller asks for debug output. */\n zone_id?: number;\n zone_name?: string;\n shadowed_zones?: Array<{ id: number; name: string; rank: number }>;\n}\n\n/** Error codes the shipping endpoints and order creation can return. */\nexport const SHIPPING_ERROR_CODES = {\n QUOTE_CHANGED: \"SHIPPING_QUOTE_CHANGED\",\n RATE_UNAVAILABLE: \"ORDER_SHIPPING_RATE_UNAVAILABLE\",\n} as const;\n\n/** `details` of a SHIPPING_QUOTE_CHANGED error: the options now on offer. */\nexport interface ShippingQuoteChangedDetails {\n options: ShippingOption[];\n}\n","import type { IHttpClient, RequestOptions } from \"./types\";\n\nconst KEY_HEADER = \"x-storefront-api-key\";\n\nfunction withKey(options: RequestOptions | undefined, key: string): RequestOptions {\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(options?.headers ?? {})) {\n if (name.toLowerCase() !== KEY_HEADER) headers[name] = value;\n }\n headers[KEY_HEADER] = key;\n return { ...options, headers };\n}\n\n/**\n * Wraps an HTTP client so every request carries `x-storefront-api-key: <key>`.\n * A key header the caller set, in any casing, is removed: the secret wins.\n */\nexport function withStorefrontKey(http: IHttpClient, key: string): IHttpClient {\n return {\n get: (url, options) => http.get(url, withKey(options, key)),\n post: (url, data, options) => http.post(url, data, withKey(options, key)),\n put: (url, data, options) => http.put(url, data, withKey(options, key)),\n patch: (url, data, options) => http.patch(url, data, withKey(options, key)),\n delete: (url, options) => http.delete(url, withKey(options, key)),\n };\n}\n","import type { IHttpClient } from \"./core/types\";\nimport { withClientHeader } from \"./core/client-info\";\nimport { withStorefrontKey } from \"./core/storefront-key\";\nimport { ProductsApi } from \"./modules/products/api\";\nimport { CollectionsApi } from \"./modules/collections/api\";\nimport { CategoriesApi } from \"./modules/categories/api\";\nimport { CartApi } from \"./modules/cart/api\";\nimport { OrdersApi } from \"./modules/orders/api\";\nimport { BlogApi, BlogServerApi } from \"./modules/blog/api\";\nimport { StoresApi } from \"./modules/stores/api\";\nimport { ThemesApi } from \"./modules/themes/api\";\nimport { MetaobjectsApi } from \"./modules/metaobjects/api\";\nimport { SearchApi } from \"./modules/search/api\";\nimport { ShippingApi, ShippingServerApi } from \"./modules/shipping/api\";\nimport { PromotionsApi, PromotionsServerApi } from \"./modules/promotions/api\";\nimport { PaymentMethodsApi } from \"./modules/payment-methods/api\";\nimport { PaymentsApi } from \"./modules/payments/api\";\nimport { ReviewsApi, ReviewsServerApi } from \"./modules/reviews/api\";\nimport { CustomersApi } from \"./modules/customers/api\";\nimport { AddressesApi } from \"./modules/addresses/api\";\nimport { ContentPagesApi } from \"./modules/content-pages/api\";\nimport { MenusApi } from \"./modules/menus/api\";\nimport { RedirectsApi } from \"./modules/redirects/api\";\n\n/** What {@link createEcomwebSdk} needs: the two HTTP clients, and optional client info. */\nexport interface EcomwebSdkOptions {\n /**\n * Client for the public API routes and the calls that need no shopper\n * session. {@link createEcomwebSdk} sends it as is (with a publishable key);\n * {@link createEcomwebServerSdk} adds the secret key to it.\n */\n publicHttp: IHttpClient;\n /** Client for the routes that need the signed-in customer's credentials. */\n authHttp: IHttpClient;\n /**\n * Tokens put before this SDK's own in the `X-Ecomweb-Client` header\n * (space-separated `name/version`, e.g. `@ecomweb/storefront-kit/0.14.0`).\n */\n clientInfo?: string;\n}\n\n/** What {@link createEcomwebServerSdk} needs: the public options plus the storefront secret key. */\nexport type EcomwebServerSdkOptions = EcomwebSdkOptions & {\n /** The store's storefront secret key (`sk_storefront_...`). Server only; never ship it to a browser. */\n secretKey: string;\n};\n\n/** What {@link createEcomwebProxiedSdk} needs: a direct client for public routes and one that reaches a same-origin proxy. */\nexport interface EcomwebProxiedSdkOptions {\n /** Client for the public API routes, called directly with the publishable key. */\n publicHttp: IHttpClient;\n /** Client that sends private calls to a same-origin proxy, which holds the secret key. */\n proxyHttp: IHttpClient;\n /**\n * Tokens put before this SDK's own in the `X-Ecomweb-Client` header\n * (space-separated `name/version`).\n */\n clientInfo?: string;\n}\n\n/** The public SDK: catalog and content reads, safe with a publishable key. */\nexport interface EcomwebSdk {\n /** Products. */\n products: ProductsApi;\n /** Collections. */\n collections: CollectionsApi;\n /** Categories. */\n categories: CategoriesApi;\n /** Published blog posts, categories, tags and comments. */\n blog: BlogApi;\n /** Stores. */\n stores: StoresApi;\n /** Themes. */\n themes: ThemesApi;\n /** Metaobject entries. */\n metaobjects: MetaobjectsApi;\n /** Search. */\n search: SearchApi;\n /** Shipping locations. */\n shipping: ShippingApi;\n /** Promotion suggestions. */\n promotions: PromotionsApi;\n /** Payment methods a store accepts. */\n paymentMethods: PaymentMethodsApi;\n /** Product reviews (reads). */\n reviews: ReviewsApi;\n /** Content pages. */\n contentPages: ContentPagesApi;\n /** Menus. */\n menus: MenusApi;\n /** URL redirects. */\n redirects: RedirectsApi;\n}\n\n/** The server SDK: everything on {@link EcomwebSdk} plus the private modules. */\nexport interface EcomwebServerSdk\n extends Omit<EcomwebSdk, \"blog\" | \"reviews\" | \"shipping\" | \"promotions\"> {\n /** Blog, with comment submission. */\n blog: BlogServerApi;\n /** Reviews, with submission and invitations. */\n reviews: ReviewsServerApi;\n /** Shipping, with rate calculation. */\n shipping: ShippingServerApi;\n /** Promotions, with code validation. */\n promotions: PromotionsServerApi;\n /** Carts. */\n cart: CartApi;\n /** Orders. */\n orders: OrdersApi;\n /** Payments. */\n payments: PaymentsApi;\n /** Customers. */\n customers: CustomersApi;\n /** Customer addresses. */\n addresses: AddressesApi;\n}\n\ninterface Clients {\n publicHttp: IHttpClient;\n privateHttp: IHttpClient;\n shopperHttp: IHttpClient;\n}\n\nfunction buildAllModules({\n publicHttp,\n privateHttp,\n shopperHttp,\n}: Clients): EcomwebServerSdk {\n return {\n products: new ProductsApi(publicHttp),\n collections: new CollectionsApi(publicHttp),\n categories: new CategoriesApi(publicHttp),\n blog: new BlogServerApi(publicHttp, shopperHttp),\n stores: new StoresApi(publicHttp),\n themes: new ThemesApi(publicHttp),\n metaobjects: new MetaobjectsApi(publicHttp, shopperHttp),\n search: new SearchApi(publicHttp),\n shipping: new ShippingServerApi(publicHttp, privateHttp),\n promotions: new PromotionsServerApi(publicHttp, privateHttp),\n paymentMethods: new PaymentMethodsApi(publicHttp),\n reviews: new ReviewsServerApi(publicHttp, privateHttp),\n contentPages: new ContentPagesApi(publicHttp),\n menus: new MenusApi(publicHttp),\n redirects: new RedirectsApi(publicHttp),\n cart: new CartApi(privateHttp, shopperHttp),\n orders: new OrdersApi(privateHttp, shopperHttp),\n payments: new PaymentsApi(privateHttp),\n customers: new CustomersApi(shopperHttp),\n addresses: new AddressesApi(shopperHttp),\n };\n}\n\n/**\n * Creates the public SDK. It reads the catalog and content only (products,\n * collections, categories, blog, stores, themes, search and so on) and is safe\n * to use in a browser with a publishable key. For carts, orders, payments,\n * customers and the private methods of other modules, use\n * {@link createEcomwebServerSdk} on a server or {@link createEcomwebProxiedSdk}\n * in a browser.\n *\n * @example\n * ```ts\n * const sdk = createEcomwebSdk({ publicHttp, authHttp });\n * const product = await sdk.products.getBySlug(\"my-store\", \"blue-shirt\");\n * ```\n *\n * @param options - the HTTP clients, and optional client info for the `X-Ecomweb-Client` header\n * @returns An object with one API class per public resource\n */\nexport function createEcomwebSdk(options: EcomwebSdkOptions): EcomwebSdk {\n const publicHttp = withClientHeader(options.publicHttp, options.clientInfo);\n const shopperHttp = withClientHeader(options.authHttp, options.clientInfo);\n const all = buildAllModules({ publicHttp, privateHttp: publicHttp, shopperHttp });\n return {\n products: all.products,\n collections: all.collections,\n categories: all.categories,\n blog: new BlogApi(publicHttp, shopperHttp),\n stores: all.stores,\n themes: all.themes,\n metaobjects: all.metaobjects,\n search: all.search,\n shipping: new ShippingApi(publicHttp),\n promotions: new PromotionsApi(publicHttp),\n paymentMethods: all.paymentMethods,\n reviews: new ReviewsApi(publicHttp),\n contentPages: all.contentPages,\n menus: all.menus,\n redirects: all.redirects,\n };\n}\n\n/**\n * Creates the server SDK: the public modules plus carts, orders, payments,\n * customers, addresses and the private methods of blog, reviews, shipping and\n * promotions. Every request carries the secret in `x-storefront-api-key`, and\n * a key header set by the caller is overridden. Run it on a server only.\n *\n * @example\n * ```ts\n * const sdk = createEcomwebServerSdk({\n * publicHttp,\n * authHttp,\n * secretKey: process.env.ECOMWEB_SECRET_KEY!,\n * });\n * const cart = await sdk.cart.getCart(\"my-store\", sessionId, false);\n * ```\n *\n * @param options - the HTTP clients, the storefront secret key, and optional client info\n * @returns The public modules and the private ones\n * @throws Error when `secretKey` is blank or is a publishable key (`pk_...`), or when called in a browser; the message never includes the key\n */\nexport function createEcomwebServerSdk(\n options: EcomwebServerSdkOptions\n): EcomwebServerSdk {\n const secretKey = options.secretKey?.trim() ?? \"\";\n if (!secretKey) {\n throw new Error(\"createEcomwebServerSdk: secretKey is required\");\n }\n if (secretKey.startsWith(\"pk_\")) {\n throw new Error(\n \"createEcomwebServerSdk: secretKey is a publishable key; pass the secret key (sk_...)\"\n );\n }\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"createEcomwebServerSdk runs on a server only; in the browser use createEcomwebProxiedSdk\"\n );\n }\n const publicHttp = withClientHeader(\n withStorefrontKey(options.publicHttp, secretKey),\n options.clientInfo\n );\n const shopperHttp = withClientHeader(\n withStorefrontKey(options.authHttp, secretKey),\n options.clientInfo\n );\n return buildAllModules({ publicHttp, privateHttp: publicHttp, shopperHttp });\n}\n\n/**\n * Creates the SDK for browser code that needs private modules. Public calls go\n * straight to the API with the publishable key; private ones (cart, orders,\n * payments, customers, addresses and the private methods of other modules) go\n * to `proxyHttp`, a same-origin proxy that holds the secret key. No secret\n * reaches the browser.\n *\n * @example\n * ```ts\n * const sdk = createEcomwebProxiedSdk({ publicHttp, proxyHttp });\n * const cart = await sdk.cart.getCart(\"my-store\", sessionId, false);\n * ```\n *\n * @param options - the direct client, the proxy client, and optional client info\n * @returns The same shape as {@link createEcomwebServerSdk}\n */\nexport function createEcomwebProxiedSdk(\n options: EcomwebProxiedSdkOptions\n): EcomwebServerSdk {\n const publicHttp = withClientHeader(options.publicHttp, options.clientInfo);\n const proxyHttp = withClientHeader(options.proxyHttp, options.clientInfo);\n return buildAllModules({\n publicHttp,\n private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,WAAW,QAAQ,UAAU;AACxE,SAAO,gBAAgB;AAAA,IACrB;AAAA,IACA,aAAa;AAAA,IACb,aAAa;AAAA,EACf,CAAC;AACH;","names":["present","z","z","z","z","z","z","z","z","z","z","z","z","itemSchema","z","z","z","z","z","z","z","z","z","z","z","z","z","base","res"]}
|