readPrefix method

  1. @override
Future<Uint8List> readPrefix(
  1. String url,
  2. int length
)
override

fetch(url), read until length bytes arrived, then cancelled. An http(s): URL also asks for just that range (Range is a CORS-safelisted header); a blob: URL — the page's own copy, Cache API or OPFS — is a local read either way.

Implementation

@override
Future<Uint8List> readPrefix(String url, int length) async {
  final init = JSObject();
  if (url.startsWith('http:') || url.startsWith('https:')) {
    init['headers'] = JSObject()..['Range'] = 'bytes=0-${length - 1}'.toJS;
  }
  final response = await _fetch(url.toJS, init).toDart;
  if (!response.ok) {
    // An error page can be large or streamed: drop it before throwing.
    try {
      await response.body?.cancel().toDart;
    } catch (e) {
      runtimeLog('[LiteRtLmWebEmbedder] cancelling the read of $url: $e');
    }
    throw StateError('fetch($url) answered HTTP ${response.status}');
  }
  final body = response.body;
  if (body == null) return Uint8List(0);
  final reader = body.getReader();
  final bytes = BytesBuilder(copy: false);
  try {
    while (bytes.length < length) {
      final chunk = await reader.read().toDart;
      if (chunk.done) break;
      if (chunk.value case final value?) bytes.add(value.toDart);
    }
  } finally {
    try {
      // Stops the rest of the body: a few KB were wanted, not the model.
      await reader.cancel().toDart;
    } catch (e) {
      runtimeLog('[LiteRtLmWebEmbedder] cancelling the read of $url: $e');
    }
  }
  final read = bytes.takeBytes();
  return read.length > length ? Uint8List.sublistView(read, 0, length) : read;
}