"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var function_serialization_exports = {};
__export(function_serialization_exports, {
  deserializeFunction: () => deserializeFunction,
  functionDeserializationPlugin: () => functionDeserializationPlugin,
  isSerializedFunction: () => isSerializedFunction,
  serializeFunction: () => serializeFunction
});
module.exports = __toCommonJS(function_serialization_exports);
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)
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  deserializeFunction,
  functionDeserializationPlugin,
  isSerializedFunction,
  serializeFunction
});
//# sourceMappingURL=function-serialization.js.map