Skip to content
Open
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
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
"pretty-bytes": "^7.1.0",
"rolldown": "^1.0.0-rc.13",
"rolldown-plugin-dts": "^0.23.2",
"rollup-plugin-license": "^3.7.0",
"tinyglobby": "^0.2.15"
},
"devDependencies": {
Expand Down
570 changes: 229 additions & 341 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

278 changes: 174 additions & 104 deletions src/builders/plugins/license.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,122 +6,192 @@
* MIT Licensed: https://github.com/rollup/rollup/blob/master/LICENSE-CORE.md
*/

import { appendFile, mkdir, writeFile } from "node:fs/promises";
import license from "rollup-plugin-license";

import type { Dependency } from "rollup-plugin-license";
import type { Plugin, PluginContext } from "rolldown";
import { dirname } from "node:path";
import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import type { Plugin, PluginContext } from "rolldown";

export default function licensePlugin(opts: { output: string }): Plugin {
const originalPlugin = (license as unknown as typeof license.default)({
async thirdParty(dependencies: Dependency[]) {
const deps = sortDependencies([...dependencies]);
const licenses = sortLicenses(
new Set(dependencies.map((dep: Dependency) => dep.license).filter(Boolean) as string[]),
);

let dependencyLicenseTexts = "";
for (let i = 0; i < deps.length; i++) {
// Find dependencies with the same license text so it can be shared
const licenseText = deps[i].licenseText;
const sameDeps = [deps[i]];
if (licenseText) {
for (let j = i + 1; j < deps.length; j++) {
if (licenseText === deps[j].licenseText) {
sameDeps.push(...deps.splice(j, 1));
j--;
}
}
}
interface Person {
name?: string;
email?: string;
url?: string;
}

let text = `## ${sameDeps.map((d) => d.name || "unknown").join(", ")}\n\n`;
const depInfos = sameDeps.map((d) => getDependencyInformation(d));

// If all same dependencies have the same license and contributor names, show them only once
if (
depInfos.length > 1 &&
depInfos.every(
(info) => info.license === depInfos[0].license && info.names === depInfos[0].names,
)
) {
const { license, names } = depInfos[0];
const repositoryText = depInfos
.map((info) => info.repository)
.filter(Boolean)
.join(", ");

if (license) text += `License: ${license}\n`;
if (names) text += `By: ${names}\n`;
if (repositoryText) text += `Repositories: ${repositoryText}\n`;
}
// Else show each dependency separately
else {
for (let j = 0; j < depInfos.length; j++) {
const { license, names, repository } = depInfos[j];

if (license) text += `License: ${license}\n`;
if (names) text += `By: ${names}\n`;
if (repository) text += `Repository: ${repository}\n`;
if (j !== depInfos.length - 1) text += "\n";
}
}
interface Dependency {
name?: string;
version?: string;
license?: string;
licenseText?: string;
author?: string | Person;
maintainers: (string | Person)[];
contributors: (string | Person)[];
repository?: string | { type?: string; url: string };
}

if (licenseText) {
text +=
"\n" +
licenseText
.trim()
.replace(/\r\n|\r/g, "\n")
.split("\n")
.map((line: string) => `> ${line}`)
.join("\n") +
"\n";
}
async function collectDependencies(moduleIds: Iterable<string>): Promise<Dependency[]> {
const seen = new Set<string>();
const deps: Dependency[] = [];

if (i !== deps.length - 1) {
text += "\n---------------------------------------\n\n";
}
for (const id of moduleIds) {
const normalizedId = id.replaceAll("\\", "/");
const nodeModulesIdx = normalizedId.lastIndexOf("/node_modules/");
if (nodeModulesIdx === -1) continue;

const afterNodeModules = normalizedId.slice(nodeModulesIdx + "/node_modules/".length);
// Handle scoped packages (@scope/name)
const parts = afterNodeModules.split("/");
const pkgName = parts[0].startsWith("@") ? [parts[0], parts[1]].join("/") : parts[0];

dependencyLicenseTexts += text;
const nodeModulesDir = id.slice(0, nodeModulesIdx + "/node_modules/".length);
const pkgDir = join(nodeModulesDir, pkgName);
if (seen.has(pkgDir)) continue;
seen.add(pkgDir);
const pkgJsonPath = join(pkgDir, "package.json");

try {
const pkgJson = JSON.parse(await readFile(pkgJsonPath, "utf8"));
const dep: Dependency = {
name: pkgJson.name,
version: pkgJson.version,
license: pkgJson.license,
author: pkgJson.author,
maintainers: pkgJson.maintainers || [],
contributors: pkgJson.contributors || [],
repository: pkgJson.repository,
};

// Try to find LICENSE file
for (const licenseFile of [
"LICENSE",
"LICENSE.md",
"LICENSE.txt",
"LICENCE",
"LICENCE.md",
"LICENCE.txt",
"license",
"license.md",
"license.txt",
]) {
const licensePath = join(pkgDir, licenseFile);
if (existsSync(licensePath)) {
dep.licenseText = await readFile(licensePath, "utf8");
break;
}
}

if (!dependencyLicenseTexts) {
return;
deps.push(dep);
} catch {
// Skip packages without a valid package.json
}
}

return deps;
}

export default function licensePlugin(opts: { output: string }): Plugin {
return {
name: "obuild:license",
async generateBundle(this: PluginContext) {
if (this.meta.watchMode) return;

const dependencies = await collectDependencies(this.getModuleIds());
await generateLicenseFile(dependencies, opts.output);
},
};
}

async function generateLicenseFile(dependencies: Dependency[], output: string): Promise<void> {
const deps = sortDependencies([...dependencies]);
const licenses = sortLicenses(
new Set(dependencies.map((dep: Dependency) => dep.license).filter(Boolean) as string[]),
);

let dependencyLicenseTexts = "";
for (let i = 0; i < deps.length; i++) {
// Find dependencies with the same license text so it can be shared
const licenseText = deps[i].licenseText;
const sameDeps = [deps[i]];
if (licenseText) {
for (let j = i + 1; j < deps.length; j++) {
if (licenseText === deps[j].licenseText) {
sameDeps.push(...deps.splice(j, 1));
j--;
}
}
}

let text = `## ${sameDeps.map((d) => d.name || "unknown").join(", ")}\n\n`;
const depInfos = sameDeps.map((d) => getDependencyInformation(d));

// If all same dependencies have the same license and contributor names, show them only once
if (
depInfos.length > 1 &&
depInfos.every(
(info) => info.license === depInfos[0].license && info.names === depInfos[0].names,
)
) {
const { license, names } = depInfos[0];
const repositoryText = depInfos
.map((info) => info.repository)
.filter(Boolean)
.join(", ");

if (existsSync(opts.output)) {
// TODO: Deep merge?
console.log("Appending third-party licenses to", opts.output);
await appendFile(opts.output, "\n\n" + dependencyLicenseTexts);
} else {
const licenseText =
`# Licenses of Bundled Dependencies\n\n` +
`The published artifact additionally contains code with the following licenses:\n` +
`${licenses.join(", ")}\n\n` +
`# Bundled Dependencies\n\n` +
dependencyLicenseTexts;

console.log("Writing third-party licenses to", opts.output);

await mkdir(dirname(opts.output!), { recursive: true });
await writeFile(opts.output!, licenseText);
if (license) text += `License: ${license}\n`;
if (names) text += `By: ${names}\n`;
if (repositoryText) text += `Repositories: ${repositoryText}\n`;
}
// Else show each dependency separately
else {
for (let j = 0; j < depInfos.length; j++) {
const { license, names, repository } = depInfos[j];

if (license) text += `License: ${license}\n`;
if (names) text += `By: ${names}\n`;
if (repository) text += `Repository: ${repository}\n`;
if (j !== depInfos.length - 1) text += "\n";
}
},
});
// Skip for watch mode
for (const hook of ["renderChunk", "generateBundle"] as const) {
const originalHook = originalPlugin[hook];
if (!originalHook) continue;
// @ts-expect-error
originalPlugin[hook] = function (this: PluginContext, ...args: unknown[]) {
if (this.meta.watchMode) return;
// @ts-expect-error
return originalHook.apply(this, args);
};
}

if (licenseText) {
text +=
"\n" +
licenseText
.trim()
.replace(/\r\n|\r/g, "\n")
.split("\n")
.map((line: string) => `> ${line}`)
.join("\n") +
"\n";
}

if (i !== deps.length - 1) {
text += "\n---------------------------------------\n\n";
}

dependencyLicenseTexts += text;
}

if (!dependencyLicenseTexts) {
return;
}

if (existsSync(output)) {
// TODO: Deep merge?
console.log("Appending third-party licenses to", output);
await appendFile(output, "\n\n" + dependencyLicenseTexts);
} else {
const licenseText =
`# Licenses of Bundled Dependencies\n\n` +
`The published artifact additionally contains code with the following licenses:\n` +
`${licenses.join(", ")}\n\n` +
`# Bundled Dependencies\n\n` +
dependencyLicenseTexts;

console.log("Writing third-party licenses to", output);

await mkdir(dirname(output), { recursive: true });
await writeFile(output, licenseText);
}
return originalPlugin as Plugin;
}

function sortDependencies(dependencies: Dependency[]) {
Expand Down
38 changes: 38 additions & 0 deletions test/__snapshots__/obuild.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`obuild > license file matches snapshot 1`] = `
"# Licenses of Bundled Dependencies

The published artifact additionally contains code with the following licenses:
MIT

# Bundled Dependencies

## defu

License: MIT
Repository: https://github.com/unjs/defu

> MIT License
>
> Copyright (c) Pooya Parsa <pooya@pi0.io>
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all
> copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
> SOFTWARE.
"
`;
3 changes: 3 additions & 0 deletions test/fixture/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,8 @@
},
"dependencies": {
"obuild": "latest"
},
"devDependencies": {
"defu": "*"
}
}
3 changes: 2 additions & 1 deletion test/fixture/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import internal from "#internal";
import { defu } from "defu";

export function test(): string {
return "test bundled: " + internal;
return "test bundled: " + internal + JSON.stringify(defu({}, {}));
}

export default "default export";
9 changes: 9 additions & 0 deletions test/obuild.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ describe("obuild", () => {
const distFiles = await readdir(distDir, { recursive: true }).then((r) => r.sort());
expect(distFiles).toMatchInlineSnapshot(`
[
"THIRD-PARTY-LICENSES.md",
"_chunks",
"_chunks/libs",
"_chunks/libs/defu.mjs",
"cli.d.mts",
"cli.mjs",
"index.d.mts",
Expand Down Expand Up @@ -71,4 +75,9 @@ describe("obuild", () => {
const stats = await stat(cliPath);
expect(stats.mode & 0o111).toBe(0o111); // Check if executable
});

test("license file matches snapshot", async () => {
const content = await readFile(new URL("THIRD-PARTY-LICENSES.md", distDir), "utf8");
expect(content).toMatchSnapshot();
});
});