79467192

Date: 2025-02-25 16:20:25
Score: 2
Natty:
Report link

Use the force source map

I recently ran into a similar need, and realized that I could use sourcemaps for this. This idea is heavily inspired by this seemingly unrelated question.

So, we want a clickable link that

And we know the URL and line number of said file. We also know what error to throw.

To get there, we

  1. Make up a dummy file with a single throw statement at the correct line
  2. Append a source map that actually points at our file
  3. eval the resulting code
  4. Marvel at the result in the browser console

throwError({
  // Relative URLs also work. If your file is right next to the script, just put the filename here
  url: "https://cdn.jsdelivr.net/npm/[email protected]/esm/common.js",
  // Where does the error go?
  lineNumber: 16,
  // What should it say
  error: "I am an error in setMatrixArrayType",
});

// Based on https://stackoverflow.com/questions/65274147/sourceurl-for-css
function throwError({ url, lineNumber, error }) {
  // We need a source map mapping for each line, otherwise Firefox is unhappy.
  // First line is AAAA
  // Conveniently source map mappings are *relative* to the previous one.
  // So adding more lines is trivial
  let mappings = "AAAA" + ";AACA".repeat(lineNumber);
  // And this is what our source map looks like
  const sourceMap = {
    version: 3,
    file: null,
    sources: [url],
    sourcesContent: [null],
    names: [],
    mappings: mappings,
  };

  // So we make up some Javascript code with a proper line number and error throwing
  let generatedCode =
    "\n".repeat(lineNumber - 1) +
    "throw new Error(" +
    JSON.stringify(error + "") +
    ")";
  // And redirect it to WESL
  generatedCode +=
    "\n//# sourceMappingURL=data:application/json;base64," +
    btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
  generatedCode += "\n//# sourceURL=" + sourceMap.sources[0];

  // Victory!
  eval(generatedCode);
}
<h1>Open the browser console</h1>
And then click on it.
Isn't this cool?

Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: Stefnotch