fix(translation): preserve latest language selection during async loads

Merged
KN
6h ago
+673-203

This head

Head dcb0976b5737d8bc6d624a162b03c996d9d3843c. Base main is 93ae7c0c35bc8505cea3223ecc21ff650f65f2e9.

Confirmed defect

Out-of-order language-file responses can overwrite a newer language choice. Selecting the already-active language also leaves an older pending selection live, and a failed latest load can allow an older selection to apply unexpectedly.

ConfigManager.applyData skipped setLanguage when the configured language matched the active one. Starting on zh, applying an en configuration, then applying a zh configuration before the en request finished left that request valid. ConfigManager.makeData().language ended at zh while the late en response switched the game.

A second in-flight load of the same language could also replace the first load's cache token and still report success. A saved en selection applied before auto-detect, or a second initialize() for the default language, could then activate or mark initialization done with no dictionary cached.

On 8f3f80fb0d0c74feb976c98249a35a8a78300b40, later callers of one language already joined a single in-flight load, and success was reported only after the dictionary was cached. That load still had more than one exit. A callback that threw after a valid dictionary was cached was handled as a parse error, so finish ran again. That callback received true, then false, and threw again before the joined caller was reached, so the joined caller got no result. XMLHttpRequest.open(), send(), and abort left the pending entry in place, so a retry appended another callback to a request that never finished. _pendingLanguageLoads also inherited Object.prototype, and each callback was invoked as a method of the callback array.

On 8f194ee715d721a821ad0403d7a06aded68cac84, those load exits already went through one finish(result). With auto-detect off, aborting the default-language request delivered false to the initialization callback, and the callback set _isInitialized anyway. initialize() then returned immediately, so one transient failure left the game without its dictionary.

On 1d248e326f244de32a27b433855697229ba557af, a failed default load correctly left _isInitialized false. That flag still also meant translation was enabled. With auto-detect off, a saved en selection could cache its dictionary and getCurrentLanguage() reported en, while translate('Level') returned 'Level'. The merge base returned 'English Level'.

On b45d582adb3f531e8475542d5079c4be7d55deb7, translate() uses the cached dictionary for the current language, and _isInitialized only tells initialize() whether to try the startup load again. _applyTranslations no longer returns early while that flag is false. If a saved language finishes loading before System.json, _applyTranslations reads TextManager.currencyUnit while $dataSystem is still null. That getter throws. The loader catches the exception after the language has already switched, so _refreshAllWindows() and the registered refresh callbacks do not run.

On 2bb093a1b2745708c7e49ad2f04037114a65a904, each cached language file was still the parsed object, so it inherited Object.prototype. A string hasOwnProperty entry was accepted, and a full-mode miss called that string. With no constructor entry, translate('constructor') and translate(' constructor ') returned the inherited function. xhr.timeout stayed 0, so a stalled request never reached finish(false) and a later selection joined it. Game_Message.add translated each line before it was queued, so the joined text no longer matched a whole-message key.

Change

Each setLanguage call gets a unique request token, including an active or cached selection. Only the latest successful asynchronous selection applies translations and refreshes windows.

ConfigManager.applyData forwards every language selection to the manager when the manager exists. setLanguage replaces the request token before it returns early for the language that is already active.

Each language has one in-flight loadLanguage request. A later caller for that language joins the existing request instead of starting another one. A parsed dictionary is still rejected unless it is a non-null, non-array object whose values are strings. The load copies the accepted entries onto Object.create(null) and reports success only after that dictionary is in the cache. setLanguage activates and refreshes only after that success.

Success, a parse or validation failure, an HTTP error, open() or send() throwing, constructing XMLHttpRequest throwing, abort, and timeout all go through one finish(result). It runs once: the pending entry is removed first, then each callback is called once with that same result. A callback exception is logged with console.error. The other callbacks still run once with the original result, and the list is not run again. The pending map, the translation cache, and each language dictionary are Object.create(null). Each callback is invoked through a local variable, so a non-strict callback receives the global object as this. new XMLHttpRequest() is inside the same guarded setup as open() and send(). xhr.timeout is 30000 before send(). No request is cancelled, and the loadLanguage callback signature is unchanged.

With auto-detect off, the default-language callback sets _isInitialized only when that load succeeds. An aborted or otherwise failed startup load leaves initialize() retryable. setLanguage still returns immediately when the selected language is already active.

translate() uses the cached dictionary for the current language and does not read _isInitialized. The flag only tells initialize() whether to try the startup load again, so it can stay false while the active language has a dictionary. _applyTranslations and translateIfNeed no longer consult the flag. translate() returns the source text when that language has no dictionary. Inherited names are not entries. A real hasOwnProperty string stays a translation, and the substring scan does not call hasOwnProperty on the dictionary.

_applyTranslations skips the currency-unit setup until $dataSystem exists, so TextManager.currencyUnit is not read while system data is still null. A successful startup load after DataManager.onLoad still calls _applyTranslations. That later call does not translate the currency unit: TextManager.currencyUnit is a getter that returns a string, so the existing object check skips the setup, and TextManager.currencyUnit keeps the source value while translate('G') returns the translation. That behavior is the same on the merge base and is not changed here. The bundled testTranslationSystem() diagnostic probes when TranslationManager.getStatus().loadedTranslations contains the current language. A false _isInitialized flag no longer skips those probes.

Message translation is only in Game_Message.allText(). It tries the joined source as one key and, on a miss, translates non-blank lines. Game_Message.add and Window_Message.startMessage are not wrapped, so normal messages and scrolling text both read the same joined source.

Verification

Local checks on this head's tree before push:

  • npm ci
  • npx jest: 100 tests passed, 3 suites, on Node v22.23.4 / npm 10.9.9
  • pytest -q tests: 92 tests passed on Python 3.12.3 / pytest 9.2.0
  • git diff --check passed

Regression coverage in tests/language-race.test.js:

  • zh, then ConfigManager.applyData({ language: 'en' }), then ConfigManager.applyData({ language: 'zh' }) before en resolves. The config value and the active language stay zh, and the late en response does not apply translations or refresh windows. This test runs after the integration tests, and those tests restore the hooked RPG Maker globals.
  • A second setLanguage('en') while en is loading joins that request. Nothing is applied before the response; the single success applies and refreshes once.
  • Saved en is applied before DataManager.onLoad with auto-detect on. The plugin is installed once on fresh RPG Maker globals. The en loadLanguage count is 1 before onLoad and increases during that call. One en request succeeds, the other language probes fail, en is in the available languages, and translate('Level') returns 'English Level'. Selecting en again does not start another request.
  • With auto-detect off and $dataSystem initially null, the plugin is installed once on fresh globals. One DataManager.onLoad makes at least two loadLanguage('zh') calls. Those callers share one request, and translate('Level') returns '等級'.
  • A callback that throws after a valid en dictionary is cached is logged. The test records that callback's arguments as [true]. The joined setLanguage('en') callback is recorded separately, and its only call receives true. en becomes active.
  • open() throwing, send() throwing, abort, timeout, and a throwing XMLHttpRequest constructor each report false once and remove the pending entry. The request that times out has xhr.timeout 30000. A later en load starts a new request and can succeed. An onload after abort does not report a second result.
  • A language named constructor joins one in-flight load. Loading __proto__ stores that dictionary and leaves the cache prototype null.
  • A non-strict load callback receives the global object as this, so this.ConfigManager is the RPG Maker ConfigManager.
  • With auto-detect off, aborting the startup zh load leaves _isInitialized false and does not cache a dictionary. A later initialize() starts a new request, and its success sets _isInitialized and translate('Level') returns '等級'.
  • With auto-detect off, a saved en selection and a startup zh 404 are completed in both orders. getCurrentLanguage() is 'en', translate('Level') returns 'English Level', and _isInitialized stays false.
  • With auto-detect off and $dataSystem null, TextManager.currencyUnit is a getter that reads $dataSystem. The saved en request is completed before DataManager.onLoad. The registered refresh callback runs exactly once, and getCurrentLanguage() is 'en'.

tests/TranslationSchema.test.js loads { Level: '等級', hasOwnProperty: 'own label' } with substring extraction on. The cached dictionary's prototype is null. translate('hasOwnProperty') returns 'own label'. translate('constructor') returns 'constructor', translate(' constructor ') returns ' constructor ', and translate('zzzz') returns 'zzzz'.

tests/DynamicTranslation.test.js keeps 'Line1' and 'Line2' in the message queue. With both 'Line1' and 'Line1\nLine2' in the dictionary, allText() returns 'Whole'. When the whole message misses, lines 'Line 1', '', and 'Line 2' produce '行 1\n\n行 2'.

Independent box rerun at dcb0976 (Linux, Node v24.22.1): npm ci, npx jest 100 passed in 3 suites, pytest -q tests 92 passed.

Hosted CI at dcb0976 (run 46558194245) passed. Earlier, run 46531189703 passed at 2bb093a.

Limits

Two selections of one uncached language no longer start two requests, so there is no older-versus-newer arrival order for distinct payloads of that language. The joined-load test checks the refresh count before the single response and once after it. It does not assert separate counts for two completion orders.

The timeout test reads xhr.timeout and calls ontimeout. It does not wait 30000 milliseconds.

No separate build or lint script exists. Tests use synthetic XHR responses. No real RPG Maker installation or browser acceptance is claimed. The lockfile is unchanged relative to main. No credentials, live game files, deployment, or release used. Not merged.