-
Notifications
You must be signed in to change notification settings - Fork 360
/
compile.dart
274 lines (256 loc) · 10.7 KB
/
compile.dart
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright 2021 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:js/js.dart';
import 'package:node_interop/js.dart';
import 'package:node_interop/util.dart' hide futureToPromise;
import 'package:term_glyph/term_glyph.dart' as glyph;
import 'package:tuple/tuple.dart';
import '../../sass.dart';
import '../ast/sass.dart';
import '../callable.dart';
import '../exception.dart';
import '../importer/no_op.dart';
import '../importer/node_to_dart/async.dart';
import '../importer/node_to_dart/async_file.dart';
import '../importer/node_to_dart/file.dart';
import '../importer/node_to_dart/sync.dart';
import '../io.dart';
import '../logger/node_to_dart.dart';
import '../parse/scss.dart';
import '../util/nullable.dart';
import '../utils.dart';
import 'compile_options.dart';
import 'compile_result.dart';
import 'exception.dart';
import 'importer.dart';
import 'utils.dart';
/// The JS API `compile` function.
///
/// See https://github.com/sass/sass/spec/tree/main/js-api/compile.d.ts for
/// details.
NodeCompileResult compile(String path, [CompileOptions? options]) {
var color = options?.alertColor ?? hasTerminal;
var ascii = options?.alertAscii ?? glyph.ascii;
try {
var result = compileToResult(path,
color: color,
loadPaths: options?.loadPaths,
quietDeps: options?.quietDeps ?? false,
style: _parseOutputStyle(options?.style),
verbose: options?.verbose ?? false,
sourceMap: options?.sourceMap ?? false,
logger: NodeToDartLogger(options?.logger, Logger.stderr(color: color),
ascii: ascii),
importers: options?.importers?.map(_parseImporter),
functions: _parseFunctions(options?.functions).cast());
return _convertResult(result,
includeSourceContents: options?.sourceMapIncludeSources ?? false);
} on SassException catch (error, stackTrace) {
throwNodeException(error, color: color, ascii: ascii, trace: stackTrace);
}
}
/// The JS API `compileString` function.
///
/// See https://github.com/sass/sass/spec/tree/main/js-api/compile.d.ts for
/// details.
NodeCompileResult compileString(String text, [CompileStringOptions? options]) {
var color = options?.alertColor ?? hasTerminal;
var ascii = options?.alertAscii ?? glyph.ascii;
try {
var result = compileStringToResult(text,
syntax: parseSyntax(options?.syntax),
url: options?.url.andThen(jsToDartUrl),
color: color,
loadPaths: options?.loadPaths,
quietDeps: options?.quietDeps ?? false,
style: _parseOutputStyle(options?.style),
verbose: options?.verbose ?? false,
sourceMap: options?.sourceMap ?? false,
logger: NodeToDartLogger(options?.logger, Logger.stderr(color: color),
ascii: ascii),
importers: options?.importers?.map(_parseImporter),
importer: options?.importer.andThen(_parseImporter) ??
(options?.url == null ? NoOpImporter() : null),
functions: _parseFunctions(options?.functions).cast());
return _convertResult(result,
includeSourceContents: options?.sourceMapIncludeSources ?? false);
} on SassException catch (error, stackTrace) {
throwNodeException(error, color: color, ascii: ascii, trace: stackTrace);
}
}
/// The JS API `compile` function.
///
/// See https://github.com/sass/sass/spec/tree/main/js-api/compile.d.ts for
/// details.
Promise compileAsync(String path, [CompileOptions? options]) {
var color = options?.alertColor ?? hasTerminal;
var ascii = options?.alertAscii ?? glyph.ascii;
return _wrapAsyncSassExceptions(futureToPromise(() async {
var result = await compileToResultAsync(path,
color: color,
loadPaths: options?.loadPaths,
quietDeps: options?.quietDeps ?? false,
style: _parseOutputStyle(options?.style),
verbose: options?.verbose ?? false,
sourceMap: options?.sourceMap ?? false,
logger: NodeToDartLogger(options?.logger, Logger.stderr(color: color),
ascii: ascii),
importers: options?.importers
?.map((importer) => _parseAsyncImporter(importer)),
functions: _parseFunctions(options?.functions, asynch: true));
return _convertResult(result,
includeSourceContents: options?.sourceMapIncludeSources ?? false);
}()), color: color, ascii: ascii);
}
/// The JS API `compileString` function.
///
/// See https://github.com/sass/sass/spec/tree/main/js-api/compile.d.ts for
/// details.
Promise compileStringAsync(String text, [CompileStringOptions? options]) {
var color = options?.alertColor ?? hasTerminal;
var ascii = options?.alertAscii ?? glyph.ascii;
return _wrapAsyncSassExceptions(futureToPromise(() async {
var result = await compileStringToResultAsync(text,
syntax: parseSyntax(options?.syntax),
url: options?.url.andThen(jsToDartUrl),
color: color,
loadPaths: options?.loadPaths,
quietDeps: options?.quietDeps ?? false,
style: _parseOutputStyle(options?.style),
verbose: options?.verbose ?? false,
sourceMap: options?.sourceMap ?? false,
logger: NodeToDartLogger(options?.logger, Logger.stderr(color: color),
ascii: ascii),
importers: options?.importers
?.map((importer) => _parseAsyncImporter(importer)),
importer: options?.importer
.andThen((importer) => _parseAsyncImporter(importer)) ??
(options?.url == null ? NoOpImporter() : null),
functions: _parseFunctions(options?.functions, asynch: true));
return _convertResult(result,
includeSourceContents: options?.sourceMapIncludeSources ?? false);
}()), color: color, ascii: ascii);
}
/// Converts a Dart [CompileResult] into a JS API [NodeCompileResult].
NodeCompileResult _convertResult(CompileResult result,
{required bool includeSourceContents}) {
var sourceMap =
result.sourceMap?.toJson(includeSourceContents: includeSourceContents);
if (sourceMap is Map<String, dynamic> && !sourceMap.containsKey('sources')) {
// Dart's source map library can omit the sources key, but JS's type
// declaration doesn't allow that.
sourceMap['sources'] = <String>[];
}
var loadedUrls = toJSArray(result.loadedUrls.map(dartToJSUrl));
return sourceMap == null
// The JS API tests expects *no* source map here, not a null source map.
? NodeCompileResult(css: result.css, loadedUrls: loadedUrls)
: NodeCompileResult(
css: result.css, loadedUrls: loadedUrls, sourceMap: jsify(sourceMap));
}
/// Catches `SassException`s thrown by [promise] and rethrows them as JS API
/// exceptions.
Promise _wrapAsyncSassExceptions(Promise promise,
{required bool color, required bool ascii}) =>
promise.then(
null,
allowInterop((error) => error is SassException
? throwNodeException(error, color: color, ascii: ascii)
: jsThrow(error as Object)));
/// Converts an output style string to an instance of [OutputStyle].
OutputStyle _parseOutputStyle(String? style) {
if (style == null || style == 'expanded') return OutputStyle.expanded;
if (style == 'compressed') return OutputStyle.compressed;
jsThrow(JsError('Unknown output style "$style".'));
}
/// Converts [importer] into an [AsyncImporter] that can be used with
/// [compileAsync] or [compileStringAsync].
AsyncImporter _parseAsyncImporter(Object? importer) {
if (importer == null) jsThrow(JsError("Importers may not be null."));
importer as NodeImporter;
var findFileUrl = importer.findFileUrl;
var canonicalize = importer.canonicalize;
var load = importer.load;
if (findFileUrl == null) {
if (canonicalize == null || load == null) {
jsThrow(JsError(
"An importer must have either canonicalize and load methods, or a "
"findFileUrl method."));
}
return NodeToDartAsyncImporter(canonicalize, load);
} else if (canonicalize != null || load != null) {
jsThrow(JsError("An importer may not have a findFileUrl method as well as "
"canonicalize and load methods."));
} else {
return NodeToDartAsyncFileImporter(findFileUrl);
}
}
/// Converts [importer] into a synchronous [Importer].
Importer _parseImporter(Object? importer) {
if (importer == null) jsThrow(JsError("Importers may not be null."));
importer as NodeImporter;
var findFileUrl = importer.findFileUrl;
var canonicalize = importer.canonicalize;
var load = importer.load;
if (findFileUrl == null) {
if (canonicalize == null || load == null) {
jsThrow(JsError(
"An importer must have either canonicalize and load methods, or a "
"findFileUrl method."));
}
return NodeToDartImporter(canonicalize, load);
} else if (canonicalize != null || load != null) {
jsThrow(JsError("An importer may not have a findFileUrl method as well as "
"canonicalize and load methods."));
} else {
return NodeToDartFileImporter(findFileUrl);
}
}
/// Parses `functions` from [record] into a list of [Callable]s or
/// [AsyncCallable]s.
///
/// This is typed to always return [AsyncCallable], but in practice it will
/// return a `List<Callable>` if [asynch] is `false`.
List<AsyncCallable> _parseFunctions(Object? functions, {bool asynch = false}) {
if (functions == null) return const [];
var result = <AsyncCallable>[];
jsForEach(functions, (signature, callback) {
Tuple2<String, ArgumentDeclaration> tuple;
try {
tuple = ScssParser(signature).parseSignature();
} on SassFormatException catch (error, stackTrace) {
throwWithTrace(
SassFormatException(
'Invalid signature "$signature": ${error.message}', error.span),
stackTrace);
}
if (!asynch) {
result.add(BuiltInCallable.parsed(tuple.item1, tuple.item2, (arguments) {
var result = (callback as Function)(toJSArray(arguments));
if (result is Value) return result;
if (isPromise(result)) {
throw 'Invalid return value for custom function '
'"${tuple.item1}":\n'
'Promises may only be returned for sass.compileAsync() and '
'sass.compileStringAsync().';
} else {
throw 'Invalid return value for custom function '
'"${tuple.item1}": $result is not a sass.Value.';
}
}));
} else {
result.add(AsyncBuiltInCallable.parsed(tuple.item1, tuple.item2,
(arguments) async {
var result = (callback as Function)(toJSArray(arguments));
if (isPromise(result)) {
result = await promiseToFuture<Object>(result as Promise);
}
if (result is Value) return result;
throw 'Invalid return value for custom function '
'"${tuple.item1}": $result is not a sass.Value.';
}));
}
});
return result;
}