1 | 'use strict'
|
2 |
|
3 | const { validate } = require('./schema')
|
4 | const checkMethod = require('./checkMethod')
|
5 | const buildMatch = require('./buildMatch')
|
6 | const {
|
7 | $configurationInterface,
|
8 | $handlerMethod,
|
9 | $handlerSchema,
|
10 | $mappingChecked,
|
11 | $mappingMatch,
|
12 | $mappingMethod
|
13 | } = require('./symbols')
|
14 |
|
15 | function checkCwd (mapping) {
|
16 | if (!mapping.cwd) {
|
17 | mapping.cwd = process.cwd()
|
18 | }
|
19 | }
|
20 |
|
21 | function invalidMatch () {
|
22 | throw new Error('Invalid mapping match')
|
23 | }
|
24 |
|
25 | const 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 |
|
45 | function checkMatch (mapping) {
|
46 | matchTypes[typeof mapping.match](mapping, mapping.match)
|
47 | }
|
48 |
|
49 | function 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 |
|
56 | function 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 |
|
63 | function 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 |
|
71 | module.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 | }
|