From 28a10c1febd69a9083372faca8b28504e46f61ae Mon Sep 17 00:00:00 2001 From: Xie Yuheng Date: Wed, 15 Nov 2023 11:40:36 +0800 Subject: [PATCH] copy `fetcher/` from inet-js --- TODO.md | 8 ++++-- src/fetcher/Fetcher.ts | 63 ++++++++++++++++++++++++++++++++++++++++++ src/fetcher/index.ts | 1 + 3 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 src/fetcher/Fetcher.ts create mode 100644 src/fetcher/index.ts diff --git a/TODO.md b/TODO.md index 76068f2..5322452 100644 --- a/TODO.md +++ b/TODO.md @@ -1,13 +1,17 @@ # module system -node/Node - Mod -- has loader Place and Transition -- has modId Mod has definitions: Map +# loader + +copy `loader/` from inet-js + +# command-line + # net [net] addPlace diff --git a/src/fetcher/Fetcher.ts b/src/fetcher/Fetcher.ts new file mode 100644 index 0000000..d6884d2 --- /dev/null +++ b/src/fetcher/Fetcher.ts @@ -0,0 +1,63 @@ +export type FetcherHandler = { + fetchText: (url: URL) => string | Promise + formatURL?: (url: URL) => string +} + +export class Fetcher { + handlers: Record = {} + + constructor() { + this.register("http", { + fetchText: async (url) => await (await fetch(url)).text(), + }) + + this.register("https", { + fetchText: async (url) => await (await fetch(url)).text(), + }) + } + + findHandler(url: URL): FetcherHandler | undefined { + const scheme = url.protocol.slice(0, url.protocol.length - 1) + return this.handlers[scheme] + } + + formatURL(url: URL): string { + const handler = this.findHandler(url) + if (handler === undefined) { + throw new Error( + [ + `[Fetcher.formatURL] I meet unknown protocol.`, + ``, + ` protocol: ${url.protocol}`, + ` url: ${url.href}`, + ].join("\n"), + ) + } + + if (handler.formatURL) { + return handler.formatURL(url) + } else { + return url.href + } + } + + async fetchText(url: URL): Promise { + const handler = this.findHandler(url) + if (handler === undefined) { + throw new Error( + [ + `[Fetcher.fetchText] I meet unknown protocol.`, + ``, + ` protocol: ${url.protocol}`, + ` url: ${url.href}`, + ].join("\n"), + ) + } + + return handler.fetchText(url) + } + + register(scheme: string, handler: FetcherHandler): void { + this.handlers[scheme] = handler + } +} diff --git a/src/fetcher/index.ts b/src/fetcher/index.ts new file mode 100644 index 0000000..540c9da --- /dev/null +++ b/src/fetcher/index.ts @@ -0,0 +1 @@ +export * from "./Fetcher"