All files index.ts

88.65% Statements 125/141
85.98% Branches 92/107
100% Functions 10/10
91.4% Lines 117/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218                                44x     44x     44x     2x 44x 44x   44x 21x     44x 11x     44x 86x 86x 78x 63x 51x 33x 1x 1x   32x 1x 1x   31x 1x 1x   30x 1x 1x   29x 1x 1x   28x 1x 1x     27x 27x 17x     10x     44x 33x 33x 33x 33x 40x 40x   33x 20x 20x       13x 10x 10x     4x     3x     44x 12x 12x 12x 12x 12x 19x 19x 18x 15x 15x 15x 15x 10x     5x 1x   4x 3x   10x 10x       7x 1x   6x 6x   3x 3x     44x 18x 18x 18x 18x 18x 27x 17x 17x 9x 9x         10x 4x   6x 2x   4x   8x 8x     44x 17x 6x 6x 6x   3x 3x 3x   1x       11x   11x 15x   11x   11x 11x                                     44x 186x 62x     44x     2x      
import { Allow } from "./options";
export * from "./options";
 
class PartialJSON extends Error {}
 
class MalformedJSON extends Error {}
 
/**
 * Parse incomplete JSON
 * @param {string} jsonString Partial JSON to be parsed
 * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details
 * @returns The parsed JSON
 * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter)
 * @throws {MalformedJSON} If the JSON is malformed
 */
function parseJSON(jsonString: string, allowPartial: number = Allow.ALL): any {
    Iif (typeof jsonString !== "string") {
        throw new TypeError(`expecting str, got ${typeof jsonString}`);
    }
    Iif (!jsonString.trim()) {
        throw new Error(`${jsonString} is empty`);
    }
    return _parseJSON(jsonString.trim(), allowPartial);
}
 
const _parseJSON = (jsonString: string, allow: number) => {
    const length = jsonString.length;
    let index = 0;
 
    const markPartialJSON = (msg: string) => {
        throw new PartialJSON(`${msg} at position ${index}`);
    };
 
    const throwMalformedError = (msg: string) => {
        throw new MalformedJSON(`${msg} at position ${index}`);
    };
 
    const parseAny: () => any = () => {
        skipBlank();
        if (index >= length) markPartialJSON("Unexpected end of input");
        if (jsonString[index] === '"') return parseStr();
        if (jsonString[index] === "{") return parseObj();
        if (jsonString[index] === "[") return parseArr();
        if (jsonString.substring(index, index + 4) === "null" || (Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index)))) {
            index += 4;
            return null;
        }
        if (jsonString.substring(index, index + 4) === "true" || (Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index)))) {
            index += 4;
            return true;
        }
        if (jsonString.substring(index, index + 5) === "false" || (Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index)))) {
            index += 5;
            return false;
        }
        if (jsonString.substring(index, index + 8) === "Infinity" || (Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index)))) {
            index += 8;
            return Infinity;
        }
        if (jsonString.substring(index, index + 9) === "-Infinity" || (Allow._INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index)))) {
            index += 9;
            return -Infinity;
        }
        if (jsonString.substring(index, index + 3) === "NaN" || (Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index)))) {
            index += 3;
            return NaN;
        }
        // Check if we have a valid number character before calling parseNum
        const char = jsonString[index];
        if (char === "-" || (char >= "0" && char <= "9")) {
            return parseNum();
        }
        // If we get here, it's an invalid token
        throwMalformedError(`Unexpected token '${char}'`);
    };
 
    const parseStr: () => string = () => {
        const start = index;
        let escape = false;
        index++; // skip initial quote
        while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === "\\"))) {
            escape = jsonString[index] === "\\" ? !escape : false;
            index++;
        }
        if (jsonString.charAt(index) == '"') {
            try {
                return JSON.parse(jsonString.substring(start, ++index - Number(escape)));
            } catch (e) {
                throwMalformedError(String(e));
            }
        } else if (Allow.STR & allow) {
            try {
                return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"');
            } catch (e) {
                // SyntaxError: Invalid escape sequence
                return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
            }
        }
        markPartialJSON("Unterminated string literal");
    };
 
    const parseObj = () => {
        index++; // skip initial brace
        skipBlank();
        const obj: Record<string, any> = {};
        try {
            while (jsonString[index] !== "}") {
                skipBlank();
                if (index >= length && Allow.OBJ & allow) return obj;
                const key = parseStr();
                skipBlank();
                index++; // skip colon
                try {
                    const value = parseAny();
                    obj[key] = value;
                } catch (e) {
                    // If it's a malformed JSON error, let it bubble up
                    if (e instanceof MalformedJSON) {
                        throw e;
                    }
                    if (Allow.OBJ & allow) return obj;
                    else throw e;
                }
                skipBlank();
                if (jsonString[index] === ",") index++; // skip comma
            }
        } catch (e) {
            // If it's a malformed JSON error, let it bubble up
            if (e instanceof MalformedJSON) {
                throw e;
            }
            Iif (Allow.OBJ & allow) return obj;
            else markPartialJSON("Expected '}' at end of object");
        }
        index++; // skip final brace
        return obj;
    };
 
    const parseArr = () => {
        index++; // skip initial bracket
        skipBlank(); // skip whitespace at start of array
        const arr = [];
        try {
            while (jsonString[index] !== "]") {
                arr.push(parseAny());
                skipBlank();
                if (jsonString[index] === ",") {
                    index++; // skip comma
                    skipBlank(); // skip whitespace after comma
                }
            }
        } catch (e) {
            // If it's a malformed JSON error, let it bubble up
            if (e instanceof MalformedJSON) {
                throw e;
            }
            if (Allow.ARR & allow) {
                return arr;
            }
            markPartialJSON("Expected ']' at end of array");
        }
        index++; // skip final bracket
        return arr;
    };
 
    const parseNum = () => {
        if (index === 0) {
            Iif (jsonString === "-") throwMalformedError("Not sure what '-' is");
            try {
                return JSON.parse(jsonString);
            } catch (e) {
                Eif (Allow.NUM & allow)
                    try {
                        return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
                    } catch (e) {}
                throwMalformedError(String(e));
            }
        }
 
        const start = index;
 
        Iif (jsonString[index] === "-") index++;
        while (jsonString[index] && ",]}".indexOf(jsonString[index]) === -1) index++;
 
        Iif (index == length && !(Allow.NUM & allow)) markPartialJSON("Unterminated number literal");
 
        try {
            return JSON.parse(jsonString.substring(start, index));
        } catch (e) {
            if (jsonString.substring(start, index) === "-") markPartialJSON("Not sure what '-' is");
            // If the number is partial and we allow partial numbers, try to parse up to last 'e'
            if (Allow.NUM & allow) {
                const numberStr = jsonString.substring(start, index);
                const lastE = numberStr.lastIndexOf("e");
                if (lastE > 0) {
                    try {
                        return JSON.parse(numberStr.substring(0, lastE));
                    } catch (e2) {
                        // Still invalid, fall through to error
                    }
                }
            }
            throwMalformedError(String(e));
        }
    };
 
    const skipBlank = () => {
        while (index < length && " \n\r\t".includes(jsonString[index])) {
            index++;
        }
    };
    return parseAny();
};
 
const parse = parseJSON;
 
export { parse, parseJSON, PartialJSON, MalformedJSON, Allow };