-
Notifications
You must be signed in to change notification settings - Fork 362
/
Copy pathutils.dart
261 lines (215 loc) · 8.47 KB
/
utils.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
// Copyright 2017 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 'dart:js_util';
import 'dart:typed_data';
import 'package:node_interop/node.dart' hide module;
import 'package:js/js.dart';
import 'package:js/js_util.dart';
import '../syntax.dart';
import '../utils.dart';
import '../value.dart';
import 'array.dart';
import 'function.dart';
import 'module.dart';
import 'reflection.dart';
import 'url.dart';
/// Throws [error] like JS would, without any Dart wrappers.
Never jsThrow(Object error) => _jsThrow.call(error) as Never;
final _jsThrow = JSFunction("error", "throw error;");
/// Returns whether or not [value] is the JS `undefined` value.
bool isUndefined(Object? value) => _isUndefined.call(value) as bool;
final _isUndefined = JSFunction("value", "return value === undefined;");
/// Returns whether or not [value] is the JS `null` value.
bool isNull(Object? value) => _isNull.call(value) as bool;
final _isNull = JSFunction("value", "return value === null;");
@JS("Error")
external JSClass get jsErrorClass;
/// Returns whether [value] is a JS Error object.
bool isJSError(Object value) => instanceof(value, jsErrorClass);
/// Attaches [trace] to [error] as its stack trace.
void attachJsStack(JsError error, StackTrace trace) {
// Stack traces in v8 contain the error message itself as well as the stack
// information, so we trim that out if it exists so we don't double-print it.
var traceString = trace.toString();
var firstRealLine = traceString.indexOf('\n at');
if (firstRealLine != -1) {
// +1 to account for the newline before the first line.
traceString = traceString.substring(firstRealLine + 1);
}
setProperty(error, 'stack', "Error: ${error.message}\n$traceString");
}
/// Invokes [function] with [thisArg] as `this`.
Object? call2(JSFunction function, Object thisArg, Object arg1, Object arg2) =>
function.apply(thisArg, [arg1, arg2]);
/// Invokes [function] with [thisArg] as `this`.
Object? call3(JSFunction function, Object thisArg, Object arg1, Object arg2,
Object arg3) =>
function.apply(thisArg, [arg1, arg2, arg3]);
@JS("Object.keys")
external List<String> _keys(Object? object);
/// Invokes [callback] for each key/value pair in [object].
void jsForEach(Object object, void callback(String key, Object? value)) {
for (var key in _keys(object)) {
callback(key, getProperty(object, key));
}
}
/// Evaluates [js] in a function context.
///
/// If [js] includes a `return` statement, returns that result. Otherwise
/// returns `null`.
Object? jsEval(String js) => JSFunction('', js).call();
/// Returns whether the [object] is a JS `string`.
bool isJsString(Object? object) => _jsTypeOf(object) == 'string';
/// Returns the [object]'s `typeof` according to the JS engine.
String _jsTypeOf(Object? object) =>
JSFunction("value", "return typeof value").call(object) as String;
/// Returns `typeof value` if [value] is a native type, otherwise returns the
/// [value]'s JS class name.
String jsType(Object? value) {
var typeOf = _jsTypeOf(value);
return typeOf != 'object' ? typeOf : JSFunction('value', '''
if (value && value.constructor && value.constructor.name) {
return value.constructor.name;
}
return "object";
''').call(value) as String;
}
@JS("Object.defineProperty")
external void _defineProperty(
Object object, String name, _PropertyDescriptor prototype);
@JS()
@anonymous
class _PropertyDescriptor {
external Object get value;
external Function get get;
external bool get enumerable;
external factory _PropertyDescriptor(
{Object? value, Function? get, bool? enumerable});
}
/// Defines a JS getter on [object] named [name].
///
/// If [get] is passed, the getter invokes it with a `self` argument. Otherwise,
/// the getter just returns [value].
void defineGetter(Object object, String name, {Object? value, Function? get}) {
_defineProperty(
object,
name,
get == null
? _PropertyDescriptor(value: value, enumerable: false)
: _PropertyDescriptor(
get: allowInteropCaptureThis(get), enumerable: false));
}
/// Like [allowInterop], but gives the function a [name] so it's more ergonomic
/// when debugging.
T allowInteropNamed<T extends Function>(String name, T function) {
function = allowInterop(function);
defineGetter(function, 'name', value: name);
_hideDartProperties(function);
return function;
}
/// Like [allowInteropCaptureThis], but gives the function a [name] so it's more
/// ergonomic when debugging.
Function allowInteropCaptureThisNamed(String name, Function function) {
function = allowInteropCaptureThis(function);
defineGetter(function, 'name', value: name);
_hideDartProperties(function);
return function;
}
@JS("Object.getOwnPropertyNames")
external List<Object?> _getOwnPropertyNames(Object object);
/// Hide Dart-internal properties on [object].
///
/// Dart sometimes adds weird properties to objects that show up in
/// `utils.inspect()` or `console.log()`. This hides them by marking them as
/// non-enumerable.
void _hideDartProperties(Object object) {
for (var name in _getOwnPropertyNames(object).cast<String>()) {
if (name.startsWith('_')) {
defineGetter(object, name, value: getProperty(object, name));
}
}
}
/// Returns whether [value] is truthy according to JavaScript.
bool isTruthy(Object? value) => value != false && value != null;
@JS('Promise')
external JSClass get _promiseClass;
/// Returns whether [object] is a `Promise`.
bool isPromise(Object? object) =>
object != null && instanceof(object, _promiseClass);
/// Like [futureToPromise] from `node_interop`, but stores the stack trace for
/// errors using [throwWithTrace].
Promise futureToPromise(Future<Object?> future) => Promise(allowInterop(
(void Function(Object?) resolve, void Function(Object?) reject) {
future.then((result) => resolve(result),
onError: (Object error, StackTrace stackTrace) {
attachTrace(error, stackTrace);
reject(error);
});
}));
@JS('URL')
external JSClass get _urlClass;
/// Returns whether [object] is a JavaScript `URL`.
bool isJSUrl(Object? object) => object != null && instanceof(object, _urlClass);
@JS('Buffer.from')
external Uint8List _buffer(String text, String encoding);
/// Encodes [text] as a UTF-8 byte buffer.
///
/// We could do this using Dart's native UTF-8 support, but it's much less
/// efficient in Node.
Uint8List utf8Encode(String text) => _buffer(text, 'utf8');
/// Converts a standard JS `URL` object to a Dart [Uri] object.
Uri jsToDartUrl(JSUrl url) => Uri.parse(url.toString());
/// Converts a Dart [Uri] object to a standard JS `URL` object.
JSUrl dartToJSUrl(Uri url) => JSUrl(url.toString());
/// Creates a JavaScript array containing [iterable].
///
/// While Dart arrays are notionally compatible with JS arrays, they still have
/// some non-enumerable properties that can cause problems (for example, they
/// don't compare as "equal" for Jest's matchers) so it's preferable to use this
/// when exposing them.
JSArray toJSArray(Iterable<Object?> iterable) {
var array = JSArray();
for (var element in iterable) {
array.push(element);
}
return array;
}
/// Converts a JavaScript record into a map from property names to their values.
Map<String, Object?> objectToMap(Object object) {
var map = <String, Object?>{};
jsForEach(object, (key, value) => map[key] = value);
return map;
}
/// Converts a JavaScript separator string into a [ListSeparator].
ListSeparator jsToDartSeparator(String? separator) => switch (separator) {
' ' => ListSeparator.space,
',' => ListSeparator.comma,
'/' => ListSeparator.slash,
null => ListSeparator.undecided,
_ => jsThrow(JsError('Unknown separator "$separator".'))
};
/// Converts a syntax string to an instance of [Syntax].
Syntax parseSyntax(String? syntax) => switch (syntax) {
null || 'scss' => Syntax.scss,
'indented' => Syntax.sass,
'css' => Syntax.css,
_ => jsThrow(JsError('Unknown syntax "$syntax".'))
};
/// The path to the Node.js entrypoint, if one can be located.
String? get entrypointFilename {
if (_requireMain?.filename case var filename?) {
return filename;
} else if (process.argv case [_, String path, ...]) {
return module.createRequire(path).resolve(path);
} else {
return null;
}
}
@JS("require.main")
external _RequireMain? get _requireMain;
@JS()
@anonymous
class _RequireMain {
external String? get filename;
}