You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.5 KiB

2 years ago
  1. 'use strict'
  2. let Declaration = require('./declaration')
  3. let PreviousMap = require('./previous-map')
  4. let Comment = require('./comment')
  5. let AtRule = require('./at-rule')
  6. let Input = require('./input')
  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