Skip to content

Add conversions between Dart's Uri and the JS URL #365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions web/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
don't exist.
- Fixed generation of variadic arguments to generate 4 optional parameters.
- Removed all `@Deprecated` members.
- Added `URL.toDart` and `Uri.toJS` extension methods.

## 1.1.1

Expand Down
19 changes: 19 additions & 0 deletions web/lib/src/helpers/extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,22 @@ extension XMLHttpRequestGlue on XMLHttpRequest {
return headers;
}
}

extension URLToUri on URL {
/// Converts this to a Dart [Uri] object.
Uri get toDart => Uri.parse(toString());
}

extension UriToURL on Uri {
/// Converts this to a JavaScript [URL] object.
///
/// Throws an [ArgumentError] if this isn't an absolute URL, since [URL] can
/// only represent absolute URLs.
URL get toJS {
try {
return URL(toString());
} catch (_) {
throw ArgumentError.value(this, 'this', '"$this" isn\'t a valid JS URL.');
}
}
}
29 changes: 29 additions & 0 deletions web/test/helpers_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,33 @@ void main() {
// `close` on a `contentWindow` does nothing.
expect(contentWindow.closed, false);
});

test('converts from a JS to a Dart URL', () {
final url =
URL('https://foo:[email protected]:1234/path?query#fragment').toDart;
expect(url.scheme, equals('https'));
expect(url.userInfo, equals('foo:bar'));
expect(url.host, equals('example.org'));
expect(url.port, equals(1234));
expect(url.path, equals('/path'));
expect(url.query, equals('query'));
expect(url.fragment, equals('fragment'));
});

test('converts from a Dart to a JS URL', () {
final url =
Uri.parse('https://foo:[email protected]:1234/path?query#fragment').toJS;
expect(url.protocol, equals('https:'));
expect(url.username, equals('foo'));
expect(url.password, equals('bar'));
expect(url.hostname, equals('example.org'));
expect(url.port, equals('1234'));
expect(url.pathname, equals('/path'));
expect(url.search, equals('?query'));
expect(url.hash, equals('#fragment'));
});

test('Uri.toJS throws an ArgumentError for a relative URL', () {
expect(() => Uri.parse('/path').toJS, throwsArgumentError);
});
}