ng-packagr 12.2.1 → 12.2.5

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,8 @@
1
+ // If the platform does not support the native variant of esbuild, this will crash.
2
+ // This script can then be spawned by the CLI to determine if native usage is supported.
3
+ require('esbuild')
4
+ .formatMessages([], { kind: 'error ' })
5
+ .then(
6
+ () => {},
7
+ () => {},
8
+ );
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import type { FormatMessagesOptions, PartialMessage, TransformOptions, TransformResult } from 'esbuild';
9
+ /**
10
+ * Provides the ability to execute esbuild regardless of the current platform's support
11
+ * for using the native variant of esbuild. The native variant will be preferred (assuming
12
+ * the `alwaysUseWasm` constructor option is `false) due to its inherent performance advantages.
13
+ * At first use of esbuild, a supportability test will be automatically performed and the
14
+ * WASM-variant will be used if needed by the platform.
15
+ */
16
+ export declare class EsbuildExecutor implements Pick<typeof import('esbuild'), 'transform' | 'formatMessages'> {
17
+ private alwaysUseWasm;
18
+ private esbuildTransform;
19
+ private esbuildFormatMessages;
20
+ private initialized;
21
+ /**
22
+ * Constructs an instance of the `EsbuildExecutor` class.
23
+ *
24
+ * @param alwaysUseWasm If true, the WASM-variant will be preferred and no support test will be
25
+ * performed; if false (default), the native variant will be preferred.
26
+ */
27
+ constructor(alwaysUseWasm?: boolean);
28
+ /**
29
+ * Determines whether the native variant of esbuild can be used on the current platform.
30
+ *
31
+ * @returns True, if the native variant of esbuild is support; False, if the WASM variant is required.
32
+ */
33
+ static hasNativeSupport(): boolean;
34
+ /**
35
+ * Initializes the esbuild transform and format messages functions.
36
+ *
37
+ * @returns A promise that fulfills when esbuild has been loaded and available for use.
38
+ */
39
+ private ensureEsbuild;
40
+ /**
41
+ * Transitions an executor instance to use the WASM-variant of esbuild.
42
+ */
43
+ private useWasm;
44
+ transform(input: string, options?: TransformOptions): Promise<TransformResult>;
45
+ formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise<string[]>;
46
+ }
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ /**
3
+ * @license
4
+ * Copyright Google LLC All Rights Reserved.
5
+ *
6
+ * Use of this source code is governed by an MIT-style license that can be
7
+ * found in the LICENSE file at https://angular.io/license
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.EsbuildExecutor = void 0;
11
+ const child_process_1 = require("child_process");
12
+ const path = require("path");
13
+ /**
14
+ * Provides the ability to execute esbuild regardless of the current platform's support
15
+ * for using the native variant of esbuild. The native variant will be preferred (assuming
16
+ * the `alwaysUseWasm` constructor option is `false) due to its inherent performance advantages.
17
+ * At first use of esbuild, a supportability test will be automatically performed and the
18
+ * WASM-variant will be used if needed by the platform.
19
+ */
20
+ class EsbuildExecutor {
21
+ /**
22
+ * Constructs an instance of the `EsbuildExecutor` class.
23
+ *
24
+ * @param alwaysUseWasm If true, the WASM-variant will be preferred and no support test will be
25
+ * performed; if false (default), the native variant will be preferred.
26
+ */
27
+ constructor(alwaysUseWasm = false) {
28
+ this.alwaysUseWasm = alwaysUseWasm;
29
+ this.initialized = false;
30
+ this.esbuildTransform = this.esbuildFormatMessages = () => {
31
+ throw new Error('esbuild implementation missing');
32
+ };
33
+ }
34
+ /**
35
+ * Determines whether the native variant of esbuild can be used on the current platform.
36
+ *
37
+ * @returns True, if the native variant of esbuild is support; False, if the WASM variant is required.
38
+ */
39
+ static hasNativeSupport() {
40
+ // Try to use native variant to ensure it is functional for the platform.
41
+ // Spawning a separate esbuild check process is used to determine if the native
42
+ // variant is viable. If check fails, the WASM variant is initialized instead.
43
+ // Attempting to call one of the native esbuild functions is not a viable test
44
+ // currently since esbuild spawn errors are currently not propagated through the
45
+ // call stack for the esbuild function. If this limitation is removed in the future
46
+ // then the separate process spawn check can be removed in favor of a direct function
47
+ // call check.
48
+ try {
49
+ const { status, error } = child_process_1.spawnSync(process.execPath, [
50
+ path.join(__dirname, './esbuild-check.js'),
51
+ ]);
52
+ return status === 0 && error === undefined;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ /**
59
+ * Initializes the esbuild transform and format messages functions.
60
+ *
61
+ * @returns A promise that fulfills when esbuild has been loaded and available for use.
62
+ */
63
+ async ensureEsbuild() {
64
+ if (this.initialized) {
65
+ return;
66
+ }
67
+ // If the WASM variant was preferred at class construction or native is not supported, use WASM
68
+ if (this.alwaysUseWasm || !EsbuildExecutor.hasNativeSupport()) {
69
+ await this.useWasm();
70
+ this.initialized = true;
71
+ return;
72
+ }
73
+ try {
74
+ // Use the faster native variant if available.
75
+ const { transform, formatMessages } = await Promise.resolve().then(() => require('esbuild'));
76
+ this.esbuildTransform = transform;
77
+ this.esbuildFormatMessages = formatMessages;
78
+ }
79
+ catch {
80
+ // If the native variant is not installed then use the WASM-based variant
81
+ await this.useWasm();
82
+ }
83
+ this.initialized = true;
84
+ }
85
+ /**
86
+ * Transitions an executor instance to use the WASM-variant of esbuild.
87
+ */
88
+ async useWasm() {
89
+ const { transform, formatMessages } = await Promise.resolve().then(() => require('esbuild-wasm'));
90
+ this.esbuildTransform = transform;
91
+ this.esbuildFormatMessages = formatMessages;
92
+ // The ESBUILD_BINARY_PATH environment variable cannot exist when attempting to use the
93
+ // WASM variant. If it is then the binary located at the specified path will be used instead
94
+ // of the WASM variant.
95
+ delete process.env.ESBUILD_BINARY_PATH;
96
+ this.alwaysUseWasm = true;
97
+ }
98
+ async transform(input, options) {
99
+ await this.ensureEsbuild();
100
+ return this.esbuildTransform(input, options);
101
+ }
102
+ async formatMessages(messages, options) {
103
+ await this.ensureEsbuild();
104
+ return this.esbuildFormatMessages(messages, options);
105
+ }
106
+ }
107
+ exports.EsbuildExecutor = EsbuildExecutor;
108
+ //# sourceMappingURL=esbuild-executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"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S,EAAC,CAAC;YAE9D,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;YAClC,IAAI,CAAC,qBAAqB,GAAG,cAAc,CAAC;SAC7C;QAAC,MAAM;YACN,yEAAyE;YACzE,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;SACtB;QAED,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,OAAO;QACnB,MAAM,EAAE,SAAS,EAAE,cAAc,EAAE,GAAG,2CAAa,cAAc,EAAC,CAAC;QACnE,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;QAClC,IAAI,CAAC,qBAAqB,GAAG,cAAc,CAAC;QAE5C,uFAAuF;QACvF,4FAA4F;QAC5F,uBAAuB;QACvB,OAAO,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC;QAEvC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;IAC5B,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,KAAa,EAAE,OAA0B;QACvD,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;QAE3B,OAAO,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,cAAc,CAClB,QAA0B,EAC1B,OAA8B;QAE9B,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;QAE3B,OAAO,IAAI,CAAC,qBAAqB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACvD,CAAC;CACF;AA1GD,0CA0GC","sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n import { spawnSync } from 'child_process';\n import type {\n FormatMessagesOptions,\n PartialMessage,\n TransformOptions,\n TransformResult,\n } from 'esbuild';\n import * as path from 'path';\n \n /**\n * Provides the ability to execute esbuild regardless of the current platform's support\n * for using the native variant of esbuild. The native variant will be preferred (assuming\n * the `alwaysUseWasm` constructor option is `false) due to its inherent performance advantages.\n * At first use of esbuild, a supportability test will be automatically performed and the\n * WASM-variant will be used if needed by the platform.\n */\n export class EsbuildExecutor\n implements Pick<typeof import('esbuild'), 'transform' | 'formatMessages'>\n {\n private esbuildTransform: this['transform'];\n private esbuildFormatMessages: this['formatMessages'];\n private initialized = false;\n \n /**\n * Constructs an instance of the `EsbuildExecutor` class.\n *\n * @param alwaysUseWasm If true, the WASM-variant will be preferred and no support test will be\n * performed; if false (default), the native variant will be preferred.\n */\n constructor(private alwaysUseWasm = false) {\n this.esbuildTransform = this.esbuildFormatMessages = () => {\n throw new Error('esbuild implementation missing');\n };\n }\n \n /**\n * Determines whether the native variant of esbuild can be used on the current platform.\n *\n * @returns True, if the native variant of esbuild is support; False, if the WASM variant is required.\n */\n static hasNativeSupport(): boolean {\n // Try to use native variant to ensure it is functional for the platform.\n // Spawning a separate esbuild check process is used to determine if the native\n // variant is viable. If check fails, the WASM variant is initialized instead.\n // Attempting to call one of the native esbuild functions is not a viable test\n // currently since esbuild spawn errors are currently not propagated through the\n // call stack for the esbuild function. If this limitation is removed in the future\n // then the separate process spawn check can be removed in favor of a direct function\n // call check.\n try {\n const { status, error } = spawnSync(process.execPath, [\n path.join(__dirname, './esbuild-check.js'),\n ]);\n \n return status === 0 && error === undefined;\n } catch {\n return false;\n }\n }\n \n /**\n * Initializes the esbuild transform and format messages functions.\n *\n * @returns A promise that fulfills when esbuild has been loaded and available for use.\n */\n private async ensureEsbuild(): Promise<void> {\n if (this.initialized) {\n return;\n }\n \n // If the WASM variant was preferred at class construction or native is not supported, use WASM\n if (this.alwaysUseWasm || !EsbuildExecutor.hasNativeSupport()) {\n await this.useWasm();\n this.initialized = true;\n \n return;\n }\n \n try {\n // Use the faster native variant if available.\n const { transform, formatMessages } = await import('esbuild');\n \n this.esbuildTransform = transform;\n this.esbuildFormatMessages = formatMessages;\n } catch {\n // If the native variant is not installed then use the WASM-based variant\n await this.useWasm();\n }\n \n this.initialized = true;\n }\n \n /**\n * Transitions an executor instance to use the WASM-variant of esbuild.\n */\n private async useWasm(): Promise<void> {\n const { transform, formatMessages } = await import('esbuild-wasm');\n this.esbuildTransform = transform;\n this.esbuildFormatMessages = formatMessages;\n \n // The ESBUILD_BINARY_PATH environment variable cannot exist when attempting to use the\n // WASM variant. If it is then the binary located at the specified path will be used instead\n // of the WASM variant.\n delete process.env.ESBUILD_BINARY_PATH;\n \n this.alwaysUseWasm = true;\n }\n \n async transform(input: string, options?: TransformOptions): Promise<TransformResult> {\n await this.ensureEsbuild();\n \n return this.esbuildTransform(input, options);\n }\n \n async formatMessages(\n messages: PartialMessage[],\n options: FormatMessagesOptions,\n ): Promise<string[]> {\n await this.ensureEsbuild();\n \n return this.esbuildFormatMessages(messages, options);\n }\n }"]}
@@ -11,8 +11,10 @@ export declare class StylesheetProcessor {
11
11
  private readonly basePath;
12
12
  private readonly cssUrl?;
13
13
  private readonly styleIncludePaths?;
14
+ private targets;
14
15
  private browserslistData;
15
16
  private postCssProcessor;
17
+ private esbuild;
16
18
  constructor(basePath: string, cssUrl?: CssUrl, styleIncludePaths?: string[]);
17
19
  process(filePath: string): Promise<string>;
18
20
  private createPostCssPlugins;
@@ -7,12 +7,12 @@ const os_1 = require("os");
7
7
  const cacache = require("cacache");
8
8
  const postcss_1 = require("postcss");
9
9
  const postcssUrl = require("postcss-url");
10
- const esbuild_1 = require("esbuild");
11
10
  const postcssPresetEnv = require("postcss-preset-env");
12
11
  const log = require("../../utils/log");
13
12
  const fs_1 = require("../../utils/fs");
14
13
  const crypto_1 = require("crypto");
15
14
  const path_1 = require("path");
15
+ const esbuild_executor_1 = require("../../esbuild/esbuild-executor");
16
16
  var CssUrl;
17
17
  (function (CssUrl) {
18
18
  CssUrl["inline"] = "inline";
@@ -32,8 +32,22 @@ class StylesheetProcessor {
32
32
  this.basePath = basePath;
33
33
  this.cssUrl = cssUrl;
34
34
  this.styleIncludePaths = styleIncludePaths;
35
+ this.esbuild = new esbuild_executor_1.EsbuildExecutor();
35
36
  log.debug(`determine browserslist for ${this.basePath}`);
37
+ // By default, browserslist defaults are too inclusive
38
+ // https://github.com/browserslist/browserslist/blob/83764ea81ffaa39111c204b02c371afa44a4ff07/index.js#L516-L522
39
+ // We change the default query to browsers that Angular support.
40
+ // https://angular.io/guide/browser-support
41
+ browserslist.defaults = [
42
+ 'last 1 Chrome version',
43
+ 'last 1 Firefox version',
44
+ 'last 2 Edge major versions',
45
+ 'last 2 Safari major versions',
46
+ 'last 2 iOS major versions',
47
+ 'Firefox ESR',
48
+ ];
36
49
  this.browserslistData = browserslist(undefined, { path: this.basePath });
50
+ this.targets = transformSupportedBrowsersToTargets(this.browserslistData);
37
51
  this.postCssProcessor = this.createPostCssPlugins();
38
52
  }
39
53
  async process(filePath) {
@@ -66,13 +80,14 @@ class StylesheetProcessor {
66
80
  to: filePath.replace(path_1.extname(filePath), '.css'),
67
81
  });
68
82
  const warnings = result.warnings().map(w => w.toString());
69
- const { code, warnings: esBuildWarnings } = await esbuild_1.transform(result.css, {
83
+ const { code, warnings: esBuildWarnings } = await this.esbuild.transform(result.css, {
70
84
  loader: 'css',
71
85
  minify: true,
86
+ target: this.targets,
72
87
  sourcefile: filePath,
73
88
  });
74
89
  if (esBuildWarnings.length > 0) {
75
- warnings.push(...(await esbuild_1.formatMessages(esBuildWarnings, { kind: 'warning' })));
90
+ warnings.push(...(await this.esbuild.formatMessages(esBuildWarnings, { kind: 'warning' })));
76
91
  }
77
92
  // Add to cache
78
93
  await cacache.put(cachePath, key, JSON.stringify({
@@ -130,6 +145,7 @@ class StylesheetProcessor {
130
145
  filename: filePath,
131
146
  javascriptEnabled: true,
132
147
  paths: this.styleIncludePaths,
148
+ math: 'always',
133
149
  });
134
150
  return content;
135
151
  }
@@ -163,4 +179,31 @@ async function readCacheEntry(cachePath, key) {
163
179
  }
164
180
  return undefined;
165
181
  }
182
+ function transformSupportedBrowsersToTargets(supportedBrowsers) {
183
+ const transformed = [];
184
+ // https://esbuild.github.io/api/#target
185
+ const esBuildSupportedBrowsers = new Set(['safari', 'firefox', 'edge', 'chrome', 'ios']);
186
+ for (const browser of supportedBrowsers) {
187
+ let [browserName, version] = browser.split(' ');
188
+ // browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios`
189
+ if (browserName === 'ios_saf') {
190
+ browserName = 'ios';
191
+ // browserslist also uses ranges for iOS Safari versions but only the lowest is required
192
+ // to perform minimum supported feature checks. esbuild also expects a single version.
193
+ [version] = version.split('-');
194
+ }
195
+ if (browserName === 'ie') {
196
+ transformed.push('edge12');
197
+ }
198
+ else if (esBuildSupportedBrowsers.has(browserName)) {
199
+ if (browserName === 'safari' && version === 'TP') {
200
+ // esbuild only supports numeric versions so `TP` is converted to a high number (999) since
201
+ // a Technology Preview (TP) of Safari is assumed to support all currently known features.
202
+ version = '999';
203
+ }
204
+ transformed.push(browserName + version);
205
+ }
206
+ }
207
+ return transformed.length ? transformed : undefined;
208
+ }
166
209
  //# sourceMappingURL=stylesheet-processor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stylesheet-processor.js","sourceRoot":"","sources":["../../../../src/lib/ivy/styles/stylesheet-processor.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAC7C,qDAAqD;AACrD,2BAA4B;AAC5B,mCAAmC;AACnC,qCAA8B;AAC9B,0CAA0C;AAC1C,qCAAoD;AACpD,uDAAuD;AACvD,uCAAuC;AACvC,uCAA0C;AAC1C,mCAAoC;AACpC,+BAA+B;AAE/B,IAAY,MAGX;AAHD,WAAY,MAAM;IAChB,2BAAiB,CAAA;IACjB,uBAAa,CAAA;AACf,CAAC,EAHW,MAAM,GAAN,cAAM,KAAN,cAAM,QAGjB;AAQD,MAAM,SAAS,GAAG,kBAAkB,CAAC,EAAE,IAAI,EAAE,mBAAmB,EAAE,CAAC,IAAI,WAAM,EAAE,CAAC;AAChF,IAAI,gBAAoC,CAAC;AACzC,IAAI;IACF,gBAAgB,GAAG,OAAO,CAA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,CAAC,SAAiB,EAAE,GAAW;IAC1D,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IACrD,IAAI,KAAK,EAAE;QACT,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,aAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;KACvD;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import * as browserslist from 'browserslist';\nimport * as findCacheDirectory from 'find-cache-dir';\nimport { tmpdir } from 'os';\nimport * as cacache from 'cacache';\nimport postcss from 'postcss';\nimport * as postcssUrl from 'postcss-url';\nimport { transform, formatMessages } from 'esbuild';\nimport * as postcssPresetEnv from 'postcss-preset-env';\nimport * as log from '../../utils/log';\nimport { readFile } from '../../utils/fs';\nimport { createHash } from 'crypto';\nimport { extname } from 'path';\n\nexport enum CssUrl {\n inline = 'inline',\n none = 'none',\n}\n\nexport interface Result {\n css: string;\n warnings: string[];\n error?: string;\n}\n\nconst cachePath = findCacheDirectory({ name: 'ng-packagr-styles' }) || tmpdir();\nlet ngPackagrVersion: string | undefined;\ntry {\n ngPackagrVersion = require('../../../package.json').version;\n} catch {\n // dev path\n ngPackagrVersion = require('../../../../package.json').version;\n}\n\nexport class StylesheetProcessor {\n private browserslistData: string[];\n private postCssProcessor: ReturnType<typeof postcss>;\n\n constructor(\n private readonly basePath: string,\n private readonly cssUrl?: CssUrl,\n private readonly styleIncludePaths?: string[],\n ) {\n log.debug(`determine browserslist for ${this.basePath}`);\n this.browserslistData = browserslist(undefined, { path: this.basePath });\n this.postCssProcessor = this.createPostCssPlugins();\n }\n\n async process(filePath: string): Promise<string> {\n const content = await readFile(filePath, 'utf8');\n let key: string | undefined;\n\n if (!content.includes('@import') && !content.includes('@use')) {\n // No transitive deps, we can cache more aggressively.\n key = generateKey(content, this.browserslistData);\n const result = await readCacheEntry(cachePath, key);\n if (result) {\n result.warnings.forEach(msg => log.warn(msg));\n return result.css;\n }\n }\n\n // Render pre-processor language (sass, styl, less)\n const renderedCss = await this.renderCss(filePath, content);\n\n // We cannot cache CSS re-rendering phase, because a transitive dependency via (@import) can case different CSS output.\n // Example a change in a mixin or SCSS variable.\n if (!key) {\n key = generateKey(renderedCss, this.browserslistData);\n }\n\n const cachedResult = await readCacheEntry(cachePath, key);\n if (cachedResult) {\n cachedResult.warnings.forEach(msg => log.warn(msg));\n return cachedResult.css;\n }\n\n // Render postcss (autoprefixing and friends)\n const result = await this.postCssProcessor.process(renderedCss, {\n from: filePath,\n to: filePath.replace(extname(filePath), '.css'),\n });\n\n const warnings = result.warnings().map(w => w.toString());\n const { code, warnings: esBuildWarnings } = await transform(result.css, {\n loader: 'css',\n minify: true,\n sourcefile: filePath,\n });\n\n if (esBuildWarnings.length > 0) {\n warnings.push(...(await formatMessages(esBuildWarnings, { kind: 'warning' })));\n }\n\n // Add to cache\n await cacache.put(\n cachePath,\n key,\n JSON.stringify({\n css: code,\n warnings,\n }),\n );\n\n warnings.forEach(msg => log.warn(msg));\n\n return code;\n }\n\n private createPostCssPlugins(): ReturnType<typeof postcss> {\n const postCssPlugins = [];\n if (this.cssUrl !== CssUrl.none) {\n postCssPlugins.push(postcssUrl({ url: this.cssUrl }));\n }\n\n postCssPlugins.push(\n postcssPresetEnv({\n browsers: this.browserslistData,\n autoprefixer: true,\n stage: 3,\n }),\n );\n\n return postcss(postCssPlugins);\n }\n\n private async renderCss(filePath: string, css: string): Promise<string> {\n const ext = extname(filePath);\n\n switch (ext) {\n case '.sass':\n case '.scss': {\n /*\n * Please be aware of the few differences in behaviour https://github.com/sass/dart-sass/blob/master/README.md#behavioral-differences-from-ruby-sass\n * By default `npm install` will install sass.\n * To use node-sass you need to use:\n * Npm:\n * `npm install node-sass --save-dev`\n * Yarn:\n * `yarn add node-sass --dev`\n */\n let sassCompiler: any | undefined;\n try {\n sassCompiler = require('node-sass'); // Check if node-sass is explicitly included.\n } catch {\n sassCompiler = await import('sass');\n }\n\n return sassCompiler\n .renderSync({\n file: filePath,\n data: css,\n indentedSyntax: '.sass' === ext,\n importer: await import('node-sass-tilde-importer'),\n includePaths: this.styleIncludePaths,\n })\n .css.toString();\n }\n case '.less': {\n const { css: content } = await (\n await import('less')\n ).render(css, {\n filename: filePath,\n javascriptEnabled: true,\n paths: this.styleIncludePaths,\n });\n\n return content;\n }\n case '.styl':\n case '.stylus': {\n const stylus = await import('stylus');\n\n return (\n stylus(css)\n // add paths for resolve\n .set('paths', [this.basePath, '.', ...this.styleIncludePaths, 'node_modules'])\n // add support for resolving plugins from node_modules\n .set('filename', filePath)\n // turn on url resolver in stylus, same as flag --resolve-url\n .set('resolve url', true)\n .define('url', stylus.resolver(undefined))\n .render()\n );\n }\n case '.css':\n default:\n return css;\n }\n }\n}\n\nfunction generateKey(content: string, browserslistData: string[]): string {\n return createHash('sha1').update(ngPackagrVersion).update(content).update(browserslistData.join('')).digest('hex');\n}\n\nasync function readCacheEntry(cachePath: string, key: string): Promise<Result | undefined> {\n const entry = await cacache.get.info(cachePath, key);\n if (entry) {\n return JSON.parse(await readFile(entry.path, 'utf8'));\n }\n\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"stylesheet-processor.js","sourceRoot":"","sources":["../../../../src/lib/ivy/styles/stylesheet-processor.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAC7C,qDAAqD;AACrD,2BAA4B;AAC5B,mCAAmC;AACnC,qCAA8B;AAC9B,0CAA0C;AAC1C,uDAAuD;AACvD,uCAAuC;AACvC,uCAA0C;AAC1C,mCAAoC;AACpC,+BAA+B;AAC/B,qEAAiE;AAEjE,IAAY,MAGX;AAHD,WAAY,MAAM;IAChB,2BAAiB,CAAA;IACjB,uBAAa,CAAA;AACf,CAAC,EAHW,MAAM,GAAN,cAAM,KAAN,cAAM,QAGjB;AAQD,MAAM,SAAS,GAAG,kBAAkB,CAAC,EAAE,IAAI,EAAE,mBAAmB,EAAE,CAAC,IAAI,WAAM,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wF;YACxF,sFAAsF;YACtF,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;SAChC;QAED,IAAI,WAAW,KAAK,IAAI,EAAE;YACxB,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SAC5B;aAAM,IAAI,wBAAwB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE;YACpD,IAAI,WAAW,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,EAAE;gBAChD,2FAA2F;gBAC3F,0FAA0F;gBAC1F,OAAO,GAAG,KAAK,CAAC;aACjB;YAED,WAAW,CAAC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,CAAC;SACzC;KACF;IAED,OAAO,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC;AACtD,CAAC","sourcesContent":["import * as browserslist from 'browserslist';\nimport * as findCacheDirectory from 'find-cache-dir';\nimport { tmpdir } from 'os';\nimport * as cacache from 'cacache';\nimport postcss from 'postcss';\nimport * as postcssUrl from 'postcss-url';\nimport * as postcssPresetEnv from 'postcss-preset-env';\nimport * as log from '../../utils/log';\nimport { readFile } from '../../utils/fs';\nimport { createHash } from 'crypto';\nimport { extname } from 'path';\nimport { EsbuildExecutor } from '../../esbuild/esbuild-executor';\n\nexport enum CssUrl {\n inline = 'inline',\n none = 'none',\n}\n\nexport interface Result {\n css: string;\n warnings: string[];\n error?: string;\n}\n\nconst cachePath = findCacheDirectory({ name: 'ng-packagr-styles' }) || tmpdir();\nlet ngPackagrVersion: string | undefined;\ntry {\n ngPackagrVersion = require('../../../package.json').version;\n} catch {\n // dev path\n ngPackagrVersion = require('../../../../package.json').version;\n}\nexport class StylesheetProcessor {\n private targets: string[];\n private browserslistData: string[];\n private postCssProcessor: ReturnType<typeof postcss>;\n private esbuild = new EsbuildExecutor();\n\n constructor(\n private readonly basePath: string,\n private readonly cssUrl?: CssUrl,\n private readonly styleIncludePaths?: string[],\n ) {\n log.debug(`determine browserslist for ${this.basePath}`);\n\n // By default, browserslist defaults are too inclusive\n // https://github.com/browserslist/browserslist/blob/83764ea81ffaa39111c204b02c371afa44a4ff07/index.js#L516-L522\n\n // We change the default query to browsers that Angular support.\n // https://angular.io/guide/browser-support\n (browserslist.defaults as string[]) = [\n 'last 1 Chrome version',\n 'last 1 Firefox version',\n 'last 2 Edge major versions',\n 'last 2 Safari major versions',\n 'last 2 iOS major versions',\n 'Firefox ESR',\n ];\n\n this.browserslistData = browserslist(undefined, { path: this.basePath });\n this.targets = transformSupportedBrowsersToTargets(this.browserslistData);\n this.postCssProcessor = this.createPostCssPlugins();\n }\n\n async process(filePath: string): Promise<string> {\n const content = await readFile(filePath, 'utf8');\n let key: string | undefined;\n\n if (!content.includes('@import') && !content.includes('@use')) {\n // No transitive deps, we can cache more aggressively.\n key = generateKey(content, this.browserslistData);\n const result = await readCacheEntry(cachePath, key);\n if (result) {\n result.warnings.forEach(msg => log.warn(msg));\n return result.css;\n }\n }\n\n // Render pre-processor language (sass, styl, less)\n const renderedCss = await this.renderCss(filePath, content);\n\n // We cannot cache CSS re-rendering phase, because a transitive dependency via (@import) can case different CSS output.\n // Example a change in a mixin or SCSS variable.\n if (!key) {\n key = generateKey(renderedCss, this.browserslistData);\n }\n\n const cachedResult = await readCacheEntry(cachePath, key);\n if (cachedResult) {\n cachedResult.warnings.forEach(msg => log.warn(msg));\n return cachedResult.css;\n }\n\n // Render postcss (autoprefixing and friends)\n const result = await this.postCssProcessor.process(renderedCss, {\n from: filePath,\n to: filePath.replace(extname(filePath), '.css'),\n });\n\n const warnings = result.warnings().map(w => w.toString());\n const { code, warnings: esBuildWarnings } = await this.esbuild.transform(result.css, {\n loader: 'css',\n minify: true,\n target: this.targets,\n sourcefile: filePath,\n });\n\n if (esBuildWarnings.length > 0) {\n warnings.push(...(await this.esbuild.formatMessages(esBuildWarnings, { kind: 'warning' })));\n }\n\n // Add to cache\n await cacache.put(\n cachePath,\n key,\n JSON.stringify({\n css: code,\n warnings,\n }),\n );\n\n warnings.forEach(msg => log.warn(msg));\n\n return code;\n }\n\n private createPostCssPlugins(): ReturnType<typeof postcss> {\n const postCssPlugins = [];\n if (this.cssUrl !== CssUrl.none) {\n postCssPlugins.push(postcssUrl({ url: this.cssUrl }));\n }\n\n postCssPlugins.push(\n postcssPresetEnv({\n browsers: this.browserslistData,\n autoprefixer: true,\n stage: 3,\n }),\n );\n\n return postcss(postCssPlugins);\n }\n\n private async renderCss(filePath: string, css: string): Promise<string> {\n const ext = extname(filePath);\n\n switch (ext) {\n case '.sass':\n case '.scss': {\n /*\n * Please be aware of the few differences in behaviour https://github.com/sass/dart-sass/blob/master/README.md#behavioral-differences-from-ruby-sass\n * By default `npm install` will install sass.\n * To use node-sass you need to use:\n * Npm:\n * `npm install node-sass --save-dev`\n * Yarn:\n * `yarn add node-sass --dev`\n */\n let sassCompiler: any | undefined;\n try {\n sassCompiler = require('node-sass'); // Check if node-sass is explicitly included.\n } catch {\n sassCompiler = await import('sass');\n }\n\n return sassCompiler\n .renderSync({\n file: filePath,\n data: css,\n indentedSyntax: '.sass' === ext,\n importer: await import('node-sass-tilde-importer'),\n includePaths: this.styleIncludePaths,\n })\n .css.toString();\n }\n case '.less': {\n const { css: content } = await (\n await import('less')\n ).render(css, {\n filename: filePath,\n javascriptEnabled: true,\n paths: this.styleIncludePaths,\n math: 'always',\n });\n\n return content;\n }\n case '.styl':\n case '.stylus': {\n const stylus = await import('stylus');\n\n return (\n stylus(css)\n // add paths for resolve\n .set('paths', [this.basePath, '.', ...this.styleIncludePaths, 'node_modules'])\n // add support for resolving plugins from node_modules\n .set('filename', filePath)\n // turn on url resolver in stylus, same as flag --resolve-url\n .set('resolve url', true)\n .define('url', stylus.resolver(undefined))\n .render()\n );\n }\n case '.css':\n default:\n return css;\n }\n }\n}\n\nfunction generateKey(content: string, browserslistData: string[]): string {\n return createHash('sha1').update(ngPackagrVersion).update(content).update(browserslistData.join('')).digest('hex');\n}\n\nasync function readCacheEntry(cachePath: string, key: string): Promise<Result | undefined> {\n const entry = await cacache.get.info(cachePath, key);\n if (entry) {\n return JSON.parse(await readFile(entry.path, 'utf8'));\n }\n\n return undefined;\n}\n\nfunction transformSupportedBrowsersToTargets(supportedBrowsers: string[]): string[] {\n const transformed: string[] = [];\n\n // https://esbuild.github.io/api/#target\n const esBuildSupportedBrowsers = new Set(['safari', 'firefox', 'edge', 'chrome', 'ios']);\n\n for (const browser of supportedBrowsers) {\n let [browserName, version] = browser.split(' ');\n\n // browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios`\n if (browserName === 'ios_saf') {\n browserName = 'ios';\n // browserslist also uses ranges for iOS Safari versions but only the lowest is required\n // to perform minimum supported feature checks. esbuild also expects a single version.\n [version] = version.split('-');\n }\n\n if (browserName === 'ie') {\n transformed.push('edge12');\n } else if (esBuildSupportedBrowsers.has(browserName)) {\n if (browserName === 'safari' && version === 'TP') {\n // esbuild only supports numeric versions so `TP` is converted to a high number (999) since\n // a Technology Preview (TP) of Safari is assumed to support all currently known features.\n version = '999';\n }\n\n transformed.push(browserName + version);\n }\n }\n\n return transformed.length ? transformed : undefined;\n}\n"]}
@@ -5,13 +5,14 @@ const crypto_1 = require("crypto");
5
5
  const path = require("path");
6
6
  const postcss_1 = require("postcss");
7
7
  const postcssUrl = require("postcss-url");
8
- const esbuild_1 = require("esbuild");
9
8
  const worker_threads_1 = require("worker_threads");
10
9
  const postcssPresetEnv = require("postcss-preset-env");
10
+ const esbuild_executor_1 = require("../esbuild/esbuild-executor");
11
11
  const stylesheet_processor_1 = require("./stylesheet-processor");
12
12
  const fs_1 = require("../utils/fs");
13
13
  const ngPackagrVersion = require('../../package.json').version;
14
- async function processCss({ filePath, browserslistData, cssUrl, styleIncludePaths, basePath, cachePath, }) {
14
+ async function processCss({ filePath, browserslistData, cssUrl, styleIncludePaths, basePath, cachePath, targets, alwaysUseWasm, }) {
15
+ const esbuild = new esbuild_executor_1.EsbuildExecutor(alwaysUseWasm);
15
16
  const content = await fs_1.readFile(filePath, 'utf8');
16
17
  let key;
17
18
  if (!content.includes('@import') && !content.includes('@use')) {
@@ -36,13 +37,14 @@ async function processCss({ filePath, browserslistData, cssUrl, styleIncludePath
36
37
  // Render postcss (autoprefixing and friends)
37
38
  const result = await optimizeCss(filePath, renderedCss, browserslistData, cssUrl);
38
39
  const warnings = result.warnings().map(w => w.toString());
39
- const { code, warnings: esBuildWarnings } = await esbuild_1.transform(result.css, {
40
+ const { code, warnings: esBuildWarnings } = await esbuild.transform(result.css, {
40
41
  loader: 'css',
41
42
  minify: true,
43
+ target: targets,
42
44
  sourcefile: filePath,
43
45
  });
44
46
  if (esBuildWarnings.length > 0) {
45
- warnings.push(...(await esbuild_1.formatMessages(esBuildWarnings, { kind: 'warning' })));
47
+ warnings.push(...(await esbuild.formatMessages(esBuildWarnings, { kind: 'warning' })));
46
48
  }
47
49
  // Add to cache
48
50
  await cacache.put(cachePath, key, JSON.stringify({
@@ -90,6 +92,7 @@ async function renderCss(filePath, css, basePath, styleIncludePaths) {
90
92
  filename: filePath,
91
93
  javascriptEnabled: true,
92
94
  paths: styleIncludePaths,
95
+ math: 'always',
93
96
  });
94
97
  return content;
95
98
  }
@@ -1 +1 @@
1
- {"version":3,"file":"stylesheet-processor-worker.js","sourceRoot":"","sources":["../../../src/lib/styles/stylesheet-processor-worker.ts"],"names":[],"mappings":";;AAAA,mCAAmC;AACnC,mCAAoC;AACpC,6BAA6B;AAC7B,qCAA8C;AAC9C,0CAA0C;AAC1C,qCAAoD;AACpD,mDAA4C;AAC5C,uDAAuD;AAEvD,iEAA6E;AAC7E,oCAAuC;AAEvC,MAAM,gBAAgB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE/D,KAAK,UAAU,UAAU,CAAC,EACxB,QAAQ,EACR,gBAAgB,EAChB,MAAM,EACN,iBAAiB,EACjB,QAAQ,EACR,SAAS,GACK;IACd,MAAM,OAAO,GAAG,MAAM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S,WAAW,CAAC,OAAe,EAAE,gBAA0B;IAC9D,OAAO,mBAAU,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrH,CAAC;AAED,KAAK,UAAU,cAAc,CAAC,SAAiB,EAAE,GAAW;IAC1D,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IACrD,IAAI,KAAK,EAAE;QACT,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,aAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;KACvD;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,2BAAU,CAAC,EAAE,CAAC,SAAS,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,EAAE,EAAE;IACjE,IAAI;QACF,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,aAAa,CAAC,CAAC;QAC/C,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;KACjC;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KAC5C;YAAS;QACR,qCAAqC;QACrC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC1B,yBAAyB;QACzB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,EAAE,CAAC;KACd;AACH,CAAC,CAAC,CAAC","sourcesContent":["import * as cacache from 'cacache';\nimport { createHash } from 'crypto';\nimport * as path from 'path';\nimport postcss, { LazyResult } from 'postcss';\nimport * as postcssUrl from 'postcss-url';\nimport { formatMessages, transform } from 'esbuild';\nimport { parentPort } from 'worker_threads';\nimport * as postcssPresetEnv from 'postcss-preset-env';\n\nimport { CssUrl, WorkerOptions, WorkerResult } from './stylesheet-processor';\nimport { readFile } from '../utils/fs';\n\nconst ngPackagrVersion = require('../../package.json').version;\n\nasync function processCss({\n filePath,\n browserslistData,\n cssUrl,\n styleIncludePaths,\n basePath,\n cachePath,\n}: WorkerOptions): Promise<WorkerResult> {\n const content = await readFile(filePath, 'utf8');\n let key: string | undefined;\n\n if (!content.includes('@import') && !content.includes('@use')) {\n // No transitive deps, we can cache more aggressively.\n key = generateKey(content, browserslistData);\n const result = await readCacheEntry(cachePath, key);\n if (result) {\n return result;\n }\n }\n\n // Render pre-processor language (sass, styl, less)\n const renderedCss = await renderCss(filePath, content, basePath, styleIncludePaths);\n\n // We cannot cache CSS re-rendering phase, because a transitive dependency via (@import) can case different CSS output.\n // Example a change in a mixin or SCSS variable.\n if (!key) {\n key = generateKey(renderedCss, browserslistData);\n\n const cachedResult = await readCacheEntry(cachePath, key);\n if (cachedResult) {\n return cachedResult;\n }\n }\n\n // Render postcss (autoprefixing and friends)\n const result = await optimizeCss(filePath, renderedCss, browserslistData, cssUrl);\n const warnings = result.warnings().map(w => w.toString());\n\n const { code, warnings: esBuildWarnings } = await transform(result.css, {\n loader: 'css',\n minify: true,\n sourcefile: filePath,\n });\n\n if (esBuildWarnings.length > 0) {\n warnings.push(...(await formatMessages(esBuildWarnings, { kind: 'warning' })));\n }\n\n // Add to cache\n await cacache.put(\n cachePath,\n key,\n JSON.stringify({\n css: code,\n warnings,\n }),\n );\n\n return {\n css: code,\n warnings,\n };\n}\n\nasync function renderCss(\n filePath: string,\n css: string,\n basePath: string,\n styleIncludePaths?: string[],\n): Promise<string> {\n const ext = path.extname(filePath);\n\n switch (ext) {\n case '.sass':\n case '.scss': {\n /*\n * Please be aware of the few differences in behaviour https://github.com/sass/dart-sass/blob/master/README.md#behavioral-differences-from-ruby-sass\n * By default `npm install` will install sass.\n * To use node-sass you need to use:\n * Npm:\n * `npm install node-sass --save-dev`\n * Yarn:\n * `yarn add node-sass --dev`\n */\n let sassCompiler: any | undefined;\n try {\n sassCompiler = require('node-sass'); // Check if node-sass is explicitly included.\n } catch {\n sassCompiler = await import('sass');\n }\n\n return sassCompiler\n .renderSync({\n file: filePath,\n data: css,\n indentedSyntax: '.sass' === ext,\n importer: await import('node-sass-tilde-importer'),\n includePaths: styleIncludePaths,\n })\n .css.toString();\n }\n case '.less': {\n const { css: content } = await (\n await import('less')\n ).render(css, {\n filename: filePath,\n javascriptEnabled: true,\n paths: styleIncludePaths,\n });\n\n return content;\n }\n case '.styl':\n case '.stylus': {\n const stylus = await import('stylus');\n\n return (\n stylus(css)\n // add paths for resolve\n .set('paths', [basePath, '.', ...styleIncludePaths, 'node_modules'])\n // add support for resolving plugins from node_modules\n .set('filename', filePath)\n // turn on url resolver in stylus, same as flag --resolve-url\n .set('resolve url', true)\n .define('url', stylus.resolver(undefined))\n .render()\n );\n }\n case '.css':\n default:\n return css;\n }\n}\n\nfunction optimizeCss(filePath: string, css: string, browsers: string[], cssUrl?: CssUrl): LazyResult {\n const postCssPlugins = [];\n\n if (cssUrl !== CssUrl.none) {\n postCssPlugins.push(postcssUrl({ url: cssUrl }));\n }\n\n postCssPlugins.push(\n postcssPresetEnv({\n browsers,\n autoprefixer: true,\n stage: 3,\n }),\n );\n\n return postcss(postCssPlugins).process(css, {\n from: filePath,\n to: filePath.replace(path.extname(filePath), '.css'),\n });\n}\n\nfunction generateKey(content: string, browserslistData: string[]): string {\n return createHash('sha1').update(ngPackagrVersion).update(content).update(browserslistData.join('')).digest('hex');\n}\n\nasync function readCacheEntry(cachePath: string, key: string): Promise<WorkerResult | undefined> {\n const entry = await cacache.get.info(cachePath, key);\n if (entry) {\n return JSON.parse(await readFile(entry.path, 'utf8'));\n }\n\n return undefined;\n}\n\nparentPort.on('message', async ({ signal, port, workerOptions }) => {\n try {\n const result = await processCss(workerOptions);\n port.postMessage({ ...result });\n } catch (error) {\n port.postMessage({ error: error.message });\n } finally {\n // Change the value of signal[0] to 1\n Atomics.add(signal, 0, 1);\n // Unlock the main thread\n Atomics.notify(signal, 0);\n port.close();\n }\n});\n"]}
1
+ {"version":3,"file":"stylesheet-processor-worker.js","sourceRoot":"","sources":["../../../src/lib/styles/stylesheet-processor-worker.ts"],"names":[],"mappings":";;AAAA,mCAAmC;AACnC,mCAAoC;AACpC,6BAA6B;AAC7B,qCAA8C;AAC9C,0CAA0C;AAC1C,mDAA4C;AAC5C,uDAAuD;AACvD,kEAA8D;AAE9D,iEAA6E;AAC7E,oCAAuC;AAEvC,MAAM,gBAAgB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE/D,KAAK,UAAU,UAAU,CAAC,EACxB,QAAQ,EACR,gBAAgB,EAChB,MAAM,EACN,iBAAiB,EACjB,QAAQ,EACR,SAAS,EACT,OAAO,EACP,aAAa,GACC;IACd,MAAM,OAAO,GAAG,IAAI,kCAAe,CAAC,aAAa,CAAC,CAAC;IACnD,MAAM,OAAO,GAAG,MAAM,aAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IACjD,IAAI,GAAuB,CAAC;IAE5B,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;QAC7D,sDAAsD;QACtD,GAAG,GAAG,WAAW,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;QAC7C,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;QACpD,IAAI,MAAM,EAAE;YACV,OAAO,MAAM,CAAC;SACf;KACF;IAED,mDAAmD;IACnD,MAAM,WAAW,GAAG,MAAM,SAAS,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,CAAC,CAAC;IA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C,KAAK,CAAC,MAAM,aAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;KACvD;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,2BAAU,CAAC,EAAE,CAAC,SAAS,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,EAAE,EAAE;IACjE,IAAI;QACF,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,aAAa,CAAC,CAAC;QAC/C,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;KACjC;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;KAC5C;YAAS;QACR,qCAAqC;QACrC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC1B,yBAAyB;QACzB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,EAAE,CAAC;KACd;AACH,CAAC,CAAC,CAAC","sourcesContent":["import * as cacache from 'cacache';\nimport { createHash } from 'crypto';\nimport * as path from 'path';\nimport postcss, { LazyResult } from 'postcss';\nimport * as postcssUrl from 'postcss-url';\nimport { parentPort } from 'worker_threads';\nimport * as postcssPresetEnv from 'postcss-preset-env';\nimport { EsbuildExecutor } from '../esbuild/esbuild-executor';\n\nimport { CssUrl, WorkerOptions, WorkerResult } from './stylesheet-processor';\nimport { readFile } from '../utils/fs';\n\nconst ngPackagrVersion = require('../../package.json').version;\n\nasync function processCss({\n filePath,\n browserslistData,\n cssUrl,\n styleIncludePaths,\n basePath,\n cachePath,\n targets,\n alwaysUseWasm,\n}: WorkerOptions): Promise<WorkerResult> {\n const esbuild = new EsbuildExecutor(alwaysUseWasm);\n const content = await readFile(filePath, 'utf8');\n let key: string | undefined;\n\n if (!content.includes('@import') && !content.includes('@use')) {\n // No transitive deps, we can cache more aggressively.\n key = generateKey(content, browserslistData);\n const result = await readCacheEntry(cachePath, key);\n if (result) {\n return result;\n }\n }\n\n // Render pre-processor language (sass, styl, less)\n const renderedCss = await renderCss(filePath, content, basePath, styleIncludePaths);\n\n // We cannot cache CSS re-rendering phase, because a transitive dependency via (@import) can case different CSS output.\n // Example a change in a mixin or SCSS variable.\n if (!key) {\n key = generateKey(renderedCss, browserslistData);\n\n const cachedResult = await readCacheEntry(cachePath, key);\n if (cachedResult) {\n return cachedResult;\n }\n }\n\n // Render postcss (autoprefixing and friends)\n const result = await optimizeCss(filePath, renderedCss, browserslistData, cssUrl);\n const warnings = result.warnings().map(w => w.toString());\n\n const { code, warnings: esBuildWarnings } = await esbuild.transform(result.css, {\n loader: 'css',\n minify: true,\n target: targets,\n sourcefile: filePath,\n });\n\n if (esBuildWarnings.length > 0) {\n warnings.push(...(await esbuild.formatMessages(esBuildWarnings, { kind: 'warning' })));\n }\n\n // Add to cache\n await cacache.put(\n cachePath,\n key,\n JSON.stringify({\n css: code,\n warnings,\n }),\n );\n\n return {\n css: code,\n warnings,\n };\n}\n\nasync function renderCss(\n filePath: string,\n css: string,\n basePath: string,\n styleIncludePaths?: string[],\n): Promise<string> {\n const ext = path.extname(filePath);\n\n switch (ext) {\n case '.sass':\n case '.scss': {\n /*\n * Please be aware of the few differences in behaviour https://github.com/sass/dart-sass/blob/master/README.md#behavioral-differences-from-ruby-sass\n * By default `npm install` will install sass.\n * To use node-sass you need to use:\n * Npm:\n * `npm install node-sass --save-dev`\n * Yarn:\n * `yarn add node-sass --dev`\n */\n let sassCompiler: any | undefined;\n try {\n sassCompiler = require('node-sass'); // Check if node-sass is explicitly included.\n } catch {\n sassCompiler = await import('sass');\n }\n\n return sassCompiler\n .renderSync({\n file: filePath,\n data: css,\n indentedSyntax: '.sass' === ext,\n importer: await import('node-sass-tilde-importer'),\n includePaths: styleIncludePaths,\n })\n .css.toString();\n }\n case '.less': {\n const { css: content } = await (\n await import('less')\n ).render(css, {\n filename: filePath,\n javascriptEnabled: true,\n paths: styleIncludePaths,\n math: 'always',\n });\n\n return content;\n }\n case '.styl':\n case '.stylus': {\n const stylus = await import('stylus');\n\n return (\n stylus(css)\n // add paths for resolve\n .set('paths', [basePath, '.', ...styleIncludePaths, 'node_modules'])\n // add support for resolving plugins from node_modules\n .set('filename', filePath)\n // turn on url resolver in stylus, same as flag --resolve-url\n .set('resolve url', true)\n .define('url', stylus.resolver(undefined))\n .render()\n );\n }\n case '.css':\n default:\n return css;\n }\n}\n\nfunction optimizeCss(filePath: string, css: string, browsers: string[], cssUrl?: CssUrl): LazyResult {\n const postCssPlugins = [];\n\n if (cssUrl !== CssUrl.none) {\n postCssPlugins.push(postcssUrl({ url: cssUrl }));\n }\n\n postCssPlugins.push(\n postcssPresetEnv({\n browsers,\n autoprefixer: true,\n stage: 3,\n }),\n );\n\n return postcss(postCssPlugins).process(css, {\n from: filePath,\n to: filePath.replace(path.extname(filePath), '.css'),\n });\n}\n\nfunction generateKey(content: string, browserslistData: string[]): string {\n return createHash('sha1').update(ngPackagrVersion).update(content).update(browserslistData.join('')).digest('hex');\n}\n\nasync function readCacheEntry(cachePath: string, key: string): Promise<WorkerResult | undefined> {\n const entry = await cacache.get.info(cachePath, key);\n if (entry) {\n return JSON.parse(await readFile(entry.path, 'utf8'));\n }\n\n return undefined;\n}\n\nparentPort.on('message', async ({ signal, port, workerOptions }) => {\n try {\n const result = await processCss(workerOptions);\n port.postMessage({ ...result });\n } catch (error) {\n port.postMessage({ error: error.message });\n } finally {\n // Change the value of signal[0] to 1\n Atomics.add(signal, 0, 1);\n // Unlock the main thread\n Atomics.notify(signal, 0);\n port.close();\n }\n});\n"]}
@@ -5,10 +5,12 @@ export declare enum CssUrl {
5
5
  export interface WorkerOptions {
6
6
  filePath: string;
7
7
  basePath: string;
8
+ targets: string[];
8
9
  browserslistData: string[];
9
10
  cssUrl?: CssUrl;
10
11
  styleIncludePaths?: string[];
11
12
  cachePath: string;
13
+ alwaysUseWasm: boolean;
12
14
  }
13
15
  export interface WorkerResult {
14
16
  css: string;
@@ -22,6 +24,8 @@ export declare class StylesheetProcessor {
22
24
  private browserslistData;
23
25
  private worker;
24
26
  private readonly cachePath;
27
+ private targets;
28
+ private alwaysUseWasm;
25
29
  constructor(basePath: string, cssUrl?: CssUrl, styleIncludePaths?: string[]);
26
30
  process(filePath: string): any;
27
31
  }
@@ -7,6 +7,7 @@ const findCacheDirectory = require("find-cache-dir");
7
7
  const os_1 = require("os");
8
8
  const worker_threads_1 = require("worker_threads");
9
9
  const log = require("../utils/log");
10
+ const esbuild_executor_1 = require("../esbuild/esbuild-executor");
10
11
  var CssUrl;
11
12
  (function (CssUrl) {
12
13
  CssUrl["inline"] = "inline";
@@ -17,6 +18,7 @@ class StylesheetProcessor {
17
18
  this.basePath = basePath;
18
19
  this.cssUrl = cssUrl;
19
20
  this.styleIncludePaths = styleIncludePaths;
21
+ this.alwaysUseWasm = !esbuild_executor_1.EsbuildExecutor.hasNativeSupport();
20
22
  this.cachePath = findCacheDirectory({ name: 'ng-packagr-styles' }) || os_1.tmpdir();
21
23
  }
22
24
  process(filePath) {
@@ -25,7 +27,20 @@ class StylesheetProcessor {
25
27
  }
26
28
  if (!this.browserslistData) {
27
29
  log.debug(`determine browserslist for ${this.basePath}`);
30
+ // By default, browserslist defaults are too inclusive
31
+ // https://github.com/browserslist/browserslist/blob/83764ea81ffaa39111c204b02c371afa44a4ff07/index.js#L516-L522
32
+ // We change the default query to browsers that Angular support.
33
+ // https://angular.io/guide/browser-support
34
+ browserslist.defaults = [
35
+ 'last 1 Chrome version',
36
+ 'last 1 Firefox version',
37
+ 'last 2 Edge major versions',
38
+ 'last 2 Safari major versions',
39
+ 'last 2 iOS major versions',
40
+ 'Firefox ESR',
41
+ ];
28
42
  this.browserslistData = browserslist(undefined, { path: this.basePath });
43
+ this.targets = transformSupportedBrowsersToTargets(this.browserslistData);
29
44
  }
30
45
  const workerOptions = {
31
46
  filePath,
@@ -34,6 +49,8 @@ class StylesheetProcessor {
34
49
  styleIncludePaths: this.styleIncludePaths,
35
50
  browserslistData: this.browserslistData,
36
51
  cachePath: this.cachePath,
52
+ targets: this.targets,
53
+ alwaysUseWasm: this.alwaysUseWasm,
37
54
  };
38
55
  const ioChannel = new worker_threads_1.MessageChannel();
39
56
  try {
@@ -56,4 +73,31 @@ class StylesheetProcessor {
56
73
  }
57
74
  }
58
75
  exports.StylesheetProcessor = StylesheetProcessor;
76
+ function transformSupportedBrowsersToTargets(supportedBrowsers) {
77
+ const transformed = [];
78
+ // https://esbuild.github.io/api/#target
79
+ const esBuildSupportedBrowsers = new Set(['safari', 'firefox', 'edge', 'chrome', 'ios']);
80
+ for (const browser of supportedBrowsers) {
81
+ let [browserName, version] = browser.split(' ');
82
+ // browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios`
83
+ if (browserName === 'ios_saf') {
84
+ browserName = 'ios';
85
+ // browserslist also uses ranges for iOS Safari versions but only the lowest is required
86
+ // to perform minimum supported feature checks. esbuild also expects a single version.
87
+ [version] = version.split('-');
88
+ }
89
+ if (browserName === 'ie') {
90
+ transformed.push('edge12');
91
+ }
92
+ else if (esBuildSupportedBrowsers.has(browserName)) {
93
+ if (browserName === 'safari' && version === 'TP') {
94
+ // esbuild only supports numeric versions so `TP` is converted to a high number (999) since
95
+ // a Technology Preview (TP) of Safari is assumed to support all currently known features.
96
+ version = '999';
97
+ }
98
+ transformed.push(browserName + version);
99
+ }
100
+ }
101
+ return transformed.length ? transformed : undefined;
102
+ }
59
103
  //# sourceMappingURL=stylesheet-processor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stylesheet-processor.js","sourceRoot":"","sources":["../../../src/lib/styles/stylesheet-processor.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAC7C,+BAA4B;AAC5B,qDAAqD;AACrD,2BAA4B;AAC5B,mDAA8E;AAE9E,oCAAoC;AAEpC,IAAY,MAGX;AAHD,WA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AC,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,EAAE,aAAa,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;YAE7F,6BAA6B;YAC7B,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAE3B,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,qCAAoB,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;YAC/E,IAAI,KAAK,EAAE;gBACT,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;aACxB;YAED,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;YACvC,OAAO,GAAG,CAAC;SACZ;gBAAS;YACR,SAAS,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;YACxB,SAAS,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;YACxB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;SACrB;IACH,CAAC;CACF;AAtDD,kDAsDC","sourcesContent":["import * as browserslist from 'browserslist';\nimport { join } from 'path';\nimport * as findCacheDirectory from 'find-cache-dir';\nimport { tmpdir } from 'os';\nimport { MessageChannel, receiveMessageOnPort, Worker } from 'worker_threads';\n\nimport * as log from '../utils/log';\n\nexport enum CssUrl {\n inline = 'inline',\n none = 'none',\n}\nexport interface WorkerOptions {\n filePath: string;\n basePath: string;\n browserslistData: string[];\n cssUrl?: CssUrl;\n styleIncludePaths?: string[];\n cachePath: string;\n}\n\nexport interface WorkerResult {\n css: string;\n warnings: string[];\n error?: string;\n}\n\nexport class StylesheetProcessor {\n private browserslistData: string[] | undefined;\n private worker: Worker | undefined;\n private readonly cachePath: string;\n\n constructor(\n private readonly basePath: string,\n private readonly cssUrl?: CssUrl,\n private readonly styleIncludePaths?: string[],\n ) {\n this.cachePath = findCacheDirectory({ name: 'ng-packagr-styles' }) || tmpdir();\n }\n\n process(filePath: string) {\n if (!this.worker) {\n this.worker = new Worker(join(__dirname, './stylesheet-processor-worker.js'));\n }\n\n if (!this.browserslistData) {\n log.debug(`determine browserslist for ${this.basePath}`);\n this.browserslistData = browserslist(undefined, { path: this.basePath });\n }\n\n const workerOptions: WorkerOptions = {\n filePath,\n basePath: this.basePath,\n cssUrl: this.cssUrl,\n styleIncludePaths: this.styleIncludePaths,\n browserslistData: this.browserslistData,\n cachePath: this.cachePath,\n };\n\n const ioChannel = new MessageChannel();\n\n try {\n const signal = new Int32Array(new SharedArrayBuffer(4));\n this.worker.postMessage({ signal, port: ioChannel.port1, workerOptions }, [ioChannel.port1]);\n\n // Sleep until signal[0] is 0\n Atomics.wait(signal, 0, 0);\n\n const { css, warnings, error } = receiveMessageOnPort(ioChannel.port2).message;\n if (error) {\n throw new Error(error);\n }\n\n warnings.forEach(msg => log.warn(msg));\n return css;\n } finally {\n ioChannel.port1.close();\n ioChannel.port2.close();\n this.worker.unref();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"stylesheet-processor.js","sourceRoot":"","sources":["../../../src/lib/styles/stylesheet-processor.ts"],"names":[],"mappings":";;;AAAA,6CAA6C;AAC7C,+BAA4B;AAC5B,qDAAqD;AACrD,2BAA4B;AAC5B,mDAA8E;AAE9E,oCAAoC;AACpC,kEAA8D;AAE9D,IAAY,MAGX;AAHD,WAAY,MAAM;IAChB,2BAAiB,CAAA;IACjB,uBAAa,CAAA;AACf,CAAC,EAHW,MAAM,GAAN,cAAM,KAAN,cAAM,QAGjB;AAkBD,MAAa,mBAAmB;IAO9B,YACmB,QAAgB,EAChB,MAAe,EACf,iBAA4B;QAF5B,aAAQ,GAAR,QAAQ,CAAQ;QAChB,WAAM,GAAN,MAAM,CAAS;QACf,sBAAiB,GAAjB,iBAAiB,CAAW;QALvC,kBAAa,GAAG,CAAC,kCAAe,CAAC,gBAAgB,EAAE,CAAC;QAO1D,IAAI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ACxF,sFAAsF;YACtF,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;SAChC;QAED,IAAI,WAAW,KAAK,IAAI,EAAE;YACxB,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SAC5B;aAAM,IAAI,wBAAwB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE;YACpD,IAAI,WAAW,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,EAAE;gBAChD,2FAA2F;gBAC3F,0FAA0F;gBAC1F,OAAO,GAAG,KAAK,CAAC;aACjB;YAED,WAAW,CAAC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,CAAC;SACzC;KACF;IAED,OAAO,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC;AACtD,CAAC","sourcesContent":["import * as browserslist from 'browserslist';\nimport { join } from 'path';\nimport * as findCacheDirectory from 'find-cache-dir';\nimport { tmpdir } from 'os';\nimport { MessageChannel, receiveMessageOnPort, Worker } from 'worker_threads';\n\nimport * as log from '../utils/log';\nimport { EsbuildExecutor } from '../esbuild/esbuild-executor';\n\nexport enum CssUrl {\n inline = 'inline',\n none = 'none',\n}\nexport interface WorkerOptions {\n filePath: string;\n basePath: string;\n targets: string[];\n browserslistData: string[];\n cssUrl?: CssUrl;\n styleIncludePaths?: string[];\n cachePath: string;\n alwaysUseWasm: boolean;\n}\n\nexport interface WorkerResult {\n css: string;\n warnings: string[];\n error?: string;\n}\n\nexport class StylesheetProcessor {\n private browserslistData: string[] | undefined;\n private worker: Worker | undefined;\n private readonly cachePath: string;\n private targets: string[];\n private alwaysUseWasm = !EsbuildExecutor.hasNativeSupport();\n\n constructor(\n private readonly basePath: string,\n private readonly cssUrl?: CssUrl,\n private readonly styleIncludePaths?: string[],\n ) {\n this.cachePath = findCacheDirectory({ name: 'ng-packagr-styles' }) || tmpdir();\n }\n\n process(filePath: string) {\n if (!this.worker) {\n this.worker = new Worker(join(__dirname, './stylesheet-processor-worker.js'));\n }\n\n if (!this.browserslistData) {\n log.debug(`determine browserslist for ${this.basePath}`);\n // By default, browserslist defaults are too inclusive\n // https://github.com/browserslist/browserslist/blob/83764ea81ffaa39111c204b02c371afa44a4ff07/index.js#L516-L522\n\n // We change the default query to browsers that Angular support.\n // https://angular.io/guide/browser-support\n (browserslist.defaults as string[]) = [\n 'last 1 Chrome version',\n 'last 1 Firefox version',\n 'last 2 Edge major versions',\n 'last 2 Safari major versions',\n 'last 2 iOS major versions',\n 'Firefox ESR',\n ];\n\n this.browserslistData = browserslist(undefined, { path: this.basePath });\n this.targets = transformSupportedBrowsersToTargets(this.browserslistData);\n }\n\n const workerOptions: WorkerOptions = {\n filePath,\n basePath: this.basePath,\n cssUrl: this.cssUrl,\n styleIncludePaths: this.styleIncludePaths,\n browserslistData: this.browserslistData,\n cachePath: this.cachePath,\n targets: this.targets,\n alwaysUseWasm: this.alwaysUseWasm,\n };\n\n const ioChannel = new MessageChannel();\n\n try {\n const signal = new Int32Array(new SharedArrayBuffer(4));\n this.worker.postMessage({ signal, port: ioChannel.port1, workerOptions }, [ioChannel.port1]);\n\n // Sleep until signal[0] is 0\n Atomics.wait(signal, 0, 0);\n\n const { css, warnings, error } = receiveMessageOnPort(ioChannel.port2).message;\n if (error) {\n throw new Error(error);\n }\n\n warnings.forEach(msg => log.warn(msg));\n return css;\n } finally {\n ioChannel.port1.close();\n ioChannel.port2.close();\n this.worker.unref();\n }\n }\n}\n\nfunction transformSupportedBrowsersToTargets(supportedBrowsers: string[]): string[] {\n const transformed: string[] = [];\n\n // https://esbuild.github.io/api/#target\n const esBuildSupportedBrowsers = new Set(['safari', 'firefox', 'edge', 'chrome', 'ios']);\n\n for (const browser of supportedBrowsers) {\n let [browserName, version] = browser.split(' ');\n\n // browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios`\n if (browserName === 'ios_saf') {\n browserName = 'ios';\n // browserslist also uses ranges for iOS Safari versions but only the lowest is required\n // to perform minimum supported feature checks. esbuild also expects a single version.\n [version] = version.split('-');\n }\n\n if (browserName === 'ie') {\n transformed.push('edge12');\n } else if (esBuildSupportedBrowsers.has(browserName)) {\n if (browserName === 'safari' && version === 'TP') {\n // esbuild only supports numeric versions so `TP` is converted to a high number (999) since\n // a Technology Preview (TP) of Safari is assumed to support all currently known features.\n version = '999';\n }\n\n transformed.push(browserName + version);\n }\n }\n\n return transformed.length ? transformed : undefined;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ng-packagr",
3
- "version": "12.2.1",
3
+ "version": "12.2.5",
4
4
  "description": "Compile and package Angular libraries in Angular Package Format (APF)",
5
5
  "keywords": [
6
6
  "apf",
@@ -39,7 +39,7 @@
39
39
  "chokidar": "^3.5.1",
40
40
  "commander": "^8.0.0",
41
41
  "dependency-graph": "^0.11.0",
42
- "esbuild": "^0.12.15",
42
+ "esbuild-wasm": "^0.12.15",
43
43
  "find-cache-dir": "^3.3.1",
44
44
  "glob": "^7.1.6",
45
45
  "injection-js": "^2.4.0",
@@ -56,6 +56,9 @@
56
56
  "sass": "^1.32.8",
57
57
  "stylus": "^0.54.8"
58
58
  },
59
+ "optionalDependencies": {
60
+ "esbuild": "^0.12.15"
61
+ },
59
62
  "peerDependencies": {
60
63
  "@angular/compiler-cli": "^12.0.0 || ^12.2.0-next.0",
61
64
  "tslib": "^2.1.0",