From fb657476b5d873b23468f95c88d738e511688fed Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Mon, 9 Jan 2023 16:31:59 +0100 Subject: [PATCH] feat(dev): support for `/_vfs.json` (#809) --- .eslintrc | 1 + src/dev/vfs.ts | 66 +++++++++++++++++++++++++++++++++----------------- 2 files changed, 45 insertions(+), 22 deletions(-) diff --git a/.eslintrc b/.eslintrc index 6ecc1c66e0..714491c19c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -9,6 +9,7 @@ "quotes": 0, "keyword-spacing": 0, "no-undef": 0, + "indent": 0, "unicorn/catch-error-name": 0, "unicorn/no-null": 0, "unicorn/no-useless-undefined": 0, diff --git a/src/dev/vfs.ts b/src/dev/vfs.ts index db57384963..9636451fa1 100644 --- a/src/dev/vfs.ts +++ b/src/dev/vfs.ts @@ -8,10 +8,41 @@ export function createVFSHandler(nitro: Nitro) { ...nitro.options.virtual, }; + const url = event.node.req.url || ""; + const isJson = + event.node.req.headers.accept?.includes("application/json") || + url.startsWith(".json"); + const id = decodeURIComponent(url.replace(/^(\.json)?\/?/, "") || ""); + + if (id && !(id in vfsEntries)) { + throw createError({ message: "File not found", statusCode: 404 }); + } + + let content = id ? vfsEntries[id] : undefined; + if (typeof content === "function") { + content = await content(); + } + + if (isJson) { + return { + rootDir: nitro.options.rootDir, + entries: Object.keys(vfsEntries).map((id) => ({ + id, + path: "/_vfs.json/" + encodeURIComponent(id), + })), + current: id + ? { + id, + content, + } + : null, + }; + } + const items = Object.keys(vfsEntries) .map((key) => { const linkClass = - event.req.url === `/${encodeURIComponent(key)}` + url === `/${encodeURIComponent(key)}` ? "bg-gray-700 text-white" : "hover:bg-gray-800 text-gray-200"; return `
  • virtual files

    @@ -29,31 +61,21 @@ export function createVFSHandler(nitro: Nitro) { `; - const id = decodeURIComponent(event.req.url?.slice(1) || ""); - - let file = ""; - if (id in vfsEntries) { - let contents = vfsEntries[id]; - if (typeof contents === "function") { - contents = await contents(); - } - file = editorTemplate({ - readOnly: true, - language: id.endsWith("html") ? "html" : "javascript", - theme: "vs-dark", - value: contents, - wordWrap: "wordWrapColumn", - wordWrapColumn: 80, - }); - } else if (id) { - throw createError({ message: "File not found", statusCode: 404 }); - } else { - file = ` + const file = id + ? editorTemplate({ + readOnly: true, + language: id.endsWith("html") ? "html" : "javascript", + theme: "vs-dark", + value: content, + wordWrap: "wordWrapColumn", + wordWrapColumn: 80, + }) + : `

    Select a virtual file to inspect

    `; - } + return `