index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const semver = require('semver')
  2. const currentEnv = require('./current-env')
  3. const { checkDevEngines } = require('./dev-engines')
  4. const checkEngine = (target, npmVer, nodeVer, force = false) => {
  5. const nodev = force ? null : nodeVer
  6. const eng = target.engines
  7. const opt = { includePrerelease: true }
  8. if (!eng) {
  9. return
  10. }
  11. const nodeFail = nodev && eng.node && !semver.satisfies(nodev, eng.node, opt)
  12. const npmFail = npmVer && eng.npm && !semver.satisfies(npmVer, eng.npm, opt)
  13. if (nodeFail || npmFail) {
  14. throw Object.assign(new Error('Unsupported engine'), {
  15. pkgid: target._id,
  16. current: { node: nodeVer, npm: npmVer },
  17. required: eng,
  18. code: 'EBADENGINE',
  19. })
  20. }
  21. }
  22. const checkPlatform = (target, force = false, environment = {}) => {
  23. if (force) {
  24. return
  25. }
  26. const os = environment.os || currentEnv.os()
  27. const cpu = environment.cpu || currentEnv.cpu()
  28. const libc = environment.libc || currentEnv.libc(os)
  29. const osOk = target.os ? checkList(os, target.os) : true
  30. const cpuOk = target.cpu ? checkList(cpu, target.cpu) : true
  31. let libcOk = target.libc ? checkList(libc, target.libc) : true
  32. if (target.libc && !libc) {
  33. libcOk = false
  34. }
  35. if (!osOk || !cpuOk || !libcOk) {
  36. throw Object.assign(new Error('Unsupported platform'), {
  37. pkgid: target._id,
  38. current: {
  39. os,
  40. cpu,
  41. libc,
  42. },
  43. required: {
  44. os: target.os,
  45. cpu: target.cpu,
  46. libc: target.libc,
  47. },
  48. code: 'EBADPLATFORM',
  49. })
  50. }
  51. }
  52. const checkList = (value, list) => {
  53. if (typeof list === 'string') {
  54. list = [list]
  55. }
  56. if (list.length === 1 && list[0] === 'any') {
  57. return true
  58. }
  59. // match none of the negated values, and at least one of the
  60. // non-negated values, if any are present.
  61. let negated = 0
  62. let match = false
  63. for (const entry of list) {
  64. const negate = entry.charAt(0) === '!'
  65. const test = negate ? entry.slice(1) : entry
  66. if (negate) {
  67. negated++
  68. if (value === test) {
  69. return false
  70. }
  71. } else {
  72. match = match || value === test
  73. }
  74. }
  75. return match || negated === list.length
  76. }
  77. module.exports = {
  78. checkEngine,
  79. checkPlatform,
  80. checkDevEngines,
  81. currentEnv,
  82. }