From 14fd2c497f35295e2f5f67851c06656f76d5d1a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:17:42 +0200 Subject: [PATCH] Server entries no longer load 'use client' modules The main entry and next/middleware re-exported module barrels that also export React client components (LanguageSwitcher, AlternateLinks*, AccessibilityWidget), so payload.config, the CLI and the proxy bundle evaluated React UI. They now import concrete files; i18n client components moved to modules/i18n/client.ts. test/entryGraph guards it. Also lint fixes in tests added on this branch. Co-Authored-By: Claude Opus 5.5 --- src/exports/client.ts | 16 +++---- src/exports/next-middleware.ts | 8 ++-- src/index.ts | 33 ++++++--------- src/modules/consent/index.ts | 1 - src/modules/content/createSearchRoute.ts | 6 +-- src/modules/frontend/createContentHelpers.ts | 2 +- src/modules/i18n/client.ts | 11 +++++ src/modules/i18n/index.ts | 10 +---- src/modules/mcp/createMcpRoute.ts | 10 ++--- src/plugin.ts | 2 +- src/types.ts | 2 +- test/construction.test.ts | 4 +- test/entryGraph.test.ts | 44 ++++++++++++++++++++ test/hooksReq.test.ts | 2 +- test/rateLimit.test.ts | 2 +- test/redirectDrafts.test.ts | 6 +-- test/revalidateGlobals.test.ts | 2 +- test/settingsDepth.test.ts | 4 +- 18 files changed, 102 insertions(+), 63 deletions(-) create mode 100644 src/modules/i18n/client.ts create mode 100644 test/entryGraph.test.ts diff --git a/src/exports/client.ts b/src/exports/client.ts index 40ba644..bb0ba85 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -58,6 +58,14 @@ export { required, } from '../modules/forms/validators.js' export type { Rule } from '../modules/forms/validators.js' +export { + AlternateLinksProvider, + AlternateLinksUpdater, + LanguageSwitcher, + useAlternateLinks, + useSetAlternateLinks, +} from '../modules/i18n/client.js' +export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/client.js' // Pure i18n path helpers — no server/RSC deps, safe to import in client // components (e.g. a LanguageSwitcher that computes locale URLs on the client). export { @@ -67,14 +75,6 @@ export { switchLocalePath, } from '../modules/i18n/index.js' export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js' -export { - AlternateLinksProvider, - AlternateLinksUpdater, - LanguageSwitcher, - useAlternateLinks, - useSetAlternateLinks, -} from '../modules/i18n/index.js' -export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' export { LocaleView } from '../modules/pages/LocaleView.js' export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js' export { TableOfContents } from '../modules/richtext/TableOfContents.js' diff --git a/src/exports/next-middleware.ts b/src/exports/next-middleware.ts index 93f50d3..bfa9e17 100644 --- a/src/exports/next-middleware.ts +++ b/src/exports/next-middleware.ts @@ -5,6 +5,8 @@ * client project's middleware.ts. Kept as a thin re-export so the Next-facing * surface is separate from the main package export. */ -export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js' -export type { LocaleMiddlewareResult } from '../modules/i18n/index.js' -export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js' +// Concrete files, not the i18n barrel — it re-exports client components, which +// have no place in the proxy bundle (test/entryGraph). +export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/createProxy.js' +export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/localeMiddleware.js' +export type { LocaleMiddlewareResult } from '../modules/i18n/localeMiddleware.js' diff --git a/src/index.ts b/src/index.ts index b801ebf..42b056c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,8 +13,10 @@ export { requireRoleField, ROLE_HIERARCHY, } from './modules/access/index.js' -export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js' -export type { A11yState } from './modules/accessibility/index.js' +// Concrete files, not module barrels: a barrel that also re-exports 'use client' +// components would load React UI into payload.config / the CLI (test/entryGraph). +export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js' +export type { A11yState } from './modules/accessibility/state.js' export { rowLabel } from './modules/admin-ui/index.js' export type { RowLabelProps } from './modules/admin-ui/index.js' export type { AnalyticsConfig } from './modules/analytics/index.js' @@ -113,26 +115,15 @@ export { createContentHelpers } from './modules/frontend/index.js' // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). export { createHealthRoute } from './modules/health/index.js' export { buildCrossLocaleFieldSync, buildGlobalRevalidateHook, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js' +export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/createProxy.js' +export { getLocalizedSlugs } from './modules/i18n/getLocalizedSlugs.js' +export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './modules/i18n/helpers.js' export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js' -export { - buildLocalizedPath, - getDefaultLocale, - getLocaleCodes, - getLocaleDefinition, - getLocalizedSlugs, - isValidLocale, - LOCALE_COOKIE_NAME, - matchAcceptLanguage, - negotiateLocale, - switchLocalePath, -} from './modules/i18n/index.js' -export type { LocaleMiddlewareResult } from './modules/i18n/index.js' -export { - createLocaleMiddleware, - DEFAULT_MIDDLEWARE_MATCHER, -} from './modules/i18n/index.js' -export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js' -export { resolveLocalized } from './modules/i18n/index.js' +export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/localeMiddleware.js' +export type { LocaleMiddlewareResult } from './modules/i18n/localeMiddleware.js' +export { buildLocalizedPath, switchLocalePath } from './modules/i18n/localizedPath.js' +export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './modules/i18n/negotiateLocale.js' +export { resolveLocalized } from './modules/i18n/resolveLocalized.js' export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js' export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js' export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js' diff --git a/src/modules/consent/index.ts b/src/modules/consent/index.ts index bc06c7e..b6265da 100644 --- a/src/modules/consent/index.ts +++ b/src/modules/consent/index.ts @@ -23,4 +23,3 @@ export { serializeConsent, } from './storage.js' export type { ConsentTexts } from './texts.js' -export { useIsMounted } from './useIsMounted.js' diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index 251a504..a236604 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -3,7 +3,7 @@ import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' import type { ClientIpOptions } from '../shared/rateLimit.js' -import { type PathVisibility, pathOf } from '../construction/visibility.js' +import { pathOf, type PathVisibility } from '../construction/visibility.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { searchContent } from './searchContent.js' @@ -20,6 +20,8 @@ type CreateSearchRouteArgs = { getCachedPayload: () => Promise /** Home slug map/string so the home result collapses to root. */ homeSlug?: Record | string + /** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */ + isPathVisible?: PathVisibility /** * Per-IP limit (in memory per instance, or the store from setRateLimitStore). Default { max: 120, windowMs: 60_000 }. * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting). @@ -27,8 +29,6 @@ type CreateSearchRouteArgs = { rateLimit?: { max?: number; windowMs?: number } | false /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */ summaryField?: string - /** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */ - isPathVisible?: PathVisibility } /** diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 1f730e4..25094e7 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -776,7 +776,6 @@ export function createContentHelpers({ getCachedPayload, getConfiguredLocales, getConstructionMode, - isPathVisible, getEntries, getFormTexts, getHomeSlug, @@ -789,6 +788,7 @@ export function createContentHelpers({ healthRoute, i18n, indexNowKeyRoute, + isPathVisible, llmsFullRoute, llmsRoute, manifest, diff --git a/src/modules/i18n/client.ts b/src/modules/i18n/client.ts new file mode 100644 index 0000000..86cf63c --- /dev/null +++ b/src/modules/i18n/client.ts @@ -0,0 +1,11 @@ +// Client components of the i18n module — kept out of ./index.ts so server +// code importing i18n helpers never loads React UI (test/entryGraph). +export { + AlternateLinksProvider, + useAlternateLinks, + useSetAlternateLinks, +} from './AlternateLinksContext.js' +export type { AlternateLinks } from './AlternateLinksContext.js' +export { AlternateLinksUpdater } from './AlternateLinksUpdater.js' +export { LanguageSwitcher } from './LanguageSwitcher.js' +export type { LanguageSwitcherClassNames } from './LanguageSwitcher.js' diff --git a/src/modules/i18n/index.ts b/src/modules/i18n/index.ts index f0436d6..bfa101f 100644 --- a/src/modules/i18n/index.ts +++ b/src/modules/i18n/index.ts @@ -1,15 +1,7 @@ -export { - AlternateLinksProvider, - useAlternateLinks, - useSetAlternateLinks, -} from './AlternateLinksContext.js' -export type { AlternateLinks } from './AlternateLinksContext.js' -export { AlternateLinksUpdater } from './AlternateLinksUpdater.js' +// Client components (LanguageSwitcher, AlternateLinks*) live in ./client.ts. export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js' export { getLocalizedSlugs } from './getLocalizedSlugs.js' export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js' -export { LanguageSwitcher } from './LanguageSwitcher.js' -export type { LanguageSwitcherClassNames } from './LanguageSwitcher.js' export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js' export type { LocaleMiddlewareResult } from './localeMiddleware.js' export { buildLocalizationConfig } from './localizationConfig.js' diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index 0dd27a4..8046042 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -59,6 +59,11 @@ export type CreateMcpRouteArgs = { /** Archive-backed collections (same as the plugin option) for get_page. */ content?: ContentOption getCachedPayload: () => Promise + /** + * Hide pages the site hides (construction mode): filtered out of list_pages + * and search_content, "not found" in get_page. createContentHelpers passes it. + */ + isPathVisible?: PathVisibility /** Max messages in one JSON-RPC batch. Default 10. */ maxBatch?: number /** @@ -74,11 +79,6 @@ export type CreateMcpRouteArgs = { settingsSlug?: string /** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */ summaryField?: string - /** - * Hide pages the site hides (construction mode): filtered out of list_pages - * and search_content, "not found" in get_page. createContentHelpers passes it. - */ - isPathVisible?: PathVisibility } type JsonRpcId = null | number | string diff --git a/src/plugin.ts b/src/plugin.ts index 2aaea8f..3a10e71 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -14,10 +14,10 @@ import { buildArchiveFields } from './modules/content/index.js' import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js' import { emailSettingsFields } from './modules/forms/emailLayout.js' import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' +import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' -import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js' import { buildIndexNowHook } from './modules/seo/indexNow.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' diff --git a/src/types.ts b/src/types.ts index fe646dd..5a48cae 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,10 +12,10 @@ export type TotpPluginFactory = (options: { forceSetup: boolean totp: { issuer: string } }) => Plugin -import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { AccessOption } from './modules/access/types.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' +import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { I18nConfig } from './modules/i18n/types.js' import type { PagesOption } from './modules/pages/types.js' import type { SeoOption } from './modules/seo/types.js' diff --git a/test/construction.test.ts b/test/construction.test.ts index 7a23f1a..b1878c6 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -92,14 +92,14 @@ describe('under construction — Site Settings → createPageRoute', () => { const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }) expect((await helpers.getConstructionMode('pl')).enabled).toBe(true) - const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ locale: 'pl', slug }) }) + const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ slug, locale: 'pl' }) }) expect((await md(['o-nas'])).status).toBe(404) expect((await md(['brief'])).status).toBe(200) const rpc = async (name: string, args: Record) => { const res = await helpers.mcpPOST( new Request('https://acme.pl/api/mcp', { - body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { arguments: args, name } }), + body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name, arguments: args } }), headers: { 'content-type': 'application/json', 'x-real-ip': '198.51.100.4' }, method: 'POST', }), diff --git a/test/entryGraph.test.ts b/test/entryGraph.test.ts new file mode 100644 index 0000000..e7d04e4 --- /dev/null +++ b/test/entryGraph.test.ts @@ -0,0 +1,44 @@ +/** + * The main entry (payload.config, the payload CLI, server code) and the proxy + * entry must not load 'use client' modules: in plain Node every re-exported + * module is evaluated, and the proxy bundle should stay free of React UI. + */ +import { existsSync, readFileSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +const root = path.resolve(import.meta.dirname, '..') + +function resolve(from: string, spec: string): null | string { + if (!spec.startsWith('.')) {return null} + const base = path.resolve(path.dirname(from), spec).replace(/\.js$/, '') + for (const ext of ['.ts', '.tsx', '/index.ts']) { + if (existsSync(base + ext)) {return base + ext} + } + return null +} + +/** Runtime (non-type) imports and re-exports reachable from `entry`; returns the 'use client' ones. */ +function clientModulesReachable(entry: string): string[] { + const seen = new Set() + const hits: string[] = [] + const stack = [path.join(root, entry)] + while (stack.length) { + const file = stack.pop()! + if (seen.has(file)) {continue} + seen.add(file) + const src = readFileSync(file, 'utf8') + if (/^\s*['"]use client['"]/.test(src)) {hits.push(path.relative(root, file))} + for (const m of src.matchAll(/^(?:import|export) (?!type\b)[^'"]*?from ['"]([^'"]+)['"]/gm)) { + const next = resolve(file, m[1]) + if (next) {stack.push(next)} + } + } + return hits.sort() +} + +describe('server entries load no client modules', () => { + test.each(['src/exports/next-middleware.ts', 'src/index.ts'])('%s', (entry) => { + expect(clientModulesReachable(entry)).toEqual([]) + }) +}) diff --git a/test/hooksReq.test.ts b/test/hooksReq.test.ts index ff5540c..362f6f0 100644 --- a/test/hooksReq.test.ts +++ b/test/hooksReq.test.ts @@ -4,7 +4,7 @@ import { describe, expect, test, vi } from 'vitest' import { buildCrossLocaleFieldSync } from '../src/modules/hooks/buildCrossLocaleFieldSync.js' import { buildPreventDeleteSystemPage } from '../src/modules/hooks/preventDeleteSystemPage.js' -const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } +const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const /** Mimics the Local API: a call with `req` sets req.locale / req.fallbackLocale to its own. */ function fakeReq() { diff --git a/test/rateLimit.test.ts b/test/rateLimit.test.ts index a5bf341..d727618 100644 --- a/test/rateLimit.test.ts +++ b/test/rateLimit.test.ts @@ -3,9 +3,9 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { checkRateLimit, clientIp, - UNKNOWN_IP_FACTOR, consumeRateLimit, setRateLimitStore, + UNKNOWN_IP_FACTOR, } from '../src/modules/shared/rateLimit.js' const req = (headers: Record) => new Request('http://x/', { headers }) diff --git a/test/redirectDrafts.test.ts b/test/redirectDrafts.test.ts index 0a228af..79575ff 100644 --- a/test/redirectDrafts.test.ts +++ b/test/redirectDrafts.test.ts @@ -4,17 +4,17 @@ import { describe, expect, test, vi } from 'vitest' import { resolveRedirect } from '../src/modules/content/resolveRedirect.js' -const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }] } +const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }] } as const const payloadWith = (doc: object) => ({ find: vi.fn(async () => ({ docs: [doc] })) }) as unknown as BasePayload describe('old-slug redirects and drafts', () => { test('a published page redirects from its old slug', async () => { - const payload = payloadWith({ _status: 'published', slug: 'nowa-oferta' }) + const payload = payloadWith({ slug: 'nowa-oferta', _status: 'published' }) expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBe('/nowa-oferta') }) test('a never-published draft does not redirect (its new slug stays private)', async () => { - const payload = payloadWith({ _status: 'draft', slug: 'tajny-projekt' }) + const payload = payloadWith({ slug: 'tajny-projekt', _status: 'draft' }) expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBeNull() }) diff --git a/test/revalidateGlobals.test.ts b/test/revalidateGlobals.test.ts index f1ff0d9..7f46200 100644 --- a/test/revalidateGlobals.test.ts +++ b/test/revalidateGlobals.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { buildGlobalRevalidateHook } from '../src/modules/hooks/buildRevalidateHook.js' import { ipalKit } from '../src/plugin.js' -const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } +const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const const run = (g: GlobalConfig | undefined, context: object = {}) => g?.hooks?.afterChange?.forEach((h) => h({ context, doc: {}, global: g, previousDoc: {}, req: {} } as never)) diff --git a/test/settingsDepth.test.ts b/test/settingsDepth.test.ts index d66880b..fe6b392 100644 --- a/test/settingsDepth.test.ts +++ b/test/settingsDepth.test.ts @@ -51,12 +51,12 @@ beforeAll(async () => { const media = await payload.create({ collection: 'media' as never, data: { alt: 'hero' } as never, - file: { data: png, mimetype: 'image/png', name: 'hero.png', size: png.length }, + file: { name: 'hero.png', data: png, mimetype: 'image/png', size: png.length }, }) mediaId = media.id const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', hero: mediaId, title: 'Home' } as never }) const blog = await payload.create({ collection: 'pages' as never, data: { slug: 'blog', hero: mediaId, title: 'Blog' } as never }) - await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, featured: home.id, postsArchive: blog.id, siteName: 'Acme' } as never }) + await payload.updateGlobal({ slug: 'site-settings' as never, data: { featured: home.id, homepage: home.id, postsArchive: blog.id, siteName: 'Acme' } as never }) }, 60_000) afterAll(async () => {