| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | var GetIntrinsic = require('get-intrinsic'); |
| 4 | |
| 5 | var $TypeError = GetIntrinsic('%TypeError%'); |
| 6 | |
| 7 | var callBound = require('call-bind/callBound'); |
| 8 | var forEach = require('../helpers/forEach'); |
| 9 | var isLeadingSurrogate = require('../helpers/isLeadingSurrogate'); |
| 10 | var isTrailingSurrogate = require('../helpers/isTrailingSurrogate'); |
| 11 | |
| 12 | var $charCodeAt = callBound('String.prototype.charCodeAt'); |
| 13 | var $strSplit = callBound('String.prototype.split'); |
| 14 | |
| 15 | var Type = require('./Type'); |
| 16 | var UnicodeEscape = require('./UnicodeEscape'); |
| 17 | var UTF16Encoding = require('./UTF16Encoding'); |
| 18 | |
| 19 | var has = require('has'); |
| 20 | |
| 21 | // https://262.ecma-international.org/10.0/#sec-quotejsonstring |
| 22 | |
| 23 | var escapes = { |
| 24 | '\u0008': '\\b', |
| 25 | '\u0009': '\\t', |
| 26 | '\u000A': '\\n', |
| 27 | '\u000C': '\\f', |
| 28 | '\u000D': '\\r', |
| 29 | '\u0022': '\\"', |
| 30 | '\u005c': '\\\\' |
| 31 | }; |
| 32 | |
| 33 | module.exports = function QuoteJSONString(value) { |
| 34 | if (Type(value) !== 'String') { |
| 35 | throw new $TypeError('Assertion failed: `value` must be a String'); |
| 36 | } |
| 37 | var product = '"'; |
| 38 | if (value) { |
| 39 | forEach($strSplit(value), function (C) { |
| 40 | if (has(escapes, C)) { |
| 41 | product += escapes[C]; |
| 42 | } else { |
| 43 | var cCharCode = $charCodeAt(C, 0); |
| 44 | if (cCharCode < 0x20 || isLeadingSurrogate(C) || isTrailingSurrogate(C)) { |
| 45 | product += UnicodeEscape(C); |
| 46 | } else { |
| 47 | product += UTF16Encoding(cCharCode); |
| 48 | } |
| 49 | } |
| 50 | }); |
| 51 | } |
| 52 | product += '"'; |
| 53 | return product; |
| 54 | }; |