concatenate.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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 { assert } from 'workbox-core/_private/assert.js';
  8. import { Deferred } from 'workbox-core/_private/Deferred.js';
  9. import { logger } from 'workbox-core/_private/logger.js';
  10. import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
  11. import './_version.js';
  12. /**
  13. * Takes either a Response, a ReadableStream, or a
  14. * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the
  15. * ReadableStreamReader object associated with it.
  16. *
  17. * @param {workbox-streams.StreamSource} source
  18. * @return {ReadableStreamReader}
  19. * @private
  20. */
  21. function _getReaderFromSource(source) {
  22. if (source instanceof Response) {
  23. // See https://github.com/GoogleChrome/workbox/issues/2998
  24. if (source.body) {
  25. return source.body.getReader();
  26. }
  27. throw new WorkboxError('opaque-streams-source', { type: source.type });
  28. }
  29. if (source instanceof ReadableStream) {
  30. return source.getReader();
  31. }
  32. return new Response(source).body.getReader();
  33. }
  34. /**
  35. * Takes multiple source Promises, each of which could resolve to a Response, a
  36. * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit).
  37. *
  38. * Returns an object exposing a ReadableStream with each individual stream's
  39. * data returned in sequence, along with a Promise which signals when the
  40. * stream is finished (useful for passing to a FetchEvent's waitUntil()).
  41. *
  42. * @param {Array<Promise<workbox-streams.StreamSource>>} sourcePromises
  43. * @return {Object<{done: Promise, stream: ReadableStream}>}
  44. *
  45. * @memberof workbox-streams
  46. */
  47. function concatenate(sourcePromises) {
  48. if (process.env.NODE_ENV !== 'production') {
  49. assert.isArray(sourcePromises, {
  50. moduleName: 'workbox-streams',
  51. funcName: 'concatenate',
  52. paramName: 'sourcePromises',
  53. });
  54. }
  55. const readerPromises = sourcePromises.map((sourcePromise) => {
  56. return Promise.resolve(sourcePromise).then((source) => {
  57. return _getReaderFromSource(source);
  58. });
  59. });
  60. const streamDeferred = new Deferred();
  61. let i = 0;
  62. const logMessages = [];
  63. const stream = new ReadableStream({
  64. pull(controller) {
  65. return readerPromises[i]
  66. .then((reader) => {
  67. if (reader instanceof ReadableStreamDefaultReader) {
  68. return reader.read();
  69. }
  70. else {
  71. return;
  72. }
  73. })
  74. .then((result) => {
  75. if (result === null || result === void 0 ? void 0 : result.done) {
  76. if (process.env.NODE_ENV !== 'production') {
  77. logMessages.push([
  78. 'Reached the end of source:',
  79. sourcePromises[i],
  80. ]);
  81. }
  82. i++;
  83. if (i >= readerPromises.length) {
  84. // Log all the messages in the group at once in a single group.
  85. if (process.env.NODE_ENV !== 'production') {
  86. logger.groupCollapsed(`Concatenating ${readerPromises.length} sources.`);
  87. for (const message of logMessages) {
  88. if (Array.isArray(message)) {
  89. logger.log(...message);
  90. }
  91. else {
  92. logger.log(message);
  93. }
  94. }
  95. logger.log('Finished reading all sources.');
  96. logger.groupEnd();
  97. }
  98. controller.close();
  99. streamDeferred.resolve();
  100. return;
  101. }
  102. // The `pull` method is defined because we're inside it.
  103. return this.pull(controller);
  104. }
  105. else {
  106. controller.enqueue(result === null || result === void 0 ? void 0 : result.value);
  107. }
  108. })
  109. .catch((error) => {
  110. if (process.env.NODE_ENV !== 'production') {
  111. logger.error('An error occurred:', error);
  112. }
  113. streamDeferred.reject(error);
  114. throw error;
  115. });
  116. },
  117. cancel() {
  118. if (process.env.NODE_ENV !== 'production') {
  119. logger.warn('The ReadableStream was cancelled.');
  120. }
  121. streamDeferred.resolve();
  122. },
  123. });
  124. return { done: streamDeferred.promise, stream };
  125. }
  126. export { concatenate };