| 129 | * - `\u{#ff0000}` (hex color code) |
| 130 | */ |
| 131 | export function parseEscapeSequence<T>(parser: Parser<T>): string | undefined { |
| 132 | const start = parser.pos; |
| 133 | if (!parser.match('\\')) return undefined; // Not an escape sequence |
| 134 | |
| 135 | const char = parser.peek(); |
| 136 | if (char === undefined) { |
| 137 | parser.pos = start; // Reset position if no character to consume |
| 138 | return undefined; |
| 139 | } |
| 140 | |
| 141 | // If we have a `\` at the end of the line, we treat it as a line continuation |
| 142 | if (char === '\\' && parser.atLineEnd) return parseEscapeSequence(parser); |
| 143 | |
| 144 | const REVERSED_ESCAPED_CHARS: Record<string, string> = { |
| 145 | '0': '\0', // Not allowed in JSON |
| 146 | '\\': '\\', |
| 147 | "'": "'", |
| 148 | '"': '"', |
| 149 | 'a': '\u0007', // Bell character (from C) |
| 150 | 'b': '\b', // Backspace character |
| 151 | 'e': '\x1B', // Escape character |
| 152 | 'f': '\f', |
| 153 | 'n': '\n', |
| 154 | 'r': '\r', |
| 155 | 's': ' ', // Space character |
| 156 | 't': '\t', |
| 157 | 'v': '\v', // Vertical tab, not allowed in JSON |
| 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 | // Is it a common escape sequence? ("\b", "\n", etc...) |