-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathworker.ts
70 lines (63 loc) · 1.98 KB
/
worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { loadWasm, expose } from '@libreservice/my-worker'
import { LazyCache } from '@libreservice/lazy-cache'
import { version } from '../package.json'
const openccPath = '/usr/local/share/opencc'
const prefix = ('__LIBRESERVICE_CDN__' || './') + 'opencc'
const lazyCache = new LazyCache('config')
const readyPromise = loadWasm('opencc.js', {
url: '__LIBRESERVICE_CDN__',
init () {
for (const path of ['/usr', '/usr/local', '/usr/local/share', openccPath]) {
Module.FS.mkdir(path)
}
}
})
async function loadFile (file: string, read?: boolean): Promise<string> {
const path = `${openccPath}/${file}`
let u8array: Uint8Array
try {
Module.FS.lookupPath(path)
if (read) {
u8array = Module.FS.readFile(path)
}
} catch {
const url = `${prefix}/${file}`
u8array = new Uint8Array(await lazyCache.get(file, version, url))
Module.FS.writeFile(path, u8array)
}
if (read) {
return new TextDecoder('utf-8', { fatal: true }).decode(u8array!)
}
return ''
}
async function loadConfig (config: string) {
const content = await loadFile(config, true)
const obj = JSON.parse(content)
const files = [obj.segmentation.dict.file]
const load = (file: string) => !files.includes(file) && files.push(file)
for (const { dict } of obj.conversion_chain) {
const { file, dicts } = dict
file && load(file)
if (dicts) {
for (const { file } of dicts) {
load(file)
}
}
}
return Promise.all(files.map(file => loadFile(file)))
}
function genOcd2 (buffer: ArrayBuffer): number {
Module.FS.writeFile('/input.txt', new Uint8Array(buffer))
Module._gen_ocd2()
return Module.FS.lstat('/output.ocd2').size
}
expose({
async convert (config: string, text: string): Promise<string> {
await loadConfig(config)
return Module.ccall('convert', 'string', ['string', 'string'], [config, text])
},
genOcd2,
getFile (content: ArrayBuffer) {
new Uint8Array(content).set(Module.FS.readFile('/output.ocd2'))
}
}, readyPromise)