forked from thx/resvg-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wasm-binding.ts
47 lines (40 loc) · 1.38 KB
/
wasm-binding.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
import init, { Resvg as _Resvg, InitInput } from './wasm/dist'
import { CustomFontsOptions, ResvgRenderOptions, SystemFontsOptions } from './wasm/index'
let initialized = false
/**
* Initialize Wasm module
* @param module_or_path WebAssembly Module or .wasm url
*
*/
export const initWasm = async (module_or_path: Promise<InitInput> | InitInput): Promise<void> => {
if (initialized) {
throw new Error('Already initialized. The `initWasm()` function can be used only once.')
}
await init(await module_or_path)
initialized = true
}
export const Resvg = class extends _Resvg {
/**
* @param {Uint8Array | string} svg
* @param {ResvgRenderOptions | undefined} options
*/
constructor(svg: Uint8Array | string, options?: ResvgRenderOptions) {
if (!initialized) throw new Error('Wasm has not been initialized. Call `initWasm()` function.')
const font = options?.font
if (!!font && isCustomFontsOptions(font)) {
const serializableOptions = {
...options,
font: {
...font,
fontBuffers: undefined,
},
}
super(svg, JSON.stringify(serializableOptions), font.fontBuffers)
} else {
super(svg, JSON.stringify(options))
}
}
}
function isCustomFontsOptions(value: SystemFontsOptions | CustomFontsOptions): value is CustomFontsOptions {
return Object.prototype.hasOwnProperty.call(value, 'fontBuffers')
}