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
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"help": "^3.0.2",
"https-proxy-agent": "^7.0.6",
"js-yaml": "^4.1.1",
"jsonc-parser": "^3.3.1",
"micromatch": "^4.0.8",
"node-fetch": "^3.3.2",
"p-limit": "^4.0.0",
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,8 @@ async function detectWorkspaceManifests(root, opts) {
}
}

const hasJsLock = fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
const hasJsLock = fs.existsSync(path.join(root, 'bun.lock'))
|| fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
|| fs.existsSync(path.join(root, 'yarn.lock'))
|| fs.existsSync(path.join(root, 'package-lock.json'))

Expand Down
2 changes: 2 additions & 0 deletions src/provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import golangGomodulesProvider from './providers/golang_gomodules.js'
import Java_gradle_groovy from "./providers/java_gradle_groovy.js";
import Java_gradle_kotlin from "./providers/java_gradle_kotlin.js";
import Java_maven from "./providers/java_maven.js";
import Javascript_bun from './providers/javascript_bun.js';
import Javascript_npm from './providers/javascript_npm.js';
import Javascript_pnpm from './providers/javascript_pnpm.js';
import Javascript_yarn from './providers/javascript_yarn.js';
Expand All @@ -24,6 +25,7 @@ export const availableProviders = [
new Java_maven(),
new Java_gradle_groovy(),
new Java_gradle_kotlin(),
new Javascript_bun(),
new Javascript_pnpm(),
new Javascript_yarn(),
new Javascript_npm(),
Expand Down
6 changes: 3 additions & 3 deletions src/providers/base_javascript.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@
* @returns {boolean} True if the lock file exists
*/
validateLockFile(manifestDir, opts = {}) {
return this._findLockFileDir(manifestDir, opts) !== null

Check warning on line 178 in src/providers/base_javascript.js

View workflow job for this annotation

GitHub Actions / Lint and test project (24)

Expected '!=' and instead saw '!=='

Check warning on line 178 in src/providers/base_javascript.js

View workflow job for this annotation

GitHub Actions / Lint and test project (22)

Expected '!=' and instead saw '!=='
}

/**
Expand Down Expand Up @@ -241,7 +241,7 @@
this._version();
const manifestDir = path.dirname(this.#manifest.manifestPath);
const cmdDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
this.#createLockFile(cmdDir);
this._createLockFile(cmdDir);

let output = this.#executeListCmd(includeTransitive, cmdDir);
output = this._parseDepTreeOutput(output);
Expand Down Expand Up @@ -408,9 +408,9 @@
/**
* Creates or updates the lock file for the package manager
* @param {string} manifestDir - Directory containing the manifest file
* @private
* @protected
*/
#createLockFile(manifestDir) {
_createLockFile(manifestDir) {
const originalDir = process.cwd();
const isWindows = os.platform() === 'win32';

Expand Down
122 changes: 122 additions & 0 deletions src/providers/javascript_bun.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import fs from 'node:fs'
import path from 'node:path'

import { parse } from 'jsonc-parser';

import Base_javascript from './base_javascript.js';

export default class Javascript_bun extends Base_javascript {

_lockFileName() {
return "bun.lock";
}

_cmdName() {
return "bun";
}

_listCmdArgs() {
throw new Error("not supported by Bun");
}

_updateLockFileCmdArgs() {
return ['install', '--lockfile-only'];
}

_buildDependencyTree(includeTransitive, opts = {}) {
this._version();
const manifestDir = path.dirname(this._getManifest().manifestPath);
const lockDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
this._createLockFile(lockDir);

const lockContent = fs.readFileSync(path.join(lockDir, 'bun.lock'), 'utf-8');
const lockData = parse(lockContent);

const packages = lockData.packages || {};
const memberName = this._getManifest().name;
const workspaceEntry = this.#findWorkspaceEntry(lockData, lockDir, manifestDir, memberName);

const directDeps = workspaceEntry?.dependencies || {};
const tree = { name: memberName, version: this._getManifest().version, dependencies: {} };

const visited = new Set();
for (const depName of Object.keys(directDeps)) {
const resolved = this.#resolvePackage(depName, '', packages);
if (resolved) {
tree.dependencies[depName] = this.#buildNode(depName, resolved, packages, includeTransitive, visited);
}
}

return tree;
}

#findWorkspaceEntry(lockData, lockDir, manifestDir, memberName) {
const workspaces = lockData.workspaces || {};
const relPath = path.relative(lockDir, path.resolve(manifestDir));
if (!relPath || relPath === '.') {
return workspaces[''] || {};
}
const normalised = relPath.split(path.sep).join('/');
if (workspaces[normalised]) {
return workspaces[normalised];
}
for (const [wsPath, entry] of Object.entries(workspaces)) {
if (entry.name === memberName && wsPath !== '') {
return entry;
}
}
return workspaces[''] || {};
}

#resolvePackage(depName, parentKey, packages) {
if (parentKey) {
const scopedKey = `${parentKey}/${depName}`;
if (packages[scopedKey]) {
return packages[scopedKey];
}
}
return packages[depName] || null;
}

#buildNode(depName, resolved, packages, includeTransitive, visited) {
const resolvedId = Array.isArray(resolved) ? resolved[0] : resolved;
const version = this.#extractVersion(resolvedId);
const node = { version };

if (!includeTransitive) {
return node;
}

const metadata = Array.isArray(resolved) ? (resolved[2] || {}) : {};
const subDeps = metadata.dependencies || {};

if (Object.keys(subDeps).length > 0) {
const visitKey = `${depName}@${version}`;
if (visited.has(visitKey)) {
return node;
}
visited.add(visitKey);

node.dependencies = {};
for (const subName of Object.keys(subDeps)) {
const subResolved = this.#resolvePackage(subName, depName, packages);
if (subResolved) {
node.dependencies[subName] = this.#buildNode(subName, subResolved, packages, true, visited);
}
}
}

return node;
}

#extractVersion(resolvedId) {
if (typeof resolvedId !== 'string') {
return '0.0.0';
}
const atIdx = resolvedId.lastIndexOf('@');
if (atIdx > 0) {
return resolvedId.substring(atIdx + 1);
}
return '0.0.0';
}
}
67 changes: 66 additions & 1 deletion test/providers/javascript.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ async function createMockProvider(providerName, listingOutput) {
const Javascript_yarn = await mockProvider('yarn', listingOutput, '4.9.1');
return new Javascript_yarn();
}
case 'bun': {
const Javascript_bun = await mockProvider(providerName, listingOutput);
return new Javascript_bun();
}
default: { fail('Not implemented'); }
}
}
Expand All @@ -60,7 +64,11 @@ suite('testing the javascript-npm data provider', async () => {
{ name: 'yarn-classic/with_lock_file', validation: true },
{ name: 'yarn-classic/without_lock_file', validation: false },
{ name: 'yarn-berry/with_lock_file', validation: true },
{ name: 'yarn-berry/without_lock_file', validation: false }
{ name: 'yarn-berry/without_lock_file', validation: false },
{ name: 'bun/with_lock_file', validation: true },
{ name: 'bun/without_lock_file', validation: false },
{ name: 'bun/workspace_member_with_lock/packages/module-a', validation: true },
{ name: 'bun/workspace_member_without_lock/packages/module-a', validation: false }
].forEach(testCase => {
test(`verify isSupported returns ${testCase.expected} for ${testCase.name}`, () => {
let manifest = `test/providers/provider_manifests/${testCase.name}/package.json`;
Expand Down Expand Up @@ -192,6 +200,35 @@ suite('testing the javascript-npm data provider', async () => {
}).timeout(15000);
});

['bun'].flatMap(providerName => [
{ testCase: "package_json_deps_without_exhortignore_object", manifest: "package.json" },
{ testCase: "package_json_deps_with_exhortignore_object", manifest: "package.json" },
{ testCase: "package_json_deps_with_mixed_dep_types", manifest: "package.json" },
{ testCase: "workspace_member", manifest: "packages/member-a/package.json" },
].map(tc => ({ providerName, ...tc }))).forEach(({ providerName, testCase, manifest }) => {
let scenario = testCase.replace('package_json_deps_', '').replaceAll('_', ' ')
test(`verify package.json data provided for ${providerName} - stack analysis - ${scenario}`, async () => {
let expectedSbom = fs.readFileSync(`test/providers/tst_manifests/${providerName}/${testCase}/stack_expected_sbom.json`).toString();

const provider = await createMockProvider(providerName, '');
const manifestPath = `test/providers/tst_manifests/${providerName}/${testCase}/${manifest}`;
let providedDataForStack = provider.provideStack(manifestPath);

compareSboms(providedDataForStack.content, expectedSbom);

}).timeout(30000);
test(`verify package.json data provided for ${providerName} - component analysis - ${scenario}`, async () => {
let expectedSbom = fs.readFileSync(`test/providers/tst_manifests/${providerName}/${testCase}/component_expected_sbom.json`).toString().trim();

const provider = await createMockProvider(providerName, '');
const manifestPath = `test/providers/tst_manifests/${providerName}/${testCase}/${manifest}`;
let providedDataForComponent = provider.provideComponent(manifestPath);

compareSboms(providedDataForComponent.content, expectedSbom);
}).timeout(15000)

});

test('loads a valid manifest with ignored dependencies', () => {
const testCase = 'package_json_deps_with_exhortignore_object';
const manifestPath = `test/providers/tst_manifests/npm/${testCase}/package.json`;
Expand Down Expand Up @@ -306,4 +343,32 @@ suite('testing the javascript-npm data provider', async () => {
.to.throw('package.json requires a lock file')
})

test('verify match with opts.TRUSTIFY_DA_WORKSPACE_DIR finds bun provider when lock is at workspace root', () => {
const manifest = 'test/providers/provider_manifests/bun/with_lock_file/package.json'
const opts = { TRUSTIFY_DA_WORKSPACE_DIR: 'test/providers/provider_manifests/bun/with_lock_file' }
const provider = match(manifest, availableProviders, opts)
expect(provider).to.not.be.null
expect(provider.isSupported('package.json')).to.be.true
})

test('verify bun workspace member walks up and finds lock file at workspace root', () => {
const manifest = 'test/providers/provider_manifests/bun/workspace_member_with_lock/packages/module-a/package.json'
const provider = match(manifest, availableProviders)
expect(provider).to.not.be.null
expect(provider.isSupported('package.json')).to.be.true
})

test('verify bun workspace member throws when workspace root has no lock file', () => {
const manifest = 'test/providers/provider_manifests/bun/workspace_member_without_lock/packages/module-a/package.json'
expect(() => match(manifest, availableProviders))
.to.throw('package.json requires a lock file')
})

test('verify match with wrong TRUSTIFY_DA_WORKSPACE_DIR fails for bun even when walk-up would succeed', () => {
const manifest = 'test/providers/provider_manifests/bun/workspace_member_with_lock/packages/module-a/package.json'
const opts = { TRUSTIFY_DA_WORKSPACE_DIR: 'test/providers/provider_manifests/bun/workspace_member_without_lock' }
expect(() => match(manifest, availableProviders, opts))
.to.throw('package.json requires a lock file')
})

}).beforeAll(() => clock = useFakeTimers(new Date('2023-08-07T00:00:00.000Z'))).afterAll(() => clock.restore());
9 changes: 9 additions & 0 deletions test/providers/provider_manifests/bun/with_lock_file/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions test/providers/provider_manifests/bun/with_lock_file/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "test-workspace",
"version": "1.0.0",
"workspaces": ["packages/*"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "module-a",
"version": "1.0.0"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "test-workspace",
"version": "1.0.0",
"workspaces": ["packages/*"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "module-a",
"version": "1.0.0"
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading