Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions DynamicTranslation.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@
if (xhr.status < 400) {
try {
var translations = JSON.parse(xhr.responseText);
if (!translations || typeof translations !== 'object' || Array.isArray(translations) ||
!Object.keys(translations).every(function (key) {
return typeof translations[key] === 'string';
})) {
throw new Error('Translation file must be an object with string values');
}
this._translations[language] = translations;
console.log('翻譯載入成功:', language, Object.keys(translations).length, '個項目');
console.log('載入的翻譯項目範例:', Object.keys(translations).slice(0, 5));
Expand Down
24 changes: 24 additions & 0 deletions docs/research/translation-file-schema.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Validate translation files before caching

Base: 83ceac969392e7ea1948652d0b2dd6d06233ddeb.

The documented format is a key-value JSON translation dictionary. JSON parsing
alone also accepts arrays, primitives and dictionaries whose values are not
strings. The loader previously published those values as successful translations.
The translation/rendering path expects strings (including substring operations),
so a malformed file can return non-text data or throw during game UI rendering.
JSON null was even assigned to the cache before Object.keys threw, causing a
failed reload to destroy a previously usable dictionary.

Validate a non-null, non-array object with string values before replacing the
cache. Invalid data follows the existing callback(false) path and leaves the last
usable dictionary intact. Empty dictionaries, empty translated strings, Unicode,
and own keys such as hasOwnProperty remain valid. This does not change language
selection ordering, dictionary lookup rules, or options handlers in open PRs #7,
#8 and #9.

Regression: ten invalid shapes failed the new checks on the unchanged base;
two valid controls passed. After the fix all twelve pass, checking both callback
results and preservation of the previous dictionary/working translation.
The tests use the actual plugin loader with synthetic XMLHttpRequest responses,
not game files or external network traffic.
47 changes: 47 additions & 0 deletions tests/TranslationSchema.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
require('./setup');

describe('translation file schema', () => {
beforeEach(() => {
global.loadPlugin();
jest.spyOn(console, 'log').mockImplementation(() => {});
jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => jest.restoreAllMocks());

function load(value) {
jest.spyOn(XMLHttpRequest.prototype, 'send').mockImplementation(function () {
this.status = 200;
this.responseText = JSON.stringify(value);
this.onload();
});
const callback = jest.fn();
window.$translationManager.loadLanguage('zh', callback);
return callback;
}

test.each([
['null', null], ['array', ['translated']], ['string', 'translated'],
['number', 42], ['boolean', true],
['null entry', { Level: null }], ['number entry', { Level: 42 }],
['array entry', { Level: [] }], ['object entry', { Level: {} }],
['boolean entry', { Level: false }],
])('rejects %s without replacing a usable dictionary', (_name, value) => {
const manager = window.$translationManager;
const previous = { Level: '等級' };
manager._translations.zh = previous;
manager._currentLanguage = 'zh';
manager._isInitialized = true;
const callback = load(value);
expect(callback.mock.calls).toEqual([[false]]);
expect(manager._translations.zh).toBe(previous);
expect(manager.translate('Level')).toBe('等級');
});

test.each([{}, { Level: '等級', Empty: '', hasOwnProperty: 'literal key' }])(
'accepts string dictionaries including empty values', value => {
const callback = load(value);
expect(callback.mock.calls).toEqual([[true]]);
expect(window.$translationManager._translations.zh).toEqual(value);
}
);
});
Loading