formacao
This commit is contained in:
+34
-5
@@ -1,9 +1,37 @@
|
||||
// src/middleware/compress/index.ts
|
||||
import { parseAccept } from "../../utils/accept.js";
|
||||
import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from "../../utils/compress.js";
|
||||
var ENCODING_TYPES = ["gzip", "deflate"];
|
||||
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i;
|
||||
var selectEncoding = (header, candidates) => {
|
||||
if (header === void 0) {
|
||||
return void 0;
|
||||
}
|
||||
const accepts = parseAccept(header);
|
||||
const wildcardQ = accepts.find((a) => a.type === "*")?.q;
|
||||
let best;
|
||||
for (const enc of candidates) {
|
||||
const explicit = accepts.find((a) => a.type.toLowerCase() === enc);
|
||||
const q = explicit ? explicit.q : wildcardQ ?? 0;
|
||||
if (q === 1) {
|
||||
return enc;
|
||||
} else if (q > 0 && (!best || q > best.q)) {
|
||||
best = { encoding: enc, q };
|
||||
}
|
||||
}
|
||||
return best?.encoding;
|
||||
};
|
||||
var compress = (options) => {
|
||||
const threshold = options?.threshold ?? 1024;
|
||||
const candidates = options?.encoding ? [options.encoding] : ENCODING_TYPES;
|
||||
const contentTypeFilter = options?.contentTypeFilter ?? COMPRESSIBLE_CONTENT_TYPE_REGEX;
|
||||
const shouldCompress = typeof contentTypeFilter === "function" ? (res) => {
|
||||
const type = res.headers.get("Content-Type");
|
||||
return type && contentTypeFilter(type);
|
||||
} : (res) => {
|
||||
const type = res.headers.get("Content-Type");
|
||||
return type && contentTypeFilter.test(type);
|
||||
};
|
||||
return async function compress2(ctx, next) {
|
||||
await next();
|
||||
const contentLength = ctx.res.headers.get("Content-Length");
|
||||
@@ -16,7 +44,7 @@ var compress = (options) => {
|
||||
return;
|
||||
}
|
||||
const accepted = ctx.req.header("Accept-Encoding");
|
||||
const encoding = options?.encoding ?? ENCODING_TYPES.find((encoding2) => accepted?.includes(encoding2));
|
||||
const encoding = selectEncoding(accepted, candidates);
|
||||
if (!encoding || !ctx.res.body) {
|
||||
return;
|
||||
}
|
||||
@@ -24,16 +52,17 @@ var compress = (options) => {
|
||||
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res);
|
||||
ctx.res.headers.delete("Content-Length");
|
||||
ctx.res.headers.set("Content-Encoding", encoding);
|
||||
const etag = ctx.res.headers.get("ETag");
|
||||
if (etag && !etag.startsWith("W/")) {
|
||||
ctx.res.headers.set("ETag", `W/${etag}`);
|
||||
}
|
||||
};
|
||||
};
|
||||
var shouldCompress = (res) => {
|
||||
const type = res.headers.get("Content-Type");
|
||||
return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type);
|
||||
};
|
||||
var shouldTransform = (res) => {
|
||||
const cacheControl = res.headers.get("Cache-Control");
|
||||
return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
|
||||
};
|
||||
export {
|
||||
COMPRESSIBLE_CONTENT_TYPE_REGEX,
|
||||
compress
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user