_plainKind.mjs

//載入時取得之內建(呼叫端其後改寫全域之Object、Function.prototype.toString不影響判定)
let getProto = Object.getPrototypeOf
let getOwnDesc = Object.getOwnPropertyDescriptor
let hasOwn = Object.prototype.hasOwnProperty
let objProto = Object.prototype
let fnToString = Function.prototype.toString
let objSrc = fnToString.call(Object)


/**
 * 一般物件之判型,內部共用不對外(isPlainObj與getOptReader之單一判定;dspec〈輸入參數之檢測機制〉表O1、§4 V4)
 *
 * 一般物件: typeof為'object'且非null,原型為Object.prototype或null,或原型為他realm(vm新context、iframe)之原生Object原型(原型之原型為null,且其自有之constructor為資料屬性、為原生之Object函數)
 * 判定只看原型,不讀Symbol.toStringTag(偽稱他種類之標籤不影響),不寫入受檢物;故陣列、函數、Date、Map、類別實例為'other',arguments物件與模組命名空間物件(原型為Object.prototype或null)為'plain'
 * Proxy依其getPrototypeOf陷阱之結果判定(只觸發getPrototypeOf,他realm原型者另觸發該原型之getPrototypeOf與getOwnPropertyDescriptor,不觸發get陷阱、不呼叫存取器)
 *
 * @param {*} v 輸入任意值
 * @returns {String} 回傳'plain'(一般物件)、'other'(非一般物件,含原始值、函數)或'error'(判型時拋錯,如已撤銷之Proxy、getPrototypeOf陷阱拋錯);本函數不拋錯
 */
function plainKind(v) {
    if (typeof v !== 'object' || v === null) {
        return 'other'
    }
    try {
        let p = getProto(v)
        if (p === null || p === objProto) {
            return 'plain'
        }
        if (getProto(p) !== null) {
            return 'other'
        }
        let d = getOwnDesc(p, 'constructor')
        if (d === undefined || !hasOwn.call(d, 'value')) {
            return 'other' //無自有constructor或其為存取器(不呼叫存取器)
        }
        let c = d.value
        if (typeof c !== 'function') {
            return 'other'
        }
        return fnToString.call(c) === objSrc ? 'plain' : 'other'
    }
    catch (err) {
        return 'error'
    }
}


export default plainKind