1.18.0 performance items: reference 404 placeholder and heading font without preload, lazy form and Turnstile code (eager entry /client/eager), Turnstile space kept, background video paused for reduced motion, card hover on opacity, metadata stripped on upload, MongoDB TTL indexes for the consent log and statistics, unused-media notice, version limit for the plugin's entities
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
076b3ef707
commit
d628839235
@@ -0,0 +1,180 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { act, createElement } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { BackgroundVideo } from '../src/modules/block-library/ui/BackgroundVideo.js'
|
||||
import { CARD_INTERACTIVE_CLASS, CARD_INTERACTIVE_SHADOW_CLASS } from '../src/modules/block-library/ui/Card.js'
|
||||
import { Media } from '../src/modules/block-library/ui/Media.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
import { UnusedMediaNotice } from '../src/modules/media/UnusedMediaNotice.js'
|
||||
import { syncTtlIndex, TTL_FIELD, TTL_INDEX } from '../src/modules/shared/ttl.js'
|
||||
import { PLUGIN_VERSION_LIMIT, withVersionLimit } from '../src/modules/shared/versionLimit.js'
|
||||
import { Turnstile } from '../src/modules/turnstile/Turnstile.js'
|
||||
import { TURNSTILE_HEIGHT } from '../src/modules/turnstile/turnstileHeight.js'
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..')
|
||||
const read = (rel: string) => readFileSync(path.join(root, rel), 'utf8')
|
||||
|
||||
describe('lazy form code (item 3)', () => {
|
||||
test('the /client entry exports the lazy form and widget; /client/eager the eager ones; hooks are no client boundary', () => {
|
||||
expect(read('src/exports/client.ts')).toMatch(/export \{ LazyBuilderForm as BuilderForm \} from '\.\.\/modules\/forms\/LazyBuilderForm\.js'/)
|
||||
expect(read('src/modules/turnstile/client.ts')).toMatch(/export \{ LazyTurnstile as Turnstile \}/)
|
||||
expect(read('src/exports/client-eager.ts')).toMatch(/export \{ BuilderForm \} from '\.\.\/modules\/forms\/BuilderForm\.js'/)
|
||||
expect(JSON.parse(read('package.json')).exports['./client/eager']).toMatchObject({ import: './dist/exports/client-eager.js' })
|
||||
for (const hook of ['useBuilderForm', 'useForm', 'useContactForm']) {expect(read(`src/modules/forms/${hook}.ts`)).not.toMatch(/^'use client'/m)}
|
||||
// nothing imports the eager modules statically but the eager entry and the lazy wrappers' import()
|
||||
expect(read('src/modules/forms/RenderForm.tsx')).not.toMatch(/^import \{ BuilderForm \}/m)
|
||||
expect(read('src/modules/turnstile/TurnstileProvider.tsx')).toMatch(/lazy\(\(\) => import\('\.\/Turnstile\.js'\)/)
|
||||
})
|
||||
|
||||
test('the Turnstile widget keeps its height free before Cloudflare draws it; 0 turns it off', () => {
|
||||
expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, siteKey: 'k' }))).toBe(`<div style="min-height:${TURNSTILE_HEIGHT}px"></div>`)
|
||||
expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, reserveHeight: 0, siteKey: 'k' }))).toBe('<div></div>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('background video and reduced motion (item 4)', () => {
|
||||
const video = { filename: 'loop.mp4', mimeType: 'video/mp4', url: '/api/media/file/loop.mp4' }
|
||||
test('Media renders the background video through BackgroundVideo, same markup; opt-out keeps a plain <video>', () => {
|
||||
const html = renderToStaticMarkup(createElement(Media, { resource: video, videoMode: 'background' }))
|
||||
expect(html).toMatch(/^<video\b/)
|
||||
expect(html).toMatch(/autoplay=""/i)
|
||||
expect(html).toMatch(/\bloop=""/)
|
||||
expect(renderToStaticMarkup(createElement(Media, { pauseForReducedMotion: false, resource: video, videoMode: 'background' }))).toBe(html)
|
||||
})
|
||||
|
||||
test('paused for "reduce motion", played again when the setting changes', async () => {
|
||||
let matches = true
|
||||
const listeners: Array<() => void> = []
|
||||
vi.stubGlobal('matchMedia', () => ({ addEventListener: (_: string, l: () => void) => listeners.push(l), get matches() { return matches }, removeEventListener: () => {} }))
|
||||
const pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
|
||||
const play = vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(() => Promise.resolve())
|
||||
const host = document.createElement('div')
|
||||
const r = createRoot(host)
|
||||
await act(async () => r.render(createElement(BackgroundVideo, { autoPlay: true, loop: true, muted: true, src: '/v.mp4' })))
|
||||
expect(pause).toHaveBeenCalledTimes(1)
|
||||
matches = false
|
||||
await act(async () => {for (const l of listeners) {l()}})
|
||||
expect(play).toHaveBeenCalledTimes(1)
|
||||
await act(async () => r.unmount())
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
|
||||
describe('card hover (item 6)', () => {
|
||||
test('the lift fades an ::after layer (opacity), the card shadow itself does not animate; the 1.17 class stays exported', () => {
|
||||
expect(CARD_INTERACTIVE_CLASS).toMatch(/after:opacity-0/)
|
||||
expect(CARD_INTERACTIVE_CLASS).toMatch(/hover:after:opacity-100/)
|
||||
expect(CARD_INTERACTIVE_CLASS).not.toMatch(/transition-shadow/)
|
||||
expect(CARD_INTERACTIVE_SHADOW_CLASS).toMatch(/transition-shadow/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('TTL indexes (item 10)', () => {
|
||||
const fake = (indexes: Array<{ expireAfterSeconds?: number; name: string }>) => {
|
||||
const calls: string[] = []
|
||||
const coll = {
|
||||
collectionName: 'consent-records',
|
||||
createIndex: async (key: object, options: { expireAfterSeconds: number; name: string }) => {
|
||||
calls.push(`create ${JSON.stringify(key)} ${options.expireAfterSeconds}`)
|
||||
return options.name
|
||||
},
|
||||
dropIndex: async (name: string) => void calls.push(`drop ${name}`),
|
||||
indexes: async () => indexes,
|
||||
updateMany: async (filter: object, update: object[]) => {
|
||||
calls.push(`backfill ${JSON.stringify(filter)} ${JSON.stringify(update)}`)
|
||||
return {}
|
||||
},
|
||||
}
|
||||
const payload = { db: { collections: { 'consent-records': { collection: coll } }, connection: { db: { command: async (c: object) => void calls.push(`collMod ${JSON.stringify(c)}`) } }, name: 'mongoose' } }
|
||||
return { calls, payload: payload as never }
|
||||
}
|
||||
|
||||
test('created on its own field (not Payload\'s createdAt index), old records backfilled from their date', async () => {
|
||||
const { calls, payload } = fake([{ name: '_id_' }, { name: 'createdAt_1' }])
|
||||
expect(await syncTtlIndex(payload, 'consent-records', { days: 1095, enabled: true, from: 'createdAt' })).toBe('created')
|
||||
expect(calls).toEqual([
|
||||
`backfill {"${TTL_FIELD}":{"$exists":false},"createdAt":{"$type":"date"}} [{"$set":{"${TTL_FIELD}":"$createdAt"}}]`,
|
||||
`create {"${TTL_FIELD}":1} ${1095 * 86_400}`,
|
||||
])
|
||||
})
|
||||
|
||||
test('a changed retention moves the index (collMod); the same one does nothing; off drops it', async () => {
|
||||
const changed = fake([{ expireAfterSeconds: 90 * 86_400, name: TTL_INDEX }])
|
||||
expect(await syncTtlIndex(changed.payload, 'consent-records', { days: 30, enabled: true, from: 'lastAt' })).toBe('updated')
|
||||
expect(changed.calls.at(-1)).toBe(`collMod {"collMod":"consent-records","index":{"expireAfterSeconds":${30 * 86_400},"name":"${TTL_INDEX}"}}`)
|
||||
const same = fake([{ expireAfterSeconds: 30 * 86_400, name: TTL_INDEX }])
|
||||
expect(await syncTtlIndex(same.payload, 'consent-records', { days: 30, enabled: true, from: 'lastAt' })).toBe('none')
|
||||
const off = fake([{ expireAfterSeconds: 30 * 86_400, name: TTL_INDEX }])
|
||||
expect(await syncTtlIndex(off.payload, 'consent-records', { days: 30, enabled: false, from: 'lastAt' })).toBe('dropped')
|
||||
expect(off.calls).toEqual([`drop ${TTL_INDEX}`])
|
||||
})
|
||||
|
||||
test('Postgres / SQLite: nothing (the purge after a new record does it); the field is MongoDB-only', async () => {
|
||||
expect(await syncTtlIndex({ db: { name: 'drizzle' } } as never, 'consent-records', { days: 30, enabled: true, from: 'createdAt' })).toBe('none')
|
||||
expect(read('src/plugin.ts')).toMatch(/if \(isMongo\(config\)\) \{consentCollection\.fields = \[\.\.\.consentCollection\.fields, ttlField\(\)\]\}/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('versions (item 13)', () => {
|
||||
test('the plugin\'s entities with versions on get 20 unless the project set a limit', () => {
|
||||
expect(PLUGIN_VERSION_LIMIT).toBe(20)
|
||||
expect(withVersionLimit({ slug: 'site-integrations', versions: true }, 'global').versions).toEqual({ max: 20 })
|
||||
expect(withVersionLimit({ slug: 'forms', versions: { drafts: true } }, 'collection').versions).toEqual({ drafts: true, maxPerDoc: 20 })
|
||||
expect(withVersionLimit({ slug: 'forms', versions: { maxPerDoc: 0 } }, 'collection').versions).toEqual({ maxPerDoc: 0 }) // the project's own (unlimited) wins
|
||||
expect(withVersionLimit({ slug: 'forms' }, 'collection').versions).toBeUndefined()
|
||||
})
|
||||
|
||||
test('doctor hint for a project that turns versions on without a limit', async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-versions-'))
|
||||
try {
|
||||
const files: Record<string, string> = {
|
||||
'package.json': '{"name":"x-web"}',
|
||||
'src/collections/Pages.ts': "export const Pages = { slug: 'pages', versions: { drafts: { autosave: true } }, fields: [] }",
|
||||
'src/collections/Posts.ts': "export const Posts = { slug: 'posts', versions: { drafts: true, maxPerDoc: 20 }, fields: [] }",
|
||||
'src/globals/Header.ts': "export const Header = { slug: 'header', versions: true, fields: [] }",
|
||||
}
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true })
|
||||
writeFileSync(path.join(dir, rel), text)
|
||||
}
|
||||
const report = await runDoctor({ offline: true, only: ['growth-versions-config'], packageRoot: root, root: dir, today: '2026-12-01', writeSeen: false })
|
||||
expect(report.findings.map((f) => `${f.severity} ${f.file}: ${f.fix}`)).toEqual([
|
||||
'info src/collections/Pages.ts: versions: { …, maxPerDoc: 20 }',
|
||||
'info src/globals/Header.ts: versions: { max: 20 }',
|
||||
])
|
||||
} finally {
|
||||
rmSync(dir, { force: true, recursive: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('unused media in the panel (item 12)', () => {
|
||||
const payload = (docs: Record<string, object[]>) => ({
|
||||
config: { admin: { user: 'users' }, collections: [{ slug: 'media', upload: true }, { slug: 'pages' }, { slug: 'users' }], custom: { ipal: { staffCollections: ['users'] } }, globals: [] },
|
||||
find: async ({ collection }: { collection: string }) => ({ docs: docs[collection] ?? [] }),
|
||||
findGlobal: async () => ({}),
|
||||
})
|
||||
const editor = { collection: 'users', id: 1, roles: ['editor'] }
|
||||
|
||||
test('a link to Payload\'s own list filtered to the unused files — nothing is deleted', async () => {
|
||||
const p = payload({ media: [{ filename: 'a.jpg', id: 'm1' }, { filename: 'plan.pdf', id: 'm2' }, { filename: 'b.jpg', id: 'm3' }], pages: [{ hero: 'm1', text: 'see /api/media/file/plan.pdf' }] })
|
||||
const html = renderToStaticMarkup(await UnusedMediaNotice({ adminRoute: '/admin', collection: 'media', i18n: { language: 'en' }, payload: p as never, user: editor }))
|
||||
expect(html).toContain('1 file is not used on any page, entry or setting.')
|
||||
expect(html).toContain('href="/admin/collections/media?where[id][in][0]=m3"')
|
||||
expect(html).not.toMatch(/m1|m2/)
|
||||
})
|
||||
|
||||
test('nothing for a visitor account or when every file is used; only a hint when the site is too big to check here', async () => {
|
||||
const used = payload({ media: [{ filename: 'a.jpg', id: 'm1' }], pages: [{ hero: 'm1' }] })
|
||||
expect(await UnusedMediaNotice({ collection: 'media', payload: used as never, user: editor })).toBeNull()
|
||||
expect(await UnusedMediaNotice({ collection: 'media', payload: used as never, user: null })).toBeNull()
|
||||
const broken = { ...used, find: async ({ collection }: { collection: string }) => { if (collection === 'pages') {throw new Error('no')} return { docs: [{ filename: 'a.jpg', id: 'm1' }] } } }
|
||||
expect(renderToStaticMarkup(await UnusedMediaNotice({ collection: 'media', payload: broken as never, user: editor }))).toContain('too many documents to check')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import sharp from 'sharp'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { buildOptimizeUploadHook } from '../src/modules/media/optimizeUpload.js'
|
||||
import { exifOrientation, stripImageMetadata } from '../src/modules/media/stripMetadata.js'
|
||||
|
||||
/** A small JPEG with EXIF (camera, GPS-like comment, orientation) and an ICC profile. */
|
||||
const jpegWith = (orientation = 1) =>
|
||||
sharp({ create: { background: { b: 40, g: 120, r: 200 }, channels: 3, height: 24, width: 40 } })
|
||||
.withMetadata({ exif: { IFD0: { Copyright: 'Example', Make: 'PhoneCo', Model: 'X1' } }, orientation })
|
||||
.withIccProfile('srgb')
|
||||
.jpeg({ quality: 90 })
|
||||
.toBuffer()
|
||||
|
||||
const pngWithText = async () => {
|
||||
const png = await sharp({ create: { background: '#336699', channels: 4, height: 8, width: 8 } }).png().toBuffer()
|
||||
// a tEXt chunk after IHDR: "Comment\0secret place"
|
||||
const data = Buffer.from('Comment\0secret place', 'latin1')
|
||||
const chunk = Buffer.alloc(12 + data.length)
|
||||
chunk.writeUInt32BE(data.length, 0)
|
||||
chunk.write('tEXt', 4, 'latin1')
|
||||
data.copy(chunk, 8)
|
||||
chunk.writeUInt32BE(0, 8 + data.length) // CRC is not checked by the stripper (the chunk is dropped)
|
||||
const ihdrEnd = 8 + 12 + png.readUInt32BE(8)
|
||||
return Buffer.concat([png.subarray(0, ihdrEnd), chunk, png.subarray(ihdrEnd)])
|
||||
}
|
||||
|
||||
describe('stripImageMetadata', () => {
|
||||
test('JPEG: EXIF goes, the image data and the colour profile stay byte for byte', async () => {
|
||||
const input = await jpegWith()
|
||||
expect(input.includes(Buffer.from('PhoneCo'))).toBe(true)
|
||||
const { buffer, changed, orientation } = stripImageMetadata(input, 'image/jpeg')
|
||||
expect(changed).toBe(true)
|
||||
expect(orientation).toBe(1)
|
||||
expect(buffer.includes(Buffer.from('PhoneCo'))).toBe(false)
|
||||
const before = await sharp(input).metadata()
|
||||
const after = await sharp(buffer).metadata()
|
||||
expect(after.exif).toBeUndefined()
|
||||
expect(after.icc).toBeDefined() // the colour profile is kept
|
||||
expect([after.width, after.height]).toEqual([before.width, before.height])
|
||||
// same pixels: no re-encode
|
||||
expect(await sharp(buffer).raw().toBuffer()).toEqual(await sharp(input).raw().toBuffer())
|
||||
const sos = (b: Buffer) => b.subarray(b.indexOf(Buffer.from([0xff, 0xda])))
|
||||
expect(sos(buffer).equals(sos(input))).toBe(true)
|
||||
})
|
||||
|
||||
test('JPEG: the EXIF orientation is reported, so the caller can turn the pixels first', async () => {
|
||||
expect(stripImageMetadata(await jpegWith(6), 'image/jpeg').orientation).toBe(6)
|
||||
expect(exifOrientation(Buffer.from('not exif'))).toBe(1)
|
||||
})
|
||||
|
||||
test('PNG: text chunks go, the pixels stay', async () => {
|
||||
const input = await pngWithText()
|
||||
expect(input.includes(Buffer.from('secret place'))).toBe(true)
|
||||
const { buffer, changed } = stripImageMetadata(input, 'image/png')
|
||||
expect(changed).toBe(true)
|
||||
expect(buffer.includes(Buffer.from('secret place'))).toBe(false)
|
||||
expect(await sharp(buffer).raw().toBuffer()).toEqual(await sharp(input).raw().toBuffer())
|
||||
})
|
||||
|
||||
test('nothing to strip, another format or a broken file: returned unchanged', async () => {
|
||||
const clean = await sharp({ create: { background: '#000', channels: 3, height: 4, width: 4 } }).jpeg().toBuffer()
|
||||
expect(stripImageMetadata(clean, 'image/jpeg').changed).toBe(false)
|
||||
const webp = await sharp(clean).webp().toBuffer()
|
||||
expect(stripImageMetadata(webp, 'image/webp')).toEqual({ buffer: webp, changed: false, orientation: 1 })
|
||||
const broken = Buffer.from([0xff, 0xd8, 0x00, 0x01, 0x02])
|
||||
expect(stripImageMetadata(broken, 'image/jpeg').buffer).toBe(broken)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildOptimizeUploadHook: metadata on uploads that pass the limits', () => {
|
||||
const run = async (data: Buffer, options = {}) => {
|
||||
const file = { data, mimetype: 'image/jpeg', name: 'photo.jpg', size: data.length }
|
||||
await buildOptimizeUploadHook(options)({ args: { data: {} }, operation: 'create', req: { file, i18n: { language: 'en' }, payload: { config: { sharp } } } } as never)
|
||||
return file
|
||||
}
|
||||
test('stripped by default; an EXIF rotation is applied to the pixels; `stripMetadata: false` keeps the file', async () => {
|
||||
const plain = await run(await jpegWith())
|
||||
expect(plain.data.includes(Buffer.from('PhoneCo'))).toBe(false)
|
||||
expect(plain.name).toBe('photo.jpg') // same format and name: only the metadata went
|
||||
|
||||
const turned = await run(await jpegWith(6)) // 40×24 stored, "rotate 90°" in EXIF
|
||||
const meta = await sharp(turned.data).metadata()
|
||||
expect([meta.width, meta.height, meta.orientation]).toEqual([24, 40, undefined])
|
||||
|
||||
const original = await jpegWith()
|
||||
expect((await run(original, { stripMetadata: false })).data).toBe(original)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user