Due to the "business judgement" rule, the management of a for-profit company gets to do business just about any way they want without any legal constraint; all they need is some reasonable rationale for why it might somehow, in the long term, benefit shareholders.
This includes giving stuff away and selling stuff for a loss, as many unicorns do. It includes paying employees very well, as some companies do. It includes making donations to charity. It includes either sticking to their original business, or deciding to spend a lot of money breaking into a new business.
In practice, shareholder primacy happens less because of what's legally required and more because many companies have management and employees who are shareholders. If the company stock goes up, the employees do well, and this promotes a culture where people try to make the stock go up.