UNPKG

2.59 kBJavaScriptView Raw
1'use strict'
2const { builtinModules: builtins } = require('module')
3
4var scopedPackagePattern = new RegExp('^(?:@([^/]+?)[/])?([^/]+?)$')
5var blacklist = [
6 'node_modules',
7 'favicon.ico',
8]
9
10function validate (name) {
11 var warnings = []
12 var errors = []
13
14 if (name === null) {
15 errors.push('name cannot be null')
16 return done(warnings, errors)
17 }
18
19 if (name === undefined) {
20 errors.push('name cannot be undefined')
21 return done(warnings, errors)
22 }
23
24 if (typeof name !== 'string') {
25 errors.push('name must be a string')
26 return done(warnings, errors)
27 }
28
29 if (!name.length) {
30 errors.push('name length must be greater than zero')
31 }
32
33 if (name.match(/^\./)) {
34 errors.push('name cannot start with a period')
35 }
36
37 if (name.match(/^_/)) {
38 errors.push('name cannot start with an underscore')
39 }
40
41 if (name.trim() !== name) {
42 errors.push('name cannot contain leading or trailing spaces')
43 }
44
45 // No funny business
46 blacklist.forEach(function (blacklistedName) {
47 if (name.toLowerCase() === blacklistedName) {
48 errors.push(blacklistedName + ' is a blacklisted name')
49 }
50 })
51
52 // Generate warnings for stuff that used to be allowed
53
54 // core module names like http, events, util, etc
55 if (builtins.includes(name.toLowerCase())) {
56 warnings.push(name + ' is a core module name')
57 }
58
59 if (name.length > 214) {
60 warnings.push('name can no longer contain more than 214 characters')
61 }
62
63 // mIxeD CaSe nAMEs
64 if (name.toLowerCase() !== name) {
65 warnings.push('name can no longer contain capital letters')
66 }
67
68 if (/[~'!()*]/.test(name.split('/').slice(-1)[0])) {
69 warnings.push('name can no longer contain special characters ("~\'!()*")')
70 }
71
72 if (encodeURIComponent(name) !== name) {
73 // Maybe it's a scoped package name, like @user/package
74 var nameMatch = name.match(scopedPackagePattern)
75 if (nameMatch) {
76 var user = nameMatch[1]
77 var pkg = nameMatch[2]
78 if (encodeURIComponent(user) === user && encodeURIComponent(pkg) === pkg) {
79 return done(warnings, errors)
80 }
81 }
82
83 errors.push('name can only contain URL-friendly characters')
84 }
85
86 return done(warnings, errors)
87}
88
89var done = function (warnings, errors) {
90 var result = {
91 validForNewPackages: errors.length === 0 && warnings.length === 0,
92 validForOldPackages: errors.length === 0,
93 warnings: warnings,
94 errors: errors,
95 }
96 if (!result.warnings.length) {
97 delete result.warnings
98 }
99 if (!result.errors.length) {
100 delete result.errors
101 }
102 return result
103}
104
105module.exports = validate