update-package-json.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict'
  2. var path = require('path')
  3. var writeFileAtomic = require('write-file-atomic')
  4. var moduleName = require('../utils/module-name.js')
  5. var deepSortObject = require('../utils/deep-sort-object.js')
  6. var sortedObject = require('sorted-object')
  7. var isWindows = require('../utils/is-windows.js')
  8. var sortKeys = [
  9. 'dependencies', 'devDependencies', 'bundleDependencies',
  10. 'optionalDependencies', 'keywords', 'engines', 'scripts',
  11. 'files'
  12. ]
  13. module.exports = function (mod, buildpath, next) {
  14. var pkg = sortedObject(mod.package)
  15. var name = moduleName(mod)
  16. // Add our diagnostic keys to the package.json.
  17. // Note that there are folks relying on these, for ex, the Visual Studio
  18. // Node.js addon.
  19. pkg._requiredBy =
  20. mod.requiredBy
  21. .map(function (req) {
  22. if (
  23. req.package.devDependencies &&
  24. req.package.devDependencies[name] &&
  25. !req.package.dependencies[name]
  26. ) {
  27. return '#DEV:' + req.location
  28. } else {
  29. return req.location
  30. }
  31. })
  32. .concat(mod.userRequired ? ['#USER'] : [])
  33. .sort()
  34. pkg._location = mod.location
  35. pkg._phantomChildren = {}
  36. Object.keys(mod.phantomChildren).sort().forEach(function (name) {
  37. pkg._phantomChildren[name] = mod.phantomChildren[name].package.version
  38. })
  39. pkg._inBundle = !!mod.fromBundle
  40. // sort keys that are known safe to sort to produce more consistent output
  41. sortKeys.forEach(function (key) {
  42. if (pkg[key] != null) pkg[key] = deepSortObject(pkg[key])
  43. })
  44. var data = JSON.stringify(sortedObject(pkg), null, 2) + '\n'
  45. writeFileAtomic(path.resolve(buildpath, 'package.json'), data, {
  46. // We really don't need this guarantee, and fsyncing here is super slow. Except on
  47. // Windows where there isn't a big performance difference and it prevents errors when
  48. // rolling back optional packages (#17671)
  49. fsync: isWindows
  50. }, next)
  51. }