function isSerializedFunction(value) {
  return value instanceof MessagePort;
}
function serializeFunction(func) {
  const messageChannel = new MessageChannel();
  messageChannel.port1.onmessage = ({ data: [callId, args] }) => {
    Promise.resolve().then(() => func.apply(null, args)).then((result) => messageChannel.port1.postMessage([callId, result]));
  };
  return messageChannel.port2;
}
function onmessageHandler() {
  let nextCallId = 0;
  const calls = /* @__PURE__ */ new Map();
  const result = ({ data: [callId, result2] }) => {
    calls.get(callId)?.(result2);
    calls.delete(callId);
  };
  result.newCall = (resolve) => {
    const callId = nextCallId++;
    calls.set(callId, resolve);
    return callId;
  };
  return result;
}
function deserializeFunction(serializedFunction) {
  if (serializedFunction.onmessage == null) {
    serializedFunction.onmessage = onmessageHandler();
  }
  return function deserializedFunction(...args) {
    return new Promise((resolve) => {
      const { newCall } = serializedFunction.onmessage;
      if (newCall == null) {
        throw new Error(
          `Deserialized function call failed: 'onmessage' handler is missing 'newCall' method`
        );
      }
      const callId = newCall(resolve);
      serializedFunction.postMessage([callId, args]);
    });
  };
}
const functionDeserializationPlugin = {
  match: isSerializedFunction,
  deserialize: (value) => deserializeFunction(value)
};
export {
  deserializeFunction,
  functionDeserializationPlugin,
  isSerializedFunction,
  serializeFunction
};
//# sourceMappingURL=function-serialization.js.map