pixel-serve-server 0.0.6 β†’ 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,212 +1,270 @@
1
- # Image Server Middleware
1
+ # Pixel Serve Server
2
2
 
3
- A powerful and customizable middleware for processing, resizing, and serving images in Node.js applications. Built with **TypeScript** and powered by **Sharp**, this package allows you to handle local and network images with robust error handling, fallback images, and customizable options.
3
+ **A modern, type-safe middleware** for processing, resizing, and serving images in Node.js applications. Built with **TypeScript**, powered by **Sharp**, and designed for secure production use with ESM & CJS bundles.
4
4
 
5
- ---
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9.3-blue.svg)](https://www.typescriptlang.org/)
7
+ [![Node.js](https://img.shields.io/badge/Node.js-18+-blue.svg)](https://nodejs.org/)
6
8
 
7
9
  ## Features
8
10
 
9
- - πŸ–ΌοΈ **Dynamic Image Resizing and Formatting**
10
-
11
- - Supports various formats: `jpeg`, `png`, `webp`, `gif`, `tiff`, `avif`, and `svg`.
12
- - Adjustable dimensions with constraints for safety.
13
-
14
- - 🌐 **Network and Local File Handling**
15
-
16
- - Fetches images from allowed network domains.
17
- - Processes images stored locally with safe path validation.
18
-
19
- - πŸ”’ **Fallback Images**
20
-
21
- - Provides fallback images for invalid or missing sources.
22
-
23
- - πŸ”§ **Highly Configurable**
24
-
25
- - Flexible option to set base directories, private folders, and user-specific paths.
26
- - Supports user-defined ID handlers and folder logic.
27
-
28
- - πŸš€ **Efficient and Scalable**
29
- - Built on **Sharp** for high-performance image processing.
30
- - Handles concurrent requests with ease.
31
-
32
- ---
11
+ - πŸ–ΌοΈ **Dynamic resizing & formatting**: `jpeg`, `png`, `webp`, `gif`, `tiff`, `avif`, `svg` with configurable width/height bounds and quality limits
12
+ - 🌐 **Secure source resolution**: Strict path validation, domain allowlists, and MIME type checks for network fetches
13
+ - πŸ”’ **Fallbacks & private folders**: Built-in placeholder images plus async `getUserFolder` for private assets
14
+ - ⚑ **Caching ready**: ETag + Cache-Control headers out of the box
15
+ - πŸ§ͺ **Type-safe & tested**: 100% TypeScript with Vitest coverage and exported Zod schemas
16
+ - ♻️ **Dual builds**: Works in both ESM and CommonJS environments
33
17
 
34
18
  ## Installation
35
19
 
36
- Install the package using npm or yarn:
37
-
38
20
  ```bash
39
21
  npm install pixel-serve-server
40
22
  ```
41
23
 
42
- ---
43
-
44
- ## Usage
45
-
46
- ### Basic Setup
24
+ ## Quick Start
47
25
 
48
- Here’s how to integrate the middleware with an Express application:
26
+ ### Basic Setup (Express)
49
27
 
50
28
  ```typescript
51
29
  import express from "express";
52
30
  import { registerServe } from "pixel-serve-server";
53
- import path, { dirname } from "node:path";
54
- import { fileURLToPath } from "node:url";
31
+ import path from "node:path";
55
32
 
56
33
  const app = express();
57
- const __filename = fileURLToPath(import.meta.url);
58
- const __dirname = dirname(__filename);
59
-
60
- const BASE_IMAGE_DIR = path.join(__dirname, "../assets/images/public");
61
- const PRIVATE_IMAGE_DIR = path.join(__dirname, "../assets/images/private");
62
34
 
63
35
  const serveImage = registerServe({
64
- baseDir: BASE_IMAGE_DIR, // Base directory for local images
65
- idHandler: (id: string) => `user-${id}`, // Custom handler for user IDs
66
- getUserFolder: async (id: string) => `/private/users/${id}`, // Logic for user-specific folder paths
67
- websiteURL: "example.com", // Your website's base URL
68
- apiRegex: /^\/api\/v1\//, // Regex for removing API prefixes
69
- allowedNetworkList: ["trusted.com"], // List of allowed network domains
36
+ baseDir: path.join(__dirname, "../assets/images/public"),
70
37
  });
71
38
 
72
39
  app.get("/api/v1/pixel/serve", serveImage);
73
40
 
74
41
  app.listen(3000, () => {
75
- console.log("Server is running on http://localhost:3000");
42
+ console.log("Server running on http://localhost:3000");
76
43
  });
77
44
  ```
78
45
 
79
- ---
46
+ ### Advanced Setup with All Options
47
+
48
+ ```typescript
49
+ import express from "express";
50
+ import { registerServe } from "pixel-serve-server";
51
+ import path from "node:path";
52
+
53
+ const app = express();
80
54
 
81
- ### Options
55
+ const serveImage = registerServe({
56
+ // Required: Base directory for public images
57
+ baseDir: path.join(__dirname, "../assets/images/public"),
82
58
 
83
- The `serveImage` middleware accepts the following options:
59
+ // Custom user ID handler
60
+ idHandler: (id: string) => `user-${id}`,
84
61
 
85
- | Option | Type | Description |
86
- | -------------------- | ---------- | ----------------------------------------------------------- |
87
- | `baseDir` | `string` | Base directory for local image files. |
88
- | `idHandler` | `Function` | Function to handle and format user IDs. |
89
- | `getUserFolder` | `Function` | Async function to resolve a user-specific folder path. |
90
- | `websiteURL` | `string` | Your website's base URL for identifying internal resources. |
91
- | `apiRegex` | `RegExp` | Regex to strip API prefixes from internal paths. |
92
- | `allowedNetworkList` | `string[]` | List of allowed domains for network images. |
62
+ // Async function to resolve private folder paths
63
+ getUserFolder: async (req, userId) => {
64
+ // Your logic to resolve user-specific folder
65
+ return `/private/users/${userId}`;
66
+ },
93
67
 
94
- ---
68
+ // Your website's base URL (for treating internal URLs as local)
69
+ websiteURL: "example.com",
95
70
 
96
- ### Example Requests
71
+ // Regex to strip API prefix from internal URLs
72
+ apiRegex: /^\/api\/v1\//,
97
73
 
98
- #### Fetching a Local Image
74
+ // Allowed remote hosts for fetching network images
75
+ allowedNetworkList: ["cdn.example.com", "images.example.com"],
99
76
 
100
- ```bash
101
- GET http://localhost:3000/images?src=/uploads/image1.jpg&width=300&height=300
77
+ // Custom Cache-Control header
78
+ cacheControl: "public, max-age=86400, stale-while-revalidate=604800",
79
+
80
+ // Enable/disable ETag generation
81
+ etag: true,
82
+
83
+ // Image dimension bounds
84
+ minWidth: 50,
85
+ maxWidth: 4000,
86
+ minHeight: 50,
87
+ maxHeight: 4000,
88
+
89
+ // Default JPEG/WebP/AVIF quality
90
+ defaultQuality: 80,
91
+
92
+ // Network fetch timeout (ms)
93
+ requestTimeoutMs: 5000,
94
+
95
+ // Maximum download size from remote sources (bytes)
96
+ maxDownloadBytes: 5_000_000,
97
+ });
98
+
99
+ app.get("/api/v1/pixel/serve", serveImage);
100
+
101
+ app.listen(3000);
102
102
  ```
103
103
 
104
- #### Fetching a Network Image
104
+ ## Configuration Options
105
+
106
+ | Option | Type | Default | Description |
107
+ | -------------------- | ----------------------------------------- | -------------------------- | ----------------------------------------------------------------------- |
108
+ | `baseDir` | `string` | **required** | Base directory for local images |
109
+ | `idHandler` | `(id: string) => string` | `id => id` | Transform user IDs before lookup |
110
+ | `getUserFolder` | `(req, id?) => string \| Promise<string>` | `undefined` | Resolve private folder path when `folder=private` |
111
+ | `websiteURL` | `string` | `undefined` | If set, internal URLs pointing to this host are treated as local assets |
112
+ | `apiRegex` | `RegExp` | `/^\/api\/v1\//` | Prefix stripped from internal URLs before lookup |
113
+ | `allowedNetworkList` | `string[]` | `[]` | Allowed remote hosts. Others immediately fall back |
114
+ | `cacheControl` | `string` | `public, max-age=86400...` | Cache-Control header value |
115
+ | `etag` | `boolean` | `true` | Emit ETag and honor If-None-Match |
116
+ | `minWidth` | `number` | `50` | Minimum accepted width |
117
+ | `maxWidth` | `number` | `4000` | Maximum accepted width |
118
+ | `minHeight` | `number` | `50` | Minimum accepted height |
119
+ | `maxHeight` | `number` | `4000` | Maximum accepted height |
120
+ | `defaultQuality` | `number` | `80` | Default JPEG/WebP/AVIF quality |
121
+ | `requestTimeoutMs` | `number` | `5000` | Network fetch timeout |
122
+ | `maxDownloadBytes` | `number` | `5_000_000` | Maximum remote download size |
123
+
124
+ ## Query Parameters
125
+
126
+ | Parameter | Type | Default | Description |
127
+ | --------- | ----------------------- | ----------- | ------------------------------------------------------------------- |
128
+ | `src` | `string` | _required_ | Path or URL to the image source |
129
+ | `format` | `ImageFormat` | `jpeg` | Output format (`jpeg`, `png`, `webp`, `gif`, `tiff`, `avif`, `svg`) |
130
+ | `width` | `number` | `undefined` | Desired output width (px) |
131
+ | `height` | `number` | `undefined` | Desired output height (px) |
132
+ | `quality` | `number` | `80` | Image quality (1-100) |
133
+ | `folder` | `'public' \| 'private'` | `public` | Image folder type |
134
+ | `userId` | `string` | `undefined` | User ID for private folder access |
135
+ | `type` | `'normal' \| 'avatar'` | `normal` | Image type (affects fallback image) |
136
+
137
+ ## Example Requests
138
+
139
+ ### Local Image with Resize
105
140
 
106
141
  ```bash
107
- GET http://localhost:3000/images?src=https://trusted.com/image2.jpg&format=webp
142
+ GET /api/v1/pixel/serve?src=uploads/photo.jpg&width=800&height=600&format=webp
108
143
  ```
109
144
 
110
- #### Handling Private User Folders
145
+ ### Network Image
111
146
 
112
147
  ```bash
113
- GET http://localhost:3000/images?src=/avatar.jpg&folder=private&userId=12345
148
+ GET /api/v1/pixel/serve?src=https://cdn.example.com/image.jpg&format=avif&quality=90
114
149
  ```
115
150
 
116
- ---
151
+ ### Private User Image
117
152
 
118
- ### User Data Parameters
153
+ ```bash
154
+ GET /api/v1/pixel/serve?src=avatar.jpg&folder=private&userId=12345&type=avatar
155
+ ```
156
+
157
+ ## Integration with Pixel Serve Client
119
158
 
120
- The middleware uses the following `UserData` query parameters:
159
+ This package is designed to work seamlessly with [`pixel-serve-client`](https://www.npmjs.com/package/pixel-serve-client), a React component that automatically generates the correct query parameters.
121
160
 
122
- | Parameter | Type | Description |
123
- | --------- | ----------------------- | ---------------------------------------------------- |
124
- | `src` | `string` | Path or URL to the image source. |
125
- | `format` | `ImageFormat` | Desired output format (e.g., `jpeg`, `png`, `webp`). |
126
- | `width` | `number` | Desired width of the output image. |
127
- | `height` | `number` | Desired height of the output image. |
128
- | `quality` | `number` | Image quality (1-100, default: 80). |
129
- | `folder` | `'public' \| 'private'` | Image folder type (default: `public`). |
130
- | `userId` | `string \| null` | User ID for private folder access. |
131
- | `type` | `'normal' \| 'avatar'` | Image type (default: `normal`). |
161
+ ```tsx
162
+ // Client-side (React)
163
+ import Pixel from "pixel-serve-client";
132
164
 
133
- ---
165
+ <Pixel
166
+ src="/uploads/photo.jpg"
167
+ width={800}
168
+ height={600}
169
+ backendUrl="/api/v1/pixel/serve"
170
+ />;
171
+ ```
134
172
 
135
- ### Image Formats
173
+ ## Security Features
136
174
 
137
- The following image formats are supported:
175
+ ### Path Traversal Protection
138
176
 
139
- - `jpeg`
140
- - `jpg`
141
- - `png`
142
- - `webp`
143
- - `gif`
144
- - `tiff`
145
- - `avif`
146
- - `svg`
177
+ All local paths are validated to prevent directory traversal attacks:
147
178
 
148
- Each format is processed with the specified quality settings.
179
+ - Rejects paths with `..`
180
+ - Rejects absolute paths
181
+ - Validates resolved paths stay within `baseDir`
182
+ - Rejects null bytes and control characters
149
183
 
150
- ---
184
+ ### Network Image Security
151
185
 
152
- ### Advanced Configuration
186
+ - Only fetches from explicitly allowed domains (`allowedNetworkList`)
187
+ - Validates MIME type of responses
188
+ - Configurable timeout and size limits
189
+ - Rejects non-HTTP/HTTPS protocols
153
190
 
154
- #### Custom ID Handler
191
+ ### Private Folder Access
155
192
 
156
- Use the `idHandler` option to customize how user IDs are formatted.
193
+ Use `getUserFolder` to implement your own authentication/authorization logic:
157
194
 
158
195
  ```typescript
159
- const options = {
160
- idHandler: (id) => `user-${id.toUpperCase()}`, // Converts ID to uppercase with "user-" prefix
161
- };
196
+ const serveImage = registerServe({
197
+ baseDir: "/public/images",
198
+ getUserFolder: async (req, userId) => {
199
+ const user = await verifyToken(req.headers.authorization);
200
+ if (!user || user.id !== userId) {
201
+ return null; // Will use baseDir instead
202
+ }
203
+ return `/private/users/${userId}`;
204
+ },
205
+ });
162
206
  ```
163
207
 
164
- #### Resolving User Folders
208
+ ## Fallback Images
165
209
 
166
- The `getUserFolder` function dynamically resolves private folder paths for users.
210
+ The package includes built-in fallback images for:
167
211
 
168
- ```typescript
169
- const options = {
170
- getUserFolder: async (id) => `/private/data/users/${id}`, // Returns a private directory path
171
- };
172
- ```
212
+ - **Normal images**: Displayed when an image cannot be loaded
213
+ - **Avatars**: Displayed when an avatar image cannot be loaded
214
+
215
+ These are automatically served when:
173
216
 
174
- #### Allowed Network Domains
217
+ - The requested image doesn't exist
218
+ - Path validation fails
219
+ - Network fetch fails or returns invalid data
220
+ - Image processing fails
175
221
 
176
- Whitelist trusted domains for fetching network images.
222
+ ## Exports
177
223
 
178
224
  ```typescript
179
- const options = {
180
- allowedNetworkList: ["example.com", "cdn.example.com"], // Only allows images from these domains
181
- };
182
- ```
225
+ // Main middleware factory
226
+ import { registerServe } from "pixel-serve-server";
183
227
 
184
- ---
228
+ // Types
229
+ import type {
230
+ PixelServeOptions,
231
+ UserData,
232
+ ImageFormat,
233
+ ImageType,
234
+ } from "pixel-serve-server";
185
235
 
186
- ### Error Handling
236
+ // Zod schemas for validation
237
+ import { optionsSchema, userDataSchema } from "pixel-serve-server";
187
238
 
188
- The middleware automatically falls back to pre-defined images for errors:
239
+ // Utility function
240
+ import { isValidPath } from "pixel-serve-server";
241
+ ```
189
242
 
190
- | Error Condition | Fallback Behavior |
191
- | ----------------------------- | ------------------------------- |
192
- | Invalid local path | Returns a fallback image. |
193
- | Unsupported network domain | Returns a fallback image. |
194
- | Invalid or missing parameters | Defaults to placeholder values. |
243
+ ## Module Formats
244
+
245
+ ```typescript
246
+ // ESM
247
+ import { registerServe } from "pixel-serve-server";
248
+
249
+ // CommonJS
250
+ const { registerServe } = require("pixel-serve-server");
251
+ ```
195
252
 
196
- ### Dependencies
253
+ ## Requirements
197
254
 
198
- This package uses the following dependencies:
255
+ - Node.js >= 18
256
+ - Express 5.x (peer dependency)
199
257
 
200
- - **Express**: HTTP server framework.
201
- - **Sharp**: High-performance image processing.
202
- - **Axios**: HTTP client for fetching network images.
258
+ ## Dependencies
203
259
 
204
- ---
260
+ - **Sharp**: High-performance image processing
261
+ - **Axios**: HTTP client for fetching network images
262
+ - **Zod**: Runtime validation for options and query params
205
263
 
206
- ### License
264
+ ## License
207
265
 
208
- This package is licensed under the [MIT License](LICENSE).
266
+ MIT
209
267
 
210
- ### Feedback
268
+ ## Contributing
211
269
 
212
- If you encounter issues or have suggestions, feel free to open an [issue](https://github.com/Hiprax/pixel-serve-server/issues).
270
+ Issues and pull requests are welcome at [GitHub](https://github.com/Hiprax/pixel-serve-server).
package/dist/index.d.mts CHANGED
@@ -1,20 +1,30 @@
1
1
  import { Request, Response, NextFunction } from 'express';
2
+ import { z } from 'zod';
2
3
 
3
4
  type ImageType = "avatar" | "normal";
4
5
  type ImageFormat = "jpeg" | "jpg" | "png" | "webp" | "gif" | "tiff" | "avif" | "svg";
5
- type Options = {
6
+ type PixelServeOptions = {
6
7
  baseDir: string;
7
8
  idHandler?: (id: string) => string;
8
- getUserFolder?: (req: Request, id?: string | undefined) => Promise<string>;
9
+ getUserFolder?: (req: Request, id?: string) => Promise<string> | string;
9
10
  websiteURL?: string;
10
11
  apiRegex?: RegExp;
11
12
  allowedNetworkList?: string[];
13
+ cacheControl?: string;
14
+ etag?: boolean;
15
+ minWidth?: number;
16
+ maxWidth?: number;
17
+ minHeight?: number;
18
+ maxHeight?: number;
19
+ defaultQuality?: number;
20
+ requestTimeoutMs?: number;
21
+ maxDownloadBytes?: number;
12
22
  };
13
23
  type UserData = {
14
- quality: number | string;
15
- format: ImageFormat;
16
- src?: string;
17
- folder?: string;
24
+ src: string;
25
+ quality?: number | string;
26
+ format?: ImageFormat;
27
+ folder?: "public" | "private";
18
28
  type?: ImageType;
19
29
  userId?: string;
20
30
  width?: number | string;
@@ -24,10 +34,44 @@ type UserData = {
24
34
  /**
25
35
  * @function registerServe
26
36
  * @description A function to register the serveImage function as middleware for Express.
27
- * @param {Options} options - The options object for image processing.
37
+ * @param {PixelServeOptions} options - The options object for image processing.
28
38
  * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.
29
39
  */
30
- declare const registerServe: (options: Options) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
40
+ declare const registerServe: (options: PixelServeOptions) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
41
+
42
+ declare const userDataSchema: z.ZodObject<{
43
+ src: z.ZodDefault<z.ZodOptional<z.ZodString>>;
44
+ format: z.ZodOptional<z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>>;
45
+ width: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>, z.ZodTransform<number | undefined, string | number | undefined>>, z.ZodOptional<z.ZodNumber>>;
46
+ height: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>, z.ZodTransform<number | undefined, string | number | undefined>>, z.ZodOptional<z.ZodNumber>>;
47
+ quality: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>, z.ZodTransform<number | undefined, string | number | undefined>>, z.ZodDefault<z.ZodNumber>>;
48
+ folder: z.ZodDefault<z.ZodEnum<{
49
+ public: "public";
50
+ private: "private";
51
+ }>>;
52
+ type: z.ZodDefault<z.ZodEnum<{
53
+ avatar: "avatar";
54
+ normal: "normal";
55
+ }>>;
56
+ userId: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>, z.ZodTransform<string | undefined, string | number | undefined>>, z.ZodOptional<z.ZodString>>;
57
+ }, z.core.$strict>;
58
+ declare const optionsSchema: z.ZodObject<{
59
+ baseDir: z.ZodString;
60
+ idHandler: z.ZodOptional<z.ZodCustom<(id: string) => string, (id: string) => string>>;
61
+ getUserFolder: z.ZodOptional<z.ZodCustom<(req: unknown, id?: string) => Promise<string> | string, (req: unknown, id?: string) => Promise<string> | string>>;
62
+ websiteURL: z.ZodOptional<z.ZodUnion<readonly [z.ZodURL, z.ZodString]>>;
63
+ apiRegex: z.ZodDefault<z.ZodCustom<RegExp, RegExp>>;
64
+ allowedNetworkList: z.ZodDefault<z.ZodArray<z.ZodString>>;
65
+ cacheControl: z.ZodOptional<z.ZodString>;
66
+ etag: z.ZodDefault<z.ZodBoolean>;
67
+ minWidth: z.ZodDefault<z.ZodNumber>;
68
+ maxWidth: z.ZodDefault<z.ZodNumber>;
69
+ minHeight: z.ZodDefault<z.ZodNumber>;
70
+ maxHeight: z.ZodDefault<z.ZodNumber>;
71
+ defaultQuality: z.ZodDefault<z.ZodNumber>;
72
+ requestTimeoutMs: z.ZodDefault<z.ZodNumber>;
73
+ maxDownloadBytes: z.ZodDefault<z.ZodNumber>;
74
+ }, z.core.$strict>;
31
75
 
32
76
  /**
33
77
  * @typedef {("avatar" | "normal")} ImageType
@@ -38,8 +82,8 @@ declare const registerServe: (options: Options) => (req: Request, res: Response,
38
82
  *
39
83
  * @param {string} basePath - The base directory to resolve paths.
40
84
  * @param {string} specifiedPath - The path to check.
41
- * @returns {boolean} True if the path is valid, false otherwise.
85
+ * @returns {Promise<boolean>} True if the path is valid, false otherwise.
42
86
  */
43
87
  declare const isValidPath: (basePath: string, specifiedPath: string) => Promise<boolean>;
44
88
 
45
- export { type ImageFormat, type ImageType, type Options, type UserData, isValidPath, registerServe };
89
+ export { type ImageFormat, type ImageType, type PixelServeOptions, type UserData, isValidPath, optionsSchema, registerServe, userDataSchema };
package/dist/index.d.ts CHANGED
@@ -1,20 +1,30 @@
1
1
  import { Request, Response, NextFunction } from 'express';
2
+ import { z } from 'zod';
2
3
 
3
4
  type ImageType = "avatar" | "normal";
4
5
  type ImageFormat = "jpeg" | "jpg" | "png" | "webp" | "gif" | "tiff" | "avif" | "svg";
5
- type Options = {
6
+ type PixelServeOptions = {
6
7
  baseDir: string;
7
8
  idHandler?: (id: string) => string;
8
- getUserFolder?: (req: Request, id?: string | undefined) => Promise<string>;
9
+ getUserFolder?: (req: Request, id?: string) => Promise<string> | string;
9
10
  websiteURL?: string;
10
11
  apiRegex?: RegExp;
11
12
  allowedNetworkList?: string[];
13
+ cacheControl?: string;
14
+ etag?: boolean;
15
+ minWidth?: number;
16
+ maxWidth?: number;
17
+ minHeight?: number;
18
+ maxHeight?: number;
19
+ defaultQuality?: number;
20
+ requestTimeoutMs?: number;
21
+ maxDownloadBytes?: number;
12
22
  };
13
23
  type UserData = {
14
- quality: number | string;
15
- format: ImageFormat;
16
- src?: string;
17
- folder?: string;
24
+ src: string;
25
+ quality?: number | string;
26
+ format?: ImageFormat;
27
+ folder?: "public" | "private";
18
28
  type?: ImageType;
19
29
  userId?: string;
20
30
  width?: number | string;
@@ -24,10 +34,44 @@ type UserData = {
24
34
  /**
25
35
  * @function registerServe
26
36
  * @description A function to register the serveImage function as middleware for Express.
27
- * @param {Options} options - The options object for image processing.
37
+ * @param {PixelServeOptions} options - The options object for image processing.
28
38
  * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.
29
39
  */
30
- declare const registerServe: (options: Options) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
40
+ declare const registerServe: (options: PixelServeOptions) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
41
+
42
+ declare const userDataSchema: z.ZodObject<{
43
+ src: z.ZodDefault<z.ZodOptional<z.ZodString>>;
44
+ format: z.ZodOptional<z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<string | undefined, string | undefined>>>;
45
+ width: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>, z.ZodTransform<number | undefined, string | number | undefined>>, z.ZodOptional<z.ZodNumber>>;
46
+ height: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>, z.ZodTransform<number | undefined, string | number | undefined>>, z.ZodOptional<z.ZodNumber>>;
47
+ quality: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>, z.ZodTransform<number | undefined, string | number | undefined>>, z.ZodDefault<z.ZodNumber>>;
48
+ folder: z.ZodDefault<z.ZodEnum<{
49
+ public: "public";
50
+ private: "private";
51
+ }>>;
52
+ type: z.ZodDefault<z.ZodEnum<{
53
+ avatar: "avatar";
54
+ normal: "normal";
55
+ }>>;
56
+ userId: z.ZodPipe<z.ZodPipe<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>, z.ZodTransform<string | undefined, string | number | undefined>>, z.ZodOptional<z.ZodString>>;
57
+ }, z.core.$strict>;
58
+ declare const optionsSchema: z.ZodObject<{
59
+ baseDir: z.ZodString;
60
+ idHandler: z.ZodOptional<z.ZodCustom<(id: string) => string, (id: string) => string>>;
61
+ getUserFolder: z.ZodOptional<z.ZodCustom<(req: unknown, id?: string) => Promise<string> | string, (req: unknown, id?: string) => Promise<string> | string>>;
62
+ websiteURL: z.ZodOptional<z.ZodUnion<readonly [z.ZodURL, z.ZodString]>>;
63
+ apiRegex: z.ZodDefault<z.ZodCustom<RegExp, RegExp>>;
64
+ allowedNetworkList: z.ZodDefault<z.ZodArray<z.ZodString>>;
65
+ cacheControl: z.ZodOptional<z.ZodString>;
66
+ etag: z.ZodDefault<z.ZodBoolean>;
67
+ minWidth: z.ZodDefault<z.ZodNumber>;
68
+ maxWidth: z.ZodDefault<z.ZodNumber>;
69
+ minHeight: z.ZodDefault<z.ZodNumber>;
70
+ maxHeight: z.ZodDefault<z.ZodNumber>;
71
+ defaultQuality: z.ZodDefault<z.ZodNumber>;
72
+ requestTimeoutMs: z.ZodDefault<z.ZodNumber>;
73
+ maxDownloadBytes: z.ZodDefault<z.ZodNumber>;
74
+ }, z.core.$strict>;
31
75
 
32
76
  /**
33
77
  * @typedef {("avatar" | "normal")} ImageType
@@ -38,8 +82,8 @@ declare const registerServe: (options: Options) => (req: Request, res: Response,
38
82
  *
39
83
  * @param {string} basePath - The base directory to resolve paths.
40
84
  * @param {string} specifiedPath - The path to check.
41
- * @returns {boolean} True if the path is valid, false otherwise.
85
+ * @returns {Promise<boolean>} True if the path is valid, false otherwise.
42
86
  */
43
87
  declare const isValidPath: (basePath: string, specifiedPath: string) => Promise<boolean>;
44
88
 
45
- export { type ImageFormat, type ImageType, type Options, type UserData, isValidPath, registerServe };
89
+ export { type ImageFormat, type ImageType, type PixelServeOptions, type UserData, isValidPath, optionsSchema, registerServe, userDataSchema };
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
- "use strict";var D=Object.create;var h=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var P=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty;var _=(e,r)=>{for(var a in r)h(e,a,{get:r[a],enumerable:!0})},U=(e,r,a,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of S(r))!B.call(e,t)&&t!==a&&h(e,t,{get:()=>r[t],enumerable:!(s=M(r,t))||s.enumerable});return e};var y=(e,r,a)=>(a=e!=null?D(P(e)):{},U(r||!e||!e.__esModule?h(a,"default",{value:e,enumerable:!0}):a,e)),C=e=>U(h({},"__esModule",{value:!0}),e);var W={};_(W,{isValidPath:()=>R,registerServe:()=>A});module.exports=C(W);var z=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,m=z();var F=y(require("path")),v=y(require("sharp"));var x=require("fs/promises"),G=new URL("./assets/noimage.jpg",m).pathname,$=new URL("./assets/noavatar.png",m).pathname,c={normal:async()=>(0,x.readFile)(G),avatar:async()=>(0,x.readFile)($)},w=/^\/api\/v1\//,O=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],I={jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",tiff:"image/tiff",avif:"image/avif",svg:"image/svg+xml"};var o=y(require("path")),g=y(require("fs/promises")),L=y(require("axios"));var R=async(e,r)=>{try{if(!e||!r||r.includes("\0")||o.default.isAbsolute(r)||!/^[^\x00-\x1F]+$/.test(r))return!1;let a=o.default.resolve(e),s=o.default.resolve(a,r),[t,i]=await Promise.all([g.realpath(a),g.realpath(s)]);if(!(await g.stat(t)).isDirectory())return!1;let f=t+o.default.sep,u=(i+o.default.sep).startsWith(f)||i===t,d=o.default.relative(t,i);return!d.startsWith("..")&&!o.default.isAbsolute(d)&&u}catch{return!1}},k=async(e,r="normal")=>{try{let a=await L.default.get(e,{responseType:"arraybuffer",timeout:5e3}),s=a.headers["content-type"]?.toLowerCase();return Object.values(I).includes(s??"")?Buffer.from(a.data):await c[r]()}catch{return await c[r]()}},b=async(e,r,a="normal")=>{if(!await R(r,e))return await c[a]();try{return await g.readFile(o.default.resolve(r,e))}catch{return await c[a]()}},T=(e,r,a,s="normal",t=w,i=[])=>{let n=new URL(e);if([a,`www.${a}`].includes(n.host)){let p=n.pathname.replace(t,"");return b(p,r,s)}else return i.includes(n.host)?k(e,s):c[s]()};var j=e=>({...{baseDir:"",idHandler:a=>a,getUserFolder:async()=>"",websiteURL:"",apiRegex:w,allowedNetworkList:[]},...e}),N=e=>({...{quality:80,format:"jpeg",src:"/placeholder/noimage.jpg",folder:"public",type:"normal",width:void 0,height:void 0,userId:void 0},...e,quality:e.quality?Math.min(Math.max(Number(e.quality)||80,1),100):100,width:e.width?Math.min(Math.max(Number(e.width),50),2e3):void 0,height:e.height?Math.min(Math.max(Number(e.height),50),2e3):void 0});var H=async(e,r,a,s)=>{try{let t=N(e.query),i=j(s),n,f=i.baseDir,p;if(t.userId){let l=typeof t.userId=="object"?String(Object.values(t.userId)[0]):String(t.userId);i.idHandler?p=i.idHandler(l):p=l}if(t.folder==="private"){let l=await i?.getUserFolder?.(e,p);l&&(f=l)}let u=O.includes(t?.format?.toLowerCase())?t?.format?.toLowerCase():"jpeg";t?.src?.startsWith("http")?n=await T(t?.src??"",f,i?.websiteURL??"",t?.type,i?.apiRegex,i?.allowedNetworkList):n=await b(t?.src??"",f,t?.type);let d=(0,v.default)(n);if(t?.width||t?.height){let l={width:t?.width??void 0,height:t?.height??void 0,fit:v.default.fit.cover};d=d.resize(l)}let q=await d.toFormat(u,{quality:t?.quality?Number(t?.quality):80}).toBuffer(),E=`${F.default.basename(t?.src??"",F.default.extname(t?.src??""))}.${u}`;r.type(I[u]),r.setHeader("Content-Disposition",`inline; filename="${E}"`),r.send(q)}catch(t){a(t)}},V=e=>async(r,a,s)=>H(r,a,s,e),A=V;0&&(module.exports={isValidPath,registerServe});
1
+ 'use strict';var l=require('path'),crypto=require('crypto'),O=require('sharp'),f=require('fs/promises'),url=require('url'),q=require('axios'),zod=require('zod');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var l__default=/*#__PURE__*/_interopDefault(l);var O__default=/*#__PURE__*/_interopDefault(O);var f__namespace=/*#__PURE__*/_interopNamespace(f);var q__default=/*#__PURE__*/_interopDefault(q);var A=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,d=A();var N=l__default.default.dirname(url.fileURLToPath(d)),D=e=>l__default.default.join(N,"assets",e),M=D("noimage.jpg"),W=D("noavatar.png"),s={normal:async()=>f.readFile(M),avatar:async()=>f.readFile(W)},T=/^\/api\/v1\//,b=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],h={jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",tiff:"image/tiff",avif:"image/avif",svg:"image/svg+xml"};var U=async(e,r)=>{try{if(!e||!r||r.includes("\0")||l__default.default.isAbsolute(r)||!/^[^\x00-\x1F]+$/.test(r))return !1;let i=l__default.default.resolve(e),o=l__default.default.resolve(i,r),[a,n]=await Promise.all([f__namespace.realpath(i),f__namespace.realpath(o)]);if(!(await f__namespace.stat(a)).isDirectory())return !1;let u=a+l__default.default.sep,I=(n+l__default.default.sep).startsWith(u)||n===a,c=l__default.default.relative(a,n);return !c.startsWith("..")&&!l__default.default.isAbsolute(c)&&I}catch{return false}},z=async(e,r="normal",{timeoutMs:i,maxBytes:o})=>{try{let a=await q__default.default.get(e,{responseType:"arraybuffer",timeout:i,maxContentLength:o,maxBodyLength:o,validateStatus:u=>u>=200&&u<300}),n=a.headers["content-type"]?.toLowerCase();return Object.values(h).includes(n??"")?Buffer.from(a.data):await s[r]()}catch{return await s[r]()}},w=async(e,r,i="normal")=>{if(!await U(r,e))return await s[i]();try{return await f__namespace.readFile(l__default.default.resolve(r,e))}catch{return await s[i]()}},B=(e,r,i,o="normal",a,n=[],{timeoutMs:m,maxBytes:u})=>{try{let p=new URL(e);if(i!==void 0&&[i,`www.${i}`].includes(p.host)){let g=p.pathname.replace(a,"");return w(g,r,o)}return n.includes(p.host)?["http:","https:"].includes(p.protocol)?z(e,o,{timeoutMs:m,maxBytes:u}):s[o]():s[o]()}catch{return w(e,r,o)}};var _=zod.z.enum(b),k=zod.z.enum(["avatar","normal"]),F=zod.z.object({src:zod.z.string().min(1,"src is required").optional().default("/placeholder/noimage.jpg"),format:zod.z.string().optional().transform(e=>{let r=e?.toLowerCase();return r&&_.options.includes(r)?r:void 0}).optional(),width:zod.z.union([zod.z.number(),zod.z.string()]).optional().transform(e=>e==null?void 0:Number(e)).pipe(zod.z.number().int().min(50,"width too small").max(4e3,"width too large").optional()),height:zod.z.union([zod.z.number(),zod.z.string()]).optional().transform(e=>e==null?void 0:Number(e)).pipe(zod.z.number().int().min(50,"height too small").max(4e3,"height too large").optional()),quality:zod.z.union([zod.z.number(),zod.z.string()]).optional().transform(e=>e==null?void 0:Number(e)).pipe(zod.z.number().int().min(1).max(100).default(80)),folder:zod.z.enum(["public","private"]).default("public"),type:k.default("normal"),userId:zod.z.union([zod.z.string(),zod.z.number()]).optional().transform(e=>e==null?void 0:String(e).trim()).pipe(zod.z.string().min(1,"userId cannot be empty").max(128,"userId too long").optional())}).strict(),P=zod.z.object({baseDir:zod.z.string().min(1,"baseDir is required"),idHandler:zod.z.custom(e=>typeof e=="function",{message:"idHandler must be a function"}).optional(),getUserFolder:zod.z.custom(e=>typeof e=="function",{message:"getUserFolder must be a function"}).optional(),websiteURL:zod.z.union([zod.z.url(),zod.z.string().regex(/^[\w.-]+$/)]).optional(),apiRegex:zod.z.instanceof(RegExp).default(T),allowedNetworkList:zod.z.array(zod.z.string()).default([]),cacheControl:zod.z.string().optional(),etag:zod.z.boolean().default(true),minWidth:zod.z.number().int().positive().default(50),maxWidth:zod.z.number().int().positive().default(4e3),minHeight:zod.z.number().int().positive().default(50),maxHeight:zod.z.number().int().positive().default(4e3),defaultQuality:zod.z.number().int().min(1).max(100).default(80),requestTimeoutMs:zod.z.number().int().positive().default(5e3),maxDownloadBytes:zod.z.number().int().positive().default(5e6)}).strict();var H=e=>P.parse(e),C=(e,r)=>{let i=F.parse(e),o=(a,n,m)=>{if(a!==void 0)return Math.min(Math.max(a,n),m)};return {...i,width:o(i.width,r.minWidth,r.maxWidth),height:o(i.height,r.minHeight,r.maxHeight),quality:i.quality??r.defaultQuality,format:i.format??"jpeg"}};var G=async(e,r,i,o)=>{try{let a=H(o),n=C(e.query,{minWidth:a.minWidth,maxWidth:a.maxWidth,minHeight:a.minHeight,maxHeight:a.maxHeight,defaultQuality:a.defaultQuality}),m=a.baseDir,u;if(n.userId&&(u=a.idHandler?a.idHandler(n.userId):n.userId),n.folder==="private"&&a.getUserFolder){let x=await a.getUserFolder(e,u);x&&(m=x);}let p=b.includes((n.format??"").toLowerCase())?n.format:"jpeg",c=await(async()=>n.src?n.src.startsWith("http")?B(n.src,m,a.websiteURL,n.type,a.apiRegex,a.allowedNetworkList,{timeoutMs:a.requestTimeoutMs,maxBytes:a.maxDownloadBytes}):w(n.src,m,n.type):s[n.type??"normal"]())(),g=O__default.default(c,{failOn:"truncated"});if(n.width||n.height){let x={width:n.width??void 0,height:n.height??void 0,fit:O__default.default.fit.cover,withoutEnlargement:!0};g=g.resize(x);}let v=await g.rotate().toFormat(p,{quality:n.quality}).toBuffer(),E=`${n.src?l__default.default.basename(n.src,l__default.default.extname(n.src)):"image"}.${p}`,y=a.etag?`"${crypto.createHash("sha1").update(v).digest("hex")}"`:void 0;if(y&&e.headers["if-none-match"]===y){r.status(304).end();return}r.type(h[p]),r.setHeader("Content-Disposition",`inline; filename="${E}"`),r.setHeader("Cache-Control",a.cacheControl??"public, max-age=86400, stale-while-revalidate=604800"),y&&r.setHeader("ETag",y),r.setHeader("Content-Length",v.length.toString()),r.send(v);}catch{try{let n=await s.normal();r.type(h.jpeg),r.setHeader("Content-Disposition",'inline; filename="fallback.jpeg"'),r.setHeader("Cache-Control","public, max-age=60"),r.send(n);}catch(n){i(n);}}},Q=e=>async(r,i,o)=>G(r,i,o,e),V=Q;
2
+ exports.isValidPath=U;exports.optionsSchema=P;exports.registerServe=V;exports.userDataSchema=F;//# sourceMappingURL=index.js.map
2
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../node_modules/tsup/assets/cjs_shims.js","../src/pixel.ts","../src/variables.ts","../src/functions.ts","../src/renders.ts"],"sourcesContent":["/**\r\n * @module ImageService\r\n * @description A module to serve, process, and manage image delivery for web applications.\r\n */\r\n\r\nexport { default as registerServe } from \"./pixel\";\r\nexport * from \"./types\";\r\nexport { isValidPath } from \"./functions\";\r\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import path from \"node:path\";\r\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\r\nimport type { Request, Response, NextFunction } from \"express\";\r\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\r\nimport { allowedFormats, mimeTypes } from \"./variables\";\r\nimport { fetchImage, readLocalImage } from \"./functions\";\r\nimport { renderOptions, renderUserData } from \"./renders\";\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @function serveImage\r\n * @description Processes and serves an image based on user data and options.\r\n * @param {Request} req - The Express request object.\r\n * @param {Response} res - The Express response object.\r\n * @param {NextFunction} next - The Express next function.\r\n * @param {Options} options - The options object for image processing.\r\n * @returns {Promise<void>}\r\n */\r\nconst serveImage = async (\r\n req: Request,\r\n res: Response,\r\n next: NextFunction,\r\n options: Options\r\n) => {\r\n try {\r\n const userData = renderUserData(req.query as UserData);\r\n const parsedOptions = renderOptions(options);\r\n\r\n let imageBuffer;\r\n let baseDir = parsedOptions.baseDir;\r\n let parsedUserId;\r\n\r\n if (userData.userId) {\r\n const userIdStr =\r\n typeof userData.userId === \"object\"\r\n ? String(Object.values(userData.userId)[0])\r\n : String(userData.userId);\r\n if (parsedOptions.idHandler) {\r\n parsedUserId = parsedOptions.idHandler(userIdStr);\r\n } else {\r\n parsedUserId = userIdStr;\r\n }\r\n }\r\n\r\n if (userData.folder === \"private\") {\r\n const dir = await parsedOptions?.getUserFolder?.(req, parsedUserId);\r\n if (dir) {\r\n baseDir = dir;\r\n }\r\n }\r\n\r\n const outputFormat = allowedFormats.includes(\r\n userData?.format?.toLowerCase() as ImageFormat\r\n )\r\n ? userData?.format?.toLowerCase()\r\n : \"jpeg\";\r\n\r\n if (userData?.src?.startsWith(\"http\")) {\r\n imageBuffer = await fetchImage(\r\n userData?.src ?? \"\",\r\n baseDir,\r\n parsedOptions?.websiteURL ?? \"\",\r\n userData?.type as ImageType,\r\n parsedOptions?.apiRegex,\r\n parsedOptions?.allowedNetworkList\r\n );\r\n } else {\r\n imageBuffer = await readLocalImage(\r\n userData?.src ?? \"\",\r\n baseDir,\r\n userData?.type as ImageType\r\n );\r\n }\r\n\r\n let image = sharp(imageBuffer);\r\n\r\n if (userData?.width || userData?.height) {\r\n const resizeOptions = {\r\n width: userData?.width ?? undefined,\r\n height: userData?.height ?? undefined,\r\n fit: sharp.fit.cover,\r\n };\r\n image = image.resize(resizeOptions as ResizeOptions);\r\n }\r\n\r\n const processedImage = await image\r\n .toFormat(outputFormat as keyof FormatEnum, {\r\n quality: userData?.quality ? Number(userData?.quality) : 80,\r\n })\r\n .toBuffer();\r\n\r\n const processedFileName = `${path.basename(\r\n userData?.src ?? \"\",\r\n path.extname(userData?.src ?? \"\")\r\n )}.${outputFormat}`;\r\n\r\n res.type(mimeTypes[outputFormat]);\r\n res.setHeader(\r\n \"Content-Disposition\",\r\n `inline; filename=\"${processedFileName}\"`\r\n );\r\n res.send(processedImage);\r\n } catch (error) {\r\n next(error);\r\n }\r\n};\r\n\r\n/**\r\n * @function registerServe\r\n * @description A function to register the serveImage function as middleware for Express.\r\n * @param {Options} options - The options object for image processing.\r\n * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.\r\n */\r\nconst registerServe = (options: Options) => {\r\n return async (req: Request, res: Response, next: NextFunction) =>\r\n serveImage(req, res, next, options);\r\n};\r\n\r\nexport default registerServe;\r\n","import type { ImageFormat } from \"./types\";\r\nimport { readFile } from \"node:fs/promises\";\r\n\r\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url)\r\n .pathname;\r\n\r\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url)\r\n .pathname;\r\n\r\nexport const FALLBACKIMAGES = {\r\n normal: async () => readFile(NOT_FOUND_IMAGE),\r\n avatar: async () => readFile(NOT_FOUND_AVATAR),\r\n};\r\n\r\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\r\n\r\nexport const allowedFormats: ImageFormat[] = [\r\n \"jpeg\",\r\n \"jpg\",\r\n \"png\",\r\n \"webp\",\r\n \"gif\",\r\n \"tiff\",\r\n \"avif\",\r\n \"svg\",\r\n];\r\n\r\nexport const mimeTypes: Readonly<Record<string, string>> = {\r\n jpeg: \"image/jpeg\",\r\n jpg: \"image/jpeg\",\r\n png: \"image/png\",\r\n webp: \"image/webp\",\r\n gif: \"image/gif\",\r\n tiff: \"image/tiff\",\r\n avif: \"image/avif\",\r\n svg: \"image/svg+xml\",\r\n};\r\n","import path from \"node:path\";\r\nimport * as fs from \"node:fs/promises\";\r\nimport axios from \"axios\";\r\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\r\nimport type { ImageType } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * Checks if a specified path is valid within a base path.\r\n *\r\n * @param {string} basePath - The base directory to resolve paths.\r\n * @param {string} specifiedPath - The path to check.\r\n * @returns {boolean} True if the path is valid, false otherwise.\r\n */\r\nexport const isValidPath = async (\r\n basePath: string,\r\n specifiedPath: string\r\n): Promise<boolean> => {\r\n try {\r\n if (!basePath || !specifiedPath) return false;\r\n if (specifiedPath.includes(\"\\0\")) return false;\r\n if (path.isAbsolute(specifiedPath)) return false;\r\n if (!/^[^\\x00-\\x1F]+$/.test(specifiedPath)) return false;\r\n\r\n const resolvedBase = path.resolve(basePath);\r\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\r\n\r\n const [realBase, realPath] = await Promise.all([\r\n fs.realpath(resolvedBase),\r\n fs.realpath(resolvedPath),\r\n ]);\r\n\r\n const baseStats = await fs.stat(realBase);\r\n if (!baseStats.isDirectory()) return false;\r\n\r\n const normalizedBase = realBase + path.sep;\r\n const normalizedPath = realPath + path.sep;\r\n\r\n const isInside =\r\n normalizedPath.startsWith(normalizedBase) || realPath === realBase;\r\n\r\n const relative = path.relative(realBase, realPath);\r\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative) && isInside;\r\n } catch {\r\n return false;\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from a network source.\r\n *\r\n * @param {string} src - The URL of the image.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nconst fetchFromNetwork = async (\r\n src: string,\r\n type: ImageType = \"normal\"\r\n): Promise<Buffer> => {\r\n try {\r\n const response = await axios.get(src, {\r\n responseType: \"arraybuffer\",\r\n timeout: 5000,\r\n });\r\n\r\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\r\n const allowedMimeTypes = Object.values(mimeTypes);\r\n\r\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\r\n return Buffer.from(response.data);\r\n }\r\n return await FALLBACKIMAGES[type]();\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Reads an image from the local file system.\r\n *\r\n * @param {string} filePath - Path to the image file.\r\n * @param {string} baseDir - Base directory to resolve paths.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @returns {Promise<Buffer>} A buffer containing the image data.\r\n */\r\nexport const readLocalImage = async (\r\n filePath: string,\r\n baseDir: string,\r\n type: ImageType = \"normal\"\r\n) => {\r\n const isValid = await isValidPath(baseDir, filePath);\r\n if (!isValid) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n try {\r\n return await fs.readFile(path.resolve(baseDir, filePath));\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from either a local file or a network source.\r\n *\r\n * @param {string} src - The URL or local path of the image.\r\n * @param {string} baseDir - Base directory to resolve local paths.\r\n * @param {string} websiteURL - The URL of the website.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\r\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nexport const fetchImage = (\r\n src: string,\r\n baseDir: string,\r\n websiteURL: string,\r\n type: ImageType = \"normal\",\r\n apiRegex: RegExp = API_REGEX,\r\n allowedNetworkList: string[] = []\r\n) => {\r\n const url = new URL(src);\r\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\r\n if (isInternal) {\r\n const localPath = url.pathname.replace(apiRegex, \"\");\r\n return readLocalImage(localPath, baseDir, type);\r\n } else {\r\n const allowedCondition = allowedNetworkList.includes(url.host);\r\n if (!allowedCondition) {\r\n return FALLBACKIMAGES[type]();\r\n }\r\n return fetchFromNetwork(src, type);\r\n }\r\n};\r\n","import { API_REGEX } from \"./variables\";\r\nimport type { Options, UserData } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\r\n * @description Supported formats for image processing.\r\n */\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @typedef {Object} UserData\r\n * @property {number|string} quality - Quality of the image (1–100).\r\n * @property {ImageFormat} format - Desired format of the image.\r\n * @property {string} [src] - Source path or URL for the image.\r\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\r\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\r\n * @property {string|null} [userId] - Optional user identifier.\r\n * @property {number|string} [width] - Desired image width.\r\n * @property {number|string} [height] - Desired image height.\r\n */\r\n\r\n/**\r\n * Renders the options object with default values and user-provided values.\r\n *\r\n * @param {Partial<Options>} options - The user-provided options.\r\n * @returns {Options} The rendered options object.\r\n */\r\nexport const renderOptions = (options: Partial<Options>): Options => {\r\n const initialOptions: Options = {\r\n baseDir: \"\",\r\n idHandler: (id: string) => id,\r\n getUserFolder: async () => \"\",\r\n websiteURL: \"\",\r\n apiRegex: API_REGEX,\r\n allowedNetworkList: [],\r\n };\r\n return {\r\n ...initialOptions,\r\n ...options,\r\n };\r\n};\r\n\r\n/**\r\n * Renders the user data object with default values and user-provided values.\r\n *\r\n * @param {Partial<UserData>} userData - The user-provided data.\r\n * @returns {UserData} The rendered user data object.\r\n */\r\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\r\n const initialUserData: UserData = {\r\n quality: 80,\r\n format: \"jpeg\",\r\n src: \"/placeholder/noimage.jpg\",\r\n folder: \"public\",\r\n type: \"normal\",\r\n width: undefined,\r\n height: undefined,\r\n userId: undefined,\r\n };\r\n return {\r\n ...initialUserData,\r\n ...userData,\r\n quality: userData.quality\r\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\r\n : 100,\r\n width: userData.width\r\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\r\n : undefined,\r\n height: userData.height\r\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\r\n : undefined,\r\n };\r\n};\r\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,kBAAAC,IAAA,eAAAC,EAAAJ,GCKA,IAAMK,EAAmB,IACvB,OAAO,SAAa,IAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,KAC7B,SAAS,eAAiB,SAAS,cAAc,KAClD,IAAI,IAAI,UAAW,SAAS,OAAO,EAAE,KAE9BC,EAAgCD,EAAiB,ECX9D,IAAAE,EAAiB,mBACjBC,EAAiD,oBCAjD,IAAAC,EAAyB,uBAEnBC,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AOf,GAAU,OAAS,OAC1B,OAAQA,GAAU,QAAU,OAC5B,IAAK,EAAAc,QAAM,IAAI,KACjB,EACAD,EAAQA,EAAM,OAAOE,CAA8B,CACrD,CAEA,IAAMC,EAAiB,MAAMH,EAC1B,SAASJ,EAAkC,CAC1C,QAAST,GAAU,QAAU,OAAOA,GAAU,OAAO,EAAI,EAC3D,CAAC,EACA,SAAS,EAENiB,EAAoB,GAAG,EAAAC,QAAK,SAChClB,GAAU,KAAO,GACjB,EAAAkB,QAAK,QAAQlB,GAAU,KAAO,EAAE,CAClC,CAAC,IAAIS,CAAY,GAEjBZ,EAAI,KAAKsB,EAAUV,CAAY,CAAC,EAChCZ,EAAI,UACF,sBACA,qBAAqBoB,CAAiB,GACxC,EACApB,EAAI,KAAKmB,CAAc,CACzB,OAASI,EAAO,CACdtB,EAAKsB,CAAK,CACZ,CACF,EAQMC,EAAiBtB,GACd,MAAOH,EAAcC,EAAeC,IACzCH,EAAWC,EAAKC,EAAKC,EAAMC,CAAO,EAG/BuB,EAAQD","names":["index_exports","__export","isValidPath","pixel_default","__toCommonJS","getImportMetaUrl","importMetaUrl","import_node_path","import_sharp","import_promises","NOT_FOUND_IMAGE","importMetaUrl","NOT_FOUND_AVATAR","FALLBACKIMAGES","API_REGEX","allowedFormats","mimeTypes","import_node_path","fs","import_axios","isValidPath","basePath","specifiedPath","path","resolvedBase","resolvedPath","realBase","realPath","normalizedBase","isInside","relative","fetchFromNetwork","src","type","response","axios","contentType","mimeTypes","FALLBACKIMAGES","readLocalImage","filePath","baseDir","fetchImage","websiteURL","apiRegex","API_REGEX","allowedNetworkList","url","localPath","renderOptions","options","id","API_REGEX","renderUserData","userData","serveImage","req","res","next","options","userData","renderUserData","parsedOptions","renderOptions","imageBuffer","baseDir","parsedUserId","userIdStr","dir","outputFormat","allowedFormats","fetchImage","readLocalImage","image","sharp","resizeOptions","processedImage","processedFileName","path","mimeTypes","error","registerServe","pixel_default"]}
1
+ {"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/variables.ts","../src/functions.ts","../src/schema.ts","../src/renders.ts","../src/pixel.ts"],"names":["getImportMetaUrl","importMetaUrl","moduleDir","path","fileURLToPath","getAssetPath","filename","NOT_FOUND_IMAGE","NOT_FOUND_AVATAR","FALLBACKIMAGES","readFile","API_REGEX","allowedFormats","mimeTypes","isValidPath","basePath","specifiedPath","resolvedBase","resolvedPath","realBase","realPath","f","normalizedBase","isInside","relative","fetchFromNetwork","src","type","timeoutMs","maxBytes","response","axios","status","contentType","readLocalImage","filePath","baseDir","fetchImage","websiteURL","apiRegex","allowedNetworkList","url","localPath","imageFormatEnum","z","imageTypeEnum","userDataSchema","val","lower","value","optionsSchema","renderOptions","options","renderUserData","userData","bounds","parsed","clamp","min","max","serveImage","req","res","next","parsedOptions","parsedUserId","dir","outputFormat","imageBuffer","image","sharp","resizeOptions","processedImage","processedFileName","etag","createHash","fallback","fallbackError","registerServe","pixel_default"],"mappings":"qtBAKA,IAAMA,CAAAA,CAAmB,IACvB,OAAO,QAAA,CAAa,IAChB,IAAI,GAAA,CAAI,CAAA,KAAA,EAAQ,UAAU,EAAE,CAAA,CAAE,IAAA,CAC7B,QAAA,CAAS,aAAA,EAAiB,SAAS,aAAA,CAAc,OAAA,CAAQ,WAAA,EAAY,GAAM,SAC1E,QAAA,CAAS,aAAA,CAAc,GAAA,CACvB,IAAI,IAAI,SAAA,CAAW,QAAA,CAAS,OAAO,CAAA,CAAE,KAEhCC,CAAAA,CAAgCD,CAAAA,EAAiB,CCH9D,IAAME,CAAAA,CAAYC,kBAAAA,CAAK,OAAA,CAAQC,kBAAcH,CAAe,CAAC,CAAA,CAEvDI,CAAAA,CAAgBC,GACbH,kBAAAA,CAAK,IAAA,CAAKD,CAAAA,CAAW,QAAA,CAAUI,CAAQ,CAAA,CAG1CC,CAAAA,CAAkBF,CAAAA,CAAa,aAAa,EAC5CG,CAAAA,CAAmBH,CAAAA,CAAa,cAAc,CAAA,CAEvCI,CAAAA,CAGT,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CAAAA,CAAW,MAAMnE,CAAAA,CAAe,MAAA,GACtCqD,CAAAA,CAAI,IAAA,CAAKjD,CAAAA,CAAU,IAAI,EACvBiD,CAAAA,CAAI,SAAA,CAAU,qBAAA,CAAuB,kCAAkC,EACvEA,CAAAA,CAAI,SAAA,CAAU,eAAA,CAAiB,oBAAoB,EACnDA,CAAAA,CAAI,IAAA,CAAKc,CAAQ,EACnB,OAASC,CAAAA,CAAe,CACtBd,CAAAA,CAAKc,CAAa,EACpB,CACF,CACF,CAAA,CAQMC,CAAAA,CAAiB1B,GACd,MAAOS,CAAAA,CAAcC,CAAAA,CAAeC,CAAAA,GACzCH,EAAWC,CAAAA,CAAKC,CAAAA,CAAKC,CAAAA,CAAMX,CAAO,EAG/B2B,CAAAA,CAAQD","file":"index.js","sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import type { ImageFormat } from \"./types\";\r\nimport { readFile } from \"node:fs/promises\";\r\nimport path from \"node:path\";\r\nimport { fileURLToPath } from \"node:url\";\r\n\r\n/**\r\n * Get the directory path for the current module.\r\n * Uses import.meta.url for ESM (tsup provides shims for CJS compatibility).\r\n */\r\nconst moduleDir = path.dirname(fileURLToPath(import.meta.url));\r\n\r\nconst getAssetPath = (filename: string): string => {\r\n return path.join(moduleDir, \"assets\", filename);\r\n};\r\n\r\nconst NOT_FOUND_IMAGE = getAssetPath(\"noimage.jpg\");\r\nconst NOT_FOUND_AVATAR = getAssetPath(\"noavatar.png\");\r\n\r\nexport const FALLBACKIMAGES: Record<\r\n \"normal\" | \"avatar\",\r\n () => Promise<Buffer>\r\n> = {\r\n normal: async (): Promise<Buffer> => readFile(NOT_FOUND_IMAGE),\r\n avatar: async (): Promise<Buffer> => readFile(NOT_FOUND_AVATAR),\r\n};\r\n\r\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\r\n\r\nexport const allowedFormats: ImageFormat[] = [\r\n \"jpeg\",\r\n \"jpg\",\r\n \"png\",\r\n \"webp\",\r\n \"gif\",\r\n \"tiff\",\r\n \"avif\",\r\n \"svg\",\r\n];\r\n\r\nexport const mimeTypes: Readonly<Record<string, string>> = {\r\n jpeg: \"image/jpeg\",\r\n jpg: \"image/jpeg\",\r\n png: \"image/png\",\r\n webp: \"image/webp\",\r\n gif: \"image/gif\",\r\n tiff: \"image/tiff\",\r\n avif: \"image/avif\",\r\n svg: \"image/svg+xml\",\r\n};\r\n","import path from \"node:path\";\r\nimport * as fs from \"node:fs/promises\";\r\nimport axios from \"axios\";\r\nimport { FALLBACKIMAGES, mimeTypes } from \"./variables\";\r\nimport type { ImageType } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * Checks if a specified path is valid within a base path.\r\n *\r\n * @param {string} basePath - The base directory to resolve paths.\r\n * @param {string} specifiedPath - The path to check.\r\n * @returns {Promise<boolean>} True if the path is valid, false otherwise.\r\n */\r\nexport const isValidPath = async (\r\n basePath: string,\r\n specifiedPath: string\r\n): Promise<boolean> => {\r\n try {\r\n if (!basePath || !specifiedPath) return false;\r\n if (specifiedPath.includes(\"\\0\")) return false;\r\n if (path.isAbsolute(specifiedPath)) return false;\r\n if (!/^[^\\x00-\\x1F]+$/.test(specifiedPath)) return false;\r\n\r\n const resolvedBase = path.resolve(basePath);\r\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\r\n\r\n const [realBase, realPath] = await Promise.all([\r\n fs.realpath(resolvedBase),\r\n fs.realpath(resolvedPath),\r\n ]);\r\n\r\n const baseStats = await fs.stat(realBase);\r\n if (!baseStats.isDirectory()) return false;\r\n\r\n const normalizedBase = realBase + path.sep;\r\n const normalizedPath = realPath + path.sep;\r\n\r\n const isInside =\r\n normalizedPath.startsWith(normalizedBase) || realPath === realBase;\r\n\r\n const relative = path.relative(realBase, realPath);\r\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative) && isInside;\r\n } catch {\r\n return false;\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from a network source.\r\n *\r\n * @param {string} src - The URL of the image.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nconst fetchFromNetwork = async (\r\n src: string,\r\n type: ImageType = \"normal\",\r\n {\r\n timeoutMs,\r\n maxBytes,\r\n }: {\r\n timeoutMs: number;\r\n maxBytes: number;\r\n }\r\n): Promise<Buffer> => {\r\n try {\r\n const response = await axios.get(src, {\r\n responseType: \"arraybuffer\",\r\n timeout: timeoutMs,\r\n maxContentLength: maxBytes,\r\n maxBodyLength: maxBytes,\r\n validateStatus: (status) => status >= 200 && status < 300,\r\n });\r\n\r\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\r\n const allowedMimeTypes = Object.values(mimeTypes);\r\n\r\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\r\n return Buffer.from(response.data);\r\n }\r\n return await FALLBACKIMAGES[type]();\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Reads an image from the local file system.\r\n *\r\n * @param {string} filePath - Path to the image file.\r\n * @param {string} baseDir - Base directory to resolve paths.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @returns {Promise<Buffer>} A buffer containing the image data.\r\n */\r\nexport const readLocalImage = async (\r\n filePath: string,\r\n baseDir: string,\r\n type: ImageType = \"normal\"\r\n) => {\r\n const isValid = await isValidPath(baseDir, filePath);\r\n if (!isValid) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n try {\r\n return await fs.readFile(path.resolve(baseDir, filePath));\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from either a local file or a network source.\r\n *\r\n * @param {string} src - The URL or local path of the image.\r\n * @param {string} baseDir - Base directory to resolve local paths.\r\n * @param {string} websiteURL - The URL of the website.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nexport const fetchImage = (\r\n src: string,\r\n baseDir: string,\r\n websiteURL: string | undefined,\r\n type: ImageType = \"normal\",\r\n apiRegex: RegExp,\r\n allowedNetworkList: string[] = [],\r\n {\r\n timeoutMs,\r\n maxBytes,\r\n }: {\r\n timeoutMs: number;\r\n maxBytes: number;\r\n }\r\n): Promise<Buffer> => {\r\n try {\r\n const url = new URL(src);\r\n const isInternal =\r\n websiteURL !== undefined &&\r\n [websiteURL, `www.${websiteURL}`].includes(url.host);\r\n\r\n if (isInternal) {\r\n const localPath = url.pathname.replace(apiRegex, \"\");\r\n return readLocalImage(localPath, baseDir, type);\r\n }\r\n\r\n const allowedCondition = allowedNetworkList.includes(url.host);\r\n if (!allowedCondition) {\r\n return FALLBACKIMAGES[type]();\r\n }\r\n if (![\"http:\", \"https:\"].includes(url.protocol)) {\r\n return FALLBACKIMAGES[type]();\r\n }\r\n return fetchFromNetwork(src, type, { timeoutMs, maxBytes });\r\n } catch {\r\n return readLocalImage(src, baseDir, type);\r\n }\r\n};\r\n","import { z } from \"zod\";\r\nimport { API_REGEX, allowedFormats } from \"./variables\";\r\n\r\nconst imageFormatEnum = z.enum(allowedFormats as [string, ...string[]]);\r\nconst imageTypeEnum = z.enum([\"avatar\", \"normal\"]);\r\n\r\nexport const userDataSchema = z\r\n .object({\r\n src: z\r\n .string()\r\n .min(1, \"src is required\")\r\n .optional()\r\n .default(\"/placeholder/noimage.jpg\"),\r\n format: z\r\n .string()\r\n .optional()\r\n .transform((val) => {\r\n const lower = val?.toLowerCase();\r\n return lower && imageFormatEnum.options.includes(lower as string)\r\n ? (lower as (typeof imageFormatEnum)[\"options\"][number])\r\n : undefined;\r\n })\r\n .optional(),\r\n width: z\r\n .union([z.number(), z.string()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : Number(value)\r\n )\r\n .pipe(\r\n z\r\n .number()\r\n .int()\r\n .min(50, \"width too small\")\r\n .max(4000, \"width too large\")\r\n .optional()\r\n ),\r\n height: z\r\n .union([z.number(), z.string()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : Number(value)\r\n )\r\n .pipe(\r\n z\r\n .number()\r\n .int()\r\n .min(50, \"height too small\")\r\n .max(4000, \"height too large\")\r\n .optional()\r\n ),\r\n quality: z\r\n .union([z.number(), z.string()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : Number(value)\r\n )\r\n .pipe(z.number().int().min(1).max(100).default(80)),\r\n folder: z.enum([\"public\", \"private\"]).default(\"public\"),\r\n type: imageTypeEnum.default(\"normal\"),\r\n userId: z\r\n .union([z.string(), z.number()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : String(value).trim()\r\n )\r\n .pipe(\r\n z\r\n .string()\r\n .min(1, \"userId cannot be empty\")\r\n .max(128, \"userId too long\")\r\n .optional()\r\n ),\r\n })\r\n .strict();\r\n\r\nexport const optionsSchema = z\r\n .object({\r\n baseDir: z.string().min(1, \"baseDir is required\"),\r\n idHandler: z\r\n .custom<\r\n (id: string) => string\r\n >((val) => typeof val === \"function\", { message: \"idHandler must be a function\" })\r\n .optional(),\r\n getUserFolder: z\r\n .custom<\r\n (req: unknown, id?: string) => Promise<string> | string\r\n >((val) => typeof val === \"function\", { message: \"getUserFolder must be a function\" })\r\n .optional(),\r\n websiteURL: z.union([z.url(), z.string().regex(/^[\\w.-]+$/)]).optional(),\r\n apiRegex: z.instanceof(RegExp).default(API_REGEX),\r\n allowedNetworkList: z.array(z.string()).default([]),\r\n cacheControl: z.string().optional(),\r\n etag: z.boolean().default(true),\r\n minWidth: z.number().int().positive().default(50),\r\n maxWidth: z.number().int().positive().default(4000),\r\n minHeight: z.number().int().positive().default(50),\r\n maxHeight: z.number().int().positive().default(4000),\r\n defaultQuality: z.number().int().min(1).max(100).default(80),\r\n requestTimeoutMs: z.number().int().positive().default(5000),\r\n maxDownloadBytes: z.number().int().positive().default(5_000_000),\r\n })\r\n .strict();\r\n\r\nexport type ParsedUserData = z.infer<typeof userDataSchema>;\r\nexport type ParsedOptions = z.infer<typeof optionsSchema>;\r\n","import { optionsSchema, userDataSchema } from \"./schema\";\r\nimport type { ParsedOptions, ParsedUserData } from \"./schema\";\r\nimport type { PixelServeOptions, UserData } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\r\n * @description Supported formats for image processing.\r\n */\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @typedef {Object} UserData\r\n * @property {number|string} quality - Quality of the image (1–100).\r\n * @property {ImageFormat} format - Desired format of the image.\r\n * @property {string} [src] - Source path or URL for the image.\r\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\r\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\r\n * @property {string|null} [userId] - Optional user identifier.\r\n * @property {number|string} [width] - Desired image width.\r\n * @property {number|string} [height] - Desired image height.\r\n */\r\n\r\n/**\r\n * Renders the options object with default values and user-provided values.\r\n *\r\n * @param {Partial<Options>} options - The user-provided options.\r\n * @returns {Options} The rendered options object.\r\n */\r\nexport const renderOptions = (options: PixelServeOptions): ParsedOptions =>\r\n optionsSchema.parse(options);\r\n\r\n/**\r\n * Renders the user data object with default values and user-provided values.\r\n *\r\n * @param {Partial<UserData>} userData - The user-provided data.\r\n * @returns {UserData} The rendered user data object.\r\n */\r\nexport const renderUserData = (\r\n userData: Partial<UserData>,\r\n bounds: {\r\n minWidth: number;\r\n maxWidth: number;\r\n minHeight: number;\r\n maxHeight: number;\r\n defaultQuality: number;\r\n }\r\n): ParsedUserData => {\r\n const parsed = userDataSchema.parse(userData);\r\n\r\n const clamp = (value: number | undefined, min: number, max: number) => {\r\n if (value === undefined) return undefined;\r\n return Math.min(Math.max(value, min), max);\r\n };\r\n\r\n return {\r\n ...parsed,\r\n width: clamp(parsed.width, bounds.minWidth, bounds.maxWidth),\r\n height: clamp(parsed.height, bounds.minHeight, bounds.maxHeight),\r\n quality: parsed.quality ?? bounds.defaultQuality,\r\n format: parsed.format ?? \"jpeg\",\r\n };\r\n};\r\n","import path from \"node:path\";\r\nimport { createHash } from \"node:crypto\";\r\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\r\nimport type { Request, Response, NextFunction } from \"express\";\r\nimport type {\r\n PixelServeOptions,\r\n UserData,\r\n ImageFormat,\r\n ImageType,\r\n} from \"./types\";\r\nimport { allowedFormats, FALLBACKIMAGES, mimeTypes } from \"./variables\";\r\nimport { fetchImage, readLocalImage } from \"./functions\";\r\nimport { renderOptions, renderUserData } from \"./renders\";\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @function serveImage\r\n * @description Processes and serves an image based on user data and options.\r\n * @param {Request} req - The Express request object.\r\n * @param {Response} res - The Express response object.\r\n * @param {NextFunction} next - The Express next function.\r\n * @param {PixelServeOptions} options - The options object for image processing.\r\n * @returns {Promise<void>}\r\n */\r\nconst serveImage = async (\r\n req: Request,\r\n res: Response,\r\n next: NextFunction,\r\n options: PixelServeOptions\r\n) => {\r\n try {\r\n const parsedOptions = renderOptions(options);\r\n const userData = renderUserData(req.query as Partial<UserData>, {\r\n minWidth: parsedOptions.minWidth,\r\n maxWidth: parsedOptions.maxWidth,\r\n minHeight: parsedOptions.minHeight,\r\n maxHeight: parsedOptions.maxHeight,\r\n defaultQuality: parsedOptions.defaultQuality,\r\n });\r\n\r\n let baseDir = parsedOptions.baseDir;\r\n let parsedUserId: string | undefined;\r\n\r\n if (userData.userId) {\r\n parsedUserId = parsedOptions.idHandler\r\n ? parsedOptions.idHandler(userData.userId)\r\n : userData.userId;\r\n }\r\n\r\n if (userData.folder === \"private\" && parsedOptions.getUserFolder) {\r\n const dir = await parsedOptions.getUserFolder(req, parsedUserId);\r\n if (dir) {\r\n baseDir = dir;\r\n }\r\n }\r\n\r\n const outputFormat = allowedFormats.includes(\r\n (userData.format ?? \"\").toLowerCase() as ImageFormat\r\n )\r\n ? (userData.format as ImageFormat)\r\n : \"jpeg\";\r\n\r\n const resolveBuffer = async (): Promise<Buffer> => {\r\n if (!userData.src) {\r\n return FALLBACKIMAGES[userData.type ?? \"normal\"]();\r\n }\r\n if (userData.src.startsWith(\"http\")) {\r\n return fetchImage(\r\n userData.src,\r\n baseDir,\r\n parsedOptions.websiteURL,\r\n userData.type as ImageType,\r\n parsedOptions.apiRegex,\r\n parsedOptions.allowedNetworkList,\r\n {\r\n timeoutMs: parsedOptions.requestTimeoutMs,\r\n maxBytes: parsedOptions.maxDownloadBytes,\r\n }\r\n );\r\n }\r\n return readLocalImage(userData.src, baseDir, userData.type as ImageType);\r\n };\r\n\r\n const imageBuffer = await resolveBuffer();\r\n let image = sharp(imageBuffer, { failOn: \"truncated\" });\r\n\r\n if (userData.width || userData.height) {\r\n const resizeOptions: ResizeOptions = {\r\n width: userData.width ?? undefined,\r\n height: userData.height ?? undefined,\r\n fit: sharp.fit.cover,\r\n withoutEnlargement: true,\r\n };\r\n image = image.resize(resizeOptions);\r\n }\r\n\r\n const processedImage = await image\r\n .rotate()\r\n .toFormat(outputFormat as keyof FormatEnum, {\r\n quality: userData.quality,\r\n })\r\n .toBuffer();\r\n\r\n const sourceName = userData.src\r\n ? path.basename(userData.src, path.extname(userData.src))\r\n : \"image\";\r\n const processedFileName = `${sourceName}.${outputFormat}`;\r\n\r\n const etag = parsedOptions.etag\r\n ? `\"${createHash(\"sha1\").update(processedImage).digest(\"hex\")}\"`\r\n : undefined;\r\n\r\n if (etag && req.headers[\"if-none-match\"] === etag) {\r\n res.status(304).end();\r\n return;\r\n }\r\n\r\n res.type(mimeTypes[outputFormat]);\r\n res.setHeader(\r\n \"Content-Disposition\",\r\n `inline; filename=\"${processedFileName}\"`\r\n );\r\n res.setHeader(\r\n \"Cache-Control\",\r\n parsedOptions.cacheControl ??\r\n \"public, max-age=86400, stale-while-revalidate=604800\"\r\n );\r\n if (etag) {\r\n res.setHeader(\"ETag\", etag);\r\n }\r\n res.setHeader(\"Content-Length\", processedImage.length.toString());\r\n res.send(processedImage);\r\n /* c8 ignore next */\r\n } catch (error) {\r\n try {\r\n const fallback = await FALLBACKIMAGES.normal();\r\n res.type(mimeTypes.jpeg);\r\n res.setHeader(\"Content-Disposition\", `inline; filename=\"fallback.jpeg\"`);\r\n res.setHeader(\"Cache-Control\", \"public, max-age=60\");\r\n res.send(fallback);\r\n } catch (fallbackError) {\r\n next(fallbackError);\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * @function registerServe\r\n * @description A function to register the serveImage function as middleware for Express.\r\n * @param {PixelServeOptions} options - The options object for image processing.\r\n * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.\r\n */\r\nconst registerServe = (options: PixelServeOptions) => {\r\n return async (req: Request, res: Response, next: NextFunction) =>\r\n serveImage(req, res, next, options);\r\n};\r\n\r\nexport default registerServe;\r\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,3 @@
1
- import U from"node:path";import T from"sharp";import{readFile as x}from"node:fs/promises";var j=new URL("./assets/noimage.jpg",import.meta.url).pathname,A=new URL("./assets/noavatar.png",import.meta.url).pathname,d={normal:async()=>x(j),avatar:async()=>x(A)},h=/^\/api\/v1\//,F=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],w={jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",tiff:"image/tiff",avif:"image/avif",svg:"image/svg+xml"};import n from"node:path";import*as l from"node:fs/promises";import q from"axios";var R=async(t,r)=>{try{if(!t||!r||r.includes("\0")||n.isAbsolute(r)||!/^[^\x00-\x1F]+$/.test(r))return!1;let a=n.resolve(t),i=n.resolve(a,r),[e,s]=await Promise.all([l.realpath(a),l.realpath(i)]);if(!(await l.stat(e)).isDirectory())return!1;let g=e+n.sep,c=(s+n.sep).startsWith(g)||s===e,f=n.relative(e,s);return!f.startsWith("..")&&!n.isAbsolute(f)&&c}catch{return!1}},E=async(t,r="normal")=>{try{let a=await q.get(t,{responseType:"arraybuffer",timeout:5e3}),i=a.headers["content-type"]?.toLowerCase();return Object.values(w).includes(i??"")?Buffer.from(a.data):await d[r]()}catch{return await d[r]()}},I=async(t,r,a="normal")=>{if(!await R(r,t))return await d[a]();try{return await l.readFile(n.resolve(r,t))}catch{return await d[a]()}},b=(t,r,a,i="normal",e=h,s=[])=>{let o=new URL(t);if([a,`www.${a}`].includes(o.host)){let m=o.pathname.replace(e,"");return I(m,r,i)}else return s.includes(o.host)?E(t,i):d[i]()};var v=t=>({...{baseDir:"",idHandler:a=>a,getUserFolder:async()=>"",websiteURL:"",apiRegex:h,allowedNetworkList:[]},...t}),O=t=>({...{quality:80,format:"jpeg",src:"/placeholder/noimage.jpg",folder:"public",type:"normal",width:void 0,height:void 0,userId:void 0},...t,quality:t.quality?Math.min(Math.max(Number(t.quality)||80,1),100):100,width:t.width?Math.min(Math.max(Number(t.width),50),2e3):void 0,height:t.height?Math.min(Math.max(Number(t.height),50),2e3):void 0});var D=async(t,r,a,i)=>{try{let e=O(t.query),s=v(i),o,g=s.baseDir,m;if(e.userId){let p=typeof e.userId=="object"?String(Object.values(e.userId)[0]):String(e.userId);s.idHandler?m=s.idHandler(p):m=p}if(e.folder==="private"){let p=await s?.getUserFolder?.(t,m);p&&(g=p)}let c=F.includes(e?.format?.toLowerCase())?e?.format?.toLowerCase():"jpeg";e?.src?.startsWith("http")?o=await b(e?.src??"",g,s?.websiteURL??"",e?.type,s?.apiRegex,s?.allowedNetworkList):o=await I(e?.src??"",g,e?.type);let f=T(o);if(e?.width||e?.height){let p={width:e?.width??void 0,height:e?.height??void 0,fit:T.fit.cover};f=f.resize(p)}let L=await f.toFormat(c,{quality:e?.quality?Number(e?.quality):80}).toBuffer(),N=`${U.basename(e?.src??"",U.extname(e?.src??""))}.${c}`;r.type(w[c]),r.setHeader("Content-Disposition",`inline; filename="${N}"`),r.send(L)}catch(e){a(e)}},M=t=>async(r,a,i)=>D(r,a,i,t),P=M;export{R as isValidPath,P as registerServe};
1
+ import p from'path';import {createHash}from'crypto';import L from'sharp';import*as d from'fs/promises';import {readFile}from'fs/promises';import {fileURLToPath}from'url';import q from'axios';import {z as z$1}from'zod';var N=p.dirname(fileURLToPath(import.meta.url)),T=e=>p.join(N,"assets",e),M=T("noimage.jpg"),W=T("noavatar.png"),s={normal:async()=>readFile(M),avatar:async()=>readFile(W)},H=/^\/api\/v1\//,w=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],y={jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",tiff:"image/tiff",avif:"image/avif",svg:"image/svg+xml"};var R=async(e,r)=>{try{if(!e||!r||r.includes("\0")||p.isAbsolute(r)||!/^[^\x00-\x1F]+$/.test(r))return !1;let i=p.resolve(e),o=p.resolve(i,r),[n,a]=await Promise.all([d.realpath(i),d.realpath(o)]);if(!(await d.stat(n)).isDirectory())return !1;let u=n+p.sep,v=(a+p.sep).startsWith(u)||a===n,f=p.relative(n,a);return !f.startsWith("..")&&!p.isAbsolute(f)&&v}catch{return false}},z=async(e,r="normal",{timeoutMs:i,maxBytes:o})=>{try{let n=await q.get(e,{responseType:"arraybuffer",timeout:i,maxContentLength:o,maxBodyLength:o,validateStatus:u=>u>=200&&u<300}),a=n.headers["content-type"]?.toLowerCase();return Object.values(y).includes(a??"")?Buffer.from(n.data):await s[r]()}catch{return await s[r]()}},I=async(e,r,i="normal")=>{if(!await R(r,e))return await s[i]();try{return await d.readFile(p.resolve(r,e))}catch{return await s[i]()}},O=(e,r,i,o="normal",n,a=[],{timeoutMs:m,maxBytes:u})=>{try{let l=new URL(e);if(i!==void 0&&[i,`www.${i}`].includes(l.host)){let c=l.pathname.replace(n,"");return I(c,r,o)}return a.includes(l.host)?["http:","https:"].includes(l.protocol)?z(e,o,{timeoutMs:m,maxBytes:u}):s[o]():s[o]()}catch{return I(e,r,o)}};var k=z$1.enum(w),_=z$1.enum(["avatar","normal"]),P=z$1.object({src:z$1.string().min(1,"src is required").optional().default("/placeholder/noimage.jpg"),format:z$1.string().optional().transform(e=>{let r=e?.toLowerCase();return r&&k.options.includes(r)?r:void 0}).optional(),width:z$1.union([z$1.number(),z$1.string()]).optional().transform(e=>e==null?void 0:Number(e)).pipe(z$1.number().int().min(50,"width too small").max(4e3,"width too large").optional()),height:z$1.union([z$1.number(),z$1.string()]).optional().transform(e=>e==null?void 0:Number(e)).pipe(z$1.number().int().min(50,"height too small").max(4e3,"height too large").optional()),quality:z$1.union([z$1.number(),z$1.string()]).optional().transform(e=>e==null?void 0:Number(e)).pipe(z$1.number().int().min(1).max(100).default(80)),folder:z$1.enum(["public","private"]).default("public"),type:_.default("normal"),userId:z$1.union([z$1.string(),z$1.number()]).optional().transform(e=>e==null?void 0:String(e).trim()).pipe(z$1.string().min(1,"userId cannot be empty").max(128,"userId too long").optional())}).strict(),D=z$1.object({baseDir:z$1.string().min(1,"baseDir is required"),idHandler:z$1.custom(e=>typeof e=="function",{message:"idHandler must be a function"}).optional(),getUserFolder:z$1.custom(e=>typeof e=="function",{message:"getUserFolder must be a function"}).optional(),websiteURL:z$1.union([z$1.url(),z$1.string().regex(/^[\w.-]+$/)]).optional(),apiRegex:z$1.instanceof(RegExp).default(H),allowedNetworkList:z$1.array(z$1.string()).default([]),cacheControl:z$1.string().optional(),etag:z$1.boolean().default(true),minWidth:z$1.number().int().positive().default(50),maxWidth:z$1.number().int().positive().default(4e3),minHeight:z$1.number().int().positive().default(50),maxHeight:z$1.number().int().positive().default(4e3),defaultQuality:z$1.number().int().min(1).max(100).default(80),requestTimeoutMs:z$1.number().int().positive().default(5e3),maxDownloadBytes:z$1.number().int().positive().default(5e6)}).strict();var E=e=>D.parse(e),A=(e,r)=>{let i=P.parse(e),o=(n,a,m)=>{if(n!==void 0)return Math.min(Math.max(n,a),m)};return {...i,width:o(i.width,r.minWidth,r.maxWidth),height:o(i.height,r.minHeight,r.maxHeight),quality:i.quality??r.defaultQuality,format:i.format??"jpeg"}};var G=async(e,r,i,o)=>{try{let n=E(o),a=A(e.query,{minWidth:n.minWidth,maxWidth:n.maxWidth,minHeight:n.minHeight,maxHeight:n.maxHeight,defaultQuality:n.defaultQuality}),m=n.baseDir,u;if(a.userId&&(u=n.idHandler?n.idHandler(a.userId):a.userId),a.folder==="private"&&n.getUserFolder){let b=await n.getUserFolder(e,u);b&&(m=b);}let l=w.includes((a.format??"").toLowerCase())?a.format:"jpeg",f=await(async()=>a.src?a.src.startsWith("http")?O(a.src,m,n.websiteURL,a.type,n.apiRegex,n.allowedNetworkList,{timeoutMs:n.requestTimeoutMs,maxBytes:n.maxDownloadBytes}):I(a.src,m,a.type):s[a.type??"normal"]())(),c=L(f,{failOn:"truncated"});if(a.width||a.height){let b={width:a.width??void 0,height:a.height??void 0,fit:L.fit.cover,withoutEnlargement:!0};c=c.resize(b);}let F=await c.rotate().toFormat(l,{quality:a.quality}).toBuffer(),U=`${a.src?p.basename(a.src,p.extname(a.src)):"image"}.${l}`,x=n.etag?`"${createHash("sha1").update(F).digest("hex")}"`:void 0;if(x&&e.headers["if-none-match"]===x){r.status(304).end();return}r.type(y[l]),r.setHeader("Content-Disposition",`inline; filename="${U}"`),r.setHeader("Cache-Control",n.cacheControl??"public, max-age=86400, stale-while-revalidate=604800"),x&&r.setHeader("ETag",x),r.setHeader("Content-Length",F.length.toString()),r.send(F);}catch{try{let a=await s.normal();r.type(y.jpeg),r.setHeader("Content-Disposition",'inline; filename="fallback.jpeg"'),r.setHeader("Cache-Control","public, max-age=60"),r.send(a);}catch(a){i(a);}}},Q=e=>async(r,i,o)=>G(r,i,o,e),V=Q;
2
+ export{R as isValidPath,D as optionsSchema,V as registerServe,P as userDataSchema};//# sourceMappingURL=index.mjs.map
2
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pixel.ts","../src/variables.ts","../src/functions.ts","../src/renders.ts"],"sourcesContent":["import path from \"node:path\";\r\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\r\nimport type { Request, Response, NextFunction } from \"express\";\r\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\r\nimport { allowedFormats, mimeTypes } from \"./variables\";\r\nimport { fetchImage, readLocalImage } from \"./functions\";\r\nimport { renderOptions, renderUserData } from \"./renders\";\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @function serveImage\r\n * @description Processes and serves an image based on user data and options.\r\n * @param {Request} req - The Express request object.\r\n * @param {Response} res - The Express response object.\r\n * @param {NextFunction} next - The Express next function.\r\n * @param {Options} options - The options object for image processing.\r\n * @returns {Promise<void>}\r\n */\r\nconst serveImage = async (\r\n req: Request,\r\n res: Response,\r\n next: NextFunction,\r\n options: Options\r\n) => {\r\n try {\r\n const userData = renderUserData(req.query as UserData);\r\n const parsedOptions = renderOptions(options);\r\n\r\n let imageBuffer;\r\n let baseDir = parsedOptions.baseDir;\r\n let parsedUserId;\r\n\r\n if (userData.userId) {\r\n const userIdStr =\r\n typeof userData.userId === \"object\"\r\n ? String(Object.values(userData.userId)[0])\r\n : String(userData.userId);\r\n if (parsedOptions.idHandler) {\r\n parsedUserId = parsedOptions.idHandler(userIdStr);\r\n } else {\r\n parsedUserId = userIdStr;\r\n }\r\n }\r\n\r\n if (userData.folder === \"private\") {\r\n const dir = await parsedOptions?.getUserFolder?.(req, parsedUserId);\r\n if (dir) {\r\n baseDir = dir;\r\n }\r\n }\r\n\r\n const outputFormat = allowedFormats.includes(\r\n userData?.format?.toLowerCase() as ImageFormat\r\n )\r\n ? userData?.format?.toLowerCase()\r\n : \"jpeg\";\r\n\r\n if (userData?.src?.startsWith(\"http\")) {\r\n imageBuffer = await fetchImage(\r\n userData?.src ?? \"\",\r\n baseDir,\r\n parsedOptions?.websiteURL ?? \"\",\r\n userData?.type as ImageType,\r\n parsedOptions?.apiRegex,\r\n parsedOptions?.allowedNetworkList\r\n );\r\n } else {\r\n imageBuffer = await readLocalImage(\r\n userData?.src ?? \"\",\r\n baseDir,\r\n userData?.type as ImageType\r\n );\r\n }\r\n\r\n let image = sharp(imageBuffer);\r\n\r\n if (userData?.width || userData?.height) {\r\n const resizeOptions = {\r\n width: userData?.width ?? undefined,\r\n height: userData?.height ?? undefined,\r\n fit: sharp.fit.cover,\r\n };\r\n image = image.resize(resizeOptions as ResizeOptions);\r\n }\r\n\r\n const processedImage = await image\r\n .toFormat(outputFormat as keyof FormatEnum, {\r\n quality: userData?.quality ? Number(userData?.quality) : 80,\r\n })\r\n .toBuffer();\r\n\r\n const processedFileName = `${path.basename(\r\n userData?.src ?? \"\",\r\n path.extname(userData?.src ?? \"\")\r\n )}.${outputFormat}`;\r\n\r\n res.type(mimeTypes[outputFormat]);\r\n res.setHeader(\r\n \"Content-Disposition\",\r\n `inline; filename=\"${processedFileName}\"`\r\n );\r\n res.send(processedImage);\r\n } catch (error) {\r\n next(error);\r\n }\r\n};\r\n\r\n/**\r\n * @function registerServe\r\n * @description A function to register the serveImage function as middleware for Express.\r\n * @param {Options} options - The options object for image processing.\r\n * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.\r\n */\r\nconst registerServe = (options: Options) => {\r\n return async (req: Request, res: Response, next: NextFunction) =>\r\n serveImage(req, res, next, options);\r\n};\r\n\r\nexport default registerServe;\r\n","import type { ImageFormat } from \"./types\";\r\nimport { readFile } from \"node:fs/promises\";\r\n\r\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url)\r\n .pathname;\r\n\r\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url)\r\n .pathname;\r\n\r\nexport const FALLBACKIMAGES = {\r\n normal: async () => readFile(NOT_FOUND_IMAGE),\r\n avatar: async () => readFile(NOT_FOUND_AVATAR),\r\n};\r\n\r\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\r\n\r\nexport const allowedFormats: ImageFormat[] = [\r\n \"jpeg\",\r\n \"jpg\",\r\n \"png\",\r\n \"webp\",\r\n \"gif\",\r\n \"tiff\",\r\n \"avif\",\r\n \"svg\",\r\n];\r\n\r\nexport const mimeTypes: Readonly<Record<string, string>> = {\r\n jpeg: \"image/jpeg\",\r\n jpg: \"image/jpeg\",\r\n png: \"image/png\",\r\n webp: \"image/webp\",\r\n gif: \"image/gif\",\r\n tiff: \"image/tiff\",\r\n avif: \"image/avif\",\r\n svg: \"image/svg+xml\",\r\n};\r\n","import path from \"node:path\";\r\nimport * as fs from \"node:fs/promises\";\r\nimport axios from \"axios\";\r\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\r\nimport type { ImageType } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * Checks if a specified path is valid within a base path.\r\n *\r\n * @param {string} basePath - The base directory to resolve paths.\r\n * @param {string} specifiedPath - The path to check.\r\n * @returns {boolean} True if the path is valid, false otherwise.\r\n */\r\nexport const isValidPath = async (\r\n basePath: string,\r\n specifiedPath: string\r\n): Promise<boolean> => {\r\n try {\r\n if (!basePath || !specifiedPath) return false;\r\n if (specifiedPath.includes(\"\\0\")) return false;\r\n if (path.isAbsolute(specifiedPath)) return false;\r\n if (!/^[^\\x00-\\x1F]+$/.test(specifiedPath)) return false;\r\n\r\n const resolvedBase = path.resolve(basePath);\r\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\r\n\r\n const [realBase, realPath] = await Promise.all([\r\n fs.realpath(resolvedBase),\r\n fs.realpath(resolvedPath),\r\n ]);\r\n\r\n const baseStats = await fs.stat(realBase);\r\n if (!baseStats.isDirectory()) return false;\r\n\r\n const normalizedBase = realBase + path.sep;\r\n const normalizedPath = realPath + path.sep;\r\n\r\n const isInside =\r\n normalizedPath.startsWith(normalizedBase) || realPath === realBase;\r\n\r\n const relative = path.relative(realBase, realPath);\r\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative) && isInside;\r\n } catch {\r\n return false;\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from a network source.\r\n *\r\n * @param {string} src - The URL of the image.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nconst fetchFromNetwork = async (\r\n src: string,\r\n type: ImageType = \"normal\"\r\n): Promise<Buffer> => {\r\n try {\r\n const response = await axios.get(src, {\r\n responseType: \"arraybuffer\",\r\n timeout: 5000,\r\n });\r\n\r\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\r\n const allowedMimeTypes = Object.values(mimeTypes);\r\n\r\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\r\n return Buffer.from(response.data);\r\n }\r\n return await FALLBACKIMAGES[type]();\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Reads an image from the local file system.\r\n *\r\n * @param {string} filePath - Path to the image file.\r\n * @param {string} baseDir - Base directory to resolve paths.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @returns {Promise<Buffer>} A buffer containing the image data.\r\n */\r\nexport const readLocalImage = async (\r\n filePath: string,\r\n baseDir: string,\r\n type: ImageType = \"normal\"\r\n) => {\r\n const isValid = await isValidPath(baseDir, filePath);\r\n if (!isValid) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n try {\r\n return await fs.readFile(path.resolve(baseDir, filePath));\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from either a local file or a network source.\r\n *\r\n * @param {string} src - The URL or local path of the image.\r\n * @param {string} baseDir - Base directory to resolve local paths.\r\n * @param {string} websiteURL - The URL of the website.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\r\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nexport const fetchImage = (\r\n src: string,\r\n baseDir: string,\r\n websiteURL: string,\r\n type: ImageType = \"normal\",\r\n apiRegex: RegExp = API_REGEX,\r\n allowedNetworkList: string[] = []\r\n) => {\r\n const url = new URL(src);\r\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\r\n if (isInternal) {\r\n const localPath = url.pathname.replace(apiRegex, \"\");\r\n return readLocalImage(localPath, baseDir, type);\r\n } else {\r\n const allowedCondition = allowedNetworkList.includes(url.host);\r\n if (!allowedCondition) {\r\n return FALLBACKIMAGES[type]();\r\n }\r\n return fetchFromNetwork(src, type);\r\n }\r\n};\r\n","import { API_REGEX } from \"./variables\";\r\nimport type { Options, UserData } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\r\n * @description Supported formats for image processing.\r\n */\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @typedef {Object} UserData\r\n * @property {number|string} quality - Quality of the image (1–100).\r\n * @property {ImageFormat} format - Desired format of the image.\r\n * @property {string} [src] - Source path or URL for the image.\r\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\r\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\r\n * @property {string|null} [userId] - Optional user identifier.\r\n * @property {number|string} [width] - Desired image width.\r\n * @property {number|string} [height] - Desired image height.\r\n */\r\n\r\n/**\r\n * Renders the options object with default values and user-provided values.\r\n *\r\n * @param {Partial<Options>} options - The user-provided options.\r\n * @returns {Options} The rendered options object.\r\n */\r\nexport const renderOptions = (options: Partial<Options>): Options => {\r\n const initialOptions: Options = {\r\n baseDir: \"\",\r\n idHandler: (id: string) => id,\r\n getUserFolder: async () => \"\",\r\n websiteURL: \"\",\r\n apiRegex: API_REGEX,\r\n allowedNetworkList: [],\r\n };\r\n return {\r\n ...initialOptions,\r\n ...options,\r\n };\r\n};\r\n\r\n/**\r\n * Renders the user data object with default values and user-provided values.\r\n *\r\n * @param {Partial<UserData>} userData - The user-provided data.\r\n * @returns {UserData} The rendered user data object.\r\n */\r\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\r\n const initialUserData: UserData = {\r\n quality: 80,\r\n format: \"jpeg\",\r\n src: \"/placeholder/noimage.jpg\",\r\n folder: \"public\",\r\n type: \"normal\",\r\n width: undefined,\r\n height: undefined,\r\n userId: undefined,\r\n };\r\n return {\r\n ...initialUserData,\r\n ...userData,\r\n quality: userData.quality\r\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\r\n : 100,\r\n width: userData.width\r\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\r\n : undefined,\r\n height: userData.height\r\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\r\n : undefined,\r\n };\r\n};\r\n"],"mappings":"AAAA,OAAOA,MAAU,YACjB,OAAOC,MAA0C,QCAjD,OAAS,YAAAC,MAAgB,mBAEzB,IAAMC,EAAkB,IAAI,IAAI,uBAAwB,YAAY,GAAG,EACpE,SAEGC,EAAmB,IAAI,IAAI,wBAAyB,YAAY,GAAG,EACtE,SAEUC,EAAiB,CAC5B,OAAQ,SAAYH,EAASC,CAAe,EAC5C,OAAQ,SAAYD,EAASE,CAAgB,CAC/C,EAEaE,EAAoB,eAEpBC,EAAgC,CAC3C,OACA,MACA,MACA,OACA,MACA,OACA,OACA,KACF,EAEaC,EAA8C,CACzD,KAAM,aACN,IAAK,aACL,IAAK,YACL,KAAM,aACN,IAAK,YACL,KAAM,aACN,KA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AChCZ,EAAI,UACF,sBACA,qBAAqBoB,CAAiB,GACxC,EACApB,EAAI,KAAKmB,CAAc,CACzB,OAASI,EAAO,CACdtB,EAAKsB,CAAK,CACZ,CACF,EAQMC,EAAiBtB,GACd,MAAOH,EAAcC,EAAeC,IACzCH,EAAWC,EAAKC,EAAKC,EAAMC,CAAO,EAG/BuB,EAAQD","names":["path","sharp","readFile","NOT_FOUND_IMAGE","NOT_FOUND_AVATAR","FALLBACKIMAGES","API_REGEX","allowedFormats","mimeTypes","path","fs","axios","isValidPath","basePath","specifiedPath","path","resolvedBase","resolvedPath","realBase","realPath","normalizedBase","isInside","relative","fetchFromNetwork","src","type","response","axios","contentType","mimeTypes","FALLBACKIMAGES","readLocalImage","filePath","baseDir","fetchImage","websiteURL","apiRegex","API_REGEX","allowedNetworkList","url","localPath","renderOptions","options","id","API_REGEX","renderUserData","userData","serveImage","req","res","next","options","userData","renderUserData","parsedOptions","renderOptions","imageBuffer","baseDir","parsedUserId","userIdStr","dir","outputFormat","allowedFormats","fetchImage","readLocalImage","image","sharp","resizeOptions","processedImage","processedFileName","path","mimeTypes","error","registerServe","pixel_default"]}
1
+ {"version":3,"sources":["../src/variables.ts","../src/functions.ts","../src/schema.ts","../src/renders.ts","../src/pixel.ts"],"names":["moduleDir","path","fileURLToPath","getAssetPath","filename","NOT_FOUND_IMAGE","NOT_FOUND_AVATAR","FALLBACKIMAGES","readFile","API_REGEX","allowedFormats","mimeTypes","isValidPath","basePath","specifiedPath","resolvedBase","resolvedPath","realBase","realPath","normalizedBase","isInside","relative","fetchFromNetwork","src","type","timeoutMs","maxBytes","response","axios","status","contentType","readLocalImage","filePath","baseDir","fetchImage","websiteURL","apiRegex","allowedNetworkList","url","localPath","imageFormatEnum","z","imageTypeEnum","userDataSchema","val","lower","value","optionsSchema","renderOptions","options","renderUserData","userData","bounds","parsed","clamp","min","max","serveImage","req","res","next","parsedOptions","parsedUserId","dir","outputFormat","imageBuffer","image","sharp","resizeOptions","processedImage","processed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A,EAAI,CACpB,MACF,CAEAA,EAAI,IAAA,CAAKhD,CAAAA,CAAUqD,CAAY,CAAC,EAChCL,CAAAA,CAAI,SAAA,CACF,qBAAA,CACA,CAAA,kBAAA,EAAqBW,CAAiB,CAAA,CAAA,CACxC,CAAA,CACAX,CAAAA,CAAI,SAAA,CACF,eAAA,CACAE,CAAAA,CAAc,YAAA,EACZ,sDACJ,EACIU,CAAAA,EACFZ,CAAAA,CAAI,SAAA,CAAU,MAAA,CAAQY,CAAI,CAAA,CAE5BZ,CAAAA,CAAI,SAAA,CAAU,gBAAA,CAAkBU,EAAe,MAAA,CAAO,QAAA,EAAU,CAAA,CAChEV,CAAAA,CAAI,IAAA,CAAKU,CAAc,EAEzB,MAAgB,CACd,GAAI,CACF,IAAMI,EAAW,MAAMlE,CAAAA,CAAe,MAAA,EAAO,CAC7CoD,EAAI,IAAA,CAAKhD,CAAAA,CAAU,IAAI,CAAA,CACvBgD,CAAAA,CAAI,SAAA,CAAU,qBAAA,CAAuB,kCAAkC,EACvEA,CAAAA,CAAI,SAAA,CAAU,eAAA,CAAiB,oBAAoB,EACnDA,CAAAA,CAAI,IAAA,CAAKc,CAAQ,EACnB,OAASC,CAAAA,CAAe,CACtBd,CAAAA,CAAKc,CAAa,EACpB,CACF,CACF,CAAA,CAQMC,CAAAA,CAAiB1B,GACd,MAAOS,CAAAA,CAAcC,CAAAA,CAAeC,CAAAA,GACzCH,EAAWC,CAAAA,CAAKC,CAAAA,CAAKC,CAAAA,CAAMX,CAAO,EAG/B2B,CAAAA,CAAQD","file":"index.mjs","sourcesContent":["import type { ImageFormat } from \"./types\";\r\nimport { readFile } from \"node:fs/promises\";\r\nimport path from \"node:path\";\r\nimport { fileURLToPath } from \"node:url\";\r\n\r\n/**\r\n * Get the directory path for the current module.\r\n * Uses import.meta.url for ESM (tsup provides shims for CJS compatibility).\r\n */\r\nconst moduleDir = path.dirname(fileURLToPath(import.meta.url));\r\n\r\nconst getAssetPath = (filename: string): string => {\r\n return path.join(moduleDir, \"assets\", filename);\r\n};\r\n\r\nconst NOT_FOUND_IMAGE = getAssetPath(\"noimage.jpg\");\r\nconst NOT_FOUND_AVATAR = getAssetPath(\"noavatar.png\");\r\n\r\nexport const FALLBACKIMAGES: Record<\r\n \"normal\" | \"avatar\",\r\n () => Promise<Buffer>\r\n> = {\r\n normal: async (): Promise<Buffer> => readFile(NOT_FOUND_IMAGE),\r\n avatar: async (): Promise<Buffer> => readFile(NOT_FOUND_AVATAR),\r\n};\r\n\r\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\r\n\r\nexport const allowedFormats: ImageFormat[] = [\r\n \"jpeg\",\r\n \"jpg\",\r\n \"png\",\r\n \"webp\",\r\n \"gif\",\r\n \"tiff\",\r\n \"avif\",\r\n \"svg\",\r\n];\r\n\r\nexport const mimeTypes: Readonly<Record<string, string>> = {\r\n jpeg: \"image/jpeg\",\r\n jpg: \"image/jpeg\",\r\n png: \"image/png\",\r\n webp: \"image/webp\",\r\n gif: \"image/gif\",\r\n tiff: \"image/tiff\",\r\n avif: \"image/avif\",\r\n svg: \"image/svg+xml\",\r\n};\r\n","import path from \"node:path\";\r\nimport * as fs from \"node:fs/promises\";\r\nimport axios from \"axios\";\r\nimport { FALLBACKIMAGES, mimeTypes } from \"./variables\";\r\nimport type { ImageType } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * Checks if a specified path is valid within a base path.\r\n *\r\n * @param {string} basePath - The base directory to resolve paths.\r\n * @param {string} specifiedPath - The path to check.\r\n * @returns {Promise<boolean>} True if the path is valid, false otherwise.\r\n */\r\nexport const isValidPath = async (\r\n basePath: string,\r\n specifiedPath: string\r\n): Promise<boolean> => {\r\n try {\r\n if (!basePath || !specifiedPath) return false;\r\n if (specifiedPath.includes(\"\\0\")) return false;\r\n if (path.isAbsolute(specifiedPath)) return false;\r\n if (!/^[^\\x00-\\x1F]+$/.test(specifiedPath)) return false;\r\n\r\n const resolvedBase = path.resolve(basePath);\r\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\r\n\r\n const [realBase, realPath] = await Promise.all([\r\n fs.realpath(resolvedBase),\r\n fs.realpath(resolvedPath),\r\n ]);\r\n\r\n const baseStats = await fs.stat(realBase);\r\n if (!baseStats.isDirectory()) return false;\r\n\r\n const normalizedBase = realBase + path.sep;\r\n const normalizedPath = realPath + path.sep;\r\n\r\n const isInside =\r\n normalizedPath.startsWith(normalizedBase) || realPath === realBase;\r\n\r\n const relative = path.relative(realBase, realPath);\r\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative) && isInside;\r\n } catch {\r\n return false;\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from a network source.\r\n *\r\n * @param {string} src - The URL of the image.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nconst fetchFromNetwork = async (\r\n src: string,\r\n type: ImageType = \"normal\",\r\n {\r\n timeoutMs,\r\n maxBytes,\r\n }: {\r\n timeoutMs: number;\r\n maxBytes: number;\r\n }\r\n): Promise<Buffer> => {\r\n try {\r\n const response = await axios.get(src, {\r\n responseType: \"arraybuffer\",\r\n timeout: timeoutMs,\r\n maxContentLength: maxBytes,\r\n maxBodyLength: maxBytes,\r\n validateStatus: (status) => status >= 200 && status < 300,\r\n });\r\n\r\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\r\n const allowedMimeTypes = Object.values(mimeTypes);\r\n\r\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\r\n return Buffer.from(response.data);\r\n }\r\n return await FALLBACKIMAGES[type]();\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Reads an image from the local file system.\r\n *\r\n * @param {string} filePath - Path to the image file.\r\n * @param {string} baseDir - Base directory to resolve paths.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @returns {Promise<Buffer>} A buffer containing the image data.\r\n */\r\nexport const readLocalImage = async (\r\n filePath: string,\r\n baseDir: string,\r\n type: ImageType = \"normal\"\r\n) => {\r\n const isValid = await isValidPath(baseDir, filePath);\r\n if (!isValid) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n try {\r\n return await fs.readFile(path.resolve(baseDir, filePath));\r\n } catch (error) {\r\n return await FALLBACKIMAGES[type]();\r\n }\r\n};\r\n\r\n/**\r\n * Fetches an image from either a local file or a network source.\r\n *\r\n * @param {string} src - The URL or local path of the image.\r\n * @param {string} baseDir - Base directory to resolve local paths.\r\n * @param {string} websiteURL - The URL of the website.\r\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\r\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\r\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\r\n */\r\nexport const fetchImage = (\r\n src: string,\r\n baseDir: string,\r\n websiteURL: string | undefined,\r\n type: ImageType = \"normal\",\r\n apiRegex: RegExp,\r\n allowedNetworkList: string[] = [],\r\n {\r\n timeoutMs,\r\n maxBytes,\r\n }: {\r\n timeoutMs: number;\r\n maxBytes: number;\r\n }\r\n): Promise<Buffer> => {\r\n try {\r\n const url = new URL(src);\r\n const isInternal =\r\n websiteURL !== undefined &&\r\n [websiteURL, `www.${websiteURL}`].includes(url.host);\r\n\r\n if (isInternal) {\r\n const localPath = url.pathname.replace(apiRegex, \"\");\r\n return readLocalImage(localPath, baseDir, type);\r\n }\r\n\r\n const allowedCondition = allowedNetworkList.includes(url.host);\r\n if (!allowedCondition) {\r\n return FALLBACKIMAGES[type]();\r\n }\r\n if (![\"http:\", \"https:\"].includes(url.protocol)) {\r\n return FALLBACKIMAGES[type]();\r\n }\r\n return fetchFromNetwork(src, type, { timeoutMs, maxBytes });\r\n } catch {\r\n return readLocalImage(src, baseDir, type);\r\n }\r\n};\r\n","import { z } from \"zod\";\r\nimport { API_REGEX, allowedFormats } from \"./variables\";\r\n\r\nconst imageFormatEnum = z.enum(allowedFormats as [string, ...string[]]);\r\nconst imageTypeEnum = z.enum([\"avatar\", \"normal\"]);\r\n\r\nexport const userDataSchema = z\r\n .object({\r\n src: z\r\n .string()\r\n .min(1, \"src is required\")\r\n .optional()\r\n .default(\"/placeholder/noimage.jpg\"),\r\n format: z\r\n .string()\r\n .optional()\r\n .transform((val) => {\r\n const lower = val?.toLowerCase();\r\n return lower && imageFormatEnum.options.includes(lower as string)\r\n ? (lower as (typeof imageFormatEnum)[\"options\"][number])\r\n : undefined;\r\n })\r\n .optional(),\r\n width: z\r\n .union([z.number(), z.string()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : Number(value)\r\n )\r\n .pipe(\r\n z\r\n .number()\r\n .int()\r\n .min(50, \"width too small\")\r\n .max(4000, \"width too large\")\r\n .optional()\r\n ),\r\n height: z\r\n .union([z.number(), z.string()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : Number(value)\r\n )\r\n .pipe(\r\n z\r\n .number()\r\n .int()\r\n .min(50, \"height too small\")\r\n .max(4000, \"height too large\")\r\n .optional()\r\n ),\r\n quality: z\r\n .union([z.number(), z.string()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : Number(value)\r\n )\r\n .pipe(z.number().int().min(1).max(100).default(80)),\r\n folder: z.enum([\"public\", \"private\"]).default(\"public\"),\r\n type: imageTypeEnum.default(\"normal\"),\r\n userId: z\r\n .union([z.string(), z.number()])\r\n .optional()\r\n .transform((value) =>\r\n value === undefined || value === null ? undefined : String(value).trim()\r\n )\r\n .pipe(\r\n z\r\n .string()\r\n .min(1, \"userId cannot be empty\")\r\n .max(128, \"userId too long\")\r\n .optional()\r\n ),\r\n })\r\n .strict();\r\n\r\nexport const optionsSchema = z\r\n .object({\r\n baseDir: z.string().min(1, \"baseDir is required\"),\r\n idHandler: z\r\n .custom<\r\n (id: string) => string\r\n >((val) => typeof val === \"function\", { message: \"idHandler must be a function\" })\r\n .optional(),\r\n getUserFolder: z\r\n .custom<\r\n (req: unknown, id?: string) => Promise<string> | string\r\n >((val) => typeof val === \"function\", { message: \"getUserFolder must be a function\" })\r\n .optional(),\r\n websiteURL: z.union([z.url(), z.string().regex(/^[\\w.-]+$/)]).optional(),\r\n apiRegex: z.instanceof(RegExp).default(API_REGEX),\r\n allowedNetworkList: z.array(z.string()).default([]),\r\n cacheControl: z.string().optional(),\r\n etag: z.boolean().default(true),\r\n minWidth: z.number().int().positive().default(50),\r\n maxWidth: z.number().int().positive().default(4000),\r\n minHeight: z.number().int().positive().default(50),\r\n maxHeight: z.number().int().positive().default(4000),\r\n defaultQuality: z.number().int().min(1).max(100).default(80),\r\n requestTimeoutMs: z.number().int().positive().default(5000),\r\n maxDownloadBytes: z.number().int().positive().default(5_000_000),\r\n })\r\n .strict();\r\n\r\nexport type ParsedUserData = z.infer<typeof userDataSchema>;\r\nexport type ParsedOptions = z.infer<typeof optionsSchema>;\r\n","import { optionsSchema, userDataSchema } from \"./schema\";\r\nimport type { ParsedOptions, ParsedUserData } from \"./schema\";\r\nimport type { PixelServeOptions, UserData } from \"./types\";\r\n\r\n/**\r\n * @typedef {(\"avatar\" | \"normal\")} ImageType\r\n * @description Defines the type of image being processed.\r\n */\r\n\r\n/**\r\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\r\n * @description Supported formats for image processing.\r\n */\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @typedef {Object} UserData\r\n * @property {number|string} quality - Quality of the image (1–100).\r\n * @property {ImageFormat} format - Desired format of the image.\r\n * @property {string} [src] - Source path or URL for the image.\r\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\r\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\r\n * @property {string|null} [userId] - Optional user identifier.\r\n * @property {number|string} [width] - Desired image width.\r\n * @property {number|string} [height] - Desired image height.\r\n */\r\n\r\n/**\r\n * Renders the options object with default values and user-provided values.\r\n *\r\n * @param {Partial<Options>} options - The user-provided options.\r\n * @returns {Options} The rendered options object.\r\n */\r\nexport const renderOptions = (options: PixelServeOptions): ParsedOptions =>\r\n optionsSchema.parse(options);\r\n\r\n/**\r\n * Renders the user data object with default values and user-provided values.\r\n *\r\n * @param {Partial<UserData>} userData - The user-provided data.\r\n * @returns {UserData} The rendered user data object.\r\n */\r\nexport const renderUserData = (\r\n userData: Partial<UserData>,\r\n bounds: {\r\n minWidth: number;\r\n maxWidth: number;\r\n minHeight: number;\r\n maxHeight: number;\r\n defaultQuality: number;\r\n }\r\n): ParsedUserData => {\r\n const parsed = userDataSchema.parse(userData);\r\n\r\n const clamp = (value: number | undefined, min: number, max: number) => {\r\n if (value === undefined) return undefined;\r\n return Math.min(Math.max(value, min), max);\r\n };\r\n\r\n return {\r\n ...parsed,\r\n width: clamp(parsed.width, bounds.minWidth, bounds.maxWidth),\r\n height: clamp(parsed.height, bounds.minHeight, bounds.maxHeight),\r\n quality: parsed.quality ?? bounds.defaultQuality,\r\n format: parsed.format ?? \"jpeg\",\r\n };\r\n};\r\n","import path from \"node:path\";\r\nimport { createHash } from \"node:crypto\";\r\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\r\nimport type { Request, Response, NextFunction } from \"express\";\r\nimport type {\r\n PixelServeOptions,\r\n UserData,\r\n ImageFormat,\r\n ImageType,\r\n} from \"./types\";\r\nimport { allowedFormats, FALLBACKIMAGES, mimeTypes } from \"./variables\";\r\nimport { fetchImage, readLocalImage } from \"./functions\";\r\nimport { renderOptions, renderUserData } from \"./renders\";\r\n\r\n/**\r\n * @typedef {Object} Options\r\n * @property {string} baseDir - The base directory for public image files.\r\n * @property {function(string): string} idHandler - A function to handle user IDs.\r\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\r\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\r\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\r\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\r\n */\r\n\r\n/**\r\n * @function serveImage\r\n * @description Processes and serves an image based on user data and options.\r\n * @param {Request} req - The Express request object.\r\n * @param {Response} res - The Express response object.\r\n * @param {NextFunction} next - The Express next function.\r\n * @param {PixelServeOptions} options - The options object for image processing.\r\n * @returns {Promise<void>}\r\n */\r\nconst serveImage = async (\r\n req: Request,\r\n res: Response,\r\n next: NextFunction,\r\n options: PixelServeOptions\r\n) => {\r\n try {\r\n const parsedOptions = renderOptions(options);\r\n const userData = renderUserData(req.query as Partial<UserData>, {\r\n minWidth: parsedOptions.minWidth,\r\n maxWidth: parsedOptions.maxWidth,\r\n minHeight: parsedOptions.minHeight,\r\n maxHeight: parsedOptions.maxHeight,\r\n defaultQuality: parsedOptions.defaultQuality,\r\n });\r\n\r\n let baseDir = parsedOptions.baseDir;\r\n let parsedUserId: string | undefined;\r\n\r\n if (userData.userId) {\r\n parsedUserId = parsedOptions.idHandler\r\n ? parsedOptions.idHandler(userData.userId)\r\n : userData.userId;\r\n }\r\n\r\n if (userData.folder === \"private\" && parsedOptions.getUserFolder) {\r\n const dir = await parsedOptions.getUserFolder(req, parsedUserId);\r\n if (dir) {\r\n baseDir = dir;\r\n }\r\n }\r\n\r\n const outputFormat = allowedFormats.includes(\r\n (userData.format ?? \"\").toLowerCase() as ImageFormat\r\n )\r\n ? (userData.format as ImageFormat)\r\n : \"jpeg\";\r\n\r\n const resolveBuffer = async (): Promise<Buffer> => {\r\n if (!userData.src) {\r\n return FALLBACKIMAGES[userData.type ?? \"normal\"]();\r\n }\r\n if (userData.src.startsWith(\"http\")) {\r\n return fetchImage(\r\n userData.src,\r\n baseDir,\r\n parsedOptions.websiteURL,\r\n userData.type as ImageType,\r\n parsedOptions.apiRegex,\r\n parsedOptions.allowedNetworkList,\r\n {\r\n timeoutMs: parsedOptions.requestTimeoutMs,\r\n maxBytes: parsedOptions.maxDownloadBytes,\r\n }\r\n );\r\n }\r\n return readLocalImage(userData.src, baseDir, userData.type as ImageType);\r\n };\r\n\r\n const imageBuffer = await resolveBuffer();\r\n let image = sharp(imageBuffer, { failOn: \"truncated\" });\r\n\r\n if (userData.width || userData.height) {\r\n const resizeOptions: ResizeOptions = {\r\n width: userData.width ?? undefined,\r\n height: userData.height ?? undefined,\r\n fit: sharp.fit.cover,\r\n withoutEnlargement: true,\r\n };\r\n image = image.resize(resizeOptions);\r\n }\r\n\r\n const processedImage = await image\r\n .rotate()\r\n .toFormat(outputFormat as keyof FormatEnum, {\r\n quality: userData.quality,\r\n })\r\n .toBuffer();\r\n\r\n const sourceName = userData.src\r\n ? path.basename(userData.src, path.extname(userData.src))\r\n : \"image\";\r\n const processedFileName = `${sourceName}.${outputFormat}`;\r\n\r\n const etag = parsedOptions.etag\r\n ? `\"${createHash(\"sha1\").update(processedImage).digest(\"hex\")}\"`\r\n : undefined;\r\n\r\n if (etag && req.headers[\"if-none-match\"] === etag) {\r\n res.status(304).end();\r\n return;\r\n }\r\n\r\n res.type(mimeTypes[outputFormat]);\r\n res.setHeader(\r\n \"Content-Disposition\",\r\n `inline; filename=\"${processedFileName}\"`\r\n );\r\n res.setHeader(\r\n \"Cache-Control\",\r\n parsedOptions.cacheControl ??\r\n \"public, max-age=86400, stale-while-revalidate=604800\"\r\n );\r\n if (etag) {\r\n res.setHeader(\"ETag\", etag);\r\n }\r\n res.setHeader(\"Content-Length\", processedImage.length.toString());\r\n res.send(processedImage);\r\n /* c8 ignore next */\r\n } catch (error) {\r\n try {\r\n const fallback = await FALLBACKIMAGES.normal();\r\n res.type(mimeTypes.jpeg);\r\n res.setHeader(\"Content-Disposition\", `inline; filename=\"fallback.jpeg\"`);\r\n res.setHeader(\"Cache-Control\", \"public, max-age=60\");\r\n res.send(fallback);\r\n } catch (fallbackError) {\r\n next(fallbackError);\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * @function registerServe\r\n * @description A function to register the serveImage function as middleware for Express.\r\n * @param {PixelServeOptions} options - The options object for image processing.\r\n * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.\r\n */\r\nconst registerServe = (options: PixelServeOptions) => {\r\n return async (req: Request, res: Response, next: NextFunction) =>\r\n serveImage(req, res, next, options);\r\n};\r\n\r\nexport default registerServe;\r\n"]}
package/package.json CHANGED
@@ -1,12 +1,26 @@
1
1
  {
2
2
  "name": "pixel-serve-server",
3
- "version": "0.0.6",
3
+ "version": "1.0.0",
4
4
  "description": "A robust Node.js utility for handling and processing images. This package provides features like resizing, format conversion and etc.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
7
7
  "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ },
14
+ "./assets/*": "./dist/assets/*",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "sideEffects": false,
8
18
  "scripts": {
9
- "build": "tsup"
19
+ "build": "tsup",
20
+ "lint": "eslint \"src/**/*.{ts,tsx}\"",
21
+ "format": "prettier --check \"src/**/*.{ts,tsx}\"",
22
+ "test": "vitest run --coverage",
23
+ "test:watch": "vitest watch"
10
24
  },
11
25
  "files": [
12
26
  "dist",
@@ -31,18 +45,28 @@
31
45
  "url": "https://github.com/Hiprax/pixel-serve-server/issues"
32
46
  },
33
47
  "homepage": "https://github.com/Hiprax/pixel-serve-server#readme",
48
+ "dependencies": {
49
+ "axios": "^1.13.2",
50
+ "express": "^5.2.1",
51
+ "sharp": "^0.34.5",
52
+ "zod": "^4.1.13"
53
+ },
34
54
  "devDependencies": {
35
- "@types/express": "^5.0.0",
36
- "@types/node": "^22.10.5",
37
- "tsup": "^8.3.5",
38
- "typescript": "^5.7.3"
55
+ "@types/express": "^5.0.6",
56
+ "@types/node": "^24.10.1",
57
+ "@types/supertest": "^6.0.3",
58
+ "@typescript-eslint/eslint-plugin": "^8.48.1",
59
+ "@typescript-eslint/parser": "^8.48.1",
60
+ "@vitest/coverage-v8": "^4.0.15",
61
+ "eslint": "^9.39.1",
62
+ "eslint-config-prettier": "^10.1.8",
63
+ "prettier": "^3.7.4",
64
+ "supertest": "^7.1.4",
65
+ "tsup": "^8.5.1",
66
+ "typescript": "^5.9.3",
67
+ "vitest": "^4.0.15"
39
68
  },
40
69
  "engines": {
41
- "node": ">=8.x"
42
- },
43
- "dependencies": {
44
- "axios": "^1.7.9",
45
- "express": "^4.21.2",
46
- "sharp": "^0.33.5"
70
+ "node": ">=18"
47
71
  }
48
72
  }