index.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. * MIT License http://opensource.org/licenses/MIT
  3. * Author: Ben Holloway @bholloway
  4. */
  5. 'use strict';
  6. const path = require('path');
  7. const { createDebugLogger, formatJoinMessage } = require('./debug');
  8. const fsUtils = require('./fs-utils');
  9. const ITERATION_SAFETY_LIMIT = 100e3;
  10. /**
  11. * Wrap a function such that it always returns a generator of tuple elements.
  12. *
  13. * @param {function({uri:string},...):(Array|Iterator)<[string,string]|string>} fn The function to wrap
  14. * @returns {function({uri:string},...):(Array|Iterator)<[string,string]>} A function that always returns tuple elements
  15. */
  16. const asGenerator = (fn) => {
  17. const toTuple = (defaults) => (value) => {
  18. const partial = [].concat(value);
  19. return [...partial, ...defaults.slice(partial.length)];
  20. };
  21. const isTupleUnique = (v, i, a) => {
  22. const required = v.join(',');
  23. return a.findIndex((vv) => vv.join(',') === required) === i;
  24. };
  25. return (item, ...rest) => {
  26. const {uri} = item;
  27. const mapTuple = toTuple([null, uri]);
  28. const pending = fn(item, ...rest);
  29. if (Array.isArray(pending)) {
  30. return pending.map(mapTuple).filter(isTupleUnique)[Symbol.iterator]();
  31. } else if (
  32. pending &&
  33. (typeof pending === 'object') &&
  34. (typeof pending.next === 'function') &&
  35. (pending.next.length === 0)
  36. ) {
  37. return pending;
  38. } else {
  39. throw new TypeError(`in "join" function expected "generator" to return Array|Iterator`);
  40. }
  41. };
  42. };
  43. exports.asGenerator = asGenerator;
  44. /**
  45. * A high-level utility to create a join function.
  46. *
  47. * The `generator` is responsible for ordering possible base paths. The `operation` is responsible for joining a single
  48. * `base` path with the given `uri`. The `predicate` is responsible for reporting whether the single joined value is
  49. * successful as the overall result.
  50. *
  51. * Both the `generator` and `operation` may be `function*()` or simply `function(...):Array<string>`.
  52. *
  53. * @param {function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
  54. * selector:string}}, {filename:string, fs:Object, debug:function|boolean, root:string}):
  55. * (Array<string>|Iterator<string>)} generator A function that takes the hash of base paths from the `engine` and
  56. * returns ordered iterable of paths to consider
  57. * @returns {function({filename:string, fs:Object, debug:function|boolean, root:string}):
  58. * (function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
  59. * selector:string}}):string)} join implementation
  60. */
  61. const createJoinImplementation = (generator) => (item, options, loader) => {
  62. const { isAbsolute } = item;
  63. const { root } = options;
  64. const { fs } = loader;
  65. // generate the iterator
  66. const iterator = generator(item, options, loader);
  67. const isValidIterator = iterator && typeof iterator === 'object' && typeof iterator.next === 'function';
  68. if (!isValidIterator) {
  69. throw new Error('expected generator to return Iterator');
  70. }
  71. // run the iterator lazily and record attempts
  72. const { isFileSync, isDirectorySync } = fsUtils(fs);
  73. const attempts = [];
  74. for (let i = 0; i < ITERATION_SAFETY_LIMIT; i++) {
  75. const { value, done } = iterator.next();
  76. if (done) {
  77. break;
  78. } else if (value) {
  79. const tuple = Array.isArray(value) && value.length === 2 ? value : null;
  80. if (!tuple) {
  81. throw new Error('expected Iterator values to be tuple of [string,string], do you need asGenerator utility?');
  82. }
  83. // skip elements where base or uri is non-string
  84. // noting that we need to support base="" when root=""
  85. const [base, uri] = value;
  86. if ((typeof base === 'string') && (typeof uri === 'string')) {
  87. // validate
  88. const isValidBase = (isAbsolute && base === root) || (path.isAbsolute(base) && isDirectorySync(base));
  89. if (!isValidBase) {
  90. throw new Error(`expected "base" to be absolute path to a valid directory, got "${base}"`);
  91. }
  92. // make the attempt
  93. const joined = path.normalize(path.join(base, uri));
  94. const isFallback = true;
  95. const isSuccess = isFileSync(joined);
  96. attempts.push({base, uri, joined, isFallback, isSuccess});
  97. if (isSuccess) {
  98. break;
  99. }
  100. // validate any non-strings are falsey
  101. } else {
  102. const isValidTuple = value.every((v) => (typeof v === 'string') || !v);
  103. if (!isValidTuple) {
  104. throw new Error('expected Iterator values to be tuple of [string,string]');
  105. }
  106. }
  107. }
  108. }
  109. return attempts;
  110. };
  111. exports.createJoinImplementation = createJoinImplementation;
  112. /**
  113. * A low-level utility to create a join function.
  114. *
  115. * The `implementation` function processes an individual `item` and returns an Array of attempts. Each attempt consists
  116. * of a `base` and a `joined` value with `isSuccessful` and `isFallback` flags.
  117. *
  118. * In the case that any attempt `isSuccessful` then its `joined` value is the outcome. Otherwise the first `isFallback`
  119. * attempt is used. If there is no successful or fallback attempts then `null` is returned indicating no change to the
  120. * original URI in the CSS.
  121. *
  122. * The `attempts` Array is logged to console when in `debug` mode.
  123. *
  124. * @param {string} name Name for the resulting join function
  125. * @param {function({uri:string, query:string, isAbsolute:boolean, bases:{subString:string, value:string,
  126. * property:string, selector:string}}, {filename:string, fs:Object, debug:function|boolean, root:string}):
  127. * Array<{base:string,joined:string,fallback?:string,result?:string}>} implementation A function accepts an item and
  128. * returns a list of attempts
  129. * @returns {function({filename:string, fs:Object, debug:function|boolean, root:string}):
  130. * (function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
  131. * selector:string}}):string)} join function
  132. */
  133. const createJoinFunction = (name, implementation) => {
  134. const assertAttempts = (value) => {
  135. const isValid =
  136. Array.isArray(value) && value.every((v) =>
  137. v &&
  138. (typeof v === 'object') &&
  139. (typeof v.base === 'string') &&
  140. (typeof v.uri === 'string') &&
  141. (typeof v.joined === 'string') &&
  142. (typeof v.isSuccess === 'boolean') &&
  143. (typeof v.isFallback === 'boolean')
  144. );
  145. if (!isValid) {
  146. throw new Error(`expected implementation to return Array of {base, uri, joined, isSuccess, isFallback}`);
  147. } else {
  148. return value;
  149. }
  150. };
  151. const assertJoined = (value) => {
  152. const isValid = value && (typeof value === 'string') && path.isAbsolute(value) || (value === null);
  153. if (!isValid) {
  154. throw new Error(`expected "joined" to be absolute path, got "${value}"`);
  155. } else {
  156. return value;
  157. }
  158. };
  159. const join = (options, loader) => {
  160. const { debug } = options;
  161. const { resourcePath } = loader;
  162. const log = createDebugLogger(debug);
  163. return (item) => {
  164. const { uri } = item;
  165. const attempts = implementation(item, options, loader);
  166. assertAttempts(attempts, !!debug);
  167. const { joined: fallback } = attempts.find(({ isFallback }) => isFallback) || {};
  168. const { joined: result } = attempts.find(({ isSuccess }) => isSuccess) || {};
  169. log(formatJoinMessage, [resourcePath, uri, attempts]);
  170. return assertJoined(result || fallback || null);
  171. };
  172. };
  173. const toString = () => '[Function ' + name + ']';
  174. return Object.assign(join, !!name && {
  175. toString,
  176. toJSON: toString
  177. });
  178. };
  179. exports.createJoinFunction = createJoinFunction;
  180. /**
  181. * The default iterable factory will order `subString` then `value` then `property` then `selector`.
  182. *
  183. * @param {string} uri The uri given in the file webpack is processing
  184. * @param {boolean} isAbsolute True for absolute URIs, false for relative URIs
  185. * @param {string} subString A possible base path
  186. * @param {string} value A possible base path
  187. * @param {string} property A possible base path
  188. * @param {string} selector A possible base path
  189. * @param {string} root The loader options.root value where given
  190. * @returns {Array<string>} An iterable of possible base paths in preference order
  191. */
  192. const defaultJoinGenerator = asGenerator(
  193. ({ uri, isAbsolute, bases: { subString, value, property, selector } }, { root }) =>
  194. isAbsolute ? [root] : [subString, value, property, selector]
  195. );
  196. exports.defaultJoinGenerator = defaultJoinGenerator;
  197. /**
  198. * @type {function({filename:string, fs:Object, debug:function|boolean, root:string}):
  199. * (function({uri:string, isAbsolute:boolean, bases:{subString:string, value:string, property:string,
  200. * selector:string}}):string)} join function
  201. */
  202. exports.defaultJoin = createJoinFunction(
  203. 'defaultJoin',
  204. createJoinImplementation(defaultJoinGenerator)
  205. );