source: trip-planner-front/node_modules/resolve-url-loader/lib/join-function/index.js@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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