fromJSON.js 1.5 KB

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