Skip to content

Commit 388c1ae

Browse files
author
OkaYu
committed
fix(fs): change to reject if unsupported encodings in readTextFileLines
1 parent e97a4de commit 388c1ae

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"fs": pach
3+
"fs-js": pach
4+
---
5+
6+
Change to reject if unsupported encodings in readTextFileLines

plugins/fs/guest-js/index.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -782,6 +782,28 @@ async function readTextFile(
782782
return new TextDecoder(options?.encoding ?? 'utf-8').decode(bytes)
783783
}
784784

785+
/**
786+
* Asserts that the given encoding is ASCII-compatible for LF (0x0A) and CR (0x0D).
787+
*
788+
* @throws if the encoding is UTF-16, "replacement", or otherwise invalid.
789+
*/
790+
function assertLfCrAsciiCompatibleEncoding(encodingLabel?: string): void {
791+
// Normalize the encoding label.
792+
// If it is invalid, a RangeError is thrown here.
793+
const encoding = (new TextDecoder(encodingLabel)).encoding
794+
795+
// Reject encodings defined in the Web Encoding Standard
796+
// that do not represent LF and CR as 0x0A and 0x0D.
797+
// https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings
798+
if (
799+
encoding === "utf-16le" ||
800+
encoding === "utf-16be" ||
801+
encoding === "replacement"
802+
) {
803+
throw new Error(`Unsupported encoding label: ${encodingLabel}`)
804+
}
805+
}
806+
785807
/**
786808
* Returns an async {@linkcode AsyncIterableIterator} over the lines of a file, decoded using the specified encoding (default: UTF-8).
787809
* @example
@@ -804,6 +826,10 @@ async function readTextFileLines(
804826
if (path instanceof URL && path.protocol !== 'file:') {
805827
throw new TypeError('Must be a file URL.')
806828
}
829+
if (options?.encoding != null) {
830+
// https://github.com/tauri-apps/plugins-workspace/pull/3244#issuecomment-3869568792
831+
assertLfCrAsciiCompatibleEncoding(options.encoding)
832+
}
807833

808834
const pathStr = path instanceof URL ? path.toString() : path
809835

0 commit comments

Comments
 (0)