plugin.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import { MiddlewareConsumer, NestModule, OnApplicationBootstrap } from '@nestjs/common';
  2. import { Type } from '@vendure/common/lib/shared-types';
  3. import {
  4. AssetStorageStrategy,
  5. Logger,
  6. PluginCommonModule,
  7. ProcessContext,
  8. registerPluginStartupMessage,
  9. RuntimeVendureConfig,
  10. VendurePlugin,
  11. } from '@vendure/core';
  12. import { createHash } from 'crypto';
  13. import express, { NextFunction, Request, Response } from 'express';
  14. import { fromBuffer } from 'file-type';
  15. import fs from 'fs-extra';
  16. import path from 'path';
  17. import { loggerCtx } from './constants';
  18. import { defaultAssetStorageStrategyFactory } from './default-asset-storage-strategy-factory';
  19. import { HashedAssetNamingStrategy } from './hashed-asset-naming-strategy';
  20. import { SharpAssetPreviewStrategy } from './sharp-asset-preview-strategy';
  21. import { transformImage } from './transform-image';
  22. import { AssetServerOptions, ImageTransformPreset } from './types';
  23. /**
  24. * @description
  25. * The `AssetServerPlugin` serves assets (images and other files) from the local file system, and can also be configured to use
  26. * other storage strategies (e.g. {@link S3AssetStorageStrategy}. It can also perform on-the-fly image transformations
  27. * and caches the results for subsequent calls.
  28. *
  29. * ## Installation
  30. *
  31. * `yarn add \@vendure/asset-server-plugin`
  32. *
  33. * or
  34. *
  35. * `npm install \@vendure/asset-server-plugin`
  36. *
  37. * @example
  38. * ```ts
  39. * import { AssetServerPlugin } from '\@vendure/asset-server-plugin';
  40. *
  41. * const config: VendureConfig = {
  42. * // Add an instance of the plugin to the plugins array
  43. * plugins: [
  44. * AssetServerPlugin.init({
  45. * route: 'assets',
  46. * assetUploadDir: path.join(__dirname, 'assets'),
  47. * }),
  48. * ],
  49. * };
  50. * ```
  51. *
  52. * The full configuration is documented at [AssetServerOptions]({{< relref "asset-server-options" >}})
  53. *
  54. * ## Image transformation
  55. *
  56. * Asset preview images can be transformed (resized & cropped) on the fly by appending query parameters to the url:
  57. *
  58. * `http://localhost:3000/assets/some-asset.jpg?w=500&h=300&mode=resize`
  59. *
  60. * The above URL will return `some-asset.jpg`, resized to fit in the bounds of a 500px x 300px rectangle.
  61. *
  62. * ### Preview mode
  63. *
  64. * The `mode` parameter can be either `crop` or `resize`. See the [ImageTransformMode]({{< relref "image-transform-mode" >}}) docs for details.
  65. *
  66. * ### Focal point
  67. *
  68. * When cropping an image (`mode=crop`), Vendure will attempt to keep the most "interesting" area of the image in the cropped frame. It does this
  69. * by finding the area of the image with highest entropy (the busiest area of the image). However, sometimes this does not yield a satisfactory
  70. * result - part or all of the main subject may still be cropped out.
  71. *
  72. * This is where specifying the focal point can help. The focal point of the image may be specified by passing the `fpx` and `fpy` query parameters.
  73. * These are normalized coordinates (i.e. a number between 0 and 1), so the `fpx=0&fpy=0` corresponds to the top left of the image.
  74. *
  75. * For example, let's say there is a very wide landscape image which we want to crop to be square. The main subject is a house to the far left of the
  76. * image. The following query would crop it to a square with the house centered:
  77. *
  78. * `http://localhost:3000/assets/landscape.jpg?w=150&h=150&mode=crop&fpx=0.2&fpy=0.7`
  79. *
  80. * ### Transform presets
  81. *
  82. * Presets can be defined which allow a single preset name to be used instead of specifying the width, height and mode. Presets are
  83. * configured via the AssetServerOptions [presets property]({{< relref "asset-server-options" >}}#presets).
  84. *
  85. * For example, defining the following preset:
  86. *
  87. * ```ts
  88. * AssetServerPlugin.init({
  89. * // ...
  90. * presets: [
  91. * { name: 'my-preset', width: 85, height: 85, mode: 'crop' },
  92. * ],
  93. * }),
  94. * ```
  95. *
  96. * means that a request to:
  97. *
  98. * `http://localhost:3000/assets/some-asset.jpg?preset=my-preset`
  99. *
  100. * is equivalent to:
  101. *
  102. * `http://localhost:3000/assets/some-asset.jpg?w=85&h=85&mode=crop`
  103. *
  104. * The AssetServerPlugin comes pre-configured with the following presets:
  105. *
  106. * name | width | height | mode
  107. * -----|-------|--------|-----
  108. * tiny | 50px | 50px | crop
  109. * thumb | 150px | 150px | crop
  110. * small | 300px | 300px | resize
  111. * medium | 500px | 500px | resize
  112. * large | 800px | 800px | resize
  113. *
  114. * ### Caching
  115. * By default, the AssetServerPlugin will cache every transformed image, so that the transformation only needs to be performed a single time for
  116. * a given configuration. Caching can be disabled per-request by setting the `?cache=false` query parameter.
  117. *
  118. * @docsCategory AssetServerPlugin
  119. */
  120. @VendurePlugin({
  121. imports: [PluginCommonModule],
  122. configuration: config => AssetServerPlugin.configure(config),
  123. })
  124. export class AssetServerPlugin implements NestModule, OnApplicationBootstrap {
  125. private static assetStorage: AssetStorageStrategy;
  126. private readonly cacheDir = 'cache';
  127. private presets: ImageTransformPreset[] = [
  128. { name: 'tiny', width: 50, height: 50, mode: 'crop' },
  129. { name: 'thumb', width: 150, height: 150, mode: 'crop' },
  130. { name: 'small', width: 300, height: 300, mode: 'resize' },
  131. { name: 'medium', width: 500, height: 500, mode: 'resize' },
  132. { name: 'large', width: 800, height: 800, mode: 'resize' },
  133. ];
  134. private static options: AssetServerOptions;
  135. /**
  136. * @description
  137. * Set the plugin options.
  138. */
  139. static init(options: AssetServerOptions): Type<AssetServerPlugin> {
  140. AssetServerPlugin.options = options;
  141. return this;
  142. }
  143. /** @internal */
  144. static async configure(config: RuntimeVendureConfig) {
  145. const storageStrategyFactory =
  146. this.options.storageStrategyFactory || defaultAssetStorageStrategyFactory;
  147. this.assetStorage = await storageStrategyFactory(this.options);
  148. config.assetOptions.assetPreviewStrategy = new SharpAssetPreviewStrategy({
  149. maxWidth: this.options.previewMaxWidth || 1600,
  150. maxHeight: this.options.previewMaxHeight || 1600,
  151. });
  152. config.assetOptions.assetStorageStrategy = this.assetStorage;
  153. config.assetOptions.assetNamingStrategy =
  154. this.options.namingStrategy || new HashedAssetNamingStrategy();
  155. return config;
  156. }
  157. constructor(private processContext: ProcessContext) {}
  158. /** @internal */
  159. onApplicationBootstrap(): void | Promise<void> {
  160. if (this.processContext.isWorker) {
  161. return;
  162. }
  163. if (AssetServerPlugin.options.presets) {
  164. for (const preset of AssetServerPlugin.options.presets) {
  165. const existingIndex = this.presets.findIndex(p => p.name === preset.name);
  166. if (-1 < existingIndex) {
  167. this.presets.splice(existingIndex, 1, preset);
  168. } else {
  169. this.presets.push(preset);
  170. }
  171. }
  172. }
  173. const cachePath = path.join(AssetServerPlugin.options.assetUploadDir, this.cacheDir);
  174. fs.ensureDirSync(cachePath);
  175. }
  176. configure(consumer: MiddlewareConsumer) {
  177. if (this.processContext.isWorker) {
  178. return;
  179. }
  180. Logger.info('Creating asset server middleware', loggerCtx);
  181. consumer.apply(this.createAssetServer()).forRoutes(AssetServerPlugin.options.route);
  182. registerPluginStartupMessage('Asset server', AssetServerPlugin.options.route);
  183. }
  184. /**
  185. * Creates the image server instance
  186. */
  187. private createAssetServer() {
  188. const assetServer = express.Router();
  189. assetServer.use(this.sendAsset(), this.generateTransformedImage());
  190. return assetServer;
  191. }
  192. /**
  193. * Reads the file requested and send the response to the browser.
  194. */
  195. private sendAsset() {
  196. return async (req: Request, res: Response, next: NextFunction) => {
  197. const key = this.getFileNameFromRequest(req);
  198. try {
  199. const file = await AssetServerPlugin.assetStorage.readFileToBuffer(key);
  200. let mimeType = this.getMimeType(key);
  201. if (!mimeType) {
  202. mimeType = (await fromBuffer(file))?.mime || 'application/octet-stream';
  203. }
  204. res.contentType(mimeType);
  205. res.send(file);
  206. } catch (e) {
  207. const err = new Error('File not found');
  208. (err as any).status = 404;
  209. return next(err);
  210. }
  211. };
  212. }
  213. /**
  214. * If an exception was thrown by the first handler, then it may be because a transformed image
  215. * is being requested which does not yet exist. In this case, this handler will generate the
  216. * transformed image, save it to cache, and serve the result as a response.
  217. */
  218. private generateTransformedImage() {
  219. return async (err: any, req: Request, res: Response, next: NextFunction) => {
  220. if (err && (err.status === 404 || err.statusCode === 404)) {
  221. if (req.query) {
  222. const decodedReqPath = decodeURIComponent(req.path);
  223. Logger.debug(`Pre-cached Asset not found: ${decodedReqPath}`, loggerCtx);
  224. let file: Buffer;
  225. try {
  226. file = await AssetServerPlugin.assetStorage.readFileToBuffer(decodedReqPath);
  227. } catch (err) {
  228. res.status(404).send('Resource not found');
  229. return;
  230. }
  231. const image = await transformImage(file, req.query as any, this.presets || []);
  232. try {
  233. const imageBuffer = await image.toBuffer();
  234. if (!req.query.cache || req.query.cache === 'true') {
  235. const cachedFileName = this.getFileNameFromRequest(req);
  236. await AssetServerPlugin.assetStorage.writeFileFromBuffer(
  237. cachedFileName,
  238. imageBuffer,
  239. );
  240. Logger.debug(`Saved cached asset: ${cachedFileName}`, loggerCtx);
  241. }
  242. res.set('Content-Type', `image/${(await image.metadata()).format}`);
  243. res.send(imageBuffer);
  244. return;
  245. } catch (e) {
  246. Logger.error(e, 'AssetServerPlugin', e.stack);
  247. res.status(500).send(e.message);
  248. return;
  249. }
  250. }
  251. }
  252. next();
  253. };
  254. }
  255. private getFileNameFromRequest(req: Request): string {
  256. const { w, h, mode, preset, fpx, fpy } = req.query;
  257. const focalPoint = fpx && fpy ? `_fpx${fpx}_fpy${fpy}` : '';
  258. let imageParamHash: string | null = null;
  259. if (w || h) {
  260. const width = w || '';
  261. const height = h || '';
  262. imageParamHash = this.md5(`_transform_w${width}_h${height}_m${mode}${focalPoint}`);
  263. } else if (preset) {
  264. if (this.presets && !!this.presets.find(p => p.name === preset)) {
  265. imageParamHash = this.md5(`_transform_pre_${preset}${focalPoint}`);
  266. }
  267. }
  268. const decodedReqPath = decodeURIComponent(req.path);
  269. if (imageParamHash) {
  270. return path.join(this.cacheDir, this.addSuffix(decodedReqPath, imageParamHash));
  271. } else {
  272. return decodedReqPath;
  273. }
  274. }
  275. private md5(input: string): string {
  276. return createHash('md5').update(input).digest('hex');
  277. }
  278. private addSuffix(fileName: string, suffix: string): string {
  279. const ext = path.extname(fileName);
  280. const baseName = path.basename(fileName, ext);
  281. const dirName = path.dirname(fileName);
  282. return path.join(dirName, `${baseName}${suffix}${ext}`);
  283. }
  284. /**
  285. * Attempt to get the mime type from the file name.
  286. */
  287. private getMimeType(fileName: string): string | undefined {
  288. const ext = path.extname(fileName);
  289. switch (ext) {
  290. case '.jpg':
  291. case '.jpeg':
  292. return 'image/jpeg';
  293. case '.png':
  294. return 'image/png';
  295. case '.gif':
  296. return 'image/gif';
  297. case '.svg':
  298. return 'image/svg+xml';
  299. case '.tiff':
  300. return 'image/tiff';
  301. case '.webp':
  302. return 'image/webp';
  303. }
  304. }
  305. }