Merge commit '977872b' into claude/ipal-doctor-build
# Conflicts: # src/modules/seo/buildSitemapEntries.ts
This commit is contained in:
@@ -1,22 +1,42 @@
|
||||
'use client'
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
import { Cookie } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { useConsentContext } from './ConsentContext.js'
|
||||
import { useIsMounted } from './useIsMounted.js'
|
||||
|
||||
/** Elements the button moves up for, so it never covers footer links. */
|
||||
export const COOKIE_BUTTON_AVOID = 'footer, [role="contentinfo"]'
|
||||
|
||||
export type CookieButtonProps = {
|
||||
/**
|
||||
* CSS selector of elements the button lifts above while they are on screen
|
||||
* (default: the site footer). `false` = never move.
|
||||
*/
|
||||
avoid?: false | string
|
||||
/** Replaces the default classes (look and position). The lift above `avoid` still applies. */
|
||||
className?: string
|
||||
/** Corner. Default 'left'. */
|
||||
side?: 'left' | 'right'
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating "cookie settings" button — lets visitors reopen the consent panel
|
||||
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
|
||||
* Hidden while the banner is showing.
|
||||
*
|
||||
* Colours follow the same design tokens as CookieBanner (--ipal-surface,
|
||||
* --ipal-border, --ipal-hover, --ipal-text), so a client's palette applies to
|
||||
* both without touching either component. Pass className to
|
||||
* replace the styling outright.
|
||||
* --ipal-border, --ipal-hover, --ipal-text). Position: --ipal-cookie-button-offset
|
||||
* (distance from the bottom, default 1rem), --ipal-cookie-button-inset (from the
|
||||
* side, default 1rem), z-index --ipal-z-header. When the footer scrolls into
|
||||
* view the button moves up by the visible part of it, so footer links stay free.
|
||||
*/
|
||||
export function CookieButton({ className }: { className?: string } = {}) {
|
||||
export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'left' }: CookieButtonProps = {}) {
|
||||
const isMounted = useIsMounted()
|
||||
const { decided, reopen, texts } = useConsentContext()
|
||||
const lift = useLiftAbove(avoid, isMounted && decided)
|
||||
|
||||
// Render nothing until mounted — prevents hydration mismatch (no project
|
||||
// ConsentWrapper workaround needed).
|
||||
@@ -25,9 +45,18 @@ export function CookieButton({ className }: { className?: string } = {}) {
|
||||
|
||||
const cls =
|
||||
className ??
|
||||
'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +
|
||||
'flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-[background-color,transform] ' +
|
||||
'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))] border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]'
|
||||
|
||||
const position: CSSProperties = className
|
||||
? {}
|
||||
: {
|
||||
bottom: 'calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))',
|
||||
position: 'fixed',
|
||||
[side]: 'var(--ipal-cookie-button-inset, 1rem)',
|
||||
zIndex: 'var(--ipal-z-header, 40)' as unknown as number,
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
// a11y label per locale: the panel's "settings title" (Cookie Settings global)
|
||||
@@ -35,6 +64,7 @@ export function CookieButton({ className }: { className?: string } = {}) {
|
||||
className={cls}
|
||||
data-ipal="cookie-button"
|
||||
onClick={reopen}
|
||||
style={{ ...position, ...(lift ? { transform: `translateY(-${lift}px)` } : {}) }}
|
||||
type="button"
|
||||
>
|
||||
<Cookie
|
||||
@@ -44,3 +74,37 @@ export function CookieButton({ className }: { className?: string } = {}) {
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** Pixels of the `avoid` elements visible at the bottom of the viewport (0 when none). */
|
||||
export function bottomOverlap(tops: number[], viewportHeight: number): number {
|
||||
const top = Math.min(...tops, viewportHeight)
|
||||
// Never push the button off the top of the screen.
|
||||
return Math.max(0, Math.min(viewportHeight - top, viewportHeight - 96))
|
||||
}
|
||||
|
||||
function useLiftAbove(selector: false | string, active: boolean): number {
|
||||
const [lift, setLift] = useState(0)
|
||||
const frame = useRef(0)
|
||||
useEffect(() => {
|
||||
if (!selector || !active) {return}
|
||||
const measure = () => {
|
||||
cancelAnimationFrame(frame.current)
|
||||
frame.current = requestAnimationFrame(() => {
|
||||
const tops = [...document.querySelectorAll(selector)].map((el) => el.getBoundingClientRect().top)
|
||||
setLift(bottomOverlap(tops, window.innerHeight))
|
||||
})
|
||||
}
|
||||
measure()
|
||||
window.addEventListener('scroll', measure, { passive: true })
|
||||
window.addEventListener('resize', measure)
|
||||
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure)
|
||||
observer?.observe(document.body)
|
||||
return () => {
|
||||
cancelAnimationFrame(frame.current)
|
||||
window.removeEventListener('scroll', measure)
|
||||
window.removeEventListener('resize', measure)
|
||||
observer?.disconnect()
|
||||
}
|
||||
}, [selector, active])
|
||||
return selector ? lift : 0
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@ export { ConsentProvider, useConsentContext } from './ConsentContext.js'
|
||||
export { ConsentScript } from './ConsentScript.js'
|
||||
export { CookieBanner } from './CookieBanner.js'
|
||||
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
|
||||
export { CookieButton } from './CookieButton.js'
|
||||
export { bottomOverlap, COOKIE_BUTTON_AVOID, CookieButton } from './CookieButton.js'
|
||||
export type { CookieButtonProps } from './CookieButton.js'
|
||||
// Client-only consent exports — hook, provider, and UI components.
|
||||
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
|
||||
export type { ConsentCookieMap } from './useConsent.js'
|
||||
|
||||
@@ -27,6 +27,8 @@ type CreateSearchRouteArgs = {
|
||||
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
|
||||
*/
|
||||
rateLimit?: { max?: number; windowMs?: number } | false
|
||||
/** SiteSettings global (the assigned 404 page is left out of results). Default 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
summaryField?: string
|
||||
}
|
||||
@@ -50,7 +52,7 @@ type CreateSearchRouteArgs = {
|
||||
* Uses the global Request/Response — no next/server import.
|
||||
*/
|
||||
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, summaryField } = args
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, settingsSlug, summaryField } = args
|
||||
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
|
||||
const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
|
||||
|
||||
@@ -85,6 +87,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
})
|
||||
const shownLocale = locale ?? config.defaultLocale
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'
|
||||
import { unlistedPageIds } from '../pages/unlistedPages.js'
|
||||
|
||||
export type SearchResult = {
|
||||
description?: string
|
||||
@@ -27,6 +28,8 @@ type SearchContentArgs = {
|
||||
payload: BasePayload
|
||||
/** Keywords. */
|
||||
query: string
|
||||
/** SiteSettings global — the assigned 404 page is left out (unlistedPageIds). Default 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/**
|
||||
* Field holding a richer AI summary (see buildSummaryField). When set and
|
||||
* present on a doc, it's preferred over meta.description for the result's
|
||||
@@ -64,6 +67,7 @@ export async function searchContent({
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
}: SearchContentArgs): Promise<SearchResult[]> {
|
||||
const q = query.trim()
|
||||
@@ -89,7 +93,25 @@ export async function searchContent({
|
||||
return []
|
||||
}
|
||||
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
|
||||
const unlisted = await readUnlisted(payload, settingsSlug)
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField, unlisted })
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids of pages with no URL of their own (the assigned 404 page), from Site settings — one small read
|
||||
* (depth 0, two fields). A missing global means none.
|
||||
*/
|
||||
async function readUnlisted(payload: BasePayload, settingsSlug = 'site-settings'): Promise<Set<number | string>> {
|
||||
try {
|
||||
const settings = (await payload.findGlobal({
|
||||
slug: settingsSlug as never,
|
||||
depth: 0,
|
||||
select: { homepage: true, notFound: true } as never,
|
||||
})) as Record<string, unknown>
|
||||
return unlistedPageIds(settings)
|
||||
} catch {
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
|
||||
type ToResultsArgs = {
|
||||
@@ -99,13 +121,15 @@ type ToResultsArgs = {
|
||||
max: number
|
||||
origin: string
|
||||
summaryField?: string
|
||||
unlisted: Set<number | string>
|
||||
}
|
||||
|
||||
/** Published, indexable docs → results. Shared by searchContent and listContent. */
|
||||
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField }: ToResultsArgs): SearchResult[] {
|
||||
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField, unlisted }: ToResultsArgs): SearchResult[] {
|
||||
const results: SearchResult[] = []
|
||||
for (const doc of docs) {
|
||||
if (doc._status && doc._status !== 'published') {continue}
|
||||
if (unlisted.has(doc.id)) {continue}
|
||||
if (doc.noindex || doc.meta?.noindex) {continue}
|
||||
const title = typeof doc.title === 'string' ? doc.title : undefined
|
||||
const slug = typeof doc.slug === 'string' ? doc.slug : undefined
|
||||
@@ -145,6 +169,7 @@ export async function listContent({
|
||||
limit = 50,
|
||||
locale,
|
||||
payload,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
}: Omit<SearchContentArgs, 'query'>): Promise<SearchResult[]> {
|
||||
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
|
||||
@@ -164,5 +189,6 @@ export async function listContent({
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
|
||||
const unlisted = await readUnlisted(payload, settingsSlug)
|
||||
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField, unlisted })
|
||||
}
|
||||
|
||||
@@ -246,6 +246,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
settingsSlug,
|
||||
summaryField,
|
||||
}), locale)
|
||||
if (results.length === 0) {return `No pages matched "${query}".`}
|
||||
|
||||
@@ -2,3 +2,4 @@ export { getSystemPagePath } from './getSystemPagePath.js'
|
||||
export { buildSystemPagesFields } from './systemPagesFields.js'
|
||||
export type { PagesOption, SystemPageRole } from './types.js'
|
||||
export { ALL_SYSTEM_PAGE_ROLES } from './types.js'
|
||||
export { unlistedPageIds } from './unlistedPages.js'
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/** A relationship value (populated or an id) → its id. */
|
||||
const idOf = (rel: unknown): number | string | undefined => {
|
||||
if (typeof rel === 'string' || typeof rel === 'number') {return rel}
|
||||
if (rel && typeof rel === 'object') {
|
||||
const id = (rel as { id?: unknown }).id
|
||||
return typeof id === 'string' || typeof id === 'number' ? id : undefined
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Pages that have no URL of their own, from Site settings → System pages: the page assigned as the
|
||||
* 404 page renders through not-found.tsx and answers 404 at its own address, so the sitemap, llms.txt
|
||||
* and the site index leave it out. A 404 page that is also the homepage stays listed.
|
||||
*/
|
||||
export function unlistedPageIds(settings: null | Record<string, unknown> | undefined): Set<number | string> {
|
||||
const ids = new Set<number | string>()
|
||||
const notFound = idOf(settings?.notFound)
|
||||
if (notFound !== undefined && notFound !== idOf(settings?.homepage)) {ids.add(notFound)}
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Texts of the 2FA screens and the user field (@clocklimited/payload-2fa reads
|
||||
* them as `totpPlugin:*` through Payload's i18n). The package ships long,
|
||||
* informal texts; these follow docs/dev/admin-ux.md. ipalKit merges them over
|
||||
* the package's and under the project's own `i18n.translations`, so a project
|
||||
* still overrides any key. `setup.description` is rendered as HTML by the package.
|
||||
*/
|
||||
const AUTHENTICATOR =
|
||||
'<a href="https://support.google.com/accounts/answer/1066447" target="_blank" rel="nofollow noopener noreferrer">Google Authenticator</a>'
|
||||
|
||||
export const TOTP_TEXTS = {
|
||||
en: {
|
||||
totpPlugin: {
|
||||
authApp: 'Authenticator app',
|
||||
configured: 'Set up',
|
||||
errors: { alreadySet: 'Two-step verification is already set up.' },
|
||||
fieldDescription: 'Codes from an authenticator app protect this account.',
|
||||
forceTotp: { description: 'The user must set up two-step verification.', label: 'Require 2FA' },
|
||||
setup: {
|
||||
addCodeManually: 'Enter the key manually',
|
||||
button: 'Set up',
|
||||
description: `Scan the QR code with an authenticator app, e.g. ${AUTHENTICATOR} or Microsoft Authenticator.`,
|
||||
enterCode: 'Enter the {digits}-digit code from the app:',
|
||||
incorrectCode: 'Incorrect code. Check the time on your phone or scan the QR code again.',
|
||||
title: 'Set up two-step verification',
|
||||
},
|
||||
verify: { title: 'Two-step verification' },
|
||||
},
|
||||
},
|
||||
pl: {
|
||||
totpPlugin: {
|
||||
authApp: 'Aplikacja uwierzytelniająca',
|
||||
configured: 'Skonfigurowano',
|
||||
errors: { alreadySet: 'Weryfikacja dwuetapowa jest już skonfigurowana.' },
|
||||
fieldDescription: 'Kody z aplikacji uwierzytelniającej chronią to konto.',
|
||||
forceTotp: { description: 'Użytkownik musi skonfigurować weryfikację dwuetapową.', label: 'Wymagaj 2FA' },
|
||||
setup: {
|
||||
addCodeManually: 'Wpisz klucz ręcznie',
|
||||
button: 'Skonfiguruj',
|
||||
description: `Zeskanuj kod QR aplikacją uwierzytelniającą, np. ${AUTHENTICATOR} lub Microsoft Authenticator.`,
|
||||
enterCode: 'Wpisz {digits}-cyfrowy kod z aplikacji:',
|
||||
incorrectCode: 'Nieprawidłowy kod. Sprawdź czas w telefonie lub zeskanuj kod QR ponownie.',
|
||||
title: 'Konfiguracja weryfikacji dwuetapowej',
|
||||
},
|
||||
verify: { title: 'Weryfikacja dwuetapowa' },
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
/** Browser-tab title of the 2FA screens (Payload view meta is a plain string: the site's language). */
|
||||
export const TOTP_VIEW_TITLE = { en: 'Two-step verification', pl: 'Weryfikacja dwuetapowa' }
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
defaultHashField,
|
||||
defaultUntouchedSeconds,
|
||||
editedSinceSeed,
|
||||
hasContent,
|
||||
isLocalizedValue,
|
||||
isUnsetValue,
|
||||
localesOf,
|
||||
localize,
|
||||
projectOnto,
|
||||
@@ -426,9 +426,12 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
if (!listed(`global:${slug}`)) {return report(notListed(label))}
|
||||
try {
|
||||
const target = { global: slug }
|
||||
const withHash = hasHashField(payload.config.globals.find((g) => g.slug === slug)?.fields as undefined | unknown[])
|
||||
const global = payload.config.globals.find((g) => g.slug === slug)
|
||||
const withHash = hasHashField(global?.fields as undefined | unknown[])
|
||||
const fieldOf = (name: string) => (global?.flattenedFields as { defaultValue?: unknown; name?: string; type?: string }[] | undefined)?.find((f) => f.name === name)
|
||||
const cur = await readSeedTarget(payload, target, defaultLocale)
|
||||
const empty = Object.keys(data).filter((k) => !hasContent(cur[k]))
|
||||
// Empty, or a choice still at its default value (e.g. Theme → light): never text an editor wrote.
|
||||
const empty = Object.keys(data).filter((k) => isUnsetValue(cur[k], fieldOf(k)))
|
||||
let keys = empty
|
||||
let edited: null | string = null
|
||||
if (update) {
|
||||
|
||||
@@ -175,6 +175,20 @@ export async function writeLocales(
|
||||
}
|
||||
|
||||
/** True when a value has content (non-empty text, a number, true, or a nested one). */
|
||||
/** Field types whose stored value is a choice, not text an editor wrote. */
|
||||
const CHOICE_TYPES = new Set(['checkbox', 'date', 'number', 'point', 'radio', 'select'])
|
||||
|
||||
/**
|
||||
* A global field nobody has set yet: empty, or — for a choice (select, radio, checkbox, number, date) —
|
||||
* still holding the field's own `defaultValue`, which Payload stores on the first save of the global.
|
||||
* Text an editor wrote is never "unset", even when it equals a default.
|
||||
*/
|
||||
export function isUnsetValue(value: unknown, field?: { defaultValue?: unknown; type?: string }): boolean {
|
||||
if (!hasContent(value)) {return true}
|
||||
if (!field || !CHOICE_TYPES.has(field.type ?? '') || field.defaultValue === undefined || typeof field.defaultValue === 'function') {return false}
|
||||
return JSON.stringify(value) === JSON.stringify(field.defaultValue)
|
||||
}
|
||||
|
||||
export function hasContent(v: unknown): boolean {
|
||||
if (typeof v === 'string') {return v.trim() !== ''}
|
||||
if (typeof v === 'number' || v === true) {return true}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { archiveFieldName } from '../content/index.js'
|
||||
import { buildLocalizedPath, getLocaleCodes , getLocalizedSlugs } from '../i18n/index.js'
|
||||
import { unlistedPageIds } from '../pages/unlistedPages.js'
|
||||
import { buildHreflangAlternates } from './hreflang.js'
|
||||
|
||||
/**
|
||||
@@ -253,11 +254,6 @@ export async function buildSitemapEntries({
|
||||
extractSlugInLocale(settings.homepage, defaultLocale) ??
|
||||
'home'
|
||||
|
||||
// The page assigned as the 404 in System pages renders with status 404 — never a sitemap URL,
|
||||
// whatever its slug (the slug list above only catches '404', 'not-found' …).
|
||||
const notFound = settings.notFound as { id?: number | string } | null | number | string | undefined
|
||||
const notFoundId = notFound && typeof notFound === 'object' ? notFound.id : notFound
|
||||
|
||||
// Which collections to walk: pages (no prefix) + each content collection with
|
||||
// its archive-page slugs as the localized prefix.
|
||||
const collections: CollectionEntry[] = [{ slug: pagesSlug }]
|
||||
@@ -269,6 +265,7 @@ export async function buildSitemapEntries({
|
||||
}
|
||||
|
||||
const entries: SitemapEntry[] = []
|
||||
const unlisted = unlistedPageIds(settings)
|
||||
|
||||
for (const collection of collections) {
|
||||
// Read every doc once, across locales, so one row yields all its language
|
||||
@@ -277,7 +274,7 @@ export async function buildSitemapEntries({
|
||||
// loads every block of every post into memory at once.
|
||||
for await (const raw of readAll(payload, collection.slug, select)) {
|
||||
if (!isIndexable(raw)) {continue}
|
||||
if (collection.slug === pagesSlug && notFoundId != null && String(raw.id) === String(notFoundId)) {continue}
|
||||
if (collection.slug === pagesSlug && unlisted.has(raw.id)) {continue}
|
||||
const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))]
|
||||
|
||||
// Emit a separate <url> for EACH locale. Google's sitemap spec for
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { I18nConfig } from '../i18n/index.js'
|
||||
import { archiveFieldName } from '../content/index.js'
|
||||
import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js'
|
||||
import { resolveLocalized } from '../i18n/resolveLocalized.js'
|
||||
import { unlistedPageIds } from '../pages/unlistedPages.js'
|
||||
|
||||
/** One public, indexable document in one language. */
|
||||
export type SiteIndexEntry = {
|
||||
@@ -154,6 +155,7 @@ export async function collectSiteIndex({
|
||||
}
|
||||
|
||||
const entries: SiteIndexEntry[] = []
|
||||
const unlisted = unlistedPageIds(settings)
|
||||
for (const locale of wanted) {
|
||||
for (const { slug: collection, prefix } of collections) {
|
||||
// An archive collection without an archive page in this locale has no URLs there.
|
||||
@@ -170,6 +172,7 @@ export async function collectSiteIndex({
|
||||
for (const doc of docs) {
|
||||
if (doc._status && doc._status !== 'published') {continue}
|
||||
if (doc.noindex || doc.meta?.noindex) {continue}
|
||||
if (collection === pagesSlug && unlisted.has(doc.id)) {continue}
|
||||
const title = typeof doc.title === 'string' ? doc.title.trim() : ''
|
||||
const slug = typeof doc.slug === 'string' ? doc.slug : ''
|
||||
if (!title || !slug || EXCLUDED_SLUGS.has(slug)) {continue}
|
||||
|
||||
@@ -14,9 +14,11 @@ export type ImagesConfig = {
|
||||
* - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
|
||||
* optimize R2 files — otherwise it refuses them;
|
||||
* - optimized images cached for 31 days (uploads get new names when replaced);
|
||||
* - outside production, media served by the app itself (`/api/media/file/**` on
|
||||
* NEXT_PUBLIC_SERVER_URL — local disk, no R2), including localhost, which
|
||||
* Next 16 otherwise refuses as a private IP.
|
||||
* - media served by the app itself (`/api/media/file/**` on NEXT_PUBLIC_SERVER_URL —
|
||||
* local disk, no R2): always outside production, and in production whenever
|
||||
* R2_PUBLIC_URL is empty (Payload then gives absolute URLs on the site's own host,
|
||||
* which next/image refuses with 400 unless they are allowed); outside production
|
||||
* also localhost, which Next 16 otherwise refuses as a private IP.
|
||||
*
|
||||
* import { buildImagesConfig } from '@intecion/ipal-kit'
|
||||
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
|
||||
@@ -39,7 +41,8 @@ export function buildImagesConfig({
|
||||
}
|
||||
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })}
|
||||
let localMedia = false
|
||||
if (!production && serverUrl && /^https?:\/\//i.test(serverUrl)) {
|
||||
const r2 = remotePatterns.length > 0
|
||||
if ((!production || !r2) && serverUrl && /^https?:\/\//i.test(serverUrl)) {
|
||||
const u = new URL(serverUrl)
|
||||
remotePatterns.push({
|
||||
hostname: u.hostname,
|
||||
@@ -47,7 +50,7 @@ export function buildImagesConfig({
|
||||
...(u.port ? { port: u.port } : {}),
|
||||
pathname: '/api/media/file/**',
|
||||
})
|
||||
localMedia = /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname)
|
||||
localMedia = !production && /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname)
|
||||
}
|
||||
return {
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
|
||||
Reference in New Issue
Block a user