Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function parseSpecifier(specifier: string): ParsedSpecifier {
const ch = specifier.charCodeAt(i);
if (ch === CHAR_EXCLAMATION) {
lastBang = i;
} else if (ch === CHAR_QUESTION || ch === CHAR_HASH) {
} else if (ch === CHAR_QUESTION || (ch === CHAR_HASH && i !== lastBang + 1)) {
suffixStart = i;
break;
}
Expand Down Expand Up @@ -139,7 +139,9 @@ export async function buildExportMap(

if (isAbsolute(resolvedPath)) {
await processLocalExport(exports, node, resolvedPath, specifier, pos, sourceFileCache);
} else {
} else if (!specifier.startsWith("#")) {
// The resolver returns a bare string for external or unresolved imports.
// Without a concrete target, a package-private key cannot be moved safely.
processExternalExport(exports, node, specifier, pos);
}
}
Expand Down Expand Up @@ -190,7 +192,7 @@ async function processLocalExport(
exportStar: !node.exportClause,
exportStarIsTypeOnly: !node.exportClause ? node.isTypeOnly : undefined,
reExportedNs: namespace,
externalSpecifier: specifier.startsWith(".") ? undefined : specifier,
externalSpecifier: specifier.startsWith(".") || specifier.startsWith("#") ? undefined : specifier,
});
}
}
Expand Down
19 changes: 8 additions & 11 deletions src/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import {
createUnsafeNamespaceDeclaration,
} from "./factory.ts";
import { printNode } from "./printer.ts";
import { buildSpecifier } from "./resolver.ts";
import { buildRewriteSpecifier } from "./resolver.ts";
import type { RewriteContext } from "./rewriter.ts";
import type { Rewrite } from "./types.ts";

export interface ExampleCandidate {
original: string;
targetMap: Map<string, Rewrite>;
filePath: string;
singleQuote: boolean;
}

export function extractImportLine(text: string): string {
Expand All @@ -38,13 +39,7 @@ export function formatExampleDiff(
const unsafeNsIdentifiers: string[] = [];

for (const [targetFilePath, rewrite] of targetMap) {
const specifier =
rewrite.externalSpecifier ??
buildSpecifier(filePath, targetFilePath, {
ext: ctx.ext,
originalSpecifier: rewrite.originalSpecifier,
aliases: ctx.aliases,
});
const specifier = buildRewriteSpecifier(filePath, targetFilePath, rewrite, ctx);

if (rewrite.unsafeNsName) {
unsafeNsName = rewrite.unsafeNsName;
Expand All @@ -54,11 +49,13 @@ export function formatExampleDiff(
}

if (rewrite.reExportedNs) {
replacements.push(printNode(createNsImportDeclaration(specifier, rewrite.reExportedNs), dummySource));
replacements.push(
printNode(createNsImportDeclaration(specifier, rewrite.reExportedNs, ctx.singleQuote), dummySource),
);
} else if (rewrite.type === "import") {
replacements.push(printNode(createImportDeclaration(rewrite, specifier), dummySource));
replacements.push(printNode(createImportDeclaration(rewrite, specifier, ctx.singleQuote), dummySource));
} else {
replacements.push(printNode(createReExportDeclaration(rewrite, specifier), dummySource));
replacements.push(printNode(createReExportDeclaration(rewrite, specifier, ctx.singleQuote), dummySource));
}
}

Expand Down
7 changes: 5 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,10 @@ async function processFiles(files: string[], ctx: Context): Promise<Result> {
}

const exampleDiff = bestExample
? formatExampleDiff(bestExample.original, bestExample.targetMap, bestExample.filePath, baseRewriteContext)
? formatExampleDiff(bestExample.original, bestExample.targetMap, bestExample.filePath, {
...baseRewriteContext,
singleQuote: bestExample.singleQuote,
})
: undefined;

return { modified, deleted, preserved, untraceableImports: ctx.tracker.untraceableImports, exampleDiff };
Expand Down Expand Up @@ -318,7 +321,7 @@ function pickBestExample(
if (targetMap.size > (current?.targetMap.size ?? 0)) {
const [start, end] = posKey.split(":").map(Number);
const original = extractImportLine(sourceFile.text.slice(start, end));
return { original, targetMap, filePath };
return { original, targetMap, filePath, singleQuote: detectSingleQuote(sourceFile) };
}
}
return current;
Expand Down
38 changes: 34 additions & 4 deletions src/resolver.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { dirname, extname, relative } from "node:path";
import { basename, dirname, extname, relative } from "node:path";
import { realpathSync } from "node:fs";
import { ResolverFactory } from "oxc-resolver";
import type { NapiResolveOptions } from "oxc-resolver";
import { getExtensionFromSpecifier, tryMapToAlias } from "./config.ts";
import type { PathAliases } from "./types.ts";
import type { PathAliases, Rewrite } from "./types.ts";
import { JS_EXT_PATTERN, RESOLVER_EXTENSIONS, TS_EXTENSIONS } from "./constants.ts";

const resolverOptions: NapiResolveOptions = {
Expand Down Expand Up @@ -86,11 +86,22 @@ export function ensureExtension(path: string, ext: string | null): string {
interface SpecifierOptions {
ext?: string | null;
originalSpecifier?: string;
packageImportSpecifier?: string;
packageTargetSpecifier?: string;
aliases?: PathAliases | null;
}

export function buildSpecifier(from: string, to: string, options: SpecifierOptions = {}): string {
const { ext, originalSpecifier, aliases } = options;
const { ext, originalSpecifier, aliases, packageImportSpecifier, packageTargetSpecifier } = options;
const packageKey = packageImportSpecifier ?? (originalSpecifier?.startsWith("#") ? originalSpecifier : undefined);
if (packageKey) {
const slash = packageKey.lastIndexOf("/");
const candidates =
slash < 0 ? [packageKey] : [packageKey, packageKey.slice(0, slash + 1) + basename(to, extname(to))];
for (const candidate of candidates) {
if (resolveModule(from, candidate, aliases ?? null) === to) return candidate;
Comment on lines +99 to +102

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reusing the barrel's own key has no test either. The suite passes when packageKey is left out of the candidates, and when packageImportSpecifier is removed in buildRewriteItem, buildUnsafeNamespaceRewrites or traceStarExports. The behavior is right in my runs: a same-package consumer of a barrel with export * from "#internal" keeps #internal. One test for that case would pin it.

}
}

if (originalSpecifier && aliases) {
const aliasSpecifier = tryMapToAlias(to, aliases, originalSpecifier);
Expand All @@ -117,7 +128,9 @@ export function buildSpecifier(from: string, to: string, options: SpecifierOptio
if (ext !== undefined) {
finalExt = ext;
} else if (originalSpecifier) {
finalExt = getExtensionFromSpecifier(originalSpecifier);
finalExt =
getExtensionFromSpecifier(originalSpecifier) ??
(packageKey ? (packageTargetSpecifier && getExtensionFromSpecifier(packageTargetSpecifier)) || null : null);
} else {
finalExt = extname(to) || null;
}
Expand All @@ -127,6 +140,23 @@ export function buildSpecifier(from: string, to: string, options: SpecifierOptio
return relPath.startsWith(".") ? relPath : `./${relPath}`;
}

export function buildRewriteSpecifier(
from: string,
to: string,
rewrite: Rewrite,
options: Pick<SpecifierOptions, "aliases" | "ext">,
): string {
const base =
rewrite.externalSpecifier ??
buildSpecifier(from, to, {
...options,
originalSpecifier: rewrite.originalSpecifier,
packageImportSpecifier: rewrite.packageImportSpecifier,
packageTargetSpecifier: rewrite.packageTargetSpecifier,
});
return (rewrite.specifierPrefix ?? "") + base + (rewrite.specifierSuffix ?? "");
}

function inferAliasSpecifier(originalSpecifier: string, targetPath: string): string | null {
const origParts = originalSpecifier.split("/");
const targetParts = targetPath.replace(JS_EXT_PATTERN, "").split("/");
Expand Down
15 changes: 6 additions & 9 deletions src/rewriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import { isBarrel } from "./main.ts";
import { organizeImports } from "./organize.ts";
import { printNode } from "./printer.ts";
import { buildSpecifier } from "./resolver.ts";
import { buildRewriteSpecifier } from "./resolver.ts";
import type {
Context,
ExportData,
Expand Down Expand Up @@ -45,6 +45,8 @@ export function buildRewriteItem(name: Name, importItem: ImportData, exportItem:
reExportedNs: exportItem.reExportedNs,
defaultName: isDefault && !isReExport ? (name.alias ?? importItem.name) : undefined,
originalSpecifier: importItem.originalSpecifier,
packageTargetSpecifier: importItem.originalSpecifier?.startsWith("#") ? exportItem.specifier : undefined,
packageImportSpecifier: exportItem.specifier.startsWith("#") ? exportItem.specifier : undefined,
specifierPrefix: importItem.specifierPrefix,
specifierSuffix: importItem.specifierSuffix,
};
Expand Down Expand Up @@ -74,14 +76,7 @@ export function applyRewrites(
const unsafeNsIdentifiers: string[] = [];

for (const [targetFilePath, rewrite] of rewriteMap) {
const baseSpecifier =
rewrite.externalSpecifier ??
buildSpecifier(filePath, targetFilePath, {
ext: ctx.ext,
originalSpecifier: rewrite.originalSpecifier,
aliases: ctx.aliases,
});
const specifier = (rewrite.specifierPrefix ?? "") + baseSpecifier + (rewrite.specifierSuffix ?? "");
const specifier = buildRewriteSpecifier(filePath, targetFilePath, rewrite, ctx);

if (rewrite.unsafeNsName) {
unsafeNsName = rewrite.unsafeNsName;
Expand Down Expand Up @@ -353,6 +348,7 @@ async function buildUnsafeNamespaceRewrites(
members: [],
unsafeNsName: item.name,
originalSpecifier: item.originalSpecifier,
packageImportSpecifier: exportData.specifier.startsWith("#") ? exportData.specifier : undefined,
specifierPrefix: item.specifierPrefix,
specifierSuffix: item.specifierSuffix,
});
Expand Down Expand Up @@ -445,6 +441,7 @@ async function traceStarExports(
members: [],
isTypeOnly,
originalSpecifier: item.originalSpecifier,
packageImportSpecifier: exportData.specifier.startsWith("#") ? exportData.specifier : undefined,
specifierPrefix: item.specifierPrefix,
specifierSuffix: item.specifierSuffix,
});
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ export interface Rewrite {
defaultName?: string;
isTypeOnly?: boolean;
originalSpecifier?: string;
packageImportSpecifier?: string;
packageTargetSpecifier?: string;
specifierPrefix?: string;
specifierSuffix?: string;
unsafeNsName?: string; // For --unsafe-namespace: the namespace identifier name
Expand Down
Loading
Loading