Files
Reims-Go/frontend/scripts/check-ui-contract.mjs
T

62 lines
2.5 KiB
JavaScript

import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootDir = path.resolve(__dirname, '..')
const srcDir = path.join(rootDir, 'src')
const contractSrc = fs.readFileSync(path.join(srcDir, 'styles', 'ui-contract.ts'), 'utf8')
const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8')
function extractArray(name) {
const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`)
const m = contractSrc.match(re)
if (!m) throw new Error(`Could not parse ${name} from ui-contract.ts`)
return [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1])
}
const apiMatch = contractSrc.match(/UI_API_VERSION\s*=\s*'([^']+)'/)
const uiApi = apiMatch ? apiMatch[1] : '1.0.0'
const parts = extractArray('UI_CONTRACT_PARTS')
const stateAttrs = extractArray('UI_CONTRACT_STATE_ATTRS')
const slots = extractArray('UI_CONTRACT_SLOTS')
const tokens = extractArray('UI_CONTRACT_TOKENS')
// Collect all React component TSX source text (excluding contract/SDK/theme helpers)
// and verify every declared part class is emitted as a distinct class token (§5.1, M17).
function readComponentTsx(dir) {
let buf = ''
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) buf += readComponentTsx(full)
else if (entry.name.endsWith('.tsx')) buf += '\n' + fs.readFileSync(full, 'utf8')
}
return buf
}
const allTsx = readComponentTsx(srcDir)
const missingParts = parts.filter((p) => {
const re = new RegExp(`(?<![a-zA-Z0-9_-])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![a-zA-Z0-9_-])`)
return !re.test(allTsx)
})
const missingTokens = tokens.filter((tk) => !tokensCss.includes(`${tk}:`))
if (missingParts.length > 0) {
console.error('[ui-contract] ERROR: contract parts not emitted by any component:', missingParts.join(', '))
process.exit(1)
}
if (missingTokens.length > 0) {
console.error('[ui-contract] ERROR: contract tokens missing in tokens.css:', missingTokens.join(', '))
process.exit(1)
}
const out = { uiApi, tokens, parts, stateAttrs, slots }
const jsonText = JSON.stringify(out, null, 2) + '\n'
fs.writeFileSync(path.join(rootDir, 'ui-contract.json'), jsonText, 'utf8')
const distDir = path.join(rootDir, 'dist')
if (fs.existsSync(distDir)) {
fs.writeFileSync(path.join(distDir, 'ui-contract.json'), jsonText, 'utf8')
}
console.log(`[ui-contract] OK (uiApi=${uiApi}, parts=${parts.length}, tokens=${tokens.length}, slots=${slots.length})`)