thrownIn

tcmts.cli.main.thrownIn · #ijehkqjp · term · runs on the server

uses node:fs

The definition an error was thrown in, by hash: of its stack's frames, the first in the codebase's own code (a definition's view or generated module, in .tcm). A page's frames count too where they name the module (tcm dev serves each at /@fs/…/.tcm/cache/<hash>.ts), and a production build's chunks through their source maps (assetSource). Undefined if none does.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { assetSource, definitionsAt, stackFrames } from "#codebase/tcmts/cli/main";
import fs from "node:fs";
import path from "node:path";

export function thrownIn(cb: Codebase, stack: string | undefined): string | undefined {
  if (!stack) return undefined;
  const roots = [
    cb.lay.tcmDir,
    fs.existsSync(cb.lay.tcmDir) ? fs.realpathSync(cb.lay.tcmDir) : cb.lay.tcmDir,
  ].map((d) => d + path.sep);
  for (const frame of stackFrames(stack)) {
    const { file, line } = frame.asset
      ? (assetSource(cb, frame.asset, frame.line, frame.column) ?? { file: "", line: 0 })
      : { file: frame.file!, line: frame.line };
    if (!roots.some((r) => file.startsWith(r))) continue;
    try {
      const at = definitionsAt(cb, file, line).find((d) => d.hash);
      if (at) return at.hash;
    } catch {
      // (a view of another branch's, or a file gone since: the next frame)
    }
  }
  return undefined;
}

uses

used by