encoding.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // We can't return native TextDecoder if it's present, as Node.js one is broken on windows-1252 and we fix that
  2. // We are also faster than Node.js built-in on both TextEncoder and TextDecoder
  3. import { utf16toString, utf16toStringLoose } from '@exodus/bytes/utf16.js'
  4. import { utf8fromStringLoose, utf8toString, utf8toStringLoose } from '@exodus/bytes/utf8.js'
  5. import {
  6. createSinglebyteDecoder,
  7. latin1toString,
  8. latin1fromString,
  9. } from '@exodus/bytes/single-byte.js'
  10. import labels from './encoding.labels.js'
  11. import { fromSource, getBOMEncoding } from './encoding.api.js'
  12. import { unfinishedBytes, mergePrefix } from './encoding.util.js'
  13. export { getBOMEncoding } from './encoding.api.js'
  14. export const E_ENCODING = 'Unknown encoding'
  15. const E_MULTI = "import '@exodus/bytes/encoding.js' for legacy multi-byte encodings support"
  16. const E_OPTIONS = 'The "options" argument must be of type object'
  17. const replacementChar = '\uFFFD'
  18. const multibyteSet = new Set(['big5', 'euc-kr', 'euc-jp', 'iso-2022-jp', 'shift_jis', 'gbk', 'gb18030']) // prettier-ignore
  19. let createMultibyteDecoder, multibyteEncoder
  20. let labelsMap
  21. // Warning: unlike whatwg-encoding, returns lowercased labels
  22. // Those are case-insensitive and that's how TextDecoder encoding getter normalizes them
  23. // https://encoding.spec.whatwg.org/#names-and-labels
  24. export function normalizeEncoding(label) {
  25. // fast path
  26. if (label === 'utf-8' || label === 'utf8' || label === 'UTF-8' || label === 'UTF8') return 'utf-8'
  27. if (label === 'windows-1252' || label === 'ascii' || label === 'latin1') return 'windows-1252'
  28. // full map
  29. if (/[^\w\t\n\f\r .:-]/i.test(label)) return null // must be ASCII (with ASCII whitespace)
  30. const low = `${label}`.trim().toLowerCase()
  31. if (Object.hasOwn(labels, low)) return low
  32. if (!labelsMap) {
  33. labelsMap = new Map()
  34. for (const [name, aliases] of Object.entries(labels)) {
  35. for (const alias of aliases) labelsMap.set(alias, name)
  36. }
  37. }
  38. const mapped = labelsMap.get(low)
  39. if (mapped) return mapped
  40. return null
  41. }
  42. const uppercasePrefixes = new Set(['utf', 'iso', 'koi', 'euc', 'ibm', 'gbk'])
  43. // Unlike normalizeEncoding, case-sensitive
  44. // https://encoding.spec.whatwg.org/#names-and-labels
  45. export function labelToName(label) {
  46. const enc = normalizeEncoding(label)
  47. if (enc === 'utf-8') return 'UTF-8' // fast path
  48. if (!enc) return enc
  49. if (uppercasePrefixes.has(enc.slice(0, 3))) return enc.toUpperCase()
  50. if (enc === 'big5') return 'Big5'
  51. if (enc === 'shift_jis') return 'Shift_JIS'
  52. return enc
  53. }
  54. export const isMultibyte = (enc) => multibyteSet.has(enc)
  55. export function setMultibyte(createDecoder, createEncoder) {
  56. createMultibyteDecoder = createDecoder
  57. multibyteEncoder = createEncoder
  58. }
  59. export function getMultibyteEncoder() {
  60. if (!multibyteEncoder) throw new Error(E_MULTI)
  61. return multibyteEncoder
  62. }
  63. const define = (obj, key, value) => Object.defineProperty(obj, key, { value, writable: false })
  64. function isAnyUint8Array(x) {
  65. if (x instanceof Uint8Array) return true
  66. if (!x || !ArrayBuffer.isView(x) || x.BYTES_PER_ELEMENT !== 1) return false
  67. return Object.prototype.toString.call(x) === '[object Uint8Array]'
  68. }
  69. function unicodeDecoder(encoding, loose) {
  70. if (encoding === 'utf-8') return loose ? utf8toStringLoose : utf8toString // likely
  71. const form = encoding === 'utf-16le' ? 'uint8-le' : 'uint8-be'
  72. return loose ? (u) => utf16toStringLoose(u, form) : (u) => utf16toString(u, form)
  73. }
  74. export class TextDecoder {
  75. #decode
  76. #unicode
  77. #multibyte
  78. #chunk
  79. #canBOM
  80. constructor(encoding = 'utf-8', options = {}) {
  81. if (typeof options !== 'object') throw new TypeError(E_OPTIONS)
  82. const enc = normalizeEncoding(encoding)
  83. if (!enc || enc === 'replacement') throw new RangeError(E_ENCODING)
  84. define(this, 'encoding', enc)
  85. define(this, 'fatal', !!options.fatal)
  86. define(this, 'ignoreBOM', !!options.ignoreBOM)
  87. this.#unicode = enc === 'utf-8' || enc === 'utf-16le' || enc === 'utf-16be'
  88. this.#multibyte = !this.#unicode && isMultibyte(enc)
  89. this.#canBOM = this.#unicode && !this.ignoreBOM
  90. }
  91. get [Symbol.toStringTag]() {
  92. return 'TextDecoder'
  93. }
  94. decode(input, options = {}) {
  95. if (typeof options !== 'object') throw new TypeError(E_OPTIONS)
  96. const stream = !!options.stream
  97. let u = input === undefined ? new Uint8Array() : fromSource(input)
  98. const empty = u.length === 0 // also can't be streaming after next line
  99. if (empty && stream) return '' // no state change
  100. if (this.#unicode) {
  101. let prefix
  102. if (this.#chunk) {
  103. const merged = mergePrefix(u, this.#chunk, this.encoding)
  104. if (u.length < 3) {
  105. u = merged // might be unfinished, but fully consumed old u
  106. } else {
  107. prefix = merged // stops at complete chunk
  108. const add = prefix.length - this.#chunk.length
  109. if (add > 0) u = u.subarray(add)
  110. }
  111. this.#chunk = null
  112. } else if (empty) {
  113. this.#canBOM = !this.ignoreBOM // not streaming
  114. return ''
  115. }
  116. // For non-stream utf-8 we don't have to do this as it matches utf8toStringLoose already
  117. // For non-stream loose utf-16 we still have to do this as this API supports uneven byteLength unlike utf16toStringLoose
  118. let suffix = ''
  119. if (stream || (!this.fatal && this.encoding !== 'utf-8')) {
  120. const trail = unfinishedBytes(u, u.byteLength, this.encoding)
  121. if (trail > 0) {
  122. if (stream) {
  123. this.#chunk = Uint8Array.from(u.subarray(-trail)) // copy
  124. } else {
  125. // non-fatal mode as already checked
  126. suffix = replacementChar
  127. }
  128. u = u.subarray(0, -trail)
  129. }
  130. }
  131. let seenBOM = false
  132. if (this.#canBOM) {
  133. const bom = this.#findBom(prefix ?? u)
  134. if (bom) {
  135. seenBOM = true
  136. if (prefix) {
  137. prefix = prefix.subarray(bom)
  138. } else {
  139. u = u.subarray(bom)
  140. }
  141. }
  142. } else if (!stream && !this.ignoreBOM) {
  143. this.#canBOM = true
  144. }
  145. if (!this.#decode) this.#decode = unicodeDecoder(this.encoding, !this.fatal)
  146. try {
  147. const res = (prefix ? this.#decode(prefix) : '') + this.#decode(u) + suffix
  148. // "BOM seen" is set on the current decode call only if it did not error, in "serialize I/O queue" after decoding
  149. if (stream && (seenBOM || res.length > 0)) this.#canBOM = false
  150. return res
  151. } catch (err) {
  152. this.#chunk = null // reset unfinished chunk on errors
  153. // The correct way per spec seems to be not destroying the decoder state (aka BOM here) in stream mode
  154. // See also multi-byte.js
  155. throw err
  156. }
  157. // eslint-disable-next-line no-else-return
  158. } else if (this.#multibyte) {
  159. if (!createMultibyteDecoder) throw new Error(E_MULTI)
  160. if (!this.#decode) this.#decode = createMultibyteDecoder(this.encoding, !this.fatal) // can contain state!
  161. return this.#decode(u, stream)
  162. } else {
  163. if (!this.#decode) this.#decode = createSinglebyteDecoder(this.encoding, !this.fatal)
  164. return this.#decode(u)
  165. }
  166. }
  167. #findBom(u) {
  168. switch (this.encoding) {
  169. case 'utf-8':
  170. return u.byteLength >= 3 && u[0] === 0xef && u[1] === 0xbb && u[2] === 0xbf ? 3 : 0
  171. case 'utf-16le':
  172. return u.byteLength >= 2 && u[0] === 0xff && u[1] === 0xfe ? 2 : 0
  173. case 'utf-16be':
  174. return u.byteLength >= 2 && u[0] === 0xfe && u[1] === 0xff ? 2 : 0
  175. }
  176. /* c8 ignore next */
  177. throw new Error('Unreachable')
  178. }
  179. }
  180. export class TextEncoder {
  181. constructor() {
  182. define(this, 'encoding', 'utf-8')
  183. }
  184. get [Symbol.toStringTag]() {
  185. return 'TextEncoder'
  186. }
  187. encode(str = '') {
  188. if (typeof str !== 'string') str = `${str}`
  189. return utf8fromStringLoose(str) // non-pooled
  190. }
  191. encodeInto(str, target) {
  192. if (typeof str !== 'string') str = `${str}`
  193. if (!isAnyUint8Array(target)) throw new TypeError('Target must be an Uint8Array')
  194. if (target.buffer.detached) return { read: 0, written: 0 } // Until https://github.com/whatwg/encoding/issues/324 is resolved
  195. const tlen = target.length
  196. if (tlen < str.length) str = str.slice(0, tlen)
  197. let u8 = utf8fromStringLoose(str)
  198. let read
  199. if (tlen >= u8.length) {
  200. read = str.length
  201. } else if (u8.length === str.length) {
  202. if (u8.length > tlen) u8 = u8.subarray(0, tlen) // ascii can be truncated
  203. read = u8.length
  204. } else {
  205. u8 = u8.subarray(0, tlen)
  206. const unfinished = unfinishedBytes(u8, u8.length, 'utf-8')
  207. if (unfinished > 0) u8 = u8.subarray(0, u8.length - unfinished)
  208. // We can do this because loose str -> u8 -> str preserves length, unlike loose u8 -> str -> u8
  209. // Each unpaired surrogate (1 charcode) is replaced with a single charcode
  210. read = utf8toStringLoose(u8).length // FIXME: Converting back is very inefficient
  211. }
  212. try {
  213. target.set(u8)
  214. } catch {
  215. return { read: 0, written: 0 } // see above, likely detached but no .detached property support
  216. }
  217. return { read, written: u8.length }
  218. }
  219. }
  220. const E_NO_STREAMS = 'TransformStream global not present in the environment'
  221. // https://encoding.spec.whatwg.org/#interface-textdecoderstream
  222. export class TextDecoderStream {
  223. constructor(encoding = 'utf-8', options = {}) {
  224. if (!globalThis.TransformStream) throw new Error(E_NO_STREAMS)
  225. const decoder = new TextDecoder(encoding, options)
  226. const transform = new TransformStream({
  227. transform: (chunk, controller) => {
  228. const value = decoder.decode(fromSource(chunk), { stream: true })
  229. if (value) controller.enqueue(value)
  230. },
  231. flush: (controller) => {
  232. // https://streams.spec.whatwg.org/#dom-transformer-flush
  233. const value = decoder.decode()
  234. if (value) controller.enqueue(value)
  235. // No need to call .terminate() (Node.js is wrong)
  236. },
  237. })
  238. define(this, 'encoding', decoder.encoding)
  239. define(this, 'fatal', decoder.fatal)
  240. define(this, 'ignoreBOM', decoder.ignoreBOM)
  241. define(this, 'readable', transform.readable)
  242. define(this, 'writable', transform.writable)
  243. }
  244. get [Symbol.toStringTag]() {
  245. return 'TextDecoderStream'
  246. }
  247. }
  248. // https://encoding.spec.whatwg.org/#interface-textencoderstream
  249. // Only UTF-8 per spec
  250. export class TextEncoderStream {
  251. constructor() {
  252. if (!globalThis.TransformStream) throw new Error(E_NO_STREAMS)
  253. let lead
  254. const transform = new TransformStream({
  255. // https://encoding.spec.whatwg.org/#encode-and-enqueue-a-chunk
  256. // Not identical in code, but reuses loose mode to have identical behavior
  257. transform: (chunk, controller) => {
  258. let s = String(chunk) // DOMString, might contain unpaired surrogates
  259. if (s.length === 0) return
  260. if (lead) {
  261. s = lead + s
  262. lead = null
  263. }
  264. const last = s.charCodeAt(s.length - 1) // Can't come from previous lead due to length check
  265. if ((last & 0xfc_00) === 0xd8_00) {
  266. lead = s[s.length - 1]
  267. s = s.slice(0, -1)
  268. }
  269. if (s) controller.enqueue(utf8fromStringLoose(s))
  270. },
  271. // https://encoding.spec.whatwg.org/#encode-and-flush
  272. flush: (controller) => {
  273. if (lead) controller.enqueue(Uint8Array.of(0xef, 0xbf, 0xbd))
  274. },
  275. })
  276. define(this, 'encoding', 'utf-8')
  277. define(this, 'readable', transform.readable)
  278. define(this, 'writable', transform.writable)
  279. }
  280. get [Symbol.toStringTag]() {
  281. return 'TextEncoderStream'
  282. }
  283. }
  284. // https://encoding.spec.whatwg.org/#decode
  285. // Warning: encoding sniffed from BOM takes preference over the supplied one
  286. // Warning: lossy, performs replacement, no option of throwing
  287. // Completely ignores encoding and even skips validation when BOM is found
  288. // Unlike TextDecoder public API, additionally supports 'replacement' encoding
  289. export function legacyHookDecode(input, fallbackEncoding = 'utf-8') {
  290. let u8 = fromSource(input)
  291. const bomEncoding = getBOMEncoding(u8)
  292. if (bomEncoding) u8 = u8.subarray(bomEncoding === 'utf-8' ? 3 : 2)
  293. const enc = bomEncoding ?? normalizeEncoding(fallbackEncoding) // "the byte order mark is more authoritative than anything else"
  294. if (enc === 'utf-8') return utf8toStringLoose(u8)
  295. if (enc === 'utf-16le' || enc === 'utf-16be') {
  296. let suffix = ''
  297. if (u8.byteLength % 2 !== 0) {
  298. suffix = replacementChar
  299. u8 = u8.subarray(0, -unfinishedBytes(u8, u8.byteLength, enc))
  300. }
  301. return utf16toStringLoose(u8, enc === 'utf-16le' ? 'uint8-le' : 'uint8-be') + suffix
  302. }
  303. if (!Object.hasOwn(labels, enc)) throw new RangeError(E_ENCODING)
  304. if (isMultibyte(enc)) {
  305. if (!createMultibyteDecoder) throw new Error(E_MULTI)
  306. return createMultibyteDecoder(enc, true)(u8)
  307. }
  308. // https://encoding.spec.whatwg.org/#replacement-decoder
  309. // On non-streaming non-fatal case, it just replaces any non-empty input with a single replacement char
  310. if (enc === 'replacement') return input.byteLength > 0 ? replacementChar : ''
  311. return createSinglebyteDecoder(enc, true)(u8)
  312. }
  313. export function isomorphicDecode(input) {
  314. return latin1toString(fromSource(input))
  315. }
  316. export function isomorphicEncode(str) {
  317. return latin1fromString(str)
  318. }