mikro-orm-attachments 2.0.0 → 2.1.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/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [2.1.0](https://github.com/reptoxx/mikro-orm-attachments/compare/mikro-orm-attachments@2.0.0...mikro-orm-attachments@2.1.0) (2026-04-08)
6
+
7
+
8
+ ### ⚠ BREAKING CHANGES
9
+
10
+ * only support v7
11
+
12
+ ### Features
13
+
14
+ * only support v7 ([4397990](https://github.com/reptoxx/mikro-orm-attachments/commit/4397990322df92c85c4c77b023f7e6e4072d0028))
15
+
5
16
  ## [2.0.0](https://github.com/reptoxx/mikro-orm-attachments/compare/mikro-orm-attachments@1.3.2...mikro-orm-attachments@2.0.0) (2026-04-07)
6
17
 
7
18
  ### [1.3.2](https://github.com/reptoxx/mikro-orm-attachments/compare/mikro-orm-attachments@1.3.1...mikro-orm-attachments@1.3.2) (2026-02-24)
@@ -1 +1 @@
1
- import{a}from"../shared/chunk-4thj50nc.js";export{a as BaseConverter};
1
+ import{a}from"../shared/chunk-4thj50nc.js";import"../shared/chunk-v2cxb1jc.js";export{a as BaseConverter};
@@ -1 +1 @@
1
- import{a as o}from"../shared/chunk-4thj50nc.js";import{b as i}from"../shared/chunk-cm81a68q.js";import{fileTypeFromBuffer as n}from"file-type";class m extends o{options;constructor(t){super();this.options=t}async supports(t){return t.mimeType.startsWith("image/")}async handle(t){let e=await(await i("imgkit")).transform(t.buffer,this.options??{}),r=await n(new Uint8Array(e.buffer));return{buffer:e,mimeType:r?.mime??t.mimeType,extname:r?.ext??t.extname}}}export{m as ImgkitConverter};
1
+ import{a as o}from"../shared/chunk-4thj50nc.js";import{b as i}from"../shared/chunk-tgvybtjr.js";import"../shared/chunk-v2cxb1jc.js";import{fileTypeFromBuffer as n}from"file-type";class m extends o{options;constructor(t){super();this.options=t}async supports(t){return t.mimeType.startsWith("image/")}async handle(t){let e=await(await i("imgkit")).transform(t.buffer,this.options??{}),r=await n(new Uint8Array(e.buffer));return{buffer:e,mimeType:r?.mime??t.mimeType,extname:r?.ext??t.extname}}}export{m as ImgkitConverter};
@@ -1 +1 @@
1
- import{a as n}from"../shared/chunk-4thj50nc.js";import{b as a}from"../shared/chunk-cm81a68q.js";import{fileTypeFromBuffer as h}from"file-type";class u extends n{options;constructor(t){super();this.options=t}async supports(t){return t.mimeType.startsWith("image/")}async handle(t){let s=await a("sharp"),f=this.options?.resize||{},e=this.options?.format||"webp",m=this.options?.autoOrient||!0,r={};if(typeof e!=="string")r=e?.options,e=e.format;let o=s(t.buffer).withMetadata();if(m)o.autoOrient();let p=await o.resize(f).toFormat(e,r).toBuffer(),i=await h(p);return{buffer:p,mimeType:i?.mime??t.mimeType,extname:i?.ext??t.extname}}}export{u as SharpConverter};
1
+ import{a as n}from"../shared/chunk-4thj50nc.js";import{b as a}from"../shared/chunk-tgvybtjr.js";import"../shared/chunk-v2cxb1jc.js";import{fileTypeFromBuffer as h}from"file-type";class u extends n{options;constructor(t){super();this.options=t}async supports(t){return t.mimeType.startsWith("image/")}async handle(t){let s=await a("sharp"),f=this.options?.resize||{},e=this.options?.format||"webp",m=this.options?.autoOrient||!0,r={};if(typeof e!=="string")r=e?.options,e=e.format;let o=s(t.buffer).withMetadata();if(m)o.autoOrient();let p=await o.resize(f).toFormat(e,r).toBuffer(),i=await h(p);return{buffer:p,mimeType:i?.mime??t.mimeType,extname:i?.ext??t.extname}}}export{u as SharpConverter};
package/dist/index.js CHANGED
@@ -1 +1,15 @@
1
- import{a as C}from"./shared/chunk-4thj50nc.js";import{c as W,d as l}from"./shared/chunk-cm81a68q.js";import{Buffer as B}from"node:buffer";var x=Symbol("attachment:loaded"),D=Symbol("attachment:options"),y=Symbol("attachment:file"),i=Symbol("attachment:disk"),P=Symbol("attachment:fn:process"),V=Symbol("attachment:fn:load"),O=Symbol("attachment:fn:save");class p{[x]=!1;[y];[i];data;constructor(t){if(t instanceof File)this[y]=t;else this[x]=!0,this.data=t}#t(){if(!this[x])throw Error("Attachment is not processed, please flush the entity first.")}get#s(){return this.#t(),this[i]}[O](){return this.data??{}}static[V](t){return new p(t)}[P](t){if(this[x])return;this.data=t,this[x]=!0}static fromFile(t){return new p(t)}static async fromUrl(t){let r=await fetch(t),s=await r.arrayBuffer(),e,o=r.headers.get("content-disposition");if(o){let S=o.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i);if(S)e=S[1].replace(/['"]/g,"")}if(!e)e=t.split("?")[0].split("/").pop()||"download";let c=B.from(s),n=new File([c],e,{type:r.headers.get("content-type")??""});return new p(n)}#r(t){this.#t();let r=this.data?.variants.find((s)=>s.name===t)??null;if(!r)throw Error(`Attachment: Variant '${t}' not found`);return r}url(t){if(this.#t(),t)return this.#s?.getUrl(this.#r(t).path);return this.data?.url}originalName(){return this.data?.originalName??""}size(t){if(t)return this.#r(t).size;return this.data?.size}meta(t){if(t)return this.#r(t).meta;return this.data?.meta}preSignedUrl(t,r){if(this.#t(),typeof t==="string")return this.#s?.getSignedUrl(this.#r(t).path,r);return this.#s?.getSignedUrl(this.data?.path??"",r)}blurhash(){return this.#t(),this.data?.blurhash}getDisk(){return this.#s}getDrive(){return this.data?.drive??""}async getBytes(t){this.#t();let r=t?this.#r(t).path:this.data?.path??"";return this.#s?.getBytes(r)}async getBuffer(t){this.#t();let r=await this.getBytes(t);if(!r)return null;return B.from(r)}async getStream(t){this.#t();let r=t?this.#r(t).path:this.data?.path??"";return this.#s?.getStream(r)}getMimeType(t){return this.#t(),(t?this.#r(t):this.data)?.mimeType??""}toJSON(){return{url:this.url(),blurhash:this.blurhash()}}}import{Disk as M}from"flydrive";import{join as I}from"node:path";import{fileTypeFromBuffer as Q}from"file-type";import{v7 as X}from"uuid";class b{att;file;disk;buffer;modelOptions;config;entity;columnName;diskName;fileInfo;constructor(t,r){this.att=t;let{disk:s,options:e,config:o,entity:c,columnName:n,diskName:h}=r;if(this.disk=s,this.modelOptions=e,this.config=o,this.entity=c,this.columnName=n,this.diskName=h,t[x])throw Error("Attachment already processed, please use the Attachment.fromFile method to create a new attachment");this.file=this.att[y]}done(t){this.att[P](t)}generateKey(t,...r){let s=this.modelOptions.folder??"";return s=s.replace(/:([A-Za-z0-9_]+)/g,(e,o)=>{let c=this.entity[o];if(c===void 0||c===null)throw Error(`Missing value for Attachment path "${o}" in entity ${this.entity.constructor.name}. Please ensure that the referenced property is computed before the attachment is processed. (Auto incrementing fields are not supported.)`);return this.normalizeFileName(String(c))}),I(s,t,...r)}normalizeFileName(t){return encodeURIComponent(t.replace(/[^a-zA-Z0-9.-]/g,"_")).toLowerCase()}async fileToBuffer(){if(this.buffer)return this.buffer;let t=await this.file.arrayBuffer(),r=Buffer.from(t);return this.buffer=r,r}getFileName(){if(!this.config.rename)return this.normalizeFileName(this.file.name);if(typeof this.config.rename==="function")return this.normalizeFileName(this.config.rename(this.file,this.columnName,this.entity));return this.normalizeFileName(X())}async getFileType(){return Q(await this.fileToBuffer())}async analyseFile(){let t=await this.getFileType();this.fileInfo={extname:t?.ext??this.file.name.split(".").pop()??"",mimeType:t?.mime??this.file.type,size:this.file.size}}async uploadFile(t,r){await this.disk.put(t,r)}async pickConverter(t,r){if(!this.fileInfo)throw Error("Attachment Converter: File info not found");if(this.config.variants?.[t])r=this.config.variants[t];if(r instanceof C){if(await r.supports({size:this.fileInfo.size,mimeType:this.fileInfo.mimeType,buffer:await this.fileToBuffer(),extname:this.fileInfo.extname}))return r}return null}async process(){await this.analyseFile();let t=await this.fileToBuffer(),r=this.getFileName(),s=this.fileInfo?.extname??"",e=this.generateKey(r,`${r}.${s}`);await this.uploadFile(e,t);let o={name:r,extname:s,size:this.file.size,drive:this.diskName,mimeType:this.file.type,path:e,url:await this.disk.getUrl(e),originalName:this.file.name,variants:[]},c=await this.config.metadata?.metadata({buffer:t,size:this.fileInfo?.size??0,mimeType:this.fileInfo?.mimeType??"",extname:this.fileInfo?.extname??""});if(o.meta=c,this.modelOptions.variants)for(let[n,h]of Object.entries(this.modelOptions.variants)){let S=await this.pickConverter(n,h);if(!S)throw Error(`Attachment Converter: No converter for the variant ${n} found`);let m=await S.handle({buffer:t,size:this.fileInfo?.size??0,mimeType:this.fileInfo?.mimeType??"",extname:this.fileInfo?.extname??"",variantName:n,variant:h}),g=this.generateKey(e.split("/").pop().split(".").shift(),`${n}.${m.extname}`);await this.uploadFile(g,m.buffer),o.variants.push({name:n,extname:m.extname,size:m.buffer.length,mimeType:m.mimeType,path:g})}if(this.fileInfo?.mimeType.startsWith("image/")){if(typeof this.modelOptions.blurhash==="boolean"?this.modelOptions.blurhash:this.modelOptions.blurhash?.enabled)o.blurhash=await l(t,typeof this.modelOptions.blurhash==="object"?this.modelOptions.blurhash:void 0)}this.done(o)}}import{Type as Z,ValidationError as $}from"@mikro-orm/core";class R extends Z{options={folder:"attachments",blurhash:!0};constructor(t){super();this.options={...this.options,...t}}convertToDatabaseValue(t){if(t===null)return null;if(t instanceof p)return t[O]();return t}convertToJSValue(t){try{return p[V](JSON.parse(t))}catch(r){try{return p[V](t)}catch(s){throw $.invalidType(R,t,"database")}}}getColumnType(){return"json"}}var J={blurhash:!0},T={rename:!0},F=["accessor","comment","customOrder","getter","getterName","hidden","index","lazy","name","nullable","serializedName","serializedPrimaryKey","serializer","version"];var{Property:w}=W(["@mikro-orm/decorators/legacy","@mikro-orm/core"]),d=Symbol("attachment:props");function A(t={}){return(r,s)=>{let{mikro:e,attachment:o}=G(t,F);o={...J,...o};let c=r.constructor;if(!c[d])c[d]={};return c[d][s]=o,w({...e,type:new R(o)})(r,s)}}function Y(t){return A(t)}function z(t){let s=t.constructor[d];return s?s:{}}function G(t,r){let s=new Set(r),e={},o={};for(let c in t)if(s.has(c))e[c]=t[c];else o[c]=t[c];return{mikro:e,attachment:o}}class q{options;disks;constructor(t){this.options=t;this.options={...T,...this.options},this.disks=new Map(Object.entries(this.options.drivers).map(([r,s])=>[r,new M(s)]))}async onLoad(t){let{entity:r}=t,s=z(r);for(let e of Object.keys(s)){let o=r[e],c=s[e];if(o instanceof p){let n=this.#t(c,o.getDrive(),!1);if(!n)continue;o[i]=n}}}#t(t,r,s){let e=this.disks.get(r??t.driver??this.options.defaultDriver);if(r&&!e)e=this.disks.get(t.driver??this.options.defaultDriver);if(!e){if(s)throw Error(`Unknown attachment driver "${String(r??t.driver??this.options.defaultDriver)}"`);return null}return e}async beforeFlush(t){let{uow:r}=t,s=new Set([...r.getChangeSets().map((e)=>e.entity),...r.getPersistStack()]);for(let e of s)await this.#s(e)}async#s(t){let r=z(t);for(let s of Object.keys(r)){let e=t[s],o=r[s];if(e instanceof p){if(e[x])continue;let c=this.#t(o);if(!c)continue;e[i]=c;let n=this.#r(o.variants),h=new b(e,{disk:c,options:{...o,variants:n},config:this.options,entity:t,columnName:s,diskName:o.driver??this.options.defaultDriver});try{await h.process()}catch(S){throw console.error(S),Error("Failed to process attachment")}}}}AttachmentDecorator(t){return Y(t)}#r(t){if(!t)return;if(Array.isArray(t)){let r={};for(let s of t)if(typeof s==="string"){let e=this.options.variants?.[s];if(!e)throw Error(`Unknown attachment variant "${s}"`);r[s]=e}else if(s&&typeof s==="object")Object.assign(r,s);return r}if(t&&typeof t==="object")return t;return}}export{q as AttachmentSubscriber,p as Attachment};
1
+ import{a as jY}from"./shared/chunk-4thj50nc.js";import{c as wY}from"./shared/chunk-tgvybtjr.js";import{e as HV,f as WV}from"./shared/chunk-v2cxb1jc.js";var UY=WV(()=>{/*! *****************************************************************************
2
+ Copyright (C) Microsoft. All rights reserved.
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4
+ this file except in compliance with the License. You may obtain a copy of the
5
+ License at http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10
+ MERCHANTABLITY OR NON-INFRINGEMENT.
11
+
12
+ See the Apache Version 2.0 License for specific language governing permissions
13
+ and limitations under the License.
14
+ ***************************************************************************** */var xY;(function(A){(function(X){var Q=typeof globalThis==="object"?globalThis:typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:x(),q=H(A);if(typeof Q.Reflect<"u")q=H(Q.Reflect,q);if(X(q,Q),typeof Q.Reflect>"u")Q.Reflect=A;function H(D,U){return function(b,v){if(Object.defineProperty(D,b,{configurable:!0,writable:!0,value:v}),U)U(b,v)}}function L(){try{return Function("return this;")()}catch(D){}}function E(){try{return(0,eval)("(function() { return this; })()")}catch(D){}}function x(){return L()||E()}})(function(X,Q){var q=Object.prototype.hasOwnProperty,H=typeof Symbol==="function",L=H&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",E=H&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",x=typeof Object.create==="function",D={__proto__:[]}instanceof Array,U=!x&&!D,b={create:x?function(){return YY(Object.create(null))}:D?function(){return YY({__proto__:null})}:function(){return YY({})},has:U?function(Y,V){return q.call(Y,V)}:function(Y,V){return V in Y},get:U?function(Y,V){return q.call(Y,V)?Y[V]:void 0}:function(Y,V){return Y[V]}},v=Object.getPrototypeOf(Function),c=typeof Map==="function"&&typeof Map.prototype.entries==="function"?Map:YV(),o=typeof Set==="function"&&typeof Set.prototype.entries==="function"?Set:VV(),r=typeof WeakMap==="function"?WeakMap:AV(),K=H?Symbol.for("@reflect-metadata:registry"):void 0,s=aY(),XY=tY(s);function OY(Y,V,J,$){if(!R(J)){if(!HY(Y))throw TypeError();if(!T(V))throw TypeError();if(!T($)&&!R($)&&!k($))throw TypeError();if(k($))$=void 0;return J=P(J),nY(Y,V,J,$)}else{if(!HY(Y))throw TypeError();if(!RY(V))throw TypeError();return sY(Y,V)}}X("decorate",OY);function KY(Y,V){function J($,W){if(!T($))throw TypeError();if(!R(W)&&!oY(W))throw TypeError();ZY(Y,V,$,W)}return J}X("metadata",KY);function kY(Y,V,J,$){if(!T(J))throw TypeError();if(!R($))$=P($);return ZY(Y,V,J,$)}X("defineMetadata",kY);function uY(Y,V,J){if(!T(V))throw TypeError();if(!R(J))J=P(J);return $Y(Y,V,J)}X("hasMetadata",uY);function MY(Y,V,J){if(!T(V))throw TypeError();if(!R(J))J=P(J);return a(Y,V,J)}X("hasOwnMetadata",MY);function vY(Y,V,J){if(!T(V))throw TypeError();if(!R(J))J=P(J);return QY(Y,V,J)}X("getMetadata",vY);function cY(Y,V,J){if(!T(V))throw TypeError();if(!R(J))J=P(J);return BY(Y,V,J)}X("getOwnMetadata",cY);function mY(Y,V){if(!T(Y))throw TypeError();if(!R(V))V=P(V);return zY(Y,V)}X("getMetadataKeys",mY);function gY(Y,V){if(!T(Y))throw TypeError();if(!R(V))V=P(V);return FY(Y,V)}X("getOwnMetadataKeys",gY);function lY(Y,V,J){if(!T(V))throw TypeError();if(!R(J))J=P(J);if(!T(V))throw TypeError();if(!R(J))J=P(J);var $=m(V,J,!1);if(R($))return!1;return $.OrdinaryDeleteMetadata(Y,V,J)}X("deleteMetadata",lY);function sY(Y,V){for(var J=Y.length-1;J>=0;--J){var $=Y[J],W=$(V);if(!R(W)&&!k(W)){if(!RY(W))throw TypeError();V=W}}return V}function nY(Y,V,J,$){for(var W=Y.length-1;W>=0;--W){var j=Y[W],h=j(V,J,$);if(!R(h)&&!k(h)){if(!T(h))throw TypeError();$=h}}return $}function $Y(Y,V,J){var $=a(Y,V,J);if($)return!0;var W=e(V);if(!k(W))return $Y(Y,W,J);return!1}function a(Y,V,J){var $=m(V,J,!1);if(R($))return!1;return WY($.OrdinaryHasOwnMetadata(Y,V,J))}function QY(Y,V,J){var $=a(Y,V,J);if($)return BY(Y,V,J);var W=e(V);if(!k(W))return QY(Y,W,J);return}function BY(Y,V,J){var $=m(V,J,!1);if(R($))return;return $.OrdinaryGetOwnMetadata(Y,V,J)}function ZY(Y,V,J,$){var W=m(J,$,!0);W.OrdinaryDefineOwnMetadata(Y,V,J,$)}function zY(Y,V){var J=FY(Y,V),$=e(Y);if($===null)return J;var W=zY($,V);if(W.length<=0)return J;if(J.length<=0)return W;var j=new o,h=[];for(var _=0,B=J;_<B.length;_++){var Z=B[_],z=j.has(Z);if(!z)j.add(Z),h.push(Z)}for(var F=0,G=W;F<G.length;F++){var Z=G[F],z=j.has(Z);if(!z)j.add(Z),h.push(Z)}return h}function FY(Y,V){var J=m(Y,V,!1);if(!J)return[];return J.OrdinaryOwnMetadataKeys(Y,V)}function qY(Y){if(Y===null)return 1;switch(typeof Y){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return Y===null?1:6;default:return 6}}function R(Y){return Y===void 0}function k(Y){return Y===null}function dY(Y){return typeof Y==="symbol"}function T(Y){return typeof Y==="object"?Y!==null:typeof Y==="function"}function yY(Y,V){switch(qY(Y)){case 0:return Y;case 1:return Y;case 2:return Y;case 3:return Y;case 4:return Y;case 5:return Y}var J=V===3?"string":V===5?"number":"default",$=_Y(Y,L);if($!==void 0){var W=$.call(Y,J);if(T(W))throw TypeError();return W}return iY(Y,J==="default"?"number":J)}function iY(Y,V){if(V==="string"){var J=Y.toString;if(u(J)){var $=J.call(Y);if(!T($))return $}var W=Y.valueOf;if(u(W)){var $=W.call(Y);if(!T($))return $}}else{var W=Y.valueOf;if(u(W)){var $=W.call(Y);if(!T($))return $}var j=Y.toString;if(u(j)){var $=j.call(Y);if(!T($))return $}}throw TypeError()}function WY(Y){return!!Y}function pY(Y){return""+Y}function P(Y){var V=yY(Y,3);if(dY(V))return V;return pY(V)}function HY(Y){return Array.isArray?Array.isArray(Y):Y instanceof Object?Y instanceof Array:Object.prototype.toString.call(Y)==="[object Array]"}function u(Y){return typeof Y==="function"}function RY(Y){return typeof Y==="function"}function oY(Y){switch(qY(Y)){case 3:return!0;case 4:return!0;default:return!1}}function t(Y,V){return Y===V||Y!==Y&&V!==V}function _Y(Y,V){var J=Y[V];if(J===void 0||J===null)return;if(!u(J))throw TypeError();return J}function GY(Y){var V=_Y(Y,E);if(!u(V))throw TypeError();var J=V.call(Y);if(!T(J))throw TypeError();return J}function LY(Y){return Y.value}function DY(Y){var V=Y.next();return V.done?!1:V}function EY(Y){var V=Y.return;if(V)V.call(Y)}function e(Y){var V=Object.getPrototypeOf(Y);if(typeof Y!=="function"||Y===v)return V;if(V!==v)return V;var J=Y.prototype,$=J&&Object.getPrototypeOf(J);if($==null||$===Object.prototype)return V;var W=$.constructor;if(typeof W!=="function")return V;if(W===Y)return V;return W}function rY(){var Y;if(!R(K)&&typeof Q.Reflect<"u"&&!(K in Q.Reflect)&&typeof Q.Reflect.defineMetadata==="function")Y=eY(Q.Reflect);var V,J,$,W=new r,j={registerProvider:h,getProvider:B,setProvider:z};return j;function h(F){if(!Object.isExtensible(j))throw Error("Cannot add provider to a frozen registry.");switch(!0){case Y===F:break;case R(V):V=F;break;case V===F:break;case R(J):J=F;break;case J===F:break;default:if($===void 0)$=new o;$.add(F);break}}function _(F,G){if(!R(V)){if(V.isProviderFor(F,G))return V;if(!R(J)){if(J.isProviderFor(F,G))return V;if(!R($)){var S=GY($);while(!0){var w=DY(S);if(!w)return;var I=LY(w);if(I.isProviderFor(F,G))return EY(S),I}}}}if(!R(Y)&&Y.isProviderFor(F,G))return Y;return}function B(F,G){var S=W.get(F),w;if(!R(S))w=S.get(G);if(!R(w))return w;if(w=_(F,G),!R(w)){if(R(S))S=new c,W.set(F,S);S.set(G,w)}return w}function Z(F){if(R(F))throw TypeError();return V===F||J===F||!R($)&&$.has(F)}function z(F,G,S){if(!Z(S))throw Error("Metadata provider not registered.");var w=B(F,G);if(w!==S){if(!R(w))return!1;var I=W.get(F);if(R(I))I=new c,W.set(F,I);I.set(G,S)}return!0}}function aY(){var Y;if(!R(K)&&T(Q.Reflect)&&Object.isExtensible(Q.Reflect))Y=Q.Reflect[K];if(R(Y))Y=rY();if(!R(K)&&T(Q.Reflect)&&Object.isExtensible(Q.Reflect))Object.defineProperty(Q.Reflect,K,{enumerable:!1,configurable:!1,writable:!1,value:Y});return Y}function tY(Y){var V=new r,J={isProviderFor:function(Z,z){var F=V.get(Z);if(R(F))return!1;return F.has(z)},OrdinaryDefineOwnMetadata:h,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:j,OrdinaryOwnMetadataKeys:_,OrdinaryDeleteMetadata:B};return s.registerProvider(J),J;function $(Z,z,F){var G=V.get(Z),S=!1;if(R(G)){if(!F)return;G=new c,V.set(Z,G),S=!0}var w=G.get(z);if(R(w)){if(!F)return;if(w=new c,G.set(z,w),!Y.setProvider(Z,z,J)){if(G.delete(z),S)V.delete(Z);throw Error("Wrong provider for target.")}}return w}function W(Z,z,F){var G=$(z,F,!1);if(R(G))return!1;return WY(G.has(Z))}function j(Z,z,F){var G=$(z,F,!1);if(R(G))return;return G.get(Z)}function h(Z,z,F,G){var S=$(F,G,!0);S.set(Z,z)}function _(Z,z){var F=[],G=$(Z,z,!1);if(R(G))return F;var S=G.keys(),w=GY(S),I=0;while(!0){var SY=DY(w);if(!SY)return F.length=I,F;var JV=LY(SY);try{F[I]=JV}catch(XV){try{EY(w)}finally{throw XV}}I++}}function B(Z,z,F){var G=$(z,F,!1);if(R(G))return!1;if(!G.delete(Z))return!1;if(G.size===0){var S=V.get(z);if(!R(S)){if(S.delete(F),S.size===0)V.delete(S)}}return!0}}function eY(Y){var{defineMetadata:V,hasOwnMetadata:J,getOwnMetadata:$,getOwnMetadataKeys:W,deleteMetadata:j}=Y,h=new r,_={isProviderFor:function(B,Z){var z=h.get(B);if(!R(z)&&z.has(Z))return!0;if(W(B,Z).length){if(R(z))z=new o,h.set(B,z);return z.add(Z),!0}return!1},OrdinaryDefineOwnMetadata:V,OrdinaryHasOwnMetadata:J,OrdinaryGetOwnMetadata:$,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:j};return _}function m(Y,V,J){var $=s.getProvider(Y,V);if(!R($))return $;if(J){if(s.setProvider(Y,V,XY))return XY;throw Error("Illegal state.")}return}function YV(){var Y={},V=[],J=function(){function _(B,Z,z){this._index=0,this._keys=B,this._values=Z,this._selector=z}return _.prototype["@@iterator"]=function(){return this},_.prototype[E]=function(){return this},_.prototype.next=function(){var B=this._index;if(B>=0&&B<this._keys.length){var Z=this._selector(this._keys[B],this._values[B]);if(B+1>=this._keys.length)this._index=-1,this._keys=V,this._values=V;else this._index++;return{value:Z,done:!1}}return{value:void 0,done:!0}},_.prototype.throw=function(B){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;throw B},_.prototype.return=function(B){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;return{value:B,done:!0}},_}(),$=function(){function _(){this._keys=[],this._values=[],this._cacheKey=Y,this._cacheIndex=-2}return Object.defineProperty(_.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),_.prototype.has=function(B){return this._find(B,!1)>=0},_.prototype.get=function(B){var Z=this._find(B,!1);return Z>=0?this._values[Z]:void 0},_.prototype.set=function(B,Z){var z=this._find(B,!0);return this._values[z]=Z,this},_.prototype.delete=function(B){var Z=this._find(B,!1);if(Z>=0){var z=this._keys.length;for(var F=Z+1;F<z;F++)this._keys[F-1]=this._keys[F],this._values[F-1]=this._values[F];if(this._keys.length--,this._values.length--,t(B,this._cacheKey))this._cacheKey=Y,this._cacheIndex=-2;return!0}return!1},_.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=Y,this._cacheIndex=-2},_.prototype.keys=function(){return new J(this._keys,this._values,W)},_.prototype.values=function(){return new J(this._keys,this._values,j)},_.prototype.entries=function(){return new J(this._keys,this._values,h)},_.prototype["@@iterator"]=function(){return this.entries()},_.prototype[E]=function(){return this.entries()},_.prototype._find=function(B,Z){if(!t(this._cacheKey,B)){this._cacheIndex=-1;for(var z=0;z<this._keys.length;z++)if(t(this._keys[z],B)){this._cacheIndex=z;break}}if(this._cacheIndex<0&&Z)this._cacheIndex=this._keys.length,this._keys.push(B),this._values.push(void 0);return this._cacheIndex},_}();return $;function W(_,B){return _}function j(_,B){return B}function h(_,B){return[_,B]}}function VV(){var Y=function(){function V(){this._map=new c}return Object.defineProperty(V.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),V.prototype.has=function(J){return this._map.has(J)},V.prototype.add=function(J){return this._map.set(J,J),this},V.prototype.delete=function(J){return this._map.delete(J)},V.prototype.clear=function(){this._map.clear()},V.prototype.keys=function(){return this._map.keys()},V.prototype.values=function(){return this._map.keys()},V.prototype.entries=function(){return this._map.entries()},V.prototype["@@iterator"]=function(){return this.keys()},V.prototype[E]=function(){return this.keys()},V}();return Y}function AV(){var Y=16,V=b.create(),J=$();return function(){function B(){this._key=$()}return B.prototype.has=function(Z){var z=W(Z,!1);return z!==void 0?b.has(z,this._key):!1},B.prototype.get=function(Z){var z=W(Z,!1);return z!==void 0?b.get(z,this._key):void 0},B.prototype.set=function(Z,z){var F=W(Z,!0);return F[this._key]=z,this},B.prototype.delete=function(Z){var z=W(Z,!1);return z!==void 0?delete z[this._key]:!1},B.prototype.clear=function(){this._key=$()},B}();function $(){var B;do B="@@WeakMap@@"+_();while(b.has(V,B));return V[B]=!0,B}function W(B,Z){if(!q.call(B,J)){if(!Z)return;Object.defineProperty(B,J,{value:b.create()})}return B[J]}function j(B,Z){for(var z=0;z<Z;++z)B[z]=Math.random()*255|0;return B}function h(B){if(typeof Uint8Array==="function"){var Z=new Uint8Array(B);if(typeof crypto<"u")crypto.getRandomValues(Z);else if(typeof msCrypto<"u")msCrypto.getRandomValues(Z);else j(Z,B);return Z}return j(Array(B),B)}function _(){var B=h(Y);B[6]=B[6]&79|64,B[8]=B[8]&191|128;var Z="";for(var z=0;z<Y;++z){var F=B[z];if(z===4||z===6||z===8)Z+="-";if(F<16)Z+="0";Z+=F.toString(16).toLowerCase()}return Z}}function YY(Y){return Y.__=void 0,delete Y.__,Y}})})(xY||(xY={}))});import{Buffer as TY}from"node:buffer";var f=Symbol("attachment:loaded"),EV=Symbol("attachment:options"),g=Symbol("attachment:file"),M=Symbol("attachment:disk"),n=Symbol("attachment:fn:process"),l=Symbol("attachment:fn:load"),d=Symbol("attachment:fn:save");class N{[f]=!1;[g];[M];data;constructor(A){if(A instanceof File)this[g]=A;else this[f]=!0,this.data=A}#Y(){if(!this[f])throw Error("Attachment is not processed, please flush the entity first.")}get#A(){return this.#Y(),this[M]}[d](){return this.data??{}}static[l](A){return new N(A)}[n](A){if(this[f])return;this.data=A,this[f]=!0}static fromFile(A){return new N(A)}static async fromUrl(A){let X=await fetch(A),Q=await X.arrayBuffer(),q,H=X.headers.get("content-disposition");if(H){let D=H.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i);if(D)q=D[1].replace(/['"]/g,"")}if(!q)q=A.split("?")[0].split("/").pop()||"download";let L=TY.from(Q),E=new File([L],q,{type:X.headers.get("content-type")??""});return new N(E)}#V(A){this.#Y();let X=this.data?.variants.find((Q)=>Q.name===A)??null;if(!X)throw Error(`Attachment: Variant '${A}' not found`);return X}url(A){if(this.#Y(),A)return this.#A?.getUrl(this.#V(A).path);return this.data?.url}originalName(){return this.data?.originalName??""}size(A){if(A)return this.#V(A).size;return this.data?.size}meta(A){if(A)return this.#V(A).meta;return this.data?.meta}preSignedUrl(A,X){if(this.#Y(),typeof A==="string")return this.#A?.getSignedUrl(this.#V(A).path,X);return this.#A?.getSignedUrl(this.data?.path??"",X)}blurhash(){return this.#Y(),this.data?.blurhash}getDisk(){return this.#A}getDrive(){return this.data?.drive??""}async getBytes(A){this.#Y();let X=A?this.#V(A).path:this.data?.path??"";return this.#A?.getBytes(X)}async getBuffer(A){this.#Y();let X=await this.getBytes(A);if(!X)return null;return TY.from(X)}async getStream(A){this.#Y();let X=A?this.#V(A).path:this.data?.path??"";return this.#A?.getStream(X)}getMimeType(A){return this.#Y(),(A?this.#V(A):this.data)?.mimeType??""}toJSON(){return{url:this.url(),blurhash:this.blurhash()}}}import{Disk as DV}from"flydrive";import{join as $V}from"node:path";import{fileTypeFromBuffer as QV}from"file-type";import{v7 as BV}from"uuid";class VY{att;file;disk;buffer;modelOptions;config;entity;columnName;diskName;fileInfo;constructor(A,X){this.att=A;let{disk:Q,options:q,config:H,entity:L,columnName:E,diskName:x}=X;if(this.disk=Q,this.modelOptions=q,this.config=H,this.entity=L,this.columnName=E,this.diskName=x,A[f])throw Error("Attachment already processed, please use the Attachment.fromFile method to create a new attachment");this.file=this.att[g]}done(A){this.att[n](A)}generateKey(A,...X){let Q=this.modelOptions.folder??"";return Q=Q.replace(/:([A-Za-z0-9_]+)/g,(q,H)=>{let L=this.entity[H];if(L===void 0||L===null)throw Error(`Missing value for Attachment path "${H}" in entity ${this.entity.constructor.name}. Please ensure that the referenced property is computed before the attachment is processed. (Auto incrementing fields are not supported.)`);return this.normalizeFileName(String(L))}),$V(Q,A,...X)}normalizeFileName(A){return encodeURIComponent(A.replace(/[^a-zA-Z0-9.-]/g,"_")).toLowerCase()}async fileToBuffer(){if(this.buffer)return this.buffer;let A=await this.file.arrayBuffer(),X=Buffer.from(A);return this.buffer=X,X}getFileName(){if(!this.config.rename)return this.normalizeFileName(this.file.name);if(typeof this.config.rename==="function")return this.normalizeFileName(this.config.rename(this.file,this.columnName,this.entity));return this.normalizeFileName(BV())}async getFileType(){return QV(await this.fileToBuffer())}async analyseFile(){let A=await this.getFileType();this.fileInfo={extname:A?.ext??this.file.name.split(".").pop()??"",mimeType:A?.mime??this.file.type,size:this.file.size}}async uploadFile(A,X){await this.disk.put(A,X)}async pickConverter(A,X){if(!this.fileInfo)throw Error("Attachment Converter: File info not found");if(this.config.variants?.[A])X=this.config.variants[A];if(X instanceof jY){if(await X.supports({size:this.fileInfo.size,mimeType:this.fileInfo.mimeType,buffer:await this.fileToBuffer(),extname:this.fileInfo.extname}))return X}return null}async process(){await this.analyseFile();let A=await this.fileToBuffer(),X=this.getFileName(),Q=this.fileInfo?.extname??"",q=this.generateKey(X,`${X}.${Q}`);await this.uploadFile(q,A);let H={name:X,extname:Q,size:this.file.size,drive:this.diskName,mimeType:this.file.type,path:q,url:await this.disk.getUrl(q),originalName:this.file.name,variants:[]},L=await this.config.metadata?.metadata({buffer:A,size:this.fileInfo?.size??0,mimeType:this.fileInfo?.mimeType??"",extname:this.fileInfo?.extname??""});if(H.meta=L,this.modelOptions.variants)for(let[E,x]of Object.entries(this.modelOptions.variants)){let D=await this.pickConverter(E,x);if(!D)throw Error(`Attachment Converter: No converter for the variant ${E} found`);let U=await D.handle({buffer:A,size:this.fileInfo?.size??0,mimeType:this.fileInfo?.mimeType??"",extname:this.fileInfo?.extname??"",variantName:E,variant:x}),b=this.generateKey(q.split("/").pop().split(".").shift(),`${E}.${U.extname}`);await this.uploadFile(b,U.buffer),H.variants.push({name:E,extname:U.extname,size:U.buffer.length,mimeType:U.mimeType,path:b})}if(this.fileInfo?.mimeType.startsWith("image/")){if(typeof this.modelOptions.blurhash==="boolean"?this.modelOptions.blurhash:this.modelOptions.blurhash?.enabled)H.blurhash=await wY(A,typeof this.modelOptions.blurhash==="object"?this.modelOptions.blurhash:void 0)}this.done(H)}}import{ReferenceKind as vV}from"@mikro-orm/core";import{EntityManager as fV,EntityRepository as OV,MetadataError as ZV,MetadataStorage as y,MikroORM as KV,Utils as kV}from"@mikro-orm/core";function O(A,X,Q){if(A.properties[X]&&A.properties[X].kind!==Q)throw ZV.multipleDecorators(A.className,X)}function zV(A,X){X=X||Error().stack.split(`
15
+ `);let Q=X.findIndex((q)=>/__decorate|Reflect\.decorate|_applyDecoratedDescriptor|applyClassDecs/.exec(q));if(Q===-1){let q=X.findLastIndex((H)=>H.includes("bun:wrap"));if(q!==-1&&q+1<X.length)Q=q+1;else{let H=X.findLastIndex((L)=>L.replace(/\\/g,"/").includes("node_modules/reflect-metadata/Reflect.js"));if(H===-1||H+2>=X.length||!X[H+1].includes("bun:wrap"))return A;Q=H+2}}if(X[Q].includes("Reflect.decorate"))Q++;while(Q<X.length&&/node_modules\/tslib\/|@oxc-project[/+]runtime/.test(X[Q].replace(/\\/g,"/")))Q++;try{let q=/\(.+\)/i.exec(X[Q])?/\((.*?)(?::\d+){1,2}\)/:/at\s*(.*?)(?::\d+){1,2}$/;return X[Q].match(q)[1]}catch{return A}}function C(A){if(!Object.hasOwn(A,y.PATH_SYMBOL))Object.defineProperty(A,y.PATH_SYMBOL,{value:zV(A.name),writable:!0});return y.getMetadata(A.name,A[y.PATH_SYMBOL])}import{Utils as lV}from"@mikro-orm/core";import{ReferenceKind as yV}from"@mikro-orm/core";import{ReferenceKind as rV}from"@mikro-orm/core";import{ReferenceKind as YA}from"@mikro-orm/core";import{ReferenceKind as XA}from"@mikro-orm/core";import{Utils as FV,ReferenceKind as hY}from"@mikro-orm/core";function CY(A={}){return function(X,Q){let q=C(X.constructor),H=Object.getOwnPropertyDescriptor(X,Q)||{};O(q,Q,hY.SCALAR);let L=A.name||Q;if(Q!==L&&!(H.value instanceof Function))FV.renameKey(A,"name","fieldName");A.name=Q;let{check:E,...x}=A,D={kind:hY.SCALAR,...x};if(D.getter=!!H.get,D.setter=!!H.set,H.value instanceof Function)D.getter=!0,D.persist=!1,D.type="method",D.getterName=Q,D.name=L;if(E)q.checks.push({property:D.name,expression:E});q.properties[D.name]=D}}import{ReferenceKind as HA}from"@mikro-orm/core";import{ReferenceKind as LA}from"@mikro-orm/core";import{ReferenceKind as CA,Utils as xA}from"@mikro-orm/core";import{RequestContext as fA,TransactionContext as OA}from"@mikro-orm/core";import{EventType as MA}from"@mikro-orm/core";import{TransactionPropagation as gA,RequestContext as lA,TransactionContext as sA}from"@mikro-orm/core";var pA=HV(UY(),1);import{EntitySchema as rA,MetadataProvider as aA,ReferenceKind as tA,Utils as eA}from"@mikro-orm/core";import{Type as RV,ValidationError as _V}from"@mikro-orm/core";class i extends RV{options={folder:"attachments",blurhash:!0};constructor(A){super();this.options={...this.options,...A}}convertToDatabaseValue(A){if(A===null)return null;if(A instanceof N)return A[d]();return A}convertToJSValue(A){try{return N[l](JSON.parse(A))}catch(X){try{return N[l](A)}catch(Q){throw _V.invalidType(i,A,"database")}}}getColumnType(){return"json"}}var NY={blurhash:!0},bY={rename:!0},IY=["accessor","comment","customOrder","getter","getterName","hidden","index","lazy","name","nullable","serializedName","serializedPrimaryKey","serializer","version"];var p=Symbol("attachment:props");function GV(A={}){return(X,Q)=>{let{mikro:q,attachment:H}=LV(A,IY);H={...NY,...H};let L=X.constructor;if(!L[p])L[p]={};return L[p][Q]=H,CY({...q,type:new i(H)})(X,Q)}}function PY(A){return GV(A)}function JY(A){let Q=A.constructor[p];return Q?Q:{}}function LV(A,X){let Q=new Set(X),q={},H={};for(let L in A)if(Q.has(L))q[L]=A[L];else H[L]=A[L];return{mikro:q,attachment:H}}class fY{options;disks;constructor(A){this.options=A;this.options={...bY,...this.options},this.disks=new Map(Object.entries(this.options.drivers).map(([X,Q])=>[X,new DV(Q)]))}async onLoad(A){let{entity:X}=A,Q=JY(X);for(let q of Object.keys(Q)){let H=X[q],L=Q[q];if(H instanceof N){let E=this.#Y(L,H.getDrive(),!1);if(!E)continue;H[M]=E}}}#Y(A,X,Q){let q=this.disks.get(X??A.driver??this.options.defaultDriver);if(X&&!q)q=this.disks.get(A.driver??this.options.defaultDriver);if(!q){if(Q)throw Error(`Unknown attachment driver "${String(X??A.driver??this.options.defaultDriver)}"`);return null}return q}async beforeFlush(A){let{uow:X}=A,Q=new Set([...X.getChangeSets().map((q)=>q.entity),...X.getPersistStack()]);for(let q of Q)await this.#A(q)}async#A(A){let X=JY(A);for(let Q of Object.keys(X)){let q=A[Q],H=X[Q];if(q instanceof N){if(q[f])continue;let L=this.#Y(H);if(!L)continue;q[M]=L;let E=this.#V(H.variants),x=new VY(q,{disk:L,options:{...H,variants:E},config:this.options,entity:A,columnName:Q,diskName:H.driver??this.options.defaultDriver});try{await x.process()}catch(D){throw console.error(D),Error("Failed to process attachment")}}}}AttachmentDecorator(A){return PY(A)}#V(A){if(!A)return;if(Array.isArray(A)){let X={};for(let Q of A)if(typeof Q==="string"){let q=this.options.variants?.[Q];if(!q)throw Error(`Unknown attachment variant "${Q}"`);X[Q]=q}else if(Q&&typeof Q==="object")Object.assign(X,Q);return X}if(A&&typeof A==="object")return A;return}}export{fY as AttachmentSubscriber,N as Attachment};
@@ -1 +1 @@
1
- import{e as a}from"../shared/chunk-523ncfdc.js";export{a as BaseMetadata};
1
+ import{d as a}from"../shared/chunk-wrbx2tbm.js";import"../shared/chunk-v2cxb1jc.js";export{a as BaseMetadata};
@@ -1 +1 @@
1
- import{b as t}from"../shared/chunk-cm81a68q.js";import{e as a}from"../shared/chunk-523ncfdc.js";class m extends a{async metadata(e){return await(await t("imgkit")).metadata(e.buffer)}}export{m as ImgkitMetadata};
1
+ import{b as t}from"../shared/chunk-tgvybtjr.js";import{d as a}from"../shared/chunk-wrbx2tbm.js";import"../shared/chunk-v2cxb1jc.js";class m extends a{async metadata(e){return await(await t("imgkit")).metadata(e.buffer)}}export{m as ImgkitMetadata};
@@ -1 +1 @@
1
- import"../shared/chunk-cm81a68q.js";import"../shared/chunk-523ncfdc.js";
1
+ import"../shared/chunk-tgvybtjr.js";import"../shared/chunk-wrbx2tbm.js";import"../shared/chunk-v2cxb1jc.js";
@@ -0,0 +1,2 @@
1
+ import{createRequire as l}from"module";import{encode as h}from"blurhash";var m=l(import.meta.url);async function f(t){try{let r=await import(t);if(r.default)return r.default;return r}catch(r){throw Error(`Module ${t} not found, please install it first.`)}}function w(t,r){let{componentX:n,componentY:a}=r??{enabled:!0,componentX:4,componentY:4};return new Promise(async(i,s)=>{try{let e=await f("sharp"),{data:u,info:o}=await e(t).raw().ensureAlpha().toBuffer({resolveWithObject:!0}),c=h(new Uint8ClampedArray(u),o.width,o.height,n,a);return i(c)}catch(e){return s(e)}})}
2
+ export{f as b,w as c};
@@ -0,0 +1,2 @@
1
+ import{createRequire as t}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,q=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var r=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);
2
+ export{q as e,r as f};
@@ -0,0 +1,2 @@
1
+ class t{}
2
+ export{t as d};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mikro-orm-attachments",
3
3
  "description": "Attachment handling for MikroORM with support for image processing, variants, and multiple storage drivers",
4
- "version": "2.0.0",
4
+ "version": "2.1.0",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",
@@ -1,2 +0,0 @@
1
- class t{}
2
- export{t as e};
@@ -1,2 +0,0 @@
1
- import{createRequire as l}from"module";import{encode as f}from"blurhash";var h=l(import.meta.url);async function p(t){try{let r=await import(t);if(r.default)return r.default;return r}catch(r){throw Error(`Module ${t} not found, please install it first.`)}}function w(t){for(let r of t)try{return h(r)}catch{continue}throw Error(`Could not resolve any of the following modules: ${t.join(", ")}`)}function y(t,r){let{componentX:n,componentY:a}=r??{enabled:!0,componentX:4,componentY:4};return new Promise(async(i,s)=>{try{let e=await p("sharp"),{data:u,info:o}=await e(t).raw().ensureAlpha().toBuffer({resolveWithObject:!0}),c=f(new Uint8ClampedArray(u),o.width,o.height,n,a);return i(c)}catch(e){return s(e)}})}
2
- export{p as b,w as c,y as d};