snapshot.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. var _typeof = require("@babel/runtime/helpers/typeof");
  4. Object.defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.createSnapshotFromFactories = createSnapshotFromFactories;
  8. exports.validateBundle = validateBundle;
  9. exports.validateTypeOf = void 0;
  10. var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
  11. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  12. var _assert = _interopRequireDefault(require("assert"));
  13. var allIsFunctions = _interopRequireWildcard(require("./is.js"));
  14. var _create = require("../core/create.js");
  15. var _string = require("./string.js");
  16. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  17. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  18. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
  19. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
  20. var validateTypeOf = allIsFunctions.typeOf;
  21. exports.validateTypeOf = validateTypeOf;
  22. function validateBundle(expectedBundleStructure, bundle) {
  23. var originalWarn = console.warn;
  24. console.warn = function () {
  25. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  26. args[_key] = arguments[_key];
  27. }
  28. if (args.join(' ').indexOf('is moved to') !== -1 && args.join(' ').indexOf('Please use the new location instead') !== -1) {
  29. // Ignore warnings like:
  30. // Warning: math.type.isNumber is moved to math.isNumber in v6.0.0. Please use the new location instead.
  31. return;
  32. }
  33. originalWarn.apply(console, args);
  34. };
  35. try {
  36. var issues = [];
  37. // see whether all expected functions and objects are there
  38. traverse(expectedBundleStructure, function (expectedType, path) {
  39. var actualValue = get(bundle, path);
  40. var actualType = validateTypeOf(actualValue);
  41. var message = actualType === 'undefined' ? 'Missing entry in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType) : 'Unexpected entry type in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType);
  42. if (actualType !== expectedType) {
  43. issues.push({
  44. actualType: actualType,
  45. expectedType: expectedType,
  46. message: message
  47. });
  48. console.warn(message);
  49. }
  50. });
  51. // see whether there are any functions or objects that shouldn't be there
  52. traverse(bundle, function (actualValue, path) {
  53. var actualType = validateTypeOf(actualValue);
  54. var expectedType = get(expectedBundleStructure, path) || 'undefined';
  55. // FIXME: ugly to have these special cases
  56. if (path.join('.').indexOf('docs.') !== -1) {
  57. // ignore the contents of docs
  58. return;
  59. }
  60. if (path.join('.').indexOf('all.') !== -1) {
  61. // ignore the contents of all dependencies
  62. return;
  63. }
  64. var message = expectedType === 'undefined' ? 'Unknown entry in bundle. ' + 'Is there a new function added which is missing in this snapshot test? ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType) : 'Unexpected entry type in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType);
  65. if (actualType !== expectedType) {
  66. issues.push({
  67. actualType: actualType,
  68. expectedType: expectedType,
  69. message: message
  70. });
  71. console.warn(message);
  72. }
  73. });
  74. // assert on the first issue (if any)
  75. if (issues.length > 0) {
  76. var _issues$ = issues[0],
  77. actualType = _issues$.actualType,
  78. expectedType = _issues$.expectedType,
  79. message = _issues$.message;
  80. console.warn("".concat(issues.length, " bundle issues found"));
  81. _assert["default"].strictEqual(actualType, expectedType, message);
  82. }
  83. } finally {
  84. console.warn = originalWarn;
  85. }
  86. }
  87. /**
  88. * Based on an object with factory functions, create the expected
  89. * structures for ES6 export and a mathjs instance.
  90. * @param {Object} factories
  91. * @return {{expectedInstanceStructure: Object, expectedES6Structure: Object}}
  92. */
  93. function createSnapshotFromFactories(factories) {
  94. var math = (0, _create.create)(factories);
  95. var allFactoryFunctions = {};
  96. var allFunctionsConstantsClasses = {};
  97. var allFunctionsConstants = {};
  98. var allTransformFunctions = {};
  99. var allDependencyCollections = {};
  100. var allClasses = {};
  101. var allNodeClasses = {};
  102. Object.keys(factories).forEach(function (factoryName) {
  103. var factory = factories[factoryName];
  104. var name = factory.fn;
  105. var isTransformFunction = factory.meta && factory.meta.isTransformFunction;
  106. var isClass = !isLowerCase(name[0]) && validateTypeOf(math[name]) === 'function';
  107. var dependenciesName = factory.fn + (isTransformFunction ? 'Transform' : '') + 'Dependencies';
  108. allFactoryFunctions[factoryName] = 'function';
  109. allFunctionsConstantsClasses[name] = validateTypeOf(math[name]);
  110. allDependencyCollections[dependenciesName] = 'Object';
  111. if (isTransformFunction) {
  112. allTransformFunctions[name] = 'function';
  113. }
  114. if (isClass) {
  115. if ((0, _string.endsWith)(name, 'Node')) {
  116. allNodeClasses[name] = 'function';
  117. } else {
  118. allClasses[name] = 'function';
  119. }
  120. } else {
  121. allFunctionsConstants[name] = validateTypeOf(math[name]);
  122. }
  123. });
  124. var embeddedDocs = {};
  125. Object.keys(factories).forEach(function (factoryName) {
  126. var factory = factories[factoryName];
  127. var name = factory.fn;
  128. if (isLowerCase(factory.fn[0])) {
  129. // ignore class names starting with upper case
  130. embeddedDocs[name] = 'Object';
  131. }
  132. });
  133. embeddedDocs = exclude(embeddedDocs, ['equalScalar', 'apply', 'addScalar', 'multiplyScalar', 'print', 'divideScalar', 'parse', 'compile', 'parser', 'chain', 'reviver', 'replacer']);
  134. var allTypeChecks = {};
  135. Object.keys(allIsFunctions).forEach(function (name) {
  136. if (name.indexOf('is') === 0) {
  137. allTypeChecks[name] = 'function';
  138. }
  139. });
  140. var allErrorClasses = {
  141. ArgumentsError: 'function',
  142. DimensionError: 'function',
  143. IndexError: 'function'
  144. };
  145. var expectedInstanceStructure = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, allFunctionsConstantsClasses), {}, {
  146. on: 'function',
  147. off: 'function',
  148. once: 'function',
  149. emit: 'function',
  150. "import": 'function',
  151. config: 'function',
  152. create: 'function',
  153. factory: 'function'
  154. }, allTypeChecks), allErrorClasses), {}, {
  155. expression: {
  156. transform: _objectSpread({}, allTransformFunctions),
  157. mathWithTransform: _objectSpread(_objectSpread({}, exclude(allFunctionsConstants, ['chain'])), {}, {
  158. config: 'function'
  159. })
  160. }
  161. });
  162. var expectedES6Structure = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, exclude(allFunctionsConstantsClasses, ['E', 'false', 'Infinity', 'NaN', 'null', 'PI', 'true'])), {}, {
  163. create: 'function',
  164. config: 'function',
  165. factory: 'function',
  166. _true: 'boolean',
  167. _false: 'boolean',
  168. _null: 'null',
  169. _Infinity: 'number',
  170. _NaN: 'number'
  171. }, allTypeChecks), allErrorClasses), allDependencyCollections), allFactoryFunctions), {}, {
  172. docs: embeddedDocs
  173. });
  174. return {
  175. expectedInstanceStructure: expectedInstanceStructure,
  176. expectedES6Structure: expectedES6Structure
  177. };
  178. }
  179. function traverse(obj) {
  180. var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (value, path) {};
  181. var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  182. // FIXME: ugly to have these special cases
  183. if (path.length > 0 && path[0].indexOf('Dependencies') !== -1) {
  184. // special case for objects holding a collection of dependencies
  185. callback(obj, path);
  186. } else if (validateTypeOf(obj) === 'Array') {
  187. obj.map(function (item, index) {
  188. return traverse(item, callback, path.concat(index));
  189. });
  190. } else if (validateTypeOf(obj) === 'Object') {
  191. Object.keys(obj).forEach(function (key) {
  192. // FIXME: ugly to have these special cases
  193. // ignore special case of deprecated docs
  194. if (key === 'docs' && path.join('.') === 'expression') {
  195. return;
  196. }
  197. traverse(obj[key], callback, path.concat(key));
  198. });
  199. } else {
  200. callback(obj, path);
  201. }
  202. }
  203. function get(object, path) {
  204. var child = object;
  205. for (var i = 0; i < path.length; i++) {
  206. var key = path[i];
  207. child = child ? child[key] : undefined;
  208. }
  209. return child;
  210. }
  211. /**
  212. * Create a copy of the provided `object` and delete
  213. * all properties listed in `excludedProperties`
  214. * @param {Object} object
  215. * @param {string[]} excludedProperties
  216. * @return {Object}
  217. */
  218. function exclude(object, excludedProperties) {
  219. var strippedObject = (0, _extends2["default"])({}, object);
  220. excludedProperties.forEach(function (excludedProperty) {
  221. delete strippedObject[excludedProperty];
  222. });
  223. return strippedObject;
  224. }
  225. function isLowerCase(text) {
  226. return typeof text === 'string' && text.toLowerCase() === text;
  227. }