diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 606ea4320..ab5225a3b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -66,4 +66,8 @@ jobs: working-directory: main/manager-web run: | npm ci --no-audit --no-fund + node scripts/integrity-check.js + npm run check:i18n + npm run test:snapshot + npm run test:contract npm run test:unit diff --git a/.github/workflows/upstream-sync-check.yml b/.github/workflows/upstream-sync-check.yml new file mode 100644 index 000000000..ffa112fe1 --- /dev/null +++ b/.github/workflows/upstream-sync-check.yml @@ -0,0 +1,51 @@ +name: Upstream Sync Check + +# Nightly dry-run: merge upstream/main into the downstream branch in a +# throwaway workspace and run the web verification gates against the merged +# result. This gives an early, loud signal ("the next sync will break") the +# night before a human performs the real sync, instead of after deploy. +# It never pushes anything. + +on: + schedule: + - cron: '30 4 * * *' # 04:30 UTC daily + workflow_dispatch: + +jobs: + dry-merge: + name: Merge upstream/main and run web gates + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Configure git identity + run: | + git config user.email "ci@localhost" + git config user.name "upstream-sync-check" + - name: Merge upstream/main (dry run) + run: | + git remote add upstream https://github.com/xinnan-tech/xiaozhi-esp32-server.git || true + git fetch upstream main + git checkout -B sync-dry-run + if ! git merge --no-commit --no-ff upstream/main; then + echo "::error::upstream/main no longer merges cleanly into this branch; resolve conflicts before syncing" + git diff --name-only --diff-filter=U || true + exit 1 + fi + echo "MERGED_CLEAN=1" >> "$GITHUB_ENV" + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + cache-dependency-path: main/manager-web/package-lock.json + - name: Web gates on merged tree + working-directory: main/manager-web + run: | + npm ci --no-audit --no-fund + node scripts/integrity-check.js + npm run --silent check:i18n + npm run --silent test:snapshot + npm run --silent test:contract + - name: Westernization audit on merged tree + run: bash scripts/westernization_audit.sh diff --git a/.gitignore b/.gitignore index 1c0c024ba..4ae574a1c 100644 --- a/.gitignore +++ b/.gitignore @@ -187,3 +187,4 @@ uploadfile !main/manager-mobile/**/*.json original-server +scripts/.translate_cache.json diff --git a/main/manager-web/package-lock.json b/main/manager-web/package-lock.json index cc0cd2005..f57312fef 100644 --- a/main/manager-web/package-lock.json +++ b/main/manager-web/package-lock.json @@ -34,7 +34,9 @@ "@vue/cli-plugin-vuex": "~5.0.0", "@vue/cli-service": "~5.0.0", "@vue/test-utils": "^1.3.6", + "acorn": "^8.18.0", "compression-webpack-plugin": "^11.1.0", + "eslint-scope": "^5.1.1", "jsdom": "^24.1.0", "sass": "^1.32.7", "sass-loader": "^12.0.0", @@ -4164,7 +4166,6 @@ "resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.18.0.tgz", "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", "dev": true, - "license": "MIT", "bin": { "acorn": "bin/acorn" }, diff --git a/main/manager-web/package.json b/main/manager-web/package.json index f5a837221..c157a6dcd 100644 --- a/main/manager-web/package.json +++ b/main/manager-web/package.json @@ -5,6 +5,7 @@ "scripts": { "serve": "vue-cli-service serve", "check:i18n": "node scripts/check-i18n.js", + "check:integrity": "node scripts/integrity-check.js", "test:snapshot": "node --test src/components/agentSnapshotDisplayUtils.test.mjs src/apis/module/agentSnapshotApi.test.mjs", "build": "vue-cli-service build", "test:contract": "node --test tests/*Contract.test.mjs", @@ -39,7 +40,9 @@ "@vue/cli-plugin-vuex": "~5.0.0", "@vue/cli-service": "~5.0.0", "@vue/test-utils": "^1.3.6", + "acorn": "^8.18.0", "compression-webpack-plugin": "^11.1.0", + "eslint-scope": "^5.1.1", "jsdom": "^24.1.0", "sass": "^1.32.7", "sass-loader": "^12.0.0", diff --git a/main/manager-web/scripts/check-i18n.js b/main/manager-web/scripts/check-i18n.js index 14c828090..11379bc67 100644 --- a/main/manager-web/scripts/check-i18n.js +++ b/main/manager-web/scripts/check-i18n.js @@ -1,50 +1,80 @@ +/* + * i18n consistency checker (westernized fork). + * + * Differences from upstream's version: + * - The fork removed zh_CN/zh_TW locales; the base locale is `en`. + * - Locale set is discovered from src/i18n/*.js instead of hardcoded. + * - Also verifies that every static translation key referenced anywhere in + * src/ ($t('a.b'), i18n.t('a.b'), this.$t('a.b'), t('a.b')) exists in the + * base locale. Upstream rebases repeatedly added views calling $t() for + * keys that were never added downstream, which renders raw keys/blank + * labels at runtime with no build error. + */ const fs = require('fs'); const path = require('path'); const rootDir = path.resolve(__dirname, '..'); -const locales = [ - { name: 'zh_CN', file: 'src/i18n/zh_CN.js' }, - { name: 'zh_TW', file: 'src/i18n/zh_TW.js' }, - { name: 'en', file: 'src/i18n/en.js' }, - { name: 'de', file: 'src/i18n/de.js' }, - { name: 'vi', file: 'src/i18n/vi.js' }, - { name: 'pt_BR', file: 'src/i18n/pt_BR.js' }, -]; +const i18nDir = path.join(rootDir, 'src/i18n'); +const BASE = 'en'; + +function discoverLocales() { + return fs + .readdirSync(i18nDir) + .filter((f) => f.endsWith('.js') && f !== 'index.js') + .map((f) => ({ name: f.replace(/\.js$/, ''), file: `src/i18n/${f}` })) + .sort((a, b) => (a.name === BASE ? -1 : b.name === BASE ? 1 : a.name.localeCompare(b.name))); +} + +function evalLocale(file) { + const src = fs.readFileSync(path.join(rootDir, file), 'utf8'); + const objText = src.replace(/^\s*import[^;]+;\s*$/gm, '').replace(/export\s+default\s*/, ''); + // Locale files are plain object literals; evaluate without importing (ESM). + // eslint-disable-next-line no-new-func + return new Function(`"use strict"; return (${objText});`)(); +} function readLocale(locale) { - const filePath = path.join(rootDir, locale.file); - const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/); - const keys = []; + const flat = evalLocale(locale.file); + const keys = Object.keys(flat); + // duplicate detection on raw text (object literal would silently dedupe) + const lines = fs.readFileSync(path.join(rootDir, locale.file), 'utf8').split(/\r?\n/); const seen = new Map(); const duplicates = []; - lines.forEach((line, index) => { const match = line.match(/^\s*['"]([^'"]+)['"]\s*:/); - if (!match) { - return; - } - - const key = match[1]; - keys.push(key); - if (!seen.has(key)) { - seen.set(key, []); - } - seen.get(key).push(index + 1); + if (!match) return; + if (!seen.has(match[1])) seen.set(match[1], []); + seen.get(match[1]).push(index + 1); }); - seen.forEach((lineNumbers, key) => { - if (lineNumbers.length > 1) { - duplicates.push({ key, lineNumbers }); - } + if (lineNumbers.length > 1) duplicates.push({ key, lineNumbers }); }); + return { ...locale, keys, keySet: new Set(keys), duplicates, flat }; +} - return { - ...locale, - filePath, - keys, - keySet: new Set(keys), - duplicates, - }; +function walk(dir, out = []) { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { + if (e.name !== 'node_modules') walk(p, out); + } else if (/\.(vue|js)$/.test(e.name) && !p.startsWith(i18nDir)) { + out.push(p); + } + } + return out; +} + +function collectReferencedKeys() { + const keys = new Map(); // key -> first file seen + const re = /(?:\$t|\bt)\(\s*['"]([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+)['"]\s*[,)]/g; + for (const f of walk(path.join(rootDir, 'src'))) { + const src = fs.readFileSync(f, 'utf8'); + let m; + while ((m = re.exec(src))) { + if (!keys.has(m[1])) keys.set(m[1], path.relative(rootDir, f)); + } + } + return keys; } function diffKeys(left, right) { @@ -52,19 +82,21 @@ function diffKeys(left, right) { } function formatKeyList(keys) { - return keys.length ? keys.map((key) => ` - ${key}`).join('\n') : ''; + return keys.length ? keys.map((k) => ` - ${k}`).join('\n') : ''; } function main() { - const results = locales.map(readLocale); - const base = results.find((locale) => locale.name === 'zh_CN'); + const results = discoverLocales().map(readLocale); + const base = results.find((l) => l.name === BASE); + if (!base) { + console.error(`base locale "${BASE}" not found under src/i18n`); + process.exit(1); + } const errors = []; results.forEach((locale) => { locale.duplicates.forEach(({ key, lineNumbers }) => { - errors.push( - `${locale.file} has duplicate key "${key}" on lines ${lineNumbers.join(', ')}` - ); + errors.push(`${locale.file} has duplicate key "${key}" on lines ${lineNumbers.join(', ')}`); }); }); @@ -73,24 +105,33 @@ function main() { .forEach((locale) => { const missing = diffKeys(base.keySet, locale.keySet); const extra = diffKeys(locale.keySet, base.keySet); - if (missing.length) { errors.push(`${locale.file} is missing keys from ${base.file}:\n${formatKeyList(missing)}`); } - if (extra.length) { errors.push(`${locale.file} has keys that do not exist in ${base.file}:\n${formatKeyList(extra)}`); } }); + const referenced = collectReferencedKeys(); + const unresolved = [...referenced].filter(([k]) => !base.keySet.has(k)); + if (unresolved.length) { + errors.push( + `referenced translation keys missing from ${base.file}:\n` + + unresolved.map(([k, f]) => ` - ${k} (used in ${f})`).join('\n') + ); + } + if (errors.length) { console.error(`i18n check failed with ${errors.length} issue(s):`); console.error(errors.join('\n\n')); process.exit(1); } - const keyCount = base.keySet.size; - console.log(`i18n check passed: ${results.length} locale files, ${keyCount} keys each.`); + console.log( + `i18n check passed: ${results.length} locales x ${base.keySet.size} keys, ` + + `${referenced.size} referenced keys all resolve.` + ); } main(); diff --git a/main/manager-web/scripts/integrity-check.js b/main/manager-web/scripts/integrity-check.js new file mode 100644 index 000000000..d86f26a90 --- /dev/null +++ b/main/manager-web/scripts/integrity-check.js @@ -0,0 +1,194 @@ +#!/usr/bin/env node +/* + * Post-rebase web integrity checker. + * + * The upstream rebase has repeatedly produced *silent* runtime breakage that + * `vue-cli-service build` does NOT fail on and that unit tests (which do not + * mount full views) do not catch. Three classes of corruption have bitten us: + * + * 1. Lost/duplicated imports -> shorthand component/object references to an + * identifier that was never imported/declared (e.g. `components: + * { CustomDialog }` with no import). Throwing module factory makes + * webpack cache a half-initialized module and vue-router silently renders + * a blank page (no console error). + * + * 2. Dropped function-signature parameters / const bindings (e.g. a method + * body that references `request`, `onTerminalFailure`, `retryCount`, + * `retryWindowStartedAt`, `failCallback` after the merge deleted them + * from the signature). Throws ReferenceError at call time. + * + * 3. Interleaved / half-converted Vue templates -> mismatched tags + * (`` ... ``, `` ... ``) + * and duplicated option keys (`computed:` twice) that silently clobber + * each other. + * + * This script fails hard (exit 1) if any of those reappear, so a future + * rebase cannot merge them in silently. Run via `npm run check:integrity` + * (wired into CI and into scripts/westernization_rebase_check.sh). + */ +const fs = require('fs'); +const path = require('path'); +const acorn = require('acorn'); +const { analyze } = require('eslint-scope'); +const { parseComponent, compile } = require('vue-template-compiler'); + +const ROOT = path.resolve(__dirname, '..'); +const SRC = path.join(ROOT, 'src'); + +// Browser/ES/Node globals that legitimately resolve outside module scope. +const GLOBALS = new Set([ + 'window', 'document', 'navigator', 'location', 'localStorage', 'sessionStorage', 'console', + 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'requestAnimationFrame', + 'cancelAnimationFrame', 'Promise', 'JSON', 'Math', 'Date', 'Array', 'Object', 'String', + 'Number', 'Boolean', 'Symbol', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Proxy', 'Reflect', + 'Error', 'TypeError', 'RangeError', 'SyntaxError', 'EvalError', 'ReferenceError', + 'URIError', 'RegExp', 'encodeURIComponent', 'decodeURIComponent', 'encodeURI', 'decodeURI', + 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'fetch', 'URL', 'URLSearchParams', 'Blob', + 'File', 'FileReader', 'FormData', 'AbortController', 'AbortSignal', 'atob', 'btoa', + 'Image', 'Audio', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'MutationObserver', + 'IntersectionObserver', 'ResizeObserver', 'performance', 'crypto', 'process', 'Function', + 'alert', 'confirm', 'prompt', 'getComputedStyle', 'matchMedia', 'CSS', 'DOMParser', + 'XMLSerializer', 'TextEncoder', 'TextDecoder', 'Uint8Array', 'Int8Array', 'Uint16Array', + 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array', + 'Uint8ClampedArray', 'DataView', 'ArrayBuffer', 'Notification', 'caches', 'indexedDB', + 'self', 'globalThis', 'structuredClone', 'queueMicrotask', 'Intl', 'eval', 'arguments', + 'AudioContext', 'webkitAudioContext', 'Element', 'Node', 'HTMLElement', 'SVGElement', + 'Event', 'CustomEvent', 'KeyboardEvent', 'MouseEvent', 'DOMException', 'devicePixelRatio', + 'screen', 'history', 'Worker', 'IDBKeyRange', 'SpeechSynthesisUtterance', 'Range', 'Text', + 'undefined', 'NaN', 'Infinity', 'global', 'module', 'require', 'exports', 'Buffer', + '__dirname', '__filename', 'Response', 'Request', 'Headers', 'importScripts', + // ServiceWorker scope (src/service-worker.js, injected by workbox) + 'workbox', 'skipWaiting', 'clients', 'registration', 'serviceWorker', +]); + +// Vue SFC macros available inside