All files / lib/internal wasm_web_api.js

100% Statements 66/66
100% Branches 22/22
100% Functions 2/2
100% Lines 66/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 67147x 147x 147x 147x 147x 147x 147x 147x 147x 147x 147x 228x 228x 228x 147x 147x 147x 147x 147x 228x 228x 228x 228x 60x 60x 60x 168x 168x 184x 6x 6x 6x 162x 184x 2x 2x 2x 160x 184x 4x 4x 156x 180x 12x 12x 156x 156x 156x 156x 152x 352x 352x 150x 228x 154x 154x 228x 74x 74x 74x 228x 228x 147x 147x 147x 147x  
'use strict';
 
const {
  PromiseResolve,
} = primordials;
const {
  ERR_INVALID_ARG_TYPE,
  ERR_WEBASSEMBLY_RESPONSE,
} = require('internal/errors').codes;
 
let undici;
function lazyUndici() {
  return undici ??= require('internal/deps/undici/undici');
}
 
// This is essentially an implementation of a v8::WasmStreamingCallback, except
// that it is implemented in JavaScript because the fetch() implementation is
// difficult to use from C++. See lib/internal/bootstrap/pre_execution.js and
// src/node_wasm_web_api.cc that interact with this function.
function wasmStreamingCallback(streamState, source) {
  (async () => {
    const response = await PromiseResolve(source);
    if (!(response instanceof lazyUndici().Response)) {
      throw new ERR_INVALID_ARG_TYPE(
        'source', ['Response', 'Promise resolving to Response'], response);
    }
 
    const contentType = response.headers.get('Content-Type');
    if (contentType !== 'application/wasm') {
      throw new ERR_WEBASSEMBLY_RESPONSE(
        `has unsupported MIME type '${contentType}'`);
    }
 
    if (!response.ok) {
      throw new ERR_WEBASSEMBLY_RESPONSE(
        `has status code ${response.status}`);
    }
 
    if (response.bodyUsed !== false) {
      throw new ERR_WEBASSEMBLY_RESPONSE('body has already been used');
    }
 
    if (response.url) {
      streamState.setURL(response.url);
    }
 
    // Pass all data from the response body to the WebAssembly compiler.
    const { body } = response;
    if (body != null) {
      for await (const chunk of body) {
        streamState.push(chunk);
      }
    }
  })().then(() => {
    // No error occurred. Tell the implementation that the stream has ended.
    streamState.finish();
  }, (err) => {
    // An error occurred, either because the given object was not a valid
    // and usable Response or because a network error occurred.
    streamState.abort(err);
  });
}
 
module.exports = {
  wasmStreamingCallback
};