{"version":3,"sources":["../../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n  return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n  process.env.NEXT_RUNTIME === 'edge'\n    ? noSourceMap\n    : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n  offset: {\n    line: number\n    column: number\n  }\n  map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n  version: number\n  file: string\n  sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n  version: number\n  // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n  /** WARNING: `file` is optional. */\n  file: string\n  sourceRoot?: string\n  // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n  /** WARNING: `sources[number]` can be `null`. */\n  sources: Array<string>\n  names: Array<string>\n  mappings: string\n  ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n  sourceURL: string\n): ModernSourceMapPayload | undefined {\n  const sourceMap = findSourceMap(sourceURL)\n  if (sourceMap === undefined) {\n    return undefined\n  }\n  let payload = sourceMapPayloads.get(sourceMap)\n  if (payload === undefined) {\n    payload = sourceMap.payload as ModernSourceMapPayload\n    sourceMapPayloads.set(sourceMap, payload)\n  }\n  return payload\n}\n\nexport function sourceMapIgnoreListsEverything(\n  sourceMap: BasicSourceMapPayload\n): boolean {\n  return (\n    sourceMap.ignoreList !== undefined &&\n    sourceMap.sources.length === sourceMap.ignoreList.length\n  )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n  line0: number,\n  column0: number,\n  payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n  if ('sections' in payload) {\n    if (payload.sections.length === 0) {\n      return undefined\n    }\n\n    // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n    // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n    const sections = payload.sections\n    let left = 0\n    let right = sections.length - 1\n    let result: IndexSourceMapSection | null = null\n\n    while (left <= right) {\n      // fast Math.floor\n      const middle = ~~((left + right) / 2)\n      const section = sections[middle]\n      const offset = section.offset\n\n      if (\n        offset.line < line0 ||\n        (offset.line === line0 && offset.column <= column0)\n      ) {\n        result = section\n        left = middle + 1\n      } else {\n        right = middle - 1\n      }\n    }\n\n    return result === null ? undefined : result.map\n  } else {\n    return payload\n  }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n  sourceURL: string,\n  functionName: string,\n  line1: number,\n  column1: number\n): boolean {\n  if (sourceURL === '') {\n    // The default implementation filters out <anonymous> stack frames\n    // but we want to retain them because current Server Components and\n    // built-in Components in parent stacks don't have source location.\n    // Filter out frames that show up in Promises to get good names in React's\n    // Server Request track until we come up with a better heuristic.\n    return functionName !== 'new Promise'\n  }\n  if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n    return false\n  }\n  try {\n    // Node.js loads source maps eagerly so this call is cheap.\n    // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n    // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n    const payload = findSourceMapPayload(sourceURL)\n    if (payload === undefined) {\n      // No source map associated.\n      return true\n    }\n    const sourceMapPayload = findApplicableSourceMapPayload(\n      line1 - 1,\n      column1 - 1,\n      payload\n    )\n    if (sourceMapPayload === undefined) {\n      // No source map section applicable to the frame.\n      return true\n    }\n    return !sourceMapIgnoreListsEverything(sourceMapPayload)\n  } catch (cause) {\n    if (process.env.NODE_ENV !== 'production') {\n      // TODO: Share cache with patch-error-inspect\n      if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n        didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n        // We should not log an actual error instance here because that will re-enter\n        // this codepath during error inspection and could lead to infinite recursion.\n        console.error(\n          `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n        )\n      }\n    }\n\n    return true\n  }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n  'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n  findSourceMapURLImplementation: FindSourceMapURL\n): void {\n  ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n    findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n  const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n    bundlerFindSourceMapURLSymbol\n  ]\n  return implementation === undefined\n    ? null\n    : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n  512 * 1024 * 1024,\n  (url, sourceURL) =>\n    sourceURL.length +\n    (url === invalidSourceMap\n      ? // Guestimate a small source map so invalid entries don't fill the cache.\n        8 * 1024\n      : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n        url.length)\n)\nexport function findSourceMapURLDEV(\n  scriptNameOrSourceURL: string\n): string | null {\n  try {\n    const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n    if (bundlerSourceMapURL !== null) {\n      return bundlerSourceMapURL\n    }\n  } catch (cause) {\n    console.error(\n      `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n    )\n  }\n\n  // No bundler implementation (e.g. Webpack): inline the source map Node.js\n  // knows as a `data:` URL.\n  let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n  if (sourceMapURL === undefined) {\n    let sourceMapPayload: ModernSourceMapPayload | undefined\n    try {\n      sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\n    } catch (cause) {\n      console.error(\n        `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n      )\n    }\n\n    if (sourceMapPayload === undefined) {\n      sourceMapURL = invalidSourceMap\n    } else {\n      // TODO: Might be more efficient to extract the relevant section from Index Maps.\n      // Unclear if that search is worth the smaller payload we have to stringify.\n      const sourceMapJSON = JSON.stringify(sourceMapPayload)\n      const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n        'base64'\n      )\n      sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n    }\n\n    sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n  }\n\n  return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n  if (sourceURL.startsWith('about://React/')) {\n    // about://React/Server/file://<filename>?42 => file://<filename>\n    const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n    const suffixIdx = sourceURL.lastIndexOf('?')\n    if (envIdx > -1 && suffixIdx > -1) {\n      return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n    }\n  }\n  return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n  // Anonymous frames can also be produced in React parent stacks either from\n  // host components or Server Components. We don't want to ignore those.\n  // This could hide user-space methods that are named like native JS methods but\n  // should you really do that?\n  return (\n    // e.g. JSON.parse\n    methodName.startsWith('JSON.') ||\n    // E.g. Promise.withResolves\n    methodName.startsWith('Function.') ||\n    // various JS built-ins\n    methodName.startsWith('Promise.') ||\n    methodName.startsWith('Array.') ||\n    methodName.startsWith('Set.') ||\n    methodName.startsWith('Map.')\n  )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n  frames: Frame[],\n  isAnonymousFrame: (frame: Frame) => boolean,\n  isIgnoredFrame: (frame: Frame) => boolean,\n  getMethodName: (frame: Frame) => string,\n  /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n  ignoreFrame: (frame: Frame) => void\n): void {\n  for (let i = 1; i < frames.length; i++) {\n    const currentFrame = frames[i]\n    if (\n      !(\n        isAnonymousFrame(currentFrame) &&\n        isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n      )\n    ) {\n      continue\n    }\n\n    const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n    if (previousFrameIsIgnored && i < frames.length - 1) {\n      let ignoreSandwich = false\n      let j = i + 1\n      for (j; j < frames.length; j++) {\n        const nextFrame = frames[j]\n        const nextFrameIsAnonymous =\n          isAnonymousFrame(nextFrame) &&\n          isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n        if (nextFrameIsAnonymous) {\n          continue\n        }\n\n        const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n        if (nextFrameIsIgnored) {\n          ignoreSandwich = true\n          break\n        }\n      }\n\n      if (ignoreSandwich) {\n        for (i; i < j; i++) {\n          ignoreFrame(frames[i])\n        }\n      }\n    }\n  }\n}\n"],"names":["LRUCache","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapPayloads","WeakMap","findSourceMapPayload","sourceURL","sourceMap","payload","get","set","sourceMapIgnoreListsEverything","ignoreList","sources","length","findApplicableSourceMapPayload","line0","column0","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","filterStackFrameDEV","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","setBundlerFindSourceMapURLImplementation","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","url","findSourceMapURLDEV","bundlerSourceMapURL","sourceMapURL","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","devirtualizeReactServerURL","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","ignoreListAnonymousStackFramesIfSandwiched","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":"AACA,SAASA,QAAQ,QAAQ,cAAa;AAEtC,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;AAsClE,0EAA0E;AAC1E,0EAA0E;AAC1E,qCAAqC;AACrC,MAAMK,oBAAoB,IAAIC;AAE9B;;;;CAIC,GACD,OAAO,SAASC,qBACdC,SAAiB;IAEjB,MAAMC,YAAYT,cAAcQ;IAChC,IAAIC,cAAcV,WAAW;QAC3B,OAAOA;IACT;IACA,IAAIW,UAAUL,kBAAkBM,GAAG,CAACF;IACpC,IAAIC,YAAYX,WAAW;QACzBW,UAAU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