All files / lib/internal/modules/esm get_source.js

95.56% Statements 43/45
86.67% Branches 13/15
100% Functions 1/1
95.56% Lines 43/45

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 46138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 459x 459x 459x 459x 431x 455x 28x 28x 1x 1x 27x 28x 28x     459x 3x 3x 455x 459x 138x  
'use strict';
 
const {
  RegExpPrototypeExec,
  decodeURIComponent,
} = primordials;
const { getOptionValue } = require('internal/options');
// Do not eagerly grab .manifest, it may be in TDZ
const policy = getOptionValue('--experimental-policy') ?
  require('internal/process/policy') :
  null;
 
const { Buffer } = require('buffer');
 
const fs = require('internal/fs/promises').exports;
const { URL } = require('internal/url');
const {
  ERR_INVALID_URL,
  ERR_INVALID_URL_SCHEME,
} = require('internal/errors').codes;
const readFileAsync = fs.readFile;
 
const DATA_URL_PATTERN = /^[^/]+\/[^,;]+(?:[^,]*?)(;base64)?,([\s\S]*)$/;
 
async function defaultGetSource(url, { format } = {}, defaultGetSource) {
  const parsed = new URL(url);
  let source;
  if (parsed.protocol === 'file:') {
    source = await readFileAsync(parsed);
  } else if (parsed.protocol === 'data:') {
    const match = RegExpPrototypeExec(DATA_URL_PATTERN, parsed.pathname);
    if (!match) {
      throw new ERR_INVALID_URL(url);
    }
    const { 1: base64, 2: body } = match;
    source = Buffer.from(decodeURIComponent(body), base64 ? 'base64' : 'utf8');
  } else {
    throw new ERR_INVALID_URL_SCHEME(['file', 'data']);
  }
  if (policy?.manifest) {
    policy.manifest.assertIntegrity(parsed, source);
  }
  return source;
}
exports.defaultGetSource = defaultGetSource;