@uploadista/flow-images-sharp 0.0.10 → 0.0.12

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/dist/index.cjs CHANGED
@@ -1 +1,11 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`@uploadista/core/errors`),l=require(`@uploadista/core/flow`),u=require(`effect`),d=require(`sharp`);d=s(d);const f=e=>{switch(e){case`fill`:return`cover`;case`contain`:return`contain`}},p=u.Layer.succeed(l.ImagePlugin,l.ImagePlugin.of({optimize:(e,{quality:t,format:n})=>u.Effect.gen(function*(){let r=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).toFormat(n,{quality:t}).toBuffer(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{cause:e})});return new Uint8Array(r)}),resize:(e,{width:t,height:n,fit:r})=>u.Effect.gen(function*(){if(!t&&!n)throw Error(`Either width or height must be specified for resize`);let i=f(r),a=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).resize(t,n,{fit:i}).toBuffer(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{cause:e})});return new Uint8Array(a)})}));exports.imagePlugin=p;
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`@uploadista/core/errors`),l=require(`@uploadista/core/flow`),u=require(`effect`),d=require(`sharp`);d=s(d);const f=e=>{switch(e){case`fill`:return`cover`;case`contain`:return`contain`}},p=(e,t,n,r,i,a=0,o=0)=>{let s=0,c=0;switch(e){case`top-left`:s=o,c=a;break;case`top-right`:s=o,c=t-r-a;break;case`bottom-left`:s=n-i-o,c=a;break;case`bottom-right`:s=n-i-o,c=t-r-a;break;case`center`:s=Math.floor((n-i)/2)+o,c=Math.floor((t-r)/2)+a;break}return{top:s,left:c}},m=u.Layer.succeed(l.ImagePlugin,l.ImagePlugin.of({optimize:(e,{quality:t,format:n})=>u.Effect.gen(function*(){let r=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).toFormat(n,{quality:t}).toBuffer(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{cause:e})});return new Uint8Array(r)}),resize:(e,{width:t,height:n,fit:r})=>u.Effect.gen(function*(){if(!t&&!n)throw Error(`Either width or height must be specified for resize`);let i=f(r),a=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).resize(t,n,{fit:i}).toBuffer(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{cause:e})});return new Uint8Array(a)}),transform:(e,t)=>u.Effect.gen(function*(){let n=(0,d.default)(e);switch(t.type){case`resize`:{let e=f(t.fit);n=n.resize(t.width,t.height,{fit:e});break}case`blur`:n=n.blur(t.sigma);break;case`rotate`:{let e=t.background?{background:t.background}:void 0;n=n.rotate(t.angle,e);break}case`flip`:n=t.direction===`horizontal`?n.flop():n.flip();break;case`grayscale`:n=n.grayscale();break;case`sepia`:n=n.tint({r:112,g:66,b:20});break;case`brightness`:{let e=1+t.value/100;n=n.modulate({brightness:e});break}case`contrast`:{let e=1+t.value/100;n=n.linear(e,0);break}case`sharpen`:n=t.sigma===void 0?n.sharpen():n.sharpen({sigma:t.sigma});break;case`watermark`:{let e=yield*u.Effect.tryPromise({try:async()=>{let e=await fetch(t.imagePath);if(!e.ok)throw Error(`Failed to fetch watermark: ${e.statusText}`);let n=await e.arrayBuffer();return Buffer.from(n)},catch:e=>c.UploadistaError.fromCode(`FILE_NOT_FOUND`,{body:`Watermark image not found or failed to fetch: ${t.imagePath}`,cause:e})}),r=yield*u.Effect.tryPromise({try:async()=>await n.metadata(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read image metadata`,cause:e})}),i=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).metadata(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read watermark metadata`,cause:e})});if(!r.width||!r.height||!i.width||!i.height)return yield*u.Effect.fail(c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Could not determine image or watermark dimensions`}));let{top:a,left:o}=p(t.position,r.width,r.height,i.width,i.height,t.offsetX,t.offsetY),s=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).composite([{input:Buffer.from([255,255,255,Math.round(t.opacity*255)]),raw:{width:1,height:1,channels:4},tile:!0,blend:`dest-in`}]).toBuffer(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to apply watermark opacity`,cause:e})});n=n.composite([{input:s,top:a,left:o}]);break}case`logo`:{let e=yield*u.Effect.tryPromise({try:async()=>{let e=await fetch(t.imagePath);if(!e.ok)throw Error(`Failed to fetch logo: ${e.statusText}`);let n=await e.arrayBuffer();return Buffer.from(n)},catch:e=>c.UploadistaError.fromCode(`FILE_NOT_FOUND`,{body:`Logo image not found or failed to fetch: ${t.imagePath}`,cause:e})}),r=yield*u.Effect.tryPromise({try:async()=>await n.metadata(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read image metadata`,cause:e})}),i=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).metadata(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read logo metadata`,cause:e})});if(!r.width||!r.height||!i.width||!i.height)return yield*u.Effect.fail(c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Could not determine image or logo dimensions`}));let a=Math.round(i.width*t.scale),o=Math.round(i.height*t.scale),s=yield*u.Effect.tryPromise({try:async()=>await(0,d.default)(e).resize(a,o).toBuffer(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to scale logo`,cause:e})}),{top:l,left:f}=p(t.position,r.width,r.height,a,o,t.offsetX,t.offsetY);n=n.composite([{input:s,top:l,left:f}]);break}case`text`:{let e=yield*u.Effect.tryPromise({try:async()=>await n.metadata(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read image metadata`,cause:e})});if(!e.width||!e.height)return yield*u.Effect.fail(c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Could not determine image dimensions`}));let r=t.fontFamily||`sans-serif`,i=t.text.length*t.fontSize*.6,a=t.fontSize,{top:o,left:s}=p(t.position,e.width,e.height,i,a,t.offsetX,t.offsetY),l=`
2
+ <svg width="${e.width}" height="${e.height}">
3
+ <text
4
+ x="${s}"
5
+ y="${o+t.fontSize}"
6
+ font-family="${r}"
7
+ font-size="${t.fontSize}"
8
+ fill="${t.color}"
9
+ >${t.text}</text>
10
+ </svg>
11
+ `;n=n.composite([{input:Buffer.from(l),top:0,left:0}]);break}default:return yield*u.Effect.fail(c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Unsupported transformation type: ${t.type}`}))}let r=yield*u.Effect.tryPromise({try:async()=>await n.toBuffer(),catch:e=>c.UploadistaError.fromCode(`UNKNOWN_ERROR`,{body:`Failed to apply transformation: ${t.type}`,cause:e})});return new Uint8Array(r)})}));exports.imagePlugin=m;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/image-plugin.ts"],"sourcesContent":[],"mappings":";;;;cAca,aAAW,KAAA,CAAA,MAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/image-plugin.ts"],"sourcesContent":[],"mappings":";;;;cAuDa,aAAW,KAAA,CAAA,MAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/image-plugin.ts"],"sourcesContent":[],"mappings":";;;;cAca,aAAW,KAAA,CAAA,MAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/image-plugin.ts"],"sourcesContent":[],"mappings":";;;;cAuDa,aAAW,KAAA,CAAA,MAAA"}
package/dist/index.mjs CHANGED
@@ -1,2 +1,12 @@
1
- import{UploadistaError as e}from"@uploadista/core/errors";import{ImagePlugin as t}from"@uploadista/core/flow";import{Effect as n,Layer as r}from"effect";import i from"sharp";const a=e=>{switch(e){case`fill`:return`cover`;case`contain`:return`contain`}},o=r.succeed(t,t.of({optimize:(t,{quality:r,format:a})=>n.gen(function*(){let o=yield*n.tryPromise({try:async()=>await i(t).toFormat(a,{quality:r}).toBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{cause:t})});return new Uint8Array(o)}),resize:(t,{width:r,height:o,fit:s})=>n.gen(function*(){if(!r&&!o)throw Error(`Either width or height must be specified for resize`);let c=a(s),l=yield*n.tryPromise({try:async()=>await i(t).resize(r,o,{fit:c}).toBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{cause:t})});return new Uint8Array(l)})}));export{o as imagePlugin};
1
+ import{UploadistaError as e}from"@uploadista/core/errors";import{ImagePlugin as t}from"@uploadista/core/flow";import{Effect as n,Layer as r}from"effect";import i from"sharp";const a=e=>{switch(e){case`fill`:return`cover`;case`contain`:return`contain`}},o=(e,t,n,r,i,a=0,o=0)=>{let s=0,c=0;switch(e){case`top-left`:s=o,c=a;break;case`top-right`:s=o,c=t-r-a;break;case`bottom-left`:s=n-i-o,c=a;break;case`bottom-right`:s=n-i-o,c=t-r-a;break;case`center`:s=Math.floor((n-i)/2)+o,c=Math.floor((t-r)/2)+a;break}return{top:s,left:c}},s=r.succeed(t,t.of({optimize:(t,{quality:r,format:a})=>n.gen(function*(){let o=yield*n.tryPromise({try:async()=>await i(t).toFormat(a,{quality:r}).toBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{cause:t})});return new Uint8Array(o)}),resize:(t,{width:r,height:o,fit:s})=>n.gen(function*(){if(!r&&!o)throw Error(`Either width or height must be specified for resize`);let c=a(s),l=yield*n.tryPromise({try:async()=>await i(t).resize(r,o,{fit:c}).toBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{cause:t})});return new Uint8Array(l)}),transform:(t,r)=>n.gen(function*(){let s=i(t);switch(r.type){case`resize`:{let e=a(r.fit);s=s.resize(r.width,r.height,{fit:e});break}case`blur`:s=s.blur(r.sigma);break;case`rotate`:{let e=r.background?{background:r.background}:void 0;s=s.rotate(r.angle,e);break}case`flip`:s=r.direction===`horizontal`?s.flop():s.flip();break;case`grayscale`:s=s.grayscale();break;case`sepia`:s=s.tint({r:112,g:66,b:20});break;case`brightness`:{let e=1+r.value/100;s=s.modulate({brightness:e});break}case`contrast`:{let e=1+r.value/100;s=s.linear(e,0);break}case`sharpen`:s=r.sigma===void 0?s.sharpen():s.sharpen({sigma:r.sigma});break;case`watermark`:{let t=yield*n.tryPromise({try:async()=>{let e=await fetch(r.imagePath);if(!e.ok)throw Error(`Failed to fetch watermark: ${e.statusText}`);let t=await e.arrayBuffer();return Buffer.from(t)},catch:t=>e.fromCode(`FILE_NOT_FOUND`,{body:`Watermark image not found or failed to fetch: ${r.imagePath}`,cause:t})}),a=yield*n.tryPromise({try:async()=>await s.metadata(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read image metadata`,cause:t})}),c=yield*n.tryPromise({try:async()=>await i(t).metadata(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read watermark metadata`,cause:t})});if(!a.width||!a.height||!c.width||!c.height)return yield*n.fail(e.fromCode(`UNKNOWN_ERROR`,{body:`Could not determine image or watermark dimensions`}));let{top:l,left:u}=o(r.position,a.width,a.height,c.width,c.height,r.offsetX,r.offsetY),d=yield*n.tryPromise({try:async()=>await i(t).composite([{input:Buffer.from([255,255,255,Math.round(r.opacity*255)]),raw:{width:1,height:1,channels:4},tile:!0,blend:`dest-in`}]).toBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to apply watermark opacity`,cause:t})});s=s.composite([{input:d,top:l,left:u}]);break}case`logo`:{let t=yield*n.tryPromise({try:async()=>{let e=await fetch(r.imagePath);if(!e.ok)throw Error(`Failed to fetch logo: ${e.statusText}`);let t=await e.arrayBuffer();return Buffer.from(t)},catch:t=>e.fromCode(`FILE_NOT_FOUND`,{body:`Logo image not found or failed to fetch: ${r.imagePath}`,cause:t})}),a=yield*n.tryPromise({try:async()=>await s.metadata(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read image metadata`,cause:t})}),c=yield*n.tryPromise({try:async()=>await i(t).metadata(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read logo metadata`,cause:t})});if(!a.width||!a.height||!c.width||!c.height)return yield*n.fail(e.fromCode(`UNKNOWN_ERROR`,{body:`Could not determine image or logo dimensions`}));let l=Math.round(c.width*r.scale),u=Math.round(c.height*r.scale),d=yield*n.tryPromise({try:async()=>await i(t).resize(l,u).toBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to scale logo`,cause:t})}),{top:f,left:p}=o(r.position,a.width,a.height,l,u,r.offsetX,r.offsetY);s=s.composite([{input:d,top:f,left:p}]);break}case`text`:{let t=yield*n.tryPromise({try:async()=>await s.metadata(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to read image metadata`,cause:t})});if(!t.width||!t.height)return yield*n.fail(e.fromCode(`UNKNOWN_ERROR`,{body:`Could not determine image dimensions`}));let i=r.fontFamily||`sans-serif`,a=r.text.length*r.fontSize*.6,c=r.fontSize,{top:l,left:u}=o(r.position,t.width,t.height,a,c,r.offsetX,r.offsetY),d=`
2
+ <svg width="${t.width}" height="${t.height}">
3
+ <text
4
+ x="${u}"
5
+ y="${l+r.fontSize}"
6
+ font-family="${i}"
7
+ font-size="${r.fontSize}"
8
+ fill="${r.color}"
9
+ >${r.text}</text>
10
+ </svg>
11
+ `;s=s.composite([{input:Buffer.from(d),top:0,left:0}]);break}default:return yield*n.fail(e.fromCode(`UNKNOWN_ERROR`,{body:`Unsupported transformation type: ${r.type}`}))}let c=yield*n.tryPromise({try:async()=>await s.toBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to apply transformation: ${r.type}`,cause:t})});return new Uint8Array(c)})}));export{s as imagePlugin};
2
12
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/image-plugin.ts"],"sourcesContent":["import { UploadistaError } from \"@uploadista/core/errors\";\nimport { ImagePlugin } from \"@uploadista/core/flow\";\nimport { Effect, Layer } from \"effect\";\nimport sharp from \"sharp\";\n\nconst mapFitToSharp = (fit: \"fill\" | \"contain\" | \"cover\") => {\n switch (fit) {\n case \"fill\":\n return \"cover\";\n case \"contain\":\n return \"contain\";\n }\n};\n\nexport const imagePlugin = Layer.succeed(\n ImagePlugin,\n ImagePlugin.of({\n optimize: (inputBytes, { quality, format }) => {\n return Effect.gen(function* () {\n const outputBytes = yield* Effect.tryPromise({\n try: async () =>\n await sharp(inputBytes).toFormat(format, { quality }).toBuffer(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: error,\n });\n },\n });\n return new Uint8Array(outputBytes);\n });\n },\n resize: (inputBytes, { width, height, fit }) => {\n return Effect.gen(function* () {\n if (!width && !height) {\n throw new Error(\n \"Either width or height must be specified for resize\",\n );\n }\n\n const sharpFit = mapFitToSharp(fit);\n const outputBytes = yield* Effect.tryPromise({\n try: async () =>\n await sharp(inputBytes)\n .resize(width, height, { fit: sharpFit })\n .toBuffer(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: error,\n });\n },\n });\n\n return new Uint8Array(outputBytes);\n });\n },\n }),\n);\n"],"mappings":"8KAKA,MAAM,EAAiB,GAAsC,CAC3D,OAAQ,EAAR,CACE,IAAK,OACH,MAAO,QACT,IAAK,UACH,MAAO,YAIA,EAAc,EAAM,QAC/B,EACA,EAAY,GAAG,CACb,UAAW,EAAY,CAAE,UAAS,YACzB,EAAO,IAAI,WAAa,CAC7B,IAAM,EAAc,MAAO,EAAO,WAAW,CAC3C,IAAK,SACH,MAAM,EAAM,EAAW,CAAC,SAAS,EAAQ,CAAE,UAAS,CAAC,CAAC,UAAU,CAClE,MAAQ,GACC,EAAgB,SAAS,gBAAiB,CAC/C,MAAO,EACR,CAAC,CAEL,CAAC,CACF,OAAO,IAAI,WAAW,EAAY,EAClC,CAEJ,QAAS,EAAY,CAAE,QAAO,SAAQ,SAC7B,EAAO,IAAI,WAAa,CAC7B,GAAI,CAAC,GAAS,CAAC,EACb,MAAU,MACR,sDACD,CAGH,IAAM,EAAW,EAAc,EAAI,CAC7B,EAAc,MAAO,EAAO,WAAW,CAC3C,IAAK,SACH,MAAM,EAAM,EAAW,CACpB,OAAO,EAAO,EAAQ,CAAE,IAAK,EAAU,CAAC,CACxC,UAAU,CACf,MAAQ,GACC,EAAgB,SAAS,gBAAiB,CAC/C,MAAO,EACR,CAAC,CAEL,CAAC,CAEF,OAAO,IAAI,WAAW,EAAY,EAClC,CAEL,CAAC,CACH"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/image-plugin.ts"],"sourcesContent":["import { UploadistaError } from \"@uploadista/core/errors\";\nimport { ImagePlugin } from \"@uploadista/core/flow\";\nimport { Effect, Layer } from \"effect\";\nimport sharp from \"sharp\";\n\nconst mapFitToSharp = (fit: \"fill\" | \"contain\" | \"cover\") => {\n switch (fit) {\n case \"fill\":\n return \"cover\";\n case \"contain\":\n return \"contain\";\n }\n};\n\n/**\n * Calculate position coordinates for overlays based on position string and offsets.\n */\nconst calculateOverlayPosition = (\n position: string,\n imageWidth: number,\n imageHeight: number,\n overlayWidth: number,\n overlayHeight: number,\n offsetX = 0,\n offsetY = 0,\n): { top: number; left: number } => {\n let top = 0;\n let left = 0;\n\n switch (position) {\n case \"top-left\":\n top = offsetY;\n left = offsetX;\n break;\n case \"top-right\":\n top = offsetY;\n left = imageWidth - overlayWidth - offsetX;\n break;\n case \"bottom-left\":\n top = imageHeight - overlayHeight - offsetY;\n left = offsetX;\n break;\n case \"bottom-right\":\n top = imageHeight - overlayHeight - offsetY;\n left = imageWidth - overlayWidth - offsetX;\n break;\n case \"center\":\n top = Math.floor((imageHeight - overlayHeight) / 2) + offsetY;\n left = Math.floor((imageWidth - overlayWidth) / 2) + offsetX;\n break;\n }\n\n return { top, left };\n};\n\nexport const imagePlugin = Layer.succeed(\n ImagePlugin,\n ImagePlugin.of({\n optimize: (inputBytes, { quality, format }) => {\n return Effect.gen(function* () {\n const outputBytes = yield* Effect.tryPromise({\n try: async () =>\n await sharp(inputBytes).toFormat(format, { quality }).toBuffer(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: error,\n });\n },\n });\n return new Uint8Array(outputBytes);\n });\n },\n resize: (inputBytes, { width, height, fit }) => {\n return Effect.gen(function* () {\n if (!width && !height) {\n throw new Error(\n \"Either width or height must be specified for resize\",\n );\n }\n\n const sharpFit = mapFitToSharp(fit);\n const outputBytes = yield* Effect.tryPromise({\n try: async () =>\n await sharp(inputBytes)\n .resize(width, height, { fit: sharpFit })\n .toBuffer(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: error,\n });\n },\n });\n\n return new Uint8Array(outputBytes);\n });\n },\n transform: (inputBytes, transformation) => {\n return Effect.gen(function* () {\n let pipeline = sharp(inputBytes);\n\n switch (transformation.type) {\n case \"resize\": {\n const sharpFit = mapFitToSharp(transformation.fit);\n pipeline = pipeline.resize(\n transformation.width,\n transformation.height,\n {\n fit: sharpFit,\n },\n );\n break;\n }\n\n case \"blur\": {\n pipeline = pipeline.blur(transformation.sigma);\n break;\n }\n\n case \"rotate\": {\n const options = transformation.background\n ? { background: transformation.background }\n : undefined;\n pipeline = pipeline.rotate(transformation.angle, options);\n break;\n }\n\n case \"flip\": {\n if (transformation.direction === \"horizontal\") {\n pipeline = pipeline.flop();\n } else {\n pipeline = pipeline.flip();\n }\n break;\n }\n\n case \"grayscale\": {\n pipeline = pipeline.grayscale();\n break;\n }\n\n case \"sepia\": {\n // Apply sepia tone using tint\n pipeline = pipeline.tint({ r: 112, g: 66, b: 20 });\n break;\n }\n\n case \"brightness\": {\n // Convert -100 to +100 range to multiplier (0 to 2)\n const multiplier = 1 + transformation.value / 100;\n pipeline = pipeline.modulate({ brightness: multiplier });\n break;\n }\n\n case \"contrast\": {\n // Convert -100 to +100 range to linear adjustment\n const a = 1 + transformation.value / 100;\n pipeline = pipeline.linear(a, 0);\n break;\n }\n\n case \"sharpen\": {\n if (transformation.sigma !== undefined) {\n pipeline = pipeline.sharpen({ sigma: transformation.sigma });\n } else {\n pipeline = pipeline.sharpen();\n }\n break;\n }\n\n case \"watermark\": {\n // Fetch watermark image from URL\n const watermarkBuffer = yield* Effect.tryPromise({\n try: async () => {\n const response = await fetch(transformation.imagePath);\n if (!response.ok) {\n throw new Error(`Failed to fetch watermark: ${response.statusText}`);\n }\n const arrayBuffer = await response.arrayBuffer();\n return Buffer.from(arrayBuffer);\n },\n catch: (error) => {\n return UploadistaError.fromCode(\"FILE_NOT_FOUND\", {\n body: `Watermark image not found or failed to fetch: ${transformation.imagePath}`,\n cause: error,\n });\n },\n });\n\n // Get image metadata to calculate positioning\n const metadata = yield* Effect.tryPromise({\n try: async () => await pipeline.metadata(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Failed to read image metadata\",\n cause: error,\n });\n },\n });\n\n // Get watermark metadata\n const watermarkMetadata = yield* Effect.tryPromise({\n try: async () => await sharp(watermarkBuffer).metadata(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Failed to read watermark metadata\",\n cause: error,\n });\n },\n });\n\n if (\n !metadata.width ||\n !metadata.height ||\n !watermarkMetadata.width ||\n !watermarkMetadata.height\n ) {\n return yield* Effect.fail(\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Could not determine image or watermark dimensions\",\n }),\n );\n }\n\n const { top, left } = calculateOverlayPosition(\n transformation.position,\n metadata.width,\n metadata.height,\n watermarkMetadata.width,\n watermarkMetadata.height,\n transformation.offsetX,\n transformation.offsetY,\n );\n\n // Apply watermark with opacity\n const watermarkWithOpacity = yield* Effect.tryPromise({\n try: async () =>\n await sharp(watermarkBuffer)\n .composite([\n {\n input: Buffer.from([\n 255,\n 255,\n 255,\n Math.round(transformation.opacity * 255),\n ]),\n raw: {\n width: 1,\n height: 1,\n channels: 4,\n },\n tile: true,\n blend: \"dest-in\",\n },\n ])\n .toBuffer(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Failed to apply watermark opacity\",\n cause: error,\n });\n },\n });\n\n pipeline = pipeline.composite([\n {\n input: watermarkWithOpacity,\n top,\n left,\n },\n ]);\n break;\n }\n\n case \"logo\": {\n // Fetch logo image from URL\n const logoBuffer = yield* Effect.tryPromise({\n try: async () => {\n const response = await fetch(transformation.imagePath);\n if (!response.ok) {\n throw new Error(`Failed to fetch logo: ${response.statusText}`);\n }\n const arrayBuffer = await response.arrayBuffer();\n return Buffer.from(arrayBuffer);\n },\n catch: (error) => {\n return UploadistaError.fromCode(\"FILE_NOT_FOUND\", {\n body: `Logo image not found or failed to fetch: ${transformation.imagePath}`,\n cause: error,\n });\n },\n });\n\n // Get image metadata\n const metadata = yield* Effect.tryPromise({\n try: async () => await pipeline.metadata(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Failed to read image metadata\",\n cause: error,\n });\n },\n });\n\n // Get logo metadata\n const logoMetadata = yield* Effect.tryPromise({\n try: async () => await sharp(logoBuffer).metadata(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Failed to read logo metadata\",\n cause: error,\n });\n },\n });\n\n if (\n !metadata.width ||\n !metadata.height ||\n !logoMetadata.width ||\n !logoMetadata.height\n ) {\n return yield* Effect.fail(\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Could not determine image or logo dimensions\",\n }),\n );\n }\n\n // Scale logo\n const scaledLogoWidth = Math.round(\n logoMetadata.width * transformation.scale,\n );\n const scaledLogoHeight = Math.round(\n logoMetadata.height * transformation.scale,\n );\n\n const scaledLogo = yield* Effect.tryPromise({\n try: async () =>\n await sharp(logoBuffer)\n .resize(scaledLogoWidth, scaledLogoHeight)\n .toBuffer(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Failed to scale logo\",\n cause: error,\n });\n },\n });\n\n const { top, left } = calculateOverlayPosition(\n transformation.position,\n metadata.width,\n metadata.height,\n scaledLogoWidth,\n scaledLogoHeight,\n transformation.offsetX,\n transformation.offsetY,\n );\n\n pipeline = pipeline.composite([\n {\n input: scaledLogo,\n top,\n left,\n },\n ]);\n break;\n }\n\n case \"text\": {\n // Get image metadata\n const metadata = yield* Effect.tryPromise({\n try: async () => await pipeline.metadata(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Failed to read image metadata\",\n cause: error,\n });\n },\n });\n\n if (!metadata.width || !metadata.height) {\n return yield* Effect.fail(\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: \"Could not determine image dimensions\",\n }),\n );\n }\n\n // Create SVG text overlay\n const fontFamily = transformation.fontFamily || \"sans-serif\";\n\n // Estimate text dimensions (rough approximation)\n const textWidth =\n transformation.text.length * transformation.fontSize * 0.6;\n const textHeight = transformation.fontSize;\n\n const { top, left } = calculateOverlayPosition(\n transformation.position,\n metadata.width,\n metadata.height,\n textWidth,\n textHeight,\n transformation.offsetX,\n transformation.offsetY,\n );\n\n // Create positioned SVG\n const positionedSvg = `\n <svg width=\"${metadata.width}\" height=\"${metadata.height}\">\n <text\n x=\"${left}\"\n y=\"${top + transformation.fontSize}\"\n font-family=\"${fontFamily}\"\n font-size=\"${transformation.fontSize}\"\n fill=\"${transformation.color}\"\n >${transformation.text}</text>\n </svg>\n `;\n\n pipeline = pipeline.composite([\n {\n input: Buffer.from(positionedSvg),\n top: 0,\n left: 0,\n },\n ]);\n break;\n }\n\n default: {\n // TypeScript should ensure this is unreachable\n return yield* Effect.fail(\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: `Unsupported transformation type: ${(transformation as { type: string }).type}`,\n }),\n );\n }\n }\n\n // Convert pipeline to buffer\n const outputBytes = yield* Effect.tryPromise({\n try: async () => await pipeline.toBuffer(),\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: `Failed to apply transformation: ${transformation.type}`,\n cause: error,\n });\n },\n });\n\n return new Uint8Array(outputBytes);\n });\n },\n }),\n);\n"],"mappings":"8KAKA,MAAM,EAAiB,GAAsC,CAC3D,OAAQ,EAAR,CACE,IAAK,OACH,MAAO,QACT,IAAK,UACH,MAAO,YAOP,GACJ,EACA,EACA,EACA,EACA,EACA,EAAU,EACV,EAAU,IACwB,CAClC,IAAI,EAAM,EACN,EAAO,EAEX,OAAQ,EAAR,CACE,IAAK,WACH,EAAM,EACN,EAAO,EACP,MACF,IAAK,YACH,EAAM,EACN,EAAO,EAAa,EAAe,EACnC,MACF,IAAK,cACH,EAAM,EAAc,EAAgB,EACpC,EAAO,EACP,MACF,IAAK,e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Ae,SAE5B,CAAE,MAAK,QAAS,EACpB,EAAe,SACf,EAAS,MACT,EAAS,OACT,EACA,EACA,EAAe,QACf,EAAe,QAChB,CAGK,EAAgB;4BACN,EAAS,MAAM,YAAY,EAAS,OAAO;;uBAEhD,EAAK;uBACL,EAAM,EAAe,SAAS;iCACpB,EAAW;+BACb,EAAe,SAAS;0BAC7B,EAAe,MAAM;mBAC5B,EAAe,KAAK;;cAI3B,EAAW,EAAS,UAAU,CAC5B,CACE,MAAO,OAAO,KAAK,EAAc,CACjC,IAAK,EACL,KAAM,EACP,CACF,CAAC,CACF,MAGF,QAEE,OAAO,MAAO,EAAO,KACnB,EAAgB,SAAS,gBAAiB,CACxC,KAAM,oCAAqC,EAAoC,OAChF,CAAC,CACH,CAKL,IAAM,EAAc,MAAO,EAAO,WAAW,CAC3C,IAAK,SAAY,MAAM,EAAS,UAAU,CAC1C,MAAQ,GACC,EAAgB,SAAS,gBAAiB,CAC/C,KAAM,mCAAmC,EAAe,OACxD,MAAO,EACR,CAAC,CAEL,CAAC,CAEF,OAAO,IAAI,WAAW,EAAY,EAClC,CAEL,CAAC,CACH"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@uploadista/flow-images-sharp",
3
3
  "type": "module",
4
- "version": "0.0.10",
4
+ "version": "0.0.12",
5
5
  "description": "Sharp image processing service for Uploadista Flow",
6
6
  "license": "MIT",
7
7
  "author": "Uploadista",
@@ -15,16 +15,16 @@
15
15
  },
16
16
  "dependencies": {
17
17
  "sharp": "0.34.4",
18
- "effect": "3.19.0",
18
+ "effect": "3.19.1",
19
19
  "tinycolor2": "1.6.0",
20
20
  "zod": "4.1.12",
21
- "@uploadista/core": "0.0.10"
21
+ "@uploadista/core": "0.0.12"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/node": "24.10.0",
25
25
  "@types/tinycolor2": "1.4.6",
26
26
  "tsdown": "0.16.0",
27
- "@uploadista/typescript-config": "0.0.10"
27
+ "@uploadista/typescript-config": "0.0.12"
28
28
  },
29
29
  "scripts": {
30
30
  "build": "tsdown",
@@ -12,6 +12,47 @@ const mapFitToSharp = (fit: "fill" | "contain" | "cover") => {
12
12
  }
13
13
  };
14
14
 
15
+ /**
16
+ * Calculate position coordinates for overlays based on position string and offsets.
17
+ */
18
+ const calculateOverlayPosition = (
19
+ position: string,
20
+ imageWidth: number,
21
+ imageHeight: number,
22
+ overlayWidth: number,
23
+ overlayHeight: number,
24
+ offsetX = 0,
25
+ offsetY = 0,
26
+ ): { top: number; left: number } => {
27
+ let top = 0;
28
+ let left = 0;
29
+
30
+ switch (position) {
31
+ case "top-left":
32
+ top = offsetY;
33
+ left = offsetX;
34
+ break;
35
+ case "top-right":
36
+ top = offsetY;
37
+ left = imageWidth - overlayWidth - offsetX;
38
+ break;
39
+ case "bottom-left":
40
+ top = imageHeight - overlayHeight - offsetY;
41
+ left = offsetX;
42
+ break;
43
+ case "bottom-right":
44
+ top = imageHeight - overlayHeight - offsetY;
45
+ left = imageWidth - overlayWidth - offsetX;
46
+ break;
47
+ case "center":
48
+ top = Math.floor((imageHeight - overlayHeight) / 2) + offsetY;
49
+ left = Math.floor((imageWidth - overlayWidth) / 2) + offsetX;
50
+ break;
51
+ }
52
+
53
+ return { top, left };
54
+ };
55
+
15
56
  export const imagePlugin = Layer.succeed(
16
57
  ImagePlugin,
17
58
  ImagePlugin.of({
@@ -50,6 +91,363 @@ export const imagePlugin = Layer.succeed(
50
91
  },
51
92
  });
52
93
 
94
+ return new Uint8Array(outputBytes);
95
+ });
96
+ },
97
+ transform: (inputBytes, transformation) => {
98
+ return Effect.gen(function* () {
99
+ let pipeline = sharp(inputBytes);
100
+
101
+ switch (transformation.type) {
102
+ case "resize": {
103
+ const sharpFit = mapFitToSharp(transformation.fit);
104
+ pipeline = pipeline.resize(
105
+ transformation.width,
106
+ transformation.height,
107
+ {
108
+ fit: sharpFit,
109
+ },
110
+ );
111
+ break;
112
+ }
113
+
114
+ case "blur": {
115
+ pipeline = pipeline.blur(transformation.sigma);
116
+ break;
117
+ }
118
+
119
+ case "rotate": {
120
+ const options = transformation.background
121
+ ? { background: transformation.background }
122
+ : undefined;
123
+ pipeline = pipeline.rotate(transformation.angle, options);
124
+ break;
125
+ }
126
+
127
+ case "flip": {
128
+ if (transformation.direction === "horizontal") {
129
+ pipeline = pipeline.flop();
130
+ } else {
131
+ pipeline = pipeline.flip();
132
+ }
133
+ break;
134
+ }
135
+
136
+ case "grayscale": {
137
+ pipeline = pipeline.grayscale();
138
+ break;
139
+ }
140
+
141
+ case "sepia": {
142
+ // Apply sepia tone using tint
143
+ pipeline = pipeline.tint({ r: 112, g: 66, b: 20 });
144
+ break;
145
+ }
146
+
147
+ case "brightness": {
148
+ // Convert -100 to +100 range to multiplier (0 to 2)
149
+ const multiplier = 1 + transformation.value / 100;
150
+ pipeline = pipeline.modulate({ brightness: multiplier });
151
+ break;
152
+ }
153
+
154
+ case "contrast": {
155
+ // Convert -100 to +100 range to linear adjustment
156
+ const a = 1 + transformation.value / 100;
157
+ pipeline = pipeline.linear(a, 0);
158
+ break;
159
+ }
160
+
161
+ case "sharpen": {
162
+ if (transformation.sigma !== undefined) {
163
+ pipeline = pipeline.sharpen({ sigma: transformation.sigma });
164
+ } else {
165
+ pipeline = pipeline.sharpen();
166
+ }
167
+ break;
168
+ }
169
+
170
+ case "watermark": {
171
+ // Fetch watermark image from URL
172
+ const watermarkBuffer = yield* Effect.tryPromise({
173
+ try: async () => {
174
+ const response = await fetch(transformation.imagePath);
175
+ if (!response.ok) {
176
+ throw new Error(`Failed to fetch watermark: ${response.statusText}`);
177
+ }
178
+ const arrayBuffer = await response.arrayBuffer();
179
+ return Buffer.from(arrayBuffer);
180
+ },
181
+ catch: (error) => {
182
+ return UploadistaError.fromCode("FILE_NOT_FOUND", {
183
+ body: `Watermark image not found or failed to fetch: ${transformation.imagePath}`,
184
+ cause: error,
185
+ });
186
+ },
187
+ });
188
+
189
+ // Get image metadata to calculate positioning
190
+ const metadata = yield* Effect.tryPromise({
191
+ try: async () => await pipeline.metadata(),
192
+ catch: (error) => {
193
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
194
+ body: "Failed to read image metadata",
195
+ cause: error,
196
+ });
197
+ },
198
+ });
199
+
200
+ // Get watermark metadata
201
+ const watermarkMetadata = yield* Effect.tryPromise({
202
+ try: async () => await sharp(watermarkBuffer).metadata(),
203
+ catch: (error) => {
204
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
205
+ body: "Failed to read watermark metadata",
206
+ cause: error,
207
+ });
208
+ },
209
+ });
210
+
211
+ if (
212
+ !metadata.width ||
213
+ !metadata.height ||
214
+ !watermarkMetadata.width ||
215
+ !watermarkMetadata.height
216
+ ) {
217
+ return yield* Effect.fail(
218
+ UploadistaError.fromCode("UNKNOWN_ERROR", {
219
+ body: "Could not determine image or watermark dimensions",
220
+ }),
221
+ );
222
+ }
223
+
224
+ const { top, left } = calculateOverlayPosition(
225
+ transformation.position,
226
+ metadata.width,
227
+ metadata.height,
228
+ watermarkMetadata.width,
229
+ watermarkMetadata.height,
230
+ transformation.offsetX,
231
+ transformation.offsetY,
232
+ );
233
+
234
+ // Apply watermark with opacity
235
+ const watermarkWithOpacity = yield* Effect.tryPromise({
236
+ try: async () =>
237
+ await sharp(watermarkBuffer)
238
+ .composite([
239
+ {
240
+ input: Buffer.from([
241
+ 255,
242
+ 255,
243
+ 255,
244
+ Math.round(transformation.opacity * 255),
245
+ ]),
246
+ raw: {
247
+ width: 1,
248
+ height: 1,
249
+ channels: 4,
250
+ },
251
+ tile: true,
252
+ blend: "dest-in",
253
+ },
254
+ ])
255
+ .toBuffer(),
256
+ catch: (error) => {
257
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
258
+ body: "Failed to apply watermark opacity",
259
+ cause: error,
260
+ });
261
+ },
262
+ });
263
+
264
+ pipeline = pipeline.composite([
265
+ {
266
+ input: watermarkWithOpacity,
267
+ top,
268
+ left,
269
+ },
270
+ ]);
271
+ break;
272
+ }
273
+
274
+ case "logo": {
275
+ // Fetch logo image from URL
276
+ const logoBuffer = yield* Effect.tryPromise({
277
+ try: async () => {
278
+ const response = await fetch(transformation.imagePath);
279
+ if (!response.ok) {
280
+ throw new Error(`Failed to fetch logo: ${response.statusText}`);
281
+ }
282
+ const arrayBuffer = await response.arrayBuffer();
283
+ return Buffer.from(arrayBuffer);
284
+ },
285
+ catch: (error) => {
286
+ return UploadistaError.fromCode("FILE_NOT_FOUND", {
287
+ body: `Logo image not found or failed to fetch: ${transformation.imagePath}`,
288
+ cause: error,
289
+ });
290
+ },
291
+ });
292
+
293
+ // Get image metadata
294
+ const metadata = yield* Effect.tryPromise({
295
+ try: async () => await pipeline.metadata(),
296
+ catch: (error) => {
297
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
298
+ body: "Failed to read image metadata",
299
+ cause: error,
300
+ });
301
+ },
302
+ });
303
+
304
+ // Get logo metadata
305
+ const logoMetadata = yield* Effect.tryPromise({
306
+ try: async () => await sharp(logoBuffer).metadata(),
307
+ catch: (error) => {
308
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
309
+ body: "Failed to read logo metadata",
310
+ cause: error,
311
+ });
312
+ },
313
+ });
314
+
315
+ if (
316
+ !metadata.width ||
317
+ !metadata.height ||
318
+ !logoMetadata.width ||
319
+ !logoMetadata.height
320
+ ) {
321
+ return yield* Effect.fail(
322
+ UploadistaError.fromCode("UNKNOWN_ERROR", {
323
+ body: "Could not determine image or logo dimensions",
324
+ }),
325
+ );
326
+ }
327
+
328
+ // Scale logo
329
+ const scaledLogoWidth = Math.round(
330
+ logoMetadata.width * transformation.scale,
331
+ );
332
+ const scaledLogoHeight = Math.round(
333
+ logoMetadata.height * transformation.scale,
334
+ );
335
+
336
+ const scaledLogo = yield* Effect.tryPromise({
337
+ try: async () =>
338
+ await sharp(logoBuffer)
339
+ .resize(scaledLogoWidth, scaledLogoHeight)
340
+ .toBuffer(),
341
+ catch: (error) => {
342
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
343
+ body: "Failed to scale logo",
344
+ cause: error,
345
+ });
346
+ },
347
+ });
348
+
349
+ const { top, left } = calculateOverlayPosition(
350
+ transformation.position,
351
+ metadata.width,
352
+ metadata.height,
353
+ scaledLogoWidth,
354
+ scaledLogoHeight,
355
+ transformation.offsetX,
356
+ transformation.offsetY,
357
+ );
358
+
359
+ pipeline = pipeline.composite([
360
+ {
361
+ input: scaledLogo,
362
+ top,
363
+ left,
364
+ },
365
+ ]);
366
+ break;
367
+ }
368
+
369
+ case "text": {
370
+ // Get image metadata
371
+ const metadata = yield* Effect.tryPromise({
372
+ try: async () => await pipeline.metadata(),
373
+ catch: (error) => {
374
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
375
+ body: "Failed to read image metadata",
376
+ cause: error,
377
+ });
378
+ },
379
+ });
380
+
381
+ if (!metadata.width || !metadata.height) {
382
+ return yield* Effect.fail(
383
+ UploadistaError.fromCode("UNKNOWN_ERROR", {
384
+ body: "Could not determine image dimensions",
385
+ }),
386
+ );
387
+ }
388
+
389
+ // Create SVG text overlay
390
+ const fontFamily = transformation.fontFamily || "sans-serif";
391
+
392
+ // Estimate text dimensions (rough approximation)
393
+ const textWidth =
394
+ transformation.text.length * transformation.fontSize * 0.6;
395
+ const textHeight = transformation.fontSize;
396
+
397
+ const { top, left } = calculateOverlayPosition(
398
+ transformation.position,
399
+ metadata.width,
400
+ metadata.height,
401
+ textWidth,
402
+ textHeight,
403
+ transformation.offsetX,
404
+ transformation.offsetY,
405
+ );
406
+
407
+ // Create positioned SVG
408
+ const positionedSvg = `
409
+ <svg width="${metadata.width}" height="${metadata.height}">
410
+ <text
411
+ x="${left}"
412
+ y="${top + transformation.fontSize}"
413
+ font-family="${fontFamily}"
414
+ font-size="${transformation.fontSize}"
415
+ fill="${transformation.color}"
416
+ >${transformation.text}</text>
417
+ </svg>
418
+ `;
419
+
420
+ pipeline = pipeline.composite([
421
+ {
422
+ input: Buffer.from(positionedSvg),
423
+ top: 0,
424
+ left: 0,
425
+ },
426
+ ]);
427
+ break;
428
+ }
429
+
430
+ default: {
431
+ // TypeScript should ensure this is unreachable
432
+ return yield* Effect.fail(
433
+ UploadistaError.fromCode("UNKNOWN_ERROR", {
434
+ body: `Unsupported transformation type: ${(transformation as { type: string }).type}`,
435
+ }),
436
+ );
437
+ }
438
+ }
439
+
440
+ // Convert pipeline to buffer
441
+ const outputBytes = yield* Effect.tryPromise({
442
+ try: async () => await pipeline.toBuffer(),
443
+ catch: (error) => {
444
+ return UploadistaError.fromCode("UNKNOWN_ERROR", {
445
+ body: `Failed to apply transformation: ${transformation.type}`,
446
+ cause: error,
447
+ });
448
+ },
449
+ });
450
+
53
451
  return new Uint8Array(outputBytes);
54
452
  });
55
453
  },