import { useMemo, useRef } from "react";
function useResolvableRecord(resolvables) {
  const snapshot = useRef({ resolvedValues: {}, dirtyProps: /* @__PURE__ */ new Set() });
  return useMemo(() => {
    return {
      name: "resolvable-record",
      subscribe: (onUpdate) => {
        const unsubscribes = Object.values(resolvables).map((s) => s.subscribe(onUpdate));
        return () => {
          unsubscribes.forEach((u) => u());
        };
      },
      readStable: () => {
        const nextSnapshot = Object.entries(resolvables).reduce(
          ({ dirtyProps, resolvedValues }, [propName, subscription]) => {
            const lastPropValue = snapshot.current.resolvedValues[propName];
            const propValue = subscription.readStable();
            const isDirty = propValue !== lastPropValue;
            return {
              dirtyProps: isDirty ? dirtyProps.add(propName) : dirtyProps,
              resolvedValues: { ...resolvedValues, [propName]: propValue }
            };
          },
          { resolvedValues: {}, dirtyProps: /* @__PURE__ */ new Set() }
        );
        if (nextSnapshot.dirtyProps.size > 0) {
          snapshot.current = nextSnapshot;
        }
        return snapshot.current.resolvedValues;
      },
      triggerResolve: async () => {
        return await Promise.all(
          Object.entries(resolvables).map(
            ([propName, sub]) => sub.triggerResolve(snapshot.current.resolvedValues[propName])
          )
        );
      }
    };
  }, [resolvables]);
}
export {
  useResolvableRecord
};
//# sourceMappingURL=use-resolvable-record.js.map