| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- import fs from 'node:fs';
- import cp from 'node:child_process';
- import ts from 'typescript';
- const baseline = '317182004f51f1cb88f2022e8dbce8d7e1802b06';
- const printer = ts.createPrinter({ removeComments: true });
- const ast = (p,text) => ts.createSourceFile(p,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
- const print = (n,a) => printer.printNode(ts.EmitHint.Unspecified,n,a).trim();
- function collect(a) {
- const functions={},effects=[],state=[],controls=[];
- function walk(n) {
- 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);
- if (ts.isFunctionDeclaration(n) && n.name && n.name.text==='initData') functions.initData=print(n,a);
- if (ts.isCallExpression(n) && n.expression.getText(a)==='useEffect') effects.push(print(n,a));
- if (ts.isCallExpression(n) && n.expression.getText(a)==='useState') state.push(print(n,a));
- if ((ts.isJsxOpeningElement(n)||ts.isJsxSelfClosingElement(n)) && ['input','select','textarea'].includes(n.tagName.getText(a))) {
- const important=['type','name','required','min','max','minLength','maxLength','pattern','disabled','readOnly','value','checked','onChange'];
- 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(' '));
- }
- ts.forEachChild(n,walk);
- }
- walk(a);return {functions,effects,state,controls};
- }
- const sources={
- 'src/components/CreateOrderForm.tsx': ['initData','ensureUserLoggedIn','checkUserEmail','handleInputChange','performOrderCreation','handleSubmit','handleConfirmSubmit','handleBindSuccess','getSortedKeys'],
- 'src/components/AuthForm.tsx':['handleSubmit','handleCloseMsg','showMessage'],
- 'src/components/BindEmailModal.tsx':['handleSendCode','handleVerifyAndBind','handleCloseMsg','showMessage'],
- 'src/components/ForgotPasswordModal.tsx':['handleSendCode','handleSubmitReset','handleCloseMsg','showMessage'],
- 'src/components/PaymentProcessor.tsx':['fetchProviders','fetchOrderInfo','handlePay','handleUserConfirm','handleBack','formatMoney','showMessage','handleCloseMsg'],
- 'src/components/dashboard/ChangePasswordModal.tsx':['handleSendCode','handleSubmit','showMessage','handleCloseMsg'],
- 'src/components/dashboard/ProfileSettings.tsx':['handleFileChange','uploadImage','handleSubmit','handleCancel','showMessage','handleCloseMsg'],
- 'src/components/dashboard/OrderList.tsx':['fetchOrders','handleSearch','handleKeyDown','formatMoney'],
- 'src/components/dashboard/TicketList.tsx':['fetchTickets','handleSearch','handleKeyDown'],
- 'src/components/dashboard/TicketModal.tsx':['handleSubmit','showMessage','handleCloseMsg'],
- 'src/components/dashboard/UserTicketDetailModal.tsx':['fetchMessages','handleImageUpload','handleRemoveImage','handleSend','scrollToBottom','extractImages','showMessage','handleCloseMsg'],
- 'src/components/dashboard/UserOrderDetailModal.tsx':['fetchPayments','fetchEvents','formatMoney'],
- 'src/components/payment/PaymentConfirmCard.tsx':[],
- 'src/components/pages/DashboardPage.tsx':['handleCreateTicket','handleTicketSuccess','handleViewOrder','handleViewTicket','handleForceBindSuccess','showMessage','handleMessageClose'],
- 'src/components/pages/SettingsPage.tsx':['handleLogout','handleTabChange'],
- 'src/components/pages/SlotsPage.tsx':[],
- };
- 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;
- const changes=[],proof=[];
- for (const [p,names] of Object.entries(sources)) {
- const before=collect(ast(p,cp.execFileSync('git',['show',baseline+':'+oldPath(p)],{encoding:'utf8'}))), after=collect(ast(p,fs.readFileSync(p,'utf8')));
- 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")');
- for (const name of names) {
- if (!before.functions[name] || !after.functions[name]) {changes.push({p,name,missing:true});continue;}
- if(normalize(before.functions[name])!==normalize(after.functions[name])) changes.push({p,name,before:before.functions[name],after:after.functions[name]});
- else proof.push({file:p,check:name,unchanged:true});
- }
- for(const kind of ['state','controls','effects']) {
- if(p==='src/components/pages/SlotsPage.tsx' && kind==='controls') continue; // Labels' data arrays are checked separately by browser.
- if(JSON.stringify(before[kind].map(normalize))!==JSON.stringify(after[kind].map(normalize))) changes.push({p,kind,before:before[kind],after:after[kind]});
- else proof.push({file:p,check:kind,unchanged:true});
- }
- }
- 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)]) {
- const before=cp.execFileSync('git',['show',baseline+':'+p],{encoding:'utf8'}); const after=fs.readFileSync(p,'utf8');
- if(before!==after) changes.push({p,kind:'Protected module changed'}); else proof.push({file:p,check:'byte-identical',unchanged:true});
- }
- for(const p of ['src/lib/api.js','src/lib/auth.ts']) {
- const before=ast(p,cp.execFileSync('git',['show',baseline+':'+p],{encoding:'utf8'}));
- 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');
- const after=ast(p,text);
- 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});
- }
- // Existing terms/refund/privacy/cookie commitments are not copy-optimization targets.
- function readDictionary(text, name) {
- const compiled = ts.transpileModule(text, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;
- const module = { exports: {} }; new Function('module', 'exports', compiled)(module, module.exports);
- return module.exports[name];
- }
- const englishFormEdits = JSON.parse(fs.readFileSync('scripts/fixtures/english-form-copy.json', 'utf8')).edits;
- const englishFormDictionary = new Map(englishFormEdits.filter(edit => edit.source === 'base').map(edit => [edit.key, edit]));
- const englishFormCopyChanges = [];
- for (const locale of ['en', 'zh']) {
- const p = `src/lib/i18n/locales/${locale}.ts`;
- const before = readDictionary(cp.execFileSync('git', ['show', baseline + ':' + p], { encoding: 'utf8' }), locale);
- const after = readDictionary(fs.readFileSync(p, 'utf8'), locale);
- const originalCopyDifferences = [];
- function compareOriginalCopy(source, current, prefix = '') {
- for (const [key, value] of Object.entries(source)) {
- const name = prefix ? `${prefix}.${key}` : key;
- if (typeof value === 'string') {
- if (current?.[key] !== value) {
- const edit = locale === 'en' ? englishFormDictionary.get(name) : undefined;
- if (edit?.before === value && edit.after === current?.[key]) englishFormCopyChanges.push(name);
- else originalCopyDifferences.push(name);
- }
- } else if (value && typeof value === 'object') {
- compareOriginalCopy(value, current?.[key], name);
- }
- }
- }
- compareOriginalCopy(before, after);
- if (originalCopyDifferences.length) changes.push({ p, kind: 'Original wording outside the authorized English form-copy edits changed', keys: originalCopyDifferences });
- 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 });
- for (const section of ['refund', 'terms', 'privacy_content', 'cookie_content']) {
- if (JSON.stringify(before[section]) !== JSON.stringify(after[section])) changes.push({ p, kind: 'Policy commitments changed', section });
- else proof.push({ file: p, check: section + ' unchanged', unchanged: true });
- }
- }
- 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'];
- fs.writeFileSync(process.env.LOCALIZATION_SCOPE_RECEIPT || 'output/playwright/multilingual-resume/business-scope-check.json',JSON.stringify({baseline,allowedPresentationChanges,englishFormCopyChanges,proof,changes},null,2));
- console.log('Unchanged protected functions/controls/state/effects:',proof.length,'differences requiring review:',changes.length);
- if(changes.length) process.exitCode=1;
- console.log(changes.map(c=>[c.p,c.name||c.kind,c.missing||''].join(': ')).join('\n'));
|