1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const DescriptionFileUtils = require("./DescriptionFileUtils");
|
---|
9 |
|
---|
10 | /** @typedef {import("./Resolver")} Resolver */
|
---|
11 | /** @typedef {import("./Resolver").JsonObject} JsonObject */
|
---|
12 | /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
|
---|
13 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
---|
14 |
|
---|
15 | const slashCode = "/".charCodeAt(0);
|
---|
16 |
|
---|
17 | module.exports = class SelfReferencePlugin {
|
---|
18 | /**
|
---|
19 | * @param {string | ResolveStepHook} source source
|
---|
20 | * @param {string | string[]} fieldNamePath name path
|
---|
21 | * @param {string | ResolveStepHook} target target
|
---|
22 | */
|
---|
23 | constructor(source, fieldNamePath, target) {
|
---|
24 | this.source = source;
|
---|
25 | this.target = target;
|
---|
26 | this.fieldName = fieldNamePath;
|
---|
27 | }
|
---|
28 |
|
---|
29 | /**
|
---|
30 | * @param {Resolver} resolver the resolver
|
---|
31 | * @returns {void}
|
---|
32 | */
|
---|
33 | apply(resolver) {
|
---|
34 | const target = resolver.ensureHook(this.target);
|
---|
35 | resolver
|
---|
36 | .getHook(this.source)
|
---|
37 | .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => {
|
---|
38 | if (!request.descriptionFilePath) return callback();
|
---|
39 |
|
---|
40 | const req = request.request;
|
---|
41 | if (!req) return callback();
|
---|
42 |
|
---|
43 | // Feature is only enabled when an exports field is present
|
---|
44 | const exportsField = DescriptionFileUtils.getField(
|
---|
45 | /** @type {JsonObject} */ (request.descriptionFileData),
|
---|
46 | this.fieldName
|
---|
47 | );
|
---|
48 | if (!exportsField) return callback();
|
---|
49 |
|
---|
50 | const name = DescriptionFileUtils.getField(
|
---|
51 | /** @type {JsonObject} */ (request.descriptionFileData),
|
---|
52 | "name"
|
---|
53 | );
|
---|
54 | if (typeof name !== "string") return callback();
|
---|
55 |
|
---|
56 | if (
|
---|
57 | req.startsWith(name) &&
|
---|
58 | (req.length === name.length ||
|
---|
59 | req.charCodeAt(name.length) === slashCode)
|
---|
60 | ) {
|
---|
61 | const remainingRequest = `.${req.slice(name.length)}`;
|
---|
62 | /** @type {ResolveRequest} */
|
---|
63 | const obj = {
|
---|
64 | ...request,
|
---|
65 | request: remainingRequest,
|
---|
66 | path: /** @type {string} */ (request.descriptionFileRoot),
|
---|
67 | relativePath: "."
|
---|
68 | };
|
---|
69 |
|
---|
70 | resolver.doResolve(
|
---|
71 | target,
|
---|
72 | obj,
|
---|
73 | "self reference",
|
---|
74 | resolveContext,
|
---|
75 | callback
|
---|
76 | );
|
---|
77 | } else {
|
---|
78 | return callback();
|
---|
79 | }
|
---|
80 | });
|
---|
81 | }
|
---|
82 | };
|
---|