UNPKG

929 BJavaScriptView Raw
1'use strict';
2
3const { URL } = require('url');
4
5/**
6 * Get unit from value node
7 *
8 * Returns `null` if the unit is not found.
9 *
10 * @param {string} urlString
11 */
12module.exports = function (urlString) {
13 let protocol = null;
14
15 try {
16 protocol = new URL(urlString).protocol;
17 } catch (err) {
18 return null;
19 }
20
21 if (protocol === null || typeof protocol === 'undefined') {
22 return null;
23 }
24
25 const scheme = protocol.slice(0, -1); // strip trailing `:`
26
27 // The URL spec does not require a scheme to be followed by `//`, but checking
28 // for it allows this rule to differentiate <scheme>:<hostname> urls from
29 // <hostname>:<port> urls. `data:` scheme urls are an exception to this rule.
30 const slashIndex = protocol.length;
31 const expectedSlashes = urlString.slice(slashIndex, slashIndex + 2);
32 const isSchemeLessUrl = expectedSlashes !== '//' && scheme !== 'data';
33
34 if (isSchemeLessUrl) {
35 return null;
36 }
37
38 return scheme;
39};