Files

74 lines
5.6 KiB
JavaScript

import enUS from '../src/i18n/messages/en-US.ts'
import zhCN from '../src/i18n/messages/zh-CN.ts'
import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
function flatten(value, prefix = '') {
return Object.entries(value).flatMap(([key, child]) => {
const path = prefix ? `${prefix}.${key}` : key
return child && typeof child === 'object' ? flatten(child, path) : [path]
})
}
const reference = new Set(flatten(zhCN))
const candidate = new Set(flatten(enUS))
const missing = [...reference].filter((key) => !candidate.has(key))
const extra = [...candidate].filter((key) => !reference.has(key))
// Fully migrated pages must not silently reintroduce hardcoded Chinese UI copy.
const completedViews = ['CoursesView.vue', 'OtherExamsView.vue', 'BaseDataView.vue', 'OfficialDocumentsView.vue', 'CampusRegistrationsView.vue', 'ClassroomReservationsView.vue', 'CourseAdjustmentsView.vue', 'UsersView.vue', 'OperationsConsoleView.vue', 'PhysicalFitnessView.vue', 'TeacherAttendanceView.vue', 'TimetableView.vue', 'GradeAnalyticsView.vue', 'CourseSelectionView.vue', 'ExamsView.vue', 'ExperimentsView.vue', 'MakeupExamsView.vue', 'TeachingTasksView.vue']
const hardcoded = completedViews.filter((name) => {
const file = fileURLToPath(new URL(`../src/views/${name}`, import.meta.url))
let source = readFileSync(file, 'utf8')
// These are editable persisted business defaults, not display labels.
if (name === 'BaseDataView.vue') source = source.replace("degreeType: '学士'", '').replace("roomType: '普通教室'", '')
return /\p{Script=Han}/u.test(source)
})
// These pages retain Chinese API values or editable business defaults in script.
// Guard their templates separately, ignoring non-rendered comments.
for (const name of ['TeachingMonitoringView.vue', 'AcademicPlanningView.vue', 'PersonnelView.vue', 'StatisticsView.vue', 'EvaluationView.vue', 'ApprovalCenterView.vue', 'StudentAttendanceView.vue', 'NotificationCenterView.vue', 'GradeAnalyticsView.vue', 'ExperimentGradesView.vue', 'TimetableView.vue', 'TeacherAttendanceView.vue', 'GradesView.vue', 'ExamsView.vue', 'MakeupExamsView.vue', 'CurriculumView.vue', 'PhysicalFitnessView.vue', 'CourseSelectionView.vue', 'TeachingTasksView.vue', 'ComprehensiveAssessmentsView.vue', 'DormitoryHygieneView.vue', 'ExperimentsView.vue', 'SchedulesView.vue']) {
const source = readFileSync(new URL(`../src/views/${name}`, import.meta.url), 'utf8')
const start = source.indexOf('<template>')
const end = source.lastIndexOf('</template>')
if (start < 0 || end < start) throw new Error(`Missing template in ${name}`)
const template = source.slice(start, end).replace(/<!--[\s\S]*?-->/g, '')
if (/\p{Script=Han}/u.test(template)) hardcoded.push(name)
}
const viewsDirectory = new URL('../src/views/', import.meta.url)
const missingBatchReferences = []
const numericPlaceholderReferences = []
for (const name of readdirSync(viewsDirectory).filter((file) => file.endsWith('.vue'))) {
const source = readFileSync(new URL(name, viewsDirectory), 'utf8')
for (const match of source.matchAll(/(?:^|[.\"'])k\d+(?=[.\"']|$)/gm)) {
numericPlaceholderReferences.push(`${name}: ${match[0].trim()}`)
}
for (const match of source.matchAll(/t\(['"]((?:batchBusiness|workflowBatch|timetableTemplate|teacherAttendanceTemplate|gradesTemplate|examsTemplate|curriculumTemplate|fitnessTemplate|selectionTemplate|teachingTaskTemplate|assessmentTemplate|dormTemplate|dormTemplateCounts|experimentsTemplate|experimentsDynamic|schedulesTemplate|schedulesDynamic|physicalFitnessScript|teacherAttendanceScript|timetableScript|dormScript|gradeAnalyticsScript|examsScript|experimentGradesScript|curriculumScript|teachingTasksScript|courseSelectionScript|experimentsScript|gradesScript|schedulesScript|assessmentScript)\.[^'"]+)['"]/g)) {
if (!reference.has(match[1])) missingBatchReferences.push(`${name}: ${match[1]}`)
}
}
const fixedLocaleViews = readdirSync(viewsDirectory).filter((name) => name.endsWith('.vue') &&
/(?:toLocale(?:Date|Time)?String|DateTimeFormat|NumberFormat|Collator)\(['"]zh-CN['"]/.test(readFileSync(new URL(name, viewsDirectory), 'utf8')))
function values(value, prefix = '') {
return Object.entries(value).flatMap(([key, child]) => {
const path = prefix ? `${prefix}.${key}` : key
return child && typeof child === 'object' ? values(child, path) : [[path, child]]
})
}
const english = new Map(values(enUS))
const placeholders = (value) => [...new Set([...String(value).matchAll(/\{(\w+)\}/g)].map((match) => match[1]))].sort().join(',')
const mismatched = values(zhCN).filter(([key, value]) => candidate.has(key) && placeholders(value) !== placeholders(english.get(key))).map(([key]) => key)
if (missing.length || extra.length || hardcoded.length || mismatched.length || fixedLocaleViews.length || missingBatchReferences.length || numericPlaceholderReferences.length) {
if (missing.length) console.error(`en-US missing keys:\n${missing.join('\n')}`)
if (extra.length) console.error(`en-US extra keys:\n${extra.join('\n')}`)
if (hardcoded.length) console.error(`Hardcoded Chinese in completed views:\n${hardcoded.join('\n')}`)
if (mismatched.length) console.error(`Interpolation parameters differ:\n${mismatched.join('\n')}`)
if (fixedLocaleViews.length) console.error(`Fixed Chinese display formats:\n${fixedLocaleViews.join('\n')}`)
if (missingBatchReferences.length) console.error(`Missing batch translations:\n${missingBatchReferences.join('\n')}`)
if (numericPlaceholderReferences.length) console.error(`Numeric placeholder i18n references:\n${numericPlaceholderReferences.join('\n')}`)
process.exitCode = 1
} else {
console.log(`i18n catalogs match (${reference.size} keys).`)
}