UNPKG

2.63 kBJavaScriptView Raw
1// https://tools.ietf.org/html/rfc7540#section-5.3.5
2// All streams are initially assigned a non-exclusive dependency on
3// stream 0x0. Pushed streams (Section 8.2) initially depend on their
4// associated stream. In both cases, streams are assigned a default
5// weight of 16.
6const DEFAULT_PRIORITY = 16
7
8function isUri (value) {
9 return typeof value === 'string' && value.startsWith('https://')
10}
11
12function isGlob (value) {
13 return typeof value === 'string' && !value.startsWith('https://')
14}
15
16function validRule ({get, push}) {
17 return push.length && get.length
18}
19
20function validLookup ({uri, glob}) {
21 return (uri && uri.length) || (glob && glob.length)
22}
23
24module.exports.normalise =
25function (manifest) {
26 return (manifest || []).map((rule) => {
27 for (const key of ['get', 'uri', 'glob', 'push']) {
28 if (typeof rule[key] === 'string') rule[key] = [rule[key]]
29 }
30
31 for (const key of ['get', 'push']) {
32 if (!Array.isArray(rule[key])) {
33 if (rule[key] === undefined) rule[key] = []
34 else rule[key] = [rule[key]]
35 }
36 }
37
38 if (rule.get.length > 0 && rule.get.every(isGlob)) {
39 rule.get = [{glob: rule.get}]
40 } else {
41 rule.get = rule.get.map((dep) => {
42 if (typeof dep === 'string') {
43 if (dep.startsWith('https://')) dep = {uri: [dep]}
44 else dep = {glob: [dep]}
45 }
46 if (typeof dep.uri === 'string') dep.uri = [dep.uri]
47 if (typeof dep.glob === 'string') dep.glob = [dep.glob]
48 return dep
49 }).filter(validLookup)
50 }
51
52 for (const key of ['uri', 'glob']) {
53 if (key in rule) {
54 if (rule[key].length > 0) {
55 rule.get.push({[key]: rule[key]})
56 }
57 delete rule[key]
58 }
59 }
60
61 if (rule.push.length > 0 && rule.push.every(isGlob)) {
62 rule.push = [{
63 priority: DEFAULT_PRIORITY,
64 glob: Array.from(rule.push)
65 }]
66 } else {
67 rule.push = rule.push.map((dep) => {
68 if (Array.isArray(dep)) {
69 const uris = dep.filter(isUri)
70 const globs = dep.filter(isGlob)
71 dep = {}
72 if (uris.length) dep.uri = uris
73 if (globs.length) dep.glob = globs
74 }
75 if (typeof dep === 'string') {
76 if (dep.startsWith('https://')) dep = {uri: [dep]}
77 else dep = {glob: [dep]}
78 }
79 if (typeof dep.uri === 'string') dep.uri = [dep.uri]
80 if (typeof dep.glob === 'string') dep.glob = [dep.glob]
81 if (typeof dep.priority !== 'number') dep.priority = DEFAULT_PRIORITY
82 return dep
83 }).filter(validLookup)
84 }
85 return rule
86 }).filter(validRule)
87}