parseRangeHeader.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 'workbox-core/_private/WorkboxError.js';
  8. import { assert } from 'workbox-core/_private/assert.js';
  9. import '../_version.js';
  10. /**
  11. * @param {string} rangeHeader A Range: header value.
  12. * @return {Object} An object with `start` and `end` properties, reflecting
  13. * the parsed value of the Range: header. If either the `start` or `end` are
  14. * omitted, then `null` will be returned.
  15. *
  16. * @private
  17. */
  18. function parseRangeHeader(rangeHeader) {
  19. if (process.env.NODE_ENV !== 'production') {
  20. assert.isType(rangeHeader, 'string', {
  21. moduleName: 'workbox-range-requests',
  22. funcName: 'parseRangeHeader',
  23. paramName: 'rangeHeader',
  24. });
  25. }
  26. const normalizedRangeHeader = rangeHeader.trim().toLowerCase();
  27. if (!normalizedRangeHeader.startsWith('bytes=')) {
  28. throw new WorkboxError('unit-must-be-bytes', { normalizedRangeHeader });
  29. }
  30. // Specifying multiple ranges separate by commas is valid syntax, but this
  31. // library only attempts to handle a single, contiguous sequence of bytes.
  32. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax
  33. if (normalizedRangeHeader.includes(',')) {
  34. throw new WorkboxError('single-range-only', { normalizedRangeHeader });
  35. }
  36. const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader);
  37. // We need either at least one of the start or end values.
  38. if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {
  39. throw new WorkboxError('invalid-range-values', { normalizedRangeHeader });
  40. }
  41. return {
  42. start: rangeParts[1] === '' ? undefined : Number(rangeParts[1]),
  43. end: rangeParts[2] === '' ? undefined : Number(rangeParts[2]),
  44. };
  45. }
  46. export { parseRangeHeader };