UNPKG

9.83 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
14 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
16 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
17 return c > 3 && r && Object.defineProperty(target, key, r), r;
18};
19var __read = (this && this.__read) || function (o, n) {
20 var m = typeof Symbol === "function" && o[Symbol.iterator];
21 if (!m) return o;
22 var i = m.call(o), r, ar = [], e;
23 try {
24 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
25 }
26 catch (error) { e = { error: error }; }
27 finally {
28 try {
29 if (r && !r.done && (m = i["return"])) m.call(i);
30 }
31 finally { if (e) throw e.error; }
32 }
33 return ar;
34};
35var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
36 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
37 if (ar || !(i in from)) {
38 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
39 ar[i] = from[i];
40 }
41 }
42 return to.concat(ar || Array.prototype.slice.call(from));
43};
44Object.defineProperty(exports, "__esModule", { value: true });
45exports.importer = exports.Importer = void 0;
46exports.__requireModule = __requireModule;
47var logger_1 = require("./logger");
48var memoize_1 = require("./memoize");
49var messages_1 = require("./messages");
50var version_checkers_1 = require("./version-checkers");
51var logger = logger_1.rootLogger.child({ namespace: 'Importer' });
52// eslint-disable-next-line @typescript-eslint/no-explicit-any
53var passThru = function (action) { return function (input) {
54 action();
55 return input;
56}; };
57/**
58 * @internal
59 */
60var Importer = /** @class */ (function () {
61 function Importer(_patches) {
62 if (_patches === void 0) { _patches = {}; }
63 this._patches = _patches;
64 }
65 Object.defineProperty(Importer, "instance", {
66 get: function () {
67 logger.debug('creating Importer singleton');
68 // here we can define patches to apply to modules.
69 // it could be fixes that are not deployed, or
70 // abstractions so that multiple versions work the same
71 return new Importer({
72 '@babel/core': [passThru(version_checkers_1.VersionCheckers.babelCore.warn)],
73 'babel-jest': [passThru(version_checkers_1.VersionCheckers.babelJest.warn)],
74 typescript: [passThru(version_checkers_1.VersionCheckers.typescript.warn)],
75 jest: [passThru(version_checkers_1.VersionCheckers.jest.warn)],
76 });
77 },
78 enumerable: false,
79 configurable: true
80 });
81 Importer.prototype.babelJest = function (why) {
82 return this._import(why, 'babel-jest');
83 };
84 Importer.prototype.babelCore = function (why) {
85 return this._import(why, '@babel/core');
86 };
87 Importer.prototype.typescript = function (why, which) {
88 return this._import(why, which);
89 };
90 Importer.prototype.esBuild = function (why) {
91 return this._import(why, 'esbuild');
92 };
93 Importer.prototype.tryThese = function (moduleName) {
94 var fallbacks = [];
95 for (var _i = 1; _i < arguments.length; _i++) {
96 fallbacks[_i - 1] = arguments[_i];
97 }
98 var name;
99 var loaded;
100 var tries = __spreadArray([moduleName], __read(fallbacks), false);
101 while ((name = tries.shift()) !== undefined) {
102 var req = requireWrapper(name);
103 // remove exports from what we're going to log
104 // eslint-disable-next-line @typescript-eslint/no-explicit-any
105 var contextReq = __assign({}, req);
106 delete contextReq.exports;
107 if (req.exists) {
108 // module exists
109 loaded = req;
110 if (loaded.error) {
111 // require-ing it failed
112 logger.error({ requireResult: contextReq }, "failed loading module '".concat(name, "'"), loaded.error.message);
113 }
114 else {
115 // it has been loaded, let's patch it
116 logger.debug({ requireResult: contextReq }, 'loaded module', name);
117 loaded.exports = this._patch(name, loaded.exports);
118 }
119 break;
120 }
121 else {
122 // module does not exists in the path
123 logger.debug({ requireResult: contextReq }, "module '".concat(name, "' not found"));
124 }
125 }
126 // return the loaded one, could be one that has been loaded, or one which has failed during load
127 // but not one which does not exists
128 return loaded;
129 };
130 // eslint-disable-next-line no-dupe-class-members
131 Importer.prototype.tryTheseOr = function (moduleNames, missingResult, allowLoadError) {
132 if (allowLoadError === void 0) { allowLoadError = false; }
133 var args = Array.isArray(moduleNames) ? moduleNames : [moduleNames];
134 var result = this.tryThese.apply(this, __spreadArray([], __read(args), false));
135 if (!result)
136 return missingResult;
137 if (!result.error)
138 return result.exports;
139 if (allowLoadError)
140 return missingResult;
141 throw result.error;
142 };
143 Importer.prototype._patch = function (name, unpatched) {
144 if (name in this._patches) {
145 logger.debug('patching', name);
146 return this._patches[name].reduce(function (mod, patcher) { return patcher(mod); }, unpatched);
147 }
148 return unpatched;
149 };
150 Importer.prototype._import = function (why, moduleName, _a) {
151 var _b = _a === void 0 ? {} : _a, _c = _b.alternatives, alternatives = _c === void 0 ? [] : _c, _d = _b.installTip, installTip = _d === void 0 ? moduleName : _d;
152 // try to load any of the alternative after trying main one
153 var res = this.tryThese.apply(this, __spreadArray([moduleName], __read(alternatives), false));
154 // if we could load one, return it
155 if (res && res.exists) {
156 if (!res.error)
157 return res.exports;
158 // it could not load because of a failure while importing, but it exists
159 throw new Error((0, messages_1.interpolate)("Loading module {{module}} failed with error: {{error}}" /* Errors.LoadingModuleFailed */, { module: res.given, error: res.error.message }));
160 }
161 // if it couldn't load, build a nice error message so the user can fix it by himself
162 var msg = alternatives.length ? "Unable to load any of these modules: {{module}}. {{reason}}. To fix it:\n{{fix}}" /* Errors.UnableToLoadAnyModule */ : "Unable to load the module {{module}}. {{reason}} To fix it:\n{{fix}}" /* Errors.UnableToLoadOneModule */;
163 var loadModule = __spreadArray([moduleName], __read(alternatives), false).map(function (m) { return "\"".concat(m, "\""); }).join(', ');
164 if (typeof installTip === 'string') {
165 installTip = [{ module: installTip, label: "install \"".concat(installTip, "\"") }];
166 }
167 var fix = installTip
168 .map(function (tip) { return " ".concat(installTip.length === 1 ? '↳' : '•', " ").concat((0, messages_1.interpolate)("{{label}}: `npm i -D {{module}}` (or `yarn add --dev {{module}}`)" /* Helps.FixMissingModule */, tip)); })
169 .join('\n');
170 throw new Error((0, messages_1.interpolate)(msg, {
171 module: loadModule,
172 reason: why,
173 fix: fix,
174 }));
175 };
176 __decorate([
177 (0, memoize_1.Memoize)(function () {
178 var args = [];
179 for (var _i = 0; _i < arguments.length; _i++) {
180 args[_i] = arguments[_i];
181 }
182 return args.join(':');
183 })
184 ], Importer.prototype, "tryThese", null);
185 __decorate([
186 (0, memoize_1.Memoize)(function (name) { return name; })
187 ], Importer.prototype, "_patch", null);
188 __decorate([
189 (0, memoize_1.Memoize)()
190 ], Importer, "instance", null);
191 return Importer;
192}());
193exports.Importer = Importer;
194/**
195 * @internal
196 */
197exports.importer = Importer.instance;
198function requireWrapper(moduleName) {
199 var path;
200 var exists = false;
201 try {
202 path = resolveModule(moduleName);
203 exists = true;
204 }
205 catch (error) {
206 return { error: error, exists: exists, given: moduleName };
207 }
208 var result = { exists: exists, path: path, given: moduleName };
209 try {
210 result.exports = requireModule(path);
211 }
212 catch (error) {
213 try {
214 result.exports = requireModule(moduleName);
215 }
216 catch (error) {
217 result.error = error;
218 }
219 }
220 return result;
221}
222var requireModule = function (mod) { return require(mod); };
223var resolveModule = function (mod) { return require.resolve(mod, { paths: [process.cwd(), __dirname] }); };
224/**
225 * @internal
226 */
227// so that we can test easier
228function __requireModule(localRequire, localResolve) {
229 requireModule = localRequire;
230 resolveModule = localResolve;
231}