brainerce 1.53.1 → 1.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -246,7 +246,91 @@ interface StoreInfo {
246
246
  * Feeds Product JSON-LD `shippingDetails` — pass as `buildProductJsonLd(product, { ..., shipping: storeInfo.shipping })`.
247
247
  */
248
248
  shipping?: ShippingSummaryEntry[];
249
+ /**
250
+ * Marketing tag ids for this sales channel (sales-channel mode only).
251
+ *
252
+ * Resolved server-side from the marketplace apps the merchant already
253
+ * connected — connecting the Google & YouTube app runs GA4 discovery and the
254
+ * measurement id lands here on its own; same for the Meta and TikTok pixels.
255
+ * The merchant types nothing, and the storefront needs no redeploy: a newly
256
+ * connected app shows up here within 5 minutes.
257
+ *
258
+ * Pass the whole object to {@link BrainerceClient.initTracking} — it boots
259
+ * every tag that is present and skips the rest. Absent fields are the normal
260
+ * state (that app simply isn't connected), never an error.
261
+ */
262
+ tracking?: StoreTracking;
263
+ }
264
+ /**
265
+ * Marketing tag ids served by `GET /api/vc/:connectionId/info`.
266
+ *
267
+ * Every id here is public by nature — it renders into the page source of the
268
+ * storefront — and is format-validated by the backend before being served, so
269
+ * it is safe to interpolate into a tag bootstrap.
270
+ */
271
+ interface StoreTracking {
272
+ /** GA4 measurement id, `G-XXXXXXX`. Auto-discovered by the Google & YouTube app. */
273
+ ga4MeasurementId?: string;
274
+ /**
275
+ * Google Tag Manager container id, `GTM-XXXXXX`. The one tag that cannot be
276
+ * auto-discovered — no OAuth surface exposes a container id — so it appears
277
+ * only when a merchant sets it on the sales channel.
278
+ */
279
+ gtmContainerId?: string;
280
+ /** Meta (Facebook) pixel id. Auto-discovered by the Meta Commerce app. */
281
+ metaPixelId?: string;
282
+ /** TikTok pixel id. Auto-discovered by the TikTok Shop app. */
283
+ tiktokPixelId?: string;
284
+ }
285
+ /**
286
+ * A normalized e-commerce event, fanned out by
287
+ * {@link BrainerceClient.trackMarketingEvent} to every tag that is loaded.
288
+ *
289
+ * Field names follow the GA4 e-commerce spec; the SDK translates them to each
290
+ * vendor's own vocabulary (`fbq` Meta standard events, `ttq` TikTok events) so
291
+ * you describe what happened once instead of three times.
292
+ */
293
+ interface TrackingEventPayload {
294
+ /** ISO 4217, e.g. `ILS`. Required for `purchase` / `begin_checkout` to be usable in ad optimization. */
295
+ currency?: string;
296
+ /** Monetary value of the event. */
297
+ value?: number;
298
+ /**
299
+ * Order id, for `purchase` only. Used as GA4's `transaction_id`, Meta's
300
+ * `eventID` and TikTok's `event_id`, which makes a duplicate send (page
301
+ * refresh, back-button) de-duplicate on the vendor's side rather than
302
+ * double-counting revenue.
303
+ */
304
+ transactionId?: string;
305
+ /** Shipping charged on the order (`purchase`). */
306
+ shipping?: number;
307
+ /** Tax charged on the order (`purchase`). */
308
+ tax?: number;
309
+ /** Coupon code applied. */
310
+ coupon?: string;
311
+ /** Line items. `itemId` must match the id you sync to the ad platform's catalog. */
312
+ items?: TrackingEventItem[];
313
+ }
314
+ /** One line item inside a {@link TrackingEventPayload}. */
315
+ interface TrackingEventItem {
316
+ /**
317
+ * The item id as the ad platform's catalog knows it.
318
+ *
319
+ * Use the product's SKU: that is what the Meta and Google catalog feeds
320
+ * publish as the item id, so anything else silently breaks attribution and
321
+ * dynamic remarketing — the pixel reports an id the catalog has never heard
322
+ * of, and the audience never builds.
323
+ */
324
+ itemId: string;
325
+ itemName?: string;
326
+ /** Unit price (GA4 multiplies by `quantity` itself — do not pre-multiply). */
327
+ price?: number;
328
+ quantity?: number;
329
+ itemVariant?: string;
330
+ itemCategory?: string;
249
331
  }
332
+ /** E-commerce event names understood by {@link BrainerceClient.trackMarketingEvent}. */
333
+ type TrackingEventName = 'view_item' | 'view_item_list' | 'add_to_cart' | 'remove_from_cart' | 'view_cart' | 'begin_checkout' | 'add_payment_info' | 'purchase' | 'search' | 'sign_up';
250
334
  /** One flat-rate/free shipping zone, as exposed by `StoreInfo.shipping`. */
251
335
  interface ShippingSummaryEntry {
252
336
  /** ISO 3166-1 alpha-2 country codes this rate applies to. */
@@ -1131,8 +1215,14 @@ declare function getCartTotals(cart: Pick<Cart, 'subtotal' | 'discountAmount'> |
1131
1215
  };
1132
1216
  /**
1133
1217
  * Get the display name for a cart item.
1134
- * Handles the nested product/variant structure - uses variant name if available,
1135
- * otherwise falls back to product name.
1218
+ * Handles the nested product/variant structure - the product name identifies the
1219
+ * line, with the variant name appended as a qualifier: `"Blue T-Shirt - Large"`.
1220
+ *
1221
+ * The suffix is omitted for products with no variant, and for variants whose name
1222
+ * was copied from the product (so the name never renders twice).
1223
+ *
1224
+ * Need the two parts separately — e.g. to render the variant on its own line —
1225
+ * read `item.product.name` and `item.variant?.name` directly.
1136
1226
  *
1137
1227
  * @param item - The cart item
1138
1228
  * @returns The display name for the item
@@ -1140,7 +1230,7 @@ declare function getCartTotals(cart: Pick<Cart, 'subtotal' | 'discountAmount'> |
1140
1230
  * @example
1141
1231
  * ```typescript
1142
1232
  * cart.items.forEach(item => {
1143
- * const name = getCartItemName(item);
1233
+ * const name = getCartItemName(item); // "Blue T-Shirt - Large"
1144
1234
  * console.log(`${name} x ${item.quantity}`);
1145
1235
  * });
1146
1236
  * ```
@@ -4630,6 +4720,37 @@ interface AutoRegionResponse {
4630
4720
  * still runs at checkout against the full shipping address (state / postal /
4631
4721
  * per-class). Render with an "Estimate" affordance.
4632
4722
  */
4723
+ /**
4724
+ * Manual per-region price override (regional pricing) — the merchant's
4725
+ * hand-set price pair for one product or variant in one region, denominated
4726
+ * in the REGION's currency. Replaces the automatic FX conversion for regions
4727
+ * that actually charge their currency (presentment). Admin (api-key) surface.
4728
+ */
4729
+ interface RegionPrice {
4730
+ id: string;
4731
+ productId: string;
4732
+ /** null = the product-level price (covers every variant without its own row). */
4733
+ variantId: string | null;
4734
+ /** Regular price in the region currency (Decimal string). */
4735
+ price: string;
4736
+ /** Sale price in the region currency — always lower than price; null = no regional sale. */
4737
+ salePrice: string | null;
4738
+ updatedAt: string;
4739
+ }
4740
+ /** One bulk entry for `upsertRegionPrices`. `remove: true` deletes the row. */
4741
+ interface RegionPriceEntry {
4742
+ productId: string;
4743
+ variantId?: string;
4744
+ /** Required unless `remove` — regular price in the region currency. */
4745
+ price?: number;
4746
+ /** Optional sale price — must be lower than `price`. */
4747
+ salePrice?: number;
4748
+ remove?: boolean;
4749
+ }
4750
+ interface UpsertRegionPricesResult {
4751
+ upserted: number;
4752
+ removed: number;
4753
+ }
4633
4754
  interface TaxEstimateResponse {
4634
4755
  appliesTax: boolean;
4635
4756
  /** Percent — e.g. 18 for 18%. `null` when no matching rule. */
@@ -6278,6 +6399,17 @@ declare global {
6278
6399
  interface Window {
6279
6400
  dataLayer?: unknown[];
6280
6401
  gtag?: (...args: unknown[]) => void;
6402
+ /** Meta pixel queue, installed by `initTracking()` when a pixel id is configured. */
6403
+ fbq?: ((...args: unknown[]) => void) & {
6404
+ queue?: unknown[];
6405
+ loaded?: boolean;
6406
+ version?: string;
6407
+ };
6408
+ _fbq?: unknown;
6409
+ /** TikTok pixel queue, installed by `initTracking()` when a pixel id is configured. */
6410
+ ttq?: Record<string, unknown> & {
6411
+ track?: (...args: unknown[]) => void;
6412
+ };
6281
6413
  }
6282
6414
  }
6283
6415
  /**
@@ -6340,6 +6472,9 @@ declare class BrainerceClient {
6340
6472
  private _pendingRecoverCartId;
6341
6473
  private _ga4MeasurementId;
6342
6474
  private _ga4StitchPromise;
6475
+ private _gtmContainerId;
6476
+ private _metaPixelId;
6477
+ private _tiktokPixelId;
6343
6478
  /**
6344
6479
  * Fields present on `getAddressDetails().address` that the address endpoints
6345
6480
  * do NOT accept — stripped by `stripResolvedOnlyAddressFields()` so a
@@ -6572,6 +6707,71 @@ declare class BrainerceClient {
6572
6707
  * consent.
6573
6708
  */
6574
6709
  private resolveGa4StitchIds;
6710
+ /**
6711
+ * Boot every marketing tag the merchant has configured — GA4, Google Tag
6712
+ * Manager, the Meta pixel, the TikTok pixel — in one call.
6713
+ *
6714
+ * Pass `storeInfo.tracking` straight through. The ids in it are resolved
6715
+ * server-side from the marketplace apps the merchant already connected, so
6716
+ * for the common case nobody types an id anywhere and nobody redeploys the
6717
+ * storefront: connect the Google app in the dashboard and this call starts
6718
+ * loading GA4 on the next page render.
6719
+ *
6720
+ * Call it once, as early as possible (root layout / app entry). It is
6721
+ * idempotent, a no-op during SSR, and never throws — a blocked or missing
6722
+ * tag must never take a storefront down with it.
6723
+ *
6724
+ * GA4 goes through {@link loadGoogleAnalytics}, so the `client_id` /
6725
+ * `session_id` stitch ids keep flowing onto cart and checkout calls and the
6726
+ * server-side purchase conversion still lands in the right session.
6727
+ *
6728
+ * @example
6729
+ * ```typescript
6730
+ * const storeInfo = await client.getStoreInfo();
6731
+ * client.initTracking(storeInfo.tracking);
6732
+ * // …later, on the order confirmation page:
6733
+ * client.trackMarketingEvent('purchase', {
6734
+ * transactionId: order.id,
6735
+ * currency: order.currency,
6736
+ * value: order.totalAmount,
6737
+ * items: order.items.map((i) => ({ itemId: i.sku, itemName: i.name, price: i.price, quantity: i.quantity })),
6738
+ * });
6739
+ * ```
6740
+ */
6741
+ initTracking(tracking?: StoreTracking | null): void;
6742
+ /**
6743
+ * Report one e-commerce event to every marketing tag that
6744
+ * {@link initTracking} loaded (GA4/GTM, Meta, TikTok).
6745
+ *
6746
+ * Distinct from {@link trackEvent}, which posts a cookieless pageview/beacon
6747
+ * to Brainerce's own storefront analytics. This one is about ad platforms —
6748
+ * call both; they answer different questions.
6749
+ *
6750
+ * You describe what happened once, in GA4's vocabulary, and the SDK
6751
+ * translates: a `dataLayer` push for GA4/GTM, the matching Meta standard
6752
+ * event via `fbq`, and the matching TikTok event via `ttq`. Tags that aren't
6753
+ * loaded are skipped silently, so the same call is correct whether the
6754
+ * merchant has connected none, one, or all of them.
6755
+ *
6756
+ * Why this matters for ad spend: a GTM container with no `dataLayer` events
6757
+ * is an empty container, and Meta cannot optimize a campaign it never sees a
6758
+ * `Purchase` for. The value/currency/item-id triple in {@link TrackingEventPayload}
6759
+ * is the whole input to that optimization.
6760
+ *
6761
+ * `purchase` is de-duplicated by the vendors on `transactionId` (GA4
6762
+ * `transaction_id`, Meta `eventID`, TikTok `event_id`), so a shopper
6763
+ * refreshing the confirmation page cannot double-count the order — pass the
6764
+ * order id and the safety is automatic.
6765
+ *
6766
+ * SSR-safe and never throws.
6767
+ */
6768
+ trackMarketingEvent(name: TrackingEventName, payload?: TrackingEventPayload): void;
6769
+ /** Install the GTM container loader. Idempotent; no-op if already present. */
6770
+ private loadGtm;
6771
+ /** Install the Meta pixel and fire its initial PageView. Idempotent. */
6772
+ private loadMetaPixel;
6773
+ /** Install the TikTok pixel and fire its initial page view. Idempotent. */
6774
+ private loadTikTokPixel;
6575
6775
  /**
6576
6776
  * Merge the resolved GA4 stitch ids onto a request body — only for fields
6577
6777
  * the caller didn't already set explicitly (explicit values always win).
@@ -10474,6 +10674,24 @@ declare class BrainerceClient {
10474
10674
  appId: string;
10475
10675
  name?: string | null;
10476
10676
  }>>;
10677
+ /**
10678
+ * List a region's manual price overrides (regional pricing, admin). Prices
10679
+ * are in the region's currency; `variantId: null` rows are product-level.
10680
+ */
10681
+ getRegionPrices(regionId: string, params?: {
10682
+ productId?: string;
10683
+ page?: number;
10684
+ limit?: number;
10685
+ }): Promise<PaginatedResponse<RegionPrice>>;
10686
+ /**
10687
+ * Bulk upsert/remove manual price overrides for a region (admin). Each
10688
+ * entry: `price` = regular, `salePrice` = sale (must be lower), in the
10689
+ * REGION's currency; `remove: true` deletes. A product/variant with no
10690
+ * entry keeps automatic FX conversion.
10691
+ */
10692
+ upsertRegionPrices(regionId: string, entries: RegionPriceEntry[]): Promise<UpsertRegionPricesResult>;
10693
+ /** Delete one manual price override by id (admin). */
10694
+ deleteRegionPrice(regionId: string, priceId: string): Promise<void>;
10477
10695
  /**
10478
10696
  * List the store's ACTIVE regions (public, no apiKey). Works in storeId and
10479
10697
  * vibe-coded modes. Returns only storefront-safe fields (no internal flags).
@@ -11126,7 +11344,7 @@ declare class BrainerceError extends Error {
11126
11344
  constructor(message: string, statusCode: number, details?: unknown);
11127
11345
  }
11128
11346
 
11129
- declare const SDK_VERSION = "1.53.1";
11347
+ declare const SDK_VERSION = "1.54.0";
11130
11348
 
11131
11349
  /**
11132
11350
  * Verify a webhook signature from Brainerce
@@ -11524,4 +11742,4 @@ interface CategorySitemapOptions {
11524
11742
  */
11525
11743
  declare function getCategorySitemapEntries(client: BrainerceClient, opts: CategorySitemapOptions): Promise<SitemapEntry[]>;
11526
11744
 
11527
- export { type AddToCartDto, type AddressDetailsResult, type AddressSuggestion, type AnnouncementContent, type AnnouncementSeverity, type AppliedDiscount, type ApplyCouponDto, type AttachModifierGroupInput, type Attribute, type AttributeOption, type AttributeSource, type BlogSitemapOptions, type BrainerceApiError, BrainerceClient, type BrainerceClientOptions, BrainerceError, type Brand, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type BusinessHoursWindow, type Cart, type CartAppliedDiscount, type CartBundleOffer, type CartBundlesResponse, type CartIncludeOption, type CartIncludeOptions, type CartItem, type CartItemModifierLine, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type CartWithIncludes, type Category, type CategoryDetail, type CategoryNode, type CategorySitemapOptions, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutBumpsResponse, type CheckoutCustomFieldDefinition, type CheckoutFieldPricing, type CheckoutFieldVisibility, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConfigureOAuthProviderDto as ConfigureOAuthProviderInput, type ConflictStatus, type ConnectorPlatform, type ContactFormFieldType, type ContactFormFieldValidation, type ContactFormPublic, type ContactFormPublicField, type ContactFormSummary, type Content, type ContentDataMap, type ContentStatus, type ContentSummary, type ContentType, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateAttributeDto as CreateAttributeInput, type CreateAttributeOptionDto as CreateAttributeOptionInput, type CreateBrandDto as CreateBrandInput, type CreateCategoryDto as CreateCategoryInput, type CreateCheckoutDto, type CreateContentInput, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateInquiryInput, type CreateInquiryResponse, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateModifierGroupInput, type CreateModifierInput, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateShippingRateDto as CreateShippingRateInput, type CreateShippingZoneDto as CreateShippingZoneInput, type CreateTagDto as CreateTagInput, type CreateTaxRateDto as CreateTaxRateInput, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DateAvailabilityConstraints, type DateFieldParseResult, type DeleteProductResponse, type DiscountBanner, type DiscountRuleType, type DownloadFile, type DraftLineItem, type EditInventoryDto, type EmailDomain, type EmailEventSettings, type EmailEventType, type EmailSettings, type EmailTemplate, type EmailTemplatePreview, type EmailTemplatesResponse, type EmailVerificationResponse, type ExtendReservationResponse, type FaqContent, type FaqItem, type FooterColumn, type FooterContent, type FooterLink, type FooterSocialLink, type FormatPriceOptions, type FormatProductPriceOptions, type FreeAllocationPolicy, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type HeaderContent, type HeaderCta, type HeaderLogo, type HeaderNavItem, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type JsonLdOptions, type ListModifierGroupsParams, type LocalCart, type LocalCartItem, type LockedVariant, type LoyaltyNextTierSummary, type LoyaltyReward, type LoyaltyStatus, type LoyaltyTierSummary, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldFilter, type MetafieldFilterValue, type MetafieldFiltersResponse, type MetafieldType, type Modifier, type ModifierGroup, type ModifierSelection, type ModifierSelectionType, type ModifierValidationCode, type ModifierValidationError, type MyProductReview, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProviderConfig, type OAuthProviderType, type OAuthProvidersResponse, type Order, type OrderAddress, type OrderBump, type OrderCustomer, type OrderDownloadLink, type OrderItem, type OrderQueryParams, type OrderStatus, type OrderStatusChange, type PageContent, type PageSeo, type PaginatedResponse, type ParsedDateFieldValue, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PaymentUrlOptions, type PickupLocation, type PlatformCouponCapabilities, type PlatformMetafieldMetadata, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductModifierGroupAttachment, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductReview, type ProductReviewAdmin, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, RTL_LOCALES, type RecommendationVariant, type ReconcileInventoryResponse, type RedeemRewardResult, type ReferralInfo, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, type RichTextContent, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetDefinitionProductsDto as SetDefinitionProductsInput, type SetMetafieldPlatformsDto as SetMetafieldPlatformsInput, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingSummaryEntry, type ShippingZone, type ShippingZoneQueryParams, type SitemapEntry, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type SubmitProductReviewInput, type SupportedLocaleObject, type SyncConflict, type SyncConflictResolution, type SyncJob, type Tag, type TaxBreakdown, type TaxBreakdownItem, type TaxRate, type TaxonomyQueryParams, type TeamInvitation, type TeamInvitationsResponse, type TeamMember, type TeamMembersResponse, type TeamRole, type UpdateAddressDto, type UpdateAttachmentInput, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateContentInput, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateEmailSettingsDto as UpdateEmailSettingsInput, type UpdateEmailTemplateDto as UpdateEmailTemplateInput, type UpdateInventoryDto, type UpdateMemberRoleDto as UpdateMemberRoleInput, type UpdateMetafieldDefinitionDto as UpdateMetafieldDefinitionInput, type UpdateModifierGroupInput, type UpdateModifierInput, type UpdateOAuthProviderDto as UpdateOAuthProviderInput, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateShippingRateDto as UpdateShippingRateInput, type UpdateShippingZoneDto as UpdateShippingZoneInput, type UpdateStoreMemberDto as UpdateStoreMemberInput, type UpdateTagDto as UpdateTagInput, type UpdateTaxRateDto as UpdateTaxRateInput, type UpdateVariantDto, type UpdateVariantInventoryDto, type UpsertProductMetafieldDto as UpsertProductMetafieldInput, type UserStore, type UserStorePermissions, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, type WriteProductReviewInput, buildArticleJsonLd, buildBreadcrumbJsonLd, buildCollectionPageJsonLd, buildOrganizationJsonLd, buildProductJsonLd, buildWebsiteJsonLd, computeAvailableSlots, createWebhookHandler, deriveSeoDescription, enableDevGuards, formatMoney, formatPrice, formatProductPrice, formatVariantPrice, getBlogSitemapEntries, getBusinessHoursForDate, getCartItemImage, getCartItemName, getCartTotals, getCategorySitemapEntries, getDescriptionContent, getDirectionForLocale, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isAllowedPaymentUrl, isCalendarDateAllowed, isCouponApplicableToProduct, isDateValueAllowed, isHtmlDescription, isWebhookEventType, jsonLdScriptProps, parseDateFieldValue, parseWebhookEvent, resolveStoreLocalParts, safePaymentRedirect, stripHtml, validateDateAvailabilityConfig, verifyWebhook };
11745
+ export { type AddToCartDto, type AddressDetailsResult, type AddressSuggestion, type AnnouncementContent, type AnnouncementSeverity, type AppliedDiscount, type ApplyCouponDto, type AttachModifierGroupInput, type Attribute, type AttributeOption, type AttributeSource, type BlogPost, type BlogPostListParams, type BlogPostListResponse, type BlogSitemapOptions, type BrainerceApiError, BrainerceClient, type BrainerceClientOptions, BrainerceError, type Brand, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type BusinessHoursWindow, type Cart, type CartAppliedDiscount, type CartBundleOffer, type CartBundlesResponse, type CartIncludeOption, type CartIncludeOptions, type CartItem, type CartItemModifierLine, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type CartWithIncludes, type Category, type CategoryDetail, type CategoryNode, type CategorySitemapOptions, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutBumpsResponse, type CheckoutCustomFieldDefinition, type CheckoutFieldPricing, type CheckoutFieldVisibility, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConfigureOAuthProviderDto as ConfigureOAuthProviderInput, type ConflictStatus, type ConnectorPlatform, type ContactFormFieldType, type ContactFormFieldValidation, type ContactFormPublic, type ContactFormPublicField, type ContactFormSummary, type Content, type ContentDataMap, type ContentStatus, type ContentSummary, type ContentType, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateAttributeDto as CreateAttributeInput, type CreateAttributeOptionDto as CreateAttributeOptionInput, type CreateBrandDto as CreateBrandInput, type CreateCategoryDto as CreateCategoryInput, type CreateCheckoutDto, type CreateContentInput, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateInquiryInput, type CreateInquiryResponse, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateModifierGroupInput, type CreateModifierInput, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateShippingRateDto as CreateShippingRateInput, type CreateShippingZoneDto as CreateShippingZoneInput, type CreateTagDto as CreateTagInput, type CreateTaxRateDto as CreateTaxRateInput, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DateAvailabilityConstraints, type DateFieldParseResult, type DeleteProductResponse, type DiscountBanner, type DiscountRuleType, type DownloadFile, type DraftLineItem, type EditInventoryDto, type EmailDomain, type EmailEventSettings, type EmailEventType, type EmailSettings, type EmailTemplate, type EmailTemplatePreview, type EmailTemplatesResponse, type EmailVerificationResponse, type ExtendReservationResponse, type FaqContent, type FaqItem, type FooterColumn, type FooterContent, type FooterLink, type FooterSocialLink, type FormatPriceOptions, type FormatProductPriceOptions, type FreeAllocationPolicy, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type HeaderContent, type HeaderCta, type HeaderLogo, type HeaderNavItem, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type JsonLdOptions, type ListModifierGroupsParams, type LocalCart, type LocalCartItem, type LockedVariant, type LoyaltyNextTierSummary, type LoyaltyReward, type LoyaltyStatus, type LoyaltyTierSummary, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldFilter, type MetafieldFilterValue, type MetafieldFiltersResponse, type MetafieldType, type Modifier, type ModifierGroup, type ModifierSelection, type ModifierSelectionType, type ModifierValidationCode, type ModifierValidationError, type MyProductReview, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProviderConfig, type OAuthProviderType, type OAuthProvidersResponse, type Order, type OrderAddress, type OrderBump, type OrderCustomer, type OrderDownloadLink, type OrderItem, type OrderQueryParams, type OrderStatus, type OrderStatusChange, type PageContent, type PageSeo, type PaginatedResponse, type ParsedDateFieldValue, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PaymentUrlOptions, type PickupLocation, type PlatformCouponCapabilities, type PlatformMetafieldMetadata, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductModifierGroupAttachment, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductReview, type ProductReviewAdmin, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, RTL_LOCALES, type RecommendationVariant, type ReconcileInventoryResponse, type RedeemRewardResult, type ReferralInfo, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, type RichTextContent, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetDefinitionProductsDto as SetDefinitionProductsInput, type SetMetafieldPlatformsDto as SetMetafieldPlatformsInput, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingSummaryEntry, type ShippingZone, type ShippingZoneQueryParams, type SitemapEntry, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type StoreTracking, type SubmitProductReviewInput, type SupportedLocaleObject, type SyncConflict, type SyncConflictResolution, type SyncJob, type Tag, type TaxBreakdown, type TaxBreakdownItem, type TaxRate, type TaxonomyQueryParams, type TeamInvitation, type TeamInvitationsResponse, type TeamMember, type TeamMembersResponse, type TeamRole, type TrackingEventItem, type TrackingEventName, type TrackingEventPayload, type UpdateAddressDto, type UpdateAttachmentInput, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateContentInput, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateEmailSettingsDto as UpdateEmailSettingsInput, type UpdateEmailTemplateDto as UpdateEmailTemplateInput, type UpdateInventoryDto, type UpdateMemberRoleDto as UpdateMemberRoleInput, type UpdateMetafieldDefinitionDto as UpdateMetafieldDefinitionInput, type UpdateModifierGroupInput, type UpdateModifierInput, type UpdateOAuthProviderDto as UpdateOAuthProviderInput, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateShippingRateDto as UpdateShippingRateInput, type UpdateShippingZoneDto as UpdateShippingZoneInput, type UpdateStoreMemberDto as UpdateStoreMemberInput, type UpdateTagDto as UpdateTagInput, type UpdateTaxRateDto as UpdateTaxRateInput, type UpdateVariantDto, type UpdateVariantInventoryDto, type UpsertProductMetafieldDto as UpsertProductMetafieldInput, type UserStore, type UserStorePermissions, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, type WriteProductReviewInput, buildArticleJsonLd, buildBreadcrumbJsonLd, buildCollectionPageJsonLd, buildOrganizationJsonLd, buildProductJsonLd, buildWebsiteJsonLd, computeAvailableSlots, createWebhookHandler, deriveSeoDescription, enableDevGuards, formatMoney, formatPrice, formatProductPrice, formatVariantPrice, getBlogSitemapEntries, getBusinessHoursForDate, getCartItemImage, getCartItemName, getCartTotals, getCategorySitemapEntries, getDescriptionContent, getDirectionForLocale, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isAllowedPaymentUrl, isCalendarDateAllowed, isCouponApplicableToProduct, isDateValueAllowed, isHtmlDescription, isWebhookEventType, jsonLdScriptProps, parseDateFieldValue, parseWebhookEvent, resolveStoreLocalParts, safePaymentRedirect, stripHtml, validateDateAvailabilityConfig, verifyWebhook };
package/dist/index.js CHANGED
@@ -98,7 +98,7 @@ var CART_GUARDS = [
98
98
  var CART_ITEM_GUARDS = [
99
99
  {
100
100
  property: "name",
101
- message: 'CartItem has no "name" field. Use item.product.name or getCartItemName(item).\nImport: import { getCartItemName } from "brainerce";'
101
+ message: 'CartItem has no "name" field. Use getCartItemName(item) for the full\n"Product - Variant" label, or item.product.name for the product name alone.\nImport: import { getCartItemName } from "brainerce";'
102
102
  },
103
103
  {
104
104
  property: "price",
@@ -201,11 +201,29 @@ function isDevGuardsEnabled() {
201
201
  }
202
202
 
203
203
  // src/version.ts
204
- var SDK_VERSION = "1.53.1";
204
+ var SDK_VERSION = "1.54.0";
205
205
 
206
206
  // src/client.ts
207
207
  var DEFAULT_BASE_URL = "https://api.brainerce.com";
208
208
  var DEFAULT_TIMEOUT = 3e4;
209
+ var META_EVENT_NAMES = {
210
+ view_item: "ViewContent",
211
+ add_to_cart: "AddToCart",
212
+ begin_checkout: "InitiateCheckout",
213
+ add_payment_info: "AddPaymentInfo",
214
+ purchase: "Purchase",
215
+ search: "Search",
216
+ sign_up: "CompleteRegistration"
217
+ };
218
+ var TIKTOK_EVENT_NAMES = {
219
+ view_item: "ViewContent",
220
+ add_to_cart: "AddToCart",
221
+ begin_checkout: "InitiateCheckout",
222
+ add_payment_info: "AddPaymentInfo",
223
+ purchase: "CompletePayment",
224
+ search: "Search",
225
+ sign_up: "CompleteRegistration"
226
+ };
209
227
  var RTL_LOCALES = /* @__PURE__ */ new Set(["ar", "he", "fa", "ur", "yi"]);
210
228
  function getDirectionForLocale(locale) {
211
229
  if (!locale) return "ltr";
@@ -260,6 +278,12 @@ var _BrainerceClient = class _BrainerceClient {
260
278
  // GA4 stitch state (see `loadGoogleAnalytics()` in the Analytics section).
261
279
  this._ga4MeasurementId = null;
262
280
  this._ga4StitchPromise = null;
281
+ // Marketing tags booted by `initTracking()`. Each holds the id already
282
+ // loaded, which is what makes a repeat call a no-op instead of a second
283
+ // pixel install (and a doubled PageView).
284
+ this._gtmContainerId = null;
285
+ this._metaPixelId = null;
286
+ this._tiktokPixelId = null;
263
287
  /** One warning per client, not per keystroke-driven address submit. */
264
288
  this._warnedResolvedOnlyAddressFields = false;
265
289
  /** localStorage key for session cart reference (sessionToken + cartId) */
@@ -1281,6 +1305,225 @@ var _BrainerceClient = class _BrainerceClient {
1281
1305
  }
1282
1306
  });
1283
1307
  }
1308
+ /**
1309
+ * Boot every marketing tag the merchant has configured — GA4, Google Tag
1310
+ * Manager, the Meta pixel, the TikTok pixel — in one call.
1311
+ *
1312
+ * Pass `storeInfo.tracking` straight through. The ids in it are resolved
1313
+ * server-side from the marketplace apps the merchant already connected, so
1314
+ * for the common case nobody types an id anywhere and nobody redeploys the
1315
+ * storefront: connect the Google app in the dashboard and this call starts
1316
+ * loading GA4 on the next page render.
1317
+ *
1318
+ * Call it once, as early as possible (root layout / app entry). It is
1319
+ * idempotent, a no-op during SSR, and never throws — a blocked or missing
1320
+ * tag must never take a storefront down with it.
1321
+ *
1322
+ * GA4 goes through {@link loadGoogleAnalytics}, so the `client_id` /
1323
+ * `session_id` stitch ids keep flowing onto cart and checkout calls and the
1324
+ * server-side purchase conversion still lands in the right session.
1325
+ *
1326
+ * @example
1327
+ * ```typescript
1328
+ * const storeInfo = await client.getStoreInfo();
1329
+ * client.initTracking(storeInfo.tracking);
1330
+ * // …later, on the order confirmation page:
1331
+ * client.trackMarketingEvent('purchase', {
1332
+ * transactionId: order.id,
1333
+ * currency: order.currency,
1334
+ * value: order.totalAmount,
1335
+ * items: order.items.map((i) => ({ itemId: i.sku, itemName: i.name, price: i.price, quantity: i.quantity })),
1336
+ * });
1337
+ * ```
1338
+ */
1339
+ initTracking(tracking) {
1340
+ if (typeof window === "undefined" || !tracking) return;
1341
+ if (tracking.ga4MeasurementId) {
1342
+ this.loadGoogleAnalytics(tracking.ga4MeasurementId);
1343
+ }
1344
+ if (tracking.gtmContainerId) this.loadGtm(tracking.gtmContainerId);
1345
+ if (tracking.metaPixelId) this.loadMetaPixel(tracking.metaPixelId);
1346
+ if (tracking.tiktokPixelId) this.loadTikTokPixel(tracking.tiktokPixelId);
1347
+ }
1348
+ /**
1349
+ * Report one e-commerce event to every marketing tag that
1350
+ * {@link initTracking} loaded (GA4/GTM, Meta, TikTok).
1351
+ *
1352
+ * Distinct from {@link trackEvent}, which posts a cookieless pageview/beacon
1353
+ * to Brainerce's own storefront analytics. This one is about ad platforms —
1354
+ * call both; they answer different questions.
1355
+ *
1356
+ * You describe what happened once, in GA4's vocabulary, and the SDK
1357
+ * translates: a `dataLayer` push for GA4/GTM, the matching Meta standard
1358
+ * event via `fbq`, and the matching TikTok event via `ttq`. Tags that aren't
1359
+ * loaded are skipped silently, so the same call is correct whether the
1360
+ * merchant has connected none, one, or all of them.
1361
+ *
1362
+ * Why this matters for ad spend: a GTM container with no `dataLayer` events
1363
+ * is an empty container, and Meta cannot optimize a campaign it never sees a
1364
+ * `Purchase` for. The value/currency/item-id triple in {@link TrackingEventPayload}
1365
+ * is the whole input to that optimization.
1366
+ *
1367
+ * `purchase` is de-duplicated by the vendors on `transactionId` (GA4
1368
+ * `transaction_id`, Meta `eventID`, TikTok `event_id`), so a shopper
1369
+ * refreshing the confirmation page cannot double-count the order — pass the
1370
+ * order id and the safety is automatic.
1371
+ *
1372
+ * SSR-safe and never throws.
1373
+ */
1374
+ trackMarketingEvent(name, payload = {}) {
1375
+ if (typeof window === "undefined") return;
1376
+ try {
1377
+ const items = payload.items ?? [];
1378
+ window.dataLayer = window.dataLayer || [];
1379
+ window.dataLayer.push({ ecommerce: null });
1380
+ window.dataLayer.push({
1381
+ event: name,
1382
+ ecommerce: {
1383
+ ...payload.currency ? { currency: payload.currency } : {},
1384
+ ...payload.value !== void 0 ? { value: payload.value } : {},
1385
+ ...payload.transactionId ? { transaction_id: payload.transactionId } : {},
1386
+ ...payload.shipping !== void 0 ? { shipping: payload.shipping } : {},
1387
+ ...payload.tax !== void 0 ? { tax: payload.tax } : {},
1388
+ ...payload.coupon ? { coupon: payload.coupon } : {},
1389
+ items: items.map((item) => ({
1390
+ item_id: item.itemId,
1391
+ ...item.itemName ? { item_name: item.itemName } : {},
1392
+ ...item.price !== void 0 ? { price: item.price } : {},
1393
+ ...item.quantity !== void 0 ? { quantity: item.quantity } : {},
1394
+ ...item.itemVariant ? { item_variant: item.itemVariant } : {},
1395
+ ...item.itemCategory ? { item_category: item.itemCategory } : {}
1396
+ }))
1397
+ }
1398
+ });
1399
+ if (window.gtag && this._ga4MeasurementId) {
1400
+ window.gtag("event", name, {
1401
+ ...payload.currency ? { currency: payload.currency } : {},
1402
+ ...payload.value !== void 0 ? { value: payload.value } : {},
1403
+ ...payload.transactionId ? { transaction_id: payload.transactionId } : {},
1404
+ ...payload.shipping !== void 0 ? { shipping: payload.shipping } : {},
1405
+ ...payload.tax !== void 0 ? { tax: payload.tax } : {},
1406
+ ...payload.coupon ? { coupon: payload.coupon } : {},
1407
+ items: items.map((item) => ({
1408
+ item_id: item.itemId,
1409
+ item_name: item.itemName,
1410
+ price: item.price,
1411
+ quantity: item.quantity
1412
+ }))
1413
+ });
1414
+ }
1415
+ const metaEvent = META_EVENT_NAMES[name];
1416
+ if (window.fbq && metaEvent) {
1417
+ const contents = items.map((item) => ({
1418
+ id: item.itemId,
1419
+ quantity: item.quantity ?? 1,
1420
+ ...item.price !== void 0 ? { item_price: item.price } : {}
1421
+ }));
1422
+ window.fbq(
1423
+ "track",
1424
+ metaEvent,
1425
+ {
1426
+ ...payload.currency ? { currency: payload.currency } : {},
1427
+ ...payload.value !== void 0 ? { value: payload.value } : {},
1428
+ ...contents.length ? { contents, content_ids: contents.map((c) => c.id), content_type: "product" } : {}
1429
+ },
1430
+ // Meta de-dupes a browser event against a server (CAPI) event of the
1431
+ // same eventID, and against a repeat send of the same page.
1432
+ payload.transactionId ? { eventID: payload.transactionId } : void 0
1433
+ );
1434
+ }
1435
+ const tiktokEvent = TIKTOK_EVENT_NAMES[name];
1436
+ if (window.ttq?.track && tiktokEvent) {
1437
+ window.ttq.track(
1438
+ tiktokEvent,
1439
+ {
1440
+ ...payload.currency ? { currency: payload.currency } : {},
1441
+ ...payload.value !== void 0 ? { value: payload.value } : {},
1442
+ contents: items.map((item) => ({
1443
+ content_id: item.itemId,
1444
+ content_name: item.itemName,
1445
+ quantity: item.quantity ?? 1,
1446
+ price: item.price
1447
+ }))
1448
+ },
1449
+ payload.transactionId ? { event_id: payload.transactionId } : void 0
1450
+ );
1451
+ }
1452
+ } catch {
1453
+ }
1454
+ }
1455
+ /** Install the GTM container loader. Idempotent; no-op if already present. */
1456
+ loadGtm(containerId) {
1457
+ if (this._gtmContainerId === containerId) return;
1458
+ this._gtmContainerId = containerId;
1459
+ try {
1460
+ window.dataLayer = window.dataLayer || [];
1461
+ window.dataLayer.push({ "gtm.start": Date.now(), event: "gtm.js" });
1462
+ const script = document.createElement("script");
1463
+ script.async = true;
1464
+ script.src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(containerId)}`;
1465
+ document.head.appendChild(script);
1466
+ } catch {
1467
+ }
1468
+ }
1469
+ /** Install the Meta pixel and fire its initial PageView. Idempotent. */
1470
+ loadMetaPixel(pixelId) {
1471
+ if (this._metaPixelId === pixelId) return;
1472
+ this._metaPixelId = pixelId;
1473
+ try {
1474
+ if (!window.fbq) {
1475
+ const queue = [];
1476
+ const fbq = ((...args) => {
1477
+ if (fbq.callMethod) fbq.callMethod(...args);
1478
+ else queue.push(args);
1479
+ });
1480
+ fbq.queue = queue;
1481
+ fbq.loaded = true;
1482
+ fbq.version = "2.0";
1483
+ window.fbq = fbq;
1484
+ window._fbq = fbq;
1485
+ const script = document.createElement("script");
1486
+ script.async = true;
1487
+ script.src = "https://connect.facebook.net/en_US/fbevents.js";
1488
+ document.head.appendChild(script);
1489
+ }
1490
+ window.fbq("init", pixelId);
1491
+ window.fbq("track", "PageView");
1492
+ } catch {
1493
+ }
1494
+ }
1495
+ /** Install the TikTok pixel and fire its initial page view. Idempotent. */
1496
+ loadTikTokPixel(pixelId) {
1497
+ if (this._tiktokPixelId === pixelId) return;
1498
+ this._tiktokPixelId = pixelId;
1499
+ try {
1500
+ const ttq = window.ttq ?? {};
1501
+ ttq._i = ttq._i ?? {};
1502
+ ttq._i[pixelId] = ttq._i[pixelId] ?? [];
1503
+ ttq._t = ttq._t ?? {};
1504
+ ttq._t[pixelId] = Date.now();
1505
+ ttq._o = ttq._o ?? {};
1506
+ ttq._o[pixelId] = {};
1507
+ const methods = ["page", "track", "identify", "instances", "ready"];
1508
+ ttq.methods = methods;
1509
+ for (const method of methods) {
1510
+ if (typeof ttq[method] !== "function") {
1511
+ ttq[method] = (...args) => {
1512
+ ttq._i?.[pixelId]?.push([method, ...args]);
1513
+ };
1514
+ }
1515
+ }
1516
+ window.ttq = ttq;
1517
+ const script = document.createElement("script");
1518
+ script.async = true;
1519
+ script.src = `https://analytics.tiktok.com/i18n/pixel/events.js?sdkid=${encodeURIComponent(
1520
+ pixelId
1521
+ )}&lib=ttq`;
1522
+ document.head.appendChild(script);
1523
+ ttq.page?.();
1524
+ } catch {
1525
+ }
1526
+ }
1284
1527
  /**
1285
1528
  * Merge the resolved GA4 stitch ids onto a request body — only for fields
1286
1529
  * the caller didn't already set explicitly (explicit values always win).
@@ -5201,9 +5444,7 @@ var _BrainerceClient = class _BrainerceClient {
5201
5444
  * ```
5202
5445
  */
5203
5446
  async setShippingAddress(checkoutId, address) {
5204
- const body = await this.withAnalyticsStitchIds(
5205
- this.stripResolvedOnlyAddressFields(address)
5206
- );
5447
+ const body = await this.withAnalyticsStitchIds(this.stripResolvedOnlyAddressFields(address));
5207
5448
  if (this.isVibeCodedMode()) {
5208
5449
  return this.vibeCodedRequest(
5209
5450
  "PATCH",
@@ -8260,6 +8501,42 @@ var _BrainerceClient = class _BrainerceClient {
8260
8501
  `/api/v1/regions/${encodePathSegment(regionId)}/compatible-providers`
8261
8502
  );
8262
8503
  }
8504
+ /**
8505
+ * List a region's manual price overrides (regional pricing, admin). Prices
8506
+ * are in the region's currency; `variantId: null` rows are product-level.
8507
+ */
8508
+ async getRegionPrices(regionId, params = {}) {
8509
+ return this.adminRequest(
8510
+ "GET",
8511
+ `/api/v1/regions/${encodePathSegment(regionId)}/prices`,
8512
+ void 0,
8513
+ {
8514
+ productId: params.productId,
8515
+ page: params.page,
8516
+ limit: params.limit
8517
+ }
8518
+ );
8519
+ }
8520
+ /**
8521
+ * Bulk upsert/remove manual price overrides for a region (admin). Each
8522
+ * entry: `price` = regular, `salePrice` = sale (must be lower), in the
8523
+ * REGION's currency; `remove: true` deletes. A product/variant with no
8524
+ * entry keeps automatic FX conversion.
8525
+ */
8526
+ async upsertRegionPrices(regionId, entries) {
8527
+ return this.adminRequest(
8528
+ "PUT",
8529
+ `/api/v1/regions/${encodePathSegment(regionId)}/prices`,
8530
+ { entries }
8531
+ );
8532
+ }
8533
+ /** Delete one manual price override by id (admin). */
8534
+ async deleteRegionPrice(regionId, priceId) {
8535
+ await this.adminRequest(
8536
+ "DELETE",
8537
+ `/api/v1/regions/${encodePathSegment(regionId)}/prices/${encodePathSegment(priceId)}`
8538
+ );
8539
+ }
8263
8540
  // -------------------- Regions (Storefront + vibe-coded, public — no apiKey) --------------------
8264
8541
  // storeId- or connectionId-based, no auth. Call these from a storefront to
8265
8542
  // detect the buyer's region (story S1), then pair with detectRegion(). Then
@@ -10209,7 +10486,10 @@ function getCartTotals(cart, shippingPrice) {
10209
10486
  return { subtotal, discount, shipping, total };
10210
10487
  }
10211
10488
  function getCartItemName(item) {
10212
- return item.variant?.name || item.product.name;
10489
+ const productName = item.product.name;
10490
+ const variantName = item.variant?.name?.trim();
10491
+ if (!variantName || variantName === productName) return productName;
10492
+ return `${productName} - ${variantName}`;
10213
10493
  }
10214
10494
  function getCartItemImage(item) {
10215
10495
  if (item.variant?.image) {