( resolvedPath: string, )
| 18 | export type LineEndingType = 'CRLF' | 'LF' |
| 19 | |
| 20 | export function detectEncodingForResolvedPath( |
| 21 | resolvedPath: string, |
| 22 | ): BufferEncoding { |
| 23 | const { buffer, bytesRead } = getFsImplementation().readSync(resolvedPath, { |
| 24 | length: 4096, |
| 25 | }) |
| 26 | |
| 27 | // Empty files should default to utf8, not ascii |
| 28 | // This fixes a bug where writing emojis/CJK to empty files caused corruption |
| 29 | if (bytesRead === 0) { |
| 30 | return 'utf8' |
| 31 | } |
| 32 | |
| 33 | if (bytesRead >= 2) { |
| 34 | if (buffer[0] === 0xff && buffer[1] === 0xfe) return 'utf16le' |
| 35 | } |
| 36 | |
| 37 | if ( |
| 38 | bytesRead >= 3 && |
| 39 | buffer[0] === 0xef && |
| 40 | buffer[1] === 0xbb && |
| 41 | buffer[2] === 0xbf |
| 42 | ) { |
| 43 | return 'utf8' |
| 44 | } |
| 45 | |
| 46 | // For non-empty files, default to utf8 since it's a superset of ascii |
| 47 | // and handles all Unicode characters properly |
| 48 | return 'utf8' |
| 49 | } |
| 50 | |
| 51 | export function detectLineEndingsForString(content: string): LineEndingType { |
| 52 | let crlfCount = 0 |
no test coverage detected