blob: 350fd51cfcb70c1d8fb1680d19d7dce80dc02e2b [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var GetIntrinsic = require('get-intrinsic');
4
5var $TypeError = GetIntrinsic('%TypeError%');
6
7var callBound = require('call-bind/callBound');
8var forEach = require('../helpers/forEach');
9var isLeadingSurrogate = require('../helpers/isLeadingSurrogate');
10var isTrailingSurrogate = require('../helpers/isTrailingSurrogate');
11
12var $charCodeAt = callBound('String.prototype.charCodeAt');
13var $strSplit = callBound('String.prototype.split');
14
15var Type = require('./Type');
16var UnicodeEscape = require('./UnicodeEscape');
17var UTF16Encoding = require('./UTF16Encoding');
18
19var has = require('has');
20
21// https://262.ecma-international.org/10.0/#sec-quotejsonstring
22
23var escapes = {
24 '\u0008': '\\b',
25 '\u0009': '\\t',
26 '\u000A': '\\n',
27 '\u000C': '\\f',
28 '\u000D': '\\r',
29 '\u0022': '\\"',
30 '\u005c': '\\\\'
31};
32
33module.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};