assert.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import { WorkboxError } from '../_private/WorkboxError.js';
  8. import '../_version.js';
  9. /*
  10. * This method throws if the supplied value is not an array.
  11. * The destructed values are required to produce a meaningful error for users.
  12. * The destructed and restructured object is so it's clear what is
  13. * needed.
  14. */
  15. const isArray = (value, details) => {
  16. if (!Array.isArray(value)) {
  17. throw new WorkboxError('not-an-array', details);
  18. }
  19. };
  20. const hasMethod = (object, expectedMethod, details) => {
  21. const type = typeof object[expectedMethod];
  22. if (type !== 'function') {
  23. details['expectedMethod'] = expectedMethod;
  24. throw new WorkboxError('missing-a-method', details);
  25. }
  26. };
  27. const isType = (object, expectedType, details) => {
  28. if (typeof object !== expectedType) {
  29. details['expectedType'] = expectedType;
  30. throw new WorkboxError('incorrect-type', details);
  31. }
  32. };
  33. const isInstance = (object,
  34. // Need the general type to do the check later.
  35. // eslint-disable-next-line @typescript-eslint/ban-types
  36. expectedClass, details) => {
  37. if (!(object instanceof expectedClass)) {
  38. details['expectedClassName'] = expectedClass.name;
  39. throw new WorkboxError('incorrect-class', details);
  40. }
  41. };
  42. const isOneOf = (value, validValues, details) => {
  43. if (!validValues.includes(value)) {
  44. details['validValueDescription'] = `Valid values are ${JSON.stringify(validValues)}.`;
  45. throw new WorkboxError('invalid-value', details);
  46. }
  47. };
  48. const isArrayOfClass = (value,
  49. // Need general type to do check later.
  50. expectedClass, // eslint-disable-line
  51. details) => {
  52. const error = new WorkboxError('not-array-of-class', details);
  53. if (!Array.isArray(value)) {
  54. throw error;
  55. }
  56. for (const item of value) {
  57. if (!(item instanceof expectedClass)) {
  58. throw error;
  59. }
  60. }
  61. };
  62. const finalAssertExports = process.env.NODE_ENV === 'production'
  63. ? null
  64. : {
  65. hasMethod,
  66. isArray,
  67. isInstance,
  68. isOneOf,
  69. isType,
  70. isArrayOfClass,
  71. };
  72. export { finalAssertExports as assert };