UNPKG

1.51 kBJavaScriptView Raw
1'use strict'
2
3let Declaration = require('./declaration')
4let PreviousMap = require('./previous-map')
5let Comment = require('./comment')
6let AtRule = require('./at-rule')
7let Input = require('./input')
8let Root = require('./root')
9let Rule = require('./rule')
10
11function fromJSON(json, inputs) {
12 if (Array.isArray(json)) return json.map(n => fromJSON(n))
13
14 let { inputs: ownInputs, ...defaults } = json
15 if (ownInputs) {
16 inputs = []
17 for (let input of ownInputs) {
18 let inputHydrated = { ...input, __proto__: Input.prototype }
19 if (inputHydrated.map) {
20 inputHydrated.map = {
21 ...inputHydrated.map,
22 __proto__: PreviousMap.prototype
23 }
24 }
25 inputs.push(inputHydrated)
26 }
27 }
28 if (defaults.nodes) {
29 defaults.nodes = json.nodes.map(n => fromJSON(n, inputs))
30 }
31 if (defaults.source) {
32 let { inputId, ...source } = defaults.source
33 defaults.source = source
34 if (inputId != null) {
35 defaults.source.input = inputs[inputId]
36 }
37 }
38 if (defaults.type === 'root') {
39 return new Root(defaults)
40 } else if (defaults.type === 'decl') {
41 return new Declaration(defaults)
42 } else if (defaults.type === 'rule') {
43 return new Rule(defaults)
44 } else if (defaults.type === 'comment') {
45 return new Comment(defaults)
46 } else if (defaults.type === 'atrule') {
47 return new AtRule(defaults)
48 } else {
49 throw new Error('Unknown node type: ' + json.type)
50 }
51}
52
53module.exports = fromJSON
54fromJSON.default = fromJSON