@parcel/transformer-css 2.0.0-nightly.140 → 2.0.0-nightly.1400

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.
@@ -4,174 +4,342 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
- var _plugin = require("@parcel/plugin");
9
-
10
- var _utils = require("@parcel/utils");
11
-
12
- var _postcss = _interopRequireDefault(require("postcss"));
13
-
14
- var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
15
-
16
- var _semver = _interopRequireDefault(require("semver"));
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
-
20
- const URL_RE = /url\s*\("?(?![a-z]+:)/;
21
- const IMPORT_RE = /@import/;
22
-
23
- function canHaveDependencies(filePath, code) {
24
- return !/\.css$/.test(filePath) || IMPORT_RE.test(code) || URL_RE.test(code);
7
+ function _path() {
8
+ const data = _interopRequireDefault(require("path"));
9
+ _path = function () {
10
+ return data;
11
+ };
12
+ return data;
25
13
  }
26
-
27
- var _default = new _plugin.Transformer({
28
- canReuseAST({
29
- ast
30
- }) {
31
- return ast.type === 'postcss' && _semver.default.satisfies(ast.version, '^7.0.0');
32
- },
33
-
34
- async parse({
35
- asset
14
+ function _sourceMap() {
15
+ const data = _interopRequireDefault(require("@parcel/source-map"));
16
+ _sourceMap = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _plugin() {
22
+ const data = require("@parcel/plugin");
23
+ _plugin = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function _lightningcss() {
29
+ const data = require("lightningcss");
30
+ _lightningcss = function () {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
35
+ function _utils() {
36
+ const data = require("@parcel/utils");
37
+ _utils = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
42
+ function _browserslist() {
43
+ const data = _interopRequireDefault(require("browserslist"));
44
+ _browserslist = function () {
45
+ return data;
46
+ };
47
+ return data;
48
+ }
49
+ function _nullthrows() {
50
+ const data = _interopRequireDefault(require("nullthrows"));
51
+ _nullthrows = function () {
52
+ return data;
53
+ };
54
+ return data;
55
+ }
56
+ function _diagnostic() {
57
+ const data = _interopRequireWildcard(require("@parcel/diagnostic"));
58
+ _diagnostic = function () {
59
+ return data;
60
+ };
61
+ return data;
62
+ }
63
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
64
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }
65
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
66
+ var _default = new (_plugin().Transformer)({
67
+ async loadConfig({
68
+ config,
69
+ options
36
70
  }) {
37
- // This is set by other transformers (e.g. Stylus) to indicate that it has already processed
38
- // all dependencies, and that the CSS transformer can skip this asset completely. This is
39
- // required because when stylus processes e.g. url() it replaces them with a dependency id
40
- // to be filled in later. When the CSS transformer runs, it would pick that up and try to
41
- // resolve a dependency for the id which obviously doesn't exist. Also, it's faster to do
42
- // it this way since the resulting CSS doesn't need to be re-parsed.
43
- if (asset.meta.hasDependencies === false) {
44
- return null;
45
- }
46
-
47
- let code = await asset.getCode();
48
-
49
- if (!canHaveDependencies(asset.filePath, code)) {
50
- return null;
51
- }
52
-
53
- return {
54
- type: 'postcss',
55
- version: '7.0.0',
56
- isDirty: false,
57
- program: _postcss.default.parse(code, {
58
- from: asset.filePath
59
- })
60
- };
71
+ let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
72
+ packageKey: '@parcel/transformer-css'
73
+ });
74
+ return conf === null || conf === void 0 ? void 0 : conf.contents;
61
75
  },
62
-
63
- transform({
64
- asset
76
+ async transform({
77
+ asset,
78
+ config,
79
+ options,
80
+ logger
65
81
  }) {
66
82
  // Normalize the asset's environment so that properties that only affect JS don't cause CSS to be duplicated.
67
83
  // For example, with ESModule and CommonJS targets, only a single shared CSS bundle should be produced.
84
+ let env = asset.env;
68
85
  asset.setEnvironment({
69
86
  context: 'browser',
70
87
  engines: {
71
88
  browsers: asset.env.engines.browsers
72
89
  },
73
- minify: asset.env.minify
74
- }); // When this asset is an bundle entry, allow that bundle to be split to load shared assets separately.
75
- // Only set here if it is null to allow previous transformers to override this behavior.
76
-
77
- if (asset.isSplittable == null) {
78
- asset.isSplittable = true;
90
+ shouldOptimize: asset.env.shouldOptimize,
91
+ shouldScopeHoist: asset.env.shouldScopeHoist,
92
+ sourceMap: asset.env.sourceMap
93
+ });
94
+ let [code, originalMap] = await Promise.all([asset.getBuffer(), asset.getMap()]);
95
+ let targets = getTargets(asset.env.engines.browsers);
96
+ let res;
97
+ try {
98
+ if (asset.meta.type === 'attr') {
99
+ res = (0, _lightningcss().transformStyleAttribute)({
100
+ code,
101
+ analyzeDependencies: true,
102
+ errorRecovery: (config === null || config === void 0 ? void 0 : config.errorRecovery) || false,
103
+ targets
104
+ });
105
+ } else {
106
+ let cssModules = false;
107
+ if (asset.meta.type !== 'tag' && asset.meta.cssModulesCompiled == null) {
108
+ let cssModulesConfig = config === null || config === void 0 ? void 0 : config.cssModules;
109
+ if (asset.isSource && (typeof cssModulesConfig === 'boolean' || cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.global) || /\.module\./.test(asset.filePath)) {
110
+ if (cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.dashedIdents && !asset.isSource) {
111
+ cssModulesConfig.dashedIdents = false;
112
+ }
113
+ cssModules = cssModulesConfig !== null && cssModulesConfig !== void 0 ? cssModulesConfig : true;
114
+ }
115
+ }
116
+ res = (0, _lightningcss().transform)({
117
+ filename: _path().default.relative(options.projectRoot, asset.filePath),
118
+ code,
119
+ cssModules,
120
+ analyzeDependencies: asset.meta.hasDependencies !== false,
121
+ sourceMap: !!asset.env.sourceMap,
122
+ drafts: config === null || config === void 0 ? void 0 : config.drafts,
123
+ pseudoClasses: config === null || config === void 0 ? void 0 : config.pseudoClasses,
124
+ errorRecovery: (config === null || config === void 0 ? void 0 : config.errorRecovery) || false,
125
+ targets
126
+ });
127
+ }
128
+ } catch (err) {
129
+ var _err$data;
130
+ err.filePath = asset.filePath;
131
+ let diagnostic = (0, _diagnostic().errorToDiagnostic)(err, {
132
+ origin: '@parcel/transformer-css'
133
+ });
134
+ if (((_err$data = err.data) === null || _err$data === void 0 ? void 0 : _err$data.type) === 'AmbiguousUrlInCustomProperty' && err.data.url) {
135
+ let p = '/' + (0, _utils().relativePath)(options.projectRoot, _path().default.resolve(_path().default.dirname(asset.filePath), err.data.url), false);
136
+ diagnostic[0].hints = [`Replace with: url(${p})`];
137
+ diagnostic[0].documentationURL = 'https://parceljs.org/languages/css/#url()';
138
+ }
139
+ throw new (_diagnostic().default)({
140
+ diagnostic
141
+ });
79
142
  }
80
-
81
- let ast = asset.ast; // Check for `hasDependencies` being false here as well, as it's possible
82
- // another transformer (such as PostCSSTransformer) has already parsed an
83
- // ast and CSSTransformer's parse was never called.
84
-
85
- if (!ast || asset.meta.hasDependencies === false) {
86
- return [asset];
143
+ if (res.warnings) {
144
+ for (let warning of res.warnings) {
145
+ logger.warn({
146
+ message: warning.message,
147
+ codeFrames: [{
148
+ filePath: asset.filePath,
149
+ codeHighlights: [{
150
+ start: {
151
+ line: warning.loc.line,
152
+ column: warning.loc.column + 1
153
+ },
154
+ end: {
155
+ line: warning.loc.line,
156
+ column: warning.loc.column + 1
157
+ }
158
+ }]
159
+ }]
160
+ });
161
+ }
87
162
  }
88
-
89
- ast.program.walkAtRules('import', rule => {
90
- let params = (0, _postcssValueParser.default)(rule.params);
91
- let [name, ...media] = params.nodes;
92
- let moduleSpecifier;
93
-
94
- if (name.type === 'function' && name.value === 'url' && name.nodes.length) {
95
- name = name.nodes[0];
163
+ asset.setBuffer(res.code);
164
+ if (res.map != null) {
165
+ let vlqMap = JSON.parse(res.map.toString());
166
+ let map = new (_sourceMap().default)(options.projectRoot);
167
+ map.addVLQMap(vlqMap);
168
+ if (originalMap) {
169
+ map.extends(originalMap);
96
170
  }
97
-
98
- moduleSpecifier = name.value;
99
-
100
- if (!moduleSpecifier) {
101
- throw new Error('Could not find import name for ' + rule);
171
+ asset.setMap(map);
172
+ }
173
+ if (res.dependencies) {
174
+ for (let dep of res.dependencies) {
175
+ let loc = convertLoc(dep.loc);
176
+ if (originalMap) {
177
+ loc = (0, _utils().remapSourceLocation)(loc, originalMap);
178
+ }
179
+ if (dep.type === 'import' && !res.exports) {
180
+ asset.addDependency({
181
+ specifier: dep.url,
182
+ specifierType: 'url',
183
+ loc,
184
+ packageConditions: ['style'],
185
+ meta: {
186
+ // For the glob resolver to distinguish between `@import` and other URL dependencies.
187
+ isCSSImport: true,
188
+ media: dep.media
189
+ }
190
+ });
191
+ } else if (dep.type === 'url') {
192
+ asset.addURLDependency(dep.url, {
193
+ loc,
194
+ meta: {
195
+ placeholder: dep.placeholder
196
+ }
197
+ });
198
+ }
102
199
  }
103
-
104
- if ((0, _utils.isURL)(moduleSpecifier)) {
105
- name.value = asset.addURLDependency(moduleSpecifier, {
106
- loc: (0, _utils.createDependencyLocation)(rule.source.start, moduleSpecifier, 0, 8)
107
- });
108
- } else {
109
- // If this came from an inline <style> tag, don't inline the imported file. Replace with the correct URL instead.
110
- // TODO: run CSSPackager on inline style tags.
111
- // let inlineHTML =
112
- // this.options.rendition && this.options.rendition.inlineHTML;
113
- // if (inlineHTML) {
114
- // name.value = asset.addURLDependency(dep, {loc: rule.source.start});
115
- // rule.params = params.toString();
116
- // } else {
117
- media = _postcssValueParser.default.stringify(media).trim();
118
- let dep = {
119
- moduleSpecifier,
120
- // Offset by 8 as it does not include `@import `
121
- loc: (0, _utils.createDependencyLocation)(rule.source.start, moduleSpecifier, 0, 8),
122
- meta: {
123
- media
124
- }
125
- };
126
- asset.addDependency(dep);
127
- rule.remove(); // }
200
+ }
201
+ let assets = [asset];
202
+ if (res.exports != null) {
203
+ var _asset$uniqueKey;
204
+ let exports = res.exports;
205
+ asset.symbols.ensure();
206
+ asset.symbols.set('default', 'default');
207
+ let dependencies = new Map();
208
+ let locals = new Map();
209
+ let c = 0;
210
+ let depjs = '';
211
+ let js = '';
212
+ for (let key in exports) {
213
+ locals.set(exports[key].name, key);
128
214
  }
129
-
130
- ast.isDirty = true;
131
- });
132
- ast.program.walkDecls(decl => {
133
- if (URL_RE.test(decl.value)) {
134
- let parsed = (0, _postcssValueParser.default)(decl.value);
135
- let isDirty = false;
136
- parsed.walk(node => {
137
- if (node.type === 'function' && node.value === 'url' && node.nodes.length > 0 && !node.nodes[0].value.startsWith('#') // IE's `behavior: url(#default#VML)`
138
- ) {
139
- node.nodes[0].value = asset.addURLDependency(node.nodes[0].value, {
140
- loc: (0, _utils.createDependencyLocation)(decl.source.start, node.nodes[0].value)
215
+ (_asset$uniqueKey = asset.uniqueKey) !== null && _asset$uniqueKey !== void 0 ? _asset$uniqueKey : asset.uniqueKey = asset.id;
216
+ let seen = new Set();
217
+ let add = key => {
218
+ if (seen.has(key)) {
219
+ return;
220
+ }
221
+ seen.add(key);
222
+ let e = exports[key];
223
+ let s = `module.exports[${JSON.stringify(key)}] = \`${e.name}`;
224
+ for (let ref of e.composes) {
225
+ s += ' ';
226
+ if (ref.type === 'local') {
227
+ let exported = (0, _nullthrows().default)(locals.get(ref.name));
228
+ add(exported);
229
+ s += '${' + `module.exports[${JSON.stringify(exported)}]` + '}';
230
+ asset.addDependency({
231
+ specifier: (0, _nullthrows().default)(asset.uniqueKey),
232
+ specifierType: 'esm',
233
+ symbols: new Map([[exported, {
234
+ local: ref.name,
235
+ isWeak: false,
236
+ loc: null
237
+ }]])
238
+ });
239
+ } else if (ref.type === 'global') {
240
+ s += ref.name;
241
+ } else if (ref.type === 'dependency') {
242
+ let d = dependencies.get(ref.specifier);
243
+ if (d == null) {
244
+ d = `dep_${c++}`;
245
+ depjs += `import * as ${d} from ${JSON.stringify(ref.specifier)};\n`;
246
+ dependencies.set(ref.specifier, d);
247
+ asset.addDependency({
248
+ specifier: ref.specifier,
249
+ specifierType: 'esm',
250
+ packageConditions: ['style']
141
251
  });
142
- isDirty = true;
143
252
  }
144
- });
145
-
146
- if (isDirty) {
147
- decl.value = parsed.toString();
148
- ast.isDirty = true;
253
+ s += '${' + `${d}[${JSON.stringify(ref.name)}]` + '}';
254
+ }
149
255
  }
150
- }
151
- });
152
- return [asset];
153
- },
154
-
155
- async generate({
156
- asset
157
- }) {
158
- let code;
256
+ s += '`;\n';
159
257
 
160
- if (!asset.ast || !asset.ast.isDirty) {
161
- code = await asset.getCode();
162
- } else {
163
- code = '';
258
+ // If the export is referenced internally (e.g. used @keyframes), add a self-reference
259
+ // to the JS so the symbol is retained during tree-shaking.
260
+ if (e.isReferenced) {
261
+ s += `module.exports[${JSON.stringify(key)}];\n`;
262
+ asset.addDependency({
263
+ specifier: (0, _nullthrows().default)(asset.uniqueKey),
264
+ specifierType: 'esm',
265
+ symbols: new Map([[key, {
266
+ local: exports[key].name,
267
+ isWeak: false,
268
+ loc: null
269
+ }]])
270
+ });
271
+ }
272
+ js += s;
273
+ };
164
274
 
165
- _postcss.default.stringify(asset.ast.program, c => {
166
- code += c;
275
+ // It's possible that the exports can be ordered differently between builds.
276
+ // Sorting by key is safe as the order is irrelevant but needs to be deterministic.
277
+ for (let key of Object.keys(exports).sort()) {
278
+ asset.symbols.set(key, exports[key].name);
279
+ add(key);
280
+ }
281
+ if (res.dependencies) {
282
+ for (let dep of res.dependencies) {
283
+ if (dep.type === 'import') {
284
+ // TODO: Figure out how to treeshake this
285
+ let d = `dep_$${c++}`;
286
+ depjs += `import * as ${d} from ${JSON.stringify(dep.url)};\n`;
287
+ js += `for (let key in ${d}) { if (key in module.exports) module.exports[key] += ' ' + ${d}[key]; else module.exports[key] = ${d}[key]; }\n`;
288
+ asset.symbols.set('*', '*');
289
+ }
290
+ }
291
+ }
292
+ if (res.references != null) {
293
+ let references = res.references;
294
+ for (let symbol in references) {
295
+ let reference = references[symbol];
296
+ asset.addDependency({
297
+ specifier: reference.specifier,
298
+ specifierType: 'esm',
299
+ packageConditions: ['style'],
300
+ symbols: new Map([[reference.name, {
301
+ local: symbol,
302
+ isWeak: false,
303
+ loc: null
304
+ }]])
305
+ });
306
+ asset.meta.hasReferences = true;
307
+ }
308
+ }
309
+ assets.push({
310
+ type: 'js',
311
+ content: depjs + js,
312
+ dependencies: [],
313
+ env
167
314
  });
168
315
  }
169
-
170
- return {
171
- code
172
- };
316
+ return assets;
173
317
  }
174
-
175
318
  });
176
-
177
- exports.default = _default;
319
+ exports.default = _default;
320
+ let cache = new Map();
321
+ function getTargets(browsers) {
322
+ if (browsers == null) {
323
+ return undefined;
324
+ }
325
+ let cached = cache.get(browsers);
326
+ if (cached != null) {
327
+ return cached;
328
+ }
329
+ let targets = (0, _lightningcss().browserslistToTargets)((0, _browserslist().default)(browsers));
330
+ cache.set(browsers, targets);
331
+ return targets;
332
+ }
333
+ function convertLoc(loc) {
334
+ return {
335
+ filePath: loc.filePath,
336
+ start: {
337
+ line: loc.start.line,
338
+ column: loc.start.column
339
+ },
340
+ end: {
341
+ line: loc.end.line,
342
+ column: loc.end.column + 1
343
+ }
344
+ };
345
+ }
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "@parcel/transformer-css",
3
- "version": "2.0.0-nightly.140+4fd6dcae",
3
+ "version": "2.0.0-nightly.1400+1a3a2544b",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
+ "funding": {
9
+ "type": "opencollective",
10
+ "url": "https://opencollective.com/parcel"
11
+ },
8
12
  "repository": {
9
13
  "type": "git",
10
14
  "url": "https://github.com/parcel-bundler/parcel.git"
@@ -12,15 +16,17 @@
12
16
  "main": "lib/CSSTransformer.js",
13
17
  "source": "src/CSSTransformer.js",
14
18
  "engines": {
15
- "node": ">= 10.0.0",
16
- "parcel": "^2.0.0-alpha.1.1"
19
+ "node": ">= 12.0.0",
20
+ "parcel": "2.0.0-nightly.1398+1a3a2544b"
17
21
  },
18
22
  "dependencies": {
19
- "@parcel/plugin": "2.0.0-nightly.140+4fd6dcae",
20
- "@parcel/utils": "2.0.0-nightly.140+4fd6dcae",
21
- "postcss": "^7.0.5",
22
- "postcss-value-parser": "^3.3.1",
23
- "semver": "^5.4.1"
23
+ "@parcel/diagnostic": "2.0.0-nightly.1400+1a3a2544b",
24
+ "@parcel/plugin": "2.0.0-nightly.1400+1a3a2544b",
25
+ "@parcel/source-map": "^2.1.1",
26
+ "@parcel/utils": "2.0.0-nightly.1400+1a3a2544b",
27
+ "browserslist": "^4.6.6",
28
+ "lightningcss": "^1.16.1",
29
+ "nullthrows": "^1.1.1"
24
30
  },
25
- "gitHead": "4fd6dcaea61185bfb4d87ef707e23fb980f8d8a3"
31
+ "gitHead": "1a3a2544b568b1c2bb95eb17ce3b5d4514ab9f08"
26
32
  }
@@ -1,178 +1,334 @@
1
- // @flow
1
+ // @flow strict-local
2
2
 
3
- import type {FilePath} from '@parcel/types';
3
+ import type {SourceLocation} from '@parcel/types';
4
4
 
5
+ import path from 'path';
6
+ import SourceMap from '@parcel/source-map';
5
7
  import {Transformer} from '@parcel/plugin';
6
- import {createDependencyLocation, isURL} from '@parcel/utils';
7
- import postcss from 'postcss';
8
- import valueParser from 'postcss-value-parser';
9
- import semver from 'semver';
8
+ import {
9
+ transform,
10
+ transformStyleAttribute,
11
+ browserslistToTargets,
12
+ type SourceLocation as LightningSourceLocation,
13
+ } from 'lightningcss';
14
+ import {remapSourceLocation, relativePath} from '@parcel/utils';
15
+ import browserslist from 'browserslist';
16
+ import nullthrows from 'nullthrows';
17
+ import ThrowableDiagnostic, {errorToDiagnostic} from '@parcel/diagnostic';
10
18
 
11
- const URL_RE = /url\s*\("?(?![a-z]+:)/;
12
- const IMPORT_RE = /@import/;
13
-
14
- function canHaveDependencies(filePath: FilePath, code: string) {
15
- return !/\.css$/.test(filePath) || IMPORT_RE.test(code) || URL_RE.test(code);
16
- }
17
-
18
- export default new Transformer({
19
- canReuseAST({ast}) {
20
- return ast.type === 'postcss' && semver.satisfies(ast.version, '^7.0.0');
21
- },
22
-
23
- async parse({asset}) {
24
- // This is set by other transformers (e.g. Stylus) to indicate that it has already processed
25
- // all dependencies, and that the CSS transformer can skip this asset completely. This is
26
- // required because when stylus processes e.g. url() it replaces them with a dependency id
27
- // to be filled in later. When the CSS transformer runs, it would pick that up and try to
28
- // resolve a dependency for the id which obviously doesn't exist. Also, it's faster to do
29
- // it this way since the resulting CSS doesn't need to be re-parsed.
30
- if (asset.meta.hasDependencies === false) {
31
- return null;
32
- }
33
-
34
- let code = await asset.getCode();
35
- if (!canHaveDependencies(asset.filePath, code)) {
36
- return null;
37
- }
38
-
39
- return {
40
- type: 'postcss',
41
- version: '7.0.0',
42
- isDirty: false,
43
- program: postcss.parse(code, {
44
- from: asset.filePath,
45
- }),
46
- };
19
+ export default (new Transformer({
20
+ async loadConfig({config, options}) {
21
+ let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
22
+ packageKey: '@parcel/transformer-css',
23
+ });
24
+ return conf?.contents;
47
25
  },
48
-
49
- transform({asset}) {
26
+ async transform({asset, config, options, logger}) {
50
27
  // Normalize the asset's environment so that properties that only affect JS don't cause CSS to be duplicated.
51
28
  // For example, with ESModule and CommonJS targets, only a single shared CSS bundle should be produced.
29
+ let env = asset.env;
52
30
  asset.setEnvironment({
53
31
  context: 'browser',
54
32
  engines: {
55
33
  browsers: asset.env.engines.browsers,
56
34
  },
57
- minify: asset.env.minify,
35
+ shouldOptimize: asset.env.shouldOptimize,
36
+ shouldScopeHoist: asset.env.shouldScopeHoist,
37
+ sourceMap: asset.env.sourceMap,
58
38
  });
59
39
 
60
- // When this asset is an bundle entry, allow that bundle to be split to load shared assets separately.
61
- // Only set here if it is null to allow previous transformers to override this behavior.
62
- if (asset.isSplittable == null) {
63
- asset.isSplittable = true;
40
+ let [code, originalMap] = await Promise.all([
41
+ asset.getBuffer(),
42
+ asset.getMap(),
43
+ ]);
44
+
45
+ let targets = getTargets(asset.env.engines.browsers);
46
+ let res;
47
+ try {
48
+ if (asset.meta.type === 'attr') {
49
+ res = transformStyleAttribute({
50
+ code,
51
+ analyzeDependencies: true,
52
+ errorRecovery: config?.errorRecovery || false,
53
+ targets,
54
+ });
55
+ } else {
56
+ let cssModules = false;
57
+ if (
58
+ asset.meta.type !== 'tag' &&
59
+ asset.meta.cssModulesCompiled == null
60
+ ) {
61
+ let cssModulesConfig = config?.cssModules;
62
+ if (
63
+ (asset.isSource &&
64
+ (typeof cssModulesConfig === 'boolean' ||
65
+ cssModulesConfig?.global)) ||
66
+ /\.module\./.test(asset.filePath)
67
+ ) {
68
+ if (cssModulesConfig?.dashedIdents && !asset.isSource) {
69
+ cssModulesConfig.dashedIdents = false;
70
+ }
71
+
72
+ cssModules = cssModulesConfig ?? true;
73
+ }
74
+ }
75
+
76
+ res = transform({
77
+ filename: path.relative(options.projectRoot, asset.filePath),
78
+ code,
79
+ cssModules,
80
+ analyzeDependencies: asset.meta.hasDependencies !== false,
81
+ sourceMap: !!asset.env.sourceMap,
82
+ drafts: config?.drafts,
83
+ pseudoClasses: config?.pseudoClasses,
84
+ errorRecovery: config?.errorRecovery || false,
85
+ targets,
86
+ });
87
+ }
88
+ } catch (err) {
89
+ err.filePath = asset.filePath;
90
+ let diagnostic = errorToDiagnostic(err, {
91
+ origin: '@parcel/transformer-css',
92
+ });
93
+ if (err.data?.type === 'AmbiguousUrlInCustomProperty' && err.data.url) {
94
+ let p =
95
+ '/' +
96
+ relativePath(
97
+ options.projectRoot,
98
+ path.resolve(path.dirname(asset.filePath), err.data.url),
99
+ false,
100
+ );
101
+ diagnostic[0].hints = [`Replace with: url(${p})`];
102
+ diagnostic[0].documentationURL =
103
+ 'https://parceljs.org/languages/css/#url()';
104
+ }
105
+
106
+ throw new ThrowableDiagnostic({
107
+ diagnostic,
108
+ });
64
109
  }
65
110
 
66
- let ast = asset.ast;
67
- // Check for `hasDependencies` being false here as well, as it's possible
68
- // another transformer (such as PostCSSTransformer) has already parsed an
69
- // ast and CSSTransformer's parse was never called.
70
- if (!ast || asset.meta.hasDependencies === false) {
71
- return [asset];
111
+ if (res.warnings) {
112
+ for (let warning of res.warnings) {
113
+ logger.warn({
114
+ message: warning.message,
115
+ codeFrames: [
116
+ {
117
+ filePath: asset.filePath,
118
+ codeHighlights: [
119
+ {
120
+ start: {
121
+ line: warning.loc.line,
122
+ column: warning.loc.column + 1,
123
+ },
124
+ end: {
125
+ line: warning.loc.line,
126
+ column: warning.loc.column + 1,
127
+ },
128
+ },
129
+ ],
130
+ },
131
+ ],
132
+ });
133
+ }
72
134
  }
73
135
 
74
- ast.program.walkAtRules('import', rule => {
75
- let params = valueParser(rule.params);
76
- let [name, ...media] = params.nodes;
77
- let moduleSpecifier;
78
- if (
79
- name.type === 'function' &&
80
- name.value === 'url' &&
81
- name.nodes.length
82
- ) {
83
- name = name.nodes[0];
136
+ asset.setBuffer(res.code);
137
+
138
+ if (res.map != null) {
139
+ let vlqMap = JSON.parse(res.map.toString());
140
+ let map = new SourceMap(options.projectRoot);
141
+ map.addVLQMap(vlqMap);
142
+
143
+ if (originalMap) {
144
+ map.extends(originalMap);
84
145
  }
85
146
 
86
- moduleSpecifier = name.value;
147
+ asset.setMap(map);
148
+ }
149
+
150
+ if (res.dependencies) {
151
+ for (let dep of res.dependencies) {
152
+ let loc = convertLoc(dep.loc);
153
+ if (originalMap) {
154
+ loc = remapSourceLocation(loc, originalMap);
155
+ }
87
156
 
88
- if (!moduleSpecifier) {
89
- throw new Error('Could not find import name for ' + rule);
157
+ if (dep.type === 'import' && !res.exports) {
158
+ asset.addDependency({
159
+ specifier: dep.url,
160
+ specifierType: 'url',
161
+ loc,
162
+ packageConditions: ['style'],
163
+ meta: {
164
+ // For the glob resolver to distinguish between `@import` and other URL dependencies.
165
+ isCSSImport: true,
166
+ media: dep.media,
167
+ },
168
+ });
169
+ } else if (dep.type === 'url') {
170
+ asset.addURLDependency(dep.url, {
171
+ loc,
172
+ meta: {
173
+ placeholder: dep.placeholder,
174
+ },
175
+ });
176
+ }
90
177
  }
178
+ }
91
179
 
92
- if (isURL(moduleSpecifier)) {
93
- name.value = asset.addURLDependency(moduleSpecifier, {
94
- loc: createDependencyLocation(
95
- rule.source.start,
96
- moduleSpecifier,
97
- 0,
98
- 8,
99
- ),
100
- });
101
- } else {
102
- // If this came from an inline <style> tag, don't inline the imported file. Replace with the correct URL instead.
103
- // TODO: run CSSPackager on inline style tags.
104
- // let inlineHTML =
105
- // this.options.rendition && this.options.rendition.inlineHTML;
106
- // if (inlineHTML) {
107
- // name.value = asset.addURLDependency(dep, {loc: rule.source.start});
108
- // rule.params = params.toString();
109
- // } else {
110
- media = valueParser.stringify(media).trim();
111
- let dep = {
112
- moduleSpecifier,
113
- // Offset by 8 as it does not include `@import `
114
- loc: createDependencyLocation(
115
- rule.source.start,
116
- moduleSpecifier,
117
- 0,
118
- 8,
119
- ),
120
- meta: {
121
- media,
122
- },
123
- };
124
- asset.addDependency(dep);
125
- rule.remove();
126
- // }
180
+ let assets = [asset];
181
+
182
+ if (res.exports != null) {
183
+ let exports = res.exports;
184
+ asset.symbols.ensure();
185
+ asset.symbols.set('default', 'default');
186
+
187
+ let dependencies = new Map();
188
+ let locals = new Map();
189
+ let c = 0;
190
+ let depjs = '';
191
+ let js = '';
192
+
193
+ let jsDeps = [];
194
+
195
+ for (let key in exports) {
196
+ locals.set(exports[key].name, key);
127
197
  }
128
- ast.isDirty = true;
129
- });
130
198
 
131
- ast.program.walkDecls(decl => {
132
- if (URL_RE.test(decl.value)) {
133
- let parsed = valueParser(decl.value);
134
- let isDirty = false;
199
+ asset.uniqueKey ??= asset.id;
135
200
 
136
- parsed.walk(node => {
137
- if (
138
- node.type === 'function' &&
139
- node.value === 'url' &&
140
- node.nodes.length > 0 &&
141
- !node.nodes[0].value.startsWith('#') // IE's `behavior: url(#default#VML)`
142
- ) {
143
- node.nodes[0].value = asset.addURLDependency(node.nodes[0].value, {
144
- loc: createDependencyLocation(
145
- decl.source.start,
146
- node.nodes[0].value,
147
- ),
201
+ let seen = new Set();
202
+ let add = key => {
203
+ if (seen.has(key)) {
204
+ return;
205
+ }
206
+ seen.add(key);
207
+
208
+ let e = exports[key];
209
+ let s = `module.exports[${JSON.stringify(key)}] = \`${e.name}`;
210
+
211
+ for (let ref of e.composes) {
212
+ s += ' ';
213
+ if (ref.type === 'local') {
214
+ let exported = nullthrows(locals.get(ref.name));
215
+ add(exported);
216
+ s += '${' + `module.exports[${JSON.stringify(exported)}]` + '}';
217
+ asset.addDependency({
218
+ specifier: nullthrows(asset.uniqueKey),
219
+ specifierType: 'esm',
220
+ symbols: new Map([
221
+ [exported, {local: ref.name, isWeak: false, loc: null}],
222
+ ]),
148
223
  });
149
- isDirty = true;
224
+ } else if (ref.type === 'global') {
225
+ s += ref.name;
226
+ } else if (ref.type === 'dependency') {
227
+ let d = dependencies.get(ref.specifier);
228
+ if (d == null) {
229
+ d = `dep_${c++}`;
230
+ depjs += `import * as ${d} from ${JSON.stringify(
231
+ ref.specifier,
232
+ )};\n`;
233
+ dependencies.set(ref.specifier, d);
234
+ asset.addDependency({
235
+ specifier: ref.specifier,
236
+ specifierType: 'esm',
237
+ packageConditions: ['style'],
238
+ });
239
+ }
240
+ s += '${' + `${d}[${JSON.stringify(ref.name)}]` + '}';
150
241
  }
151
- });
242
+ }
243
+
244
+ s += '`;\n';
245
+
246
+ // If the export is referenced internally (e.g. used @keyframes), add a self-reference
247
+ // to the JS so the symbol is retained during tree-shaking.
248
+ if (e.isReferenced) {
249
+ s += `module.exports[${JSON.stringify(key)}];\n`;
250
+ asset.addDependency({
251
+ specifier: nullthrows(asset.uniqueKey),
252
+ specifierType: 'esm',
253
+ symbols: new Map([
254
+ [key, {local: exports[key].name, isWeak: false, loc: null}],
255
+ ]),
256
+ });
257
+ }
152
258
 
153
- if (isDirty) {
154
- decl.value = parsed.toString();
155
- ast.isDirty = true;
259
+ js += s;
260
+ };
261
+
262
+ // It's possible that the exports can be ordered differently between builds.
263
+ // Sorting by key is safe as the order is irrelevant but needs to be deterministic.
264
+ for (let key of Object.keys(exports).sort()) {
265
+ asset.symbols.set(key, exports[key].name);
266
+ add(key);
267
+ }
268
+
269
+ if (res.dependencies) {
270
+ for (let dep of res.dependencies) {
271
+ if (dep.type === 'import') {
272
+ // TODO: Figure out how to treeshake this
273
+ let d = `dep_$${c++}`;
274
+ depjs += `import * as ${d} from ${JSON.stringify(dep.url)};\n`;
275
+ js += `for (let key in ${d}) { if (key in module.exports) module.exports[key] += ' ' + ${d}[key]; else module.exports[key] = ${d}[key]; }\n`;
276
+ asset.symbols.set('*', '*');
277
+ }
156
278
  }
157
279
  }
158
- });
159
280
 
160
- return [asset];
161
- },
281
+ if (res.references != null) {
282
+ let references = res.references;
283
+ for (let symbol in references) {
284
+ let reference = references[symbol];
285
+ asset.addDependency({
286
+ specifier: reference.specifier,
287
+ specifierType: 'esm',
288
+ packageConditions: ['style'],
289
+ symbols: new Map([
290
+ [reference.name, {local: symbol, isWeak: false, loc: null}],
291
+ ]),
292
+ });
293
+
294
+ asset.meta.hasReferences = true;
295
+ }
296
+ }
162
297
 
163
- async generate({asset}) {
164
- let code;
165
- if (!asset.ast || !asset.ast.isDirty) {
166
- code = await asset.getCode();
167
- } else {
168
- code = '';
169
- postcss.stringify(asset.ast.program, c => {
170
- code += c;
298
+ assets.push({
299
+ type: 'js',
300
+ content: depjs + js,
301
+ dependencies: jsDeps,
302
+ env,
171
303
  });
172
304
  }
173
305
 
174
- return {
175
- code,
176
- };
306
+ return assets;
177
307
  },
178
- });
308
+ }): Transformer);
309
+
310
+ let cache = new Map();
311
+
312
+ function getTargets(browsers) {
313
+ if (browsers == null) {
314
+ return undefined;
315
+ }
316
+
317
+ let cached = cache.get(browsers);
318
+ if (cached != null) {
319
+ return cached;
320
+ }
321
+
322
+ let targets = browserslistToTargets(browserslist(browsers));
323
+
324
+ cache.set(browsers, targets);
325
+ return targets;
326
+ }
327
+
328
+ function convertLoc(loc: LightningSourceLocation): SourceLocation {
329
+ return {
330
+ filePath: loc.filePath,
331
+ start: {line: loc.start.line, column: loc.start.column},
332
+ end: {line: loc.end.line, column: loc.end.column + 1},
333
+ };
334
+ }