├── .nvmrc ├── .atlassian └── OWNER ├── tsconfig.build.json ├── .babelrc ├── .prettierrc.js ├── .npmignore ├── .gitignore ├── CHANGELOG.md ├── .eslintrc.js ├── .github └── workflows │ └── nodejs.yml ├── tsconfig.json ├── CONTRIBUTING.md ├── README.md ├── package.json ├── CODE_OF_CONDUCT.md ├── src ├── __tests__ │ ├── resolver.test.js │ ├── index.test.js │ └── utils.test.js ├── resolver.js ├── index.js └── utils.js └── LICENSE /.nvmrc: -------------------------------------------------------------------------------- 1 | v12.16.2 2 | -------------------------------------------------------------------------------- /.atlassian/OWNER: -------------------------------------------------------------------------------- 1 | nmakarevich 2 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src/**/*"], 4 | "exclude": ["src/__tests__/**/*"] 5 | } -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/env", 4 | "@babel/typescript" 5 | ], 6 | "plugins": [ 7 | "@babel/proposal-class-properties" 8 | ] 9 | } -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | printWidth: 100, 3 | tabWidth: 4, 4 | semi: true, 5 | singleQuote: true, 6 | trailingComma: 'es5', 7 | } -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Editors 7 | .idea 8 | .vscode 9 | .history 10 | *.iml 11 | .vs 12 | jsconfig.json 13 | *.swp 14 | 15 | # Dependency directories 16 | node_modules 17 | .yalc 18 | yalc.lock 19 | 20 | # Optional npm cache directory 21 | .npm 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Editors 7 | .idea 8 | .vscode 9 | .history 10 | *.iml 11 | .vs 12 | jsconfig.json 13 | *.swp 14 | 15 | # Dependency directories 16 | node_modules 17 | .yalc 18 | yalc.lock 19 | 20 | # Optional npm cache directory 21 | .npm 22 | 23 | # Build files 24 | build -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 0.0.3 / 2020-04-29 2 | ================== 3 | 4 | * Performance improvements for module resolution 5 | 6 | 0.0.4 / 2020-12-07 7 | ================== 8 | 9 | * Bug fix where dependency was being deduped with incorrect packages that partially 10 | matched in package name. E.g. button vs button-group. 11 | 12 | 0.0.5 / 2020-12-08 13 | ================== 14 | 15 | * add .npmignore 16 | 17 | 0.0.6 / 2021-03-10 18 | ================== 19 | 20 | * Broken version! Please use v0.0.7 21 | 22 | 0.0.7 / 2021-03-10 23 | ================== 24 | 25 | * Updated to use enhanced-resolver (same as webpack) 26 | 27 | 0.0.8 / 2021-03-10 28 | ================== 29 | 30 | * No change, update of CHANGELOG only 31 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | const importOrder = { 2 | "groups": [ 3 | 'builtin', 4 | 'external', 5 | 'internal', 6 | 'parent', 7 | 'sibling', 8 | 'unknown', 9 | ], 10 | "pathGroupsExcludedImportTypes": [], 11 | "alphabetize": { 12 | "order": 'asc', 13 | "caseInsensitive": true 14 | } 15 | }; 16 | 17 | module.exports = { 18 | parser: 'babel-eslint', 19 | env: { 20 | browser: true, 21 | es6: true, 22 | }, 23 | extends: [ 24 | 'eslint:recommended', 25 | 'plugin:prettier/recommended', 26 | 'plugin:jest/recommended', 27 | 'plugin:import/errors', 28 | 'plugin:import/typescript' 29 | ], 30 | parserOptions: { 31 | ecmaVersion: 2018, 32 | sourceType: 'module', 33 | }, 34 | plugins: ['prettier', 'jest'], 35 | rules: { 36 | 'import/order': ['error', importOrder], 37 | }, 38 | env: { 39 | node: true, 40 | 'jest/globals': true, 41 | }, 42 | }; -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [12.x] 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Use Node.js ${{ matrix.node-version }} 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: ${{ matrix.node-version }} 27 | - name: Install dependencies 28 | run: yarn 29 | - name: Run tests 30 | run: yarn test 31 | - name: Run linting 32 | run: yarn lint 33 | - name: Run type check 34 | run: yarn type-check 35 | - name: Build 36 | run: yarn build -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 4 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 5 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 6 | "outDir": "build", /* Redirect output structure to the directory. */ 7 | "strict": true, /* Enable all strict type-checking options. */ 8 | "esModuleInterop": false, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 9 | "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ 10 | "moduleResolution": "node", 11 | "allowJs": true 12 | }, 13 | "include": [ 14 | "src/**/*" 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Webpack Deduplication Plugin 2 | 3 | Thank you for considering a contribution to Webpack Deduplication Plugin! Pull requests, issues and comments are welcome. For pull requests, please: 4 | 5 | * Add tests for new features and bug fixes 6 | * Follow the existing style 7 | * Separate unrelated changes into multiple pull requests 8 | 9 | See the existing issues for things to start contributing. 10 | 11 | For bigger changes, please make sure you start a discussion first by creating an issue and explaining the intended change. 12 | 13 | Atlassian requires contributors to sign a Contributor License Agreement, known as a CLA. This serves as a record stating that the contributor is entitled to contribute the code/documentation/translation to the project and is willing to have it used in distributions and derivative works (or is willing to transfer ownership). 14 | 15 | Prior to accepting your contributions we ask that you please follow the appropriate link below to digitally sign the CLA. The Corporate CLA is for those who are contributing as a member of an organization and the individual CLA is for those contributing as an individual. 16 | 17 | * [CLA for corporate contributors](https://opensource.atlassian.com/corporate) 18 | * [CLA for individuals](https://opensource.atlassian.com/individual) 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Webpack Deduplication Plugin 2 | 3 | Plugin for webpack that de-duplicates transitive dependencies in yarn and webpack-based projects. 4 | 5 | ## Usage 6 | 7 | Import it from the package 8 | 9 | ``` 10 | const { WebpackDeduplicationPlugin } = require('webpack-deduplication-plugin'); 11 | ``` 12 | 13 | And add it to your webpack config: 14 | 15 | ``` 16 | plugins: [ 17 | new WebpackDeduplicationPlugin({ 18 | cacheDir: cacheDirPath, 19 | rootPath: rootPath, 20 | }), 21 | ] 22 | ``` 23 | 24 | where: 25 | 26 | - cacheDirPath - absolute path to the directory where the cache of the duplicates will be stored. 27 | Cache is based on the content of `yarn.lock` file and will be updated with every change. 28 | If not provided then the duplicates will be re-generated with every run. 29 | 30 | * rootPath - absolute path to the root of the project. If not provided it will be auto-detected 31 | by [`app-root-path`](https://www.npmjs.com/package/app-root-path) plugin 32 | 33 | ## Development 34 | 35 | TBD 36 | 37 | ## Contributions 38 | 39 | Contributions to Webpack Deduplication Plugin are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details. 40 | 41 | ## License 42 | 43 | Copyright (c) 2020 Atlassian and others. 44 | Apache 2.0 licensed, see [LICENSE](LICENSE) file. 45 | 46 |
47 | 48 | [![With ❤️ from Atlassian](https://raw.githubusercontent.com/atlassian-internal/oss-assets/master/banner-with-thanks.png)](https://www.atlassian.com) 49 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webpack-deduplication-plugin", 3 | "version": "0.0.8", 4 | "description": "Webpack plugin for deduplicating transitive dependencies", 5 | "keywords": [ 6 | "Webpack", 7 | "Webpack plugin" 8 | ], 9 | "types": "./build/index.d.ts", 10 | "main": "build/index.js", 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/atlassian-labs/webpack-deduplication-plugin" 14 | }, 15 | "author": "Nadia Makarevich", 16 | "license": "Apache-2.0", 17 | "bugs": { 18 | "url": "https://github.com/atlassian-labs/webpack-deduplication-plugin/issues" 19 | }, 20 | "homepage": "https://github.com/atlassian-labs/webpack-deduplication-plugin#readme", 21 | "scripts": { 22 | "test": "jest", 23 | "type-check": "tsc --noEmit", 24 | "type-check:watch": "npm run type-check -- --watch", 25 | "build": "rm -rf build && npm run build:types && npm run build:js", 26 | "build:types": "tsc --project tsconfig.build.json --emitDeclarationOnly", 27 | "build:js": "babel src --out-dir build --extensions \".ts,.tsx,.js\" --ignore src/__tests__ --source-maps inline", 28 | "lint": "eslint --ext .ts,.tsx,.js src/", 29 | "prepare": "npm run build" 30 | }, 31 | "jest": { 32 | "roots": [ 33 | "src" 34 | ] 35 | }, 36 | "dependencies": { 37 | "app-root-path": "^3.0.0", 38 | "enhanced-resolve": "^5.7.0", 39 | "fast-glob": "^3.2.2", 40 | "find-package-json": "^1.2.0", 41 | "lodash": "^4.17.15", 42 | "mkdirp": "^1.0.3" 43 | }, 44 | "devDependencies": { 45 | "@babel/cli": "^7.8.4", 46 | "@babel/core": "^7.9.0", 47 | "@babel/plugin-proposal-class-properties": "^7.8.3", 48 | "@babel/preset-env": "^7.9.0", 49 | "@babel/preset-typescript": "^7.9.0", 50 | "@types/jest": "^25.1.4", 51 | "@types/node": "^13.9.3", 52 | "@typescript-eslint/eslint-plugin": "^2.24.0", 53 | "@typescript-eslint/parser": "^2.24.0", 54 | "babel-eslint": "^10.1.0", 55 | "eslint": "^6.8.0", 56 | "eslint-config-prettier": "^6.10.1", 57 | "eslint-plugin-import": "^2.20.1", 58 | "eslint-plugin-jest": "^23.8.2", 59 | "eslint-plugin-prettier": "^3.1.2", 60 | "jest": "^25.1.0", 61 | "mock-fs": "^4.11.0", 62 | "prettier": "2.0.1", 63 | "typescript": "^3.8.3" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. 6 | 7 | Examples of unacceptable behavior by participants include: 8 | 9 | * The use of sexualized language or imagery 10 | * Personal attacks 11 | * Trolling or insulting/derogatory comments 12 | * Public or private harassment 13 | * Publishing other's private information, such as physical or electronic addresses, without explicit permission 14 | * Submitting contributions or comments that you know to violate the intellectual property or privacy rights of others 15 | * Other unethical or unprofessional conduct 16 | 17 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 18 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. 19 | 20 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. 21 | 22 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer. Complaints will result in a response and be reviewed and investigated in a way that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. 23 | 24 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] 25 | 26 | [homepage]: http://contributor-covenant.org 27 | [version]: http://contributor-covenant.org/version/1/3/0/ -------------------------------------------------------------------------------- /src/__tests__/resolver.test.js: -------------------------------------------------------------------------------- 1 | const mockFs = require('mock-fs'); 2 | const { createMemoisedResolver } = require('../resolver'); 3 | 4 | describe('resolver', () => { 5 | afterEach(() => { 6 | mockFs.restore(); 7 | }); 8 | 9 | it('resolves things', () => { 10 | mockFs({ 11 | '/pkg/node_modules/@org': { 12 | foo: { 13 | 'package.json': JSON.stringify({ 14 | name: '@org/foo', 15 | version: '1.0.0', 16 | main: 'dist/index.js', 17 | }), 18 | dist: { 19 | 'index.js': '1;', 20 | }, 21 | node_modules: { 22 | other: { 23 | 'package.json': JSON.stringify({ 24 | name: 'other', 25 | module: 'dist/index.js', 26 | main: 'dist/none.js', 27 | }), 28 | dist: { 29 | 'index.js': '3;', 30 | }, 31 | }, 32 | }, 33 | }, 34 | bar: { 35 | 'package.json': JSON.stringify({ 36 | name: '@org/bar', 37 | version: '1.0.0', 38 | module: 'dist/index.js', 39 | main: 'dist/none.js', 40 | }), 41 | 42 | dist: { 'index.js': '0;' }, 43 | }, 44 | }, 45 | }); 46 | 47 | const resolver = createMemoisedResolver(['module', 'main']); 48 | const tests = [ 49 | { 50 | request: '@org/bar', 51 | context: '/pkg', 52 | expected: '/pkg/node_modules/@org/bar/dist/index.js', 53 | }, 54 | { 55 | request: '@org/foo', 56 | context: '/pkg/@org/bar/dist/index.js', 57 | expected: '/pkg/node_modules/@org/foo/dist/index.js', 58 | }, 59 | { 60 | request: 'other', 61 | context: '/pkg/node_modules/@org/foo/dist/index.js', 62 | expected: '/pkg/node_modules/@org/foo/node_modules/other/dist/index.js', 63 | }, 64 | { 65 | request: 'fs', 66 | context: '/pkg/node_modules/@org/foo/dist/index.js', 67 | expected: 'fs', 68 | }, 69 | ]; 70 | 71 | const results = tests.map((test) => resolver(test.request, test.context)); 72 | mockFs.restore(); 73 | results.forEach((result, idx) => { 74 | expect(result).toEqual(tests[idx].expected); 75 | }); 76 | }); 77 | }); 78 | -------------------------------------------------------------------------------- /src/resolver.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const { ResolverFactory, CachedInputFileSystem } = require('enhanced-resolve'); 3 | const memoize = require('lodash/memoize'); 4 | 5 | const noop = () => {}; 6 | 7 | const createMemoisedResolver = (mainFields) => { 8 | const resolver = ResolverFactory.createResolver({ 9 | fileSystem: new CachedInputFileSystem(fs, 4000), 10 | useSyncFileSystemCalls: true, 11 | mainFields, 12 | }); 13 | 14 | return memoize( 15 | (request, context) => { 16 | let resolved; 17 | 18 | // This is a bit of a performance hack. The short of it is that the way to checks for the 19 | // existence of a file in Node is by performing an fs operation (whether that's a `read` 20 | // or a `stat`). When this operation fails, an exception is created and thrown. Checking 21 | // the underlying OS error type in this exception can be used to determine whether the file 22 | // exists or some other error occurred. 23 | // 24 | // Node does this through an internal method called `uvException` - https://github.com/nodejs/node/blob/307c67be175b8fe7d9dd9e1b5ed55d928b73d66d/lib/internal/errors.js#L399 25 | // (`libuv` being the underlying library that handles Node's async i/o). These exceptions 26 | // have a full stacktrace generated, which is actually a super expensive operation. Now 27 | // when we call `resolve` 20,000+ times during a webpack build we're generating a lot of 28 | // exceptions with stack traces that we just end up throwing away. 29 | // 30 | // So this hack noops the `captureStackTrace` method Node uses, and cuts the stack limit for 31 | // `new Error` calls. This means that errors occurring in this function won't have stack 32 | // traces, but this is an acceptable tradeoff for the almost 50% perf improvement we get 33 | // when we have a compile of significant size. 34 | // 35 | // A profile still shows significant time in `uvException`, but there aren't any extra obvious 36 | // easy optimisation opportunities. 37 | const originalCaptureStackTrace = Error.captureStackTrace; 38 | const originalStackLimit = Error.stackTraceLimit; 39 | try { 40 | Error.captureStackTrace = noop; 41 | Error.stackTraceLimit = 0; 42 | 43 | resolved = resolver.resolveSync({}, context, request); 44 | } catch (e) { 45 | // Where a resolution fails (e.g. trying to resolve a built-in) we just 46 | // return the original request, this allows it to be handled properly downstream 47 | resolved = request; 48 | } finally { 49 | Error.captureStackTrace = originalCaptureStackTrace; 50 | Error.stackTraceLimit = originalStackLimit; 51 | } 52 | return resolved; 53 | }, 54 | (r, c) => `${r} _____ ${c}` 55 | ); 56 | }; 57 | 58 | module.exports = { createMemoisedResolver }; 59 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const packageJsonFinder = require('find-package-json'); 3 | 4 | const { createMemoisedResolver } = require('./resolver'); 5 | const { getDuplicatedPackages } = require('./utils'); 6 | 7 | const containsNodeModules = (resolvedResource) => { 8 | return resolvedResource.includes('node_modules'); 9 | }; 10 | 11 | const findDuplicate = (resolvedResource) => (duplicate) => { 12 | // prevent partial name matches. I.e. don't match `/button` when resolving `/button-group` 13 | const duplicateDir = `${duplicate}${path.sep}`; 14 | return resolvedResource.includes(duplicateDir); 15 | }; 16 | 17 | const findBestMatch = (arr, matcher) => { 18 | return arr.filter(matcher).sort((a, b) => b.length - a.length)[0]; 19 | }; 20 | 21 | const deduplicate = (result, dupVals, resolver) => { 22 | // Note that the "API" for a beforeResolve hook is to return `undefined` to continue, 23 | // or `false` to skip this dependency. So we pretty much always return `undefined`. 24 | 25 | if (!result) return undefined; 26 | 27 | // dont touch loaders 28 | if (result.request.startsWith('!')) { 29 | return undefined; 30 | } 31 | 32 | const resolvedResource = resolver(result.request, result.context); 33 | if (!resolvedResource) { 34 | return undefined; 35 | } 36 | 37 | // short circuit 38 | if (!containsNodeModules(resolvedResource)) { 39 | return undefined; 40 | } 41 | 42 | // we will change result as a side-effect 43 | dupVals.some((onePackageDuplicates) => { 44 | const found = findBestMatch(onePackageDuplicates, findDuplicate(resolvedResource)); 45 | 46 | if (!found) { 47 | return false; 48 | } 49 | 50 | const replaceWithFirst = onePackageDuplicates[0]; 51 | const resolvedDup = resolvedResource.replace(found, replaceWithFirst); 52 | 53 | const lastIndex = resolvedDup.indexOf( 54 | 'node_modules', 55 | resolvedDup.indexOf(replaceWithFirst) + replaceWithFirst.length 56 | ); 57 | 58 | if (lastIndex !== -1) { 59 | return false; 60 | } 61 | 62 | const resolvedBase = packageJsonFinder(resolvedDup).next().value.name; 63 | const resolvedResourceBase = packageJsonFinder(resolvedResource).next().value.name; 64 | if (resolvedBase !== resolvedResourceBase) { 65 | return false; 66 | } 67 | 68 | // this is how it works with webpack 69 | // eslint-disable-next-line no-param-reassign 70 | result.request = resolvedDup; 71 | return true; 72 | }); 73 | 74 | return undefined; 75 | }; 76 | 77 | class WebpackDeduplicationPlugin { 78 | constructor({ cacheDir, rootPath }) { 79 | this.cacheDir = cacheDir; 80 | this.rootPath = rootPath; 81 | } 82 | 83 | apply(compiler) { 84 | const { cacheDir, rootPath } = this; 85 | const duplicates = getDuplicatedPackages({ 86 | cacheDir, 87 | rootPath, 88 | }); 89 | 90 | const resolver = createMemoisedResolver(compiler.options.resolve.mainFields); 91 | 92 | const dupVals = Object.values(duplicates); 93 | compiler.hooks.normalModuleFactory.tap('WebpackDeduplicationPlugin', (nmf) => { 94 | nmf.hooks.beforeResolve.tap('WebpackDeduplicationPlugin', (result) => { 95 | return deduplicate(result, dupVals, resolver); 96 | }); 97 | }); 98 | } 99 | } 100 | 101 | module.exports = { 102 | WebpackDeduplicationPlugin, 103 | deduplicate, 104 | }; 105 | -------------------------------------------------------------------------------- /src/utils.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const appRoot = require('app-root-path'); 5 | const glob = require('fast-glob'); 6 | const flatten = require('lodash/flatten'); 7 | const isEqual = require('lodash/isEqual'); 8 | const pickBy = require('lodash/pickBy'); 9 | const transform = require('lodash/transform'); 10 | const mkdirp = require('mkdirp'); 11 | 12 | const patchesPath = 'patches'; 13 | 14 | const extractPackageName = (name, scope) => { 15 | const patchName = scope ? `${scope}+${name}` : name; 16 | const patchArr = patchName.split('++'); 17 | // we care about only the last package name, this is the one that is duplicated/patched 18 | // the rest from the path, if it exists, is the "parent" packages 19 | const lastPkg = patchArr[patchArr.length - 1].replace('.patch', '').split('+'); 20 | 21 | // taking care of the scoped and non-scoped packages 22 | return lastPkg.length === 2 23 | ? `${lastPkg[0]}@${lastPkg[1]}` 24 | : `${lastPkg[0]}/${lastPkg[1]}@${lastPkg[2]}`; 25 | }; 26 | 27 | const getListOfPackages = (list, root, scope) => { 28 | return flatten( 29 | list.map((item) => { 30 | const itemPath = path.resolve(root, item); 31 | if (fs.lstatSync(itemPath).isFile()) { 32 | return extractPackageName(item, scope); 33 | } 34 | const innerList = fs.readdirSync(itemPath); 35 | 36 | return getListOfPackages(innerList, itemPath, item); 37 | }) 38 | ); 39 | }; 40 | 41 | const getPatchedPackages = (pPath) => { 42 | if (!fs.existsSync(pPath)) { 43 | return []; 44 | } 45 | const list = fs.readdirSync(pPath); 46 | 47 | return getListOfPackages(list, pPath); 48 | }; 49 | 50 | const extractProperDuplicates = (duplicates) => { 51 | return duplicates.filter((dup) => { 52 | const firstDupFilepath = path.resolve(duplicates[0], 'package.json'); 53 | const dupFilepath = path.resolve(dup, 'package.json'); 54 | const firstDupJson = JSON.parse(fs.readFileSync(firstDupFilepath).toString()); 55 | const dupJson = JSON.parse(fs.readFileSync(dupFilepath).toString()); 56 | 57 | return isEqual(firstDupJson, dupJson); 58 | }); 59 | }; 60 | 61 | const getCacheKey = ({ patchedPackages, rootPath }) => { 62 | const yarnLock = fs.readFileSync(path.resolve(rootPath, 'yarn.lock')); 63 | const hash = crypto.createHash('md5'); 64 | hash.update(yarnLock); 65 | hash.update(patchedPackages.join(',')); 66 | return hash.digest('hex'); 67 | }; 68 | 69 | // node_modules/**/node_modules/**/package.json pattern is a duplicate, we don't really need root-level packages 70 | const filterOnlyDuplicates = (pkg) => 71 | pkg.split(path.sep).filter((p) => p === 'node_modules').length > 1; 72 | 73 | const CACHE_BUST = 1; 74 | 75 | const getDuplicatedPackages = (options = {}) => { 76 | const rootPath = options.rootPath || appRoot.toString(); 77 | const patchedPackages = getPatchedPackages(options.patchesPath || patchesPath); 78 | let cacheFileName; 79 | if (options.cacheDir) { 80 | mkdirp.sync(options.cacheDir); 81 | const cacheKey = getCacheKey({ rootPath, patchedPackages }); 82 | cacheFileName = path.resolve(options.cacheDir, `duplicates-${cacheKey}.${CACHE_BUST}.json`); 83 | if (fs.existsSync(cacheFileName)) { 84 | return JSON.parse(fs.readFileSync(cacheFileName, 'utf8')); 85 | } 86 | } 87 | const packages = glob 88 | .sync(`${rootPath}/node_modules/**/package.json`) 89 | .sort() 90 | .filter(filterOnlyDuplicates); 91 | 92 | const packageJsonsByKeyFull = {}; 93 | 94 | packages.forEach((p) => { 95 | let json = {}; 96 | 97 | try { 98 | json = JSON.parse(fs.readFileSync(path.resolve(p)).toString()); 99 | } catch (e) { 100 | // console && console.error && console.error('Something went wrong while parsing package.json', p, e); 101 | } 102 | 103 | const { name, version, dependencies } = json; 104 | 105 | // check whether it's a "proper" package, you'd be surprised how many weird `package.json` out there 106 | if (name && version && dependencies) { 107 | const depName = `${name}@${version}`; 108 | 109 | packageJsonsByKeyFull[depName] = packageJsonsByKeyFull[depName] || []; 110 | packageJsonsByKeyFull[depName].push(path.parse(p).dir); 111 | } 112 | }); 113 | 114 | const onlyDuplicates = pickBy(packageJsonsByKeyFull, (value, key) => { 115 | return value.length > 1 && !patchedPackages.includes(key); 116 | }); 117 | 118 | const cleanFromFalsePositives = transform( 119 | onlyDuplicates, 120 | (result, value, key) => { 121 | // eslint-disable-next-line no-param-reassign 122 | result[key] = extractProperDuplicates(value).sort(); 123 | }, 124 | {} 125 | ); 126 | 127 | if (cacheFileName) { 128 | fs.writeFileSync(cacheFileName, JSON.stringify(cleanFromFalsePositives, null, 2), 'utf8'); 129 | } 130 | 131 | return cleanFromFalsePositives; 132 | }; 133 | 134 | module.exports = { 135 | getDuplicatedPackages, 136 | extractPackageName, 137 | getListOfPackages, 138 | }; 139 | -------------------------------------------------------------------------------- /src/__tests__/index.test.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const mockFs = require('mock-fs'); 3 | const { deduplicate } = require('../index'); 4 | 5 | jest.mock('../utils'); 6 | 7 | const mockResource = ({ filename, context }) => { 8 | return { 9 | request: filename, 10 | context, 11 | }; 12 | }; 13 | 14 | jest.mock('find-package-json', () => jest.fn()); 15 | 16 | describe('duplicate-transitive-replacement', () => { 17 | afterEach(() => mockFs.restore()); 18 | 19 | it('duplicate transitive dependencies replacement - matching duplicates should return replaced request', () => { 20 | mockFs({ 21 | [path.resolve( 22 | 'node_modules/@atlaskit/bar/node_modules/@atlaskit/foo', 23 | './something' 24 | )]: 'stuff', 25 | [path.resolve( 26 | 'node_modules/@atlaskit/zoo/node_modules/@atlaskit/foo', 27 | './something' 28 | )]: 'stuff', 29 | [path.resolve( 30 | 'node_modules/@atlaskit/auh/node_modules/@atlaskit/bar', 31 | './something' 32 | )]: 'stuff', 33 | }); 34 | const duplicates = [ 35 | [ 36 | 'node_modules/@atlaskit/zoo/node_modules/@atlaskit/foo', 37 | 'node_modules/@atlaskit/bar/node_modules/@atlaskit/foo', 38 | ], 39 | ]; 40 | 41 | const matchingResource = mockResource({ 42 | filename: './something', 43 | context: path.resolve('node_modules/@atlaskit/bar/node_modules/@atlaskit/foo'), 44 | }); 45 | 46 | const finder = require('find-package-json'); 47 | 48 | finder.mockImplementation(() => ({ 49 | next: () => ({ value: { name: '@atlaskit/foo' } }), 50 | })); 51 | 52 | const resolver = () => path.resolve(matchingResource.context, matchingResource.request); 53 | 54 | deduplicate(matchingResource, duplicates, resolver); 55 | 56 | expect(matchingResource).toEqual( 57 | mockResource({ 58 | filename: path.resolve( 59 | 'node_modules/@atlaskit/zoo/node_modules/@atlaskit/foo/something' 60 | ), 61 | context: path.resolve('node_modules/@atlaskit/bar/node_modules/@atlaskit/foo'), 62 | }) 63 | ); 64 | }); 65 | 66 | it('should not deduplicate when package name is partial match', () => { 67 | mockFs({ 68 | [path.resolve( 69 | 'node_modules/@org/component-a/node_modules/@org/radio-button', 70 | './index.js' 71 | )]: 'some radio button code', 72 | 73 | [path.resolve( 74 | 'node_modules/@org/component-b/node_modules/@org/radio-button', 75 | './index.js' 76 | )]: 'some radio button code', 77 | 78 | [path.resolve( 79 | 'node_modules/@org/component-b/node_modules/@org/radio-button-group', 80 | './index.js' 81 | )]: 'some radio button GROUP code', 82 | }); 83 | 84 | const duplicates = [ 85 | // although duplicate packages are prefixed with 'radio-button', these should 86 | // be ignored as they are not a full match on the 'radio-button-group' 87 | [ 88 | 'node_modules/@org/component-a/node_modules/@org/radio-button', 89 | 'node_modules/@org/component-b/node_modules/@org/radio-button', 90 | ], 91 | ]; 92 | 93 | const matchingResource = mockResource({ 94 | filename: './index.js', 95 | context: path.resolve( 96 | 'node_modules/@org/component-b/node_modules/@org/radio-button-group' 97 | ), 98 | }); 99 | 100 | const resolver = () => path.resolve(matchingResource.context, matchingResource.request); 101 | 102 | const finder = require('find-package-json'); 103 | 104 | finder.mockImplementation(() => ({ 105 | next: () => ({ value: { name: '@org/component-b' } }), 106 | })); 107 | 108 | deduplicate(matchingResource, duplicates, resolver); 109 | 110 | expect(matchingResource.context).not.toContain(/radio-button$/); 111 | }); 112 | 113 | it('duplicate transitive dependencies replacement - non-matching duplicates should not modify result', () => { 114 | mockFs({ 115 | [path.resolve( 116 | 'node_modules/@atlaskit/bar/node_modules/@atlaskit/foo', 117 | './something' 118 | )]: 'stuff', 119 | [path.resolve( 120 | 'node_modules/@atlaskit/zoo/node_modules/@atlaskit/foo', 121 | './something' 122 | )]: 'stuff', 123 | [path.resolve( 124 | 'node_modules/@atlaskit/auh/node_modules/@atlaskit/bar', 125 | './something' 126 | )]: 'stuff', 127 | }); 128 | const duplicates = [ 129 | [ 130 | 'node_modules/@atlaskit/zoo/node_modules/@atlaskit/foo', 131 | 'node_modules/@atlaskit/bar/node_modules/@atlaskit/foo', 132 | ], 133 | ]; 134 | 135 | const nonMatchingResource = mockResource({ 136 | filename: './something', 137 | context: path.resolve('node_modules/@atlaskit/auh/node_modules/@atlaskit/foo'), 138 | }); 139 | 140 | const resolver = () => 141 | path.resolve(nonMatchingResource.context, nonMatchingResource.request); 142 | 143 | const finder = require('find-package-json'); 144 | 145 | finder.mockImplementation(() => ({ 146 | next: () => ({ value: { name: '@atlaskit/foo' } }), 147 | })); 148 | 149 | const input = { ...nonMatchingResource }; 150 | deduplicate(input, duplicates, resolver); 151 | expect(nonMatchingResource).toEqual(input); 152 | }); 153 | }); 154 | -------------------------------------------------------------------------------- /src/__tests__/utils.test.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const mockFs = require('mock-fs'); 4 | 5 | const { getDuplicatedPackages, extractPackageName } = require('../utils'); 6 | 7 | const nodeModulesPrefix = path.resolve('node_modules/something/node_modules'); 8 | 9 | const nodeModulesMock = { 10 | 'yarn.lock': 'this has stuff in it', 11 | // we expect this to be handled by Yarn, so explicitly excluding root level node_modules from the check 12 | node_modules: { 13 | 'package-a-root-duplicate': { 14 | 'package.json': `{ 15 | "name": "package-a", 16 | "version": "0.1.0", 17 | "dependencies": { 18 | "package-d": "1.0.1" 19 | } 20 | }`, 21 | }, 22 | }, 23 | [nodeModulesPrefix]: { 24 | 'package-a': { 25 | 'package.json': `{ 26 | "name": "package-a", 27 | "version": "0.1.0", 28 | "dependencies": { 29 | "package-d": "1.0.1" 30 | } 31 | }`, 32 | }, 33 | 'package-a-duplicate': { 34 | 'package.json': `{ 35 | "name": "package-a", 36 | "version": "0.1.0", 37 | "dependencies": { 38 | "package-d": "1.0.1" 39 | } 40 | }`, 41 | }, 42 | 'package-a-different-version': { 43 | 'package.json': `{ 44 | "name": "package-a", 45 | "version": "0.1.1", 46 | "dependencies": { 47 | "package-d": "1.0.1" 48 | } 49 | }`, 50 | }, 51 | 'package-b-standalone': { 52 | 'package.json': `{ 53 | "name": "package-b", 54 | "version": "0.1.0", 55 | "dependencies": { 56 | "package-d": "1.0.1" 57 | } 58 | }`, 59 | }, 60 | 'package-c-not-valid': { 61 | 'package.json': `{ 62 | "name": "package-a", 63 | "version": "0.1.0", 64 | }`, 65 | }, 66 | 'package-d': { 67 | 'package.json': `{ 68 | "name": "package-d", 69 | "version": "0.1.0", 70 | "dependencies": { 71 | "package-d": "1.0.1" 72 | } 73 | }`, 74 | }, 75 | 'package-d-duplicate': { 76 | 'package.json': `{ 77 | "name": "package-d", 78 | "version": "0.1.0", 79 | "dependencies": { 80 | "package-d": "1.0.1" 81 | } 82 | }`, 83 | }, 84 | }, 85 | }; 86 | 87 | describe('deduplicate transitive dependenices plugin', () => { 88 | beforeEach(() => { 89 | jest.resetModules(); 90 | 91 | mockFs({ 92 | ...nodeModulesMock, 93 | patches: {}, 94 | }); 95 | }); 96 | 97 | afterEach(() => { 98 | mockFs.restore(); 99 | }); 100 | 101 | it('should find duplicated packages', () => { 102 | const duplicates = getDuplicatedPackages(); 103 | mockFs.restore(); 104 | expect(duplicates).toEqual({ 105 | 'package-a@0.1.0': [ 106 | `${nodeModulesPrefix}/package-a`, 107 | `${nodeModulesPrefix}/package-a-duplicate`, 108 | ], 109 | 'package-d@0.1.0': [ 110 | `${nodeModulesPrefix}/package-d`, 111 | `${nodeModulesPrefix}/package-d-duplicate`, 112 | ], 113 | }); 114 | }); 115 | 116 | it('should use cached result if deps have not changed', () => { 117 | const one = getDuplicatedPackages({ 118 | cacheDir: '/cache', 119 | }); 120 | const two = getDuplicatedPackages({ 121 | cacheDir: '/cache', 122 | }); 123 | 124 | expect(one).toEqual(two); 125 | // The best we can do without digging into internals is to make sure a cache entry was 126 | // created 127 | const cacheEntries = fs 128 | .readdirSync('/cache') 129 | .filter((filename) => /^duplicates-.*\.json$/.test(filename)); 130 | expect(cacheEntries).toHaveLength(1); 131 | }); 132 | 133 | it('should invalidate cache if yarn.lock changes', () => { 134 | const one = getDuplicatedPackages({ 135 | cacheDir: '/cache', 136 | }); 137 | fs.writeFileSync('yarn.lock', 'different content', 'utf8'); 138 | const two = getDuplicatedPackages({ 139 | cacheDir: '/cache', 140 | }); 141 | 142 | expect(one).toEqual(two); 143 | // The best we can do without digging into internals is to make sure a cache entry was 144 | // created 145 | const cacheEntries = fs 146 | .readdirSync('/cache') 147 | .filter((filename) => /^duplicates-.*\.json$/.test(filename)); 148 | expect(cacheEntries).toHaveLength(2); 149 | }); 150 | 151 | it('should invalidate cache if patches list changes', () => { 152 | getDuplicatedPackages({ 153 | cacheDir: '/cache', 154 | }); 155 | fs.writeFileSync('patches/package-a+0.1.0.patch', 'whatever', 'utf8'); 156 | const two = getDuplicatedPackages({ 157 | cacheDir: '/cache', 158 | }); 159 | const three = getDuplicatedPackages({ 160 | cacheDir: '/cache', 161 | }); 162 | expect(two).toEqual(three); 163 | 164 | // The best we can do without digging into internals is to make sure a cache entry was 165 | // created 166 | const cacheEntries = fs 167 | .readdirSync('/cache') 168 | .filter((filename) => /^duplicates-.*\.json$/.test(filename)); 169 | expect(cacheEntries).toHaveLength(2); 170 | }); 171 | 172 | it('should exclude patches', () => { 173 | mockFs({ 174 | ...nodeModulesMock, 175 | patches: { 176 | 'package-a+0.1.0.patch': '', 177 | }, 178 | }); 179 | const duplicates = getDuplicatedPackages(); 180 | mockFs.restore(); 181 | expect(duplicates).toEqual({ 182 | 'package-d@0.1.0': [ 183 | `${nodeModulesPrefix}/package-d`, 184 | `${nodeModulesPrefix}/package-d-duplicate`, 185 | ], 186 | }); 187 | }); 188 | 189 | it('should extract correct names from patches', () => { 190 | const patches = { 191 | 'eslint-plugin-formatjs+1.5.4.patch': 'eslint-plugin-formatjs@1.5.4', 192 | '@atlaskit+blanket+10.0.16.patch': '@atlaskit/blanket@10.0.16', 193 | '@atlaskit+blanket++@atlaskit+analytics-next+6.3.4.patch': 194 | '@atlaskit/analytics-next@6.3.4', 195 | }; 196 | 197 | Object.entries(patches).forEach(([patch, pkg]) => { 198 | expect(extractPackageName(patch, '')).toEqual(pkg); 199 | }); 200 | 201 | expect(extractPackageName('analytics-web-client+1.10.0.patch', '@atlassiansox')).toEqual( 202 | '@atlassiansox/analytics-web-client@1.10.0' 203 | ); 204 | }); 205 | }); 206 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] - [yyyy] Atlassian Pty Ltd 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------