How to create header anchor links in a script?

Question: How can a script identify and place header anchor links? They appear to be not included in the markdown of the field.

There are multiple reasons why this would be useful.
One of the reasons is:

I’m working on a Table Of Contents script, because:

  1. the current TOC feature we never use: people overlook it,
  2. and it can’t be configured what to include and what not.
  3. a TOC is most often an integral part of a text to be printed or shared, currently its invisible.
  4. There are multiple feature requests to improve the current TOC.

If you retrieve the doc content as JSON (instead of markdown) you will find that paragraphs have attributes, including the ‘level’ and a guid.
The level will tell you if it’s a header. and anchors are formed by adding the guid property to the base url.