"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidPostMessage = isValidPostMessage;
exports.requestActionPostMessage = requestActionPostMessage;
exports.listenPostMessageEvents = listenPostMessageEvents;
exports.usePostMessageAPIListener = usePostMessageAPIListener;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const constants_1 = require("./constants.js");
function isValidPostMessage(data) {
    return (typeof data === 'object' &&
        data !== null &&
        data.source === constants_1.POST_MESSAGE_SOURCE);
}
function requestActionPostMessage(action, data, destinationElement) {
    const message = { action, data, source: constants_1.POST_MESSAGE_SOURCE };
    destinationElement.postMessage(message, '*');
}
function listenPostMessageEvents(action, callback) {
    const onMessage = (e) => {
        if (!isValidPostMessage(e.data)) {
            return undefined;
        }
        const message = e.data;
        if (message.action === action) {
            return callback(message.data);
        }
        return undefined;
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
}
function usePostMessageAPIListener(action, callback, deps = []) {
    React.useEffect(() => {
        return listenPostMessageEvents(action, callback);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [...deps]);
}
//# sourceMappingURL=postMessage.js.map
