Files
ipal-kit/test/construction.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 546806fe39 Admin follow-ups: localised stats tab title, scanner names, close label, favicon hint
- Statistics view: the browser-tab title follows the admin language.
  Payload's custom-view meta.title is one plain string and its custom-view
  metadata ignores i18n, so the view renders <DocumentTitle> (/admin) with the
  translated title; it re-applies the title while the view is open because
  Next streams the English metadata in after hydration. adminDocumentTitle()
  adds admin.meta.titleSuffix the way Payload does.
- Cookie scanner: CookieIntegration.label may be { en, pl, ... }. The built-in
  names without a product name come from the shared admin texts
  (cookieIntegration*, cookieSourceProject); the scan endpoint answers in the
  request's admin language and stored source names use the scanning editor's.
- Maintenance notice: getConstructionMode(locale) returns `locale`; the "x"
  close button gets a screen-reader name "Close" / "Zamknij" (locale and
  closeLabel props; constructionCloseLabel exported).
- Favicon: FaviconCheck (/admin, afterInput on Site settings -> Site icon)
  warns in the admin language when the image is under 48x48 or not square,
  without blocking the save; validateFaviconField shares faviconProblems().
- Docs, AGENT.md and skills: the above, plus Next.js 16.4.1 or later as the
  minimum safe version (AGENT.md 4.11, ipal-setup, ipal-upgrade).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:31:46 +01:00

160 lines
7.8 KiB
TypeScript

import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { constructionNoticeHref, isPathAllowed, isPathVisibleIn, normalizePath } from '../src/modules/construction/logic.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
describe('under construction — path logic', () => {
test('paths compare without a trailing slash; the notice link carries the parameter', () => {
expect(normalizePath('/pl/')).toBe('/pl')
expect(normalizePath('')).toBe('/')
expect(isPathAllowed('/pl/brief/', ['/pl', '/pl/brief'])).toBe(true)
expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false)
expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction')
})
test('isPathVisibleIn: off → everything; on → allowed paths only', () => {
expect(isPathVisibleIn({ allowedPaths: [], enabled: false }, '/pl/o-nas')).toBe(true)
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/brief/')).toBe(true)
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/o-nas')).toBe(false)
})
})
describe('under construction — Site Settings → createPageRoute', () => {
let payload: Payload
let configPromise: Parameters<typeof getPayload>[0]['config']
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
beforeAll(async () => {
configPromise = buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', index: true, localized: true }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-construction') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'construction-test-secret',
telemetry: false,
})
payload = await getPayload({ config: configPromise })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
const redirectError = (url: string): never => {
throw new Error(`REDIRECT ${url}`)
}
const route = () =>
createPageRoute(createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n }), {
blocks: {},
notFound: () => {
throw new Error('NEXT_NOT_FOUND')
},
permanentRedirect: vi.fn() as unknown as (url: string) => never,
redirect: redirectError,
})
const open = (locale: string, slug?: string[]) => route().Page({ params: Promise.resolve({ slug, locale }) })
test('off: pages open normally; on: only the homepage and the chosen pages, everything else → homepage + notice', async () => {
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', title: 'Start' } as never, locale: 'pl' as never })
const brief = await payload.create({ collection: 'pages' as never, data: { slug: 'brief', title: 'Brief' } as never, locale: 'pl' as never })
await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', title: 'O nas' } as never, locale: 'pl' as never })
await payload.update({ id: brief.id, collection: 'pages' as never, data: { slug: 'project-brief' } as never, locale: 'en' as never })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
await expect(open('pl', ['o-nas'])).resolves.toBeTruthy()
await payload.updateGlobal({
slug: 'site-settings' as never,
data: { construction: { allowedPages: [brief.id], enabled: true, message: 'Strona w budowie', title: 'Pracujemy nad stroną' } } as never,
locale: 'pl' as never,
})
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
const mode = await helpers.getConstructionMode('pl')
expect(mode).toMatchObject({ enabled: true, homePath: '/pl', locale: 'pl', texts: { message: 'Strona w budowie', title: 'Pracujemy nad stroną' } })
expect(mode.allowedPaths).toEqual(expect.arrayContaining(['/pl', '/pl/brief', '/en', '/en/project-brief']))
await expect(open('pl')).resolves.toBeTruthy()
await expect(open('pl', ['brief'])).resolves.toBeTruthy()
await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction')
await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction')
})
test('on: Markdown, MCP and search hide the same pages the page route hides', async () => {
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({ 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<string, unknown>) => {
const res = await helpers.mcpPOST(
new Request('https://acme.pl/api/mcp', {
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',
}),
)
return ((await res.json()) as { result: { content: { text: string }[] } }).result.content[0].text
}
const list = await rpc('list_pages', { locale: 'pl' })
expect(list).toContain('/pl/brief')
expect(list).not.toContain('/pl/o-nas')
expect(await rpc('get_page', { path: '/pl/o-nas' })).toMatch(/No page found/)
expect(await rpc('search_content', { locale: 'pl', query: 'nas' })).not.toContain('/pl/o-nas')
// a whole list shares one construction-mode read (React cache doesn't dedupe in route handlers)
const readsFor = async (n: number) => {
const spy = vi.spyOn(payload, 'findGlobal')
await Promise.all(Array.from({ length: n }, (_, i) => helpers.isPathVisible(`/pl/p-${i}`, 'pl')))
const count = spy.mock.calls.length
spy.mockRestore()
return count
}
expect(await readsFor(50)).toBe(await readsFor(1))
expect(await helpers.isPathVisible('/pl/o-nas', 'pl')).toBe(false)
expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true)
})
})
describe('under construction — opting out per route', () => {
test('a project can pass its own isPathVisible to Markdown / MCP', async () => {
const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js')
const seen: string[] = []
const mcp = createMcpRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] },
getCachedPayload: async () => ({}) as never,
isPathVisible: (path) => {
seen.push(path)
return false
},
rateLimit: false,
})
const res = await mcp.POST(
new Request('https://x/api/mcp', {
body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name: 'get_page', arguments: { path: '/pl/o-nas' } } }),
method: 'POST',
}),
)
expect(JSON.stringify(await res.json())).toContain('No page found')
expect(seen).toEqual(['/pl/o-nas'])
})
})