identifier.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const path = require("path");
  6. // Any absolute path: POSIX (/foo) and every Windows form — drive-letter (C:\,
  7. // C:/), UNC (\\, //), rooted (\, /); equals posix||win32 isAbsolute.
  8. const ABSOLUTE_PATH_REGEXP = /^(?:[a-z]:)?[\\/]/i;
  9. // Windows drive-letter absolute path only (C:\ or C:/), where a leading "/" is
  10. // NOT absolute — used where POSIX paths must stay relative to a base.
  11. const WINDOWS_ABS_PATH_REGEXP = /^[a-z]:[\\/]/i;
  12. const SEGMENTS_SPLIT_REGEXP = /([|!])/;
  13. const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g;
  14. const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
  15. /**
  16. * Relative path to request.
  17. * @param {string} relativePath relative path
  18. * @returns {string} request
  19. */
  20. const relativePathToRequest = (relativePath) => {
  21. if (relativePath === "") return "./.";
  22. if (relativePath === "..") return "../.";
  23. if (relativePath.startsWith("../")) return relativePath;
  24. return `./${relativePath}`;
  25. };
  26. /**
  27. * Absolute to request.
  28. * @param {string} context context for relative path
  29. * @param {string} maybeAbsolutePath path to make relative
  30. * @returns {string} relative path in request style
  31. */
  32. const absoluteToRequest = (context, maybeAbsolutePath) => {
  33. if (maybeAbsolutePath[0] === "/") {
  34. if (
  35. maybeAbsolutePath.length > 1 &&
  36. maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/"
  37. ) {
  38. // this 'path' is actually a regexp generated by dynamic requires.
  39. // Don't treat it as an absolute path.
  40. return maybeAbsolutePath;
  41. }
  42. const querySplitPos = maybeAbsolutePath.indexOf("?");
  43. let resource =
  44. querySplitPos === -1
  45. ? maybeAbsolutePath
  46. : maybeAbsolutePath.slice(0, querySplitPos);
  47. resource = relativePathToRequest(path.posix.relative(context, resource));
  48. return querySplitPos === -1
  49. ? resource
  50. : resource + maybeAbsolutePath.slice(querySplitPos);
  51. }
  52. if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) {
  53. const querySplitPos = maybeAbsolutePath.indexOf("?");
  54. let resource =
  55. querySplitPos === -1
  56. ? maybeAbsolutePath
  57. : maybeAbsolutePath.slice(0, querySplitPos);
  58. resource = path.win32.relative(context, resource);
  59. if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) {
  60. resource = relativePathToRequest(
  61. resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/")
  62. );
  63. }
  64. return querySplitPos === -1
  65. ? resource
  66. : resource + maybeAbsolutePath.slice(querySplitPos);
  67. }
  68. // not an absolute path
  69. return maybeAbsolutePath;
  70. };
  71. /**
  72. * Request to absolute.
  73. * @param {string} context context for relative path
  74. * @param {string} relativePath path
  75. * @returns {string} absolute path
  76. */
  77. const requestToAbsolute = (context, relativePath) => {
  78. if (relativePath.startsWith("./") || relativePath.startsWith("../")) {
  79. return path.join(context, relativePath);
  80. }
  81. return relativePath;
  82. };
  83. /** @typedef {EXPECTED_OBJECT} AssociatedObjectForCache */
  84. /**
  85. * Defines the make cacheable result type used by this module.
  86. * @template T
  87. * @typedef {(value: string, cache?: AssociatedObjectForCache) => T} MakeCacheableResult
  88. */
  89. /**
  90. * Defines the bind cache result fn type used by this module.
  91. * @template T
  92. * @typedef {(value: string) => T} BindCacheResultFn
  93. */
  94. /**
  95. * Defines the bind cache type used by this module.
  96. * @template T
  97. * @typedef {(cache: AssociatedObjectForCache) => BindCacheResultFn<T>} BindCache
  98. */
  99. /**
  100. * Returns } cacheable function.
  101. * @template T
  102. * @param {((value: string) => T)} realFn real function
  103. * @returns {MakeCacheableResult<T> & { bindCache: BindCache<T> }} cacheable function
  104. */
  105. const makeCacheable = (realFn) => {
  106. /**
  107. * Defines the cache item type used by this module.
  108. * @template T
  109. * @typedef {Map<string, T>} CacheItem
  110. */
  111. /** @type {WeakMap<AssociatedObjectForCache, CacheItem<T>>} */
  112. const cache = new WeakMap();
  113. /**
  114. * Returns cache item.
  115. * @param {AssociatedObjectForCache} associatedObjectForCache an object to which the cache will be attached
  116. * @returns {CacheItem<T>} cache item
  117. */
  118. const getCache = (associatedObjectForCache) => {
  119. const entry = cache.get(associatedObjectForCache);
  120. if (entry !== undefined) return entry;
  121. /** @type {Map<string, T>} */
  122. const map = new Map();
  123. cache.set(associatedObjectForCache, map);
  124. return map;
  125. };
  126. /** @type {MakeCacheableResult<T> & { bindCache: BindCache<T> }} */
  127. const fn = (str, associatedObjectForCache) => {
  128. if (!associatedObjectForCache) return realFn(str);
  129. const cache = getCache(associatedObjectForCache);
  130. const entry = cache.get(str);
  131. if (entry !== undefined) return entry;
  132. const result = realFn(str);
  133. cache.set(str, result);
  134. return result;
  135. };
  136. /** @type {BindCache<T>} */
  137. fn.bindCache = (associatedObjectForCache) => {
  138. const cache = getCache(associatedObjectForCache);
  139. /**
  140. * Returns value.
  141. * @param {string} str string
  142. * @returns {T} value
  143. */
  144. return (str) => {
  145. const entry = cache.get(str);
  146. if (entry !== undefined) return entry;
  147. const result = realFn(str);
  148. cache.set(str, result);
  149. return result;
  150. };
  151. };
  152. return fn;
  153. };
  154. /** @typedef {(context: string, value: string, associatedObjectForCache?: AssociatedObjectForCache) => string} MakeCacheableWithContextResult */
  155. /** @typedef {(context: string, value: string) => string} BindCacheForContextResultFn */
  156. /** @typedef {(value: string) => string} BindContextCacheForContextResultFn */
  157. /** @typedef {(associatedObjectForCache?: AssociatedObjectForCache) => BindCacheForContextResultFn} BindCacheForContext */
  158. /** @typedef {(value: string, associatedObjectForCache?: AssociatedObjectForCache) => BindContextCacheForContextResultFn} BindContextCacheForContext */
  159. /**
  160. * Creates cacheable with context.
  161. * @param {(context: string, identifier: string) => string} fn function
  162. * @returns {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} cacheable function with context
  163. */
  164. const makeCacheableWithContext = (fn) => {
  165. /** @typedef {Map<string, Map<string, string>>} InnerCache */
  166. /** @type {WeakMap<AssociatedObjectForCache, InnerCache>} */
  167. const cache = new WeakMap();
  168. /** @type {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} */
  169. const cachedFn = (context, identifier, associatedObjectForCache) => {
  170. if (!associatedObjectForCache) return fn(context, identifier);
  171. let innerCache = cache.get(associatedObjectForCache);
  172. if (innerCache === undefined) {
  173. innerCache = new Map();
  174. cache.set(associatedObjectForCache, innerCache);
  175. }
  176. /** @type {undefined | string} */
  177. let cachedResult;
  178. let innerSubCache = innerCache.get(context);
  179. if (innerSubCache === undefined) {
  180. innerCache.set(context, (innerSubCache = new Map()));
  181. } else {
  182. cachedResult = innerSubCache.get(identifier);
  183. }
  184. if (cachedResult !== undefined) {
  185. return cachedResult;
  186. }
  187. const result = fn(context, identifier);
  188. innerSubCache.set(identifier, result);
  189. return result;
  190. };
  191. /** @type {BindCacheForContext} */
  192. cachedFn.bindCache = (associatedObjectForCache) => {
  193. /** @type {undefined | InnerCache} */
  194. let innerCache;
  195. if (associatedObjectForCache) {
  196. innerCache = cache.get(associatedObjectForCache);
  197. if (innerCache === undefined) {
  198. innerCache = new Map();
  199. cache.set(associatedObjectForCache, innerCache);
  200. }
  201. } else {
  202. innerCache = new Map();
  203. }
  204. /**
  205. * Returns the returned relative path.
  206. * @param {string} context context used to create relative path
  207. * @param {string} identifier identifier used to create relative path
  208. * @returns {string} the returned relative path
  209. */
  210. const boundFn = (context, identifier) => {
  211. /** @type {undefined | string} */
  212. let cachedResult;
  213. let innerSubCache = innerCache.get(context);
  214. if (innerSubCache === undefined) {
  215. innerCache.set(context, (innerSubCache = new Map()));
  216. } else {
  217. cachedResult = innerSubCache.get(identifier);
  218. }
  219. if (cachedResult !== undefined) {
  220. return cachedResult;
  221. }
  222. const result = fn(context, identifier);
  223. innerSubCache.set(identifier, result);
  224. return result;
  225. };
  226. return boundFn;
  227. };
  228. /** @type {BindContextCacheForContext} */
  229. cachedFn.bindContextCache = (context, associatedObjectForCache) => {
  230. /** @type {undefined | Map<string, string>} */
  231. let innerSubCache;
  232. if (associatedObjectForCache) {
  233. let innerCache = cache.get(associatedObjectForCache);
  234. if (innerCache === undefined) {
  235. innerCache = new Map();
  236. cache.set(associatedObjectForCache, innerCache);
  237. }
  238. innerSubCache = innerCache.get(context);
  239. if (innerSubCache === undefined) {
  240. innerCache.set(context, (innerSubCache = new Map()));
  241. }
  242. } else {
  243. innerSubCache = new Map();
  244. }
  245. /**
  246. * Returns the returned relative path.
  247. * @param {string} identifier identifier used to create relative path
  248. * @returns {string} the returned relative path
  249. */
  250. const boundFn = (identifier) => {
  251. const cachedResult = innerSubCache.get(identifier);
  252. if (cachedResult !== undefined) {
  253. return cachedResult;
  254. }
  255. const result = fn(context, identifier);
  256. innerSubCache.set(identifier, result);
  257. return result;
  258. };
  259. return boundFn;
  260. };
  261. return cachedFn;
  262. };
  263. /**
  264. * Make paths relative.
  265. * @param {string} context context for relative path
  266. * @param {string} identifier identifier for path
  267. * @returns {string} a converted relative path
  268. */
  269. const _makePathsRelative = (context, identifier) =>
  270. identifier
  271. .split(SEGMENTS_SPLIT_REGEXP)
  272. .map((str) => absoluteToRequest(context, str))
  273. .join("");
  274. /**
  275. * Make paths absolute.
  276. * @param {string} context context for relative path
  277. * @param {string} identifier identifier for path
  278. * @returns {string} a converted relative path
  279. */
  280. const _makePathsAbsolute = (context, identifier) =>
  281. identifier
  282. .split(SEGMENTS_SPLIT_REGEXP)
  283. .map((str) => requestToAbsolute(context, str))
  284. .join("");
  285. /**
  286. * Returns a new request string avoiding absolute paths when possible.
  287. * @param {string} context absolute context path
  288. * @param {string} request any request string may containing absolute paths, query string, etc.
  289. * @returns {string} a new request string avoiding absolute paths when possible
  290. */
  291. const _contextify = (context, request) =>
  292. request
  293. .split("!")
  294. .map((r) => absoluteToRequest(context, r))
  295. .join("!");
  296. const contextify = makeCacheableWithContext(_contextify);
  297. /**
  298. * Returns a new request string using absolute paths when possible.
  299. * @param {string} context absolute context path
  300. * @param {string} request any request string
  301. * @returns {string} a new request string using absolute paths when possible
  302. */
  303. const _absolutify = (context, request) =>
  304. request
  305. .split("!")
  306. .map((r) => requestToAbsolute(context, r))
  307. .join("!");
  308. const absolutify = makeCacheableWithContext(_absolutify);
  309. const PATH_QUERY_FRAGMENT_REGEXP =
  310. /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/;
  311. const PATH_QUERY_REGEXP = /^((?:\0.|[^?\0])*)(\?.*)?$/;
  312. const ZERO_ESCAPE_REGEXP = /\0(.)/g;
  313. /** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */
  314. /** @typedef {{ resource: string, path: string, query: string }} ParsedResourceWithoutFragment */
  315. /**
  316. * Returns parsed parts.
  317. * @param {string} str the path with query and fragment
  318. * @returns {ParsedResource} parsed parts
  319. */
  320. const _parseResource = (str) => {
  321. const firstEscape = str.indexOf("\0");
  322. // Handle `\0`
  323. if (firstEscape !== -1) {
  324. const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
  325. // malformed escaping (e.g. a trailing lone \0) never matches; treat as path
  326. if (!match) return { resource: str, path: str, query: "", fragment: "" };
  327. return {
  328. resource: str,
  329. path: match[1].replace(ZERO_ESCAPE_REGEXP, "$1"),
  330. query: match[2] ? match[2].replace(ZERO_ESCAPE_REGEXP, "$1") : "",
  331. fragment: match[3] || ""
  332. };
  333. }
  334. /** @type {ParsedResource} */
  335. const result = { resource: str, path: "", query: "", fragment: "" };
  336. const queryStart = str.indexOf("?");
  337. const fragmentStart = str.indexOf("#");
  338. if (fragmentStart < 0) {
  339. if (queryStart < 0) {
  340. result.path = result.resource;
  341. // No fragment, no query
  342. return result;
  343. }
  344. result.path = str.slice(0, queryStart);
  345. result.query = str.slice(queryStart);
  346. // Query, no fragment
  347. return result;
  348. }
  349. if (queryStart < 0 || fragmentStart < queryStart) {
  350. result.path = str.slice(0, fragmentStart);
  351. result.fragment = str.slice(fragmentStart);
  352. // Fragment, no query
  353. return result;
  354. }
  355. result.path = str.slice(0, queryStart);
  356. result.query = str.slice(queryStart, fragmentStart);
  357. result.fragment = str.slice(fragmentStart);
  358. // Query and fragment
  359. return result;
  360. };
  361. /**
  362. * Parse resource, skips fragment part
  363. * @param {string} str the path with query and fragment
  364. * @returns {ParsedResourceWithoutFragment} parsed parts
  365. */
  366. const _parseResourceWithoutFragment = (str) => {
  367. const firstEscape = str.indexOf("\0");
  368. // Handle `\0`
  369. if (firstEscape !== -1) {
  370. const match = PATH_QUERY_REGEXP.exec(str);
  371. // malformed escaping (e.g. a trailing lone \0) never matches; treat as path
  372. if (!match) return { resource: str, path: str, query: "" };
  373. return {
  374. resource: str,
  375. path: match[1].replace(ZERO_ESCAPE_REGEXP, "$1"),
  376. query: match[2] ? match[2].replace(ZERO_ESCAPE_REGEXP, "$1") : ""
  377. };
  378. }
  379. /** @type {ParsedResourceWithoutFragment} */
  380. const result = { resource: str, path: "", query: "" };
  381. const queryStart = str.indexOf("?");
  382. if (queryStart < 0) {
  383. result.path = result.resource;
  384. // No query
  385. return result;
  386. }
  387. result.path = str.slice(0, queryStart);
  388. result.query = str.slice(queryStart);
  389. // Query
  390. return result;
  391. };
  392. /**
  393. * Returns repeated ../ to leave the directory of the provided filename to be back on output dir.
  394. * @param {string} filename the filename which should be undone
  395. * @param {string} outputPath the output path that is restored (only relevant when filename contains "..")
  396. * @param {boolean} enforceRelative true returns ./ for empty paths
  397. * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir
  398. */
  399. const getUndoPath = (filename, outputPath, enforceRelative) => {
  400. let depth = -1;
  401. let append = "";
  402. outputPath = outputPath.replace(/[\\/]$/, "");
  403. for (const part of filename.split(/[/\\]+/)) {
  404. if (part === "..") {
  405. if (depth > -1) {
  406. depth--;
  407. } else {
  408. const i = outputPath.lastIndexOf("/");
  409. const j = outputPath.lastIndexOf("\\");
  410. const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j);
  411. if (pos < 0) return `${outputPath}/`;
  412. append = `${outputPath.slice(pos + 1)}/${append}`;
  413. outputPath = outputPath.slice(0, pos);
  414. }
  415. } else if (part !== ".") {
  416. depth++;
  417. }
  418. }
  419. return depth > 0
  420. ? `${"../".repeat(depth)}${append}`
  421. : enforceRelative
  422. ? `./${append}`
  423. : append;
  424. };
  425. const HASH_REGEXP = /(?<!\0)#/g;
  426. /**
  427. * Escape `#` characters that appear inside a path request's directory portion
  428. * with the `\0#` escape recognized by enhanced-resolve, so a project located at
  429. * a path like `/home/user/proj#1/` (or `./proj#1/`) resolves correctly. Applies
  430. * to absolute paths (Unix or Windows) and relative paths (starting with `./` or
  431. * `../`). Only triggers when a query string is present, because that is the case
  432. * where the resolver's parseIdentifier fails (without a `?`, the resolver
  433. * handles directory `#` via its own fallback). A `#` after the last path
  434. * separator is left alone so that explicit fragment requests like
  435. * `/abs/path/file.js#fragment` still behave the same. Bare module specifiers
  436. * are not touched. Already-escaped `\0#` sequences are preserved so the
  437. * explicit opt-out remains stable.
  438. * @param {string} request request to potentially escape
  439. * @returns {string} request with directory `#` characters escaped
  440. */
  441. const escapeHashInPathRequest = (request) => {
  442. if (request.length === 0) return request;
  443. const queryStart = request.indexOf("?");
  444. if (queryStart < 0) return request;
  445. const hashStart = request.indexOf("#");
  446. if (hashStart < 0 || hashStart >= queryStart) return request;
  447. const c0 = request.charCodeAt(0);
  448. const isAbsolute =
  449. c0 === 47 /* "/" */ || WINDOWS_ABS_PATH_REGEXP.test(request);
  450. let isRelative = false;
  451. if (!isAbsolute && c0 === 46 /* "." */) {
  452. const c1 = request.charCodeAt(1);
  453. if (c1 === 47 || c1 === 92 /* "/" or "\" */) {
  454. isRelative = true;
  455. } else if (c1 === 46 /* "." */) {
  456. const c2 = request.charCodeAt(2);
  457. if (c2 === 47 || c2 === 92) isRelative = true;
  458. }
  459. }
  460. if (!isAbsolute && !isRelative) return request;
  461. const lastSep = Math.max(
  462. request.lastIndexOf("/", queryStart - 1),
  463. request.lastIndexOf("\\", queryStart - 1)
  464. );
  465. if (hashStart >= lastSep) return request;
  466. const pathPart = request.slice(0, lastSep);
  467. return pathPart.replace(HASH_REGEXP, "\0#") + request.slice(lastSep);
  468. };
  469. const makePathsRelative = makeCacheableWithContext(_makePathsRelative);
  470. /**
  471. * Turns a source path into a `webpack://`-prefixed, context-relative source
  472. * URL, as used for the `sources` of module-level source maps.
  473. * @param {string} context absolute context path
  474. * @param {string} source a source path
  475. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  476. * @returns {string} new source path
  477. */
  478. const contextifySourceUrl = (context, source, associatedObjectForCache) => {
  479. if (source.startsWith("webpack://")) return source;
  480. return `webpack://${makePathsRelative(
  481. context,
  482. source,
  483. associatedObjectForCache
  484. )}`;
  485. };
  486. const LINE_SEPARATOR_REGEXP = /[\u2028\u2029]/g;
  487. /**
  488. * Quotes a string as a JS string literal safe to inline in generated code.
  489. * `JSON.stringify` leaves U+2028/U+2029 raw, but both terminate a JS string
  490. * literal (valid in JSON, not in JS), so escape them (matches JsonGenerator).
  491. * @param {string} str raw string
  492. * @returns {string} a quoted, inline-safe JS string literal
  493. */
  494. const toJsStringLiteral = (str) =>
  495. JSON.stringify(str).replace(LINE_SEPARATOR_REGEXP, (c) =>
  496. c === "\u2029" ? "\\u2029" : "\\u2028"
  497. );
  498. module.exports.ABSOLUTE_PATH_REGEXP = ABSOLUTE_PATH_REGEXP;
  499. module.exports.NODE_MODULES_REGEXP = NODE_MODULES_REGEXP;
  500. module.exports.WINDOWS_ABS_PATH_REGEXP = WINDOWS_ABS_PATH_REGEXP;
  501. module.exports.WINDOWS_PATH_SEPARATOR_REGEXP = WINDOWS_PATH_SEPARATOR_REGEXP;
  502. module.exports.absolutify = absolutify;
  503. module.exports.contextify = contextify;
  504. module.exports.contextifySourceUrl = contextifySourceUrl;
  505. module.exports.escapeHashInPathRequest = escapeHashInPathRequest;
  506. module.exports.getUndoPath = getUndoPath;
  507. module.exports.makeCacheable = makeCacheable;
  508. module.exports.makePathsAbsolute = makeCacheableWithContext(_makePathsAbsolute);
  509. module.exports.makePathsRelative = makePathsRelative;
  510. module.exports.parseResource = makeCacheable(_parseResource);
  511. module.exports.parseResourceWithoutFragment = makeCacheable(
  512. _parseResourceWithoutFragment
  513. );
  514. module.exports.relativePathToRequest = relativePathToRequest;
  515. module.exports.toJsStringLiteral = toJsStringLiteral;