{"version":3,"sources":["../../../../src/server/stream-utils/node-web-streams-helper.ts"],"sourcesContent":["import type { ReactDOMServerReadableStream } from 'react-dom/server'\nimport { getTracer } from '../lib/trace/tracer'\nimport { AppRenderSpan } from '../lib/trace/constants'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport {\n  scheduleImmediate,\n  atLeastOneTask,\n  waitAtLeastOneReactRenderTask,\n} from '../../lib/scheduler'\nimport { ENCODED_TAGS } from './encoded-tags'\nimport {\n  indexOfUint8Array,\n  isEquivalentUint8Arrays,\n  removeFromUint8Array,\n} from './uint8array-helpers'\nimport { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants'\nimport {\n  RSC_HEADER,\n  NEXT_ROUTER_PREFETCH_HEADER,\n  NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n  NEXT_RSC_UNION_QUERY,\n  NEXT_INSTANT_PREFETCH_HEADER,\n} from '../../client/components/app-router-headers'\nimport { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'\n\nfunction voidCatch() {\n  // this catcher is designed to be used with pipeTo where we expect the underlying\n  // pipe implementation to forward errors but we don't want the pipeTo promise to reject\n  // and be unhandled\n}\n\n// We can share the same encoder instance everywhere\n// Notably we cannot do the same for TextDecoder because it is stateful\n// when handling streaming data\nconst encoder = new TextEncoder()\n\nexport function chainStreams<T>(\n  ...streams: ReadableStream<T>[]\n): ReadableStream<T> {\n  // If we have no streams, return an empty stream. This behavior is\n  // intentional as we're now providing the `RenderResult.EMPTY` value.\n  if (streams.length === 0) {\n    return new ReadableStream<T>({\n      start(controller) {\n        controller.close()\n      },\n    })\n  }\n\n  // If we only have 1 stream we fast path it by returning just this stream\n  if (streams.length === 1) {\n    return streams[0]\n  }\n\n  const { readable, writable } = new TransformStream()\n\n  // We always initiate pipeTo immediately. We know we have at least 2 streams\n  // so we need to avoid closing the writable when this one finishes.\n  let promise = streams[0].pipeTo(writable, { preventClose: true })\n\n  let i = 1\n  for (; i < streams.length - 1; i++) {\n    const nextStream = streams[i]\n    promise = promise.then(() =>\n      nextStream.pipeTo(writable, { preventClose: true })\n    )\n  }\n\n  // We can omit the length check because we halted before the last stream and there\n  // is at least two streams so the lastStream here will always be defined\n  const lastStream = streams[i]\n  promise = promise.then(() => lastStream.pipeTo(writable))\n\n  // Catch any errors from the streams and ignore them, they will be handled\n  // by whatever is consuming the readable stream.\n  promise.catch(voidCatch)\n\n  return readable\n}\n\nexport function streamFromString(str: string): ReadableStream<Uint8Array> {\n  return new ReadableStream({\n    start(controller) {\n      controller.enqueue(encoder.encode(str))\n      controller.close()\n    },\n  })\n}\n\nexport function streamFromBuffer(chunk: Buffer): ReadableStream<Uint8Array> {\n  return new ReadableStream({\n    start(controller) {\n      controller.enqueue(chunk)\n      controller.close()\n    },\n  })\n}\n\nasync function streamToChunks(\n  stream: ReadableStream<Uint8Array>\n): Promise<Array<Uint8Array>> {\n  const reader = stream.getReader()\n  const chunks: Array<Uint8Array> = []\n\n  while (true) {\n    const { done, value } = await reader.read()\n    if (done) {\n      break\n    }\n\n    chunks.push(value)\n  }\n\n  return chunks\n}\n\nfunction concatUint8Arrays(chunks: Array<Uint8Array>): Uint8Array {\n  const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0)\n  const result = new Uint8Array(totalLength)\n  let offset = 0\n  for (const chunk of chunks) {\n    result.set(chunk, offset)\n    offset += chunk.length\n  }\n  return result\n}\n\nexport async function streamToUint8Array(\n  stream: ReadableStream<Uint8Array>\n): Promise<Uint8Array> {\n  return concatUint8Arrays(await streamToChunks(stream))\n}\n\nexport async function streamToBuffer(\n  stream: ReadableStream<Uint8Array>\n): Promise<Buffer> {\n  return Buffer.concat(await streamToChunks(stream))\n}\n\nexport async function streamToString(\n  stream: ReadableStream<Uint8Array>,\n  signal?: AbortSignal\n): Promise<string> {\n  const decoder = new TextDecoder('utf-8', { fatal: true })\n  let string = ''\n\n  for await (const chunk of stream) {\n    if (signal?.aborted) {\n      return string\n    }\n\n    string += decoder.decode(chunk, { stream: true })\n  }\n\n  string += decoder.decode()\n\n  return string\n}\n\nexport type BufferedTransformOptions = {\n  /**\n   * Flush synchronously once the buffer reaches this many bytes.\n   */\n  readonly maxBufferByteLength?: number\n}\n\nexport function createBufferedTransformStream(\n  options: BufferedTransformOptions = {}\n): TransformStream<Uint8Array, Uint8Array> {\n  const { maxBufferByteLength = Infinity } = options\n\n  let bufferedChunks: Array<Uint8Array> = []\n  let bufferByteLength: number = 0\n  let pending: DetachedPromise<void> | undefined\n\n  const flush = (controller: TransformStreamDefaultController) => {\n    try {\n      if (bufferedChunks.length === 0) {\n        return\n      }\n\n      const chunk = new Uint8Array(bufferByteLength)\n      let copiedBytes = 0\n\n      for (let i = 0; i < bufferedChunks.length; i++) {\n        const bufferedChunk = bufferedChunks[i]\n        chunk.set(bufferedChunk, copiedBytes)\n        copiedBytes += bufferedChunk.byteLength\n      }\n      // We just wrote all the buffered chunks so we need to reset the bufferedChunks array\n      // and our bufferByteLength to prepare for the next round of buffered chunks\n      bufferedChunks.length = 0\n      bufferByteLength = 0\n      controller.enqueue(chunk)\n    } catch {\n      // If an error occurs while enqueuing, it can't be due to this\n      // transformer. It's most likely caused by the controller having been\n      // errored (for example, if the stream was cancelled).\n    }\n  }\n\n  const scheduleFlush = (controller: TransformStreamDefaultController) => {\n    if (pending) {\n      return\n    }\n\n    const detached = new DetachedPromise<void>()\n    pending = detached\n\n    scheduleImmediate(() => {\n      try {\n        flush(controller)\n      } finally {\n        pending = undefined\n        detached.resolve()\n      }\n    })\n  }\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      // Combine the previous buffer with the new chunk.\n      bufferedChunks.push(chunk)\n      bufferByteLength += chunk.byteLength\n\n      if (bufferByteLength >= maxBufferByteLength) {\n        flush(controller)\n      } else {\n        scheduleFlush(controller)\n      }\n    },\n    flush() {\n      return pending?.promise\n    },\n  })\n}\n\n// TODO this is currently unused but once we add proper output:export support, it needs to be\n// revisited. See https://github.com/vercel/next.js/pull/89478 for more details\n//\n// function createPrefetchCommentStream(\n//   isBuildTimePrerendering: boolean,\n//   buildId: string\n// ): TransformStream<Uint8Array, Uint8Array> {\n//   // Insert an extra comment at the beginning of the HTML document. This must\n//   // come after the DOCTYPE, which is inserted by React.\n//   //\n//   // The first chunk sent by React will contain the doctype. After that, we can\n//   // pass through the rest of the chunks as-is.\n//   let didTransformFirstChunk = false\n//   return new TransformStream({\n//     transform(chunk, controller) {\n//       if (isBuildTimePrerendering && !didTransformFirstChunk) {\n//         didTransformFirstChunk = true\n//         const decoder = new TextDecoder('utf-8', { fatal: true })\n//         const chunkStr = decoder.decode(chunk, {\n//           stream: true,\n//         })\n//         const updatedChunkStr = insertBuildIdComment(chunkStr, buildId)\n//         controller.enqueue(encoder.encode(updatedChunkStr))\n//         return\n//       }\n//       controller.enqueue(chunk)\n//     },\n//   })\n// }\n\nexport function renderToInitialFizzStream({\n  ReactDOMServer,\n  element,\n  streamOptions,\n}: {\n  ReactDOMServer: {\n    renderToReadableStream: typeof import('react-dom/server').renderToReadableStream\n  }\n  element: React.ReactElement\n  streamOptions?: Parameters<typeof ReactDOMServer.renderToReadableStream>[1]\n}): Promise<ReactDOMServerReadableStream> {\n  return getTracer().trace(AppRenderSpan.renderToReadableStream, async () =>\n    ReactDOMServer.renderToReadableStream(element, streamOptions)\n  )\n}\n\nfunction createMetadataTransformStream(\n  insert: () => Promise<string> | string\n): TransformStream<Uint8Array, Uint8Array> {\n  let chunkIndex = -1\n  let isMarkRemoved = false\n\n  return new TransformStream({\n    async transform(chunk, controller) {\n      let iconMarkIndex = -1\n      let closedHeadIndex = -1\n      chunkIndex++\n\n      if (isMarkRemoved) {\n        controller.enqueue(chunk)\n        return\n      }\n      let iconMarkLength = 0\n      // Only search for the closed head tag once\n      if (iconMarkIndex === -1) {\n        iconMarkIndex = indexOfUint8Array(chunk, ENCODED_TAGS.META.ICON_MARK)\n        if (iconMarkIndex === -1) {\n          controller.enqueue(chunk)\n          return\n        } else {\n          // When we found the `<meta name=\"«nxt-icon»\"` tag prefix, we will remove it from the chunk.\n          // Its close tag could either be `/>` or `>`, checking the next char to ensure we cover both cases.\n          iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length\n          // Check if next char is /, this is for xml mode.\n          if (chunk[iconMarkIndex + iconMarkLength] === 47) {\n            iconMarkLength += 2\n          } else {\n            // The last char is `>`\n            iconMarkLength++\n          }\n        }\n      }\n\n      // Check if icon mark is inside <head> tag in the first chunk.\n      if (chunkIndex === 0) {\n        closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)\n        if (iconMarkIndex !== -1) {\n          // The mark icon is located in the 1st chunk before the head tag.\n          // We do not need to insert the script tag in this case because it's in the head.\n          // Just remove the icon mark from the chunk.\n          if (iconMarkIndex < closedHeadIndex) {\n            const replaced = new Uint8Array(chunk.length - iconMarkLength)\n\n            // Remove the icon mark from the chunk.\n            replaced.set(chunk.subarray(0, iconMarkIndex))\n            replaced.set(\n              chunk.subarray(iconMarkIndex + iconMarkLength),\n              iconMarkIndex\n            )\n            chunk = replaced\n          } else {\n            // The icon mark is after the head tag, replace and insert the script tag at that position.\n            const insertion = await insert()\n            const encodedInsertion = encoder.encode(insertion)\n            const insertionLength = encodedInsertion.length\n            const replaced = new Uint8Array(\n              chunk.length - iconMarkLength + insertionLength\n            )\n            replaced.set(chunk.subarray(0, iconMarkIndex))\n            replaced.set(encodedInsertion, iconMarkIndex)\n            replaced.set(\n              chunk.subarray(iconMarkIndex + iconMarkLength),\n              iconMarkIndex + insertionLength\n            )\n            chunk = replaced\n          }\n          isMarkRemoved = true\n        }\n        // If there's no icon mark located, it will be handled later when if present in the following chunks.\n      } else {\n        // When it's appeared in the following chunks, we'll need to\n        // remove the mark and then insert the script tag at that position.\n        const insertion = await insert()\n        const encodedInsertion = encoder.encode(insertion)\n        const insertionLength = encodedInsertion.length\n        // Replace the icon mark with the hoist script or empty string.\n        const replaced = new Uint8Array(\n          chunk.length - iconMarkLength + insertionLength\n        )\n        // Set the first part of the chunk, before the icon mark.\n        replaced.set(chunk.subarray(0, iconMarkIndex))\n        // Set the insertion after the icon mark.\n        replaced.set(encodedInsertion, iconMarkIndex)\n\n        // Set the rest of the chunk after the icon mark.\n        replaced.set(\n          chunk.subarray(iconMarkIndex + iconMarkLength),\n          iconMarkIndex + insertionLength\n        )\n        chunk = replaced\n        isMarkRemoved = true\n      }\n      controller.enqueue(chunk)\n    },\n  })\n}\n\nfunction createHeadInsertionTransformStream(\n  insert: () => Promise<string>\n): TransformStream<Uint8Array, Uint8Array> {\n  let inserted = false\n\n  // We need to track if this transform saw any bytes because if it didn't\n  // we won't want to insert any server HTML at all\n  let hasBytes = false\n\n  return new TransformStream({\n    async transform(chunk, controller) {\n      hasBytes = true\n\n      const insertion = await insert()\n      if (inserted) {\n        if (insertion) {\n          const encodedInsertion = encoder.encode(insertion)\n          controller.enqueue(encodedInsertion)\n        }\n        controller.enqueue(chunk)\n      } else {\n        // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for.\n        const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)\n        // In fully static rendering or non PPR rendering cases:\n        // `/head>` will always be found in the chunk in first chunk rendering.\n        if (index !== -1) {\n          if (insertion) {\n            const encodedInsertion = encoder.encode(insertion)\n            // Get the total count of the bytes in the chunk and the insertion\n            // e.g.\n            // chunk = <head><meta charset=\"utf-8\"></head>\n            // insertion = <script>...</script>\n            // output = <head><meta charset=\"utf-8\"> [ <script>...</script> ] </head>\n            const insertedHeadContent = new Uint8Array(\n              chunk.length + encodedInsertion.length\n            )\n            // Append the first part of the chunk, before the head tag\n            insertedHeadContent.set(chunk.slice(0, index))\n            // Append the server inserted content\n            insertedHeadContent.set(encodedInsertion, index)\n            // Append the rest of the chunk\n            insertedHeadContent.set(\n              chunk.slice(index),\n              index + encodedInsertion.length\n            )\n            controller.enqueue(insertedHeadContent)\n          } else {\n            controller.enqueue(chunk)\n          }\n          inserted = true\n        } else {\n          // This will happens in PPR rendering during next start, when the page is partially rendered.\n          // When the page resumes, the head tag will be found in the middle of the chunk.\n          // Where we just need to append the insertion and chunk to the current stream.\n          // e.g.\n          // PPR-static: <head>...</head><body> [ resume content ] </body>\n          // PPR-resume: [ insertion ] [ rest content ]\n          if (insertion) {\n            controller.enqueue(encoder.encode(insertion))\n          }\n          controller.enqueue(chunk)\n          inserted = true\n        }\n      }\n    },\n    async flush(controller) {\n      // Check before closing if there's anything remaining to insert.\n      if (hasBytes) {\n        const insertion = await insert()\n        if (insertion) {\n          controller.enqueue(encoder.encode(insertion))\n        }\n      }\n    },\n  })\n}\n\nasync function createClientResumeScriptInsertionTransformStream(): Promise<\n  TransformStream<Uint8Array, Uint8Array>\n> {\n  const segmentPath = '/_full'\n  const cacheBustingHeader = await computeCacheBustingSearchParam(\n    '1', //            headers[NEXT_ROUTER_PREFETCH_HEADER]\n    '/_full', //       headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]\n    undefined, //      headers[NEXT_ROUTER_STATE_TREE_HEADER]\n    undefined //       headers[NEXT_URL]\n  )\n  const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`\n  const NEXT_CLIENT_RESUME_SCRIPT = `<script>__NEXT_CLIENT_RESUME=fetch(location.pathname+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}': '1','${NEXT_ROUTER_PREFETCH_HEADER}': '1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}': '${segmentPath}'}})</script>`\n\n  let didAlreadyInsert = false\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (didAlreadyInsert) {\n        // Already inserted the script into the head. Pass through.\n        controller.enqueue(chunk)\n        return\n      }\n      // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for.\n      const headClosingTagIndex = indexOfUint8Array(\n        chunk,\n        ENCODED_TAGS.CLOSED.HEAD\n      )\n\n      if (headClosingTagIndex === -1) {\n        // In fully static rendering or non PPR rendering cases:\n        // `/head>` will always be found in the chunk in first chunk rendering.\n        controller.enqueue(chunk)\n        return\n      }\n\n      const encodedInsertion = encoder.encode(NEXT_CLIENT_RESUME_SCRIPT)\n      // Get the total count of the bytes in the chunk and the insertion\n      // e.g.\n      // chunk = <head><meta charset=\"utf-8\"></head>\n      // insertion = <script>...</script>\n      // output = <head><meta charset=\"utf-8\"> [ <script>...</script> ] </head>\n      const insertedHeadContent = new Uint8Array(\n        chunk.length + encodedInsertion.length\n      )\n      // Append the first part of the chunk, before the head tag\n      insertedHeadContent.set(chunk.slice(0, headClosingTagIndex))\n      // Append the server inserted content\n      insertedHeadContent.set(encodedInsertion, headClosingTagIndex)\n      // Append the rest of the chunk\n      insertedHeadContent.set(\n        chunk.slice(headClosingTagIndex),\n        headClosingTagIndex + encodedInsertion.length\n      )\n\n      controller.enqueue(insertedHeadContent)\n      didAlreadyInsert = true\n    },\n  })\n}\n\n/**\n * Creates a transform stream that injects an inline script as the first\n * element inside <head>. Used during instant navigation testing to set\n * self.__next_instant_test before any async bootstrap scripts execute.\n */\nexport async function createInstantTestScriptInsertionTransformStream(\n  requestId: string | null\n): Promise<TransformStream<Uint8Array, Uint8Array>> {\n  // Kick off a fetch for the static RSC payload. This is the hydration\n  // source for the locked static shell — same as the __NEXT_CLIENT_RESUME\n  // fetch used for fallback routes, but with NEXT_INSTANT_PREFETCH_HEADER\n  // so the server returns static-only data.\n  //\n  // The fetch promise is stored as self.__next_instant_test, which doubles\n  // as the feature flag (truthy = instant test mode). The client processes\n  // this as a fallback prerender payload for hydration.\n  const segmentPath = '/_full'\n  const cacheBustingHeader = await computeCacheBustingSearchParam(\n    '1',\n    segmentPath,\n    undefined,\n    undefined\n  )\n  const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`\n  // In dev mode, inject self.__next_r (request ID) so that HMR WebSocket\n  // and debug channel initialization don't crash. The static shell\n  // bypasses renderToFizzStream which normally injects this via\n  // bootstrapScriptContent.\n  const requestIdScript =\n    requestId !== null ? `self.__next_r=${JSON.stringify(requestId)};` : ''\n  const INSTANT_TEST_SCRIPT = `<script>${requestIdScript}self.__next_instant_test=fetch(location.pathname+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}':'1','${NEXT_ROUTER_PREFETCH_HEADER}':'1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}':'${segmentPath}','${NEXT_INSTANT_PREFETCH_HEADER}':'1'}})</script>`\n\n  let didAlreadyInsert = false\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (didAlreadyInsert) {\n        // Already inserted the script into the head. Pass through.\n        controller.enqueue(chunk)\n        return\n      }\n\n      // Find the opening <head tag (may have attributes like <head class=\"...\">)\n      const headOpenIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HEAD)\n\n      if (headOpenIndex === -1) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      // Find the closing > of the <head ...> tag\n      const headCloseAngle = chunk.indexOf(\n        62, // '>'\n        headOpenIndex + ENCODED_TAGS.OPENING.HEAD.length\n      )\n      if (headCloseAngle === -1) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      const encodedInsertion = encoder.encode(INSTANT_TEST_SCRIPT)\n      const insertionPoint = headCloseAngle + 1\n      // e.g.\n      // chunk = <!DOCTYPE html><html><head><meta charset=\"utf-8\">...\n      // insertion = <script>self.__next_instant_test=fetch(...)</script>\n      // output = <!DOCTYPE html><html><head> [ <script>...</script> ] <meta charset=\"utf-8\">...\n      const insertedHeadContent = new Uint8Array(\n        chunk.length + encodedInsertion.length\n      )\n      insertedHeadContent.set(chunk.slice(0, insertionPoint))\n      insertedHeadContent.set(encodedInsertion, insertionPoint)\n      insertedHeadContent.set(\n        chunk.slice(insertionPoint),\n        insertionPoint + encodedInsertion.length\n      )\n\n      controller.enqueue(insertedHeadContent)\n      didAlreadyInsert = true\n    },\n    flush(controller) {\n      // Append closing tags so the browser can parse the full document.\n      controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n    },\n  })\n}\n\n// Suffix after main body content - scripts before </body>,\n// but wait for the major chunks to be enqueued.\nfunction createDeferredSuffixStream(\n  suffix: string\n): TransformStream<Uint8Array, Uint8Array> {\n  let flushed = false\n  let pending: DetachedPromise<void> | undefined\n\n  const flush = (controller: TransformStreamDefaultController) => {\n    const detached = new DetachedPromise<void>()\n    pending = detached\n\n    scheduleImmediate(() => {\n      try {\n        controller.enqueue(encoder.encode(suffix))\n      } catch {\n        // If an error occurs while enqueuing it can't be due to this\n        // transformers fault. It's likely due to the controller being\n        // errored due to the stream being cancelled.\n      } finally {\n        pending = undefined\n        detached.resolve()\n      }\n    })\n  }\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      controller.enqueue(chunk)\n\n      // If we've already flushed, we're done.\n      if (flushed) return\n\n      // Schedule the flush to happen.\n      flushed = true\n      flush(controller)\n    },\n    flush(controller) {\n      if (pending) return pending.promise\n      if (flushed) return\n\n      // Flush now.\n      controller.enqueue(encoder.encode(suffix))\n    },\n  })\n}\n\nfunction createFlightDataInjectionTransformStream(\n  stream: ReadableStream<Uint8Array>,\n  delayDataUntilFirstHtmlChunk: boolean\n): TransformStream<Uint8Array, Uint8Array> {\n  let htmlStreamFinished = false\n\n  let pull: Promise<void> | null = null\n  let donePulling = false\n\n  function startOrContinuePulling(\n    controller: TransformStreamDefaultController\n  ) {\n    if (!pull) {\n      pull = startPulling(controller)\n    }\n    return pull\n  }\n\n  async function startPulling(controller: TransformStreamDefaultController) {\n    const reader = stream.getReader()\n\n    if (delayDataUntilFirstHtmlChunk) {\n      // NOTE: streaming flush\n      // We are buffering here for the inlined data stream because the\n      // \"shell\" stream might be chunkenized again by the underlying stream\n      // implementation, e.g. with a specific high-water mark. To ensure it's\n      // the safe timing to pipe the data stream, this extra tick is\n      // necessary.\n\n      // We don't start reading until we've left the current Task to ensure\n      // that it's inserted after flushing the shell. Note that this implementation\n      // might get stale if impl details of Fizz change in the future.\n      await atLeastOneTask()\n    }\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read()\n        if (done) {\n          donePulling = true\n          return\n        }\n\n        // We want to prioritize HTML over RSC data.\n        // The SSR render is based on the same RSC stream, so when we get a new RSC chunk,\n        // we're likely to produce an HTML chunk as well, so give it a chance to flush first.\n        if (!delayDataUntilFirstHtmlChunk && !htmlStreamFinished) {\n          await atLeastOneTask()\n        }\n        controller.enqueue(value)\n      }\n    } catch (err) {\n      controller.error(err)\n    }\n  }\n\n  return new TransformStream({\n    start(controller) {\n      if (!delayDataUntilFirstHtmlChunk) {\n        startOrContinuePulling(controller)\n      }\n    },\n    transform(chunk, controller) {\n      controller.enqueue(chunk)\n\n      // Start the streaming if it hasn't already been started yet.\n      if (delayDataUntilFirstHtmlChunk) {\n        startOrContinuePulling(controller)\n      }\n    },\n    flush(controller) {\n      htmlStreamFinished = true\n      if (donePulling) {\n        return\n      }\n      return startOrContinuePulling(controller)\n    },\n  })\n}\n\nconst CLOSE_TAG = '</body></html>'\n\n/**\n * This transform stream moves the suffix to the end of the stream, so results\n * like `</body></html><script>...</script>` will be transformed to\n * `<script>...</script></body></html>`.\n */\nfunction createMoveSuffixStream(): TransformStream<Uint8Array, Uint8Array> {\n  let foundSuffix = false\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (foundSuffix) {\n        return controller.enqueue(chunk)\n      }\n\n      const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n      if (index > -1) {\n        foundSuffix = true\n\n        // If the whole chunk is the suffix, then don't write anything, it will\n        // be written in the flush.\n        if (chunk.length === ENCODED_TAGS.CLOSED.BODY_AND_HTML.length) {\n          return\n        }\n\n        // Write out the part before the suffix.\n        const before = chunk.slice(0, index)\n        controller.enqueue(before)\n\n        // In the case where the suffix is in the middle of the chunk, we need\n        // to split the chunk into two parts.\n        if (chunk.length > ENCODED_TAGS.CLOSED.BODY_AND_HTML.length + index) {\n          // Write out the part after the suffix.\n          const after = chunk.slice(\n            index + ENCODED_TAGS.CLOSED.BODY_AND_HTML.length\n          )\n          controller.enqueue(after)\n        }\n      } else {\n        controller.enqueue(chunk)\n      }\n    },\n    flush(controller) {\n      // Even if we didn't find the suffix, the HTML is not valid if we don't\n      // add it, so insert it at the end.\n      controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n    },\n  })\n}\n\nfunction createStripDocumentClosingTagsTransform(): TransformStream<\n  Uint8Array,\n  Uint8Array\n> {\n  return new TransformStream({\n    transform(chunk, controller) {\n      // We rely on the assumption that chunks will never break across a code unit.\n      // This is reasonable because we currently concat all of React's output from a single\n      // flush into one chunk before streaming it forward which means the chunk will represent\n      // a single coherent utf-8 string. This is not safe to use if we change our streaming to no\n      // longer do this large buffered chunk\n      if (\n        isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.BODY_AND_HTML) ||\n        isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.BODY) ||\n        isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.HTML)\n      ) {\n        // the entire chunk is the closing tags; return without enqueueing anything.\n        return\n      }\n\n      // We assume these tags will go at together at the end of the document and that\n      // they won't appear anywhere else in the document. This is not really a safe assumption\n      // but until we revamp our streaming infra this is a performant way to string the tags\n      chunk = removeFromUint8Array(chunk, ENCODED_TAGS.CLOSED.BODY)\n      chunk = removeFromUint8Array(chunk, ENCODED_TAGS.CLOSED.HTML)\n\n      controller.enqueue(chunk)\n    },\n  })\n}\n\nfunction createHtmlDataDplIdTransformStream(\n  dplId: string\n): TransformStream<Uint8Array, Uint8Array> {\n  let didTransform = false\n\n  return new TransformStream({\n    transform(chunk, controller) {\n      if (didTransform) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      const htmlTagIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML)\n      if (htmlTagIndex === -1) {\n        controller.enqueue(chunk)\n        return\n      }\n\n      // Insert the data-dpl-id attribute right after \"<html \"\n      const insertionPoint = htmlTagIndex + ENCODED_TAGS.OPENING.HTML.length\n      const attribute = ` data-dpl-id=\"${dplId}\"`\n      const encodedAttribute = encoder.encode(attribute)\n      const modifiedChunk = new Uint8Array(\n        chunk.length + encodedAttribute.length\n      )\n\n      // Copy everything before the insertion point\n      modifiedChunk.set(chunk.subarray(0, insertionPoint))\n      // Insert the attribute\n      modifiedChunk.set(encodedAttribute, insertionPoint)\n      // Copy everything after\n      modifiedChunk.set(\n        chunk.subarray(insertionPoint),\n        insertionPoint + encodedAttribute.length\n      )\n\n      controller.enqueue(modifiedChunk)\n      didTransform = true\n    },\n  })\n}\n\n/*\n * Checks if the root layout is missing the html or body tags\n * and if so, it will inject a script tag to throw an error in the browser, showing the user\n * the error message in the error overlay.\n */\nexport function createRootLayoutValidatorStream(): TransformStream<\n  Uint8Array,\n  Uint8Array\n> {\n  let foundHtml = false\n  let foundBody = false\n  return new TransformStream({\n    async transform(chunk, controller) {\n      // Peek into the streamed chunk to see if the tags are present.\n      if (\n        !foundHtml &&\n        indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML) > -1\n      ) {\n        foundHtml = true\n      }\n\n      if (\n        !foundBody &&\n        indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.BODY) > -1\n      ) {\n        foundBody = true\n      }\n\n      controller.enqueue(chunk)\n    },\n    flush(controller) {\n      const missingTags: ('html' | 'body')[] = []\n      if (!foundHtml) missingTags.push('html')\n      if (!foundBody) missingTags.push('body')\n\n      if (!missingTags.length) return\n\n      controller.enqueue(\n        encoder.encode(\n          `<html id=\"__next_error__\">\n            <template\n              data-next-error-message=\"Missing ${missingTags\n                .map((c) => `<${c}>`)\n                .join(\n                  missingTags.length > 1 ? ' and ' : ''\n                )} tags in the root layout.\\nRead more at https://nextjs.org/docs/messages/missing-root-layout-tags\"\n              data-next-error-digest=\"${MISSING_ROOT_TAGS_ERROR}\"\n              data-next-error-stack=\"\"\n            ></template>\n          `\n        )\n      )\n    },\n  })\n}\n\nfunction chainTransformers<T>(\n  readable: ReadableStream<T>,\n  transformers: ReadonlyArray<TransformStream<T, T> | null>\n): ReadableStream<T> {\n  let stream = readable\n  for (const transformer of transformers) {\n    if (!transformer) continue\n\n    stream = stream.pipeThrough(transformer)\n  }\n  return stream\n}\n\nexport type ContinueStreamOptions = {\n  inlinedDataStream: ReadableStream<Uint8Array> | undefined\n  isStaticGeneration: boolean\n  deploymentId: string | undefined\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  validateRootLayout?: boolean\n  /**\n   * Suffix to inject after the buffered data, but before the close tags.\n   */\n  suffix?: string | undefined\n}\n\nexport async function continueFizzStream(\n  renderStream: ReactDOMServerReadableStream,\n  {\n    suffix,\n    inlinedDataStream,\n    isStaticGeneration,\n    deploymentId,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    validateRootLayout,\n  }: ContinueStreamOptions\n): Promise<ReadableStream<Uint8Array>> {\n  // Suffix itself might contain close tags at the end, so we need to split it.\n  const suffixUnclosed = suffix ? suffix.split(CLOSE_TAG, 1)[0] : null\n\n  if (isStaticGeneration) {\n    // If we're generating static HTML we need to wait for it to resolve before continuing.\n    await renderStream.allReady\n  } else {\n    // Otherwise, we want to make sure Fizz is done with all microtasky work\n    // before we start pulling the stream and cause a flush.\n    await waitAtLeastOneReactRenderTask()\n  }\n\n  return chainTransformers(renderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n\n    // Insert suffix content\n    suffixUnclosed != null && suffixUnclosed.length > 0\n      ? createDeferredSuffixStream(suffixUnclosed)\n      : null,\n\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    inlinedDataStream\n      ? createFlightDataInjectionTransformStream(inlinedDataStream, true)\n      : null,\n\n    // Validate the root layout for missing html or body tags\n    validateRootLayout ? createRootLayoutValidatorStream() : null,\n\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n\n    // Special head insertions\n    // TODO-APP: Insert server side html to end of head in app layout rendering, to avoid\n    // hydration errors. Remove this once it's ready to be handled by react itself.\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n  ])\n}\n\ntype ContinueDynamicPrerenderOptions = {\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  deploymentId: string | undefined\n}\n\nexport async function continueDynamicPrerender(\n  prerenderStream: ReadableStream<Uint8Array>,\n  {\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueDynamicPrerenderOptions\n) {\n  return chainTransformers(prerenderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    createStripDocumentClosingTagsTransform(),\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n  ])\n}\n\ntype ContinueStaticPrerenderOptions = {\n  inlinedDataStream: ReadableStream<Uint8Array>\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  deploymentId: string | undefined\n}\n\nexport async function continueStaticPrerender(\n  prerenderStream: ReadableStream<Uint8Array>,\n  {\n    inlinedDataStream,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueStaticPrerenderOptions\n) {\n  return chainTransformers(prerenderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    // Add build id comment to start of the HTML document (in export mode)\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    createFlightDataInjectionTransformStream(inlinedDataStream, true),\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n  ])\n}\n\nexport async function continueStaticFallbackPrerender(\n  prerenderStream: ReadableStream<Uint8Array>,\n  {\n    inlinedDataStream,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueStaticPrerenderOptions\n) {\n  // Same as `continueStaticPrerender`, but also inserts an additional script\n  // to instruct the client to start fetching the hydration data as early\n  // as possible.\n  return chainTransformers(prerenderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Insert the client resume script into the head\n    await createClientResumeScriptInsertionTransformStream(),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    createFlightDataInjectionTransformStream(inlinedDataStream, true),\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n  ])\n}\n\ntype ContinueResumeOptions = {\n  inlinedDataStream: ReadableStream<Uint8Array>\n  getServerInsertedHTML: () => Promise<string>\n  getServerInsertedMetadata: () => Promise<string>\n  delayDataUntilFirstHtmlChunk: boolean\n  deploymentId: string | undefined\n}\n\nexport async function continueDynamicHTMLResume(\n  renderStream: ReadableStream<Uint8Array>,\n  {\n    delayDataUntilFirstHtmlChunk,\n    inlinedDataStream,\n    getServerInsertedHTML,\n    getServerInsertedMetadata,\n    deploymentId,\n  }: ContinueResumeOptions\n) {\n  return chainTransformers(renderStream, [\n    // Buffer everything to avoid flushing too frequently\n    createBufferedTransformStream(),\n    // Insert data-dpl-id attribute on the html tag\n    deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n    // Insert generated tags to head\n    createHeadInsertionTransformStream(getServerInsertedHTML),\n    // Transform metadata\n    createMetadataTransformStream(getServerInsertedMetadata),\n    // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n    createFlightDataInjectionTransformStream(\n      inlinedDataStream,\n      delayDataUntilFirstHtmlChunk\n    ),\n    // Close tags should always be deferred to the end\n    createMoveSuffixStream(),\n  ])\n}\n\nexport function createDocumentClosingStream(): ReadableStream<Uint8Array> {\n  return streamFromString(CLOSE_TAG)\n}\n\n// ---------------------------------------------------------------------------\n// Runtime prefetch transform (Web streams)\n// ---------------------------------------------------------------------------\n\n/**\n * Web TransformStream that replaces the runtime prefetch sentinel in an RSC\n * payload stream: `[<sentinel>]` -> `[<isPartial>,<staleTime>]`.\n *\n * This is the web equivalent of createRuntimePrefetchNodeTransform\n * in node-stream-helpers.ts.\n */\nexport function createRuntimePrefetchTransformStream(\n  sentinel: number,\n  isPartial: boolean,\n  staleTime: number\n): TransformStream<Uint8Array, Uint8Array> {\n  const enc = new TextEncoder()\n\n  // Search for: [<sentinel>]\n  // Replace with: [<isPartial>,<staleTime>]\n  const search = enc.encode(`[${sentinel}]`)\n  const first = search[0]\n  const replace = enc.encode(`[${isPartial},${staleTime}]`)\n  const searchLen = search.length\n\n  let currentChunk: Uint8Array | null = null\n  let found = false\n\n  function processChunk(\n    controller: TransformStreamDefaultController<Uint8Array>,\n    nextChunk: null | Uint8Array\n  ) {\n    if (found) {\n      if (nextChunk) {\n        controller.enqueue(nextChunk)\n      }\n      return\n    }\n\n    if (currentChunk) {\n      // We can't search past the index that can contain a full match\n      let exclusiveUpperBound = currentChunk.length - (searchLen - 1)\n      if (nextChunk) {\n        // If we have any overflow bytes we can search up to the chunk's final byte\n        exclusiveUpperBound += Math.min(nextChunk.length, searchLen - 1)\n      }\n      if (exclusiveUpperBound < 1) {\n        // we can't match the current chunk.\n        controller.enqueue(currentChunk)\n        currentChunk = nextChunk // advance so we don't process this chunk again\n        return\n      }\n\n      let currentIndex = currentChunk.indexOf(first)\n\n      // check the current candidate match if it is within the bounds of our search space for the currentChunk\n      candidateLoop: while (\n        -1 < currentIndex &&\n        currentIndex < exclusiveUpperBound\n      ) {\n        // We already know index 0 matches because we used indexOf to find the candidateIndex so we start at index 1\n        let matchIndex = 1\n        while (matchIndex < searchLen) {\n          const candidateIndex = currentIndex + matchIndex\n          const candidateValue =\n            candidateIndex < currentChunk.length\n              ? currentChunk[candidateIndex]\n              : // if we ever hit this condition it is because there is a nextChunk we can read from\n                nextChunk![candidateIndex - currentChunk.length]\n          if (candidateValue !== search[matchIndex]) {\n            // No match, reset and continue the search from the next position\n            currentIndex = currentChunk.indexOf(first, currentIndex + 1)\n            continue candidateLoop\n          }\n          matchIndex++\n        }\n        // We found a complete match. currentIndex is our starting point to replace the value.\n        found = true\n        // enqueue everything up to the match\n        controller.enqueue(currentChunk.subarray(0, currentIndex))\n        // enqueue the replacement value\n        controller.enqueue(replace)\n        // If there are bytes in the currentChunk after the match enqueue them\n        if (currentIndex + searchLen < currentChunk.length) {\n          controller.enqueue(currentChunk.slice(currentIndex + searchLen))\n        }\n        // If we have a next chunk we enqueue it now\n        if (nextChunk) {\n          // if replacement spills over to the next chunk we first exclude the replaced bytes\n          const overflowBytes = currentIndex + searchLen - currentChunk.length\n          const truncatedChunk =\n            overflowBytes > 0 ? nextChunk!.subarray(overflowBytes) : nextChunk\n          controller.enqueue(truncatedChunk)\n        }\n        // We are now in found mode and don't need to track currentChunk anymore\n        currentChunk = null\n        return\n      }\n      // No match found in this chunk, emit it and wait for the next one\n      controller.enqueue(currentChunk)\n    }\n\n    // Advance to the next chunk\n    currentChunk = nextChunk\n  }\n\n  return new TransformStream<Uint8Array, Uint8Array>({\n    transform(chunk, controller) {\n      processChunk(controller, chunk)\n    },\n    flush(controller) {\n      processChunk(controller, null)\n    },\n  })\n}\n"],"names":["getTracer","AppRenderSpan","DetachedPromise","scheduleImmediate","atLeastOneTask","waitAtLeastOneReactRenderTask","ENCODED_TAGS","indexOfUint8Array","isEquivalentUint8Arrays","removeFromUint8Array","MISSING_ROOT_TAGS_ERROR","RSC_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_RSC_UNION_QUERY","NEXT_INSTANT_PREFETCH_HEADER","computeCacheBustingSearchParam","voidCatch","encoder","TextEncoder","chainStreams","streams","length","ReadableStream","start","controller","close","readable","writable","TransformStream","promise","pipeTo","preventClose","i","nextStream","then","lastStream","catch","streamFromString","str","enqueue","encode","streamFromBuffer","chunk","streamToChunks","stream","reader","getReader","chunks","done","value","read","push","concatUint8Arrays","totalLength","reduce","sum","result","Uint8Array","offset","set","streamToUint8Array","streamToBuffer","Buffer","concat","streamToString","signal","decoder","TextDecoder","fatal","string","aborted","decode","createBufferedTransformStream","options","maxBufferByteLength","Infinity","bufferedChunks","bufferByteLength","pending","flush","copiedBytes","bufferedChunk","byteLength","scheduleFlush","detached","undefined","resolve","transform","renderToInitialFizzStream","ReactDOMServer","element","streamOptions","trace","renderToReadableStream","createMetadataTransformStream","insert","chunkIndex","isMarkRemoved","iconMarkIndex","closedHeadIndex","iconMarkLength","META","ICON_MARK","CLOSED","HEAD","replaced","subarray","insertion","encodedInsertion","insertionLength","createHeadInsertionTransformStream","inserted","hasBytes","index","insertedHeadContent","slice","createClientResumeScriptInsertionTransformStream","segmentPath","cacheBustingHeader","searchStr","NEXT_CLIENT_RESUME_SCRIPT","didAlreadyInsert","headClosingTagIndex","createInstantTestScriptInsertionTransformStream","requestId","requestIdScript","JSON","stringify","INSTANT_TEST_SCRIPT","headOpenIndex","OPENING","headCloseAngle","indexOf","insertionPoint","BODY_AND_HTML","createDeferredSuffixStream","suffix","flushed","createFlightDataInjectionTransformStream","delayDataUntilFirstHtmlChunk","htmlStreamFinished","pull","donePulling","startOrContinuePulling","startPulling","err","error","CLOSE_TAG","createMoveSuffixStream","foundSuffix","before","after","createStripDocumentClosingTagsTransform","BODY","HTML","createHtmlDataDplIdTransformStream","dplId","didTransform","htmlTagIndex","attribute","encodedAttribute","modifiedChunk","createRootLayoutValidatorStream","foundHtml","foundBody","missingTags","map","c","join","chainTransformers","transformers","transformer","pipeThrough","continueFizzStream","renderStream","inlinedDataStream","isStaticGeneration","deploymentId","getServerInsertedHTML","getServerInsertedMetadata","validateRootLayout","suffixUnclosed","split","allReady","continueDynamicPrerender","prerenderStream","continueStaticPrerender","continueStaticFallbackPrerender","continueDynamicHTMLResume","createDocumentClosingStream","createRuntimePrefetchTransformStream","sentinel","isPartial","staleTime","enc","search","first","replace","searchLen","currentChunk","found","processChunk","nextChunk","exclusiveUpperBound","Math","min","currentIndex","candidateLoop","matchIndex","candidateIndex","candidateValue","overflowBytes","truncatedChunk"],"mappings":"AACA,SAASA,SAAS,QAAQ,sBAAqB;AAC/C,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SACEC,iBAAiB,EACjBC,cAAc,EACdC,6BAA6B,QACxB,sBAAqB;AAC5B,SAASC,YAAY,QAAQ,iBAAgB;AAC7C,SACEC,iBAAiB,EACjBC,uBAAuB,EACvBC,oBAAoB,QACf,uBAAsB;AAC7B,SAASC,uBAAuB,QAAQ,oCAAmC;AAC3E,SACEC,UAAU,EACVC,2BAA2B,EAC3BC,mCAAmC,EACnCC,oBAAoB,EACpBC,4BAA4B,QACvB,6CAA4C;AACnD,SAASC,8BAA8B,QAAQ,2DAA0D;AAEzG,SAASC;AACP,iFAAiF;AACjF,uFAAuF;AACvF,mBAAmB;AACrB;AAEA,oDAAoD;AACpD,uEAAuE;AACvE,+BAA+B;AAC/B,MAAMC,UAAU,IAAIC;AAEpB,OAAO,SAASC,aACd,GAAGC,OAA4B;IAE/B,kEAAkE;IAClE,qEAAqE;IACrE,IAAIA,QAAQC,MAAM,KAAK,GAAG;QACxB,OAAO,IAAIC,eAAkB;YAC3BC,OAAMC,UAAU;gBACdA,WAAWC,KAAK;YAClB;QACF;IACF;IAEA,yEAAyE;IACzE,IAAIL,QAAQC,MAAM,KAAK,GAAG;Q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