@atlaspack/transformer-js 2.12.1-canary.3354

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,870 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ function _sourceMap() {
8
+ const data = _interopRequireDefault(require("@parcel/source-map"));
9
+ _sourceMap = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ function _plugin() {
15
+ const data = require("@atlaspack/plugin");
16
+ _plugin = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _rust() {
22
+ const data = require("@atlaspack/rust");
23
+ _rust = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function _browserslist() {
29
+ const data = _interopRequireDefault(require("browserslist"));
30
+ _browserslist = function () {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
35
+ function _semver() {
36
+ const data = _interopRequireDefault(require("semver"));
37
+ _semver = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
42
+ function _nullthrows() {
43
+ const data = _interopRequireDefault(require("nullthrows"));
44
+ _nullthrows = function () {
45
+ return data;
46
+ };
47
+ return data;
48
+ }
49
+ function _diagnostic() {
50
+ const data = _interopRequireWildcard(require("@atlaspack/diagnostic"));
51
+ _diagnostic = function () {
52
+ return data;
53
+ };
54
+ return data;
55
+ }
56
+ function _utils() {
57
+ const data = require("@atlaspack/utils");
58
+ _utils = function () {
59
+ return data;
60
+ };
61
+ return data;
62
+ }
63
+ var _package = _interopRequireDefault(require("../package.json"));
64
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
65
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
66
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
67
+ const JSX_EXTENSIONS = {
68
+ jsx: true,
69
+ tsx: true
70
+ };
71
+ const JSX_PRAGMA = {
72
+ react: {
73
+ pragma: 'React.createElement',
74
+ pragmaFrag: 'React.Fragment',
75
+ automatic: '>= 17.0.0 || ^16.14.0 || >= 0.0.0-0 < 0.0.0'
76
+ },
77
+ preact: {
78
+ pragma: 'h',
79
+ pragmaFrag: 'Fragment',
80
+ automatic: '>= 10.5.0'
81
+ },
82
+ nervjs: {
83
+ pragma: 'Nerv.createElement',
84
+ pragmaFrag: undefined,
85
+ automatic: undefined
86
+ },
87
+ hyperapp: {
88
+ pragma: 'h',
89
+ pragmaFrag: undefined,
90
+ automatic: undefined
91
+ }
92
+ };
93
+ const BROWSER_MAPPING = {
94
+ and_chr: 'chrome',
95
+ and_ff: 'firefox',
96
+ ie_mob: 'ie',
97
+ ios_saf: 'ios',
98
+ op_mob: 'opera',
99
+ and_qq: null,
100
+ and_uc: null,
101
+ baidu: null,
102
+ bb: null,
103
+ kaios: null,
104
+ op_mini: null
105
+ };
106
+
107
+ // List of browsers to exclude when the esmodule target is specified.
108
+ // Based on https://caniuse.com/#feat=es6-module
109
+ const ESMODULE_BROWSERS = ['not ie <= 11', 'not edge < 16', 'not firefox < 60', 'not chrome < 61', 'not safari < 11', 'not opera < 48', 'not ios_saf < 11', 'not op_mini all', 'not android < 76', 'not blackberry > 0', 'not op_mob > 0', 'not and_chr < 76', 'not and_ff < 68', 'not ie_mob > 0', 'not and_uc > 0', 'not samsung < 8.2', 'not and_qq > 0', 'not baidu > 0', 'not kaios > 0'];
110
+ const CONFIG_SCHEMA = {
111
+ type: 'object',
112
+ properties: {
113
+ inlineFS: {
114
+ type: 'boolean'
115
+ },
116
+ inlineEnvironment: {
117
+ oneOf: [{
118
+ type: 'boolean'
119
+ }, {
120
+ type: 'array',
121
+ items: {
122
+ type: 'string'
123
+ }
124
+ }]
125
+ },
126
+ unstable_inlineConstants: {
127
+ type: 'boolean'
128
+ }
129
+ },
130
+ additionalProperties: false
131
+ };
132
+ const SCRIPT_ERRORS = {
133
+ browser: {
134
+ message: 'Browser scripts cannot have imports or exports.',
135
+ hint: 'Add the type="module" attribute to the <script> tag.'
136
+ },
137
+ 'web-worker': {
138
+ message: 'Web workers cannot have imports or exports without the `type: "module"` option.',
139
+ hint: "Add {type: 'module'} as a second argument to the Worker constructor."
140
+ },
141
+ 'service-worker': {
142
+ message: 'Service workers cannot have imports or exports without the `type: "module"` option.',
143
+ hint: "Add {type: 'module'} as a second argument to the navigator.serviceWorker.register() call."
144
+ }
145
+ };
146
+
147
+ // NOTE: Make sure this is in sync with the TypeScript definition in the @atlaspack/macros package.
148
+ var _default = exports.default = new (_plugin().Transformer)({
149
+ async loadConfig({
150
+ config,
151
+ options
152
+ }) {
153
+ let pkg = await config.getPackage();
154
+ let isJSX, pragma, pragmaFrag, jsxImportSource, automaticJSXRuntime, reactRefresh, decorators, useDefineForClassFields;
155
+ if (config.isSource) {
156
+ var _pkg$dependencies2, _pkg$devDependencies2, _pkg$peerDependencies2, _tsconfig$contents;
157
+ let reactLib;
158
+ if (pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react']) {
159
+ // e.g.: `{ alias: { "react": "preact/compat" } }`
160
+ reactLib = 'react';
161
+ } else {
162
+ // Find a dependency that we can map to a JSX pragma
163
+ reactLib = Object.keys(JSX_PRAGMA).find(libName => {
164
+ var _pkg$dependencies, _pkg$devDependencies, _pkg$peerDependencies;
165
+ return (pkg === null || pkg === void 0 || (_pkg$dependencies = pkg.dependencies) === null || _pkg$dependencies === void 0 ? void 0 : _pkg$dependencies[libName]) || (pkg === null || pkg === void 0 || (_pkg$devDependencies = pkg.devDependencies) === null || _pkg$devDependencies === void 0 ? void 0 : _pkg$devDependencies[libName]) || (pkg === null || pkg === void 0 || (_pkg$peerDependencies = pkg.peerDependencies) === null || _pkg$peerDependencies === void 0 ? void 0 : _pkg$peerDependencies[libName]);
166
+ });
167
+ }
168
+ reactRefresh = options.hmrOptions && options.mode === 'development' && Boolean((pkg === null || pkg === void 0 || (_pkg$dependencies2 = pkg.dependencies) === null || _pkg$dependencies2 === void 0 ? void 0 : _pkg$dependencies2.react) || (pkg === null || pkg === void 0 || (_pkg$devDependencies2 = pkg.devDependencies) === null || _pkg$devDependencies2 === void 0 ? void 0 : _pkg$devDependencies2.react) || (pkg === null || pkg === void 0 || (_pkg$peerDependencies2 = pkg.peerDependencies) === null || _pkg$peerDependencies2 === void 0 ? void 0 : _pkg$peerDependencies2.react));
169
+ let tsconfig = await config.getConfigFrom(options.projectRoot + '/index', ['tsconfig.json', 'jsconfig.json']);
170
+ let compilerOptions = tsconfig === null || tsconfig === void 0 || (_tsconfig$contents = tsconfig.contents) === null || _tsconfig$contents === void 0 ? void 0 : _tsconfig$contents.compilerOptions;
171
+
172
+ // Use explicitly defined JSX options in tsconfig.json over inferred values from dependencies.
173
+ pragma = (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxFactory) || (reactLib ? JSX_PRAGMA[reactLib].pragma : undefined);
174
+ pragmaFrag = (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxFragmentFactory) || (reactLib ? JSX_PRAGMA[reactLib].pragmaFrag : undefined);
175
+ if ((compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsx) === 'react-jsx' || (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsx) === 'react-jsxdev' || compilerOptions !== null && compilerOptions !== void 0 && compilerOptions.jsxImportSource) {
176
+ jsxImportSource = compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsxImportSource;
177
+ automaticJSXRuntime = true;
178
+ } else if (reactLib) {
179
+ var _JSX_PRAGMA$effective, _pkg$dependencies3, _pkg$devDependencies3, _pkg$peerDependencies3, _semver$minVersion;
180
+ let effectiveReactLib = pkg !== null && pkg !== void 0 && pkg.alias && pkg.alias['react'] === 'preact/compat' ? 'preact' : reactLib;
181
+ let automaticVersion = (_JSX_PRAGMA$effective = JSX_PRAGMA[effectiveReactLib]) === null || _JSX_PRAGMA$effective === void 0 ? void 0 : _JSX_PRAGMA$effective.automatic;
182
+ let reactLibVersion = (pkg === null || pkg === void 0 || (_pkg$dependencies3 = pkg.dependencies) === null || _pkg$dependencies3 === void 0 ? void 0 : _pkg$dependencies3[effectiveReactLib]) || (pkg === null || pkg === void 0 || (_pkg$devDependencies3 = pkg.devDependencies) === null || _pkg$devDependencies3 === void 0 ? void 0 : _pkg$devDependencies3[effectiveReactLib]) || (pkg === null || pkg === void 0 || (_pkg$peerDependencies3 = pkg.peerDependencies) === null || _pkg$peerDependencies3 === void 0 ? void 0 : _pkg$peerDependencies3[effectiveReactLib]);
183
+ reactLibVersion = reactLibVersion ? _semver().default.validRange(reactLibVersion) : null;
184
+ let minReactLibVersion = reactLibVersion !== null && reactLibVersion !== '*' ? (_semver$minVersion = _semver().default.minVersion(reactLibVersion)) === null || _semver$minVersion === void 0 ? void 0 : _semver$minVersion.toString() : null;
185
+ automaticJSXRuntime = automaticVersion && !(compilerOptions !== null && compilerOptions !== void 0 && compilerOptions.jsxFactory) && minReactLibVersion != null && _semver().default.satisfies(minReactLibVersion, automaticVersion, {
186
+ includePrerelease: true
187
+ });
188
+ if (automaticJSXRuntime) {
189
+ jsxImportSource = reactLib;
190
+ }
191
+ }
192
+ isJSX = Boolean((compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.jsx) || pragma);
193
+ decorators = compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.experimentalDecorators;
194
+ useDefineForClassFields = compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.useDefineForClassFields;
195
+ if (useDefineForClassFields === undefined && (compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.target) != null) {
196
+ // Default useDefineForClassFields to true if target is ES2022 or higher (including ESNext)
197
+ let target = compilerOptions.target.slice(2);
198
+ if (target === 'next') {
199
+ useDefineForClassFields = true;
200
+ } else {
201
+ useDefineForClassFields = Number(target) >= 2022;
202
+ }
203
+ }
204
+ }
205
+
206
+ // Check if we should ignore fs calls
207
+ // See https://github.com/defunctzombie/node-browser-resolve#skip
208
+ let ignoreFS = pkg && pkg.browser && typeof pkg.browser === 'object' && pkg.browser.fs === false;
209
+ let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
210
+ packageKey: '@atlaspack/transformer-js'
211
+ });
212
+ let inlineEnvironment = config.isSource;
213
+ let inlineFS = !ignoreFS;
214
+ let inlineConstants = false;
215
+ if (conf && conf.contents) {
216
+ var _conf$contents, _conf$contents2, _conf$contents3;
217
+ _utils().validateSchema.diagnostic(CONFIG_SCHEMA, {
218
+ data: conf.contents,
219
+ // FIXME
220
+ source: await options.inputFS.readFile(conf.filePath, 'utf8'),
221
+ filePath: conf.filePath,
222
+ prependKey: `/${(0, _diagnostic().encodeJSONKeyComponent)('@atlaspack/transformer-js')}`
223
+ },
224
+ // FIXME
225
+ '@atlaspack/transformer-js', 'Invalid config for @atlaspack/transformer-js');
226
+ inlineEnvironment = ((_conf$contents = conf.contents) === null || _conf$contents === void 0 ? void 0 : _conf$contents.inlineEnvironment) ?? inlineEnvironment;
227
+ inlineFS = ((_conf$contents2 = conf.contents) === null || _conf$contents2 === void 0 ? void 0 : _conf$contents2.inlineFS) ?? inlineFS;
228
+ inlineConstants = ((_conf$contents3 = conf.contents) === null || _conf$contents3 === void 0 ? void 0 : _conf$contents3.unstable_inlineConstants) ?? inlineConstants;
229
+ }
230
+ return {
231
+ isJSX,
232
+ automaticJSXRuntime,
233
+ jsxImportSource,
234
+ pragma,
235
+ pragmaFrag,
236
+ inlineEnvironment,
237
+ inlineFS,
238
+ inlineConstants,
239
+ reactRefresh,
240
+ decorators,
241
+ useDefineForClassFields
242
+ };
243
+ },
244
+ async transform({
245
+ asset,
246
+ config,
247
+ options,
248
+ logger
249
+ }) {
250
+ let [code, originalMap] = await Promise.all([asset.getBuffer(), asset.getMap()]);
251
+ let targets;
252
+ if (asset.env.isElectron() && asset.env.engines.electron) {
253
+ var _semver$minVersion2;
254
+ targets = {
255
+ electron: (_semver$minVersion2 = _semver().default.minVersion(asset.env.engines.electron)) === null || _semver$minVersion2 === void 0 ? void 0 : _semver$minVersion2.toString()
256
+ };
257
+ } else if (asset.env.isBrowser() && asset.env.engines.browsers) {
258
+ targets = {};
259
+ let browsers = Array.isArray(asset.env.engines.browsers) ? asset.env.engines.browsers : [asset.env.engines.browsers];
260
+
261
+ // If the output format is esmodule, exclude browsers
262
+ // that support them natively so that we transpile less.
263
+ if (asset.env.outputFormat === 'esmodule') {
264
+ browsers = [...browsers, ...ESMODULE_BROWSERS];
265
+ }
266
+ browsers = (0, _browserslist().default)(browsers);
267
+ for (let browser of browsers) {
268
+ let [name, version] = browser.split(' ');
269
+ if (BROWSER_MAPPING.hasOwnProperty(name)) {
270
+ name = BROWSER_MAPPING[name];
271
+ if (!name) {
272
+ continue;
273
+ }
274
+ }
275
+ let [major, minor = '0', patch = '0'] = version.split('-')[0].split('.');
276
+ if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
277
+ continue;
278
+ }
279
+ let semverVersion = `${major}.${minor}.${patch}`;
280
+ if (targets[name] == null || _semver().default.gt(targets[name], semverVersion)) {
281
+ targets[name] = semverVersion;
282
+ }
283
+ }
284
+ } else if (asset.env.isNode() && asset.env.engines.node) {
285
+ var _semver$minVersion3;
286
+ targets = {
287
+ node: (_semver$minVersion3 = _semver().default.minVersion(asset.env.engines.node)) === null || _semver$minVersion3 === void 0 ? void 0 : _semver$minVersion3.toString()
288
+ };
289
+ }
290
+ let env = {};
291
+ if (!(config !== null && config !== void 0 && config.inlineEnvironment)) {
292
+ if (options.env.NODE_ENV != null) {
293
+ env.NODE_ENV = options.env.NODE_ENV;
294
+ }
295
+ } else if (Array.isArray(config === null || config === void 0 ? void 0 : config.inlineEnvironment)) {
296
+ for (let match of (0, _utils().globMatch)(Object.keys(options.env), config.inlineEnvironment)) {
297
+ env[match] = String(options.env[match]);
298
+ }
299
+ } else {
300
+ for (let key in options.env) {
301
+ if (!key.startsWith('npm_')) {
302
+ env[key] = String(options.env[key]);
303
+ }
304
+ }
305
+ }
306
+ let supportsModuleWorkers = asset.env.shouldScopeHoist && asset.env.supports('worker-module', true);
307
+ let isJSX = Boolean(config === null || config === void 0 ? void 0 : config.isJSX);
308
+ if (asset.isSource) {
309
+ if (asset.type === 'ts') {
310
+ isJSX = false;
311
+ } else if (!isJSX) {
312
+ isJSX = Boolean(JSX_EXTENSIONS[asset.type]);
313
+ }
314
+ }
315
+ let macroAssets = [];
316
+ let {
317
+ dependencies,
318
+ code: compiledCode,
319
+ map,
320
+ shebang,
321
+ hoist_result,
322
+ symbol_result,
323
+ needs_esm_helpers,
324
+ diagnostics,
325
+ used_env,
326
+ has_node_replacements,
327
+ is_constant_module
328
+ } = await (_rust().transformAsync || _rust().transform)({
329
+ filename: asset.filePath,
330
+ code,
331
+ module_id: asset.id,
332
+ project_root: options.projectRoot,
333
+ replace_env: !asset.env.isNode(),
334
+ inline_fs: Boolean(config === null || config === void 0 ? void 0 : config.inlineFS) && !asset.env.isNode(),
335
+ insert_node_globals: !asset.env.isNode() && asset.env.sourceType !== 'script',
336
+ node_replacer: asset.env.isNode(),
337
+ is_browser: asset.env.isBrowser(),
338
+ is_worker: asset.env.isWorker(),
339
+ env,
340
+ is_type_script: asset.type === 'ts' || asset.type === 'tsx',
341
+ is_jsx: isJSX,
342
+ jsx_pragma: config === null || config === void 0 ? void 0 : config.pragma,
343
+ jsx_pragma_frag: config === null || config === void 0 ? void 0 : config.pragmaFrag,
344
+ automatic_jsx_runtime: Boolean(config === null || config === void 0 ? void 0 : config.automaticJSXRuntime),
345
+ jsx_import_source: config === null || config === void 0 ? void 0 : config.jsxImportSource,
346
+ is_development: options.mode === 'development',
347
+ react_refresh: asset.env.isBrowser() && !asset.env.isLibrary && !asset.env.isWorker() && !asset.env.isWorklet() && Boolean(config === null || config === void 0 ? void 0 : config.reactRefresh),
348
+ decorators: Boolean(config === null || config === void 0 ? void 0 : config.decorators),
349
+ use_define_for_class_fields: Boolean(config === null || config === void 0 ? void 0 : config.useDefineForClassFields),
350
+ targets,
351
+ source_maps: !!asset.env.sourceMap,
352
+ scope_hoist: asset.env.shouldScopeHoist && asset.env.sourceType !== 'script',
353
+ source_type: asset.env.sourceType === 'script' ? 'Script' : 'Module',
354
+ supports_module_workers: supportsModuleWorkers,
355
+ is_library: asset.env.isLibrary,
356
+ is_esm_output: asset.env.outputFormat === 'esmodule',
357
+ trace_bailouts: options.logLevel === 'verbose',
358
+ is_swc_helpers: /@swc[/\\]helpers/.test(asset.filePath),
359
+ standalone: asset.query.has('standalone'),
360
+ inline_constants: config.inlineConstants,
361
+ callMacro: asset.isSource ? async (err, src, exportName, args, loc) => {
362
+ let mod;
363
+ try {
364
+ mod = await options.packageManager.require(src, asset.filePath);
365
+
366
+ // Default interop for CommonJS modules.
367
+ if (exportName === 'default' && !mod.__esModule &&
368
+ // $FlowFixMe
369
+ Object.prototype.toString.call(config) !== '[object Module]') {
370
+ mod = {
371
+ default: mod
372
+ };
373
+ }
374
+ if (!Object.hasOwnProperty.call(mod, exportName)) {
375
+ throw new Error(`"${src}" does not export "${exportName}".`);
376
+ }
377
+ } catch (err) {
378
+ throw {
379
+ kind: 1,
380
+ message: err.message
381
+ };
382
+ }
383
+ try {
384
+ if (typeof mod[exportName] === 'function') {
385
+ return mod[exportName].apply({
386
+ // Allows macros to emit additional assets to add as dependencies (e.g. css).
387
+ addAsset(a) {
388
+ let k = String(macroAssets.length);
389
+ let map;
390
+ if (asset.env.sourceMap) {
391
+ // Generate a source map that maps each line of the asset to the original macro call.
392
+ map = new (_sourceMap().default)(options.projectRoot);
393
+ let mappings = [];
394
+ let line = 1;
395
+ for (let i = 0; i <= a.content.length; i++) {
396
+ if (i === a.content.length || a.content[i] === '\n') {
397
+ mappings.push({
398
+ generated: {
399
+ line,
400
+ column: 0
401
+ },
402
+ source: asset.filePath,
403
+ original: {
404
+ line: loc.line,
405
+ column: loc.col
406
+ }
407
+ });
408
+ line++;
409
+ }
410
+ }
411
+ map.addIndexedMappings(mappings);
412
+ if (originalMap) {
413
+ map.extends(originalMap);
414
+ } else {
415
+ map.setSourceContent(asset.filePath, code.toString());
416
+ }
417
+ }
418
+ macroAssets.push({
419
+ type: a.type,
420
+ content: a.content,
421
+ map,
422
+ uniqueKey: k
423
+ });
424
+ asset.addDependency({
425
+ specifier: k,
426
+ specifierType: 'esm'
427
+ });
428
+ },
429
+ invalidateOnFileChange(filePath) {
430
+ asset.invalidateOnFileChange(filePath);
431
+ },
432
+ invalidateOnFileCreate(invalidation) {
433
+ asset.invalidateOnFileCreate(invalidation);
434
+ },
435
+ invalidateOnEnvChange(env) {
436
+ asset.invalidateOnEnvChange(env);
437
+ },
438
+ invalidateOnStartup() {
439
+ asset.invalidateOnStartup();
440
+ },
441
+ invalidateOnBuild() {
442
+ asset.invalidateOnBuild();
443
+ }
444
+ }, args);
445
+ } else {
446
+ throw new Error(`"${exportName}" in "${src}" is not a function.`);
447
+ }
448
+ } catch (err) {
449
+ // Remove atlaspack core from stack and build string so Rust can process errors more easily.
450
+ let stack = (err.stack || '').split('\n').slice(1);
451
+ let message = err.message;
452
+ for (let line of stack) {
453
+ if (line.includes(__filename)) {
454
+ break;
455
+ }
456
+ message += '\n' + line;
457
+ }
458
+ throw {
459
+ kind: 2,
460
+ message
461
+ };
462
+ }
463
+ } : null
464
+ });
465
+ if (is_constant_module) {
466
+ asset.meta.isConstantModule = true;
467
+ }
468
+ let convertLoc = loc => {
469
+ let location = {
470
+ filePath: asset.filePath,
471
+ start: {
472
+ line: loc.start_line + Number(asset.meta.startLine ?? 1) - 1,
473
+ column: loc.start_col
474
+ },
475
+ end: {
476
+ line: loc.end_line + Number(asset.meta.startLine ?? 1) - 1,
477
+ column: loc.end_col
478
+ }
479
+ };
480
+
481
+ // If there is an original source map, use it to remap to the original source location.
482
+ if (originalMap) {
483
+ location = (0, _utils().remapSourceLocation)(location, originalMap);
484
+ }
485
+ return location;
486
+ };
487
+ if (diagnostics) {
488
+ let errors = diagnostics.filter(d => d.severity === 'Error' || d.severity === 'SourceError' && asset.isSource);
489
+ let warnings = diagnostics.filter(d => d.severity === 'Warning' || d.severity === 'SourceError' && !asset.isSource);
490
+ let convertDiagnostic = diagnostic => {
491
+ var _diagnostic$code_high;
492
+ let message = diagnostic.message;
493
+ if (message === 'SCRIPT_ERROR') {
494
+ let err = SCRIPT_ERRORS[asset.env.context];
495
+ message = (err === null || err === void 0 ? void 0 : err.message) || SCRIPT_ERRORS.browser.message;
496
+ }
497
+ let res = {
498
+ message,
499
+ codeFrames: [{
500
+ filePath: asset.filePath,
501
+ codeHighlights: (_diagnostic$code_high = diagnostic.code_highlights) === null || _diagnostic$code_high === void 0 ? void 0 : _diagnostic$code_high.map(highlight => (0, _diagnostic().convertSourceLocationToHighlight)(convertLoc(highlight.loc), highlight.message ?? undefined))
502
+ }],
503
+ hints: diagnostic.hints
504
+ };
505
+ if (diagnostic.documentation_url) {
506
+ res.documentationURL = diagnostic.documentation_url;
507
+ }
508
+ if (diagnostic.show_environment) {
509
+ if (asset.env.loc && asset.env.loc.filePath !== asset.filePath) {
510
+ var _res$codeFrames;
511
+ (_res$codeFrames = res.codeFrames) === null || _res$codeFrames === void 0 || _res$codeFrames.push({
512
+ filePath: asset.env.loc.filePath,
513
+ codeHighlights: [(0, _diagnostic().convertSourceLocationToHighlight)(asset.env.loc, 'The environment was originally created here')]
514
+ });
515
+ }
516
+ let err = SCRIPT_ERRORS[asset.env.context];
517
+ if (err) {
518
+ if (!res.hints) {
519
+ res.hints = [err.hint];
520
+ } else {
521
+ res.hints.push(err.hint);
522
+ }
523
+ }
524
+ }
525
+ return res;
526
+ };
527
+ if (errors.length > 0) {
528
+ throw new (_diagnostic().default)({
529
+ diagnostic: errors.map(convertDiagnostic)
530
+ });
531
+ }
532
+ logger.warn(warnings.map(convertDiagnostic));
533
+ }
534
+ if (shebang) {
535
+ asset.meta.interpreter = shebang;
536
+ }
537
+ if (has_node_replacements) {
538
+ asset.meta.has_node_replacements = has_node_replacements;
539
+ }
540
+ for (let env of used_env) {
541
+ asset.invalidateOnEnvChange(env);
542
+ }
543
+ for (let dep of dependencies) {
544
+ if (dep.kind === 'WebWorker') {
545
+ // Use native ES module output if the worker was created with `type: 'module'` and all targets
546
+ // support native module workers. Only do this if parent asset output format is also esmodule so that
547
+ // assets can be shared between workers and the main thread in the global output format.
548
+ let outputFormat;
549
+ if (asset.env.outputFormat === 'esmodule' && dep.source_type === 'Module' && supportsModuleWorkers) {
550
+ outputFormat = 'esmodule';
551
+ } else {
552
+ outputFormat = asset.env.outputFormat === 'commonjs' ? 'commonjs' : 'global';
553
+ }
554
+ let loc = convertLoc(dep.loc);
555
+ asset.addURLDependency(dep.specifier, {
556
+ loc,
557
+ env: {
558
+ context: 'web-worker',
559
+ sourceType: dep.source_type === 'Module' ? 'module' : 'script',
560
+ outputFormat,
561
+ loc
562
+ },
563
+ meta: {
564
+ webworker: true,
565
+ placeholder: dep.placeholder
566
+ }
567
+ });
568
+ } else if (dep.kind === 'ServiceWorker') {
569
+ let loc = convertLoc(dep.loc);
570
+ asset.addURLDependency(dep.specifier, {
571
+ loc,
572
+ needsStableName: true,
573
+ env: {
574
+ context: 'service-worker',
575
+ sourceType: dep.source_type === 'Module' ? 'module' : 'script',
576
+ outputFormat: 'global',
577
+ // TODO: module service worker support
578
+ loc
579
+ },
580
+ meta: {
581
+ placeholder: dep.placeholder
582
+ }
583
+ });
584
+ } else if (dep.kind === 'Worklet') {
585
+ let loc = convertLoc(dep.loc);
586
+ asset.addURLDependency(dep.specifier, {
587
+ loc,
588
+ env: {
589
+ context: 'worklet',
590
+ sourceType: 'module',
591
+ outputFormat: 'esmodule',
592
+ // Worklets require ESM
593
+ loc
594
+ },
595
+ meta: {
596
+ placeholder: dep.placeholder
597
+ }
598
+ });
599
+ } else if (dep.kind === 'Url') {
600
+ asset.addURLDependency(dep.specifier, {
601
+ bundleBehavior: 'isolated',
602
+ loc: convertLoc(dep.loc),
603
+ meta: {
604
+ placeholder: dep.placeholder
605
+ }
606
+ });
607
+ } else if (dep.kind === 'File') {
608
+ asset.invalidateOnFileChange(dep.specifier);
609
+ } else {
610
+ let meta = {
611
+ kind: dep.kind
612
+ };
613
+ if (dep.attributes) {
614
+ meta.importAttributes = dep.attributes;
615
+ }
616
+ if (dep.placeholder) {
617
+ meta.placeholder = dep.placeholder;
618
+ }
619
+ let env;
620
+ if (dep.kind === 'DynamicImport') {
621
+ // https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-modulerequest,-promisecapability)
622
+ if (asset.env.isWorklet() || asset.env.context === 'service-worker') {
623
+ let loc = convertLoc(dep.loc);
624
+ let diagnostic = {
625
+ message: `import() is not allowed in ${asset.env.isWorklet() ? 'worklets' : 'service workers'}.`,
626
+ codeFrames: [{
627
+ filePath: asset.filePath,
628
+ codeHighlights: [(0, _diagnostic().convertSourceLocationToHighlight)(loc)]
629
+ }],
630
+ hints: ['Try using a static `import`.']
631
+ };
632
+ if (asset.env.loc) {
633
+ diagnostic.codeFrames.push({
634
+ filePath: asset.env.loc.filePath,
635
+ codeHighlights: [(0, _diagnostic().convertSourceLocationToHighlight)(asset.env.loc, 'The environment was originally created here')]
636
+ });
637
+ }
638
+ throw new (_diagnostic().default)({
639
+ diagnostic
640
+ });
641
+ }
642
+
643
+ // If all of the target engines support dynamic import natively,
644
+ // we can output native ESM if scope hoisting is enabled.
645
+ // Only do this for scripts, rather than modules in the global
646
+ // output format so that assets can be shared between the bundles.
647
+ let outputFormat = asset.env.outputFormat;
648
+ if (asset.env.sourceType === 'script' && asset.env.shouldScopeHoist && asset.env.supports('dynamic-import', true)) {
649
+ outputFormat = 'esmodule';
650
+ }
651
+ env = {
652
+ sourceType: 'module',
653
+ outputFormat,
654
+ loc: convertLoc(dep.loc)
655
+ };
656
+ }
657
+
658
+ // Always bundle helpers, even with includeNodeModules: false, except if this is a library.
659
+ let isHelper = dep.is_helper && !(dep.specifier.endsWith('/jsx-runtime') || dep.specifier.endsWith('/jsx-dev-runtime'));
660
+ if (isHelper && !asset.env.isLibrary) {
661
+ env = {
662
+ ...env,
663
+ includeNodeModules: true
664
+ };
665
+ }
666
+
667
+ // Add required version range for helpers.
668
+ let range;
669
+ if (isHelper) {
670
+ let idx = dep.specifier.indexOf('/');
671
+ if (dep.specifier[0] === '@') {
672
+ idx = dep.specifier.indexOf('/', idx + 1);
673
+ }
674
+ let module = idx >= 0 ? dep.specifier.slice(0, idx) : dep.specifier;
675
+ range = _package.default.dependencies[module];
676
+ }
677
+ asset.addDependency({
678
+ specifier: dep.specifier,
679
+ specifierType: dep.kind === 'Require' ? 'commonjs' : 'esm',
680
+ loc: convertLoc(dep.loc),
681
+ priority: dep.kind === 'DynamicImport' ? 'lazy' : 'sync',
682
+ isOptional: dep.is_optional,
683
+ meta,
684
+ resolveFrom: isHelper ? __filename : undefined,
685
+ range,
686
+ env
687
+ });
688
+ }
689
+ }
690
+ asset.meta.id = asset.id;
691
+ if (hoist_result) {
692
+ asset.symbols.ensure();
693
+ for (let {
694
+ exported,
695
+ local,
696
+ loc,
697
+ is_esm
698
+ } of hoist_result.exported_symbols) {
699
+ asset.symbols.set(exported, local, convertLoc(loc), {
700
+ isEsm: is_esm
701
+ });
702
+ }
703
+
704
+ // deps is a map of dependencies that are keyed by placeholder or specifier
705
+ // If a placeholder is present, that is used first since placeholders are
706
+ // hashed with DependencyKind's.
707
+ // If not, the specifier is used along with its specifierType appended to
708
+ // it to separate dependencies with the same specifier.
709
+ let deps = new Map(asset.getDependencies().map(dep => [dep.meta.placeholder ?? dep.specifier, dep]));
710
+ for (let dep of deps.values()) {
711
+ dep.symbols.ensure();
712
+ }
713
+ for (let {
714
+ source,
715
+ local,
716
+ imported,
717
+ loc
718
+ } of hoist_result.imported_symbols) {
719
+ let dep = deps.get(source);
720
+ if (!dep) continue;
721
+ dep.symbols.set(imported, local, convertLoc(loc));
722
+ }
723
+ for (let {
724
+ source,
725
+ local,
726
+ imported,
727
+ loc
728
+ } of hoist_result.re_exports) {
729
+ let dep = deps.get(source);
730
+ if (!dep) continue;
731
+ if (local === '*' && imported === '*') {
732
+ dep.symbols.set('*', '*', convertLoc(loc), true);
733
+ } else {
734
+ var _dep$symbols$get;
735
+ let reExportName = ((_dep$symbols$get = dep.symbols.get(imported)) === null || _dep$symbols$get === void 0 ? void 0 : _dep$symbols$get.local) ?? `$${asset.id}$re_export$${local}`;
736
+ asset.symbols.set(local, reExportName);
737
+ dep.symbols.set(imported, reExportName, convertLoc(loc), true);
738
+ }
739
+ }
740
+ for (let specifier of hoist_result.wrapped_requires) {
741
+ let dep = deps.get(specifier);
742
+ if (!dep) continue;
743
+ dep.meta.shouldWrap = true;
744
+ }
745
+ for (let name in hoist_result.dynamic_imports) {
746
+ let dep = deps.get(hoist_result.dynamic_imports[name]);
747
+ if (!dep) continue;
748
+ dep.meta.promiseSymbol = name;
749
+ }
750
+ if (hoist_result.self_references.length > 0) {
751
+ let symbols = new Map();
752
+ for (let name of hoist_result.self_references) {
753
+ // Do not create a self-reference for the `default` symbol unless we have seen an __esModule flag.
754
+ if (name === 'default' && !asset.symbols.hasExportSymbol('__esModule')) {
755
+ continue;
756
+ }
757
+ let local = (0, _nullthrows().default)(asset.symbols.get(name)).local;
758
+ symbols.set(name, {
759
+ local,
760
+ isWeak: false,
761
+ loc: null
762
+ });
763
+ }
764
+
765
+ // Use the asset id as a unique key if one has not already been set.
766
+ // This lets us create a dependency on the asset itself by using it as a specifier.
767
+ // Using the unique key ensures that the dependency always resolves to the correct asset,
768
+ // even if it came from a transformer that produced multiple assets (e.g. css modules).
769
+ // Also avoids needing a resolution request.
770
+ asset.uniqueKey ||= asset.id;
771
+ asset.addDependency({
772
+ specifier: asset.uniqueKey,
773
+ specifierType: 'esm',
774
+ symbols
775
+ });
776
+ }
777
+
778
+ // Add * symbol if there are CJS exports, no imports/exports at all
779
+ // (and the asset has side effects), or the asset is wrapped.
780
+ // This allows accessing symbols that don't exist without errors in symbol propagation.
781
+ if (hoist_result.has_cjs_exports || !hoist_result.is_esm && asset.sideEffects && deps.size === 0 && Object.keys(hoist_result.exported_symbols).length === 0 || hoist_result.should_wrap && !asset.symbols.hasExportSymbol('*')) {
782
+ asset.symbols.set('*', `$${asset.id}$exports`);
783
+ }
784
+ asset.meta.hasCJSExports = hoist_result.has_cjs_exports;
785
+ asset.meta.staticExports = hoist_result.static_cjs_exports;
786
+ asset.meta.shouldWrap = hoist_result.should_wrap;
787
+ } else {
788
+ if (symbol_result) {
789
+ let deps = new Map(asset.getDependencies().map(dep => [dep.meta.placeholder ?? dep.specifier, dep]));
790
+ asset.symbols.ensure();
791
+ for (let {
792
+ exported,
793
+ local,
794
+ loc,
795
+ source
796
+ } of symbol_result.exports) {
797
+ let dep = source ? deps.get(source) : undefined;
798
+ asset.symbols.set(exported, `${(dep === null || dep === void 0 ? void 0 : dep.id) ?? ''}$${local}`, convertLoc(loc));
799
+ if (dep != null) {
800
+ dep.symbols.ensure();
801
+ dep.symbols.set(local, `${(dep === null || dep === void 0 ? void 0 : dep.id) ?? ''}$${local}`, convertLoc(loc), true);
802
+ }
803
+ }
804
+ for (let {
805
+ source,
806
+ local,
807
+ imported,
808
+ loc
809
+ } of symbol_result.imports) {
810
+ let dep = deps.get(source);
811
+ if (!dep) continue;
812
+ dep.symbols.ensure();
813
+ dep.symbols.set(imported, local, convertLoc(loc));
814
+ }
815
+ for (let {
816
+ source,
817
+ loc
818
+ } of symbol_result.exports_all) {
819
+ let dep = deps.get(source);
820
+ if (!dep) continue;
821
+ dep.symbols.ensure();
822
+ dep.symbols.set('*', '*', convertLoc(loc), true);
823
+ }
824
+
825
+ // Add * symbol if there are CJS exports, no imports/exports at all, or the asset is wrapped.
826
+ // This allows accessing symbols that don't exist without errors in symbol propagation.
827
+ if (symbol_result.has_cjs_exports || !symbol_result.is_esm && deps.size === 0 && symbol_result.exports.length === 0 || symbol_result.should_wrap && !asset.symbols.hasExportSymbol('*')) {
828
+ asset.symbols.ensure();
829
+ asset.symbols.set('*', `$${asset.id}$exports`);
830
+ }
831
+ } else {
832
+ // If the asset is wrapped, add * as a fallback
833
+ asset.symbols.ensure();
834
+ asset.symbols.set('*', `$${asset.id}$exports`);
835
+ }
836
+
837
+ // For all other imports and requires, mark everything as imported (this covers both dynamic
838
+ // imports and non-top-level requires.)
839
+ for (let dep of asset.getDependencies()) {
840
+ if (dep.symbols.isCleared) {
841
+ dep.symbols.ensure();
842
+ dep.symbols.set('*', `${dep.id}$`);
843
+ }
844
+ }
845
+ if (needs_esm_helpers) {
846
+ asset.addDependency({
847
+ specifier: '@atlaspack/transformer-js/src/esmodule-helpers.js',
848
+ specifierType: 'esm',
849
+ resolveFrom: __filename,
850
+ env: {
851
+ includeNodeModules: {
852
+ '@atlaspack/transformer-js': true
853
+ }
854
+ }
855
+ });
856
+ }
857
+ }
858
+ asset.type = 'js';
859
+ asset.setBuffer(compiledCode);
860
+ if (map) {
861
+ let sourceMap = new (_sourceMap().default)(options.projectRoot);
862
+ sourceMap.addVLQMap(JSON.parse(map));
863
+ if (originalMap) {
864
+ sourceMap.extends(originalMap);
865
+ }
866
+ asset.setMap(sourceMap);
867
+ }
868
+ return [asset, ...macroAssets];
869
+ }
870
+ });