test(i18n): enforce stable copy contracts

go
codex 2 weeks ago
parent ff6cff5043
commit 712d2a72f4

@ -5,19 +5,35 @@ namespace App\Services\UserCopy;
/** Reports source patterns that must disappear as pages join the copy catalog. */
final class UserCopyCoverageScanner
{
private const ALLOW_MARKER =
'/user-copy:\s*allow\s+(?:technical-constant|technical-regex|test-fixture|admin-compatibility)\s+\S+/i';
private const RULES = [
'direct_toast_text' => '/\btoast\s*\(\s*[\'\"]/',
'direct_confirm_text' => '/\b(?:window\.)?confirm\s*\(\s*[\'\"]/',
'hardcoded_zh_locale' =>
'/\.toLocale(?:String|DateString|TimeString)\s*\(\s*[\'\"]zh-CN[\'\"]/',
'/(?:\.toLocale(?:String|DateString|TimeString)|\b(?:new\s+)?Intl\.(?:DateTimeFormat|NumberFormat|RelativeTimeFormat|PluralRules|ListFormat|Collator))\s*\(\s*[\'\"]zh-CN[\'\"]/',
'legacy_language_branch' => '/\$language\s*={2,3}\s*[\'\"]true[\'\"]/',
'visible_chinese_literal' => '/\p{Han}/u',
'raw_backend_copy' =>
'/(?<![.\w\'\"`])(?:payload|data|result|response|task)\s*(?:(?:\?\.|\.)\s*(?:message|detail|msg|errmsg|error)\b|(?:\?\.)?\[\s*[\'\"](?:message|detail|msg|errmsg|error)[\'\"]\s*\])/',
'raw_error_feedback' =>
'/\b(?:toast|showError|inform|text)\s*\([^;\n]{0,240}\berror\s*(?:\?\.|\.)\s*message\b/',
'generated_copy_key' => '/\.dynamic\.h[0-9a-f]{6,}\b/i',
'visible_chinese_literal' =>
'/[\x{3400}-\x{4DBF}\x{4E00}-\x{9FFF}\x{F900}-\x{FAFF}]/u',
];
private const TEMPLATE_RULES = [
'visible_english_text' =>
'/>\s*[A-Za-z][A-Za-z0-9 _.,:;\/+&()#-]{1,160}\s*</',
'visible_english_attribute' =>
'/\b(?:aria-label|placeholder|title)\s*=\s*[\'\"][A-Za-z][^\'\"{}$]*[\'\"]/',
];
/**
* Lines can be temporarily excluded with a documented marker while a
* migration is in progress. The final strict gate will reject markers
* without a non-empty reason.
* A non-rendered technical constant, technical regular expression or
* test fixture can be excluded with a same-line, categorized marker and
* a non-empty reason. All other markers are violations.
*/
public static function scanContents(string $path, string $contents): array
{
@ -28,10 +44,23 @@ final class UserCopyCoverageScanner
}
foreach ($lines as $offset => $line) {
if (preg_match('/user-copy:\s*allow\s+\S+/i', $line) === 1) {
if (stripos($line, 'user-copy: allow') !== false) {
if (preg_match(self::ALLOW_MARKER, $line) === 1) {
continue;
}
$violations[] = [
'path' => $path,
'line' => $offset + 1,
'rule' => 'invalid_allow_marker',
'snippet' => trim($line),
];
continue;
}
foreach (self::RULES as $rule => $pattern) {
$rules = self::RULES;
if (str_ends_with(strtolower($path), '.tpl')) {
$rules += self::TEMPLATE_RULES;
}
foreach ($rules as $rule => $pattern) {
if (preg_match($pattern, $line) !== 1) {
continue;
}

@ -14,6 +14,7 @@ use InvalidArgumentException;
final class UserCopyManifest
{
private const KEY_PATTERN = '/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+$/D';
private const GENERATED_KEY_PATTERN = '/(?:^|\.)dynamic\.h[0-9a-f]{6,}(?:\.|$)/D';
private const NAME_PATTERN = '/^[a-z][a-z0-9_]*$/D';
private const PAGE_PATTERN = '/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/D';
@ -124,7 +125,8 @@ final class UserCopyManifest
$copyKey = $entry['key'] ?? null;
if (!is_string($copyKey)
|| preg_match(self::KEY_PATTERN, $copyKey) !== 1) {
|| preg_match(self::KEY_PATTERN, $copyKey) !== 1
|| preg_match(self::GENERATED_KEY_PATTERN, $copyKey) === 1) {
throw new InvalidArgumentException(
'文案词条键必须是静态语义键:' . (string) $copyKey
);

@ -0,0 +1,75 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\UserCopy\UserCopyCoverageScanner;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$rules = static function (array $violations): array {
return array_values(array_unique(array_column($violations, 'rule')));
};
$javascript = <<<'JS'
toast('Saved');
window.confirm("Continue?");
date.toLocaleString('zh-CN');
new Intl.NumberFormat('zh-CN');
node.textContent = payload?.message;
node.textContent = response['detail'];
toast(error?.message, 'error');
const key = `sample.dynamic.h12abcdef`;
const visible = '未登记文案';
const classifier = /访客代理/u; // user-copy: allow technical-regex non-rendered provider classifier
const protocol = 'HTTP'; // user-copy: allow technical-constant non-rendered protocol token
const invalid = '错误放行'; // user-copy: allow arbitrary-reason
const missingCategory = '分类缺失'; // user-copy: allow
const missingReason = '理由缺失'; // user-copy: allow technical-regex
JS;
$javascriptViolations = UserCopyCoverageScanner::scanContents(
'fixture.js',
$javascript
);
$javascriptRules = $rules($javascriptViolations);
foreach ([
'direct_toast_text',
'direct_confirm_text',
'hardcoded_zh_locale',
'raw_backend_copy',
'raw_error_feedback',
'generated_copy_key',
'visible_chinese_literal',
'invalid_allow_marker',
] as $rule) {
$assert(in_array($rule, $javascriptRules, true),
'Scanner did not detect rule: ' . $rule);
}
$invalidMarkers = array_values(array_filter(
$javascriptViolations,
static fn (array $violation): bool =>
($violation['rule'] ?? null) === 'invalid_allow_marker'
));
$assert(count($invalidMarkers) === 3,
'Unclassified, unsupported and empty-reason markers must all fail.');
$templateRules = $rules(UserCopyCoverageScanner::scanContents(
'fixture.tpl',
'<button title="Continue">Support</button>'
));
$assert(in_array('visible_english_text', $templateRules, true),
'Scanner did not detect visible English template text.');
$assert(in_array('visible_english_attribute', $templateRules, true),
'Scanner did not detect a visible English template attribute.');
$allowed = UserCopyCoverageScanner::scanContents(
'fixture.js',
"const sample = '中文'; // user-copy: allow test-fixture scanner rejection sample\n"
. "const shared = '后台兼容'; // user-copy: allow admin-compatibility shared admin fallback"
);
$assert($allowed === [], 'A categorized marker with a reason was not honored.');
echo "User-copy coverage scanner strict rules passed.\n";

@ -29,6 +29,13 @@ $assert(($manifest['version'] ?? null) === 1
&& isset($manifest['pages']['cloud.instances'])
&& isset($loadedEntries['common.toast.success.title']),
'Source-language user-copy Manifest did not load its page and Toast contract.');
$hashedDetailKeys = array_filter(
array_keys($loadedEntries),
static fn (string $key): bool => str_contains($key, '.dynamic.h')
);
$assert($hashedDetailKeys === [],
'Instance-detail user copy must use stable semantic keys, not generated hashes: '
. implode(', ', $hashedDetailKeys));
$assert(strlen(UserCopyManifest::digest($manifest)) === 64,
'User-copy Manifest digest is not a SHA-256 identity.');
$runtimeSource = new UserCopySourceCatalog($manifest);
@ -70,6 +77,10 @@ $invalidKey = $base;
$invalidKey['entries'][0]['key'] = 'test.{dynamic}';
$rejects($invalidKey, '静态语义键');
$generatedKey = $base;
$generatedKey['entries'][0]['key'] = 'test.dynamic.h0123abc';
$rejects($generatedKey, '静态语义键');
$invalidParameter = $base;
$invalidParameter['entries'][0]['parameters'] = [
'other' => 'string',
@ -83,7 +94,7 @@ $invalidParameterName['entries'][0]['parameters'] = [
$rejects($invalidParameterName, '参数合同无效');
$translationInSource = $base;
$translationInSource['entries'][0]['en'] = 'Hello';
$translationInSource['entries'][0]['en'] = '不应存在的目标译文';
$rejects($translationInSource, '未声明字段');
$unsafeDirection = $base;
@ -102,7 +113,7 @@ $source = <<<'SOURCE'
toast('任务已接收。', 'success');
window.confirm('确定删除?');
date.toLocaleString('zh-CN');
// user-copy: allow fixture 中文测试数据
// user-copy: allow test-fixture scanner marker contract
SOURCE;
$violations = UserCopyCoverageScanner::scanContents('fixture.js', $source);
$rules = array_count_values(array_column($violations, 'rule'));

Loading…
Cancel
Save