@wix/web5-core 1.63.5 → 1.63.7
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/cjs/component/types.js.map +1 -1
- package/dist/cjs/entity/defaultExtractor.js +11 -0
- package/dist/cjs/entity/defaultExtractor.js.map +1 -1
- package/dist/cjs/entity/index.js +9 -3
- package/dist/cjs/entity/index.js.map +1 -1
- package/dist/cjs/entity/matchedVariant.js +151 -0
- package/dist/cjs/entity/matchedVariant.js.map +1 -0
- package/dist/cjs/hooks/useResolveSearchSpringEntityData.js +17 -1
- package/dist/cjs/hooks/useResolveSearchSpringEntityData.js.map +1 -1
- package/dist/cjs/hooks/useResolveShopifyEntityData.js +30 -9
- package/dist/cjs/hooks/useResolveShopifyEntityData.js.map +1 -1
- package/dist/cjs/index.js +7 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/services/shopify/transformShopifyEntity.js +27 -6
- package/dist/cjs/services/shopify/transformShopifyEntity.js.map +1 -1
- package/dist/cjs/types/entity.js.map +1 -1
- package/dist/esm/component/types.js.map +1 -1
- package/dist/esm/entity/defaultExtractor.js +11 -0
- package/dist/esm/entity/defaultExtractor.js.map +1 -1
- package/dist/esm/entity/index.js +1 -0
- package/dist/esm/entity/index.js.map +1 -1
- package/dist/esm/entity/matchedVariant.js +146 -0
- package/dist/esm/entity/matchedVariant.js.map +1 -0
- package/dist/esm/hooks/useResolveSearchSpringEntityData.js +17 -1
- package/dist/esm/hooks/useResolveSearchSpringEntityData.js.map +1 -1
- package/dist/esm/hooks/useResolveShopifyEntityData.js +30 -9
- package/dist/esm/hooks/useResolveShopifyEntityData.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/services/shopify/transformShopifyEntity.js +27 -6
- package/dist/esm/services/shopify/transformShopifyEntity.js.map +1 -1
- package/dist/esm/types/entity.js.map +1 -1
- package/dist/types/component/types.d.ts +22 -0
- package/dist/types/component/types.d.ts.map +1 -1
- package/dist/types/entity/defaultExtractor.d.ts.map +1 -1
- package/dist/types/entity/index.d.ts +1 -0
- package/dist/types/entity/index.d.ts.map +1 -1
- package/dist/types/entity/matchedVariant.d.ts +79 -0
- package/dist/types/entity/matchedVariant.d.ts.map +1 -0
- package/dist/types/hooks/useResolveSearchSpringEntityData.d.ts +11 -0
- package/dist/types/hooks/useResolveSearchSpringEntityData.d.ts.map +1 -1
- package/dist/types/hooks/useResolveShopifyEntityData.d.ts +11 -0
- package/dist/types/hooks/useResolveShopifyEntityData.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/services/shopify/transformShopifyEntity.d.ts +2 -2
- package/dist/types/services/shopify/transformShopifyEntity.d.ts.map +1 -1
- package/dist/types/types/entity.d.ts +16 -0
- package/dist/types/types/entity.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":[],"sources":["../../../src/component/types.ts"],"sourcesContent":["import type { FC } from 'react';\nimport type { Callout } from '../types/callout';\n\n/** Props extracted from markdown (base layer). */\nexport interface BaseCompProps {}\nexport interface SlotCompProps extends BaseCompProps {\n callout?: Callout;\n}\n\nexport interface SectionCompProps extends BaseCompProps {\n callout?: Callout;\n}\n\n/** Section props with a slot. TSlot enforces which slot component this section accepts. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface SectionCompPropsWithSlot<TSlot extends FC<any> = FC<any>>\n extends SectionCompProps {\n slot?: TSlot;\n}\n\n// ----------------------\n// Base Components\n// ----------------------\n\nexport interface TextCompProps extends BaseCompProps {\n content: string;\n variant?: 'h1' | 'h2' | 'body' | 'caption';\n}\n\nexport interface ButtonCompProps extends BaseCompProps {\n label: string;\n variant?: 'primary' | 'secondary' | 'ghost';\n onClick?: string;\n}\n\nexport interface ImageCompProps extends BaseCompProps {\n src: string;\n alt: string;\n ratio?: '16:9' | '4:3' | '1:1' | '9:16' | '3:4';\n}\n\nexport interface BadgeCompProps extends BaseCompProps {\n label: string;\n color?: 'primary' | 'secondary' | 'success' | 'warning' | 'error';\n}\n\n// ----------------------\n// Hero Button (aligned to HeroSection1Button)\n// ----------------------\n\nexport interface HeroButton {\n id: string;\n text: string;\n variant?: 'primary' | 'secondary';\n onClick?: string;\n}\n\n// ----------------------\n// Slot Components\n// ----------------------\n\nexport interface KpiItemCompProps extends SlotCompProps {\n title: string;\n description: string;\n icon?: string;\n}\n\n/** Feature item — aligned to web50-server-ui Feature interface */\nexport interface FeatureItemCompProps extends SlotCompProps {\n title?: string;\n description?: string;\n icon?: string;\n}\n\n/** Feature card — aligned to web50-server-ui FeatureCard */\nexport interface FeatureCardCompProps extends SlotCompProps {\n title: string;\n description: string;\n imageUrl?: string;\n imageFromText?: boolean;\n linkText?: string;\n linkHref?: string;\n callout?: Callout;\n}\n\n/** Resolved entity data (populated at runtime via useResolveGenericEntityData) */\nexport interface EntityItemData {\n url: string;\n title: string;\n type: string;\n description?: string;\n excerpt?: string;\n imageUrl?: string;\n date?: string;\n publishDate?: string;\n author?: string;\n cmsItemId?: string;\n usage?: number;\n tags?: string[];\n /** Product vendor / brand name (e.g. \"HOKA\") */\n vendor?: string;\n /** Formatted price string (e.g. \"542.00 NIS\") */\n price?: string;\n /** Secondary product image URL — shown on hover */\n secondaryImageUrl?: string;\n /** Available sizes for the product */\n sizes?: string[];\n /** Original price before discount (formatted, e.g. \"494.00 NIS\") — shown with strikethrough */\n compareAtPrice?: string;\n /** Discount percentage (e.g. \"30% OFF\") */\n discountPercent?: string;\n /** Product variants with IDs and availability — used for add-to-cart and size display */\n variants?: {\n label: string;\n variantId: string;\n available: boolean;\n selectedOptions?: { name: string; value: string }[];\n price?: string;\n compareAtPrice?: string;\n }[];\n /** All product image URLs (not just featured + secondary) */\n allImages?: string[];\n /** Product option groups (e.g. Size, Color) with their available values */\n options?: { name: string; values: string[] }[];\n}\n\n/** Single entity item within an entity section */\nexport interface EntityItem {\n entityId: string;\n linkText?: string;\n entityType: string;\n entityUrl: string;\n description?: string;\n imageUrl?: string;\n /** Per-item callout from a blockquote inside the list item */\n callout?: Callout;\n /** Resolved at runtime via useResolveGenericEntityData hook; not produced by parse() */\n data?: EntityItemData;\n}\n\n// ---------------------------------------------------------------------------\n// Deprecated aliases — kept for seed-components compilation\n// ---------------------------------------------------------------------------\n/** @deprecated Use EntityItemData */\nexport type GenericEntityData = EntityItemData;\n/** @deprecated Use EntityItemData */\nexport type SolutionEntityData = EntityItemData;\n/** @deprecated Use EntityItemData */\nexport type BlogEntityData = EntityItemData;\n/** @deprecated Use EntityItem */\nexport type GenericEntityCompProps = EntityItem;\n\n/** Comparison row — aligned to web50-server-ui ComparisonRow */\nexport interface ComparisonRow {\n feature: string;\n iconHint?: string;\n values: (boolean | string)[];\n}\n\nexport interface ComparisonColumn {\n label: string;\n href?: string;\n entityId?: string;\n entityType?: string;\n}\n\n/** @deprecated Use Callout from types/callout instead */\nexport interface AiNarrativeCompProps extends SlotCompProps {\n content: string;\n}\n\n// ----------------------\n// Section Components\n// ----------------------\n\n/** Hero — aligned to HeroSection1Props */\nexport interface HeroCompProps extends SectionCompProps {\n headline: string;\n badge?: string | { text: string; showIndicator?: boolean };\n content?: string;\n buttons?: HeroButton[];\n image?: string;\n trailingList?: string;\n leadingQuote?: string;\n}\n\n/**\n * Entity hero — a hero section whose body carries one or more web5 entity\n * links (`web5://entity/...`). Shares the hero framing fields with\n * {@link HeroCompProps} but, instead of CTA buttons, surfaces the entities as\n * resolvable {@link EntityItem}s for rich rendering.\n */\nexport interface HeroEntityCompProps extends SectionCompProps {\n headline: string;\n badge?: string | { text: string; showIndicator?: boolean };\n content?: string;\n image?: string;\n leadingQuote?: string;\n items: EntityItem[];\n}\n\n/** KPI — aligned to KpiSectionProps */\nexport interface KpiCompProps\n extends SectionCompPropsWithSlot<KpiItemComponent> {\n title: string;\n items: KpiItemCompProps[];\n}\n\n/** Feature cards — aligned to FeatureCardsSectionProps */\nexport interface FeatureCardsCompProps extends SectionCompProps {\n cards: FeatureCardCompProps[];\n}\n\n/** Unified entity section — replaces EntityCompProps, SolutionEntityCompProps, BlogEntityCompProps */\nexport interface EntityCompProps extends SectionCompProps {\n title: string;\n description?: string;\n items: EntityItem[];\n}\n\n/** Comparison — aligned to ComparisonSection1Props */\nexport interface ComparisonCompProps extends SectionCompProps {\n title: string;\n description?: string;\n columnLabels: string[];\n columns?: ComparisonColumn[];\n rows: ComparisonRow[];\n featureColumnLabel?: string;\n ctaText?: string;\n ctaHref?: string;\n}\n\n/** General text — aligned to GeneralTextSectionProps (used by Fallback) */\nexport interface GeneralTextCompProps extends SectionCompProps {\n markdown: string;\n}\n\n/** Callout — aligned to CalloutSectionProps */\nexport interface CalloutCompProps extends SectionCompProps {\n callouts: Callout[];\n title?: string;\n relatedLinks?: { text: string; url: string }[];\n}\n\n/** Next steps — aligned to NextStepsSectionProps */\nexport interface NextStepsCompProps extends SectionCompProps {\n title: string;\n body?: string;\n /**\n * True when the chips are already rendered inline inside `body`. Renderers\n * must show `body` alone in that case — listing `steps` as well repeats every\n * chip. `steps` stays populated either way; it is the machine-readable chip\n * list (the scroll chips under the answer are built from it).\n */\n chipsInlineInBody?: boolean;\n backgroundImage?: string;\n steps: { content: string; iconHint?: string }[];\n}\n\n/** Feature section 9+ — aligned to FeatureSection9PlusProps */\nexport interface FeatureSection9PlusCompProps extends SectionCompProps {\n title: string;\n description?: string;\n features: { title?: string; description: string; iconHint?: string }[];\n}\n\n/** List items section — title + a list of feature items. */\nexport interface ListItemsSectionCompProps extends SectionCompProps {\n title: string;\n features: { title?: string; description: string }[];\n}\n\nexport type ListItemsSectionComponent = FC<ListItemsSectionCompProps>;\n\n/** Error — aligned to ErrorSection */\nexport interface ErrorCompProps extends SectionCompProps {\n type: import('../errors/conversationErrorTypes').ConversationErrorType;\n}\n\n/** Skip/HTML/Search — null-component parsers */\nexport interface NullCompProps extends SectionCompProps {}\n\n/** @deprecated Use EntityCompProps */\nexport type SolutionEntityCompProps = EntityCompProps;\n/** @deprecated Use EntityCompProps */\nexport type BlogEntityCompProps = EntityCompProps;\n\n/** CTA Banner — dark purple gradient card with headline, description, and pill link buttons */\nexport interface CtaBannerCompProps extends SectionCompProps {\n headline: string;\n description?: string;\n links: { text: string; href: string }[];\n /** Contextual background image — resolved from allowed keywords during parse() */\n imageUrl?: string;\n imageFromText?: boolean;\n}\n\nexport type CtaBannerSectionComponent = FC<CtaBannerCompProps>;\n\n/** Text block — heading + body with an optional pullquote callout on the side */\nexport interface TextBlockCompProps extends SectionCompProps {\n title: string;\n description: string;\n}\n\n/** Personalized narrative — standalone section with no parse() definition */\nexport interface PersonalizedNarrativeCompProps extends SectionCompProps {\n title: string;\n content?: string;\n}\n\n// --------------------------------\n// Types of component - all components\n// --------------------------------\n\nexport type Component = BaseComponent | SlotComponent | SectionComponent;\n\nexport type BaseComponent = FC<BaseCompProps>;\nexport type SlotComponent = FC<SlotCompProps>;\nexport type SectionComponent = FC<SectionCompProps>;\n\n// Base Components\nexport type TextComponent = FC<TextCompProps>;\nexport type ButtonComponent = FC<ButtonCompProps>;\nexport type ImageComponent = FC<ImageCompProps>;\nexport type BadgeComponent = FC<BadgeCompProps>;\n\n// Slot Components\nexport type KpiItemComponent = FC<KpiItemCompProps>;\nexport type FeatureItemComponent = FC<FeatureItemCompProps>;\nexport type FeatureCardComponent = FC<FeatureCardCompProps>;\n/** @deprecated Use FC<EntityItem> */\nexport type GenericEntityComponent = FC<EntityItem>;\nexport type AiNarrativeComponent = FC<AiNarrativeCompProps>;\n\n// Section Components\nexport type ComparisonSectionComponent = FC<ComparisonCompProps>;\nexport type GeneralTextSectionComponent = FC<GeneralTextCompProps>;\nexport type TextBlockSectionComponent = FC<TextBlockCompProps>;\nexport type HeroSectionComponent = FC<HeroCompProps>;\nexport type HeroEntitySectionComponent = FC<HeroEntityCompProps>;\n\n// section components with slots\nexport type KpiSectionComponent = FC<KpiCompProps>;\nexport type FeatureCardsSectionComponent = FC<FeatureCardsCompProps>;\nexport type EntitySectionComponent = FC<EntityCompProps>;\n\n// New section component types for Phase 4\nexport type CalloutSectionComponent = FC<CalloutCompProps>;\nexport type NextStepsSectionComponent = FC<NextStepsCompProps>;\nexport type FeatureSection9PlusSectionComponent =\n FC<FeatureSection9PlusCompProps>;\nexport type NullSectionComponent = FC<NullCompProps>;\nexport type ErrorSectionComponent = FC<ErrorCompProps>;\nexport type SolutionEntitySectionComponent = FC<SolutionEntityCompProps>;\nexport type BlogEntitySectionComponent = FC<BlogEntityCompProps>;\nexport type PersonalizedNarrativeSectionComponent =\n FC<PersonalizedNarrativeCompProps>;\n\nexport type PropsOf<T> = T extends (props: infer P) => unknown ? P : never;\n\nexport interface SectionFixture<TProps> {\n markdown: string;\n expected: Partial<TProps>;\n}\n"],"mappings":"","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":[],"sources":["../../../src/component/types.ts"],"sourcesContent":["import type { FC } from 'react';\nimport type { Callout } from '../types/callout';\n\n/** Props extracted from markdown (base layer). */\nexport interface BaseCompProps {}\nexport interface SlotCompProps extends BaseCompProps {\n callout?: Callout;\n}\n\nexport interface SectionCompProps extends BaseCompProps {\n callout?: Callout;\n}\n\n/** Section props with a slot. TSlot enforces which slot component this section accepts. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface SectionCompPropsWithSlot<TSlot extends FC<any> = FC<any>>\n extends SectionCompProps {\n slot?: TSlot;\n}\n\n// ----------------------\n// Base Components\n// ----------------------\n\nexport interface TextCompProps extends BaseCompProps {\n content: string;\n variant?: 'h1' | 'h2' | 'body' | 'caption';\n}\n\nexport interface ButtonCompProps extends BaseCompProps {\n label: string;\n variant?: 'primary' | 'secondary' | 'ghost';\n onClick?: string;\n}\n\nexport interface ImageCompProps extends BaseCompProps {\n src: string;\n alt: string;\n ratio?: '16:9' | '4:3' | '1:1' | '9:16' | '3:4';\n}\n\nexport interface BadgeCompProps extends BaseCompProps {\n label: string;\n color?: 'primary' | 'secondary' | 'success' | 'warning' | 'error';\n}\n\n// ----------------------\n// Hero Button (aligned to HeroSection1Button)\n// ----------------------\n\nexport interface HeroButton {\n id: string;\n text: string;\n variant?: 'primary' | 'secondary';\n onClick?: string;\n}\n\n// ----------------------\n// Slot Components\n// ----------------------\n\nexport interface KpiItemCompProps extends SlotCompProps {\n title: string;\n description: string;\n icon?: string;\n}\n\n/** Feature item — aligned to web50-server-ui Feature interface */\nexport interface FeatureItemCompProps extends SlotCompProps {\n title?: string;\n description?: string;\n icon?: string;\n}\n\n/** Feature card — aligned to web50-server-ui FeatureCard */\nexport interface FeatureCardCompProps extends SlotCompProps {\n title: string;\n description: string;\n imageUrl?: string;\n imageFromText?: boolean;\n linkText?: string;\n linkHref?: string;\n callout?: Callout;\n}\n\n/** Resolved entity data (populated at runtime via useResolveGenericEntityData) */\nexport interface EntityItemData {\n url: string;\n title: string;\n type: string;\n description?: string;\n excerpt?: string;\n imageUrl?: string;\n date?: string;\n publishDate?: string;\n author?: string;\n cmsItemId?: string;\n usage?: number;\n tags?: string[];\n /** Product vendor / brand name (e.g. \"HOKA\") */\n vendor?: string;\n /**\n * The `{ name, value }` pairs of the one variant a search matched, in the\n * store's own order. Present only when retrieval resolved the product down\n * to a single variant. The names are the store's own, so read this by\n * iterating it — never by looking a name up.\n */\n matchedOptions?: { name: string; value: string }[];\n /**\n * Id of the one variant a search matched — the same variant `imageUrl`,\n * `url` and `matchedOptions` describe. Bare store id, no `gid://` prefix.\n * A live enricher reads this to price that variant rather than the product.\n */\n variantId?: string;\n /** Whether the matched variant is in stock, as of the last live fetch */\n available?: boolean;\n /** Formatted lowest price across the product's variants (e.g. \"$107.95\") */\n priceMin?: string;\n /** Formatted highest price across the product's variants */\n priceMax?: string;\n /** Formatted price string (e.g. \"542.00 NIS\") */\n price?: string;\n /** Secondary product image URL — shown on hover */\n secondaryImageUrl?: string;\n /** Available sizes for the product */\n sizes?: string[];\n /** Original price before discount (formatted, e.g. \"494.00 NIS\") — shown with strikethrough */\n compareAtPrice?: string;\n /** Discount percentage (e.g. \"30% OFF\") */\n discountPercent?: string;\n /** Product variants with IDs and availability — used for add-to-cart and size display */\n variants?: {\n label: string;\n variantId: string;\n available: boolean;\n selectedOptions?: { name: string; value: string }[];\n price?: string;\n compareAtPrice?: string;\n }[];\n /** All product image URLs (not just featured + secondary) */\n allImages?: string[];\n /** Product option groups (e.g. Size, Color) with their available values */\n options?: { name: string; values: string[] }[];\n}\n\n/** Single entity item within an entity section */\nexport interface EntityItem {\n entityId: string;\n linkText?: string;\n entityType: string;\n entityUrl: string;\n description?: string;\n imageUrl?: string;\n /** Per-item callout from a blockquote inside the list item */\n callout?: Callout;\n /** Resolved at runtime via useResolveGenericEntityData hook; not produced by parse() */\n data?: EntityItemData;\n}\n\n// ---------------------------------------------------------------------------\n// Deprecated aliases — kept for seed-components compilation\n// ---------------------------------------------------------------------------\n/** @deprecated Use EntityItemData */\nexport type GenericEntityData = EntityItemData;\n/** @deprecated Use EntityItemData */\nexport type SolutionEntityData = EntityItemData;\n/** @deprecated Use EntityItemData */\nexport type BlogEntityData = EntityItemData;\n/** @deprecated Use EntityItem */\nexport type GenericEntityCompProps = EntityItem;\n\n/** Comparison row — aligned to web50-server-ui ComparisonRow */\nexport interface ComparisonRow {\n feature: string;\n iconHint?: string;\n values: (boolean | string)[];\n}\n\nexport interface ComparisonColumn {\n label: string;\n href?: string;\n entityId?: string;\n entityType?: string;\n}\n\n/** @deprecated Use Callout from types/callout instead */\nexport interface AiNarrativeCompProps extends SlotCompProps {\n content: string;\n}\n\n// ----------------------\n// Section Components\n// ----------------------\n\n/** Hero — aligned to HeroSection1Props */\nexport interface HeroCompProps extends SectionCompProps {\n headline: string;\n badge?: string | { text: string; showIndicator?: boolean };\n content?: string;\n buttons?: HeroButton[];\n image?: string;\n trailingList?: string;\n leadingQuote?: string;\n}\n\n/**\n * Entity hero — a hero section whose body carries one or more web5 entity\n * links (`web5://entity/...`). Shares the hero framing fields with\n * {@link HeroCompProps} but, instead of CTA buttons, surfaces the entities as\n * resolvable {@link EntityItem}s for rich rendering.\n */\nexport interface HeroEntityCompProps extends SectionCompProps {\n headline: string;\n badge?: string | { text: string; showIndicator?: boolean };\n content?: string;\n image?: string;\n leadingQuote?: string;\n items: EntityItem[];\n}\n\n/** KPI — aligned to KpiSectionProps */\nexport interface KpiCompProps\n extends SectionCompPropsWithSlot<KpiItemComponent> {\n title: string;\n items: KpiItemCompProps[];\n}\n\n/** Feature cards — aligned to FeatureCardsSectionProps */\nexport interface FeatureCardsCompProps extends SectionCompProps {\n cards: FeatureCardCompProps[];\n}\n\n/** Unified entity section — replaces EntityCompProps, SolutionEntityCompProps, BlogEntityCompProps */\nexport interface EntityCompProps extends SectionCompProps {\n title: string;\n description?: string;\n items: EntityItem[];\n}\n\n/** Comparison — aligned to ComparisonSection1Props */\nexport interface ComparisonCompProps extends SectionCompProps {\n title: string;\n description?: string;\n columnLabels: string[];\n columns?: ComparisonColumn[];\n rows: ComparisonRow[];\n featureColumnLabel?: string;\n ctaText?: string;\n ctaHref?: string;\n}\n\n/** General text — aligned to GeneralTextSectionProps (used by Fallback) */\nexport interface GeneralTextCompProps extends SectionCompProps {\n markdown: string;\n}\n\n/** Callout — aligned to CalloutSectionProps */\nexport interface CalloutCompProps extends SectionCompProps {\n callouts: Callout[];\n title?: string;\n relatedLinks?: { text: string; url: string }[];\n}\n\n/** Next steps — aligned to NextStepsSectionProps */\nexport interface NextStepsCompProps extends SectionCompProps {\n title: string;\n body?: string;\n /**\n * True when the chips are already rendered inline inside `body`. Renderers\n * must show `body` alone in that case — listing `steps` as well repeats every\n * chip. `steps` stays populated either way; it is the machine-readable chip\n * list (the scroll chips under the answer are built from it).\n */\n chipsInlineInBody?: boolean;\n backgroundImage?: string;\n steps: { content: string; iconHint?: string }[];\n}\n\n/** Feature section 9+ — aligned to FeatureSection9PlusProps */\nexport interface FeatureSection9PlusCompProps extends SectionCompProps {\n title: string;\n description?: string;\n features: { title?: string; description: string; iconHint?: string }[];\n}\n\n/** List items section — title + a list of feature items. */\nexport interface ListItemsSectionCompProps extends SectionCompProps {\n title: string;\n features: { title?: string; description: string }[];\n}\n\nexport type ListItemsSectionComponent = FC<ListItemsSectionCompProps>;\n\n/** Error — aligned to ErrorSection */\nexport interface ErrorCompProps extends SectionCompProps {\n type: import('../errors/conversationErrorTypes').ConversationErrorType;\n}\n\n/** Skip/HTML/Search — null-component parsers */\nexport interface NullCompProps extends SectionCompProps {}\n\n/** @deprecated Use EntityCompProps */\nexport type SolutionEntityCompProps = EntityCompProps;\n/** @deprecated Use EntityCompProps */\nexport type BlogEntityCompProps = EntityCompProps;\n\n/** CTA Banner — dark purple gradient card with headline, description, and pill link buttons */\nexport interface CtaBannerCompProps extends SectionCompProps {\n headline: string;\n description?: string;\n links: { text: string; href: string }[];\n /** Contextual background image — resolved from allowed keywords during parse() */\n imageUrl?: string;\n imageFromText?: boolean;\n}\n\nexport type CtaBannerSectionComponent = FC<CtaBannerCompProps>;\n\n/** Text block — heading + body with an optional pullquote callout on the side */\nexport interface TextBlockCompProps extends SectionCompProps {\n title: string;\n description: string;\n}\n\n/** Personalized narrative — standalone section with no parse() definition */\nexport interface PersonalizedNarrativeCompProps extends SectionCompProps {\n title: string;\n content?: string;\n}\n\n// --------------------------------\n// Types of component - all components\n// --------------------------------\n\nexport type Component = BaseComponent | SlotComponent | SectionComponent;\n\nexport type BaseComponent = FC<BaseCompProps>;\nexport type SlotComponent = FC<SlotCompProps>;\nexport type SectionComponent = FC<SectionCompProps>;\n\n// Base Components\nexport type TextComponent = FC<TextCompProps>;\nexport type ButtonComponent = FC<ButtonCompProps>;\nexport type ImageComponent = FC<ImageCompProps>;\nexport type BadgeComponent = FC<BadgeCompProps>;\n\n// Slot Components\nexport type KpiItemComponent = FC<KpiItemCompProps>;\nexport type FeatureItemComponent = FC<FeatureItemCompProps>;\nexport type FeatureCardComponent = FC<FeatureCardCompProps>;\n/** @deprecated Use FC<EntityItem> */\nexport type GenericEntityComponent = FC<EntityItem>;\nexport type AiNarrativeComponent = FC<AiNarrativeCompProps>;\n\n// Section Components\nexport type ComparisonSectionComponent = FC<ComparisonCompProps>;\nexport type GeneralTextSectionComponent = FC<GeneralTextCompProps>;\nexport type TextBlockSectionComponent = FC<TextBlockCompProps>;\nexport type HeroSectionComponent = FC<HeroCompProps>;\nexport type HeroEntitySectionComponent = FC<HeroEntityCompProps>;\n\n// section components with slots\nexport type KpiSectionComponent = FC<KpiCompProps>;\nexport type FeatureCardsSectionComponent = FC<FeatureCardsCompProps>;\nexport type EntitySectionComponent = FC<EntityCompProps>;\n\n// New section component types for Phase 4\nexport type CalloutSectionComponent = FC<CalloutCompProps>;\nexport type NextStepsSectionComponent = FC<NextStepsCompProps>;\nexport type FeatureSection9PlusSectionComponent =\n FC<FeatureSection9PlusCompProps>;\nexport type NullSectionComponent = FC<NullCompProps>;\nexport type ErrorSectionComponent = FC<ErrorCompProps>;\nexport type SolutionEntitySectionComponent = FC<SolutionEntityCompProps>;\nexport type BlogEntitySectionComponent = FC<BlogEntityCompProps>;\nexport type PersonalizedNarrativeSectionComponent =\n FC<PersonalizedNarrativeCompProps>;\n\nexport type PropsOf<T> = T extends (props: infer P) => unknown ? P : never;\n\nexport interface SectionFixture<TProps> {\n markdown: string;\n expected: Partial<TProps>;\n}\n"],"mappings":"","ignoreList":[]}
|
|
@@ -7,6 +7,7 @@ exports.transformToGenericEntityData = transformToGenericEntityData;
|
|
|
7
7
|
exports.transformToSolutionEntityData = transformToSolutionEntityData;
|
|
8
8
|
var _linkTypes = require("../types/link-types");
|
|
9
9
|
var _entityLinkParser = require("../utils/entityLinkParser");
|
|
10
|
+
var _matchedVariant = require("./matchedVariant");
|
|
10
11
|
/**
|
|
11
12
|
* Extract entity type and ID from a web5://entity/ URL.
|
|
12
13
|
* Delegates to the central `parseWeb5Url` parser.
|
|
@@ -97,6 +98,12 @@ function transformToGenericEntityData(payloadItem, config) {
|
|
|
97
98
|
const imgAlreadyAbsolute = payloadItem.img.startsWith('http');
|
|
98
99
|
imageUrl = config.imageBaseUrl && !imgAlreadyAbsolute ? `${config.imageBaseUrl}${payloadItem.img}` : payloadItem.img;
|
|
99
100
|
}
|
|
101
|
+
|
|
102
|
+
// A document that retrieval narrowed to one child arrives with that child's
|
|
103
|
+
// presentation fields already overlaid (`url`, `img`, `price`) plus the pairs
|
|
104
|
+
// that identify it and the span its parent covers. The overlay is done
|
|
105
|
+
// server-side; all that is left here is to shape those two for display.
|
|
106
|
+
const currency = (0, _matchedVariant.readCurrencyCode)(payloadItem.currency, payloadItem.priceCurrency);
|
|
100
107
|
return {
|
|
101
108
|
url: payloadItem.url,
|
|
102
109
|
title: payloadItem.title,
|
|
@@ -104,6 +111,10 @@ function transformToGenericEntityData(payloadItem, config) {
|
|
|
104
111
|
description: payloadItem.description,
|
|
105
112
|
excerpt: payloadItem.excerpt,
|
|
106
113
|
imageUrl,
|
|
114
|
+
matchedOptions: (0, _matchedVariant.toMatchedOptions)(payloadItem.options),
|
|
115
|
+
price: (0, _matchedVariant.formatPriceField)(payloadItem.price, currency),
|
|
116
|
+
priceMin: (0, _matchedVariant.formatPriceField)(payloadItem.priceMin, currency),
|
|
117
|
+
priceMax: (0, _matchedVariant.formatPriceField)(payloadItem.priceMax, currency),
|
|
107
118
|
date: payloadItem.update_ts ? formatEntityDate(payloadItem.update_ts) : undefined,
|
|
108
119
|
publishDate: publishTimestamp ? formatEntityDate(publishTimestamp) : undefined,
|
|
109
120
|
author: payloadItem.author || payloadItem.authorName,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_linkTypes","require","_entityLinkParser","extractEntityIdFromUrl","entityUrl","trimmedUrl","trim","isWeb5EntityUrl","parsed","parseWeb5Url","type","Web5UrlType","ENTITY","entityType","entityId","matchesUrl","payloadItem","config","id","urlValue","urlMatchProperty","pattern","urlMatchPattern","endsWith","includes","findEntityInPayload","payload","entityConfig","typeConfig","entityTypes","matchedItem","find","item","transformToSolutionEntityData","transformToGenericEntityData","formatEntityDate","timestamp","_parts$find","_parts$find2","_parts$find3","date","Date","isNaN","getTime","undefined","formatter","Intl","DateTimeFormat","day","month","timeZone","year","parts","formatToParts","part","value","transformToBlogPostEntityData","_payloadItem$labels","_payloadItem$tags","imageUrl","publishTimestamp","publishDate","published_at","img","imgAlreadyAbsolute","startsWith","imageBaseUrl","url","title","description","excerpt","update_ts","author","authorName","cmsItemId","cms_item_id","usage","tags","labels","length","defaultExtractor","exports"],"sources":["../../../src/entity/defaultExtractor.ts"],"sourcesContent":["import type { SolutionEntityData, BlogEntityData, EntityItemData } from '../component/types';\nimport type {\n ApiPayloadItem,\n EntityConfig,\n EntityTypeConfig,\n} from '../types/entity';\nimport type { EntityExtractor } from './types';\nimport { Web5UrlType, isWeb5EntityUrl } from '../types/link-types';\nimport { parseWeb5Url } from '../utils/entityLinkParser';\n\n/**\n * Extract entity type and ID from a web5://entity/ URL.\n * Delegates to the central `parseWeb5Url` parser.\n */\nfunction extractEntityIdFromUrl(\n entityUrl: string,\n): { entityType: string; entityId: string } | null {\n const trimmedUrl = entityUrl?.trim();\n if (!trimmedUrl || !isWeb5EntityUrl(trimmedUrl)) {\n return null;\n }\n const parsed = parseWeb5Url(trimmedUrl);\n if (parsed?.type !== Web5UrlType.ENTITY || !parsed.entityType || !parsed.entityId) {\n return null;\n }\n return { entityType: parsed.entityType, entityId: parsed.entityId };\n}\n\nfunction matchesUrl(\n payloadItem: ApiPayloadItem,\n entityId: string,\n config: EntityTypeConfig,\n): boolean {\n // Entities resolve by `entityId` (the `<id>` in `web5://entity/<type>/<id>`).\n // Accept a direct `id` match, then fall back to the configured url strategy.\n if (payloadItem.id === entityId) {\n return true;\n }\n\n const urlValue = payloadItem[config.urlMatchProperty as keyof ApiPayloadItem];\n\n if (typeof urlValue !== 'string') {\n return false;\n }\n\n const pattern = config.urlMatchPattern || 'endsWith';\n\n switch (pattern) {\n case 'endsWith':\n return urlValue.endsWith(`/${entityId}`);\n case 'contains':\n return urlValue.includes(entityId);\n case 'equals':\n return urlValue === entityId;\n default:\n return urlValue.endsWith(`/${entityId}`);\n }\n}\n\nfunction findEntityInPayload(\n entityType: string,\n entityId: string,\n payload: ApiPayloadItem[],\n entityConfig: EntityConfig,\n): ApiPayloadItem | null {\n const typeConfig = entityConfig.entityTypes[entityType];\n\n if (!typeConfig) {\n return null;\n }\n\n // Resolution keys off `entityId` (not the type): find the payload item whose\n // id/url matches, using the type's configured url strategy.\n const matchedItem = payload.find((item) =>\n matchesUrl(item, entityId, typeConfig),\n );\n\n return matchedItem || null;\n}\n\n/** @deprecated Use transformToGenericEntityData */\nexport function transformToSolutionEntityData(\n payloadItem: ApiPayloadItem,\n config: EntityTypeConfig,\n): SolutionEntityData {\n return transformToGenericEntityData(payloadItem, config);\n}\n\nfunction formatEntityDate(timestamp: string): string | undefined {\n const date = new Date(timestamp);\n if (isNaN(date.getTime())) {\n return undefined;\n }\n const formatter = new Intl.DateTimeFormat('en-US', {\n day: 'numeric',\n month: 'short',\n timeZone: 'Europe/Kiev',\n year: 'numeric',\n });\n const parts = formatter.formatToParts(date);\n const day = parts.find((part) => part.type === 'day')?.value;\n const month = parts.find((part) => part.type === 'month')?.value;\n const year = parts.find((part) => part.type === 'year')?.value;\n\n if (!day || !month || !year) {\n return undefined;\n }\n\n return `${day} ${month} ${year}`;\n}\n\n/** @deprecated Use transformToGenericEntityData */\nexport function transformToBlogPostEntityData(\n payloadItem: ApiPayloadItem,\n config: EntityTypeConfig,\n): BlogEntityData {\n return transformToGenericEntityData(payloadItem, config);\n}\n\nexport function transformToGenericEntityData(\n payloadItem: ApiPayloadItem,\n config: EntityTypeConfig,\n): EntityItemData {\n let imageUrl: string | undefined;\n const publishTimestamp = payloadItem.publishDate || payloadItem.published_at;\n\n if (payloadItem.img) {\n const imgAlreadyAbsolute = payloadItem.img.startsWith('http');\n imageUrl = config.imageBaseUrl && !imgAlreadyAbsolute\n ? `${config.imageBaseUrl}${payloadItem.img}`\n : payloadItem.img;\n }\n\n return {\n url: payloadItem.url,\n title: payloadItem.title,\n type: payloadItem.type,\n description: payloadItem.description,\n excerpt: payloadItem.excerpt,\n imageUrl,\n date: payloadItem.update_ts\n ? formatEntityDate(payloadItem.update_ts)\n : undefined,\n publishDate: publishTimestamp\n ? formatEntityDate(publishTimestamp)\n : undefined,\n author: payloadItem.author || payloadItem.authorName,\n cmsItemId: payloadItem.cms_item_id,\n usage: payloadItem.usage,\n tags: payloadItem.labels?.length\n ? payloadItem.labels\n : payloadItem.tags?.length\n ? payloadItem.tags\n : undefined,\n };\n}\n\n/**\n * Default entity extractor - config-driven extraction for any client.\n * Uses entityConfig from client JSON to resolve web5://entity/ URLs against API payload.\n */\nexport const defaultExtractor: EntityExtractor = {\n extractEntityIdFromUrl,\n findEntityInPayload,\n};\n"],"mappings":";;;;;;;AAOA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,iBAAA,GAAAD,OAAA;AAEA;AACA;AACA;AACA;AACA,SAASE,sBAAsBA,CAC7BC,SAAiB,EACgC;EACjD,MAAMC,UAAU,GAAGD,SAAS,oBAATA,SAAS,CAAEE,IAAI,CAAC,CAAC;EACpC,IAAI,CAACD,UAAU,IAAI,CAAC,IAAAE,0BAAe,EAACF,UAAU,CAAC,EAAE;IAC/C,OAAO,IAAI;EACb;EACA,MAAMG,MAAM,GAAG,IAAAC,8BAAY,EAACJ,UAAU,CAAC;EACvC,IAAI,CAAAG,MAAM,oBAANA,MAAM,CAAEE,IAAI,MAAKC,sBAAW,CAACC,MAAM,IAAI,CAACJ,MAAM,CAACK,UAAU,IAAI,CAACL,MAAM,CAACM,QAAQ,EAAE;IACjF,OAAO,IAAI;EACb;EACA,OAAO;IAAED,UAAU,EAAEL,MAAM,CAACK,UAAU;IAAEC,QAAQ,EAAEN,MAAM,CAACM;EAAS,CAAC;AACrE;AAEA,SAASC,UAAUA,CACjBC,WAA2B,EAC3BF,QAAgB,EAChBG,MAAwB,EACf;EACT;EACA;EACA,IAAID,WAAW,CAACE,EAAE,KAAKJ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AC","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_linkTypes","require","_entityLinkParser","_matchedVariant","extractEntityIdFromUrl","entityUrl","trimmedUrl","trim","isWeb5EntityUrl","parsed","parseWeb5Url","type","Web5UrlType","ENTITY","entityType","entityId","matchesUrl","payloadItem","config","id","urlValue","urlMatchProperty","pattern","urlMatchPattern","endsWith","includes","findEntityInPayload","payload","entityConfig","typeConfig","entityTypes","matchedItem","find","item","transformToSolutionEntityData","transformToGenericEntityData","formatEntityDate","timestamp","_parts$find","_parts$find2","_parts$find3","date","Date","isNaN","getTime","undefined","formatter","Intl","DateTimeFormat","day","month","timeZone","year","parts","formatToParts","part","value","transformToBlogPostEntityData","_payloadItem$labels","_payloadItem$tags","imageUrl","publishTimestamp","publishDate","published_at","img","imgAlreadyAbsolute","startsWith","imageBaseUrl","currency","readCurrencyCode","priceCurrency","url","title","description","excerpt","matchedOptions","toMatchedOptions","options","price","formatPriceField","priceMin","priceMax","update_ts","author","authorName","cmsItemId","cms_item_id","usage","tags","labels","length","defaultExtractor","exports"],"sources":["../../../src/entity/defaultExtractor.ts"],"sourcesContent":["import type { SolutionEntityData, BlogEntityData, EntityItemData } from '../component/types';\nimport type {\n ApiPayloadItem,\n EntityConfig,\n EntityTypeConfig,\n} from '../types/entity';\nimport type { EntityExtractor } from './types';\nimport { Web5UrlType, isWeb5EntityUrl } from '../types/link-types';\nimport { parseWeb5Url } from '../utils/entityLinkParser';\nimport {\n formatPriceField,\n readCurrencyCode,\n toMatchedOptions,\n} from './matchedVariant';\n\n/**\n * Extract entity type and ID from a web5://entity/ URL.\n * Delegates to the central `parseWeb5Url` parser.\n */\nfunction extractEntityIdFromUrl(\n entityUrl: string,\n): { entityType: string; entityId: string } | null {\n const trimmedUrl = entityUrl?.trim();\n if (!trimmedUrl || !isWeb5EntityUrl(trimmedUrl)) {\n return null;\n }\n const parsed = parseWeb5Url(trimmedUrl);\n if (parsed?.type !== Web5UrlType.ENTITY || !parsed.entityType || !parsed.entityId) {\n return null;\n }\n return { entityType: parsed.entityType, entityId: parsed.entityId };\n}\n\nfunction matchesUrl(\n payloadItem: ApiPayloadItem,\n entityId: string,\n config: EntityTypeConfig,\n): boolean {\n // Entities resolve by `entityId` (the `<id>` in `web5://entity/<type>/<id>`).\n // Accept a direct `id` match, then fall back to the configured url strategy.\n if (payloadItem.id === entityId) {\n return true;\n }\n\n const urlValue = payloadItem[config.urlMatchProperty as keyof ApiPayloadItem];\n\n if (typeof urlValue !== 'string') {\n return false;\n }\n\n const pattern = config.urlMatchPattern || 'endsWith';\n\n switch (pattern) {\n case 'endsWith':\n return urlValue.endsWith(`/${entityId}`);\n case 'contains':\n return urlValue.includes(entityId);\n case 'equals':\n return urlValue === entityId;\n default:\n return urlValue.endsWith(`/${entityId}`);\n }\n}\n\nfunction findEntityInPayload(\n entityType: string,\n entityId: string,\n payload: ApiPayloadItem[],\n entityConfig: EntityConfig,\n): ApiPayloadItem | null {\n const typeConfig = entityConfig.entityTypes[entityType];\n\n if (!typeConfig) {\n return null;\n }\n\n // Resolution keys off `entityId` (not the type): find the payload item whose\n // id/url matches, using the type's configured url strategy.\n const matchedItem = payload.find((item) =>\n matchesUrl(item, entityId, typeConfig),\n );\n\n return matchedItem || null;\n}\n\n/** @deprecated Use transformToGenericEntityData */\nexport function transformToSolutionEntityData(\n payloadItem: ApiPayloadItem,\n config: EntityTypeConfig,\n): SolutionEntityData {\n return transformToGenericEntityData(payloadItem, config);\n}\n\nfunction formatEntityDate(timestamp: string): string | undefined {\n const date = new Date(timestamp);\n if (isNaN(date.getTime())) {\n return undefined;\n }\n const formatter = new Intl.DateTimeFormat('en-US', {\n day: 'numeric',\n month: 'short',\n timeZone: 'Europe/Kiev',\n year: 'numeric',\n });\n const parts = formatter.formatToParts(date);\n const day = parts.find((part) => part.type === 'day')?.value;\n const month = parts.find((part) => part.type === 'month')?.value;\n const year = parts.find((part) => part.type === 'year')?.value;\n\n if (!day || !month || !year) {\n return undefined;\n }\n\n return `${day} ${month} ${year}`;\n}\n\n/** @deprecated Use transformToGenericEntityData */\nexport function transformToBlogPostEntityData(\n payloadItem: ApiPayloadItem,\n config: EntityTypeConfig,\n): BlogEntityData {\n return transformToGenericEntityData(payloadItem, config);\n}\n\nexport function transformToGenericEntityData(\n payloadItem: ApiPayloadItem,\n config: EntityTypeConfig,\n): EntityItemData {\n let imageUrl: string | undefined;\n const publishTimestamp = payloadItem.publishDate || payloadItem.published_at;\n\n if (payloadItem.img) {\n const imgAlreadyAbsolute = payloadItem.img.startsWith('http');\n imageUrl = config.imageBaseUrl && !imgAlreadyAbsolute\n ? `${config.imageBaseUrl}${payloadItem.img}`\n : payloadItem.img;\n }\n\n // A document that retrieval narrowed to one child arrives with that child's\n // presentation fields already overlaid (`url`, `img`, `price`) plus the pairs\n // that identify it and the span its parent covers. The overlay is done\n // server-side; all that is left here is to shape those two for display.\n const currency = readCurrencyCode(\n payloadItem.currency,\n payloadItem.priceCurrency,\n );\n\n return {\n url: payloadItem.url,\n title: payloadItem.title,\n type: payloadItem.type,\n description: payloadItem.description,\n excerpt: payloadItem.excerpt,\n imageUrl,\n matchedOptions: toMatchedOptions(payloadItem.options),\n price: formatPriceField(payloadItem.price, currency),\n priceMin: formatPriceField(payloadItem.priceMin, currency),\n priceMax: formatPriceField(payloadItem.priceMax, currency),\n date: payloadItem.update_ts\n ? formatEntityDate(payloadItem.update_ts)\n : undefined,\n publishDate: publishTimestamp\n ? formatEntityDate(publishTimestamp)\n : undefined,\n author: payloadItem.author || payloadItem.authorName,\n cmsItemId: payloadItem.cms_item_id,\n usage: payloadItem.usage,\n tags: payloadItem.labels?.length\n ? payloadItem.labels\n : payloadItem.tags?.length\n ? payloadItem.tags\n : undefined,\n };\n}\n\n/**\n * Default entity extractor - config-driven extraction for any client.\n * Uses entityConfig from client JSON to resolve web5://entity/ URLs against API payload.\n */\nexport const defaultExtractor: EntityExtractor = {\n extractEntityIdFromUrl,\n findEntityInPayload,\n};\n"],"mappings":";;;;;;;AAOA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
package/dist/cjs/entity/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
exports.__esModule = true;
|
|
4
|
-
exports.fetchEntityListData = exports.enrichEntitiesFromPayload = exports.LIST_ITEMS_ENDPOINT = void 0;
|
|
4
|
+
exports.formatProductPriceLabel = exports.formatPriceField = exports.formatMoney = exports.fetchEntityListData = exports.enrichEntitiesFromPayload = exports.LIST_ITEMS_ENDPOINT = void 0;
|
|
5
5
|
exports.getEntityExtractor = getEntityExtractor;
|
|
6
|
-
exports.listEntityItems = void 0;
|
|
6
|
+
exports.readCurrencyCode = exports.listEntityItems = void 0;
|
|
7
7
|
exports.registerEntityExtractor = registerEntityExtractor;
|
|
8
|
-
exports.transformToSolutionEntityData = exports.transformToGenericEntityData = exports.transformToBlogPostEntityData = void 0;
|
|
8
|
+
exports.transformToSolutionEntityData = exports.transformToGenericEntityData = exports.transformToBlogPostEntityData = exports.toMatchedOptions = void 0;
|
|
9
9
|
var _defaultExtractor = require("./defaultExtractor");
|
|
10
10
|
exports.defaultExtractor = _defaultExtractor.defaultExtractor;
|
|
11
11
|
exports.transformToSolutionEntityData = _defaultExtractor.transformToSolutionEntityData;
|
|
@@ -13,6 +13,12 @@ exports.transformToBlogPostEntityData = _defaultExtractor.transformToBlogPostEnt
|
|
|
13
13
|
exports.transformToGenericEntityData = _defaultExtractor.transformToGenericEntityData;
|
|
14
14
|
var _enrichEntitiesFromPayload = require("./enrichEntitiesFromPayload");
|
|
15
15
|
exports.enrichEntitiesFromPayload = _enrichEntitiesFromPayload.enrichEntitiesFromPayload;
|
|
16
|
+
var _matchedVariant = require("./matchedVariant");
|
|
17
|
+
exports.toMatchedOptions = _matchedVariant.toMatchedOptions;
|
|
18
|
+
exports.formatMoney = _matchedVariant.formatMoney;
|
|
19
|
+
exports.readCurrencyCode = _matchedVariant.readCurrencyCode;
|
|
20
|
+
exports.formatPriceField = _matchedVariant.formatPriceField;
|
|
21
|
+
exports.formatProductPriceLabel = _matchedVariant.formatProductPriceLabel;
|
|
16
22
|
var _fetchEntityListData = require("./fetchEntityListData");
|
|
17
23
|
exports.fetchEntityListData = _fetchEntityListData.fetchEntityListData;
|
|
18
24
|
var _listEntityItems = require("./listEntityItems");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_defaultExtractor","require","exports","defaultExtractor","transformToSolutionEntityData","transformToBlogPostEntityData","transformToGenericEntityData","_enrichEntitiesFromPayload","enrichEntitiesFromPayload","_fetchEntityListData","fetchEntityListData","_listEntityItems","listEntityItems","LIST_ITEMS_ENDPOINT","extractorRegistry","getEntityExtractor","clientId","registerEntityExtractor","extractor"],"sources":["../../../src/entity/index.ts"],"sourcesContent":["import type { EntityExtractor } from './types';\nimport { defaultExtractor } from './defaultExtractor';\n\nexport {\n defaultExtractor,\n transformToSolutionEntityData,\n transformToBlogPostEntityData,\n transformToGenericEntityData,\n} from './defaultExtractor';\n\nexport { enrichEntitiesFromPayload } from './enrichEntitiesFromPayload';\nexport {\n fetchEntityListData,\n type FetchEntityListDataOptions,\n} from './fetchEntityListData';\nexport {\n listEntityItems,\n LIST_ITEMS_ENDPOINT,\n type ListEntityItemsOptions,\n} from './listEntityItems';\n\nexport type { EntityExtractor } from './types';\n\n/**\n * Registry of client-specific entity extractors.\n * Only needed if a client requires custom extraction logic beyond the config-driven default.\n */\nconst extractorRegistry: Record<string, EntityExtractor> = {};\n\n/**\n * Get the entity extractor for a specific client.\n * The default extractor is config-driven and works for any client with entityConfig.\n */\nexport function getEntityExtractor(clientId?: string): EntityExtractor {\n if (clientId && extractorRegistry[clientId]) {\n return extractorRegistry[clientId];\n }\n return defaultExtractor;\n}\n\n/**\n * Register a custom entity extractor for a client\n * Useful for runtime registration or testing\n */\nexport function registerEntityExtractor(\n clientId: string,\n extractor: EntityExtractor,\n): void {\n extractorRegistry[clientId] = extractor;\n}\n"],"mappings":";;;;;;;;AACA,IAAAA,iBAAA,GAAAC,OAAA;AAAsDC,OAAA,CAAAC,gBAAA,GAAAH,iBAAA,CAAAG,gBAAA;AAAAD,OAAA,CAAAE,6BAAA,GAAAJ,iBAAA,CAAAI,6BAAA;AAAAF,OAAA,CAAAG,6BAAA,GAAAL,iBAAA,CAAAK,6BAAA;AAAAH,OAAA,CAAAI,4BAAA,GAAAN,iBAAA,CAAAM,4BAAA;AAStD,IAAAC,0BAAA,GAAAN,OAAA;AAAwEC,OAAA,CAAAM,yBAAA,GAAAD,0BAAA,CAAAC,yBAAA;AACxE,IAAAC,
|
|
1
|
+
{"version":3,"names":["_defaultExtractor","require","exports","defaultExtractor","transformToSolutionEntityData","transformToBlogPostEntityData","transformToGenericEntityData","_enrichEntitiesFromPayload","enrichEntitiesFromPayload","_matchedVariant","toMatchedOptions","formatMoney","readCurrencyCode","formatPriceField","formatProductPriceLabel","_fetchEntityListData","fetchEntityListData","_listEntityItems","listEntityItems","LIST_ITEMS_ENDPOINT","extractorRegistry","getEntityExtractor","clientId","registerEntityExtractor","extractor"],"sources":["../../../src/entity/index.ts"],"sourcesContent":["import type { EntityExtractor } from './types';\nimport { defaultExtractor } from './defaultExtractor';\n\nexport {\n defaultExtractor,\n transformToSolutionEntityData,\n transformToBlogPostEntityData,\n transformToGenericEntityData,\n} from './defaultExtractor';\n\nexport { enrichEntitiesFromPayload } from './enrichEntitiesFromPayload';\nexport {\n toMatchedOptions,\n formatMoney,\n readCurrencyCode,\n formatPriceField,\n formatProductPriceLabel,\n type MatchedOption,\n type ProductPriceFields,\n} from './matchedVariant';\nexport {\n fetchEntityListData,\n type FetchEntityListDataOptions,\n} from './fetchEntityListData';\nexport {\n listEntityItems,\n LIST_ITEMS_ENDPOINT,\n type ListEntityItemsOptions,\n} from './listEntityItems';\n\nexport type { EntityExtractor } from './types';\n\n/**\n * Registry of client-specific entity extractors.\n * Only needed if a client requires custom extraction logic beyond the config-driven default.\n */\nconst extractorRegistry: Record<string, EntityExtractor> = {};\n\n/**\n * Get the entity extractor for a specific client.\n * The default extractor is config-driven and works for any client with entityConfig.\n */\nexport function getEntityExtractor(clientId?: string): EntityExtractor {\n if (clientId && extractorRegistry[clientId]) {\n return extractorRegistry[clientId];\n }\n return defaultExtractor;\n}\n\n/**\n * Register a custom entity extractor for a client\n * Useful for runtime registration or testing\n */\nexport function registerEntityExtractor(\n clientId: string,\n extractor: EntityExtractor,\n): void {\n extractorRegistry[clientId] = extractor;\n}\n"],"mappings":";;;;;;;;AACA,IAAAA,iBAAA,GAAAC,OAAA;AAAsDC,OAAA,CAAAC,gBAAA,GAAAH,iBAAA,CAAAG,gBAAA;AAAAD,OAAA,CAAAE,6BAAA,GAAAJ,iBAAA,CAAAI,6BAAA;AAAAF,OAAA,CAAAG,6BAAA,GAAAL,iBAAA,CAAAK,6BAAA;AAAAH,OAAA,CAAAI,4BAAA,GAAAN,iBAAA,CAAAM,4BAAA;AAStD,IAAAC,0BAAA,GAAAN,OAAA;AAAwEC,OAAA,CAAAM,yBAAA,GAAAD,0BAAA,CAAAC,yBAAA;AACxE,IAAAC,eAAA,GAAAR,OAAA;AAQ0BC,OAAA,CAAAQ,gBAAA,GAAAD,eAAA,CAAAC,gBAAA;AAAAR,OAAA,CAAAS,WAAA,GAAAF,eAAA,CAAAE,WAAA;AAAAT,OAAA,CAAAU,gBAAA,GAAAH,eAAA,CAAAG,gBAAA;AAAAV,OAAA,CAAAW,gBAAA,GAAAJ,eAAA,CAAAI,gBAAA;AAAAX,OAAA,CAAAY,uBAAA,GAAAL,eAAA,CAAAK,uBAAA;AAC1B,IAAAC,oBAAA,GAAAd,OAAA;AAG+BC,OAAA,CAAAc,mBAAA,GAAAD,oBAAA,CAAAC,mBAAA;AAC/B,IAAAC,gBAAA,GAAAhB,OAAA;AAI2BC,OAAA,CAAAgB,eAAA,GAAAD,gBAAA,CAAAC,eAAA;AAAAhB,OAAA,CAAAiB,mBAAA,GAAAF,gBAAA,CAAAE,mBAAA;AAI3B;AACA;AACA;AACA;AACA,MAAMC,iBAAkD,GAAG,CAAC,CAAC;;AAE7D;AACA;AACA;AACA;AACO,SAASC,kBAAkBA,CAACC,QAAiB,EAAmB;EACrE,IAAIA,QAAQ,IAAIF,iBAAiB,CAACE,QAAQ,CAAC,EAAE;IAC3C,OAAOF,iBAAiB,CAACE,QAAQ,CAAC;EACpC;EACA,OAAOnB,kCAAgB;AACzB;;AAEA;AACA;AACA;AACA;AACO,SAASoB,uBAAuBA,CACrCD,QAAgB,EAChBE,SAA0B,EACpB;EACNJ,iBAAiB,CAACE,QAAQ,CAAC,GAAGE,SAAS;AACzC","ignoreList":[]}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
exports.__esModule = true;
|
|
4
|
+
exports.formatMoney = formatMoney;
|
|
5
|
+
exports.formatPriceField = formatPriceField;
|
|
6
|
+
exports.formatProductPriceLabel = formatProductPriceLabel;
|
|
7
|
+
exports.readCurrencyCode = readCurrencyCode;
|
|
8
|
+
exports.toMatchedOptions = toMatchedOptions;
|
|
9
|
+
/**
|
|
10
|
+
* Presentation helpers for a document that retrieval resolved down to one
|
|
11
|
+
* child.
|
|
12
|
+
*
|
|
13
|
+
* When a query filters on an attribute that lives on the child rather than on
|
|
14
|
+
* the parent, retrieval overlays the matching child's presentation fields onto
|
|
15
|
+
* the parent document before it reaches us: `url`, `img` and `price` already
|
|
16
|
+
* describe the child, while `title`, `description` and `doc_id` stay the
|
|
17
|
+
* parent's. Two fields need shaping before a card can print them, and both
|
|
18
|
+
* live here:
|
|
19
|
+
*
|
|
20
|
+
* - `options` — the child's own `{ name: value }` pairs.
|
|
21
|
+
* - `priceMin` / `priceMax` — the parent's span, against which the child's
|
|
22
|
+
* single `price` has to be read.
|
|
23
|
+
*
|
|
24
|
+
* The overlay itself is done server-side and is deliberately NOT repeated
|
|
25
|
+
* here.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** One `{ name: value }` pair, exactly as the store named it. */
|
|
29
|
+
|
|
30
|
+
function readText(value) {
|
|
31
|
+
if (typeof value === 'string') {
|
|
32
|
+
return value.trim();
|
|
33
|
+
}
|
|
34
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
35
|
+
return String(value);
|
|
36
|
+
}
|
|
37
|
+
return '';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Turn a document's raw `options` map into an ordered list of pairs.
|
|
42
|
+
*
|
|
43
|
+
* Every entry the store put in the map is kept, under the store's own name and
|
|
44
|
+
* in the store's own order. Nothing here knows — or may learn — what any
|
|
45
|
+
* particular name means: one catalogue's pairs describe a garment, the next
|
|
46
|
+
* one's a power tool, and both have to come out identical. Entries with an
|
|
47
|
+
* empty name or an empty/non-printable value are dropped, since a card can do
|
|
48
|
+
* nothing with them.
|
|
49
|
+
*
|
|
50
|
+
* Returns `undefined` (not `[]`) when there is nothing to show, so callers can
|
|
51
|
+
* treat it like every other optional field on the entity.
|
|
52
|
+
*/
|
|
53
|
+
function toMatchedOptions(raw) {
|
|
54
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
const pairs = [];
|
|
58
|
+
for (const [rawName, rawValue] of Object.entries(raw)) {
|
|
59
|
+
const name = rawName.trim();
|
|
60
|
+
const value = readText(rawValue);
|
|
61
|
+
if (name && value) {
|
|
62
|
+
pairs.push({
|
|
63
|
+
name,
|
|
64
|
+
value
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return pairs.length ? pairs : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Render one amount in the document's currency.
|
|
73
|
+
*
|
|
74
|
+
* With no currency code on the document the amount is printed bare: assuming
|
|
75
|
+
* "$" prints a false fact on every store that doesn't sell in dollars. Whole
|
|
76
|
+
* amounts stay whole ("107" not "107.00"); a real fractional amount keeps its
|
|
77
|
+
* minor units.
|
|
78
|
+
*/
|
|
79
|
+
function formatMoney(amount, currency) {
|
|
80
|
+
if (!currency) {
|
|
81
|
+
return String(amount);
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
return new Intl.NumberFormat(undefined, {
|
|
85
|
+
style: 'currency',
|
|
86
|
+
currency,
|
|
87
|
+
minimumFractionDigits: Number.isInteger(amount) ? 0 : 2
|
|
88
|
+
}).format(amount);
|
|
89
|
+
} catch {
|
|
90
|
+
// A well-formed but unknown code: show it rather than dropping it.
|
|
91
|
+
return `${amount} ${currency}`;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Normalize a document currency to an ISO-4217 code, or drop it. */
|
|
96
|
+
function readCurrencyCode(...candidates) {
|
|
97
|
+
for (const candidate of candidates) {
|
|
98
|
+
if (typeof candidate !== 'string') {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const code = candidate.trim().toUpperCase();
|
|
102
|
+
if (/^[A-Z]{3}$/.test(code)) {
|
|
103
|
+
return code;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Format one of a document's price fields for display. Numbers are rendered in
|
|
111
|
+
* the document's currency; an already-formatted string is passed through
|
|
112
|
+
* untouched; anything else yields `undefined`.
|
|
113
|
+
*/
|
|
114
|
+
function formatPriceField(value, currency) {
|
|
115
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
116
|
+
return formatMoney(value, currency);
|
|
117
|
+
}
|
|
118
|
+
if (typeof value === 'string' && value.trim()) {
|
|
119
|
+
return value.trim();
|
|
120
|
+
}
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The already-formatted price fields a card reads. */
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* What a product card should print as its price.
|
|
128
|
+
*
|
|
129
|
+
* `price` belongs to the single variant the search matched — the same variant
|
|
130
|
+
* the card's image and link point at. `priceMin`/`priceMax` describe the whole
|
|
131
|
+
* product. When those two differ the product has no one price, and printing
|
|
132
|
+
* the matched variant's number on its own would pass it off as the product's;
|
|
133
|
+
* printing it after "from" would be worse still, because "from" is a claim
|
|
134
|
+
* about the floor of the span and the matched variant is not always the
|
|
135
|
+
* cheapest one. So a span prints its own floor, prefixed.
|
|
136
|
+
*
|
|
137
|
+
* With no span — the two ends equal, or only one of them known — nothing
|
|
138
|
+
* changes: the matched variant's price is printed as it always was.
|
|
139
|
+
*/
|
|
140
|
+
function formatProductPriceLabel(fields) {
|
|
141
|
+
const {
|
|
142
|
+
price,
|
|
143
|
+
priceMin,
|
|
144
|
+
priceMax
|
|
145
|
+
} = fields;
|
|
146
|
+
if (priceMin && priceMax && priceMin !== priceMax) {
|
|
147
|
+
return `from ${priceMin}`;
|
|
148
|
+
}
|
|
149
|
+
return price;
|
|
150
|
+
}
|
|
151
|
+
//# sourceMappingURL=matchedVariant.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["readText","value","trim","Number","isFinite","String","toMatchedOptions","raw","Array","isArray","undefined","pairs","rawName","rawValue","Object","entries","name","push","length","formatMoney","amount","currency","Intl","NumberFormat","style","minimumFractionDigits","isInteger","format","readCurrencyCode","candidates","candidate","code","toUpperCase","test","formatPriceField","formatProductPriceLabel","fields","price","priceMin","priceMax"],"sources":["../../../src/entity/matchedVariant.ts"],"sourcesContent":["/**\n * Presentation helpers for a document that retrieval resolved down to one\n * child.\n *\n * When a query filters on an attribute that lives on the child rather than on\n * the parent, retrieval overlays the matching child's presentation fields onto\n * the parent document before it reaches us: `url`, `img` and `price` already\n * describe the child, while `title`, `description` and `doc_id` stay the\n * parent's. Two fields need shaping before a card can print them, and both\n * live here:\n *\n * - `options` — the child's own `{ name: value }` pairs.\n * - `priceMin` / `priceMax` — the parent's span, against which the child's\n * single `price` has to be read.\n *\n * The overlay itself is done server-side and is deliberately NOT repeated\n * here.\n */\n\n/** One `{ name: value }` pair, exactly as the store named it. */\nexport interface MatchedOption {\n name: string;\n value: string;\n}\n\nfunction readText(value: unknown): string {\n if (typeof value === 'string') {\n return value.trim();\n }\n if (typeof value === 'number' && Number.isFinite(value)) {\n return String(value);\n }\n return '';\n}\n\n/**\n * Turn a document's raw `options` map into an ordered list of pairs.\n *\n * Every entry the store put in the map is kept, under the store's own name and\n * in the store's own order. Nothing here knows — or may learn — what any\n * particular name means: one catalogue's pairs describe a garment, the next\n * one's a power tool, and both have to come out identical. Entries with an\n * empty name or an empty/non-printable value are dropped, since a card can do\n * nothing with them.\n *\n * Returns `undefined` (not `[]`) when there is nothing to show, so callers can\n * treat it like every other optional field on the entity.\n */\nexport function toMatchedOptions(raw: unknown): MatchedOption[] | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return undefined;\n }\n\n const pairs: MatchedOption[] = [];\n for (const [rawName, rawValue] of Object.entries(\n raw as Record<string, unknown>,\n )) {\n const name = rawName.trim();\n const value = readText(rawValue);\n if (name && value) {\n pairs.push({ name, value });\n }\n }\n\n return pairs.length ? pairs : undefined;\n}\n\n/**\n * Render one amount in the document's currency.\n *\n * With no currency code on the document the amount is printed bare: assuming\n * \"$\" prints a false fact on every store that doesn't sell in dollars. Whole\n * amounts stay whole (\"107\" not \"107.00\"); a real fractional amount keeps its\n * minor units.\n */\nexport function formatMoney(amount: number, currency?: string): string {\n if (!currency) {\n return String(amount);\n }\n try {\n return new Intl.NumberFormat(undefined, {\n style: 'currency',\n currency,\n minimumFractionDigits: Number.isInteger(amount) ? 0 : 2,\n }).format(amount);\n } catch {\n // A well-formed but unknown code: show it rather than dropping it.\n return `${amount} ${currency}`;\n }\n}\n\n/** Normalize a document currency to an ISO-4217 code, or drop it. */\nexport function readCurrencyCode(...candidates: unknown[]): string | undefined {\n for (const candidate of candidates) {\n if (typeof candidate !== 'string') {\n continue;\n }\n const code = candidate.trim().toUpperCase();\n if (/^[A-Z]{3}$/.test(code)) {\n return code;\n }\n }\n return undefined;\n}\n\n/**\n * Format one of a document's price fields for display. Numbers are rendered in\n * the document's currency; an already-formatted string is passed through\n * untouched; anything else yields `undefined`.\n */\nexport function formatPriceField(\n value: unknown,\n currency?: string,\n): string | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return formatMoney(value, currency);\n }\n if (typeof value === 'string' && value.trim()) {\n return value.trim();\n }\n return undefined;\n}\n\n/** The already-formatted price fields a card reads. */\nexport interface ProductPriceFields {\n /** Price of the one variant this result matched. */\n price?: string;\n /** Lowest price across the whole product's variants. */\n priceMin?: string;\n /** Highest price across the whole product's variants. */\n priceMax?: string;\n}\n\n/**\n * What a product card should print as its price.\n *\n * `price` belongs to the single variant the search matched — the same variant\n * the card's image and link point at. `priceMin`/`priceMax` describe the whole\n * product. When those two differ the product has no one price, and printing\n * the matched variant's number on its own would pass it off as the product's;\n * printing it after \"from\" would be worse still, because \"from\" is a claim\n * about the floor of the span and the matched variant is not always the\n * cheapest one. So a span prints its own floor, prefixed.\n *\n * With no span — the two ends equal, or only one of them known — nothing\n * changes: the matched variant's price is printed as it always was.\n */\nexport function formatProductPriceLabel(\n fields: ProductPriceFields,\n): string | undefined {\n const { price, priceMin, priceMax } = fields;\n if (priceMin && priceMax && priceMin !== priceMax) {\n return `from ${priceMin}`;\n }\n return price;\n}\n"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAMA,SAASA,QAAQA,CAACC,KAAc,EAAU;EACxC,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;IAC7B,OAAOA,KAAK,CAACC,IAAI,CAAC,CAAC;EACrB;EACA,IAAI,OAAOD,KAAK,KAAK,QAAQ,IAAIE,MAAM,CAACC,QAAQ,CAACH,KAAK,CAAC,EAAE;IACvD,OAAOI,MAAM,CAACJ,KAAK,CAAC;EACtB;EACA,OAAO,EAAE;AACX;;AAEA;AACA;AACA;AACA;AACA;A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AOC,SAAS,KAAK,QAAQ,EAAE;MACjC;IACF;IACA,MAAMC,IAAI,GAAGD,SAAS,CAAC5B,IAAI,CAAC,CAAC,CAAC8B,WAAW,CAAC,CAAC;IAC3C,IAAI,YAAY,CAACC,IAAI,CAACF,IAAI,CAAC,EAAE;MAC3B,OAAOA,IAAI;IACb;EACF;EACA,OAAOrB,SAAS;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASwB,gBAAgBA,CAC9BjC,KAAc,EACdoB,QAAiB,EACG;EACpB,IAAI,OAAOpB,KAAK,KAAK,QAAQ,IAAIE,MAAM,CAACC,QAAQ,CAACH,KAAK,CAAC,EAAE;IACvD,OAAOkB,WAAW,CAAClB,KAAK,EAAEoB,QAAQ,CAAC;EACrC;EACA,IAAI,OAAOpB,KAAK,KAAK,QAAQ,IAAIA,KAAK,CAACC,IAAI,CAAC,CAAC,EAAE;IAC7C,OAAOD,KAAK,CAACC,IAAI,CAAC,CAAC;EACrB;EACA,OAAOQ,SAAS;AAClB;;AAEA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASyB,uBAAuBA,CACrCC,MAA0B,EACN;EACpB,MAAM;IAAEC,KAAK;IAAEC,QAAQ;IAAEC;EAAS,CAAC,GAAGH,MAAM;EAC5C,IAAIE,QAAQ,IAAIC,QAAQ,IAAID,QAAQ,KAAKC,QAAQ,EAAE;IACjD,OAAO,QAAQD,QAAQ,EAAE;EAC3B;EACA,OAAOD,KAAK;AACd","ignoreList":[]}
|
|
@@ -31,8 +31,20 @@ function getSearchSpringHandle(entity) {
|
|
|
31
31
|
var _entity$data;
|
|
32
32
|
return extractProductHandle((_entity$data = entity.data) == null ? void 0 : _entity$data.url) || entity.entityId;
|
|
33
33
|
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The turn owns WHICH thing to show; the live fetch owns VOLATILE FACTS about
|
|
37
|
+
* it.
|
|
38
|
+
*
|
|
39
|
+
* Only the turn saw the shopper's question, so only it knows that the brown
|
|
40
|
+
* variant was the one asked for — its `title`, `imageUrl`, `url`,
|
|
41
|
+
* `matchedOptions` and `variantId` all describe that one variant and must
|
|
42
|
+
* survive enrichment. Everything SearchSpring answers with that can go stale
|
|
43
|
+
* between the turn and the render — `price`, `compareAtPrice`, `available`,
|
|
44
|
+
* `priceMin`, `priceMax` — comes from `resolved`.
|
|
45
|
+
*/
|
|
34
46
|
function mergeSearchSpringEntityData(existing, resolved) {
|
|
35
|
-
var _existing$sizes, _existing$variants, _existing$options, _existing$allImages;
|
|
47
|
+
var _existing$matchedOpti, _existing$sizes, _existing$variants, _existing$options, _existing$allImages;
|
|
36
48
|
if (!existing) {
|
|
37
49
|
return resolved;
|
|
38
50
|
}
|
|
@@ -40,6 +52,10 @@ function mergeSearchSpringEntityData(existing, resolved) {
|
|
|
40
52
|
...existing,
|
|
41
53
|
...resolved,
|
|
42
54
|
url: existing.url || resolved.url,
|
|
55
|
+
title: existing.title || resolved.title,
|
|
56
|
+
imageUrl: existing.imageUrl || resolved.imageUrl,
|
|
57
|
+
variantId: existing.variantId || resolved.variantId,
|
|
58
|
+
matchedOptions: (_existing$matchedOpti = existing.matchedOptions) != null && _existing$matchedOpti.length ? existing.matchedOptions : resolved.matchedOptions,
|
|
43
59
|
sizes: (_existing$sizes = existing.sizes) != null && _existing$sizes.length ? existing.sizes : resolved.sizes,
|
|
44
60
|
variants: (_existing$variants = existing.variants) != null && _existing$variants.length ? existing.variants : resolved.variants,
|
|
45
61
|
options: (_existing$options = existing.options) != null && _existing$options.length ? existing.options : resolved.options,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_react","require","_searchSpringClient","_transformSSProduct","ssEntityCache","Map","extractProductHandle","url","trimmed","trim","undefined","pathname","test","URL","withoutQuery","split","withoutLeadingSlash","replace","productsIndex","indexOf","handle","slice","length","getSearchSpringHandle","entity","_entity$data","data","entityId","mergeSearchSpringEntityData","existing","resolved","_existing$sizes","_existing$variants","_existing$options","_existing$allImages","sizes","variants","options","allImages","useResolveSearchSpringEntityData","entities","config","resolvedMap","setResolvedMap","useState","settled","setSettled","entityKey","useMemo","map","e","entityType","join","useEffect","ignore","siteId","productEntityHandles","filter","toLowerCase","includes","handlesToFetch","Set","has","cached","forEach","item","get","set","fetchAll","productMap","fetchProductsByHandlesMap","product","itemData","transformSSProductToEntityItemData","finalMap","enrichedEntities","loading"],"sources":["../../../src/hooks/useResolveSearchSpringEntityData.ts"],"sourcesContent":["import { useState, useEffect, useMemo } from 'react';\nimport { fetchProductsByHandlesMap } from '../services/searchspring/searchSpringClient';\nimport { transformSSProductToEntityItemData } from '../services/searchspring/transformSSProduct';\nimport type { SearchSpringConfig } from '../services/searchspring/types';\nimport type { EntityItemData } from '../component/types';\n\n// Session-level cache: handle → resolved EntityItemData\nconst ssEntityCache = new Map<string, EntityItemData>();\n\nfunction extractProductHandle(url: string | undefined): string | undefined {\n const trimmed = url?.trim();\n if (!trimmed) {\n return undefined;\n }\n\n let pathname = trimmed;\n try {\n if (/^https?:\\/\\//i.test(trimmed)) {\n pathname = new URL(trimmed).pathname;\n }\n } catch {\n pathname = trimmed;\n }\n\n const withoutQuery = pathname.split(/[?#]/)[0];\n const withoutLeadingSlash = withoutQuery.replace(/^\\/+/, '');\n const productsIndex = withoutLeadingSlash.indexOf('products/');\n const handle =\n productsIndex >= 0\n ? withoutLeadingSlash.slice(productsIndex + 'products/'.length)\n : withoutLeadingSlash;\n\n return handle || undefined;\n}\n\nfunction getSearchSpringHandle(entity: {\n entityId: string;\n data?: EntityItemData;\n}): string {\n return extractProductHandle(entity.data?.url) || entity.entityId;\n}\n\nexport function mergeSearchSpringEntityData(\n existing: EntityItemData | undefined,\n resolved: EntityItemData,\n): EntityItemData {\n if (!existing) {\n return resolved;\n }\n\n return {\n ...existing,\n ...resolved,\n url: existing.url || resolved.url,\n sizes: existing.sizes?.length ? existing.sizes : resolved.sizes,\n variants: existing.variants?.length ? existing.variants : resolved.variants,\n options: existing.options?.length ? existing.options : resolved.options,\n allImages: existing.allImages?.length\n ? existing.allImages\n : resolved.allImages,\n };\n}\n\n/**\n * SearchSpring-backed entity resolution hook.\n *\n * Fetches product data from the SearchSpring Search API by handle\n * and transforms it to EntityItemData. Uses a single batched API call\n * for all products (bgfilter.handle supports OR).\n */\nexport function useResolveSearchSpringEntityData<\n TEntity extends {\n entityId: string;\n entityUrl: string;\n entityType: string;\n data?: EntityItemData;\n },\n>(\n entities: TEntity[],\n config: SearchSpringConfig,\n): { enrichedEntities: TEntity[]; loading: boolean } {\n const [resolvedMap, setResolvedMap] = useState<Map<string, EntityItemData>>(\n new Map(),\n );\n const [settled, setSettled] = useState(false);\n\n // Stable key for dependency tracking\n const entityKey = useMemo(\n () =>\n entities\n .map((e) => `${e.entityType}:${e.entityId}:${getSearchSpringHandle(e)}`)\n .join(','),\n [entities],\n );\n\n useEffect(() => {\n let ignore = false;\n\n if (!entities.length || !config.siteId) {\n setSettled(true);\n return;\n }\n\n const productEntityHandles = entities\n .filter((e) => e.entityType.toLowerCase().includes('product'))\n .map((entity) => ({\n entity,\n handle: getSearchSpringHandle(entity),\n }));\n\n // Collect handles that need fetching. CMS payload IDs use payload url as the handle.\n const handlesToFetch = [\n ...new Set(\n productEntityHandles\n .map(({ handle }) => handle)\n .filter((handle) => !ssEntityCache.has(handle)),\n ),\n ];\n\n // If everything is cached, resolve immediately\n if (handlesToFetch.length === 0) {\n const cached = new Map<string, EntityItemData>();\n productEntityHandles.forEach(({ entity, handle }) => {\n const item = ssEntityCache.get(handle);\n if (item) {\n cached.set(entity.entityId, item);\n }\n });\n setResolvedMap(cached);\n setSettled(true);\n return;\n }\n\n setSettled(false);\n\n const fetchAll = async () => {\n const productMap = await fetchProductsByHandlesMap(\n config.siteId,\n handlesToFetch,\n );\n\n // Transform and cache\n for (const [handle, product] of productMap) {\n const itemData = transformSSProductToEntityItemData(product);\n ssEntityCache.set(handle, itemData);\n }\n\n if (ignore) {\n return;\n }\n\n // Build the final map\n const finalMap = new Map<string, EntityItemData>();\n productEntityHandles.forEach(({ entity, handle }) => {\n const item = ssEntityCache.get(handle);\n if (item) {\n finalMap.set(entity.entityId, item);\n }\n });\n\n setResolvedMap(finalMap);\n setSettled(true);\n };\n\n fetchAll();\n return () => {\n ignore = true;\n };\n }, [entityKey, config.siteId]);\n\n // Merge resolved data into entities\n const enrichedEntities = useMemo(() => {\n return entities.map((entity) => {\n const resolved = resolvedMap.get(entity.entityId);\n if (resolved) {\n return {\n ...entity,\n data: mergeSearchSpringEntityData(entity.data, resolved),\n };\n }\n return entity;\n });\n }, [entities, resolvedMap]);\n\n return { enrichedEntities, loading: !settled };\n}\n"],"mappings":";;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,mBAAA,GAAAD,OAAA;AACA,IAAAE,mBAAA,GAAAF,OAAA;AAIA;AACA,MAAMG,aAAa,GAAG,IAAIC,GAAG,CAAyB,CAAC;AAEvD,SAASC,oBAAoBA,CAACC,GAAuB,EAAsB;EACzE,MAAMC,OAAO,GAAGD,GAAG,oBAAHA,GAAG,CAAEE,IAAI,CAAC,CAAC;EAC3B,IAAI,CAACD,OAAO,EAAE;IACZ,OAAOE,SAAS;EAClB;EAEA,IAAIC,QAAQ,GAAGH,OAAO;EACtB,IAAI;IACF,IAAI,eAAe,CAACI,IAAI,CAACJ,OAAO,CAAC,EAAE;MACjCG,QAAQ,GAAG,IAAIE,GAAG,CAACL,OAAO,CAAC,CAACG,QAAQ;IACtC;EACF,CAAC,CAAC,MAAM;IACNA,QAAQ,GAAGH,OAAO;EACpB;EAEA,MAAMM,YAAY,GAAGH,QAAQ,CAACI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;EAC9C,MAAMC,mBAAmB,GAAGF,YAAY,CAACG,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;EAC5D,MAAMC,aAAa,GAAGF,mBAAmB,CAACG,OAAO,CAAC,WAAW,CAAC;EAC9D,MAAMC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QAAQ,CAAC;MACxB5B,UAAU,CAAC,IAAI,CAAC;IAClB,CAAC;IAEDsB,QAAQ,CAAC,CAAC;IACV,OAAO,MAAM;MACXd,MAAM,GAAG,IAAI;IACf,CAAC;EACH,CAAC,EAAE,CAACP,SAAS,EAAEN,MAAM,CAACc,MAAM,CAAC,CAAC;;EAE9B;EACA,MAAMoB,gBAAgB,GAAG,IAAA3B,cAAO,EAAC,MAAM;IACrC,OAAOR,QAAQ,CAACS,GAAG,CAAEzB,MAAM,IAAK;MAC9B,MAAMM,QAAQ,GAAGY,WAAW,CAACwB,GAAG,CAAC1C,MAAM,CAACG,QAAQ,CAAC;MACjD,IAAIG,QAAQ,EAAE;QACZ,OAAO;UACL,GAAGN,MAAM;UACTE,IAAI,EAAEE,2BAA2B,CAACJ,MAAM,CAACE,IAAI,EAAEI,QAAQ;QACzD,CAAC;MACH;MACA,OAAON,MAAM;IACf,CAAC,CAAC;EACJ,CAAC,EAAE,CAACgB,QAAQ,EAAEE,WAAW,CAAC,CAAC;EAE3B,OAAO;IAAEiC,gBAAgB;IAAEC,OAAO,EAAE,CAAC/B;EAAQ,CAAC;AAChD","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_react","require","_searchSpringClient","_transformSSProduct","ssEntityCache","Map","extractProductHandle","url","trimmed","trim","undefined","pathname","test","URL","withoutQuery","split","withoutLeadingSlash","replace","productsIndex","indexOf","handle","slice","length","getSearchSpringHandle","entity","_entity$data","data","entityId","mergeSearchSpringEntityData","existing","resolved","_existing$matchedOpti","_existing$sizes","_existing$variants","_existing$options","_existing$allImages","title","imageUrl","variantId","matchedOptions","sizes","variants","options","allImages","useResolveSearchSpringEntityData","entities","config","resolvedMap","setResolvedMap","useState","settled","setSettled","entityKey","useMemo","map","e","entityType","join","useEffect","ignore","siteId","productEntityHandles","filter","toLowerCase","includes","handlesToFetch","Set","has","cached","forEach","item","get","set","fetchAll","productMap","fetchProductsByHandlesMap","product","itemData","transformSSProductToEntityItemData","finalMap","enrichedEntities","loading"],"sources":["../../../src/hooks/useResolveSearchSpringEntityData.ts"],"sourcesContent":["import { useState, useEffect, useMemo } from 'react';\nimport { fetchProductsByHandlesMap } from '../services/searchspring/searchSpringClient';\nimport { transformSSProductToEntityItemData } from '../services/searchspring/transformSSProduct';\nimport type { SearchSpringConfig } from '../services/searchspring/types';\nimport type { EntityItemData } from '../component/types';\n\n// Session-level cache: handle → resolved EntityItemData\nconst ssEntityCache = new Map<string, EntityItemData>();\n\nfunction extractProductHandle(url: string | undefined): string | undefined {\n const trimmed = url?.trim();\n if (!trimmed) {\n return undefined;\n }\n\n let pathname = trimmed;\n try {\n if (/^https?:\\/\\//i.test(trimmed)) {\n pathname = new URL(trimmed).pathname;\n }\n } catch {\n pathname = trimmed;\n }\n\n const withoutQuery = pathname.split(/[?#]/)[0];\n const withoutLeadingSlash = withoutQuery.replace(/^\\/+/, '');\n const productsIndex = withoutLeadingSlash.indexOf('products/');\n const handle =\n productsIndex >= 0\n ? withoutLeadingSlash.slice(productsIndex + 'products/'.length)\n : withoutLeadingSlash;\n\n return handle || undefined;\n}\n\nfunction getSearchSpringHandle(entity: {\n entityId: string;\n data?: EntityItemData;\n}): string {\n return extractProductHandle(entity.data?.url) || entity.entityId;\n}\n\n/**\n * The turn owns WHICH thing to show; the live fetch owns VOLATILE FACTS about\n * it.\n *\n * Only the turn saw the shopper's question, so only it knows that the brown\n * variant was the one asked for — its `title`, `imageUrl`, `url`,\n * `matchedOptions` and `variantId` all describe that one variant and must\n * survive enrichment. Everything SearchSpring answers with that can go stale\n * between the turn and the render — `price`, `compareAtPrice`, `available`,\n * `priceMin`, `priceMax` — comes from `resolved`.\n */\nexport function mergeSearchSpringEntityData(\n existing: EntityItemData | undefined,\n resolved: EntityItemData,\n): EntityItemData {\n if (!existing) {\n return resolved;\n }\n\n return {\n ...existing,\n ...resolved,\n url: existing.url || resolved.url,\n title: existing.title || resolved.title,\n imageUrl: existing.imageUrl || resolved.imageUrl,\n variantId: existing.variantId || resolved.variantId,\n matchedOptions: existing.matchedOptions?.length\n ? existing.matchedOptions\n : resolved.matchedOptions,\n sizes: existing.sizes?.length ? existing.sizes : resolved.sizes,\n variants: existing.variants?.length ? existing.variants : resolved.variants,\n options: existing.options?.length ? existing.options : resolved.options,\n allImages: existing.allImages?.length\n ? existing.allImages\n : resolved.allImages,\n };\n}\n\n/**\n * SearchSpring-backed entity resolution hook.\n *\n * Fetches product data from the SearchSpring Search API by handle\n * and transforms it to EntityItemData. Uses a single batched API call\n * for all products (bgfilter.handle supports OR).\n */\nexport function useResolveSearchSpringEntityData<\n TEntity extends {\n entityId: string;\n entityUrl: string;\n entityType: string;\n data?: EntityItemData;\n },\n>(\n entities: TEntity[],\n config: SearchSpringConfig,\n): { enrichedEntities: TEntity[]; loading: boolean } {\n const [resolvedMap, setResolvedMap] = useState<Map<string, EntityItemData>>(\n new Map(),\n );\n const [settled, setSettled] = useState(false);\n\n // Stable key for dependency tracking\n const entityKey = useMemo(\n () =>\n entities\n .map((e) => `${e.entityType}:${e.entityId}:${getSearchSpringHandle(e)}`)\n .join(','),\n [entities],\n );\n\n useEffect(() => {\n let ignore = false;\n\n if (!entities.length || !config.siteId) {\n setSettled(true);\n return;\n }\n\n const productEntityHandles = entities\n .filter((e) => e.entityType.toLowerCase().includes('product'))\n .map((entity) => ({\n entity,\n handle: getSearchSpringHandle(entity),\n }));\n\n // Collect handles that need fetching. CMS payload IDs use payload url as the handle.\n const handlesToFetch = [\n ...new Set(\n productEntityHandles\n .map(({ handle }) => handle)\n .filter((handle) => !ssEntityCache.has(handle)),\n ),\n ];\n\n // If everything is cached, resolve immediately\n if (handlesToFetch.length === 0) {\n const cached = new Map<string, EntityItemData>();\n productEntityHandles.forEach(({ entity, handle }) => {\n const item = ssEntityCache.get(handle);\n if (item) {\n cached.set(entity.entityId, item);\n }\n });\n setResolvedMap(cached);\n setSettled(true);\n return;\n }\n\n setSettled(false);\n\n const fetchAll = async () => {\n const productMap = await fetchProductsByHandlesMap(\n config.siteId,\n handlesToFetch,\n );\n\n // Transform and cache\n for (const [handle, product] of productMap) {\n const itemData = transformSSProductToEntityItemData(product);\n ssEntityCache.set(handle, itemData);\n }\n\n if (ignore) {\n return;\n }\n\n // Build the final map\n const finalMap = new Map<string, EntityItemData>();\n productEntityHandles.forEach(({ entity, handle }) => {\n const item = ssEntityCache.get(handle);\n if (item) {\n finalMap.set(entity.entityId, item);\n }\n });\n\n setResolvedMap(finalMap);\n setSettled(true);\n };\n\n fetchAll();\n return () => {\n ignore = true;\n };\n }, [entityKey, config.siteId]);\n\n // Merge resolved data into entities\n const enrichedEntities = useMemo(() => {\n return entities.map((entity) => {\n const resolved = resolvedMap.get(entity.entityId);\n if (resolved) {\n return {\n ...entity,\n data: mergeSearchSpringEntityData(entity.data, resolved),\n };\n }\n return entity;\n });\n }, [entities, resolvedMap]);\n\n return { enrichedEntities, loading: !settled };\n}\n"],"mappings":";;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,mBAAA,GAAAD,OAAA;AACA,IAAAE,mBAAA,GAAAF,OAAA;AAIA;AACA,MAAMG,aAAa,GAAG,IAAIC,GAAG,CAAyB,CAAC;AAEvD,SAASC,oBAAoBA,CAACC,GAAuB,EAAsB;EACzE,MAAMC,OAAO,GAAGD,GAAG,oBAAHA,GAAG,CAAEE,IAAI,CAAC,CAAC;EAC3B,IAAI,CAACD,OAAO,EAAE;IACZ,OAAOE,SAAS;EAClB;EAEA,IAAIC,QAAQ,GAAGH,OAAO;EACtB,IAAI;IACF,IAAI,eAAe,CAACI,IAAI,CAACJ,OAAO,CAAC,EAAE;MACjCG,QAAQ,GAAG,IAAIE,GAAG,CAACL,OAAO,CAAC,CAACG,QAAQ;IACtC;EACF,CAAC,CAAC,MAAM;IACNA,QAAQ,GAAGH,OAAO;EACpB;EAEA,MAAMM,YAAY,GAAGH,QAAQ,CAACI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;EAC9C,MAAMC,mBAAmB,GAAG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AC;AAChD","ignoreList":[]}
|
|
@@ -7,10 +7,10 @@ var _react = require("react");
|
|
|
7
7
|
var _shopifyStorefrontClient = require("../services/shopify/shopifyStorefrontClient");
|
|
8
8
|
var _shopifyEntityResolver = require("../services/shopify/shopifyEntityResolver");
|
|
9
9
|
var _transformShopifyEntity = require("../services/shopify/transformShopifyEntity");
|
|
10
|
-
// Session-level cache: entityType:entityId → resolved EntityItemData
|
|
10
|
+
// Session-level cache: entityType:entityId:variantId → resolved EntityItemData
|
|
11
11
|
const shopifyEntityCache = new Map();
|
|
12
|
-
function cacheKey(entityType, entityId) {
|
|
13
|
-
return `${entityType}:${entityId}`;
|
|
12
|
+
function cacheKey(entityType, entityId, variantId) {
|
|
13
|
+
return `${entityType}:${entityId}:${variantId || ''}`;
|
|
14
14
|
}
|
|
15
15
|
function normalizeShopifyEntityType(entityType) {
|
|
16
16
|
const lower = entityType.toLowerCase();
|
|
@@ -51,23 +51,41 @@ function extractHandleFromUrl(url) {
|
|
|
51
51
|
return withoutLeadingSlash || undefined;
|
|
52
52
|
}
|
|
53
53
|
function getShopifyLookup(entity) {
|
|
54
|
-
var _entity$data;
|
|
54
|
+
var _entity$data, _entity$data2;
|
|
55
55
|
const entityType = normalizeShopifyEntityType(entity.entityType);
|
|
56
56
|
const urlHandle = extractHandleFromUrl((_entity$data = entity.data) == null ? void 0 : _entity$data.url);
|
|
57
57
|
const entityId = (entityType === 'product' || entityType === 'collection') && urlHandle ? urlHandle : entity.entityId;
|
|
58
58
|
return {
|
|
59
59
|
entityType,
|
|
60
|
-
entityId
|
|
60
|
+
entityId,
|
|
61
|
+
variantId: (_entity$data2 = entity.data) == null ? void 0 : _entity$data2.variantId
|
|
61
62
|
};
|
|
62
63
|
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The turn owns WHICH thing to show; the live fetch owns VOLATILE FACTS about
|
|
67
|
+
* it.
|
|
68
|
+
*
|
|
69
|
+
* Only the turn saw the shopper's question, so only it knows that the brown
|
|
70
|
+
* variant was the one asked for — its `title`, `imageUrl`, `url`,
|
|
71
|
+
* `matchedOptions` and `variantId` all describe that one variant and must
|
|
72
|
+
* survive enrichment. Everything the Storefront answers with that can go stale
|
|
73
|
+
* between the turn and the render — `price`, `compareAtPrice`, `available`,
|
|
74
|
+
* `priceMin`, `priceMax` — comes from `resolved`.
|
|
75
|
+
*/
|
|
63
76
|
function mergeShopifyEntityData(existing, resolved) {
|
|
77
|
+
var _existing$matchedOpti;
|
|
64
78
|
if (!existing) {
|
|
65
79
|
return resolved;
|
|
66
80
|
}
|
|
67
81
|
return {
|
|
68
82
|
...existing,
|
|
69
83
|
...resolved,
|
|
70
|
-
url: existing.url || resolved.url
|
|
84
|
+
url: existing.url || resolved.url,
|
|
85
|
+
title: existing.title || resolved.title,
|
|
86
|
+
imageUrl: existing.imageUrl || resolved.imageUrl,
|
|
87
|
+
variantId: existing.variantId || resolved.variantId,
|
|
88
|
+
matchedOptions: (_existing$matchedOpti = existing.matchedOptions) != null && _existing$matchedOpti.length ? existing.matchedOptions : resolved.matchedOptions
|
|
71
89
|
};
|
|
72
90
|
}
|
|
73
91
|
|
|
@@ -93,7 +111,7 @@ function useResolveShopifyEntityData(entities, shopifyConfig) {
|
|
|
93
111
|
}
|
|
94
112
|
const entityIds = (0, _react.useMemo)(() => entities.map(e => {
|
|
95
113
|
const lookup = getShopifyLookup(e);
|
|
96
|
-
return `${e.entityType}:${e.entityId}:${lookup.entityType
|
|
114
|
+
return `${e.entityType}:${e.entityId}:${cacheKey(lookup.entityType, lookup.entityId, lookup.variantId)}`;
|
|
97
115
|
}).join(','), [entities]);
|
|
98
116
|
(0, _react.useEffect)(() => {
|
|
99
117
|
let ignore = false;
|
|
@@ -107,7 +125,10 @@ function useResolveShopifyEntityData(entities, shopifyConfig) {
|
|
|
107
125
|
return {
|
|
108
126
|
entity,
|
|
109
127
|
lookup,
|
|
110
|
-
key:
|
|
128
|
+
// The variant is part of the key: the cached entry carries that
|
|
129
|
+
// variant's live price, so two entities on the same product but
|
|
130
|
+
// different variants must not share it.
|
|
131
|
+
key: cacheKey(lookup.entityType, lookup.entityId, lookup.variantId)
|
|
111
132
|
};
|
|
112
133
|
});
|
|
113
134
|
|
|
@@ -141,7 +162,7 @@ function useResolveShopifyEntityData(entities, shopifyConfig) {
|
|
|
141
162
|
}) => {
|
|
142
163
|
const resolved = await (0, _shopifyEntityResolver.resolveShopifyEntity)(client, lookup.entityType, lookup.entityId, shopifyConfig);
|
|
143
164
|
if (resolved) {
|
|
144
|
-
const itemData = (0, _transformShopifyEntity.transformShopifyEntityToItemData)(resolved, lookup.entityType);
|
|
165
|
+
const itemData = (0, _transformShopifyEntity.transformShopifyEntityToItemData)(resolved, lookup.entityType, lookup.variantId);
|
|
145
166
|
shopifyEntityCache.set(key, mergeShopifyEntityData(entity.data, itemData));
|
|
146
167
|
}
|
|
147
168
|
}));
|