Skip to content

Commit 0e270f2

Browse files
authored
Merge pull request #1006 from asdf80730/pr/node-guid-guard
fix(node): never throw when a service has no guid or a request has no id
2 parents eef8683 + fab1dbc commit 0e270f2

4 files changed

Lines changed: 129 additions & 5 deletions

File tree

‎node/loadServices.js‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ function loadServices() {
4949
let services = [];
5050
imeDir.forEach((dir) => {
5151
let config = parseImeConfig(dir);
52-
if (!config || !config.moduleName) {
52+
// A request id is matched against guid, so a config without one can never
53+
// be selected; skip it instead of loading a module nothing can reach.
54+
if (!config || !config.guid || !config.moduleName) {
5355
return;
5456
}
5557

@@ -84,15 +86,15 @@ function loadServiceById(id) {
8486
}
8587

8688
let service = null;
87-
let targetId = id.toLowerCase();
89+
let targetId = String(id).toLowerCase();
8890

8991
for (let dir of imeDir) {
9092
let config = parseImeConfig(dir);
9193
if (!config || !config.guid || !config.moduleName) {
9294
continue;
9395
}
9496

95-
if (config.guid.toLowerCase() === targetId) {
97+
if (String(config.guid).toLowerCase() === targetId) {
9698
try {
9799
service = require(`./input_methods/${dir}/${config.moduleName}`);
98100
break;

‎node/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"main": "server.js",
66
"scripts": {
77
"start": "cross-env debug=nime:* node server.js",
8-
"test": "node --test tests/nimeServer.test.js"
8+
"test": "node --test tests/nimeServer.test.js tests/emojime.test.js tests/loadServices.test.js"
99
},
1010
"repository": {
1111
"type": "git",

‎node/server.js‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,12 @@ if (services.length == 0) {
2020
let server = NIME.createServer((request) => {
2121

2222
let service = null;
23+
// Dispatch must not throw: the id comes from another process and may be
24+
// missing or not a string, and a guid comes from a hand-written ime.json.
25+
let requestId = String(request['id'] || '').toLowerCase();
2326

2427
services.forEach((tmpService) => {
25-
if (tmpService['guid'].toLowerCase() === request['id'].toLowerCase()) {
28+
if (String(tmpService['guid'] || '').toLowerCase() === requestId) {
2629
service = tmpService['textService'];
2730
}
2831
});

‎node/tests/loadServices.test.js‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
'use strict';
2+
// Regression tests for the input method configs the backend loads at startup.
3+
// server.js compares the guid of every loaded service with the id of every
4+
// request, so an ime.json that has a moduleName but no guid used to throw a
5+
// TypeError inside that comparison and leave the request unanswered.
6+
// Run with: npm test (from the node/ directory)
7+
//
8+
// Generated with AI assistance from omp (DeepSeek V4.1 Flash).
9+
10+
const { test } = require('node:test');
11+
const assert = require('node:assert');
12+
const { spawn } = require('node:child_process');
13+
const fs = require('node:fs');
14+
const os = require('node:os');
15+
const path = require('node:path');
16+
17+
const NODE_DIR = path.join(__dirname, '..');
18+
const SERVER_JS = path.join(NODE_DIR, 'server.js');
19+
const MEOW = '{C5F37DA0-274E-4837-9B7C-9BB79FE85D9D}';
20+
const UNKNOWN = '{00000000-0000-0000-0000-000000000000}';
21+
22+
// server.js reads input_methods/*/ime.json from process.cwd(), while the
23+
// service module is required relative to the node/ directory. Reusing the
24+
// bundled directory names therefore pairs a temporary config with the already
25+
// vendored service module, and nothing has to be written into the product tree.
26+
function makeImeTree(configs) {
27+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pime-ime-'));
28+
configs.forEach(([dir, config]) => {
29+
const dirPath = path.join(root, 'input_methods', dir);
30+
fs.mkdirSync(dirPath, { recursive: true });
31+
fs.writeFileSync(path.join(dirPath, 'ime.json'), JSON.stringify(config));
32+
});
33+
return root;
34+
}
35+
36+
// Starts server.js the way PIMELauncher does, in cwd, and returns a helper that
37+
// sends one raw line and resolves with the parsed JSON of the next PIME_MSG reply.
38+
function startBackend(cwd) {
39+
const child = spawn(process.execPath, [SERVER_JS], { cwd, stdio: ['pipe', 'pipe', 'pipe'] });
40+
let buf = '';
41+
let waiter = null;
42+
let exited = false;
43+
let stderr = '';
44+
child.stdout.on('data', (chunk) => {
45+
buf += chunk.toString('utf8');
46+
let i;
47+
while ((i = buf.indexOf('\n')) >= 0) {
48+
const line = buf.slice(0, i).trim();
49+
buf = buf.slice(i + 1);
50+
if (line.startsWith('PIME_MSG|') && waiter) {
51+
const w = waiter;
52+
waiter = null;
53+
w(JSON.parse(line.slice(line.indexOf('|', 'PIME_MSG|'.length) + 1)));
54+
}
55+
}
56+
});
57+
child.stderr.on('data', (chunk) => { stderr += chunk.toString('utf8'); });
58+
const exit = new Promise((resolve) => {
59+
child.on('exit', (code) => {
60+
exited = true;
61+
resolve(code);
62+
if (waiter) { const w = waiter; waiter = null; w(null); }
63+
});
64+
});
65+
return {
66+
sendLine: (line) => new Promise((resolve, reject) => {
67+
const timer = setTimeout(() => { waiter = null; reject(new Error(`no reply to: ${line}`)); }, 10000);
68+
waiter = (reply) => { clearTimeout(timer); resolve(reply); };
69+
child.stdin.write(line + '\n');
70+
}),
71+
send: function (clientId, msg) { return this.sendLine(`${clientId}|${JSON.stringify(msg)}`); },
72+
alive: () => !exited,
73+
stderr: () => stderr,
74+
exit: () => exit,
75+
stop: () => child.kill(),
76+
};
77+
}
78+
79+
// Resolves with the exit code, or null when the backend is still running.
80+
function exitWithin(backend, ms) {
81+
return new Promise((resolve) => {
82+
const timer = setTimeout(() => resolve(null), ms);
83+
backend.exit().then((code) => { clearTimeout(timer); resolve(code); });
84+
});
85+
}
86+
87+
const initMsg = (id, seqNum) => ({ method: 'init', id, isWindows8Above: true, isMetroApp: false, isUiLess: false, isConsole: false, seqNum });
88+
89+
test('an ime.json without guid does not break a sibling service', async () => {
90+
const root = makeImeTree([
91+
['emojime', { name: 'no-guid', moduleName: 'index' }],
92+
['meow', { name: '喵喵輸入法', guid: MEOW, moduleName: 'index' }],
93+
]);
94+
const b = startBackend(root);
95+
try {
96+
// The guid-less config used to throw here, before any reply was written.
97+
assert.deepStrictEqual(await b.send('A', initMsg(MEOW, 0)), { success: true, seqNum: 0 });
98+
assert.ok(b.alive());
99+
// An unknown id and a request without an id are answered, not fatal.
100+
assert.deepStrictEqual(await b.send('B', initMsg(UNKNOWN, 1)), { success: false, seqNum: 1 });
101+
assert.deepStrictEqual(await b.send('C', { method: 'init', seqNum: 2 }), { success: false, seqNum: 2 });
102+
assert.ok(!b.stderr().includes('uncaught exception'), b.stderr());
103+
assert.ok(b.alive());
104+
} finally {
105+
b.stop();
106+
fs.rmSync(root, { recursive: true, force: true });
107+
}
108+
});
109+
110+
test('a tree where no config has a guid exits at startup', async () => {
111+
const root = makeImeTree([['emojime', { name: 'no-guid', moduleName: 'index' }]]);
112+
const b = startBackend(root);
113+
try {
114+
assert.strictEqual(await exitWithin(b, 5000), 1, 'no usable service left, so server.js must report it');
115+
} finally {
116+
b.stop();
117+
fs.rmSync(root, { recursive: true, force: true });
118+
}
119+
});

0 commit comments

Comments
 (0)