|
| 1 | +// misc utilities copied from vite |
| 2 | + |
| 3 | +import fs from "node:fs"; |
| 4 | +import path from "node:path"; |
| 5 | +import { stripVTControlCharacters as strip } from "node:util"; |
| 6 | +import type { DevEnvironment, ErrorPayload, Rollup } from "vite"; |
| 7 | + |
| 8 | +export const VALID_ID_PREFIX = `/@id/`; |
| 9 | + |
| 10 | +export const NULL_BYTE_PLACEHOLDER = `__x00__`; |
| 11 | + |
| 12 | +export const FS_PREFIX = `/@fs/`; |
| 13 | + |
| 14 | +export function wrapId(id: string): string { |
| 15 | + return id.startsWith(VALID_ID_PREFIX) |
| 16 | + ? id |
| 17 | + : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); |
| 18 | +} |
| 19 | + |
| 20 | +export function unwrapId(id: string): string { |
| 21 | + return id.startsWith(VALID_ID_PREFIX) |
| 22 | + ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") |
| 23 | + : id; |
| 24 | +} |
| 25 | + |
| 26 | +export function withTrailingSlash(path: string): string { |
| 27 | + if (path[path.length - 1] !== "/") { |
| 28 | + return `${path}/`; |
| 29 | + } |
| 30 | + return path; |
| 31 | +} |
| 32 | + |
| 33 | +const postfixRE = /[?#].*$/; |
| 34 | +export function cleanUrl(url: string): string { |
| 35 | + return url.replace(postfixRE, ""); |
| 36 | +} |
| 37 | + |
| 38 | +export function splitFileAndPostfix(path: string): { |
| 39 | + file: string; |
| 40 | + postfix: string; |
| 41 | +} { |
| 42 | + const file = cleanUrl(path); |
| 43 | + return { file, postfix: path.slice(file.length) }; |
| 44 | +} |
| 45 | + |
| 46 | +const windowsSlashRE = /\\/g; |
| 47 | +export function slash(p: string): string { |
| 48 | + return p.replace(windowsSlashRE, "/"); |
| 49 | +} |
| 50 | + |
| 51 | +const isWindows = |
| 52 | + typeof process !== "undefined" && process.platform === "win32"; |
| 53 | + |
| 54 | +export function injectQuery(url: string, queryToInject: string): string { |
| 55 | + const { file, postfix } = splitFileAndPostfix(url); |
| 56 | + const normalizedFile = isWindows ? slash(file) : file; |
| 57 | + return `${normalizedFile}?${queryToInject}${ |
| 58 | + postfix[0] === "?" ? `&${postfix.slice(1)}` : /* hash only */ postfix |
| 59 | + }`; |
| 60 | +} |
| 61 | + |
| 62 | +export function joinUrlSegments(a: string, b: string): string { |
| 63 | + if (!a || !b) { |
| 64 | + return a || b || ""; |
| 65 | + } |
| 66 | + if (a.endsWith("/")) { |
| 67 | + a = a.substring(0, a.length - 1); |
| 68 | + } |
| 69 | + if (b[0] !== "/") { |
| 70 | + b = "/" + b; |
| 71 | + } |
| 72 | + return a + b; |
| 73 | +} |
| 74 | + |
| 75 | +export function normalizeResolvedIdToUrl( |
| 76 | + environment: DevEnvironment, |
| 77 | + url: string, |
| 78 | + resolved: Rollup.PartialResolvedId, |
| 79 | +): string { |
| 80 | + const root = environment.config.root; |
| 81 | + const depsOptimizer = environment.depsOptimizer; |
| 82 | + |
| 83 | + // normalize all imports into resolved URLs |
| 84 | + // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'` |
| 85 | + if (resolved.id.startsWith(withTrailingSlash(root))) { |
| 86 | + // in root: infer short absolute path from root |
| 87 | + url = resolved.id.slice(root.length); |
| 88 | + } else if ( |
| 89 | + depsOptimizer?.isOptimizedDepFile(resolved.id) || |
| 90 | + // vite-plugin-react isn't following the leading \0 virtual module convention. |
| 91 | + // This is a temporary hack to avoid expensive fs checks for React apps. |
| 92 | + // We'll remove this as soon we're able to fix the react plugins. |
| 93 | + (resolved.id !== "/@react-refresh" && |
| 94 | + path.isAbsolute(resolved.id) && |
| 95 | + fs.existsSync(cleanUrl(resolved.id))) |
| 96 | + ) { |
| 97 | + // an optimized deps may not yet exists in the filesystem, or |
| 98 | + // a regular file exists but is out of root: rewrite to absolute /@fs/ paths |
| 99 | + url = path.posix.join(FS_PREFIX, resolved.id); |
| 100 | + } else { |
| 101 | + url = resolved.id; |
| 102 | + } |
| 103 | + |
| 104 | + // if the resolved id is not a valid browser import specifier, |
| 105 | + // prefix it to make it valid. We will strip this before feeding it |
| 106 | + // back into the transform pipeline |
| 107 | + if (url[0] !== "." && url[0] !== "/") { |
| 108 | + url = wrapId(resolved.id); |
| 109 | + } |
| 110 | + |
| 111 | + return url; |
| 112 | +} |
| 113 | + |
| 114 | +export function normalizeViteImportAnalysisUrl( |
| 115 | + environment: DevEnvironment, |
| 116 | + id: string, |
| 117 | +): string { |
| 118 | + let url = normalizeResolvedIdToUrl(environment, id, { id }); |
| 119 | + |
| 120 | + // https://github.com/vitejs/vite/blob/c18ce868c4d70873406e9f7d1b2d0a03264d2168/packages/vite/src/node/plugins/importAnalysis.ts#L416 |
| 121 | + if (environment.config.consumer === "client") { |
| 122 | + const mod = environment.moduleGraph.getModuleById(id); |
| 123 | + if (mod && mod.lastHMRTimestamp > 0) { |
| 124 | + url = injectQuery(url, `t=${mod.lastHMRTimestamp}`); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + return url; |
| 129 | +} |
| 130 | + |
| 131 | +// error formatting |
| 132 | +// https://github.com/vitejs/vite/blob/8033e5bf8d3ff43995d0620490ed8739c59171dd/packages/vite/src/node/server/middlewares/error.ts#L11 |
| 133 | + |
| 134 | +type RollupError = Rollup.RollupError; |
| 135 | + |
| 136 | +export function prepareError(err: Error | RollupError): ErrorPayload["err"] { |
| 137 | + // only copy the information we need and avoid serializing unnecessary |
| 138 | + // properties, since some errors may attach full objects (e.g. PostCSS) |
| 139 | + return { |
| 140 | + message: strip(err.message), |
| 141 | + stack: strip(cleanStack(err.stack || "")), |
| 142 | + id: (err as RollupError).id, |
| 143 | + frame: strip((err as RollupError).frame || ""), |
| 144 | + plugin: (err as RollupError).plugin, |
| 145 | + pluginCode: (err as RollupError).pluginCode?.toString(), |
| 146 | + loc: (err as RollupError).loc, |
| 147 | + }; |
| 148 | +} |
| 149 | + |
| 150 | +function cleanStack(stack: string) { |
| 151 | + return stack |
| 152 | + .split(/\n/) |
| 153 | + .filter((l) => /^\s*at/.test(l)) |
| 154 | + .join("\n"); |
| 155 | +} |
| 156 | + |
| 157 | +// https://github.com/vitejs/vite/blob/ea9aed7ebcb7f4be542bd2a384cbcb5a1e7b31bd/packages/vite/src/node/utils.ts#L1469-L1475 |
| 158 | +export function evalValue<T = any>(rawValue: string): T { |
| 159 | + const fn = new Function(` |
| 160 | + var console, exports, global, module, process, require |
| 161 | + return (\n${rawValue}\n) |
| 162 | + `); |
| 163 | + return fn(); |
| 164 | +} |
| 165 | + |
| 166 | +// https://github.com/vitejs/vite/blob/84079a84ad94de4c1ef4f1bdb2ab448ff2c01196/packages/vite/src/node/utils.ts#L321 |
| 167 | +export const directRequestRE: RegExp = /(\?|&)direct=?(?:&|$)/; |
0 commit comments