assert.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, expectedClass, details) => {
  34. if (!(object instanceof expectedClass)) {
  35. details['expectedClass'] = expectedClass;
  36. throw new WorkboxError('incorrect-class', details);
  37. }
  38. };
  39. const isOneOf = (value, validValues, details) => {
  40. if (!validValues.includes(value)) {
  41. details['validValueDescription'] =
  42. `Valid values are ${JSON.stringify(validValues)}.`;
  43. throw new WorkboxError('invalid-value', details);
  44. }
  45. };
  46. const isArrayOfClass = (value, expectedClass, details) => {
  47. const error = new WorkboxError('not-array-of-class', details);
  48. if (!Array.isArray(value)) {
  49. throw error;
  50. }
  51. for (const item of value) {
  52. if (!(item instanceof expectedClass)) {
  53. throw error;
  54. }
  55. }
  56. };
  57. const finalAssertExports = process.env.NODE_ENV === 'production' ? null : {
  58. hasMethod,
  59. isArray,
  60. isInstance,
  61. isOneOf,
  62. isType,
  63. isArrayOfClass,
  64. };
  65. export { finalAssertExports as assert };