Skip to content

Commit

Permalink
Make data: scheme URLs work with fetch()
Browse files Browse the repository at this point in the history
Closes #33.
  • Loading branch information
TooTallNate committed Sep 30, 2023
1 parent d22e5d2 commit 9a9dee4
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/grumpy-cooks-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'nxjs-runtime': patch
---

Make `data:` scheme URLs work with `fetch()`
1 change: 1 addition & 0 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@ungap/event-target": "^0.2.4",
"color-rgba": "^2.4.0",
"core-js": "^3.32.1",
"data-uri-to-buffer": "^6.0.1",
"dts-bundle-generator": "^8.0.1",
"esbuild": "^0.17.19",
"kleur": "github:TooTallNate/kleur#rgb",
Expand Down
18 changes: 18 additions & 0 deletions packages/runtime/src/fetch/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { dataUriToBuffer } from 'data-uri-to-buffer';
import { def } from '../utils';
import { objectUrls } from '../polyfills/url';
import { decoder } from '../polyfills/text-decoder';
Expand Down Expand Up @@ -217,6 +218,21 @@ async function fetchBlob(req: Request, url: URL) {
});
}

async function fetchData(req: Request, url: URL) {
if (req.method !== 'GET') {
throw new Error(
`GET method must be used when fetching "${url.protocol}" protocol (got "${req.method}")`
);
}
const parsed = dataUriToBuffer(url);
return new Response(parsed.buffer, {
headers: {
'content-length': String(parsed.buffer.byteLength),
'content-type': parsed.typeFull,
},
});
}

async function fetchFile(req: Request, url: URL) {
if (req.method !== 'GET') {
throw new Error(
Expand All @@ -236,6 +252,7 @@ const fetchers = new Map<string, (req: Request, url: URL) => Promise<Response>>(
[
['http:', fetchHttp],
['blob:', fetchBlob],
['data:', fetchData],
['file:', fetchFile],
['sdmc:', fetchFile],
['romfs:', fetchFile],
Expand All @@ -249,6 +266,7 @@ const fetchers = new Map<string, (req: Request, url: URL) => Promise<Response>>(
*
* - `http:` - Fetch data from the network using the HTTP protocol
* - `blob:` - Fetch data from a URL constructed by {@link URL.createObjectURL | `URL.createObjectURL()`}
* - `data:` - Fetch data from a Data URI (possibly base64-encoded)
* - `sdmc:` - Fetch data from a local file on the SD card
* - `romfs:` - Fetch data from the RomFS partition of the nx.js application
* - `file:` - Same as `sdmc:`
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9a9dee4

Please sign in to comment.