Debian Codegraph @

plugins/jieba/node/index.js

raw symbols SCIP
1 const path = require('path');
2 const os = require('os');
3
4 const platform = os.platform();
5 const arch = os.arch();
6 const prebuildDir = path.join(__dirname, 'prebuilds', `${platform}-${arch}`);
7 const scopedPackageName = `@opencc/opencc-jieba-${platform}-${arch}`;
8
9 // Platform-specific plugin library filename
10 const libName = platform === 'win32' ? 'opencc-jieba.dll'
11 : platform === 'darwin' ? 'libopencc-jieba.dylib'
12 : 'libopencc-jieba.so';
13
14 const dataDir = path.join(__dirname, 'data');
15 const configDir = dataDir;
16
17 function requireOptionalPackage(packageName) {
18 try {
19 return require(packageName);
20 } catch (error) {
21 if (error && error.code === 'MODULE_NOT_FOUND') {
22 return null;
23 }
24 throw error;
25 }
26 }
27
28 const scopedPackage = requireOptionalPackage(scopedPackageName);
29 const pluginLibrary = scopedPackage && scopedPackage.pluginLibrary
30 ? scopedPackage.pluginLibrary
31 : path.join(prebuildDir, libName);
32 const pluginDir = path.dirname(pluginLibrary);
33
34 function resolveConfigPath(config) {
35 if (typeof config !== 'string' || path.isAbsolute(config)) {
36 return null;
37 }
38 const candidates = [config];
39 if (!config.endsWith('.json')) {
40 candidates.push(`${config}.json`);
41 }
42 for (const candidate of candidates) {
43 if (candidate.includes('/') || candidate.includes('\\')) {
44 continue;
45 }
46 const configPath = path.join(configDir, candidate);
47 if (require('fs').existsSync(configPath)) {
48 return configPath;
49 }
50 }
51 return null;
52 }
53
54 module.exports = {
55 /** Directory containing the prebuilt libopencc-jieba shared library. */
56 pluginDir,
57 /** Absolute path to the platform-specific plugin shared library. */
58 pluginLibrary,
59 /** Root data directory (config files and jieba_dict/ live here). */
60 dataDir,
61 /** Directory containing jieba-backed OpenCC configuration JSON files. */
62 configDir,
63 /** Resolve a jieba-backed config name, with or without the .json suffix. */
64 resolveConfigPath,
65 };