1. 1 : /**
  2. 2 : * @module filter-source
  3. 3 : */
  4. 4 : import {isObject} from './obj';
  5. 5 : import {getMimetype} from './mimetypes';
  6. 6 :
  7. 7 : /**
  8. 8 : * Filter out single bad source objects or multiple source objects in an
  9. 9 : * array. Also flattens nested source object arrays into a 1 dimensional
  10. 10 : * array of source objects.
  11. 11 : *
  12. 12 : * @param {Tech~SourceObject|Tech~SourceObject[]} src
  13. 13 : * The src object to filter
  14. 14 : *
  15. 15 : * @return {Tech~SourceObject[]}
  16. 16 : * An array of sourceobjects containing only valid sources
  17. 17 : *
  18. 18 : * @private
  19. 19 : */
  20. 20 : const filterSource = function(src) {
  21. 21 : // traverse array
  22. 22 : if (Array.isArray(src)) {
  23. 23 : let newsrc = [];
  24. 24 :
  25. 25 : src.forEach(function(srcobj) {
  26. 26 : srcobj = filterSource(srcobj);
  27. 27 :
  28. 28 : if (Array.isArray(srcobj)) {
  29. 29 : newsrc = newsrc.concat(srcobj);
  30. 30 : } else if (isObject(srcobj)) {
  31. 31 : newsrc.push(srcobj);
  32. 32 : }
  33. 33 : });
  34. 34 :
  35. 35 : src = newsrc;
  36. 36 : } else if (typeof src === 'string' && src.trim()) {
  37. 37 : // convert string into object
  38. 38 : src = [fixSource({src})];
  39. 39 : } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  40. 40 : // src is already valid
  41. 41 : src = [fixSource(src)];
  42. 42 : } else {
  43. 43 : // invalid source, turn it into an empty array
  44. 44 : src = [];
  45. 45 : }
  46. 46 :
  47. 47 : return src;
  48. 48 : };
  49. 49 :
  50. 50 : /**
  51. 51 : * Checks src mimetype, adding it when possible
  52. 52 : *
  53. 53 : * @param {Tech~SourceObject} src
  54. 54 : * The src object to check
  55. 55 : * @return {Tech~SourceObject}
  56. 56 : * src Object with known type
  57. 57 : */
  58. 58 : function fixSource(src) {
  59. 59 : if (!src.type) {
  60. 60 : const mimetype = getMimetype(src.src);
  61. 61 :
  62. 62 : if (mimetype) {
  63. 63 : src.type = mimetype;
  64. 64 : }
  65. 65 : }
  66. 66 :
  67. 67 : return src;
  68. 68 : }
  69. 69 :
  70. 70 : export default filterSource;