UNPKG

17.9 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8function _sourceMap() {
9 const data = _interopRequireDefault(require("@parcel/source-map"));
10
11 _sourceMap = function () {
12 return data;
13 };
14
15 return data;
16}
17
18function _plugin() {
19 const data = require("@parcel/plugin");
20
21 _plugin = function () {
22 return data;
23 };
24
25 return data;
26}
27
28function _native() {
29 const data = require("./native");
30
31 _native = function () {
32 return data;
33 };
34
35 return data;
36}
37
38function _utils() {
39 const data = require("@parcel/utils");
40
41 _utils = function () {
42 return data;
43 };
44
45 return data;
46}
47
48function _path() {
49 const data = _interopRequireDefault(require("path"));
50
51 _path = function () {
52 return data;
53 };
54
55 return data;
56}
57
58function _browserslist() {
59 const data = _interopRequireDefault(require("browserslist"));
60
61 _browserslist = function () {
62 return data;
63 };
64
65 return data;
66}
67
68function _semver() {
69 const data = _interopRequireDefault(require("semver"));
70
71 _semver = function () {
72 return data;
73 };
74
75 return data;
76}
77
78function _nullthrows() {
79 const data = _interopRequireDefault(require("nullthrows"));
80
81 _nullthrows = function () {
82 return data;
83 };
84
85 return data;
86}
87
88function _diagnostic() {
89 const data = _interopRequireWildcard(require("@parcel/diagnostic"));
90
91 _diagnostic = function () {
92 return data;
93 };
94
95 return data;
96}
97
98function _micromatch() {
99 const data = require("micromatch");
100
101 _micromatch = function () {
102 return data;
103 };
104
105 return data;
106}
107
108function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
109
110function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
111
112function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
113
114const JSX_EXTENSIONS = {
115 '.jsx': true,
116 '.tsx': true
117};
118const JSX_PRAGMA = {
119 react: {
120 pragma: 'React.createElement',
121 pragmaFrag: 'React.Fragment'
122 },
123 preact: {
124 pragma: 'h',
125 pragmaFrag: 'Fragment'
126 },
127 nervjs: {
128 pragma: 'Nerv.createElement',
129 pragmaFrag: undefined
130 },
131 hyperapp: {
132 pragma: 'h',
133 pragmaFrag: undefined
134 }
135};
136const BROWSER_MAPPING = {
137 and_chr: 'chrome',
138 and_ff: 'firefox',
139 ie_mob: 'ie',
140 ios_saf: 'ios',
141 op_mob: 'opera',
142 and_qq: null,
143 and_uc: null,
144 baidu: null,
145 bb: null,
146 kaios: null,
147 op_mini: null
148};
149const CONFIG_SCHEMA = {
150 type: 'object',
151 properties: {
152 inlineFS: {
153 type: 'boolean'
154 },
155 inlineEnvironment: {
156 oneOf: [{
157 type: 'boolean'
158 }, {
159 type: 'array',
160 items: {
161 type: 'string'
162 }
163 }]
164 }
165 },
166 additionalProperties: false
167};
168
169var _default = new (_plugin().Transformer)({
170 async loadConfig({
171 config,
172 options
173 }) {
174 var _pkg$dependencies2, _pkg$devDependencies2, _pkg$peerDependencies2;
175
176 let pkg = await config.getPackage();
177 let reactLib;
178
179 if (config.isSource) {
180 if (pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react']) {
181 // e.g.: `{ alias: { "react": "preact/compat" } }`
182 reactLib = 'react';
183 } else {
184 // Find a dependency that we can map to a JSX pragma
185 reactLib = Object.keys(JSX_PRAGMA).find(libName => {
186 var _pkg$dependencies, _pkg$devDependencies, _pkg$peerDependencies;
187
188 return (pkg === null || pkg === void 0 ? void 0 : (_pkg$dependencies = pkg.dependencies) === null || _pkg$dependencies === void 0 ? void 0 : _pkg$dependencies[libName]) || (pkg === null || pkg === void 0 ? void 0 : (_pkg$devDependencies = pkg.devDependencies) === null || _pkg$devDependencies === void 0 ? void 0 : _pkg$devDependencies[libName]) || (pkg === null || pkg === void 0 ? void 0 : (_pkg$peerDependencies = pkg.peerDependencies) === null || _pkg$peerDependencies === void 0 ? void 0 : _pkg$peerDependencies[libName]);
189 });
190 }
191 }
192
193 let reactRefresh = config.isSource && options.hmrOptions && config.env.isBrowser() && !config.env.isWorker() && options.mode === 'development' && ((pkg === null || pkg === void 0 ? void 0 : (_pkg$dependencies2 = pkg.dependencies) === null || _pkg$dependencies2 === void 0 ? void 0 : _pkg$dependencies2.react) || (pkg === null || pkg === void 0 ? void 0 : (_pkg$devDependencies2 = pkg.devDependencies) === null || _pkg$devDependencies2 === void 0 ? void 0 : _pkg$devDependencies2.react) || (pkg === null || pkg === void 0 ? void 0 : (_pkg$peerDependencies2 = pkg.peerDependencies) === null || _pkg$peerDependencies2 === void 0 ? void 0 : _pkg$peerDependencies2.react)); // Check if we should ignore fs calls
194 // See https://github.com/defunctzombie/node-browser-resolve#skip
195
196 let ignoreFS = pkg && pkg.browser && typeof pkg.browser === 'object' && pkg.browser.fs === false;
197 let result = await config.getConfigFrom(_path().default.join(options.projectRoot, 'index'), ['package.json']);
198 let rootPkg = result === null || result === void 0 ? void 0 : result.contents;
199 let inlineEnvironment = config.isSource;
200 let inlineFS = !ignoreFS;
201
202 if (result && rootPkg !== null && rootPkg !== void 0 && rootPkg['@parcel/transformer-js']) {
203 var _rootPkg$ParcelTran, _rootPkg$ParcelTran2;
204
205 _utils().validateSchema.diagnostic(CONFIG_SCHEMA, {
206 data: rootPkg['@parcel/transformer-js'],
207 // FIXME
208 source: await options.inputFS.readFile(result.filePath, 'utf8'),
209 filePath: result.filePath,
210 prependKey: `/${(0, _diagnostic().encodeJSONKeyComponent)('@parcel/transformer-js')}`
211 }, // FIXME
212 '@parcel/transformer-js', 'Invalid config for @parcel/transformer-js');
213
214 inlineEnvironment = (_rootPkg$ParcelTran = rootPkg['@parcel/transformer-js'].inlineEnvironment) !== null && _rootPkg$ParcelTran !== void 0 ? _rootPkg$ParcelTran : inlineEnvironment;
215 inlineFS = (_rootPkg$ParcelTran2 = rootPkg['@parcel/transformer-js'].inlineFS) !== null && _rootPkg$ParcelTran2 !== void 0 ? _rootPkg$ParcelTran2 : inlineFS;
216 }
217
218 let pragma = reactLib ? JSX_PRAGMA[reactLib].pragma : undefined;
219 let pragmaFrag = reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined;
220
221 let isJSX = pragma || JSX_EXTENSIONS[_path().default.extname(config.searchPath)];
222
223 config.setResult({
224 isJSX,
225 pragma,
226 pragmaFrag,
227 inlineEnvironment,
228 inlineFS,
229 reactRefresh
230 });
231 },
232
233 async transform({
234 asset,
235 config,
236 options
237 }) {
238 // When this asset is an bundle entry, allow that bundle to be split to load shared assets separately.
239 // Only set here if it is null to allow previous transformers to override this behavior.
240 if (asset.isSplittable == null) {
241 asset.isSplittable = true;
242 }
243
244 let code = await asset.getBuffer();
245 let originalMap = await asset.getMap();
246 let targets;
247
248 if (asset.isSource) {
249 if (asset.env.isElectron() && asset.env.engines.electron) {
250 var _semver$minVersion;
251
252 targets = {
253 electron: (_semver$minVersion = _semver().default.minVersion(asset.env.engines.electron)) === null || _semver$minVersion === void 0 ? void 0 : _semver$minVersion.toString()
254 };
255 } else if (asset.env.isBrowser() && asset.env.engines.browsers) {
256 targets = {};
257 let browsers = (0, _browserslist().default)(asset.env.engines.browsers);
258
259 for (let browser of browsers) {
260 let [name, version] = browser.split(' ');
261
262 if (BROWSER_MAPPING.hasOwnProperty(name)) {
263 name = BROWSER_MAPPING[name];
264
265 if (!name) {
266 continue;
267 }
268 }
269
270 let [major, minor = '0', patch = '0'] = version.split('-')[0].split('.');
271 let semverVersion = `${major}.${minor}.${patch}`;
272
273 if (targets[name] == null || _semver().default.gt(targets[name], semverVersion)) {
274 targets[name] = semverVersion;
275 }
276 }
277 } else if (asset.env.isNode() && asset.env.engines.node) {
278 var _semver$minVersion2;
279
280 targets = {
281 node: (_semver$minVersion2 = _semver().default.minVersion(asset.env.engines.node)) === null || _semver$minVersion2 === void 0 ? void 0 : _semver$minVersion2.toString()
282 };
283 }
284 }
285
286 let relativePath = _path().default.relative(options.projectRoot, asset.filePath);
287
288 let env = {};
289
290 if (!(config !== null && config !== void 0 && config.inlineEnvironment)) {
291 if (options.env.NODE_ENV != null) {
292 env.NODE_ENV = options.env.NODE_ENV;
293 }
294 } else if (Array.isArray(config === null || config === void 0 ? void 0 : config.inlineEnvironment)) {
295 for (let key in options.env) {
296 if ((0, _micromatch().isMatch)(key, config.inlineEnvironment)) {
297 env[key] = String(options.env[key]);
298 }
299 }
300 } else {
301 for (let key in options.env) {
302 if (!key.startsWith('npm_')) {
303 env[key] = String(options.env[key]);
304 }
305 }
306 }
307
308 let {
309 dependencies,
310 code: compiledCode,
311 map,
312 shebang,
313 hoist_result,
314 needs_esm_helpers,
315 diagnostics,
316 used_env
317 } = (0, _native().transform)({
318 filename: asset.filePath,
319 code,
320 module_id: asset.id,
321 project_root: options.projectRoot,
322 replace_env: !asset.env.isNode(),
323 inline_fs: Boolean(config === null || config === void 0 ? void 0 : config.inlineFS) && !asset.env.isNode(),
324 insert_node_globals: !asset.env.isNode(),
325 is_browser: asset.env.isBrowser(),
326 env,
327 is_type_script: asset.type === 'ts' || asset.type === 'tsx',
328 is_jsx: Boolean(config === null || config === void 0 ? void 0 : config.isJSX),
329 jsx_pragma: config === null || config === void 0 ? void 0 : config.pragma,
330 jsx_pragma_frag: config === null || config === void 0 ? void 0 : config.pragmaFrag,
331 is_development: options.mode === 'development',
332 react_refresh: Boolean(config === null || config === void 0 ? void 0 : config.reactRefresh),
333 targets,
334 source_maps: !!asset.env.sourceMap,
335 scope_hoist: asset.env.shouldScopeHoist
336 });
337
338 let convertLoc = loc => {
339 let location = {
340 filePath: relativePath,
341 start: {
342 line: loc.start_line,
343 column: loc.start_col
344 },
345 end: {
346 line: loc.end_line,
347 column: loc.end_col
348 }
349 }; // If there is an original source map, use it to remap to the original source location.
350
351 if (originalMap) {
352 location = (0, _utils().remapSourceLocation)(location, originalMap);
353 }
354
355 return location;
356 };
357
358 if (diagnostics) {
359 throw new (_diagnostic().default)({
360 diagnostic: diagnostics.map(diagnostic => {
361 var _diagnostic$code_high;
362
363 return {
364 filePath: asset.filePath,
365 message: diagnostic.message,
366 codeFrame: {
367 code: code.toString(),
368 codeHighlights: (_diagnostic$code_high = diagnostic.code_highlights) === null || _diagnostic$code_high === void 0 ? void 0 : _diagnostic$code_high.map(highlight => {
369 let {
370 start,
371 end
372 } = convertLoc(highlight.loc);
373 return {
374 message: highlight.message,
375 start,
376 end
377 };
378 })
379 },
380 hints: diagnostic.hints
381 };
382 })
383 });
384 }
385
386 if (shebang) {
387 asset.meta.interpreter = shebang;
388 }
389
390 for (let env of used_env) {
391 asset.invalidateOnEnvChange(env);
392 }
393
394 for (let dep of dependencies) {
395 if (dep.kind === 'WebWorker') {
396 asset.addURLDependency(dep.specifier, {
397 loc: convertLoc(dep.loc),
398 env: {
399 context: 'web-worker' // outputFormat:
400 // isModule && asset.env.scopeHoist ? 'esmodule' : undefined,
401
402 },
403 meta: {
404 webworker: true
405 }
406 });
407 } else if (dep.kind === 'ServiceWorker') {
408 asset.addURLDependency(dep.specifier, {
409 loc: convertLoc(dep.loc),
410 isEntry: true,
411 env: {
412 context: 'service-worker'
413 }
414 });
415 } else if (dep.kind === 'ImportScripts') {
416 if (asset.env.isWorker()) {
417 asset.addURLDependency(dep.specifier, {
418 loc: convertLoc(dep.loc)
419 });
420 }
421 } else if (dep.kind === 'URL') {
422 asset.addURLDependency(dep.specifier, {
423 loc: convertLoc(dep.loc)
424 });
425 } else if (dep.kind === 'File') {
426 asset.addIncludedFile(dep.specifier);
427 } else {
428 if (dep.kind === 'DynamicImport' && (0, _utils().isURL)(dep.specifier)) {
429 continue;
430 }
431
432 let meta = {
433 kind: dep.kind
434 };
435
436 if (dep.attributes) {
437 meta.importAttributes = dep.attributes;
438 }
439
440 asset.addDependency({
441 moduleSpecifier: dep.specifier,
442 loc: convertLoc(dep.loc),
443 isAsync: dep.kind === 'DynamicImport',
444 isOptional: dep.is_optional,
445 meta,
446 resolveFrom: dep.is_helper ? __filename : undefined
447 });
448 }
449 }
450
451 if (hoist_result) {
452 asset.symbols.ensure();
453
454 for (let symbol in hoist_result.exported_symbols) {
455 let [local, loc] = hoist_result.exported_symbols[symbol];
456 asset.symbols.set(symbol, local, convertLoc(loc));
457 }
458
459 let deps = new Map(asset.getDependencies().map(dep => [dep.moduleSpecifier, dep]));
460
461 for (let dep of deps.values()) {
462 dep.symbols.ensure();
463 }
464
465 for (let name in hoist_result.imported_symbols) {
466 let [moduleSpecifier, exported, loc] = hoist_result.imported_symbols[name];
467 let dep = deps.get(moduleSpecifier);
468 if (!dep) continue;
469 dep.symbols.set(exported, name, convertLoc(loc));
470 }
471
472 for (let [name, moduleSpecifier, exported, loc] of hoist_result.re_exports) {
473 let dep = deps.get(moduleSpecifier);
474 if (!dep) continue;
475
476 if (name === '*' && exported === '*') {
477 dep.symbols.set('*', '*', convertLoc(loc), true);
478 } else {
479 var _dep$symbols$get$loca, _dep$symbols$get;
480
481 let reExportName = (_dep$symbols$get$loca = (_dep$symbols$get = dep.symbols.get(exported)) === null || _dep$symbols$get === void 0 ? void 0 : _dep$symbols$get.local) !== null && _dep$symbols$get$loca !== void 0 ? _dep$symbols$get$loca : `$${asset.id}$re_export$${name}`;
482 asset.symbols.set(name, reExportName);
483 dep.symbols.set(exported, reExportName, convertLoc(loc), true);
484 }
485 }
486
487 for (let moduleSpecifier of hoist_result.wrapped_requires) {
488 let dep = deps.get(moduleSpecifier);
489 if (!dep) continue;
490 dep.meta.shouldWrap = true;
491 }
492
493 for (let name in hoist_result.dynamic_imports) {
494 let dep = deps.get(hoist_result.dynamic_imports[name]);
495 if (!dep) continue;
496 dep.meta.promiseSymbol = name;
497 }
498
499 if (hoist_result.self_references.length > 0) {
500 let symbols = new Map();
501
502 for (let name of hoist_result.self_references) {
503 // Do not create a self-reference for the `default` symbol unless we have seen an __esModule flag.
504 if (name === 'default' && !asset.symbols.hasExportSymbol('__esModule')) {
505 continue;
506 }
507
508 let local = (0, _nullthrows().default)(asset.symbols.get(name)).local;
509 symbols.set(name, {
510 local,
511 isWeak: false,
512 loc: null
513 });
514 }
515
516 asset.addDependency({
517 moduleSpecifier: `./${_path().default.basename(asset.filePath)}`,
518 symbols
519 });
520 } // Add * symbol if there are CJS exports, no imports/exports at all, or the asset is wrapped.
521 // This allows accessing symbols that don't exist without errors in symbol propagation.
522
523
524 if (hoist_result.has_cjs_exports || deps.size === 0 && Object.keys(hoist_result.exported_symbols).length === 0 || hoist_result.should_wrap && !asset.symbols.hasExportSymbol('*')) {
525 asset.symbols.set('*', `$${asset.id}$exports`);
526 }
527
528 asset.meta.hasCJSExports = hoist_result.has_cjs_exports;
529 asset.meta.staticExports = hoist_result.static_cjs_exports;
530 asset.meta.shouldWrap = hoist_result.should_wrap;
531 asset.meta.id = asset.id;
532 } else if (needs_esm_helpers) {
533 asset.addDependency({
534 moduleSpecifier: '@parcel/transformer-js/src/esmodule-helpers.js',
535 resolveFrom: __filename,
536 env: {
537 includeNodeModules: {
538 '@parcel/transformer-js': true
539 }
540 }
541 });
542 }
543
544 asset.type = 'js';
545 asset.setBuffer(compiledCode);
546
547 if (map) {
548 let sourceMap = new (_sourceMap().default)(options.projectRoot);
549 sourceMap.addVLQMap(JSON.parse(map));
550
551 if (originalMap) {
552 sourceMap.extends(originalMap);
553 }
554
555 asset.setMap(sourceMap);
556 }
557
558 return [asset];
559 }
560
561});
562
563exports.default = _default;
\No newline at end of file