Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 2 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ jobs:
- # some integration tests require a certain npm version to be installable
name: update npm
run: npm i -g npm@^8
- name: Setup yarn
run: corepack enable yarn
- name: display version
run: |-
node --version
Expand Down
34 changes: 27 additions & 7 deletions src/_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,36 +18,56 @@ Copyright (c) OWASP Foundation. All Rights Reserved.
*/

import { existsSync, readFileSync } from 'fs'
import { dirname, isAbsolute, join } from 'path'
import { dirname, isAbsolute, join, sep } from 'path'

export interface PackageDescription {
path: string
packageJson: any
}

export function getPackageDescription (path: string): PackageDescription | undefined {
const isSubDirOfNodeModules = isSubDirectoryOfNodeModulesFolder(path)

while (isAbsolute(path)) {
const packageJson = join(path, 'package.json')
if (existsSync(packageJson)) {
const pathToPackageJson = join(path, 'package.json')
if (existsSync(pathToPackageJson)) {
try {
return {
path: packageJson,
packageJson: loadJsonFile(packageJson) ?? {}
const contentOfPackageJson = loadJsonFile(pathToPackageJson) ?? {}
// only look for valid candidate if we are in a node_modules subdirectory
if (!isSubDirOfNodeModules || isValidPackageJSON(contentOfPackageJson)) {
return {
path: pathToPackageJson,
packageJson: loadJsonFile(pathToPackageJson) ?? {}
}
}
} catch {
return undefined
}
}

const nextPath = dirname(path)
if (nextPath === path) {
if (nextPath === path || isNodeModulesFolder(nextPath)) {
return undefined
}
path = nextPath
}
return undefined
}

function isNodeModulesFolder (path: string): boolean {
return path.endsWith(`${sep}node_modules`)
}

function isSubDirectoryOfNodeModulesFolder (path: string): boolean {
return path.includes(`${sep}node_modules${sep}`)
}

export function isValidPackageJSON (pkg: any): boolean {
// checking for the existence of name and version properties
// both are required for a valid package.json according to https://docs.npmjs.com/cli/v10/configuring-npm/package-json
return typeof pkg.name === 'string' && typeof pkg.version === 'string'
}

export function loadJsonFile (path: string): any {
return JSON.parse(readFileSync(path, 'utf8'))
// may be replaced by `require(f, { with: { type: "json" } })`
Expand Down
Loading