retrieve.js: implement
ADD
src/retrieve.js
+export const DEFAULT_READFILE = path => {
+ throw TypeError(`Reading files like ${path} not implemented`);
+};
+
+export const makeFetchRetriever = (fetch, readFile = DEFAULT_READFILE) => {
+ return async moduleId => {
+ const url = new URL(moduleId);
+ if (url.protocol === 'file:') {
+ return readFile(url.pathname);
+ }
+ const resp = await fetch(url.href);
+ if (!resp.ok) {
+ throw Error(`fetching ${url.href}: ${resp.status} ${resp.statusText}`);
+ }
+ return resp.text();
+ };
+};

ADD
test/simple-retrieve/hello.txt
+Hello, world!

ADD
test/test-retrieve.js
+/* eslint-disable import/no-extraneous-dependencies */
+import { test } from 'tape-promise/tape';
+import fetch from 'node-fetch';
+import fs from 'fs';
+import path from 'path';
+
+import { makeFetchRetriever } from '../src';
+
+const readFile = file => fs.promises.readFile(file, 'utf-8');
+
+test.only('filesystem retriever', async t => {
+ try {
+ const retrieve = makeFetchRetriever(fetch, readFile);
+ const sr = `file://${path.join(__dirname, 'simple-retrieve')}`;
+ console.log(sr);
+ await t.rejects(
+ retrieve(`${sr}/nonexistent`),
+ Error,
+ 'cannot retrieve nonexistent',
+ );
+ t.equal(
+ await retrieve(`${sr}/hello.txt`),
+ `Hello, world!\n`,
+ `retrieve existing file`,
+ );
+ } catch (e) {
+ t.isNot(e, e, 'unexpected exception');
+ } finally {
+ t.end();
+ }
+});

retrieve.js: implement