Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(raw): use mime to chck binary types and exclude .json #2239

Merged
merged 1 commit into from
Mar 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/rollup/plugins/raw.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { promises as fsp } from "node:fs";
import { extname } from "pathe";
import mime from "mime";
import type { Plugin } from "rollup";

export interface RawOptions {
Expand All @@ -18,15 +19,9 @@ export function raw(opts: RawOptions = {}): Plugin {
".css",
".htm",
".html",
".json",
".json5",
".csv",
...(opts.extensions || []),
]);

// TODO: use ext=>mime
const isBinary = (id) => !extensions.has(extname(id));

return {
name: "raw",
resolveId(id) {
Expand Down Expand Up @@ -79,6 +74,17 @@ export function raw(opts: RawOptions = {}): Plugin {
};
}

function isBinary(id: string) {
const idMime = mime.getType(id) || "";
if (idMime.startsWith("text/")) {
return false;
}
if (/application\/(json|xml|yaml)/.test(idMime)) {
return false;
}
return true;
}

function getHelpers() {
const js = String.raw;
return js`
Expand Down
3 changes: 3 additions & 0 deletions test/fixture/assets/test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"foo": "bar"
}
25 changes: 25 additions & 0 deletions test/fixture/routes/assets/all.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export default eventHandler(async (event) => {
const serverAssets = useStorage("assets/server");

const keys = await serverAssets.getKeys();
const items = await Promise.all(
keys.map(async (key) => {
return {
key,
meta: await serverAssets.getMeta(key),
data: await serverAssets.getItem(key).then((r) =>
// prettier-ignore
typeof r === "string" ? r.slice(0, 32) : (isPureObject(r) ? r : `<data>`)
),
};
})
);

return items;
});

function isPureObject(value) {
return (
value !== null && typeof value === "object" && value.constructor === Object
);
}