transformHookSource

tcmts.cli.codebase.transformHookSource · #mxpelwxj · term · runs anywhere

The same hook as a module of its own, for the processes tcm spawns (node --import ./tcm-transform.js).

import { TRANSFORM_MARK } from "#codebase/tcmts/cli/codebase";

export function transformHookSource(transpile: { url: string; export: string }): string {
  return `// generated by tcm — do not edit: compiles cache modules that use syntax Node's type stripping can't run
import { registerHooks } from "node:module";
import { readFileSync } from "node:fs";
import { ${transpile.export} as transpileModule } from ${JSON.stringify(transpile.url)};
const transpileForNode = transpileModule().transpile;
registerHooks({
  load(url, context, nextLoad) {
    if (url.startsWith("file:") && (url.endsWith(".ts") || url.endsWith(".tsx"))) {
      const source = readFileSync(new URL(url), "utf8");
      if (source.startsWith(${JSON.stringify(TRANSFORM_MARK)})) return { format: "module", source: transpileForNode(source, url), shortCircuit: true };
    }
    return nextLoad(url, context);
  },
});
`;
}

uses

used by