pixel-serve-server 0.0.4 → 0.0.5
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 +12 -7
- package/dist/index.d.mts +10 -22
- package/dist/index.d.ts +10 -22
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -49,22 +49,27 @@ Here’s how to integrate the middleware with an Express application:
|
|
|
49
49
|
|
|
50
50
|
```typescript
|
|
51
51
|
import express from "express";
|
|
52
|
-
import
|
|
52
|
+
import { registerServe } from "pixel-serve-server";
|
|
53
|
+
import path, { dirname } from "node:path";
|
|
54
|
+
import { fileURLToPath } from "node:url";
|
|
53
55
|
|
|
54
56
|
const app = express();
|
|
57
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
58
|
+
const __dirname = dirname(__filename);
|
|
55
59
|
|
|
56
|
-
const
|
|
57
|
-
|
|
60
|
+
const BASE_IMAGE_DIR = path.join(__dirname, "../assets/images/public");
|
|
61
|
+
const PRIVATE_IMAGE_DIR = path.join(__dirname, "../assets/images/private");
|
|
62
|
+
|
|
63
|
+
const serveImage = registerServe({
|
|
64
|
+
baseDir: BASE_IMAGE_DIR, // Base directory for local images
|
|
58
65
|
idHandler: (id: string) => `user-${id}`, // Custom handler for user IDs
|
|
59
66
|
getUserFolder: async (id: string) => `/private/users/${id}`, // Logic for user-specific folder paths
|
|
60
67
|
websiteURL: "example.com", // Your website's base URL
|
|
61
68
|
apiRegex: /^\/api\/v1\//, // Regex for removing API prefixes
|
|
62
69
|
allowedNetworkList: ["trusted.com"], // List of allowed network domains
|
|
63
|
-
};
|
|
70
|
+
});
|
|
64
71
|
|
|
65
|
-
app.get("/api/v1/pixel/serve",
|
|
66
|
-
serveImage(req, res, next, options)
|
|
67
|
-
);
|
|
72
|
+
app.get("/api/v1/pixel/serve", serveImage);
|
|
68
73
|
|
|
69
74
|
app.listen(3000, () => {
|
|
70
75
|
console.log("Server is running on http://localhost:3000");
|
package/dist/index.d.mts
CHANGED
|
@@ -4,11 +4,11 @@ type ImageType = "avatar" | "normal";
|
|
|
4
4
|
type ImageFormat = "jpeg" | "jpg" | "png" | "webp" | "gif" | "tiff" | "avif" | "svg";
|
|
5
5
|
type Options = {
|
|
6
6
|
baseDir: string;
|
|
7
|
-
idHandler
|
|
8
|
-
getUserFolder
|
|
9
|
-
websiteURL
|
|
10
|
-
apiRegex
|
|
11
|
-
allowedNetworkList
|
|
7
|
+
idHandler?: (id: string) => string;
|
|
8
|
+
getUserFolder?: (req: Request, id?: string | undefined) => Promise<string>;
|
|
9
|
+
websiteURL?: string;
|
|
10
|
+
apiRegex?: RegExp;
|
|
11
|
+
allowedNetworkList?: string[];
|
|
12
12
|
};
|
|
13
13
|
type UserData = {
|
|
14
14
|
quality: number | string;
|
|
@@ -22,23 +22,11 @@ type UserData = {
|
|
|
22
22
|
};
|
|
23
23
|
|
|
24
24
|
/**
|
|
25
|
-
* @
|
|
26
|
-
* @
|
|
27
|
-
* @property {function(string): string} idHandler - A function to handle user IDs.
|
|
28
|
-
* @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.
|
|
29
|
-
* @property {string} websiteURL - The base URL of the website for internal link resolution.
|
|
30
|
-
* @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.
|
|
31
|
-
* @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.
|
|
32
|
-
*/
|
|
33
|
-
/**
|
|
34
|
-
* @function serveImage
|
|
35
|
-
* @description Processes and serves an image based on user data and options.
|
|
36
|
-
* @param {Request} req - The Express request object.
|
|
37
|
-
* @param {Response} res - The Express response object.
|
|
38
|
-
* @param {NextFunction} next - The Express next function.
|
|
25
|
+
* @function registerServe
|
|
26
|
+
* @description A function to register the serveImage function as middleware for Express.
|
|
39
27
|
* @param {Options} options - The options object for image processing.
|
|
40
|
-
* @returns {Promise<void>}
|
|
28
|
+
* @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.
|
|
41
29
|
*/
|
|
42
|
-
declare const
|
|
30
|
+
declare const registerServe: (options: Options) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
43
31
|
|
|
44
|
-
export { type ImageFormat, type ImageType, type Options, type UserData,
|
|
32
|
+
export { type ImageFormat, type ImageType, type Options, type UserData, registerServe };
|
package/dist/index.d.ts
CHANGED
|
@@ -4,11 +4,11 @@ type ImageType = "avatar" | "normal";
|
|
|
4
4
|
type ImageFormat = "jpeg" | "jpg" | "png" | "webp" | "gif" | "tiff" | "avif" | "svg";
|
|
5
5
|
type Options = {
|
|
6
6
|
baseDir: string;
|
|
7
|
-
idHandler
|
|
8
|
-
getUserFolder
|
|
9
|
-
websiteURL
|
|
10
|
-
apiRegex
|
|
11
|
-
allowedNetworkList
|
|
7
|
+
idHandler?: (id: string) => string;
|
|
8
|
+
getUserFolder?: (req: Request, id?: string | undefined) => Promise<string>;
|
|
9
|
+
websiteURL?: string;
|
|
10
|
+
apiRegex?: RegExp;
|
|
11
|
+
allowedNetworkList?: string[];
|
|
12
12
|
};
|
|
13
13
|
type UserData = {
|
|
14
14
|
quality: number | string;
|
|
@@ -22,23 +22,11 @@ type UserData = {
|
|
|
22
22
|
};
|
|
23
23
|
|
|
24
24
|
/**
|
|
25
|
-
* @
|
|
26
|
-
* @
|
|
27
|
-
* @property {function(string): string} idHandler - A function to handle user IDs.
|
|
28
|
-
* @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.
|
|
29
|
-
* @property {string} websiteURL - The base URL of the website for internal link resolution.
|
|
30
|
-
* @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.
|
|
31
|
-
* @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.
|
|
32
|
-
*/
|
|
33
|
-
/**
|
|
34
|
-
* @function serveImage
|
|
35
|
-
* @description Processes and serves an image based on user data and options.
|
|
36
|
-
* @param {Request} req - The Express request object.
|
|
37
|
-
* @param {Response} res - The Express response object.
|
|
38
|
-
* @param {NextFunction} next - The Express next function.
|
|
25
|
+
* @function registerServe
|
|
26
|
+
* @description A function to register the serveImage function as middleware for Express.
|
|
39
27
|
* @param {Options} options - The options object for image processing.
|
|
40
|
-
* @returns {Promise<void>}
|
|
28
|
+
* @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.
|
|
41
29
|
*/
|
|
42
|
-
declare const
|
|
30
|
+
declare const registerServe: (options: Options) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
43
31
|
|
|
44
|
-
export { type ImageFormat, type ImageType, type Options, type UserData,
|
|
32
|
+
export { type ImageFormat, type ImageType, type Options, type UserData, registerServe };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var D=Object.create;var
|
|
1
|
+
"use strict";var D=Object.create;var f=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty;var B=(e,r)=>{for(var i in r)f(e,i,{get:r[i],enumerable:!0})},U=(e,r,i,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of S(r))!C.call(e,t)&&t!==i&&f(e,t,{get:()=>r[t],enumerable:!(a=M(r,t))||a.enumerable});return e};var d=(e,r,i)=>(i=e!=null?D(_(e)):{},U(r||!e||!e.__esModule?f(i,"default",{value:e,enumerable:!0}):i,e)),P=e=>U(f({},"__esModule",{value:!0}),e);var V={};B(V,{registerServe:()=>q});module.exports=P(V);var G=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,o=G();var R=d(require("path")),F=d(require("sharp"));var I=require("fs/promises"),k=new URL("./assets/noimage.jpg",o).pathname,H=new URL("./assets/noavatar.png",o).pathname,g={normal:async()=>(0,I.readFile)(k),avatar:async()=>(0,I.readFile)(H)},c=/^\/api\/v1\//,v=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],u={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 y=d(require("path")),b=require("fs"),O=d(require("fs/promises")),L=d(require("axios"));var $=(e,r)=>{if(!e||!r)return!1;let i=y.default.resolve(e),a=y.default.resolve(i,r);return a.startsWith(i)&&(0,b.existsSync)(a)},z=async(e,r="normal")=>{try{let i=await L.default.get(e,{responseType:"arraybuffer",timeout:5e3}),a=i.headers["content-type"]?.toLowerCase();return Object.values(u).includes(a??"")?Buffer.from(i.data):await g[r]()}catch{return await g[r]()}},x=async(e,r,i="normal")=>{if(!$(r,e))return await g[i]();try{return await O.readFile(y.default.resolve(r,e))}catch{return await g[i]()}},T=(e,r,i,a="normal",t=c,s=[])=>{let n=new URL(e);if([i,`www.${i}`].includes(n.host)){let p=n.pathname.replace(t,"");return x(p,r,a)}else return s.includes(n.host)?z(e,a):g[a]()};var j=e=>({...{baseDir:"",idHandler:i=>i,getUserFolder:async()=>"",websiteURL:"",apiRegex:c,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 X=async(e,r,i,a)=>{try{let t=N(e.query),s=j(a),n,l=s.baseDir,p;if(t.userId){let m=typeof t.userId=="object"?String(Object.values(t.userId)[0]):String(t.userId);s.idHandler?p=s.idHandler(m):p=m}if(t.folder==="private"){let m=await s?.getUserFolder?.(e,p);m&&(l=m)}let h=v.includes(t?.format?.toLowerCase())?t?.format?.toLowerCase():"jpeg";t?.src?.startsWith("http")?n=await T(t?.src??"",l,s?.websiteURL??"",t?.type,s?.apiRegex,s?.allowedNetworkList):n=await x(t?.src??"",l,t?.type);let w=(0,F.default)(n);if(t?.width||t?.height){let m={width:t?.width??void 0,height:t?.height??void 0,fit:F.default.fit.cover};w=w.resize(m)}let E=await w.toFormat(h,{quality:t?.quality?Number(t?.quality):80}).toBuffer(),A=`${R.default.basename(t?.src??"",R.default.extname(t?.src??""))}.${h}`;r.type(u[h]),r.setHeader("Content-Disposition",`inline; filename="${A}"`),r.send(E)}catch(t){i(t)}},K=e=>async(r,i,a)=>X(r,i,a,e),q=K;0&&(module.exports={registerServe});
|
|
2
2
|
//# 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":["/**\n * @module ImageService\n * @description A module to serve, process, and manage image delivery for web applications.\n */\n\nexport { default as serveImage } from \"./pixel\";\nexport * from \"./types\";\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\";\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\nimport type { Request, Response, NextFunction } from \"express\";\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\nimport { allowedFormats, mimeTypes } from \"./variables\";\nimport { fetchImage, readLocalImage } from \"./functions\";\nimport { renderOptions, renderUserData } from \"./renders\";\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @function serveImage\n * @description Processes and serves an image based on user data and options.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The Express next function.\n * @param {Options} options - The options object for image processing.\n * @returns {Promise<void>}\n */\nconst serveImage = async (\n req: Request,\n res: Response,\n next: NextFunction,\n options: Options\n) => {\n try {\n const userData = renderUserData(req.query as UserData);\n const parsedOptions = renderOptions(options);\n\n let imageBuffer;\n let baseDir = parsedOptions.baseDir;\n let parsedUserId;\n\n if (userData.userId) {\n const userIdStr =\n typeof userData.userId === \"object\"\n ? String(Object.values(userData.userId)[0])\n : String(userData.userId);\n if (parsedOptions.idHandler) {\n parsedUserId = parsedOptions.idHandler(userIdStr);\n } else {\n parsedUserId = userIdStr;\n }\n }\n\n if (userData.folder === \"private\" && parsedUserId) {\n baseDir = await parsedOptions.getUserFolder(parsedUserId, req);\n }\n\n const outputFormat = allowedFormats.includes(\n userData.format.toLowerCase() as ImageFormat\n )\n ? userData.format.toLowerCase()\n : \"jpeg\";\n\n if (userData?.src?.startsWith(\"http\")) {\n imageBuffer = await fetchImage(\n userData.src,\n baseDir,\n parsedOptions.websiteURL,\n userData.type as ImageType,\n parsedOptions.apiRegex\n );\n } else {\n imageBuffer = await readLocalImage(\n userData?.src ?? \"\",\n baseDir,\n userData.type as ImageType\n );\n }\n\n let image = sharp(imageBuffer);\n\n if (userData?.width || userData?.height) {\n const resizeOptions = {\n width: userData?.width ?? undefined,\n height: userData?.height ?? undefined,\n fit: sharp.fit.cover,\n };\n image = image.resize(resizeOptions as ResizeOptions);\n }\n\n const processedImage = await image\n .toFormat(outputFormat as keyof FormatEnum, {\n quality: userData?.quality ? Number(userData.quality) : 80,\n })\n .toBuffer();\n\n const processedFileName = `${path.basename(\n userData.src ?? \"\",\n path.extname(userData.src ?? \"\")\n )}.${outputFormat}`;\n\n res.type(mimeTypes[outputFormat]);\n res.setHeader(\n \"Content-Disposition\",\n `inline; filename=\"${processedFileName}\"`\n );\n res.send(processedImage);\n } catch (error) {\n next(error);\n }\n};\n\nexport default serveImage;\n","import type { ImageFormat } from \"./types\";\nimport { readFile } from \"node:fs/promises\";\n\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url).href;\n\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url).href;\n\nexport const FALLBACKIMAGES = {\n normal: async () => readFile(NOT_FOUND_IMAGE),\n avatar: async () => readFile(NOT_FOUND_AVATAR),\n};\n\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\n\nexport const allowedFormats: ImageFormat[] = [\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"webp\",\n \"gif\",\n \"tiff\",\n \"avif\",\n \"svg\",\n];\n\nexport const mimeTypes: Readonly<Record<string, string>> = {\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n tiff: \"image/tiff\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n","import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport axios from \"axios\";\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\nimport type { ImageType } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * Checks if a specified path is valid within a base path.\n *\n * @param {string} basePath - The base directory to resolve paths.\n * @param {string} specifiedPath - The path to check.\n * @returns {boolean} True if the path is valid, false otherwise.\n */\nconst isValidPath = (basePath: string, specifiedPath: string): boolean => {\n if (!basePath || !specifiedPath) return false;\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\n return resolvedPath.startsWith(resolvedBase) && existsSync(resolvedPath);\n};\n\n/**\n * Fetches an image from a network source.\n *\n * @param {string} src - The URL of the image.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nconst fetchFromNetwork = async (\n src: string,\n type: ImageType = \"normal\"\n): Promise<Buffer> => {\n try {\n const response = await axios.get(src, {\n responseType: \"arraybuffer\",\n timeout: 5000,\n });\n\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\n const allowedMimeTypes = Object.values(mimeTypes);\n\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\n return Buffer.from(response.data);\n }\n return await FALLBACKIMAGES[type]();\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Reads an image from the local file system.\n *\n * @param {string} filePath - Path to the image file.\n * @param {string} baseDir - Base directory to resolve paths.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @returns {Promise<Buffer>} A buffer containing the image data.\n */\nexport const readLocalImage = async (\n filePath: string,\n baseDir: string,\n type: ImageType = \"normal\"\n) => {\n if (!isValidPath(baseDir, filePath)) {\n return await FALLBACKIMAGES[type]();\n }\n try {\n return await fs.readFile(path.resolve(baseDir, filePath));\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Fetches an image from either a local file or a network source.\n *\n * @param {string} src - The URL or local path of the image.\n * @param {string} baseDir - Base directory to resolve local paths.\n * @param {string} websiteURL - The URL of the website.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nexport const fetchImage = (\n src: string,\n baseDir: string,\n websiteURL: string,\n type: ImageType = \"normal\",\n apiRegex: RegExp = API_REGEX,\n allowedNetworkList: string[] = []\n) => {\n const url = new URL(src);\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\n if (isInternal) {\n const localPath = url.pathname.replace(apiRegex, \"\");\n return readLocalImage(localPath, baseDir, type);\n } else {\n const allowedCondition = allowedNetworkList.includes(url.host);\n if (!allowedCondition) {\n return FALLBACKIMAGES[type]();\n }\n return fetchFromNetwork(src, type);\n }\n};\n","import { API_REGEX } from \"./variables\";\nimport type { Options, UserData } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\n * @description Supported formats for image processing.\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @typedef {Object} UserData\n * @property {number|string} quality - Quality of the image (1–100).\n * @property {ImageFormat} format - Desired format of the image.\n * @property {string} [src] - Source path or URL for the image.\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\n * @property {string|null} [userId] - Optional user identifier.\n * @property {number|string} [width] - Desired image width.\n * @property {number|string} [height] - Desired image height.\n */\n\n/**\n * Renders the options object with default values and user-provided values.\n *\n * @param {Partial<Options>} options - The user-provided options.\n * @returns {Options} The rendered options object.\n */\nexport const renderOptions = (options: Partial<Options>): Options => {\n const initialOptions: Options = {\n baseDir: \"\",\n idHandler: (id: string) => id,\n getUserFolder: async () => \"\",\n websiteURL: \"\",\n apiRegex: API_REGEX,\n allowedNetworkList: [],\n };\n return {\n ...initialOptions,\n ...options,\n };\n};\n\n/**\n * Renders the user data object with default values and user-provided values.\n *\n * @param {Partial<UserData>} userData - The user-provided data.\n * @returns {UserData} The rendered user data object.\n */\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\n const initialUserData: UserData = {\n quality: 80,\n format: \"jpeg\",\n src: \"/placeholder/noimage.jpg\",\n folder: \"public\",\n type: \"normal\",\n width: undefined,\n height: undefined,\n userId: undefined,\n };\n return {\n ...initialUserData,\n ...userData,\n quality: userData.quality\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\n : 100,\n width: userData.width\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\n : undefined,\n height: userData.height\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\n : undefined,\n };\n};\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gBAAAE,IAAA,eAAAC,EAAAH,GCKA,IAAMI,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,EAAkB,IAAI,IAAI,uBAAwBC,CAAe,EAAE,KAEnEC,EAAmB,IAAI,IAAI,wBAAyBD,CAAe,EAAE,KAE9DE,EAAiB,CAC5B,OAAQ,YAAY,YAASH,CAAe,EAC5C,OAAQ,YAAY,YAASE,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,KAAM,aACN,IAAK,eACP,EClCA,IAAAC,EAAiB,mBACjBC,EAA2B,cAC3BC,EAAoB,0BACpBC,EAAkB,oBAgBlB,IAAMC,EAAc,CAACC,EAAkBC,IAAmC,CACxE,GAAI,CAACD,GAAY,CA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c,QAChB,EAEAE,EAAc,MAAMO,EAClBX,GAAU,KAAO,GACjBK,EACAL,EAAS,IACX,EAGF,IAAIY,KAAQ,EAAAC,SAAMT,CAAW,EAE7B,GAAIJ,GAAU,OAASA,GAAU,OAAQ,CACvC,IAAMc,EAAgB,CACpB,MAAOd,GAAU,OAAS,OAC1B,OAAQA,GAAU,QAAU,OAC5B,IAAK,EAAAa,QAAM,IAAI,KACjB,EACAD,EAAQA,EAAM,OAAOE,CAA8B,CACrD,CAEA,IAAMC,EAAiB,MAAMH,EAC1B,SAASJ,EAAkC,CAC1C,QAASR,GAAU,QAAU,OAAOA,EAAS,OAAO,EAAI,EAC1D,CAAC,EACA,SAAS,EAENgB,EAAoB,GAAG,EAAAC,QAAK,SAChCjB,EAAS,KAAO,GAChB,EAAAiB,QAAK,QAAQjB,EAAS,KAAO,EAAE,CACjC,CAAC,IAAIQ,CAAY,GAEjBX,EAAI,KAAKqB,EAAUV,CAAY,CAAC,EAChCX,EAAI,UACF,sBACA,qBAAqBmB,CAAiB,GACxC,EACAnB,EAAI,KAAKkB,CAAc,CACzB,OAASI,EAAO,CACdrB,EAAKqB,CAAK,CACZ,CACF,EAEOC,EAAQzB","names":["index_exports","__export","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","import_node_fs","fs","import_axios","isValidPath","basePath","specifiedPath","resolvedBase","path","resolvedPath","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","outputFormat","allowedFormats","fetchImage","readLocalImage","image","sharp","resizeOptions","processedImage","processedFileName","path","mimeTypes","error","pixel_default"]}
|
|
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":["/**\n * @module ImageService\n * @description A module to serve, process, and manage image delivery for web applications.\n */\n\nexport { default as registerServe } from \"./pixel\";\nexport * from \"./types\";\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\";\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\nimport type { Request, Response, NextFunction } from \"express\";\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\nimport { allowedFormats, mimeTypes } from \"./variables\";\nimport { fetchImage, readLocalImage } from \"./functions\";\nimport { renderOptions, renderUserData } from \"./renders\";\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @function serveImage\n * @description Processes and serves an image based on user data and options.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The Express next function.\n * @param {Options} options - The options object for image processing.\n * @returns {Promise<void>}\n */\nconst serveImage = async (\n req: Request,\n res: Response,\n next: NextFunction,\n options: Options\n) => {\n try {\n const userData = renderUserData(req.query as UserData);\n const parsedOptions = renderOptions(options);\n\n let imageBuffer;\n let baseDir = parsedOptions.baseDir;\n let parsedUserId;\n\n if (userData.userId) {\n const userIdStr =\n typeof userData.userId === \"object\"\n ? String(Object.values(userData.userId)[0])\n : String(userData.userId);\n if (parsedOptions.idHandler) {\n parsedUserId = parsedOptions.idHandler(userIdStr);\n } else {\n parsedUserId = userIdStr;\n }\n }\n\n if (userData.folder === \"private\") {\n const dir = await parsedOptions?.getUserFolder?.(req, parsedUserId);\n if (dir) {\n baseDir = dir;\n }\n }\n\n const outputFormat = allowedFormats.includes(\n userData?.format?.toLowerCase() as ImageFormat\n )\n ? userData?.format?.toLowerCase()\n : \"jpeg\";\n\n if (userData?.src?.startsWith(\"http\")) {\n imageBuffer = await fetchImage(\n userData?.src ?? \"\",\n baseDir,\n parsedOptions?.websiteURL ?? \"\",\n userData?.type as ImageType,\n parsedOptions?.apiRegex,\n parsedOptions?.allowedNetworkList\n );\n } else {\n imageBuffer = await readLocalImage(\n userData?.src ?? \"\",\n baseDir,\n userData?.type as ImageType\n );\n }\n\n let image = sharp(imageBuffer);\n\n if (userData?.width || userData?.height) {\n const resizeOptions = {\n width: userData?.width ?? undefined,\n height: userData?.height ?? undefined,\n fit: sharp.fit.cover,\n };\n image = image.resize(resizeOptions as ResizeOptions);\n }\n\n const processedImage = await image\n .toFormat(outputFormat as keyof FormatEnum, {\n quality: userData?.quality ? Number(userData?.quality) : 80,\n })\n .toBuffer();\n\n const processedFileName = `${path.basename(\n userData?.src ?? \"\",\n path.extname(userData?.src ?? \"\")\n )}.${outputFormat}`;\n\n res.type(mimeTypes[outputFormat]);\n res.setHeader(\n \"Content-Disposition\",\n `inline; filename=\"${processedFileName}\"`\n );\n res.send(processedImage);\n } catch (error) {\n next(error);\n }\n};\n\n/**\n * @function registerServe\n * @description A function to register the serveImage function as middleware for Express.\n * @param {Options} options - The options object for image processing.\n * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.\n */\nconst registerServe = (options: Options) => {\n return async (req: Request, res: Response, next: NextFunction) =>\n serveImage(req, res, next, options);\n};\n\nexport default registerServe;\n","import type { ImageFormat } from \"./types\";\nimport { readFile } from \"node:fs/promises\";\n\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url)\n .pathname;\n\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url)\n .pathname;\n\nexport const FALLBACKIMAGES = {\n normal: async () => readFile(NOT_FOUND_IMAGE),\n avatar: async () => readFile(NOT_FOUND_AVATAR),\n};\n\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\n\nexport const allowedFormats: ImageFormat[] = [\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"webp\",\n \"gif\",\n \"tiff\",\n \"avif\",\n \"svg\",\n];\n\nexport const mimeTypes: Readonly<Record<string, string>> = {\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n tiff: \"image/tiff\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n","import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport axios from \"axios\";\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\nimport type { ImageType } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * Checks if a specified path is valid within a base path.\n *\n * @param {string} basePath - The base directory to resolve paths.\n * @param {string} specifiedPath - The path to check.\n * @returns {boolean} True if the path is valid, false otherwise.\n */\nconst isValidPath = (basePath: string, specifiedPath: string): boolean => {\n if (!basePath || !specifiedPath) return false;\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\n return resolvedPath.startsWith(resolvedBase) && existsSync(resolvedPath);\n};\n\n/**\n * Fetches an image from a network source.\n *\n * @param {string} src - The URL of the image.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nconst fetchFromNetwork = async (\n src: string,\n type: ImageType = \"normal\"\n): Promise<Buffer> => {\n try {\n const response = await axios.get(src, {\n responseType: \"arraybuffer\",\n timeout: 5000,\n });\n\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\n const allowedMimeTypes = Object.values(mimeTypes);\n\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\n return Buffer.from(response.data);\n }\n return await FALLBACKIMAGES[type]();\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Reads an image from the local file system.\n *\n * @param {string} filePath - Path to the image file.\n * @param {string} baseDir - Base directory to resolve paths.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @returns {Promise<Buffer>} A buffer containing the image data.\n */\nexport const readLocalImage = async (\n filePath: string,\n baseDir: string,\n type: ImageType = \"normal\"\n) => {\n if (!isValidPath(baseDir, filePath)) {\n return await FALLBACKIMAGES[type]();\n }\n try {\n return await fs.readFile(path.resolve(baseDir, filePath));\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Fetches an image from either a local file or a network source.\n *\n * @param {string} src - The URL or local path of the image.\n * @param {string} baseDir - Base directory to resolve local paths.\n * @param {string} websiteURL - The URL of the website.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nexport const fetchImage = (\n src: string,\n baseDir: string,\n websiteURL: string,\n type: ImageType = \"normal\",\n apiRegex: RegExp = API_REGEX,\n allowedNetworkList: string[] = []\n) => {\n const url = new URL(src);\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\n if (isInternal) {\n const localPath = url.pathname.replace(apiRegex, \"\");\n return readLocalImage(localPath, baseDir, type);\n } else {\n const allowedCondition = allowedNetworkList.includes(url.host);\n if (!allowedCondition) {\n return FALLBACKIMAGES[type]();\n }\n return fetchFromNetwork(src, type);\n }\n};\n","import { API_REGEX } from \"./variables\";\nimport type { Options, UserData } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\n * @description Supported formats for image processing.\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @typedef {Object} UserData\n * @property {number|string} quality - Quality of the image (1–100).\n * @property {ImageFormat} format - Desired format of the image.\n * @property {string} [src] - Source path or URL for the image.\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\n * @property {string|null} [userId] - Optional user identifier.\n * @property {number|string} [width] - Desired image width.\n * @property {number|string} [height] - Desired image height.\n */\n\n/**\n * Renders the options object with default values and user-provided values.\n *\n * @param {Partial<Options>} options - The user-provided options.\n * @returns {Options} The rendered options object.\n */\nexport const renderOptions = (options: Partial<Options>): Options => {\n const initialOptions: Options = {\n baseDir: \"\",\n idHandler: (id: string) => id,\n getUserFolder: async () => \"\",\n websiteURL: \"\",\n apiRegex: API_REGEX,\n allowedNetworkList: [],\n };\n return {\n ...initialOptions,\n ...options,\n };\n};\n\n/**\n * Renders the user data object with default values and user-provided values.\n *\n * @param {Partial<UserData>} userData - The user-provided data.\n * @returns {UserData} The rendered user data object.\n */\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\n const initialUserData: UserData = {\n quality: 80,\n format: \"jpeg\",\n src: \"/placeholder/noimage.jpg\",\n folder: \"public\",\n type: \"normal\",\n width: undefined,\n height: undefined,\n userId: undefined,\n };\n return {\n ...initialUserData,\n ...userData,\n quality: userData.quality\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\n : 100,\n width: userData.width\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\n : undefined,\n height: userData.height\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\n : undefined,\n };\n};\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GCKA,IAAMI,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,EAAkB,IAAI,IAAI,uBAAwBC,CAAe,EACpE,SAEGC,EAAmB,IAAI,IAAI,wBAAyBD,CAAe,EACtE,SAEUE,EAAiB,CAC5B,OAAQ,YAAY,YAASH,CAAe,EAC5C,OAAQ,YAAY,YAASE,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,KAAM,aACN,IAAK,eACP,ECpCA,IAAAC,EAAiB,mBACjBC,EAA2B,cAC3BC,EAAoB,0BACpBC,EAAkB,oBAgBlB,IAAMC,EAAc,CAACC,EAAkBC,IAAmC,CACxE,GAAI,CAACD,GAAY,CAACC,EAAe,MAAO,GACxC,IAAMC,EAAe,EAAAC,QAAK,QAAQH,CAAQ,EACpCI,EAAe,EAAAD,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AE,EAAc,MAAMQ,EAClBZ,GAAU,KAAO,GACjBK,EACAL,GAAU,IACZ,EAGF,IAAIa,KAAQ,EAAAC,SAAMV,CAAW,EAE7B,GAAIJ,GAAU,OAASA,GAAU,OAAQ,CACvC,IAAMe,EAAgB,CACpB,MAAOf,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","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","import_node_fs","fs","import_axios","isValidPath","basePath","specifiedPath","resolvedBase","path","resolvedPath","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"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import O from"node:path";import U from"sharp";import{readFile as I}from"node:fs/promises";var N=new URL("./assets/noimage.jpg",import.meta.url).pathname,j=new URL("./assets/noavatar.png",import.meta.url).pathname,m={normal:async()=>I(N),avatar:async()=>I(j)},f=/^\/api\/v1\//,x=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],c={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 h from"node:path";import{existsSync as q}from"node:fs";import*as R from"node:fs/promises";import E from"axios";var A=(e,r)=>{if(!e||!r)return!1;let i=h.resolve(e),a=h.resolve(i,r);return a.startsWith(i)&&q(a)},D=async(e,r="normal")=>{try{let i=await E.get(e,{responseType:"arraybuffer",timeout:5e3}),a=i.headers["content-type"]?.toLowerCase();return Object.values(c).includes(a??"")?Buffer.from(i.data):await m[r]()}catch{return await m[r]()}},w=async(e,r,i="normal")=>{if(!A(r,e))return await m[i]();try{return await R.readFile(h.resolve(r,e))}catch{return await m[i]()}},F=(e,r,i,a="normal",t=f,s=[])=>{let o=new URL(e);if([i,`www.${i}`].includes(o.host)){let p=o.pathname.replace(t,"");return w(p,r,a)}else return s.includes(o.host)?D(e,a):m[a]()};var v=e=>({...{baseDir:"",idHandler:i=>i,getUserFolder:async()=>"",websiteURL:"",apiRegex:f,allowedNetworkList:[]},...e}),b=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 M=async(e,r,i,a)=>{try{let t=b(e.query),s=v(a),o,d=s.baseDir,p;if(t.userId){let n=typeof t.userId=="object"?String(Object.values(t.userId)[0]):String(t.userId);s.idHandler?p=s.idHandler(n):p=n}if(t.folder==="private"){let n=await s?.getUserFolder?.(e,p);n&&(d=n)}let u=x.includes(t?.format?.toLowerCase())?t?.format?.toLowerCase():"jpeg";t?.src?.startsWith("http")?o=await F(t?.src??"",d,s?.websiteURL??"",t?.type,s?.apiRegex,s?.allowedNetworkList):o=await w(t?.src??"",d,t?.type);let y=U(o);if(t?.width||t?.height){let n={width:t?.width??void 0,height:t?.height??void 0,fit:U.fit.cover};y=y.resize(n)}let T=await y.toFormat(u,{quality:t?.quality?Number(t?.quality):80}).toBuffer(),L=`${O.basename(t?.src??"",O.extname(t?.src??""))}.${u}`;r.type(c[u]),r.setHeader("Content-Disposition",`inline; filename="${L}"`),r.send(T)}catch(t){i(t)}},C=e=>async(r,i,a)=>M(r,i,a,e),S=C;export{S as registerServe};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pixel.ts","../src/variables.ts","../src/functions.ts","../src/renders.ts"],"sourcesContent":["import path from \"node:path\";\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\nimport type { Request, Response, NextFunction } from \"express\";\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\nimport { allowedFormats, mimeTypes } from \"./variables\";\nimport { fetchImage, readLocalImage } from \"./functions\";\nimport { renderOptions, renderUserData } from \"./renders\";\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @function serveImage\n * @description Processes and serves an image based on user data and options.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The Express next function.\n * @param {Options} options - The options object for image processing.\n * @returns {Promise<void>}\n */\nconst serveImage = async (\n req: Request,\n res: Response,\n next: NextFunction,\n options: Options\n) => {\n try {\n const userData = renderUserData(req.query as UserData);\n const parsedOptions = renderOptions(options);\n\n let imageBuffer;\n let baseDir = parsedOptions.baseDir;\n let parsedUserId;\n\n if (userData.userId) {\n const userIdStr =\n typeof userData.userId === \"object\"\n ? String(Object.values(userData.userId)[0])\n : String(userData.userId);\n if (parsedOptions.idHandler) {\n parsedUserId = parsedOptions.idHandler(userIdStr);\n } else {\n parsedUserId = userIdStr;\n }\n }\n\n if (userData.folder === \"private\" && parsedUserId) {\n baseDir = await parsedOptions.getUserFolder(parsedUserId, req);\n }\n\n const outputFormat = allowedFormats.includes(\n userData.format.toLowerCase() as ImageFormat\n )\n ? userData.format.toLowerCase()\n : \"jpeg\";\n\n if (userData?.src?.startsWith(\"http\")) {\n imageBuffer = await fetchImage(\n userData.src,\n baseDir,\n parsedOptions.websiteURL,\n userData.type as ImageType,\n parsedOptions.apiRegex\n );\n } else {\n imageBuffer = await readLocalImage(\n userData?.src ?? \"\",\n baseDir,\n userData.type as ImageType\n );\n }\n\n let image = sharp(imageBuffer);\n\n if (userData?.width || userData?.height) {\n const resizeOptions = {\n width: userData?.width ?? undefined,\n height: userData?.height ?? undefined,\n fit: sharp.fit.cover,\n };\n image = image.resize(resizeOptions as ResizeOptions);\n }\n\n const processedImage = await image\n .toFormat(outputFormat as keyof FormatEnum, {\n quality: userData?.quality ? Number(userData.quality) : 80,\n })\n .toBuffer();\n\n const processedFileName = `${path.basename(\n userData.src ?? \"\",\n path.extname(userData.src ?? \"\")\n )}.${outputFormat}`;\n\n res.type(mimeTypes[outputFormat]);\n res.setHeader(\n \"Content-Disposition\",\n `inline; filename=\"${processedFileName}\"`\n );\n res.send(processedImage);\n } catch (error) {\n next(error);\n }\n};\n\nexport default serveImage;\n","import type { ImageFormat } from \"./types\";\nimport { readFile } from \"node:fs/promises\";\n\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url).href;\n\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url).href;\n\nexport const FALLBACKIMAGES = {\n normal: async () => readFile(NOT_FOUND_IMAGE),\n avatar: async () => readFile(NOT_FOUND_AVATAR),\n};\n\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\n\nexport const allowedFormats: ImageFormat[] = [\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"webp\",\n \"gif\",\n \"tiff\",\n \"avif\",\n \"svg\",\n];\n\nexport const mimeTypes: Readonly<Record<string, string>> = {\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n tiff: \"image/tiff\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n","import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport axios from \"axios\";\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\nimport type { ImageType } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * Checks if a specified path is valid within a base path.\n *\n * @param {string} basePath - The base directory to resolve paths.\n * @param {string} specifiedPath - The path to check.\n * @returns {boolean} True if the path is valid, false otherwise.\n */\nconst isValidPath = (basePath: string, specifiedPath: string): boolean => {\n if (!basePath || !specifiedPath) return false;\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\n return resolvedPath.startsWith(resolvedBase) && existsSync(resolvedPath);\n};\n\n/**\n * Fetches an image from a network source.\n *\n * @param {string} src - The URL of the image.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nconst fetchFromNetwork = async (\n src: string,\n type: ImageType = \"normal\"\n): Promise<Buffer> => {\n try {\n const response = await axios.get(src, {\n responseType: \"arraybuffer\",\n timeout: 5000,\n });\n\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\n const allowedMimeTypes = Object.values(mimeTypes);\n\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\n return Buffer.from(response.data);\n }\n return await FALLBACKIMAGES[type]();\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Reads an image from the local file system.\n *\n * @param {string} filePath - Path to the image file.\n * @param {string} baseDir - Base directory to resolve paths.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @returns {Promise<Buffer>} A buffer containing the image data.\n */\nexport const readLocalImage = async (\n filePath: string,\n baseDir: string,\n type: ImageType = \"normal\"\n) => {\n if (!isValidPath(baseDir, filePath)) {\n return await FALLBACKIMAGES[type]();\n }\n try {\n return await fs.readFile(path.resolve(baseDir, filePath));\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Fetches an image from either a local file or a network source.\n *\n * @param {string} src - The URL or local path of the image.\n * @param {string} baseDir - Base directory to resolve local paths.\n * @param {string} websiteURL - The URL of the website.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nexport const fetchImage = (\n src: string,\n baseDir: string,\n websiteURL: string,\n type: ImageType = \"normal\",\n apiRegex: RegExp = API_REGEX,\n allowedNetworkList: string[] = []\n) => {\n const url = new URL(src);\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\n if (isInternal) {\n const localPath = url.pathname.replace(apiRegex, \"\");\n return readLocalImage(localPath, baseDir, type);\n } else {\n const allowedCondition = allowedNetworkList.includes(url.host);\n if (!allowedCondition) {\n return FALLBACKIMAGES[type]();\n }\n return fetchFromNetwork(src, type);\n }\n};\n","import { API_REGEX } from \"./variables\";\nimport type { Options, UserData } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\n * @description Supported formats for image processing.\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @typedef {Object} UserData\n * @property {number|string} quality - Quality of the image (1–100).\n * @property {ImageFormat} format - Desired format of the image.\n * @property {string} [src] - Source path or URL for the image.\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\n * @property {string|null} [userId] - Optional user identifier.\n * @property {number|string} [width] - Desired image width.\n * @property {number|string} [height] - Desired image height.\n */\n\n/**\n * Renders the options object with default values and user-provided values.\n *\n * @param {Partial<Options>} options - The user-provided options.\n * @returns {Options} The rendered options object.\n */\nexport const renderOptions = (options: Partial<Options>): Options => {\n const initialOptions: Options = {\n baseDir: \"\",\n idHandler: (id: string) => id,\n getUserFolder: async () => \"\",\n websiteURL: \"\",\n apiRegex: API_REGEX,\n allowedNetworkList: [],\n };\n return {\n ...initialOptions,\n ...options,\n };\n};\n\n/**\n * Renders the user data object with default values and user-provided values.\n *\n * @param {Partial<UserData>} userData - The user-provided data.\n * @returns {UserData} The rendered user data object.\n */\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\n const initialUserData: UserData = {\n quality: 80,\n format: \"jpeg\",\n src: \"/placeholder/noimage.jpg\",\n folder: \"public\",\n type: \"normal\",\n width: undefined,\n height: undefined,\n userId: undefined,\n };\n return {\n ...initialUserData,\n ...userData,\n quality: userData.quality\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\n : 100,\n width: userData.width\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\n : undefined,\n height: userData.height\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\n : undefined,\n };\n};\n"],"mappings":"AAAA,OAAOA,MAAU,YACjB,OAAOC,MAA0C,QCAjD,OAAS,YAAAC,MAAgB,mBAEzB,IAAMC,EAAkB,IAAI,IAAI,uBAAwB,YAAY,GAAG,EAAE,KAEnEC,EAAmB,IAAI,IAAI,wBAAyB,YAAY,GAAG,EAAE,KAE9DC,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,KAAM,aACN,IAAK,eACP,EClCA,OAAOC,MAAU,YACjB,OAAS,cAAAC,MAAkB,UAC3B,UAAYC,MAAQ,mBACpB,OAAOC,MAAW,QAgBlB,IAAMC,EAAc,CAACC,EAAkBC,IAAmC,CACxE,GAAI,CAACD,GAAY,CAACC,EAAe,MAAO,GACxC,IAAMC,EAAeC,EAAK,QAAQH,CAAQ,EACpCI,EAAeD,EAAK,QAAQD,EAAcD,CAAa,EAC7D,OAAOG,EAAa,WAAWF,CAAY,GAAKG,EAAWD,CAAY,CACzE,EASME,EAAmB,MACvBC,EACAC,EAAkB,WACE,CACpB,GAAI,CACF,IAAMC,EAAW,MAAMC,EAAM,IAAIH,E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AOE,CAA8B,CACrD,CAEA,IAAMC,EAAiB,MAAMH,EAC1B,SAASJ,EAAkC,CAC1C,QAASR,GAAU,QAAU,OAAOA,EAAS,OAAO,EAAI,EAC1D,CAAC,EACA,SAAS,EAENgB,EAAoB,GAAGC,EAAK,SAChCjB,EAAS,KAAO,GAChBiB,EAAK,QAAQjB,EAAS,KAAO,EAAE,CACjC,CAAC,IAAIQ,CAAY,GAEjBX,EAAI,KAAKqB,EAAUV,CAAY,CAAC,EAChCX,EAAI,UACF,sBACA,qBAAqBmB,CAAiB,GACxC,EACAnB,EAAI,KAAKkB,CAAc,CACzB,OAASI,EAAO,CACdrB,EAAKqB,CAAK,CACZ,CACF,EAEOC,EAAQzB","names":["path","sharp","readFile","NOT_FOUND_IMAGE","NOT_FOUND_AVATAR","FALLBACKIMAGES","API_REGEX","allowedFormats","mimeTypes","path","existsSync","fs","axios","isValidPath","basePath","specifiedPath","resolvedBase","path","resolvedPath","existsSync","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","outputFormat","allowedFormats","fetchImage","readLocalImage","image","sharp","resizeOptions","processedImage","processedFileName","path","mimeTypes","error","pixel_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/pixel.ts","../src/variables.ts","../src/functions.ts","../src/renders.ts"],"sourcesContent":["import path from \"node:path\";\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\nimport type { Request, Response, NextFunction } from \"express\";\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\nimport { allowedFormats, mimeTypes } from \"./variables\";\nimport { fetchImage, readLocalImage } from \"./functions\";\nimport { renderOptions, renderUserData } from \"./renders\";\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @function serveImage\n * @description Processes and serves an image based on user data and options.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The Express next function.\n * @param {Options} options - The options object for image processing.\n * @returns {Promise<void>}\n */\nconst serveImage = async (\n req: Request,\n res: Response,\n next: NextFunction,\n options: Options\n) => {\n try {\n const userData = renderUserData(req.query as UserData);\n const parsedOptions = renderOptions(options);\n\n let imageBuffer;\n let baseDir = parsedOptions.baseDir;\n let parsedUserId;\n\n if (userData.userId) {\n const userIdStr =\n typeof userData.userId === \"object\"\n ? String(Object.values(userData.userId)[0])\n : String(userData.userId);\n if (parsedOptions.idHandler) {\n parsedUserId = parsedOptions.idHandler(userIdStr);\n } else {\n parsedUserId = userIdStr;\n }\n }\n\n if (userData.folder === \"private\") {\n const dir = await parsedOptions?.getUserFolder?.(req, parsedUserId);\n if (dir) {\n baseDir = dir;\n }\n }\n\n const outputFormat = allowedFormats.includes(\n userData?.format?.toLowerCase() as ImageFormat\n )\n ? userData?.format?.toLowerCase()\n : \"jpeg\";\n\n if (userData?.src?.startsWith(\"http\")) {\n imageBuffer = await fetchImage(\n userData?.src ?? \"\",\n baseDir,\n parsedOptions?.websiteURL ?? \"\",\n userData?.type as ImageType,\n parsedOptions?.apiRegex,\n parsedOptions?.allowedNetworkList\n );\n } else {\n imageBuffer = await readLocalImage(\n userData?.src ?? \"\",\n baseDir,\n userData?.type as ImageType\n );\n }\n\n let image = sharp(imageBuffer);\n\n if (userData?.width || userData?.height) {\n const resizeOptions = {\n width: userData?.width ?? undefined,\n height: userData?.height ?? undefined,\n fit: sharp.fit.cover,\n };\n image = image.resize(resizeOptions as ResizeOptions);\n }\n\n const processedImage = await image\n .toFormat(outputFormat as keyof FormatEnum, {\n quality: userData?.quality ? Number(userData?.quality) : 80,\n })\n .toBuffer();\n\n const processedFileName = `${path.basename(\n userData?.src ?? \"\",\n path.extname(userData?.src ?? \"\")\n )}.${outputFormat}`;\n\n res.type(mimeTypes[outputFormat]);\n res.setHeader(\n \"Content-Disposition\",\n `inline; filename=\"${processedFileName}\"`\n );\n res.send(processedImage);\n } catch (error) {\n next(error);\n }\n};\n\n/**\n * @function registerServe\n * @description A function to register the serveImage function as middleware for Express.\n * @param {Options} options - The options object for image processing.\n * @returns {function(Request, Response, NextFunction): Promise<void>} The middleware function.\n */\nconst registerServe = (options: Options) => {\n return async (req: Request, res: Response, next: NextFunction) =>\n serveImage(req, res, next, options);\n};\n\nexport default registerServe;\n","import type { ImageFormat } from \"./types\";\nimport { readFile } from \"node:fs/promises\";\n\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url)\n .pathname;\n\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url)\n .pathname;\n\nexport const FALLBACKIMAGES = {\n normal: async () => readFile(NOT_FOUND_IMAGE),\n avatar: async () => readFile(NOT_FOUND_AVATAR),\n};\n\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\n\nexport const allowedFormats: ImageFormat[] = [\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"webp\",\n \"gif\",\n \"tiff\",\n \"avif\",\n \"svg\",\n];\n\nexport const mimeTypes: Readonly<Record<string, string>> = {\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n tiff: \"image/tiff\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n","import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport axios from \"axios\";\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\nimport type { ImageType } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * Checks if a specified path is valid within a base path.\n *\n * @param {string} basePath - The base directory to resolve paths.\n * @param {string} specifiedPath - The path to check.\n * @returns {boolean} True if the path is valid, false otherwise.\n */\nconst isValidPath = (basePath: string, specifiedPath: string): boolean => {\n if (!basePath || !specifiedPath) return false;\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\n return resolvedPath.startsWith(resolvedBase) && existsSync(resolvedPath);\n};\n\n/**\n * Fetches an image from a network source.\n *\n * @param {string} src - The URL of the image.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nconst fetchFromNetwork = async (\n src: string,\n type: ImageType = \"normal\"\n): Promise<Buffer> => {\n try {\n const response = await axios.get(src, {\n responseType: \"arraybuffer\",\n timeout: 5000,\n });\n\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\n const allowedMimeTypes = Object.values(mimeTypes);\n\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\n return Buffer.from(response.data);\n }\n return await FALLBACKIMAGES[type]();\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Reads an image from the local file system.\n *\n * @param {string} filePath - Path to the image file.\n * @param {string} baseDir - Base directory to resolve paths.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @returns {Promise<Buffer>} A buffer containing the image data.\n */\nexport const readLocalImage = async (\n filePath: string,\n baseDir: string,\n type: ImageType = \"normal\"\n) => {\n if (!isValidPath(baseDir, filePath)) {\n return await FALLBACKIMAGES[type]();\n }\n try {\n return await fs.readFile(path.resolve(baseDir, filePath));\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Fetches an image from either a local file or a network source.\n *\n * @param {string} src - The URL or local path of the image.\n * @param {string} baseDir - Base directory to resolve local paths.\n * @param {string} websiteURL - The URL of the website.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nexport const fetchImage = (\n src: string,\n baseDir: string,\n websiteURL: string,\n type: ImageType = \"normal\",\n apiRegex: RegExp = API_REGEX,\n allowedNetworkList: string[] = []\n) => {\n const url = new URL(src);\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\n if (isInternal) {\n const localPath = url.pathname.replace(apiRegex, \"\");\n return readLocalImage(localPath, baseDir, type);\n } else {\n const allowedCondition = allowedNetworkList.includes(url.host);\n if (!allowedCondition) {\n return FALLBACKIMAGES[type]();\n }\n return fetchFromNetwork(src, type);\n }\n};\n","import { API_REGEX } from \"./variables\";\nimport type { Options, UserData } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\n * @description Supported formats for image processing.\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @typedef {Object} UserData\n * @property {number|string} quality - Quality of the image (1–100).\n * @property {ImageFormat} format - Desired format of the image.\n * @property {string} [src] - Source path or URL for the image.\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\n * @property {string|null} [userId] - Optional user identifier.\n * @property {number|string} [width] - Desired image width.\n * @property {number|string} [height] - Desired image height.\n */\n\n/**\n * Renders the options object with default values and user-provided values.\n *\n * @param {Partial<Options>} options - The user-provided options.\n * @returns {Options} The rendered options object.\n */\nexport const renderOptions = (options: Partial<Options>): Options => {\n const initialOptions: Options = {\n baseDir: \"\",\n idHandler: (id: string) => id,\n getUserFolder: async () => \"\",\n websiteURL: \"\",\n apiRegex: API_REGEX,\n allowedNetworkList: [],\n };\n return {\n ...initialOptions,\n ...options,\n };\n};\n\n/**\n * Renders the user data object with default values and user-provided values.\n *\n * @param {Partial<UserData>} userData - The user-provided data.\n * @returns {UserData} The rendered user data object.\n */\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\n const initialUserData: UserData = {\n quality: 80,\n format: \"jpeg\",\n src: \"/placeholder/noimage.jpg\",\n folder: \"public\",\n type: \"normal\",\n width: undefined,\n height: undefined,\n userId: undefined,\n };\n return {\n ...initialUserData,\n ...userData,\n quality: userData.quality\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\n : 100,\n width: userData.width\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\n : undefined,\n height: userData.height\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\n : undefined,\n };\n};\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,YAC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EAAUG,EAEd,CAEA,IAAMC,EAAeC,EAAe,SAClCV,GAAU,QAAQ,YAAY,CAChC,EACIA,GAAU,QAAQ,YAAY,EAC9B,OAEAA,GAAU,KAAK,WAAW,MAAM,EAClCI,EAAc,MAAMO,EAClBX,GAAU,KAAO,GACjBK,EACAH,GAAe,YAAc,GAC7BF,GAAU,KACVE,GAAe,SACfA,GAAe,kBACjB,EAEAE,EAAc,MAAMQ,EAClBZ,GAAU,KAAO,GACjBK,EACAL,GAAU,IACZ,EAGF,IAAIa,EAAQC,EAAMV,CAAW,EAE7B,GAAIJ,GAAU,OAASA,GAAU,OAAQ,CACvC,IAAMe,EAAgB,CACpB,MAAOf,GAAU,OAAS,OAC1B,OAAQA,GAAU,QAAU,OAC5B,IAAKc,EAAM,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,GAAGC,EAAK,SAChClB,GAAU,KAAO,GACjBkB,EAAK,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":["path","sharp","readFile","NOT_FOUND_IMAGE","NOT_FOUND_AVATAR","FALLBACKIMAGES","API_REGEX","allowedFormats","mimeTypes","path","existsSync","fs","axios","isValidPath","basePath","specifiedPath","resolvedBase","path","resolvedPath","existsSync","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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pixel-serve-server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
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",
|