UNPKG

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