UNPKG

2.13 kBJavaScriptView Raw
1'use strict'
2
3const { validate } = require('./schema')
4const checkMethod = require('./checkMethod')
5const buildMatch = require('./buildMatch')
6const {
7 $configurationInterface,
8 $handlerMethod,
9 $handlerSchema,
10 $mappingChecked,
11 $mappingMatch,
12 $mappingMethod
13} = require('./symbols')
14
15function checkCwd (mapping) {
16 if (!mapping.cwd) {
17 mapping.cwd = process.cwd()
18 }
19}
20
21function invalidMatch () {
22 throw new Error('Invalid mapping match')
23}
24
25const matchTypes = {
26 undefined: mapping => {
27 mapping.match = /(.*)/
28 },
29 string: (mapping, match) => {
30 mapping.match = new RegExp(mapping.match)
31 },
32 object: (mapping, match) => {
33 if (!(mapping.match instanceof RegExp)) {
34 invalidMatch()
35 }
36 }
37}
38
39'boolean,number,bigint,symbol,function'
40 .split(',')
41 .forEach(type => {
42 matchTypes[type] = invalidMatch
43 })
44
45function checkMatch (mapping) {
46 matchTypes[typeof mapping.match](mapping, mapping.match)
47}
48
49function checkInvertMatch (mapping) {
50 const invertMatch = mapping['invert-match']
51 if (invertMatch !== undefined && invertMatch !== true) {
52 throw new Error('Invalid mapping invert-match')
53 }
54}
55
56function checkIfMatch (mapping) {
57 const ifMatch = mapping['if-match']
58 if (!['undefined', 'function'].includes(typeof ifMatch)) {
59 throw new Error('Invalid mapping if-match')
60 }
61}
62
63function checkHandler (configuration, mapping) {
64 const { handler } = configuration.handler(mapping)
65 if (!handler) {
66 throw new Error('Unknown handler for mapping: ' + JSON.stringify(mapping))
67 }
68 return handler
69}
70
71module.exports = {
72 async check (configuration, mapping) {
73 checkCwd(mapping)
74 checkMatch(mapping)
75 checkInvertMatch(mapping)
76 checkIfMatch(mapping)
77 const handler = checkHandler(configuration, mapping)
78 checkMethod(mapping, $mappingMethod, handler[$handlerMethod])
79 if (handler[$handlerSchema]) {
80 validate(handler[$handlerSchema], mapping)
81 }
82 if (handler.validate) {
83 await handler.validate(mapping, configuration[$configurationInterface])
84 }
85 mapping[$mappingMatch] = buildMatch(mapping)
86 mapping[$mappingChecked] = true
87 }
88}