Skip to content

Commit

Permalink
fix(interopDefault): skip nullish values for default and explicitly…
Browse files Browse the repository at this point in the history
… return non-objects as-is

related to #194
  • Loading branch information
pi0 committed Jan 11, 2024
1 parent 0d6b0b2 commit 14eb72d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
20 changes: 13 additions & 7 deletions src/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,30 @@ export function interopDefault(sourceModule: any): any {
if (!isObject(sourceModule) || !("default" in sourceModule)) {
return sourceModule;
}
const newModule = sourceModule.default;
const defaultValue = sourceModule.default;
if (defaultValue === undefined || defaultValue === null) {
return sourceModule;
}
if (typeof defaultValue !== "object") {
return defaultValue;
}
for (const key in sourceModule) {
if (key === "default") {
try {
if (!(key in newModule)) {
Object.defineProperty(newModule, key, {
if (!(key in defaultValue)) {
Object.defineProperty(defaultValue, key, {
enumerable: false,
configurable: false,
get() {
return newModule;
return defaultValue;
},
});
}
} catch {}
} else {
try {
if (!(key in newModule)) {
Object.defineProperty(newModule, key, {
if (!(key in defaultValue)) {
Object.defineProperty(defaultValue, key, {
enumerable: true,
configurable: true,
get() {
Expand All @@ -63,5 +69,5 @@ export function interopDefault(sourceModule: any): any {
} catch {}
}
}
return newModule;
return defaultValue;
}
12 changes: 11 additions & 1 deletion test/interop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ const tests = [
{ named: 1, default: { x: 2 } },
{ named: 1, x: 2 },
],
[
{ default: null, x: 1 }, // eslint-disable-line unicorn/no-null
{ default: null, x: 1 }, // eslint-disable-line unicorn/no-null
],
[
{ default: undefined, x: 1 },
{ default: undefined, x: 1 },
],
];

describe("interopDefault", () => {
Expand All @@ -24,7 +32,9 @@ describe("interopDefault", () => {
const interop = interopDefault(input);
expect(interop).to.deep.equal(result);
if (typeof input === "object" && "default" in input) {
expect(interop.default).to.deep.equal(result);
expect(interop.default).to.deep.equal(
"default" in (result as any) ? (result as any).default : result,
);
} else {
expect(interop).to.deep.equal(result);
}
Expand Down

0 comments on commit 14eb72d

Please sign in to comment.