check-localization-scope.mjs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import fs from 'node:fs';
  2. import cp from 'node:child_process';
  3. import ts from 'typescript';
  4. const baseline = '317182004f51f1cb88f2022e8dbce8d7e1802b06';
  5. const printer = ts.createPrinter({ removeComments: true });
  6. const ast = (p,text) => ts.createSourceFile(p,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
  7. const print = (n,a) => printer.printNode(ts.EmitHint.Unspecified,n,a).trim();
  8. function collect(a) {
  9. const functions={},effects=[],state=[],controls=[];
  10. function walk(n) {
  11. if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.initializer && (ts.isArrowFunction(n.initializer)||ts.isFunctionExpression(n.initializer))) functions[n.name.text]=print(n.initializer,a);
  12. if (ts.isFunctionDeclaration(n) && n.name && n.name.text==='initData') functions.initData=print(n,a);
  13. if (ts.isCallExpression(n) && n.expression.getText(a)==='useEffect') effects.push(print(n,a));
  14. if (ts.isCallExpression(n) && n.expression.getText(a)==='useState') state.push(print(n,a));
  15. if ((ts.isJsxOpeningElement(n)||ts.isJsxSelfClosingElement(n)) && ['input','select','textarea'].includes(n.tagName.getText(a))) {
  16. const important=['type','name','required','min','max','minLength','maxLength','pattern','disabled','readOnly','value','checked','onChange'];
  17. controls.push(n.tagName.getText(a)+' '+n.attributes.properties.filter(p=>ts.isJsxAttribute(p)&&important.includes(p.name.getText(a))).map(p=>print(p,a)).sort().join(' '));
  18. }
  19. ts.forEachChild(n,walk);
  20. }
  21. walk(a);return {functions,effects,state,controls};
  22. }
  23. const sources={
  24. 'src/components/CreateOrderForm.tsx': ['initData','ensureUserLoggedIn','checkUserEmail','handleInputChange','performOrderCreation','handleSubmit','handleConfirmSubmit','handleBindSuccess','getSortedKeys'],
  25. 'src/components/AuthForm.tsx':['handleSubmit','handleCloseMsg','showMessage'],
  26. 'src/components/BindEmailModal.tsx':['handleSendCode','handleVerifyAndBind','handleCloseMsg','showMessage'],
  27. 'src/components/ForgotPasswordModal.tsx':['handleSendCode','handleSubmitReset','handleCloseMsg','showMessage'],
  28. 'src/components/PaymentProcessor.tsx':['fetchProviders','fetchOrderInfo','handlePay','handleUserConfirm','handleBack','formatMoney','showMessage','handleCloseMsg'],
  29. 'src/components/dashboard/ChangePasswordModal.tsx':['handleSendCode','handleSubmit','showMessage','handleCloseMsg'],
  30. 'src/components/dashboard/ProfileSettings.tsx':['handleFileChange','uploadImage','handleSubmit','handleCancel','showMessage','handleCloseMsg'],
  31. 'src/components/dashboard/OrderList.tsx':['fetchOrders','handleSearch','handleKeyDown','formatMoney'],
  32. 'src/components/dashboard/TicketList.tsx':['fetchTickets','handleSearch','handleKeyDown'],
  33. 'src/components/dashboard/TicketModal.tsx':['handleSubmit','showMessage','handleCloseMsg'],
  34. 'src/components/dashboard/UserTicketDetailModal.tsx':['fetchMessages','handleImageUpload','handleRemoveImage','handleSend','scrollToBottom','extractImages','showMessage','handleCloseMsg'],
  35. 'src/components/dashboard/UserOrderDetailModal.tsx':['fetchPayments','fetchEvents','formatMoney'],
  36. 'src/components/payment/PaymentConfirmCard.tsx':[],
  37. 'src/components/pages/DashboardPage.tsx':['handleCreateTicket','handleTicketSuccess','handleViewOrder','handleViewTicket','handleForceBindSuccess','showMessage','handleMessageClose'],
  38. 'src/components/pages/SettingsPage.tsx':['handleLogout','handleTabChange'],
  39. 'src/components/pages/SlotsPage.tsx':[],
  40. };
  41. const oldPath = p => p.startsWith('src/components/pages/') ? {'DashboardPage.tsx':'src/app/(app)/dashboard/page.tsx','SettingsPage.tsx':'src/app/(app)/dashboard/settings/page.tsx','SlotsPage.tsx':'src/app/(app)/slots/page.tsx'}[p.split('/').pop()] : p;
  42. const changes=[],proof=[];
  43. for (const [p,names] of Object.entries(sources)) {
  44. const before=collect(ast(p,cp.execFileSync('git',['show',baseline+':'+oldPath(p)],{encoding:'utf8'}))), after=collect(ast(p,fs.readFileSync(p,'utf8')));
  45. const normalize=s=>s.replace(/setProduct\(displayProduct\(prodData, t\)\)/g,'setProduct(prodData)').replace("currentLocalePath('/login')", "'/login'").replace("error.message || t('settings.change_failed')", "error.message || '重置失败'").replace("t('payment_confirm.unknown_error') || t('payment_confirm.unknown_error')", "t('payment_confirm.unknown_error') || '未知异常'").replace("showMessage(t('会话刷新失败'))", 'showMessage("Session refresh failed")');
  46. for (const name of names) {
  47. if (!before.functions[name] || !after.functions[name]) {changes.push({p,name,missing:true});continue;}
  48. if(normalize(before.functions[name])!==normalize(after.functions[name])) changes.push({p,name,before:before.functions[name],after:after.functions[name]});
  49. else proof.push({file:p,check:name,unchanged:true});
  50. }
  51. for(const kind of ['state','controls','effects']) {
  52. if(p==='src/components/pages/SlotsPage.tsx' && kind==='controls') continue; // Labels' data arrays are checked separately by browser.
  53. if(JSON.stringify(before[kind].map(normalize))!==JSON.stringify(after[kind].map(normalize))) changes.push({p,kind,before:before[kind],after:after[kind]});
  54. else proof.push({file:p,check:kind,unchanged:true});
  55. }
  56. }
  57. for (const p of [...cp.execFileSync('git',['ls-files','src/lib/services','src/types','src/components/admin','src/app/(app)/admin'],{encoding:'utf8'}).trim().split('\n').filter(Boolean)]) {
  58. const before=cp.execFileSync('git',['show',baseline+':'+p],{encoding:'utf8'}); const after=fs.readFileSync(p,'utf8');
  59. if(before!==after) changes.push({p,kind:'Protected module changed'}); else proof.push({file:p,check:'byte-identical',unchanged:true});
  60. }
  61. for(const p of ['src/lib/api.js','src/lib/auth.ts']) {
  62. const before=ast(p,cp.execFileSync('git',['show',baseline+':'+p],{encoding:'utf8'}));
  63. let text=fs.readFileSync(p,'utf8').replace(/^import .*from '@\/lib\/i18n\/routes';\n/m,'').replace(/currentLocalePath\('\/login'\)/g,"'/login'").replace('splitLocalePath(window.location.pathname).path.startsWith', 'window.location.pathname.startsWith');
  64. const after=ast(p,text);
  65. if(printer.printFile(before)!==printer.printFile(after)) changes.push({p,kind:'Authentication or API rule changed'});else proof.push({file:p,check:'Only login URL retains locale; all other AST unchanged',unchanged:true});
  66. }
  67. // Existing terms/refund/privacy/cookie commitments are not copy-optimization targets.
  68. function readDictionary(text, name) {
  69. const compiled = ts.transpileModule(text, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;
  70. const module = { exports: {} }; new Function('module', 'exports', compiled)(module, module.exports);
  71. return module.exports[name];
  72. }
  73. const englishFormEdits = JSON.parse(fs.readFileSync('scripts/fixtures/english-form-copy.json', 'utf8')).edits;
  74. const englishFormDictionary = new Map(englishFormEdits.filter(edit => edit.source === 'base').map(edit => [edit.key, edit]));
  75. const englishFormCopyChanges = [];
  76. for (const locale of ['en', 'zh']) {
  77. const p = `src/lib/i18n/locales/${locale}.ts`;
  78. const before = readDictionary(cp.execFileSync('git', ['show', baseline + ':' + p], { encoding: 'utf8' }), locale);
  79. const after = readDictionary(fs.readFileSync(p, 'utf8'), locale);
  80. const originalCopyDifferences = [];
  81. function compareOriginalCopy(source, current, prefix = '') {
  82. for (const [key, value] of Object.entries(source)) {
  83. const name = prefix ? `${prefix}.${key}` : key;
  84. if (typeof value === 'string') {
  85. if (current?.[key] !== value) {
  86. const edit = locale === 'en' ? englishFormDictionary.get(name) : undefined;
  87. if (edit?.before === value && edit.after === current?.[key]) englishFormCopyChanges.push(name);
  88. else originalCopyDifferences.push(name);
  89. }
  90. } else if (value && typeof value === 'object') {
  91. compareOriginalCopy(value, current?.[key], name);
  92. }
  93. }
  94. }
  95. compareOriginalCopy(before, after);
  96. if (originalCopyDifferences.length) changes.push({ p, kind: 'Original wording outside the authorized English form-copy edits changed', keys: originalCopyDifferences });
  97. else proof.push({ file: p, check: locale === 'en' ? 'Original wording preserved except exact English form edits listed in scripts/fixtures/english-form-copy.json' : 'All original Chinese dictionary wording unchanged', unchanged: true });
  98. for (const section of ['refund', 'terms', 'privacy_content', 'cookie_content']) {
  99. if (JSON.stringify(before[section]) !== JSON.stringify(after[section])) changes.push({ p, kind: 'Policy commitments changed', section });
  100. else proof.push({ file: p, check: section + ' unchanged', unchanged: true });
  101. }
  102. }
  103. const allowedPresentationChanges=['Product display clone only; raw API response unchanged','Login return URL keeps locale; authentication conditions unchanged','Translated fallback for password error','Translated fallback for payment error','Translated session refresh error'];
  104. fs.writeFileSync(process.env.LOCALIZATION_SCOPE_RECEIPT || 'output/playwright/multilingual-resume/business-scope-check.json',JSON.stringify({baseline,allowedPresentationChanges,englishFormCopyChanges,proof,changes},null,2));
  105. console.log('Unchanged protected functions/controls/state/effects:',proof.length,'differences requiring review:',changes.length);
  106. if(changes.length) process.exitCode=1;
  107. console.log(changes.map(c=>[c.p,c.name||c.kind,c.missing||''].join(': ')).join('\n'));