-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathindex.js
More file actions
219 lines (194 loc) · 6.47 KB
/
Copy pathindex.js
File metadata and controls
219 lines (194 loc) · 6.47 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
const { resolve } = require('path')
const { parseCamaroJson } = require('./json-parse')
const forceMainThread = process.env.CAMARO_FORCE_SINGLE_THREAD === 'true'
const poolSize = Number(process.env.CAMARO_POOL_SIZE || 0)
const { sabEnabled, fitsSabXmlPayload } = require('./sab-ipc')
const useSabIpc = sabEnabled() && !forceMainThread
let pool = null
if (forceMainThread) {
const workerFn = require('./worker')
pool = {
run(task, opts) {
void opts
return workerFn(task).then(parseCamaroJson)
},
destroy() {},
}
} else {
const { LeanPool } = require('./lean-pool')
const leanPool = new LeanPool(resolve(__dirname, 'pool-worker.js'), {
maxThreads: poolSize > 0 ? poolSize : undefined,
onRecycleXml: recycleXmlUtf8Buffer,
useSab: useSabIpc,
})
pool = {
run(task, opts) {
return leanPool.run(task, opts)
},
destroy() {
return leanPool.destroy()
},
}
}
/** Wasm Embind Utf-16 string → std::string is slower than Utf-8 bytes + malloc; reuse the Utf-8 path. */
const textEncoderUtf8 =
typeof TextEncoder !== 'undefined' ? new TextEncoder() : null
/** Recycled after worker transfers XML buffers back post-transform. */
let xmlUtf8Scratch = null
function recycleXmlUtf8Buffer(buf) {
if (
buf instanceof Uint8Array &&
buf.buffer &&
buf.buffer.byteLength > 0 &&
(!xmlUtf8Scratch || buf.byteLength >= xmlUtf8Scratch.byteLength)
) {
xmlUtf8Scratch = buf
}
}
function utf8BytesFromJsString(xml) {
if (!textEncoderUtf8) {
return Buffer.from(xml, 'utf8')
}
const worstCase = xml.length * 3
if (
!xmlUtf8Scratch ||
xmlUtf8Scratch.length < worstCase ||
xmlUtf8Scratch.buffer.byteLength === 0
) {
xmlUtf8Scratch = new Uint8Array(Math.max(worstCase, 65536))
}
const { written } = textEncoderUtf8.encodeInto(xml, xmlUtf8Scratch)
return xmlUtf8Scratch.subarray(0, written)
}
/**
* Owned Utf-8 from `TextEncoder`/Buffer-from-string can be transferred; user-supplied Binaries skip (avoid detach).
* @returns {{ xmlWire: Uint8Array|Buffer|ArrayBuffer, poolOpts?: { transferList: ArrayBuffer[] } }}
*/
function xmlPayloadForWorkerThread(xml) {
if (typeof xml === 'string') {
if (useSabIpc && fitsSabXmlPayload(xml)) {
return { sab: true }
}
const xmlWire = utf8BytesFromJsString(xml)
if (!forceMainThread && xmlWire.buffer && xmlWire.buffer.byteLength > 0) {
return {
xmlWire,
poolOpts: { transferList: [xmlWire.buffer] },
}
}
return { xmlWire }
}
if (useSabIpc && fitsSabXmlPayload(xml)) {
return { xmlWire: xml, sab: true }
}
// User-supplied binaries: structured clone only (transfer would detach caller's buffer).
return { xmlWire: xml }
}
function buildPoolTask(fn, xml, payload, extraArgs = []) {
const task = {
fn,
args: [payload.sab ? null : payload.xmlWire, ...extraArgs],
sab: payload.sab,
recycleXml: Boolean(payload.poolOpts?.transferList?.length),
}
if (payload.sab && typeof xml === 'string') {
task.xmlString = xml
} else if (payload.sab && payload.xmlWire != null) {
task.args[0] = payload.xmlWire
}
return task
}
function dispatchPool(taskBody, poolOpts) {
return pool.run(taskBody, poolOpts ?? {})
}
function isNonEmptyString(str) {
return typeof str === 'string' && str.length > 0
}
function utf8PayloadByteLength(xml) {
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(xml)) return xml.length
if (xml instanceof ArrayBuffer) return xml.byteLength
if (ArrayBuffer.isView(xml)) return xml.byteLength
return 0
}
function isNonEmptyUtf8Payload(xml) {
return utf8PayloadByteLength(xml) > 0
}
/** Reject invalid xml types before crossing to the WASM worker */
function validateXml(xml) {
if (typeof xml === 'string') {
if (!isNonEmptyString(xml)) {
throw new TypeError(
'1st argument (xml) must be a non-empty string, Buffer, Uint8Array, or ArrayBuffer'
)
}
return
}
if (!isNonEmptyUtf8Payload(xml)) {
throw new TypeError(
'1st argument (xml) must be a non-empty string, Buffer, Uint8Array, or ArrayBuffer'
)
}
}
function isEmptyObject(obj) {
return Object.entries(obj).length === 0 && obj.constructor === Object
}
const templateStringCache = new WeakMap()
function templateString(template) {
let cached = templateStringCache.get(template)
if (cached === undefined) {
cached = JSON.stringify(template)
templateStringCache.set(template, cached)
}
return cached
}
/**
* convert xml to json base on the template object
* @param {string|Buffer|Uint8Array|ArrayBuffer} xml xml as UTF-8 string or raw bytes
* @param {object} template template object
* @returns {object} xml converted to json object based on the template
*/
function transform(xml, template) {
validateXml(xml)
if (!template || typeof template !== 'object' || isEmptyObject(template)) {
throw new TypeError('2nd argument (template) must be an object')
}
const payload = xmlPayloadForWorkerThread(xml)
return dispatchPool(
buildPoolTask('transform', xml, payload, [templateString(template)]),
payload.poolOpts,
)
}
/**
* convert xml to json
* @param {string|Buffer|Uint8Array|ArrayBuffer} xml UTF-8 string or raw UTF-8 bytes of the XML
* @returns {object} json object converted from the input xml
*/
function toJson(xml) {
validateXml(xml)
const payload = xmlPayloadForWorkerThread(xml)
return dispatchPool(buildPoolTask('toJson', xml, payload), payload.poolOpts)
}
/**
* pretty print xml string
* @param {string|Buffer|Uint8Array|ArrayBuffer} xml UTF-8 string or raw UTF-8 bytes
* @param {object} opts pretty print options
* @param {number} [opts.indentSize=2] indent size, default=2
* @returns {string} xml pretty print string
*/
function prettyPrint(xml, opts = { indentSize: 2 }) {
validateXml(xml)
const payload = xmlPayloadForWorkerThread(xml)
return dispatchPool(
buildPoolTask('prettyPrint', xml, payload, [opts]),
payload.poolOpts,
)
}
/**
* destroy the worker pool
*/
function destroy() {
if (pool && typeof pool.destroy === 'function') {
return pool.destroy();
}
}
module.exports = { transform, toJson, prettyPrint, destroy }