1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | /** @typedef {import("./Resolver")} Resolver */
|
---|
9 | /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
|
---|
10 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
---|
11 |
|
---|
12 | module.exports = class ParsePlugin {
|
---|
13 | /**
|
---|
14 | * @param {string | ResolveStepHook} source source
|
---|
15 | * @param {Partial<ResolveRequest>} requestOptions request options
|
---|
16 | * @param {string | ResolveStepHook} target target
|
---|
17 | */
|
---|
18 | constructor(source, requestOptions, target) {
|
---|
19 | this.source = source;
|
---|
20 | this.requestOptions = requestOptions;
|
---|
21 | this.target = target;
|
---|
22 | }
|
---|
23 |
|
---|
24 | /**
|
---|
25 | * @param {Resolver} resolver the resolver
|
---|
26 | * @returns {void}
|
---|
27 | */
|
---|
28 | apply(resolver) {
|
---|
29 | const target = resolver.ensureHook(this.target);
|
---|
30 | resolver
|
---|
31 | .getHook(this.source)
|
---|
32 | .tapAsync("ParsePlugin", (request, resolveContext, callback) => {
|
---|
33 | const parsed = resolver.parse(/** @type {string} */ (request.request));
|
---|
34 | const obj = { ...request, ...parsed, ...this.requestOptions };
|
---|
35 | if (request.query && !parsed.query) {
|
---|
36 | obj.query = request.query;
|
---|
37 | }
|
---|
38 | if (request.fragment && !parsed.fragment) {
|
---|
39 | obj.fragment = request.fragment;
|
---|
40 | }
|
---|
41 | if (parsed && resolveContext.log) {
|
---|
42 | if (parsed.module) resolveContext.log("Parsed request is a module");
|
---|
43 | if (parsed.directory)
|
---|
44 | resolveContext.log("Parsed request is a directory");
|
---|
45 | }
|
---|
46 | // There is an edge-case where a request with # can be a path or a fragment -> try both
|
---|
47 | if (obj.request && !obj.query && obj.fragment) {
|
---|
48 | const directory = obj.fragment.endsWith("/");
|
---|
49 | const alternative = {
|
---|
50 | ...obj,
|
---|
51 | directory,
|
---|
52 | request:
|
---|
53 | obj.request +
|
---|
54 | (obj.directory ? "/" : "") +
|
---|
55 | (directory ? obj.fragment.slice(0, -1) : obj.fragment),
|
---|
56 | fragment: ""
|
---|
57 | };
|
---|
58 | resolver.doResolve(
|
---|
59 | target,
|
---|
60 | alternative,
|
---|
61 | null,
|
---|
62 | resolveContext,
|
---|
63 | (err, result) => {
|
---|
64 | if (err) return callback(err);
|
---|
65 | if (result) return callback(null, result);
|
---|
66 | resolver.doResolve(target, obj, null, resolveContext, callback);
|
---|
67 | }
|
---|
68 | );
|
---|
69 | return;
|
---|
70 | }
|
---|
71 | resolver.doResolve(target, obj, null, resolveContext, callback);
|
---|
72 | });
|
---|
73 | }
|
---|
74 | };
|
---|