forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sass-plugin.ts
241 lines (210 loc) · 7.84 KB
/
sass-plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import type { OnLoadResult, PartialMessage, Plugin, PluginBuild, ResolveResult } from 'esbuild';
import assert from 'node:assert';
import { readFile } from 'node:fs/promises';
import { dirname, extname, join, relative } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type { CompileResult, Exception, Syntax } from 'sass';
import type {
FileImporterWithRequestContextOptions,
SassWorkerImplementation,
} from '../../../sass/sass-service';
import type { LoadResultCache } from '../load-result-cache';
export interface SassPluginOptions {
sourcemap: boolean;
loadPaths?: string[];
inlineComponentData?: Record<string, string>;
}
let sassWorkerPool: SassWorkerImplementation | undefined;
function isSassException(error: unknown): error is Exception {
return !!error && typeof error === 'object' && 'sassMessage' in error;
}
export function shutdownSassWorkerPool(): void {
sassWorkerPool?.close();
sassWorkerPool = undefined;
}
export function createSassPlugin(options: SassPluginOptions, cache?: LoadResultCache): Plugin {
return {
name: 'angular-sass',
setup(build: PluginBuild): void {
const resolveUrl = async (url: string, previousResolvedModules?: Set<string>) => {
let result = await build.resolve(url, {
kind: 'import-rule',
// This should ideally be the directory of the importer file from Sass
// but that is not currently available from the Sass importer API.
resolveDir: build.initialOptions.absWorkingDir,
});
// Workaround to support Yarn PnP without access to the importer file from Sass
if (!result.path && previousResolvedModules?.size) {
for (const previous of previousResolvedModules) {
result = await build.resolve(url, {
kind: 'import-rule',
resolveDir: previous,
});
if (result.path) {
break;
}
}
}
return result;
};
build.onLoad({ filter: /^s[ac]ss;/, namespace: 'angular:styles/component' }, async (args) => {
const data = options.inlineComponentData?.[args.path];
assert(
typeof data === 'string',
`component style name should always be found [${args.path}]`,
);
let result = cache?.get(data);
if (result === undefined) {
const [language, , filePath] = args.path.split(';', 3);
const syntax = language === 'sass' ? 'indented' : 'scss';
result = await compileString(data, filePath, syntax, options, resolveUrl);
if (result.errors === undefined) {
// Cache the result if there were no errors
await cache?.put(data, result);
}
}
return result;
});
build.onLoad({ filter: /\.s[ac]ss$/ }, async (args) => {
let result = cache?.get(args.path);
if (result === undefined) {
const data = await readFile(args.path, 'utf-8');
const syntax = extname(args.path).toLowerCase() === '.sass' ? 'indented' : 'scss';
result = await compileString(data, args.path, syntax, options, resolveUrl);
if (result.errors === undefined) {
// Cache the result if there were no errors
await cache?.put(args.path, result);
}
}
return result;
});
},
};
}
async function compileString(
data: string,
filePath: string,
syntax: Syntax,
options: SassPluginOptions,
resolveUrl: (url: string, previousResolvedModules?: Set<string>) => Promise<ResolveResult>,
): Promise<OnLoadResult> {
// Lazily load Sass when a Sass file is found
if (sassWorkerPool === undefined) {
const sassService = await import('../../../sass/sass-service');
sassWorkerPool = new sassService.SassWorkerImplementation(true);
}
const warnings: PartialMessage[] = [];
try {
const { css, sourceMap, loadedUrls } = await sassWorkerPool.compileStringAsync(data, {
url: pathToFileURL(filePath),
style: 'expanded',
syntax,
loadPaths: options.loadPaths,
sourceMap: options.sourcemap,
sourceMapIncludeSources: options.sourcemap,
quietDeps: true,
importers: [
{
findFileUrl: async (
url,
{ previousResolvedModules }: FileImporterWithRequestContextOptions,
): Promise<URL | null> => {
let result = await resolveUrl(url);
if (result.path) {
return pathToFileURL(result.path);
}
// Check for package deep imports
const parts = url.split('/');
const hasScope = parts.length >= 2 && parts[0].startsWith('@');
const [nameOrScope, nameOrFirstPath, ...pathPart] = parts;
const packageName = hasScope ? `${nameOrScope}/${nameOrFirstPath}` : nameOrScope;
let packageResult = await resolveUrl(packageName + '/package.json');
if (packageResult.path) {
return pathToFileURL(
join(
dirname(packageResult.path),
!hasScope && nameOrFirstPath ? nameOrFirstPath : '',
...pathPart,
),
);
}
// Check with Yarn PnP workaround using previous resolved modules.
// This is done last to avoid a performance penalty for common cases.
result = await resolveUrl(url, previousResolvedModules);
if (result.path) {
return pathToFileURL(result.path);
}
packageResult = await resolveUrl(
packageName + '/package.json',
previousResolvedModules,
);
if (packageResult.path) {
return pathToFileURL(
join(
dirname(packageResult.path),
!hasScope && nameOrFirstPath ? nameOrFirstPath : '',
...pathPart,
),
);
}
// Not found
return null;
},
},
],
logger: {
warn: (text, { deprecation, span }) => {
warnings.push({
text: deprecation ? 'Deprecation' : text,
location: span && {
file: span.url && fileURLToPath(span.url),
lineText: span.context,
// Sass line numbers are 0-based while esbuild's are 1-based
line: span.start.line + 1,
column: span.start.column,
},
notes: deprecation ? [{ text }] : undefined,
});
},
},
});
return {
loader: 'css',
contents: sourceMap ? `${css}\n${sourceMapToUrlComment(sourceMap, dirname(filePath))}` : css,
watchFiles: loadedUrls.map((url) => fileURLToPath(url)),
warnings,
};
} catch (error) {
if (isSassException(error)) {
const file = error.span.url ? fileURLToPath(error.span.url) : undefined;
return {
loader: 'css',
errors: [
{
text: error.message,
},
],
warnings,
watchFiles: file ? [file] : undefined,
};
}
throw error;
}
}
function sourceMapToUrlComment(
sourceMap: Exclude<CompileResult['sourceMap'], undefined>,
root: string,
): string {
// Remove `file` protocol from all sourcemap sources and adjust to be relative to the input file.
// This allows esbuild to correctly process the paths.
sourceMap.sources = sourceMap.sources.map((source) => relative(root, fileURLToPath(source)));
const urlSourceMap = Buffer.from(JSON.stringify(sourceMap), 'utf-8').toString('base64');
return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${urlSourceMap} */`;
}