fix(translation): preserve latest language selection during async loads
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 cinpx jest: 100 tests passed, 3 suites, on Node v22.23.4 / npm 10.9.9pytest -q tests: 92 tests passed on Python 3.12.3 / pytest 9.2.0git diff --checkpassed
Regression coverage in tests/language-race.test.js:
zh, thenConfigManager.applyData({ language: 'en' }), thenConfigManager.applyData({ language: 'zh' })beforeenresolves. The config value and the active language stayzh, and the lateenresponse 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')whileenis loading joins that request. Nothing is applied before the response; the single success applies and refreshes once. - Saved
enis applied beforeDataManager.onLoadwith auto-detect on. The plugin is installed once on fresh RPG Maker globals. TheenloadLanguagecount is 1 beforeonLoadand increases during that call. Oneenrequest succeeds, the other language probes fail,enis in the available languages, andtranslate('Level')returns'English Level'. Selectingenagain does not start another request. - With auto-detect off and
$dataSysteminitially null, the plugin is installed once on fresh globals. OneDataManager.onLoadmakes at least twoloadLanguage('zh')calls. Those callers share one request, andtranslate('Level')returns'等級'. - A callback that throws after a valid
endictionary is cached is logged. The test records that callback's arguments as[true]. The joinedsetLanguage('en')callback is recorded separately, and its only call receivestrue.enbecomes active. open()throwing,send()throwing, abort, timeout, and a throwingXMLHttpRequestconstructor each reportfalseonce and remove the pending entry. The request that times out hasxhr.timeout30000. A laterenload starts a new request and can succeed. Anonloadafter abort does not report a second result.- A language named
constructorjoins 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, sothis.ConfigManageris the RPG MakerConfigManager. - With auto-detect off, aborting the startup
zhload leaves_isInitializedfalse and does not cache a dictionary. A laterinitialize()starts a new request, and its success sets_isInitializedandtranslate('Level')returns'等級'. - With auto-detect off, a saved
enselection and a startupzh404 are completed in both orders.getCurrentLanguage()is'en',translate('Level')returns'English Level', and_isInitializedstays false. - With auto-detect off and
$dataSystemnull,TextManager.currencyUnitis a getter that reads$dataSystem. The savedenrequest is completed beforeDataManager.onLoad. The registered refresh callback runs exactly once, andgetCurrentLanguage()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.