|
| 1 | +// Next.js' runtime manifest registry |
| 2 | +// https://github.com/vercel/next.js/blob/8e0700c74474498a07b33f58da1c1316f740eb19/packages/next/src/server/app-render/manifests-singleton.ts#L56-L59 |
| 3 | +const NEXT_MANIFESTS_SINGLETON = Symbol.for('next.server.manifests'); |
| 4 | + |
| 5 | +type ManifestEntries = Record<string, { filename?: unknown } | undefined>; |
| 6 | + |
| 7 | +type GlobalWithManifests = typeof globalThis & { |
| 8 | + [NEXT_MANIFESTS_SINGLETON]?: { |
| 9 | + serverActionsManifest?: { |
| 10 | + node?: ManifestEntries; |
| 11 | + edge?: ManifestEntries; |
| 12 | + }; |
| 13 | + }; |
| 14 | +}; |
| 15 | + |
| 16 | +interface MultipartField { |
| 17 | + content: string; |
| 18 | + /** Index of the first character after this field. */ |
| 19 | + end: number; |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Reads one field of a multipart cache key, starting at `start`. |
| 24 | + * A field is `<length>:<content>`, with the length in lowercase hex counting UTF-16 code units. |
| 25 | + * https://github.com/vercel/next.js/blob/8e0700c74474498a07b33f58da1c1316f740eb19/packages/next/src/server/use-cache/use-cache-wrapper.ts#L1815-L1847 |
| 26 | + * |
| 27 | + * Returns `undefined` when the framing is broken. |
| 28 | + */ |
| 29 | +function readMultipartField(cacheKey: string, start: number): MultipartField | undefined { |
| 30 | + // The characters before the next `:` must be a non-empty hex length. |
| 31 | + const colon = cacheKey.indexOf(':', start); |
| 32 | + if (colon <= start || !/^[0-9a-f]+$/.test(cacheKey.slice(start, colon))) { |
| 33 | + return undefined; |
| 34 | + } |
| 35 | + |
| 36 | + // A length that points past the end of the key means the key is truncated. |
| 37 | + const contentStart = colon + 1; |
| 38 | + const contentEnd = contentStart + parseInt(cacheKey.slice(start, colon), 16); |
| 39 | + if (contentEnd > cacheKey.length) { |
| 40 | + return undefined; |
| 41 | + } |
| 42 | + |
| 43 | + return { content: cacheKey.slice(contentStart, contentEnd), end: contentEnd }; |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Cache keys with arguments that do not serialize to JSON (a page's `params` promise, a layout's |
| 48 | + * `children`) are serialized FormData: pairs of length-prefixed fields, a field name followed by |
| 49 | + * its content. React stores the key parts JSON in the field named `"0"`, which is not necessarily |
| 50 | + * the first field. Returns that JSON text, or `undefined` for a malformed key. |
| 51 | + */ |
| 52 | +function readKeyPartsFromMultipartKey(cacheKey: string): string | undefined { |
| 53 | + let position = 0; |
| 54 | + while (position < cacheKey.length) { |
| 55 | + // Each pair is the field name, then the field content. |
| 56 | + const name = readMultipartField(cacheKey, position); |
| 57 | + const content = name && readMultipartField(cacheKey, name.end); |
| 58 | + if (name === undefined || content === undefined) { |
| 59 | + return undefined; |
| 60 | + } |
| 61 | + |
| 62 | + if (name.content === '0') { |
| 63 | + return content.content; |
| 64 | + } |
| 65 | + position = content.end; |
| 66 | + } |
| 67 | + return undefined; |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Picks the function id out of the decoded key parts. Next.js 16.3 puts the id at index 1 |
| 72 | + * (`[buildId, id, args]` in prod; dev appends a fourth part). 16.4 canary moves it to index 0 |
| 73 | + * (`[id, args, …]`). Returns `undefined` for any other shape. |
| 74 | + */ |
| 75 | +function readFunctionIdFromKeyParts(keyParts: unknown): string | undefined { |
| 76 | + if (!Array.isArray(keyParts)) { |
| 77 | + return undefined; |
| 78 | + } |
| 79 | + // An args array at index 1 marks the canary shape, where the id sits at index 0. |
| 80 | + const functionId = Array.isArray(keyParts[1]) ? keyParts[0] : keyParts[1]; |
| 81 | + return typeof functionId === 'string' ? functionId : undefined; |
| 82 | +} |
| 83 | + |
| 84 | +/** |
| 85 | + * Manifest filenames start at the repo root, but only the path inside the project is useful. |
| 86 | + * The repo-root-to-project part equals the tail of `process.cwd()`, because `next dev`, |
| 87 | + * `next start`, and the standalone server all run in the project directory (the standalone |
| 88 | + * `server.js` chdirs into its mirrored copy). Unknown layouts keep the full path. |
| 89 | + */ |
| 90 | +function toProjectRelativePath(filename: string): string { |
| 91 | + // Split the cwd on both separators so Windows paths work. The manifest always uses `/`. |
| 92 | + const cwdSegments = process.cwd().split(/[\\/]/).filter(Boolean); |
| 93 | + const fileSegments = filename.split('/'); |
| 94 | + |
| 95 | + // Drop the longest filename prefix that matches the cwd tail. Longest first, so the whole |
| 96 | + // repo prefix goes, not just a part of it. At least one segment always remains. |
| 97 | + const maxOverlap = Math.min(fileSegments.length - 1, cwdSegments.length); |
| 98 | + for (let overlap = maxOverlap; overlap > 0; overlap--) { |
| 99 | + const cwdTail = cwdSegments.slice(-overlap); |
| 100 | + if (cwdTail.every((segment, index) => segment === fileSegments[index])) { |
| 101 | + return fileSegments.slice(overlap).join('/'); |
| 102 | + } |
| 103 | + } |
| 104 | + return filename; |
| 105 | +} |
| 106 | + |
| 107 | +/** |
| 108 | + * Resolves the source file of the `use cache` function behind a cache key, through the server-reference manifest. |
| 109 | + * On Next.js 16.3 the manifest only covers component-tree functions, so route handlers resolve to `undefined`. |
| 110 | + * 16.4 canary includes route handlers. |
| 111 | + * Any unexpected key or manifest shape returns `undefined`, never a wrong file. |
| 112 | + */ |
| 113 | +export function getCacheFunctionSourceFile(cacheKey: string): string | undefined { |
| 114 | + try { |
| 115 | + // The key is `encodeReply(keyParts)`: a plain JSON array when all function arguments |
| 116 | + // serialize to JSON, the multipart form otherwise. |
| 117 | + const keyPartsJson = cacheKey.startsWith('[') ? cacheKey : readKeyPartsFromMultipartKey(cacheKey); |
| 118 | + if (!keyPartsJson) { |
| 119 | + return undefined; |
| 120 | + } |
| 121 | + |
| 122 | + const functionId = readFunctionIdFromKeyParts(JSON.parse(keyPartsJson)); |
| 123 | + if (functionId === undefined) { |
| 124 | + return undefined; |
| 125 | + } |
| 126 | + |
| 127 | + // The manifest has one section per runtime. `NEXT_RUNTIME` is only `'edge'` on edge. |
| 128 | + const manifest = (globalThis as GlobalWithManifests)[NEXT_MANIFESTS_SINGLETON]?.serverActionsManifest; |
| 129 | + const filename = manifest?.[process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node']?.[functionId]?.filename; |
| 130 | + return typeof filename === 'string' && filename ? toProjectRelativePath(filename) : undefined; |
| 131 | + } catch { |
| 132 | + return undefined; |
| 133 | + } |
| 134 | +} |
0 commit comments