import { existsSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { describe, expect, test } from 'vitest' import type { ManifestField } from '../src/exports/blocks.js' import { buildBlockLibraryManifest } from '../src/exports/blocks.js' /** * Versioning guard for the block library (docs/block-library.md "Versioning"): stored content * must survive every minor release. Compared with test/block-library.schema.json: * - a field path, slug or interface name never disappears or changes type; * - a select value never disappears; a relation target never disappears; * - an existing field never becomes required, and a new field is never required. * Adding is allowed: run `UPDATE_BLOCK_SCHEMA=1 pnpm vitest run test/blockLibrarySchema.test.ts` * and commit the snapshot with the change. */ type Snapshot = Record>; interfaceName: string }> const file = path.join(import.meta.dirname, 'block-library.schema.json') const current = (): Snapshot => Object.fromEntries( buildBlockLibraryManifest().blocks.map((b) => [ b.slug, { fields: Object.fromEntries(b.fields.map(({ path: p, ...rest }) => [p, rest])), interfaceName: b.interfaceName }, ]), ) describe('block library schema (versioning)', () => { test('no stored field, value or name is removed, renamed or made required', () => { const now = current() const before = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Snapshot) : now const problems: string[] = [] for (const [slug, block] of Object.entries(before)) { const after = now[slug] if (!after) { problems.push(`${slug}: block removed`) continue } if (after.interfaceName !== block.interfaceName) {problems.push(`${slug}: interface name ${block.interfaceName} → ${after.interfaceName}`)} for (const [p, field] of Object.entries(block.fields)) { const next = after.fields[p] if (!next) { problems.push(`${slug}.${p}: removed or renamed`) continue } if (next.type !== field.type) {problems.push(`${slug}.${p}: type ${field.type} → ${next.type}`)} if (next.required && !field.required) {problems.push(`${slug}.${p}: became required`)} for (const o of field.options ?? []) { if (!next.options?.includes(o)) {problems.push(`${slug}.${p}: value "${o}" removed`)} } } for (const [p, field] of Object.entries(after.fields)) { if (!block.fields[p] && field.required) {problems.push(`${slug}.${p}: a new field must not be required`)} } } expect(problems).toEqual([]) // Only a safe change updates the snapshot. if (process.env.UPDATE_BLOCK_SCHEMA === '1' || !existsSync(file)) {writeFileSync(file, `${JSON.stringify(now, null, 2)}\n`)} }) test('the snapshot is up to date (additions are committed with the change)', () => { expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual(current()) }) })