identifier.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const path = require("path");
  6. const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/;
  7. const SEGMENTS_SPLIT_REGEXP = /([|!])/;
  8. const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g;
  9. /**
  10. * @param {string} relativePath relative path
  11. * @returns {string} request
  12. */
  13. const relativePathToRequest = (relativePath) => {
  14. if (relativePath === "") return "./.";
  15. if (relativePath === "..") return "../.";
  16. if (relativePath.startsWith("../")) return relativePath;
  17. return `./${relativePath}`;
  18. };
  19. /**
  20. * @param {string} context context for relative path
  21. * @param {string} maybeAbsolutePath path to make relative
  22. * @returns {string} relative path in request style
  23. */
  24. const absoluteToRequest = (context, maybeAbsolutePath) => {
  25. if (maybeAbsolutePath[0] === "/") {
  26. if (
  27. maybeAbsolutePath.length > 1 &&
  28. maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/"
  29. ) {
  30. // this 'path' is actually a regexp generated by dynamic requires.
  31. // Don't treat it as an absolute path.
  32. return maybeAbsolutePath;
  33. }
  34. const querySplitPos = maybeAbsolutePath.indexOf("?");
  35. let resource =
  36. querySplitPos === -1
  37. ? maybeAbsolutePath
  38. : maybeAbsolutePath.slice(0, querySplitPos);
  39. resource = relativePathToRequest(path.posix.relative(context, resource));
  40. return querySplitPos === -1
  41. ? resource
  42. : resource + maybeAbsolutePath.slice(querySplitPos);
  43. }
  44. if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) {
  45. const querySplitPos = maybeAbsolutePath.indexOf("?");
  46. let resource =
  47. querySplitPos === -1
  48. ? maybeAbsolutePath
  49. : maybeAbsolutePath.slice(0, querySplitPos);
  50. resource = path.win32.relative(context, resource);
  51. if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) {
  52. resource = relativePathToRequest(
  53. resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/")
  54. );
  55. }
  56. return querySplitPos === -1
  57. ? resource
  58. : resource + maybeAbsolutePath.slice(querySplitPos);
  59. }
  60. // not an absolute path
  61. return maybeAbsolutePath;
  62. };
  63. /**
  64. * @param {string} context context for relative path
  65. * @param {string} relativePath path
  66. * @returns {string} absolute path
  67. */
  68. const requestToAbsolute = (context, relativePath) => {
  69. if (relativePath.startsWith("./") || relativePath.startsWith("../")) {
  70. return path.join(context, relativePath);
  71. }
  72. return relativePath;
  73. };
  74. /** @typedef {EXPECTED_OBJECT} AssociatedObjectForCache */
  75. /**
  76. * @template T
  77. * @typedef {(value: string, cache?: AssociatedObjectForCache) => T} MakeCacheableResult
  78. */
  79. /**
  80. * @template T
  81. * @typedef {(value: string) => T} BindCacheResultFn
  82. */
  83. /**
  84. * @template T
  85. * @typedef {(cache: AssociatedObjectForCache) => BindCacheResultFn<T>} BindCache
  86. */
  87. /**
  88. * @template T
  89. * @param {((value: string) => T)} realFn real function
  90. * @returns {MakeCacheableResult<T> & { bindCache: BindCache<T> }} cacheable function
  91. */
  92. const makeCacheable = (realFn) => {
  93. /**
  94. * @template T
  95. * @typedef {Map<string, T>} CacheItem
  96. */
  97. /** @type {WeakMap<AssociatedObjectForCache, CacheItem<T>>} */
  98. const cache = new WeakMap();
  99. /**
  100. * @param {AssociatedObjectForCache} associatedObjectForCache an object to which the cache will be attached
  101. * @returns {CacheItem<T>} cache item
  102. */
  103. const getCache = (associatedObjectForCache) => {
  104. const entry = cache.get(associatedObjectForCache);
  105. if (entry !== undefined) return entry;
  106. /** @type {Map<string, T>} */
  107. const map = new Map();
  108. cache.set(associatedObjectForCache, map);
  109. return map;
  110. };
  111. /** @type {MakeCacheableResult<T> & { bindCache: BindCache<T> }} */
  112. const fn = (str, associatedObjectForCache) => {
  113. if (!associatedObjectForCache) return realFn(str);
  114. const cache = getCache(associatedObjectForCache);
  115. const entry = cache.get(str);
  116. if (entry !== undefined) return entry;
  117. const result = realFn(str);
  118. cache.set(str, result);
  119. return result;
  120. };
  121. /** @type {BindCache<T>} */
  122. fn.bindCache = (associatedObjectForCache) => {
  123. const cache = getCache(associatedObjectForCache);
  124. /**
  125. * @param {string} str string
  126. * @returns {T} value
  127. */
  128. return (str) => {
  129. const entry = cache.get(str);
  130. if (entry !== undefined) return entry;
  131. const result = realFn(str);
  132. cache.set(str, result);
  133. return result;
  134. };
  135. };
  136. return fn;
  137. };
  138. /** @typedef {(context: string, value: string, associatedObjectForCache?: AssociatedObjectForCache) => string} MakeCacheableWithContextResult */
  139. /** @typedef {(context: string, value: string) => string} BindCacheForContextResultFn */
  140. /** @typedef {(value: string) => string} BindContextCacheForContextResultFn */
  141. /** @typedef {(associatedObjectForCache?: AssociatedObjectForCache) => BindCacheForContextResultFn} BindCacheForContext */
  142. /** @typedef {(value: string, associatedObjectForCache?: AssociatedObjectForCache) => BindContextCacheForContextResultFn} BindContextCacheForContext */
  143. /**
  144. * @param {(context: string, identifier: string) => string} fn function
  145. * @returns {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} cacheable function with context
  146. */
  147. const makeCacheableWithContext = (fn) => {
  148. /** @type {WeakMap<AssociatedObjectForCache, Map<string, Map<string, string>>>} */
  149. const cache = new WeakMap();
  150. /** @type {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} */
  151. const cachedFn = (context, identifier, associatedObjectForCache) => {
  152. if (!associatedObjectForCache) return fn(context, identifier);
  153. let innerCache = cache.get(associatedObjectForCache);
  154. if (innerCache === undefined) {
  155. innerCache = new Map();
  156. cache.set(associatedObjectForCache, innerCache);
  157. }
  158. let cachedResult;
  159. let innerSubCache = innerCache.get(context);
  160. if (innerSubCache === undefined) {
  161. innerCache.set(context, (innerSubCache = new Map()));
  162. } else {
  163. cachedResult = innerSubCache.get(identifier);
  164. }
  165. if (cachedResult !== undefined) {
  166. return cachedResult;
  167. }
  168. const result = fn(context, identifier);
  169. innerSubCache.set(identifier, result);
  170. return result;
  171. };
  172. /** @type {BindCacheForContext} */
  173. cachedFn.bindCache = (associatedObjectForCache) => {
  174. let innerCache;
  175. if (associatedObjectForCache) {
  176. innerCache = cache.get(associatedObjectForCache);
  177. if (innerCache === undefined) {
  178. innerCache = new Map();
  179. cache.set(associatedObjectForCache, innerCache);
  180. }
  181. } else {
  182. innerCache = new Map();
  183. }
  184. /**
  185. * @param {string} context context used to create relative path
  186. * @param {string} identifier identifier used to create relative path
  187. * @returns {string} the returned relative path
  188. */
  189. const boundFn = (context, identifier) => {
  190. let cachedResult;
  191. let innerSubCache = innerCache.get(context);
  192. if (innerSubCache === undefined) {
  193. innerCache.set(context, (innerSubCache = new Map()));
  194. } else {
  195. cachedResult = innerSubCache.get(identifier);
  196. }
  197. if (cachedResult !== undefined) {
  198. return cachedResult;
  199. }
  200. const result = fn(context, identifier);
  201. innerSubCache.set(identifier, result);
  202. return result;
  203. };
  204. return boundFn;
  205. };
  206. /** @type {BindContextCacheForContext} */
  207. cachedFn.bindContextCache = (context, associatedObjectForCache) => {
  208. let innerSubCache;
  209. if (associatedObjectForCache) {
  210. let innerCache = cache.get(associatedObjectForCache);
  211. if (innerCache === undefined) {
  212. innerCache = new Map();
  213. cache.set(associatedObjectForCache, innerCache);
  214. }
  215. innerSubCache = innerCache.get(context);
  216. if (innerSubCache === undefined) {
  217. innerCache.set(context, (innerSubCache = new Map()));
  218. }
  219. } else {
  220. innerSubCache = new Map();
  221. }
  222. /**
  223. * @param {string} identifier identifier used to create relative path
  224. * @returns {string} the returned relative path
  225. */
  226. const boundFn = (identifier) => {
  227. const cachedResult = innerSubCache.get(identifier);
  228. if (cachedResult !== undefined) {
  229. return cachedResult;
  230. }
  231. const result = fn(context, identifier);
  232. innerSubCache.set(identifier, result);
  233. return result;
  234. };
  235. return boundFn;
  236. };
  237. return cachedFn;
  238. };
  239. /**
  240. * @param {string} context context for relative path
  241. * @param {string} identifier identifier for path
  242. * @returns {string} a converted relative path
  243. */
  244. const _makePathsRelative = (context, identifier) =>
  245. identifier
  246. .split(SEGMENTS_SPLIT_REGEXP)
  247. .map((str) => absoluteToRequest(context, str))
  248. .join("");
  249. /**
  250. * @param {string} context context for relative path
  251. * @param {string} identifier identifier for path
  252. * @returns {string} a converted relative path
  253. */
  254. const _makePathsAbsolute = (context, identifier) =>
  255. identifier
  256. .split(SEGMENTS_SPLIT_REGEXP)
  257. .map((str) => requestToAbsolute(context, str))
  258. .join("");
  259. /**
  260. * @param {string} context absolute context path
  261. * @param {string} request any request string may containing absolute paths, query string, etc.
  262. * @returns {string} a new request string avoiding absolute paths when possible
  263. */
  264. const _contextify = (context, request) =>
  265. request
  266. .split("!")
  267. .map((r) => absoluteToRequest(context, r))
  268. .join("!");
  269. const contextify = makeCacheableWithContext(_contextify);
  270. /**
  271. * @param {string} context absolute context path
  272. * @param {string} request any request string
  273. * @returns {string} a new request string using absolute paths when possible
  274. */
  275. const _absolutify = (context, request) =>
  276. request
  277. .split("!")
  278. .map((r) => requestToAbsolute(context, r))
  279. .join("!");
  280. const absolutify = makeCacheableWithContext(_absolutify);
  281. const PATH_QUERY_FRAGMENT_REGEXP =
  282. /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/;
  283. const PATH_QUERY_REGEXP = /^((?:\0.|[^?\0])*)(\?.*)?$/;
  284. const ZERO_ESCAPE_REGEXP = /\0(.)/g;
  285. /** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */
  286. /** @typedef {{ resource: string, path: string, query: string }} ParsedResourceWithoutFragment */
  287. /**
  288. * @param {string} str the path with query and fragment
  289. * @returns {ParsedResource} parsed parts
  290. */
  291. const _parseResource = (str) => {
  292. const firstEscape = str.indexOf("\0");
  293. // Handle `\0`
  294. if (firstEscape !== -1) {
  295. const match =
  296. /** @type {[string, string, string | undefined, string | undefined]} */
  297. (/** @type {unknown} */ (PATH_QUERY_FRAGMENT_REGEXP.exec(str)));
  298. return {
  299. resource: str,
  300. path: match[1].replace(ZERO_ESCAPE_REGEXP, "$1"),
  301. query: match[2] ? match[2].replace(ZERO_ESCAPE_REGEXP, "$1") : "",
  302. fragment: match[3] || ""
  303. };
  304. }
  305. /** @type {ParsedResource} */
  306. const result = { resource: str, path: "", query: "", fragment: "" };
  307. const queryStart = str.indexOf("?");
  308. const fragmentStart = str.indexOf("#");
  309. if (fragmentStart < 0) {
  310. if (queryStart < 0) {
  311. result.path = result.resource;
  312. // No fragment, no query
  313. return result;
  314. }
  315. result.path = str.slice(0, queryStart);
  316. result.query = str.slice(queryStart);
  317. // Query, no fragment
  318. return result;
  319. }
  320. if (queryStart < 0 || fragmentStart < queryStart) {
  321. result.path = str.slice(0, fragmentStart);
  322. result.fragment = str.slice(fragmentStart);
  323. // Fragment, no query
  324. return result;
  325. }
  326. result.path = str.slice(0, queryStart);
  327. result.query = str.slice(queryStart, fragmentStart);
  328. result.fragment = str.slice(fragmentStart);
  329. // Query and fragment
  330. return result;
  331. };
  332. /**
  333. * Parse resource, skips fragment part
  334. * @param {string} str the path with query and fragment
  335. * @returns {ParsedResourceWithoutFragment} parsed parts
  336. */
  337. const _parseResourceWithoutFragment = (str) => {
  338. const firstEscape = str.indexOf("\0");
  339. // Handle `\0`
  340. if (firstEscape !== -1) {
  341. const match =
  342. /** @type {[string, string, string | undefined]} */
  343. (/** @type {unknown} */ (PATH_QUERY_REGEXP.exec(str)));
  344. return {
  345. resource: str,
  346. path: match[1].replace(ZERO_ESCAPE_REGEXP, "$1"),
  347. query: match[2] ? match[2].replace(ZERO_ESCAPE_REGEXP, "$1") : ""
  348. };
  349. }
  350. /** @type {ParsedResourceWithoutFragment} */
  351. const result = { resource: str, path: "", query: "" };
  352. const queryStart = str.indexOf("?");
  353. if (queryStart < 0) {
  354. result.path = result.resource;
  355. // No query
  356. return result;
  357. }
  358. result.path = str.slice(0, queryStart);
  359. result.query = str.slice(queryStart);
  360. // Query
  361. return result;
  362. };
  363. /**
  364. * @param {string} filename the filename which should be undone
  365. * @param {string} outputPath the output path that is restored (only relevant when filename contains "..")
  366. * @param {boolean} enforceRelative true returns ./ for empty paths
  367. * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir
  368. */
  369. const getUndoPath = (filename, outputPath, enforceRelative) => {
  370. let depth = -1;
  371. let append = "";
  372. outputPath = outputPath.replace(/[\\/]$/, "");
  373. for (const part of filename.split(/[/\\]+/)) {
  374. if (part === "..") {
  375. if (depth > -1) {
  376. depth--;
  377. } else {
  378. const i = outputPath.lastIndexOf("/");
  379. const j = outputPath.lastIndexOf("\\");
  380. const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j);
  381. if (pos < 0) return `${outputPath}/`;
  382. append = `${outputPath.slice(pos + 1)}/${append}`;
  383. outputPath = outputPath.slice(0, pos);
  384. }
  385. } else if (part !== ".") {
  386. depth++;
  387. }
  388. }
  389. return depth > 0
  390. ? `${"../".repeat(depth)}${append}`
  391. : enforceRelative
  392. ? `./${append}`
  393. : append;
  394. };
  395. module.exports.absolutify = absolutify;
  396. module.exports.contextify = contextify;
  397. module.exports.getUndoPath = getUndoPath;
  398. module.exports.makePathsAbsolute = makeCacheableWithContext(_makePathsAbsolute);
  399. module.exports.makePathsRelative = makeCacheableWithContext(_makePathsRelative);
  400. module.exports.parseResource = makeCacheable(_parseResource);
  401. module.exports.parseResourceWithoutFragment = makeCacheable(
  402. _parseResourceWithoutFragment
  403. );