Skip to content

Commit 2ab3b0d

Browse files
committed
Add conversions between Dart's Uri and the JS URL
1 parent 553c14d commit 2ab3b0d

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

web/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
don't exist.
66
- Fixed generation of variadic arguments to generate 4 optional parameters.
77
- Removed all `@Deprecated` members.
8+
- Added `URL.toDart` and `Uri.toJS` extension methods.
89

910
## 1.1.1
1011

web/lib/src/helpers/extensions.dart

+19
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,22 @@ extension XMLHttpRequestGlue on XMLHttpRequest {
8484
return headers;
8585
}
8686
}
87+
88+
extension URLToUri on URL {
89+
/// Converts this to a Dart [Uri] object.
90+
Uri get toDart => Uri.parse(toString());
91+
}
92+
93+
extension UriToURL on Uri {
94+
/// Converts this to a JavaScript [URL] object.
95+
///
96+
/// Throws an [ArgumentError] if this isn't an absolute URL, since [URL] can
97+
/// only represent absolute URLs.
98+
URL get toJS {
99+
try {
100+
return URL(toString());
101+
} catch (_) {
102+
throw ArgumentError.value(this, 'this', '"$this" isn\'t a valid JS URL.');
103+
}
104+
}
105+
}

web/test/helpers_test.dart

+27
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,31 @@ void main() {
134134
// `close` on a `contentWindow` does nothing.
135135
expect(contentWindow.closed, false);
136136
});
137+
138+
test('converts from a JS to a Dart URL', () {
139+
var url = URL("https://foo:[email protected]:1234/path?query#fragment").toDart;
140+
expect(url.scheme, equals("https"));
141+
expect(url.userInfo, equals("foo:bar"));
142+
expect(url.host, equals("example.org"));
143+
expect(url.port, equals(1234));
144+
expect(url.path, equals("/path"));
145+
expect(url.query, equals("query"));
146+
expect(url.fragment, equals("fragment"));
147+
});
148+
149+
test('converts from a Dart to a JS URL', () {
150+
var url = Uri.parse("https://foo:[email protected]:1234/path?query#fragment").toJS;
151+
expect(url.protocol, equals("https:"));
152+
expect(url.username, equals("foo"));
153+
expect(url.password, equals("bar"));
154+
expect(url.hostname, equals("example.org"));
155+
expect(url.port, equals("1234"));
156+
expect(url.pathname, equals("/path"));
157+
expect(url.search, equals("?query"));
158+
expect(url.hash, equals("#fragment"));
159+
});
160+
161+
test('Uri.toJS throws an ArgumentError for a relative URL', () {
162+
expect(() => Uri.parse("/path").toJS, throwsArgumentError);
163+
});
137164
}

0 commit comments

Comments
 (0)