This repository has been archived by the owner on Dec 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
230 lines (205 loc) · 6.21 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import type {
MiddlewareHandlerContext,
Plugin,
PluginMiddleware,
PluginRoute,
} from "$fresh/src/server/types.ts";
import type {
ImagesPluginOptions,
TransformFn,
TransformRoute,
} from "./src/types.ts";
import { join, resolve, toFileUrl } from "$std/path/mod.ts";
import { decode } from "imagescript/mod.ts";
import { getImageResponse, getParam } from "./src/_utils.ts";
import { getCache } from "./src/server.ts";
import { handler } from "./src/middleware.ts";
export { extendKeyMap, transform } from "./src/_utils.ts";
export { getParam };
const cache = await getCache();
/**
* Parse a URL for transformation functions to apply. Functions can be passed in the query string or at the start of the path.
* @param url Request URL to parse
* @param transformers Installed image transformers
* @returns List of transformer keys to apply to the image
*/
function getTransformerFns(
url: URL,
transformers: ImagesPluginOptions["transformers"] = {},
): string[] {
const transformFns = url.searchParams.getAll("fn");
// Parse path for additional transformation functions.
// Split the public path and look for matching transformer keys
// e.g. /resize/image.jpg?rw=100&rh=100&fn=rotate&rd=90
for (const key of Object.keys(transformers)) {
const value = transformers[key];
if (typeof value === "function") {
continue;
}
if (
url.pathname.startsWith(`${value.path}/`)
) {
transformFns.push(key);
transformers[key] = value;
break;
}
}
return transformFns;
}
/**
* Handle an image transformation request.
* @param transformers Available image transformations
* @param req HTTP request
* @param publicPath Route exposed to the client
* @param localPath Optional path to the local image directory. Defaults to root.
* @returns Response containing the transformed image or an error message
*/
export async function handleImageRequest<T extends string>(
transformers: ImagesPluginOptions["transformers"] = {},
req: Request,
publicPath: T,
localPath?: string,
): Promise<Response> {
const cached = await cache.get(req);
if (cached) {
return cached;
}
const url = new URL(req.url);
const regex = new RegExp(`^${publicPath}/`);
const srcPath = url.pathname.replace(regex, "");
const resourcePath = toFileUrl(
join(resolve(Deno.cwd(), localPath ?? "./"), srcPath),
);
const transformFns = getTransformerFns(url, transformers);
try {
const resource = await fetch(resourcePath);
const data = await resource.arrayBuffer();
// Apply each transformation function in order
const img = await transformFns.reduce(async (acc, xfn) => {
if (!(xfn in transformers)) {
return acc;
}
return typeof transformers[xfn] === "function"
? await (transformers[xfn] as TransformFn)(await acc, req)
: await (transformers[xfn] as TransformRoute).handler(await acc, req);
}, decode(data));
const res = await getImageResponse(img, req);
await cache.put(req, res);
return res;
} catch (err) {
// TODO: Add option to respond with error images
return new Response(err.message, {
status: 500,
});
}
}
/**
* A Fresh plugin which adds image transformation routes to your static directory
* @property {string} publicPath The base path for the image transformation routes
* @property {string} realPath The absolute path to the image file directory
* @property {Record<string, (img: Image | GIF, req: Request) => Image | GIF>} transformers A map of image transformation functions
* @returns {Plugin} Images plugin
* @example
* ```ts
* import { defineConfig } from "$fresh/server.ts";
* import ImagesPlugin from "fresh_images/mod.ts";
* import { resize } from "fresh_images/transformer.ts";
*
* export default defineConfig({
* plugins: [
* ImagesPlugin({
* publicPath: "/img",
* transformers: { resize },
* }),
* ],
* });
* ```
*/
export default function ImagesPlugin({
route = "/images",
realPath = "./static/image",
transformers = {},
build,
middleware,
}: ImagesPluginOptions): Plugin {
try {
// Ensure route is not a directory in the ./static folder. Otherwise there will be Fresh routing conflicts.
const staticPath = resolve(Deno.cwd(), "./static");
const desiredPath = join(staticPath, route);
if (Deno.statSync(desiredPath).isDirectory) {
throw new Error(
`The route "${route}" is a directory in the static folder. Please choose a different route.`,
);
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
const middlewares: PluginMiddleware[] = [];
// Compile routes
const routes: PluginRoute[] = Object.entries(transformers).map(
([key, fn]) => {
if (typeof fn === "function") {
middlewares.push({
path: `${route}/[fileName]`,
middleware: {
// Pass middleware settings to the handlers
handler: (req: Request, ctx: MiddlewareHandlerContext) =>
handler(req, ctx, middleware),
},
});
return ({
path: `${route}/[fileName]`,
handler: async (req: Request) =>
await handleImageRequest(
transformers,
req,
route,
realPath,
),
});
}
middlewares.push({
path: `${fn.path ?? key}/[fileName]`,
middleware: {
handler: (req: Request, ctx: MiddlewareHandlerContext) =>
handler(req, ctx, middleware),
},
});
return {
path: `${fn.path ?? key}/[fileName]`,
handler: async (req: Request) =>
await handleImageRequest(
transformers,
req,
fn.path ?? key,
realPath,
),
};
},
);
return {
name: "fresh_images",
routes,
middlewares,
buildStart: () => {
if (!build) {
return;
}
console.log(
"%c 🎞️ Processing images...",
"background: #111; color: #f1820b;",
);
build({
route,
realPath,
transformers,
});
console.log(
"%c 🖼️ Finished processing images!",
"background: #111; color: #77f31d;",
);
},
};
}