oneImportEach

tcmts.cli.merge.oneImportEach · #ectvlgjv · term · runs anywhere

Two sides' import lines, each name imported once: where they import one name from two modules (one definition named twice: each side's code says it by the name it had there), or once as a type and once as a value, one stays (the value's, else the first). same says whether two names are of one definition; where they aren't, both stay, for the file's check to say so.

import { joinName } from "#codebase/tcmts/cli/mirror";

export function oneImportEach(lines: string[], same: (a: string, b: string) => boolean): string[] {
  const shape = /^import (type )?\{ ([\w$]+)(?: as ([\w$]+))? \} from "#codebase(?:\/([^"]*))?";$/;
  const kept = new Map<string, { line: string; type: boolean; name: string }>();
  const rest: string[] = [];
  for (const line of lines) {
    const m = shape.exec(line);
    if (!m) {
      rest.push(line);
      continue;
    }
    const local = m[3] ?? m[2]!;
    const name = joinName((m[4] ?? "").split("/").join("."), m[2]!);
    const type = !!m[1];
    const had = kept.get(local);
    if (!had) kept.set(local, { line, type, name });
    else if (!same(had.name, name)) rest.push(line);
    else if (had.type && !type) kept.set(local, { line, type, name });
  }
  return [...rest, ...[...kept.values()].map((k) => k.line)];
}

uses

used by