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