You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/UserCopyManifestContractTes...

189 lines
7.3 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\UserCopy\UserCopyCoverageScanner;
use App\Services\UserCopy\UserCopyCatalogCompiler;
use App\Services\UserCopy\UserCopyManifest;
use App\Services\UserCopy\UserCopySourceCatalog;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$rejects = static function (array $manifest, string $needle) use ($assert): void {
try {
UserCopyManifest::validate($manifest);
} catch (InvalidArgumentException $exception) {
$assert(str_contains($exception->getMessage(), $needle),
'Manifest rejection did not identify the expected contract: '
. $exception->getMessage());
return;
}
throw new RuntimeException('Invalid Manifest was accepted: ' . $needle);
};
$manifest = UserCopyManifest::load();
$loadedEntries = array_column($manifest['entries'], null, 'key');
$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.');
$assert(($loadedEntries['common.toast.success.title']['editor_surface'] ?? null)
=== 'feedback'
&& ($loadedEntries['common.tasks.status.running']['editor_surface'] ?? null)
=== 'task'
&& ($loadedEntries['common.tasks.status.running']['editor_group'] ?? null)
=== 'user.tasks',
'User-copy editor surfaces or task authoring groups are incomplete.');
foreach ($loadedEntries as $copyKey => $entry) {
$assert(is_string($entry['editor_surface'] ?? null)
&& is_string($entry['editor_group'] ?? null),
'User-copy entry lacks editor metadata: ' . $copyKey);
if (str_starts_with($copyKey, 'common.tasks.')) {
$assert($entry['editor_surface'] === 'task',
'Task-center copy is not isolated from page editing: ' . $copyKey);
}
if (str_starts_with((string) $entry['kind'], 'toast_')) {
$assert($entry['editor_surface'] === 'feedback',
'Toast copy is not assigned to feedback editing: ' . $copyKey);
}
if (in_array($entry['kind'], ['aria_label', 'tooltip', 'placeholder'], true)) {
$assert(in_array(
$entry['editor_surface'],
['accessibility', 'task'],
true
),
'Attribute copy is not assigned to accessibility editing: ' . $copyKey);
}
if ($entry['kind'] === 'confirmation') {
$assert($entry['editor_surface'] === 'dialog',
'Confirmation copy is not assigned to dialog editing: ' . $copyKey);
}
}
$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);
$assert(isset($runtimeSource->entries()['common.toast.success.title'])
&& in_array(
'backups',
$runtimeSource->pageScopes()['cloud.backups'],
true
),
'Validated Manifest is incompatible with the runtime source catalog.');
$base = [
'version' => 1,
'pages' => [
'test.page' => ['label' => '测试页面', 'scopes' => ['test']],
],
'entries' => [
[
'key' => 'test.greeting',
'scope' => 'test', 'page' => 'test.page', 'kind' => 'label',
'source' => '您好,{name}', 'format' => 'icu',
'parameters' => ['name' => 'string'],
'criticality' => 'normal', 'allow_hide' => true,
'toast_tone' => null,
'editor_surface' => 'page', 'editor_group' => 'test.page',
],
],
];
$validatedBase = UserCopyManifest::validate($base);
$validatedBaseEntries = array_column(
$validatedBase['entries'], null, 'key'
);
$assert($validatedBaseEntries['test.greeting']['source'] === '您好,{name}',
'Valid ICU source entry was not retained.');
$metadataOnly = $validatedBase;
$metadataOnly['entries'][0]['editor_surface'] = 'feedback';
$metadataOnly['entries'][0]['editor_group'] = 'common.shared';
$metadataOnly = UserCopyManifest::validate($metadataOnly);
$assert(
hash_equals(
(new UserCopySourceCatalog($validatedBase))->sourceHash(),
(new UserCopySourceCatalog($metadataOnly))->sourceHash()
),
'Editor-only metadata changed the runtime source catalog identity.'
);
$baseCompiled = (new UserCopyCatalogCompiler(
new UserCopySourceCatalog($validatedBase)
))->compile('en');
$metadataCompiled = (new UserCopyCatalogCompiler(
new UserCopySourceCatalog($metadataOnly)
))->compile('en');
$assert($baseCompiled->generation === $metadataCompiled->generation
&& $baseCompiled->scopes === $metadataCompiled->scopes,
'Editor-only metadata changed the compiled runtime generation.');
$duplicateKey = $base;
$duplicateKey['entries'][] = $duplicateKey['entries'][0];
$rejects($duplicateKey, '词条键重复');
$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',
];
$rejects($invalidParameter, '参数与中文基线不一致');
$invalidParameterName = $base;
$invalidParameterName['entries'][0]['parameters'] = [
'user-name' => 'string',
];
$rejects($invalidParameterName, '参数合同无效');
$translationInSource = $base;
$translationInSource['entries'][0]['en'] = '不应存在的目标译文';
$rejects($translationInSource, '未声明字段');
$unsafeDirection = $base;
$unsafeDirection['entries'][0]['source'] = "您好\u{202E}";
$rejects($unsafeDirection, '非法内容');
$hiddenCritical = $base;
$hiddenCritical['entries'][0]['criticality'] = 'critical';
$rejects($hiddenCritical, '高风险词条不能隐藏');
$toastWithoutTone = $base;
$toastWithoutTone['entries'][0]['kind'] = 'toast_body';
$rejects($toastWithoutTone, 'Toast 词条必须声明有效 tone');
$invalidEditorSurface = $base;
$invalidEditorSurface['entries'][0]['editor_surface'] = 'inline';
$rejects($invalidEditorSurface, '编辑表面无效');
$invalidEditorGroup = $base;
$invalidEditorGroup['entries'][0]['editor_group'] = 'Invalid Group';
$rejects($invalidEditorGroup, '编辑分组无效');
$source = <<<'SOURCE'
toast('任务已接收。', 'success');
window.confirm('确定删除?');
date.toLocaleString('zh-CN');
// user-copy: allow test-fixture scanner marker contract
SOURCE;
$violations = UserCopyCoverageScanner::scanContents('fixture.js', $source);
$rules = array_count_values(array_column($violations, 'rule'));
$assert(($rules['direct_toast_text'] ?? 0) === 1
&& ($rules['direct_confirm_text'] ?? 0) === 1
&& ($rules['hardcoded_zh_locale'] ?? 0) === 1
&& ($rules['visible_chinese_literal'] ?? 0) === 2,
'Coverage scanner did not report direct user-visible copy consistently.');
echo "User-copy Manifest and coverage-scanner contract checks passed.\n";