identifier.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. /** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */
  285. /** @typedef {{ resource: string, path: string, query: string }} ParsedResourceWithoutFragment */
  286. /**
  287. * @param {string} str the path with query and fragment
  288. * @returns {ParsedResource} parsed parts
  289. */
  290. const _parseResource = str => {
  291. const match =
  292. /** @type {[string, string, string | undefined, string | undefined]} */
  293. (/** @type {unknown} */ (PATH_QUERY_FRAGMENT_REGEXP.exec(str)));
  294. return {
  295. resource: str,
  296. path: match[1].replace(/\0(.)/g, "$1"),
  297. query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "",
  298. fragment: match[3] || ""
  299. };
  300. };
  301. /**
  302. * Parse resource, skips fragment part
  303. * @param {string} str the path with query and fragment
  304. * @returns {ParsedResourceWithoutFragment} parsed parts
  305. */
  306. const _parseResourceWithoutFragment = str => {
  307. const match =
  308. /** @type {[string, string, string | undefined]} */
  309. (/** @type {unknown} */ (PATH_QUERY_REGEXP.exec(str)));
  310. return {
  311. resource: str,
  312. path: match[1].replace(/\0(.)/g, "$1"),
  313. query: match[2] ? match[2].replace(/\0(.)/g, "$1") : ""
  314. };
  315. };
  316. /**
  317. * @param {string} filename the filename which should be undone
  318. * @param {string} outputPath the output path that is restored (only relevant when filename contains "..")
  319. * @param {boolean} enforceRelative true returns ./ for empty paths
  320. * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir
  321. */
  322. const getUndoPath = (filename, outputPath, enforceRelative) => {
  323. let depth = -1;
  324. let append = "";
  325. outputPath = outputPath.replace(/[\\/]$/, "");
  326. for (const part of filename.split(/[/\\]+/)) {
  327. if (part === "..") {
  328. if (depth > -1) {
  329. depth--;
  330. } else {
  331. const i = outputPath.lastIndexOf("/");
  332. const j = outputPath.lastIndexOf("\\");
  333. const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j);
  334. if (pos < 0) return `${outputPath}/`;
  335. append = `${outputPath.slice(pos + 1)}/${append}`;
  336. outputPath = outputPath.slice(0, pos);
  337. }
  338. } else if (part !== ".") {
  339. depth++;
  340. }
  341. }
  342. return depth > 0
  343. ? `${"../".repeat(depth)}${append}`
  344. : enforceRelative
  345. ? `./${append}`
  346. : append;
  347. };
  348. module.exports.absolutify = absolutify;
  349. module.exports.contextify = contextify;
  350. module.exports.getUndoPath = getUndoPath;
  351. module.exports.makePathsAbsolute = makeCacheableWithContext(_makePathsAbsolute);
  352. module.exports.makePathsRelative = makeCacheableWithContext(_makePathsRelative);
  353. module.exports.parseResource = makeCacheable(_parseResource);
  354. module.exports.parseResourceWithoutFragment = makeCacheable(
  355. _parseResourceWithoutFragment
  356. );