@butterflypress/nextjs 0.0.0-stage → 0.2.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.
Files changed (50) hide show
  1. package/dist/chunk-IFQHJL33.js +97 -0
  2. package/dist/chunk-IFQHJL33.js.map +1 -0
  3. package/dist/chunk-ROFORVTO.js +116 -0
  4. package/dist/chunk-ROFORVTO.js.map +1 -0
  5. package/dist/client.cjs +144 -0
  6. package/dist/client.cjs.map +1 -0
  7. package/dist/client.d.cts +42 -0
  8. package/dist/client.d.ts +42 -0
  9. package/dist/client.js +116 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/index.cjs +556 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +39 -0
  14. package/dist/index.d.ts +39 -0
  15. package/dist/index.js +243 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/metadata.cjs +123 -0
  18. package/dist/metadata.cjs.map +1 -0
  19. package/dist/metadata.d.cts +43 -0
  20. package/dist/metadata.d.ts +43 -0
  21. package/dist/metadata.js +3 -0
  22. package/dist/metadata.js.map +1 -0
  23. package/dist/server.cjs +369 -0
  24. package/dist/server.cjs.map +1 -0
  25. package/dist/server.d.cts +87 -0
  26. package/dist/server.d.ts +87 -0
  27. package/dist/server.js +310 -0
  28. package/dist/server.js.map +1 -0
  29. package/dist/ssr.cjs +100 -0
  30. package/dist/ssr.cjs.map +1 -0
  31. package/dist/ssr.d.cts +39 -0
  32. package/dist/ssr.d.ts +39 -0
  33. package/dist/ssr.js +3 -0
  34. package/dist/ssr.js.map +1 -0
  35. package/package.json +81 -3
  36. package/src/client.ts +4 -0
  37. package/src/components/BlockRenderer.tsx +18 -0
  38. package/src/components/DynamicForm.tsx +54 -0
  39. package/src/components/PreviewBanner.tsx +99 -0
  40. package/src/components/SectionWrapper.tsx +1 -0
  41. package/src/components/StreamFieldRenderer.tsx +8 -0
  42. package/src/index.ts +54 -0
  43. package/src/metadata/index.ts +177 -0
  44. package/src/primitives/BpAction.tsx +78 -0
  45. package/src/primitives/BpImage.tsx +200 -0
  46. package/src/primitives/BpLink.tsx +7 -0
  47. package/src/server.ts +470 -0
  48. package/src/ssr/index.ts +167 -0
  49. package/styles.css +61 -0
  50. package/README.md +0 -3
package/src/client.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { DynamicForm, type DynamicFormProps } from "./components/DynamicForm"
2
+ import { DraftModeBanner, PreviewBanner, type PreviewBannerProps } from "./components/PreviewBanner"
3
+
4
+ export { DynamicForm, type DynamicFormProps, PreviewBanner, DraftModeBanner, type PreviewBannerProps }
@@ -0,0 +1,18 @@
1
+ import { BlockRenderer as ReactBlockRenderer, type BlockRendererProps } from "@butterflypress/react"
2
+ import { BpAction as NextBpAction } from "../primitives/BpAction"
3
+ import { BpImage as NextBpImage } from "../primitives/BpImage"
4
+ import { BpLink as NextBpLink } from "../primitives/BpLink"
5
+
6
+ export function BlockRenderer({ primitives, ...props }: BlockRendererProps) {
7
+ return (
8
+ <ReactBlockRenderer
9
+ {...props}
10
+ primitives={{
11
+ BpImage: NextBpImage as any,
12
+ BpAction: NextBpAction as any,
13
+ BpLink: NextBpLink as any,
14
+ ...primitives
15
+ }}
16
+ />
17
+ )
18
+ }
@@ -0,0 +1,54 @@
1
+ "use client"
2
+
3
+ import type {
4
+ DynamicFormFieldDefinition,
5
+ DynamicFormSubmitRequest,
6
+ DynamicFormSubmitResult
7
+ } from "@butterflypress/core"
8
+ import { BpDynamicForm } from "@butterflypress/react/client"
9
+
10
+ export interface DynamicFormProps {
11
+ formUuid: string
12
+ fields: DynamicFormFieldDefinition[]
13
+ submitLabel?: string
14
+ submittingLabel?: string
15
+ successMessage?: string
16
+ errorMessage?: string
17
+ privacyNoticeText?: string | null
18
+ requireRecaptcha?: boolean
19
+ recaptchaAction?: string
20
+ onGetRecaptchaToken?: (action: string) => Promise<string | undefined>
21
+ sourcePageUrl?: string
22
+ localeCode?: string
23
+ apiBaseUrl?: string
24
+ fetchImpl?: typeof fetch
25
+ submitHandler?: (
26
+ formUuid: string,
27
+ payload: DynamicFormSubmitRequest | Record<string, unknown>
28
+ ) => Promise<DynamicFormSubmitResult>
29
+ onSubmitted?: (payload: Record<string, unknown>, result?: DynamicFormSubmitResult) => void
30
+ onRedirect?: (url: string) => void
31
+ localizePath?: (path: string) => string
32
+ pageLinkResolver?: (pageId: number | string) => string | undefined
33
+ className?: string
34
+ }
35
+
36
+ export function DynamicForm({
37
+ submitLabel = "Enviar",
38
+ submittingLabel = "Enviando...",
39
+ successMessage = "¡Gracias! Hemos recibido tu mensaje.",
40
+ errorMessage = "No se pudo enviar el formulario. Inténtalo nuevamente.",
41
+ onSubmitted,
42
+ ...rest
43
+ }: DynamicFormProps) {
44
+ return (
45
+ <BpDynamicForm
46
+ {...rest}
47
+ submitLabel={submitLabel}
48
+ submittingLabel={submittingLabel}
49
+ successMessage={successMessage}
50
+ errorMessage={errorMessage}
51
+ onSubmitted={(result, submittedData) => onSubmitted?.(submittedData, result)}
52
+ />
53
+ )
54
+ }
@@ -0,0 +1,99 @@
1
+ "use client"
2
+
3
+ import { useState } from "react"
4
+
5
+ export interface PreviewBannerProps {
6
+ isDraftMode?: boolean
7
+ pageTitle?: string
8
+ contentType?: string
9
+ disableUrl?: string
10
+ exitLabel?: string
11
+ className?: string
12
+ onExited?: () => void
13
+ onError?: (error: Error) => void
14
+ fetchImpl?: typeof fetch
15
+ }
16
+
17
+ export function PreviewBanner({
18
+ isDraftMode = true,
19
+ pageTitle,
20
+ contentType,
21
+ disableUrl = "/api/draft/disable",
22
+ exitLabel = "Exit Preview",
23
+ className,
24
+ onExited,
25
+ onError,
26
+ fetchImpl
27
+ }: PreviewBannerProps) {
28
+ const [exiting, setExiting] = useState(false)
29
+ const [errorMessage, setErrorMessage] = useState<string | null>(null)
30
+
31
+ if (!isDraftMode) {
32
+ return null
33
+ }
34
+
35
+ async function handleExit() {
36
+ setExiting(true)
37
+ setErrorMessage(null)
38
+ try {
39
+ const fetcher = fetchImpl ?? (typeof fetch === "function" ? fetch : undefined)
40
+ if (!fetcher) {
41
+ throw new Error("Fetch API is unavailable")
42
+ }
43
+ const res = await fetcher(disableUrl, {
44
+ method: "POST",
45
+ headers: {
46
+ Accept: "application/json"
47
+ }
48
+ })
49
+ if (!res.ok) {
50
+ throw new Error(`Failed to exit preview (${res.status})`)
51
+ }
52
+ onExited?.()
53
+ if (!onExited && typeof window !== "undefined") {
54
+ window.location.reload()
55
+ }
56
+ } catch (err) {
57
+ const error = err instanceof Error ? err : new Error("Failed to exit preview")
58
+ setErrorMessage(error.message)
59
+ onError?.(error)
60
+ } finally {
61
+ setExiting(false)
62
+ }
63
+ }
64
+
65
+ return (
66
+ <div
67
+ role="region"
68
+ aria-label="Draft preview controls"
69
+ data-bp-preview-banner=""
70
+ className={[
71
+ "fixed bottom-4 right-4 z-50 flex items-center gap-3 rounded-[var(--radius)] border border-border bg-card text-card-foreground px-4 py-2.5 shadow-lg",
72
+ className
73
+ ]
74
+ .filter(Boolean)
75
+ .join(" ")}>
76
+ <span className="inline-flex items-center rounded-full bg-muted text-muted-foreground px-2.5 py-0.5 text-xs font-semibold">
77
+ Draft Preview
78
+ </span>
79
+ <div className="text-xs text-card-foreground">
80
+ {pageTitle ? <span className="font-medium">{pageTitle}</span> : <span>Unpublished revision</span>}
81
+ {contentType && <span className="ml-2 text-muted-foreground">({contentType})</span>}
82
+ </div>
83
+ {errorMessage && (
84
+ <span role="alert" data-bp-preview-error="" className="text-xs font-medium text-destructive">
85
+ {errorMessage}
86
+ </span>
87
+ )}
88
+ <button
89
+ type="button"
90
+ disabled={exiting}
91
+ onClick={handleExit}
92
+ className="inline-flex items-center justify-center rounded-[var(--radius)] bg-primary text-primary-foreground px-3 py-1.5 text-xs font-semibold hover:opacity-90 transition-opacity disabled:opacity-50">
93
+ {exiting ? "Exiting..." : exitLabel}
94
+ </button>
95
+ </div>
96
+ )
97
+ }
98
+
99
+ export const DraftModeBanner = PreviewBanner
@@ -0,0 +1 @@
1
+ export { SectionWrapper, type SectionWrapperProps } from "@butterflypress/react"
@@ -0,0 +1,8 @@
1
+ import type { BlockRendererProps } from "@butterflypress/react"
2
+ import { BlockRenderer } from "./BlockRenderer"
3
+
4
+ export type StreamFieldRendererProps = BlockRendererProps
5
+
6
+ export function StreamFieldRenderer(props: StreamFieldRendererProps) {
7
+ return <BlockRenderer {...props} />
8
+ }
package/src/index.ts ADDED
@@ -0,0 +1,54 @@
1
+ export * from "@butterflypress/core"
2
+
3
+ export {
4
+ createCaseShim,
5
+ resolveBlockComponent,
6
+ DEFAULT_BLOCK_REGISTRY,
7
+ BpRichText,
8
+ BpForm,
9
+ SemanticBlockFallback,
10
+ SectionBlock,
11
+ SplitBlock,
12
+ GridBlock,
13
+ StackBlock,
14
+ CardBlock,
15
+ HeadingBlock,
16
+ ParagraphBlock,
17
+ MediaBlock,
18
+ MediaGroupBlock,
19
+ ItemListBlock,
20
+ ActionGroupBlock,
21
+ DividerBlock,
22
+ SpacerBlock,
23
+ type ResolveBlockComponentArgs,
24
+ type BpImageRenderProps,
25
+ type BpImageProps,
26
+ type BpRichTextProps,
27
+ type BpLinkRenderProps,
28
+ type BpActionProps,
29
+ type BpLinkProps,
30
+ type BpFormProps,
31
+ type BpPrimitiveOverrides,
32
+ type BlockComponentProps,
33
+ type BlockComponentMap,
34
+ type BlockRendererProps
35
+ } from "@butterflypress/react"
36
+
37
+ export { BpImage, type NextBpImageProps } from "./primitives/BpImage"
38
+ export { BpAction, type NextBpActionProps } from "./primitives/BpAction"
39
+ export { BpLink, type NextBpLinkProps } from "./primitives/BpLink"
40
+
41
+ export { BlockRenderer } from "./components/BlockRenderer"
42
+ export { StreamFieldRenderer, type StreamFieldRendererProps } from "./components/StreamFieldRenderer"
43
+ export { SectionWrapper, type SectionWrapperProps } from "./components/SectionWrapper"
44
+
45
+ export {
46
+ DynamicForm,
47
+ PreviewBanner,
48
+ DraftModeBanner,
49
+ type DynamicFormProps,
50
+ type PreviewBannerProps
51
+ } from "@butterflypress/nextjs/client"
52
+
53
+ export * from "./ssr/index"
54
+ export * from "./metadata/index"
@@ -0,0 +1,177 @@
1
+ import { createElement } from "react"
2
+ import type { Metadata } from "next"
3
+ import {
4
+ buildThemeInlineStyle,
5
+ resolvePageSEO,
6
+ type PagePayload,
7
+ type ResolvePageSEOOptions,
8
+ type SiteConfigPayload,
9
+ type ThemeSettingsPayload
10
+ } from "@butterflypress/core"
11
+
12
+ export interface BuildNextMetadataOptions extends ResolvePageSEOOptions {
13
+ fallbackTitle?: string
14
+ isDraftMode?: boolean
15
+ twitterCard?: "summary" | "summary_large_image"
16
+ }
17
+
18
+ export function buildNextMetadata(
19
+ page?: PagePayload | null,
20
+ siteConfig?: SiteConfigPayload | null,
21
+ options: BuildNextMetadataOptions = {}
22
+ ): Metadata {
23
+ const seo = resolvePageSEO(page, siteConfig, options.fallbackTitle, options)
24
+ const siteName = siteConfig?.siteName || siteConfig?.site_name
25
+
26
+ let robots: Metadata["robots"]
27
+ if (options.isDraftMode) {
28
+ robots = { index: false, follow: false }
29
+ } else {
30
+ const robotsLower = (seo.robots || "index, follow").toLowerCase()
31
+ robots = {
32
+ index: !robotsLower.includes("noindex"),
33
+ follow: !robotsLower.includes("nofollow")
34
+ }
35
+ }
36
+
37
+ const languages =
38
+ Array.isArray(seo.alternates) && seo.alternates.length > 0
39
+ ? Object.fromEntries(seo.alternates.map((alt) => [alt.hreflang, alt.href]))
40
+ : undefined
41
+
42
+ return {
43
+ title: seo.title,
44
+ description: seo.description || undefined,
45
+ robots,
46
+ alternates:
47
+ seo.canonicalUrl || languages
48
+ ? {
49
+ ...(seo.canonicalUrl ? { canonical: seo.canonicalUrl } : {}),
50
+ ...(languages ? { languages } : {})
51
+ }
52
+ : undefined,
53
+ openGraph: {
54
+ title: seo.ogTitle || seo.title,
55
+ description: seo.ogDescription || seo.description || undefined,
56
+ type: "website",
57
+ locale: seo.ogLocale,
58
+ ...(seo.alternateOgLocales.length > 0 ? { alternateLocale: seo.alternateOgLocales } : {}),
59
+ ...(seo.canonicalUrl ? { url: seo.canonicalUrl } : {}),
60
+ ...(siteName ? { siteName } : {}),
61
+ ...(seo.ogImage ? { images: [{ url: seo.ogImage }] } : {})
62
+ },
63
+ twitter: {
64
+ card: options.twitterCard || (seo.ogImage ? "summary_large_image" : "summary"),
65
+ title: seo.ogTitle || seo.title,
66
+ description: seo.ogDescription || seo.description || undefined,
67
+ ...(seo.ogImage ? { images: [seo.ogImage] } : {})
68
+ }
69
+ }
70
+ }
71
+
72
+ export const resolveNextMetadata = buildNextMetadata
73
+
74
+ function escapeJsonForHtmlScript(jsonText: string): string {
75
+ return jsonText.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026")
76
+ }
77
+
78
+ export function buildJsonLdHtml(input?: PagePayload | Record<string, unknown> | string | null): string {
79
+ if (!input) {
80
+ return ""
81
+ }
82
+
83
+ let raw: unknown = input
84
+ if (typeof input === "object" && !Array.isArray(input)) {
85
+ const pageObj = input as Record<string, any>
86
+ if (
87
+ "structuredDataJsonLd" in pageObj ||
88
+ "structured_data_json_ld" in pageObj ||
89
+ "structuredData" in pageObj ||
90
+ "structured_data" in pageObj
91
+ ) {
92
+ raw =
93
+ pageObj.structuredDataJsonLd ||
94
+ pageObj.structured_data_json_ld ||
95
+ pageObj.structuredData ||
96
+ pageObj.structured_data
97
+ }
98
+ }
99
+
100
+ if (!raw) {
101
+ return ""
102
+ }
103
+
104
+ if (typeof raw === "string") {
105
+ const trimmed = raw.trim()
106
+ if (!trimmed) return ""
107
+ try {
108
+ const parsed = JSON.parse(trimmed)
109
+ return escapeJsonForHtmlScript(JSON.stringify(parsed))
110
+ } catch {
111
+ return ""
112
+ }
113
+ }
114
+
115
+ if (typeof raw === "object") {
116
+ return escapeJsonForHtmlScript(JSON.stringify(raw))
117
+ }
118
+
119
+ return ""
120
+ }
121
+
122
+ export interface JsonLdProps {
123
+ page?: PagePayload | null
124
+ data?: Record<string, unknown> | string | null
125
+ id?: string
126
+ }
127
+
128
+ export function JsonLd({ page, data, id = "bp-jsonld" }: JsonLdProps) {
129
+ const html = buildJsonLdHtml(data ?? page)
130
+ if (!html) {
131
+ return null
132
+ }
133
+ return createElement("script", {
134
+ id,
135
+ type: "application/ld+json",
136
+ dangerouslySetInnerHTML: { __html: html }
137
+ })
138
+ }
139
+
140
+ export interface ThemeHtmlAttributes {
141
+ "data-theme"?: string
142
+ "data-color-scheme": "light" | "dark" | "system"
143
+ "data-bs-theme"?: "light" | "dark"
144
+ className?: "light" | "dark"
145
+ }
146
+
147
+ export function getThemeHtmlAttributes(themeSettings?: ThemeSettingsPayload | null): ThemeHtmlAttributes {
148
+ const rawScheme = themeSettings?.defaultColorScheme || themeSettings?.default_color_scheme || "light"
149
+ const scheme: "light" | "dark" | "system" = rawScheme === "dark" || rawScheme === "system" ? rawScheme : "light"
150
+ const activeTheme = themeSettings?.activeTheme || themeSettings?.active_theme
151
+
152
+ return {
153
+ ...(activeTheme ? { "data-theme": activeTheme } : {}),
154
+ "data-color-scheme": scheme,
155
+ ...(scheme === "dark" || scheme === "light" ? { "data-bs-theme": scheme, className: scheme } : {})
156
+ }
157
+ }
158
+
159
+ export interface ButterflyPressThemeStylesProps {
160
+ themeSettings?: ThemeSettingsPayload | null
161
+ id?: string
162
+ }
163
+
164
+ export function ButterflyPressThemeStyles({
165
+ themeSettings,
166
+ id = "bp-dual-theme-variables"
167
+ }: ButterflyPressThemeStylesProps) {
168
+ const css = buildThemeInlineStyle(themeSettings)
169
+ if (!css) {
170
+ return null
171
+ }
172
+ const safeCss = css.replace(/<\s*\/\s*style/gi, "\\3c /style")
173
+ return createElement("style", {
174
+ id,
175
+ dangerouslySetInnerHTML: { __html: safeCss }
176
+ })
177
+ }
@@ -0,0 +1,78 @@
1
+ import NextLink, { type LinkProps as NextLinkProps } from "next/link"
2
+ import { resolveCtaUrl } from "@butterflypress/core"
3
+ import { sanitizeActionUrl, type BpActionProps } from "@butterflypress/react"
4
+
5
+ const ResolvedNextLink: any = (NextLink as any)?.$$typeof ? NextLink : (NextLink as any)?.default || NextLink
6
+
7
+ export interface NextBpActionProps extends BpActionProps {
8
+ prefetch?: NextLinkProps["prefetch"]
9
+ replace?: boolean
10
+ scroll?: boolean
11
+ shallow?: boolean
12
+ }
13
+
14
+ export function BpAction({
15
+ action,
16
+ href: explicitHref,
17
+ className,
18
+ target: explicitTarget,
19
+ rel: explicitRel,
20
+ localizePath,
21
+ linkComponent: CustomLink,
22
+ prefetch,
23
+ replace,
24
+ scroll,
25
+ shallow,
26
+ children,
27
+ ...rest
28
+ }: NextBpActionProps) {
29
+ const actionObj = action && typeof action === "object" ? (action as Record<string, any>) : null
30
+ const rawResolvedUrl = explicitHref || (actionObj ? resolveCtaUrl(actionObj as any, localizePath) : "") || "#"
31
+ const resolvedUrl = sanitizeActionUrl(rawResolvedUrl)
32
+
33
+ const openInNewTab = Boolean(actionObj?.openInNewTab ?? actionObj?.open_in_new_tab ?? explicitTarget === "_blank")
34
+ const computedTarget = explicitTarget || (openInNewTab ? "_blank" : undefined)
35
+ const computedRel = explicitRel !== undefined ? explicitRel : openInNewTab ? "noopener noreferrer" : undefined
36
+
37
+ const label = actionObj?.text ?? actionObj?.label ?? actionObj?.title ?? ""
38
+ const content = children !== undefined && children !== null ? children : label
39
+
40
+ const isInternalRoute =
41
+ resolvedUrl.startsWith("/") && !resolvedUrl.startsWith("//") && !openInNewTab && !computedTarget
42
+
43
+ if (isInternalRoute) {
44
+ if (CustomLink) {
45
+ return (
46
+ <CustomLink href={resolvedUrl} className={className || undefined} data-bp-action="" {...rest}>
47
+ {content}
48
+ </CustomLink>
49
+ )
50
+ }
51
+
52
+ return (
53
+ <ResolvedNextLink
54
+ href={resolvedUrl}
55
+ prefetch={prefetch}
56
+ replace={replace}
57
+ scroll={scroll}
58
+ shallow={shallow}
59
+ className={className || undefined}
60
+ data-bp-action=""
61
+ {...rest}>
62
+ {content}
63
+ </ResolvedNextLink>
64
+ )
65
+ }
66
+
67
+ return (
68
+ <a
69
+ href={resolvedUrl}
70
+ target={computedTarget}
71
+ rel={computedRel}
72
+ className={className || undefined}
73
+ data-bp-action=""
74
+ {...rest}>
75
+ {content}
76
+ </a>
77
+ )
78
+ }
@@ -0,0 +1,200 @@
1
+ import type { CSSProperties } from "react"
2
+ import NextImage, { type ImageProps as NextImageProps } from "next/image"
3
+ import { resolveMediaUrl } from "@butterflypress/core"
4
+ import type { BpImageProps } from "@butterflypress/react"
5
+
6
+ const ResolvedNextImage: any = (NextImage as any)?.$$typeof ? NextImage : (NextImage as any)?.default || NextImage
7
+
8
+ export interface NextBpImageProps extends BpImageProps {
9
+ fill?: boolean
10
+ priority?: boolean
11
+ preload?: boolean
12
+ unoptimized?: boolean
13
+ quality?: number | `${number}`
14
+ placeholder?: NextImageProps["placeholder"]
15
+ blurDataURL?: string
16
+ }
17
+
18
+ function resolveObjectPosition(focalPoint: unknown): string | undefined {
19
+ if (!focalPoint) {
20
+ return undefined
21
+ }
22
+ if (typeof focalPoint === "string") {
23
+ const trimmed = focalPoint.trim()
24
+ return trimmed || undefined
25
+ }
26
+ if (typeof focalPoint === "object" && focalPoint !== null) {
27
+ const fp = focalPoint as Record<string, unknown>
28
+ const rawX = typeof fp.x === "number" ? fp.x : typeof fp.left === "number" ? fp.left : undefined
29
+ const rawY = typeof fp.y === "number" ? fp.y : typeof fp.top === "number" ? fp.top : undefined
30
+ if (typeof rawX === "number" && typeof rawY === "number" && !Number.isNaN(rawX) && !Number.isNaN(rawY)) {
31
+ const pctX = rawX <= 1 && rawX >= 0 ? Math.round(rawX * 10000) / 100 : rawX
32
+ const pctY = rawY <= 1 && rawY >= 0 ? Math.round(rawY * 10000) / 100 : rawY
33
+ return `${pctX}% ${pctY}%`
34
+ }
35
+ }
36
+ return undefined
37
+ }
38
+
39
+ function buildSrcSet(
40
+ image: unknown,
41
+ mediaBaseUrl?: string,
42
+ explicitSrc?: string,
43
+ rendition?: string
44
+ ): string | undefined {
45
+ if (explicitSrc || rendition || !image || typeof image !== "object") {
46
+ return undefined
47
+ }
48
+ const renditions = (image as Record<string, any>).renditions
49
+ if (!renditions || typeof renditions !== "object" || Array.isArray(renditions)) {
50
+ return undefined
51
+ }
52
+ const entries: Array<{ width: number; url: string }> = []
53
+ const seenWidths = new Set<number>()
54
+ for (const r of Object.values(renditions)) {
55
+ if (!r || typeof r !== "object") continue
56
+ const rec = r as Record<string, any>
57
+ const w = typeof rec.width === "number" ? rec.width : Number(rec.width)
58
+ if (!w || Number.isNaN(w) || w <= 0 || seenWidths.has(w)) continue
59
+ const rawUrl = rec.url || rec.downloadUrl || rec.download_url || rec.meta?.downloadUrl || rec.meta?.download_url
60
+ const url = typeof rawUrl === "string" && rawUrl ? resolveMediaUrl(rawUrl, mediaBaseUrl) : ""
61
+ if (!url) continue
62
+ seenWidths.add(w)
63
+ entries.push({ width: w, url })
64
+ }
65
+ if (entries.length === 0) return undefined
66
+ entries.sort((a, b) => a.width - b.width)
67
+ return entries.map((e) => `${e.url} ${e.width}w`).join(", ")
68
+ }
69
+
70
+ export function BpImage({
71
+ image,
72
+ src: directSrc,
73
+ alt: explicitAlt,
74
+ rendition,
75
+ mediaBaseUrl,
76
+ className,
77
+ style,
78
+ loading = "lazy",
79
+ decoding = "async",
80
+ fetchPriority,
81
+ width,
82
+ height,
83
+ sizes,
84
+ srcSet: explicitSrcSet,
85
+ fill = false,
86
+ priority,
87
+ preload,
88
+ unoptimized,
89
+ quality,
90
+ placeholder,
91
+ blurDataURL,
92
+ imageComponent: CustomImage,
93
+ ...rest
94
+ }: NextBpImageProps) {
95
+ const mediaObj = image && typeof image === "object" ? (image as Record<string, any>) : null
96
+ const targetMedia =
97
+ rendition && mediaObj?.renditions && typeof mediaObj.renditions === "object"
98
+ ? mediaObj.renditions[rendition] || mediaObj
99
+ : image
100
+
101
+ const resolvedSrc = directSrc || resolveMediaUrl(targetMedia as any, mediaBaseUrl)
102
+ if (!resolvedSrc) {
103
+ return null
104
+ }
105
+
106
+ const resolvedAlt =
107
+ explicitAlt !== undefined
108
+ ? explicitAlt
109
+ : String(
110
+ mediaObj?.alt ??
111
+ mediaObj?.altText ??
112
+ mediaObj?.alt_text ??
113
+ mediaObj?.meta?.alt ??
114
+ mediaObj?.meta?.title ??
115
+ mediaObj?.title ??
116
+ ""
117
+ )
118
+
119
+ const targetObj = targetMedia && typeof targetMedia === "object" ? (targetMedia as Record<string, any>) : null
120
+ const rawWidth = width ?? targetObj?.width ?? mediaObj?.original?.width ?? mediaObj?.width
121
+ const rawHeight = height ?? targetObj?.height ?? mediaObj?.original?.height ?? mediaObj?.height
122
+ const numWidth = rawWidth !== undefined && rawWidth !== null ? Number(rawWidth) : undefined
123
+ const numHeight = rawHeight !== undefined && rawHeight !== null ? Number(rawHeight) : undefined
124
+ const hasValidDimensions =
125
+ typeof numWidth === "number" &&
126
+ typeof numHeight === "number" &&
127
+ !Number.isNaN(numWidth) &&
128
+ !Number.isNaN(numHeight) &&
129
+ numWidth > 0 &&
130
+ numHeight > 0
131
+
132
+ const focalPosition = resolveObjectPosition(
133
+ targetObj?.focalPoint ?? targetObj?.focal_point ?? mediaObj?.focalPoint ?? mediaObj?.focal_point
134
+ )
135
+ const mergedStyle: CSSProperties | undefined =
136
+ focalPosition || style
137
+ ? {
138
+ ...(focalPosition ? { objectPosition: focalPosition } : {}),
139
+ ...(style || {})
140
+ }
141
+ : undefined
142
+
143
+ if (CustomImage) {
144
+ return (
145
+ <CustomImage
146
+ src={resolvedSrc}
147
+ alt={resolvedAlt}
148
+ width={rawWidth}
149
+ height={rawHeight}
150
+ loading={loading}
151
+ decoding={decoding}
152
+ sizes={sizes}
153
+ srcSet={explicitSrcSet ?? buildSrcSet(image, mediaBaseUrl, directSrc, rendition)}
154
+ className={className || undefined}
155
+ style={mergedStyle}
156
+ data-bp-image=""
157
+ {...rest}
158
+ />
159
+ )
160
+ }
161
+
162
+ if (fill || hasValidDimensions) {
163
+ const resolvedLoading = priority || preload ? undefined : loading
164
+ const nextImageProps: Record<string, unknown> = {
165
+ src: resolvedSrc,
166
+ alt: resolvedAlt,
167
+ "data-bp-image": "",
168
+ ...(fill ? { fill: true } : { width: numWidth, height: numHeight }),
169
+ ...(priority !== undefined ? { priority } : {}),
170
+ ...(preload !== undefined ? { preload } : {}),
171
+ ...(resolvedLoading !== undefined ? { loading: resolvedLoading } : {}),
172
+ ...(sizes !== undefined ? { sizes } : {}),
173
+ ...(quality !== undefined ? { quality } : {}),
174
+ ...(unoptimized !== undefined ? { unoptimized } : {}),
175
+ ...(placeholder !== undefined ? { placeholder } : {}),
176
+ ...(blurDataURL !== undefined ? { blurDataURL } : {}),
177
+ ...(className ? { className } : {}),
178
+ ...(mergedStyle ? { style: mergedStyle } : {}),
179
+ ...rest
180
+ }
181
+ return <ResolvedNextImage {...nextImageProps} />
182
+ }
183
+
184
+ const resolvedSrcSet = explicitSrcSet ?? buildSrcSet(image, mediaBaseUrl, directSrc, rendition)
185
+ return (
186
+ <img
187
+ src={resolvedSrc}
188
+ alt={resolvedAlt}
189
+ loading={loading}
190
+ decoding={decoding}
191
+ {...(fetchPriority !== undefined ? { fetchPriority } : {})}
192
+ {...(resolvedSrcSet ? { srcSet: resolvedSrcSet } : {})}
193
+ {...(sizes !== undefined ? { sizes } : {})}
194
+ className={className || undefined}
195
+ style={mergedStyle}
196
+ data-bp-image=""
197
+ {...rest}
198
+ />
199
+ )
200
+ }