"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJsonPrimitive = isJsonPrimitive;
exports.jsonParse = jsonParse;
/**
 * @fileoverview JSON parsing utilities with Buffer detection and BOM stripping.
 * Provides safe JSON parsing with automatic encoding handling.
 */
const strings_1 = require("./strings");
// IMPORTANT: Do not use destructuring here - use direct assignment instead.
// tsgo has a bug that incorrectly transpiles destructured exports, resulting in
// `exports.SomeName = void 0;` which causes runtime errors.
// See: https://github.com/SocketDev/socket-packageurl-js/issues/3
const JSONParse = JSON.parse;
/**
 * Check if a value is a Buffer instance.
 */
/*@__NO_SIDE_EFFECTS__*/
function isBuffer(x) {
    const obj = x;
    if (!obj || typeof obj !== 'object' || typeof obj.length !== 'number') {
        return false;
    }
    if (typeof obj.copy !== 'function' || typeof obj.slice !== 'function') {
        return false;
    }
    if (obj.length > 0 && typeof obj[0] !== 'number') {
        return false;
    }
    const Ctor = obj.constructor;
    return !!(typeof Ctor?.isBuffer === 'function' && Ctor.isBuffer(obj));
}
/**
 * Check if a value is a JSON primitive (null, boolean, number, or string).
 */
/*@__NO_SIDE_EFFECTS__*/
function isJsonPrimitive(value) {
    return (value === null ||
        typeof value === 'boolean' ||
        typeof value === 'number' ||
        typeof value === 'string');
}
/**
 * Parse JSON content with error handling and BOM stripping.
 */
/*@__NO_SIDE_EFFECTS__*/
function jsonParse(content, options) {
    const { filepath, reviver, throws } = {
        __proto__: null,
        ...options,
    };
    const shouldThrow = throws === undefined || !!throws;
    const jsonStr = isBuffer(content) ? content.toString('utf8') : content;
    try {
        return JSONParse((0, strings_1.stripBom)(jsonStr), reviver);
    }
    catch (e) {
        if (shouldThrow) {
            const error = e;
            if (error && typeof filepath === 'string') {
                error.message = `${filepath}: ${error.message}`;
            }
            throw error;
        }
    }
    return undefined;
}
