@stacksjs/image 0.75.514 → 0.75.518

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/app-icons.js CHANGED
@@ -1 +1 @@
1
- import process from"node:process";import{generateAppIcons,generateFavicons}from"ts-images";import{projectFile,requireProjectFile}from"./theme";export async function generateAppIconSet(images,root=process.cwd()){const appIcons=images.appIcons;if(appIcons?.enabled!==!0||!appIcons.source)return{icons:[],favicons:[]};const source=requireProjectFile(appIcons.source,root,"App icon source"),platforms=appIcons.platforms??["ios","macos"],icons=platforms.length===0?[]:await generateAppIcons(source,{outputDir:projectFile(appIcons.outputDir??"resources/app-icons",root),platform:platforms.length===1?platforms[0]:"all"}),favicons=appIcons.favicon?await generateFavicons(source,projectFile(appIcons.faviconDir??"public",root),{trim:appIcons.trim,manifest:appIcons.manifest===!1?!1:{name:images.brand,...appIcons.manifest??{}}}):[];return{icons,favicons}}
1
+ import process from"node:process";import{generateAppIcons,generateFavicons}from"ts-images";import{projectFile,requireProjectFile}from"./theme";export async function generateAppIconSet(images,root=process.cwd()){const appIcons=images.appIcons;if(appIcons?.enabled!==true||!appIcons.source)return{icons:[],favicons:[]};const source=requireProjectFile(appIcons.source,root,"App icon source");const platforms=appIcons.platforms??["ios","macos"];const icons=platforms.length===0?[]:await generateAppIcons(source,{outputDir:projectFile(appIcons.outputDir??"resources/app-icons",root),platform:platforms.length===1?platforms[0]:"all"});const favicons=appIcons.favicon?await generateFavicons(source,projectFile(appIcons.faviconDir??"public",root),{trim:appIcons.trim,manifest:appIcons.manifest===false?false:{name:images.brand,...appIcons.manifest??{}}}):[];return{icons,favicons}}
package/dist/app-store.js CHANGED
@@ -1 +1 @@
1
- import{mkdir}from"node:fs/promises";import process from"node:process";import{APP_STORE_MAX_SCREENSHOTS,generateAppStoreScreenshots}from"ts-images";import{loadFonts}from"./fonts";import{background,color,device,markPainter,projectFile,requireProjectFile,themed}from"./theme";export async function generateAppStoreScreenshotSet(images,root=process.cwd()){if(images.appStore?.enabled!==!0||!images.appStore.slides?.length)return{};const appStore=themed(images,images.appStore),declared=images.appStore.slides,displays=appStore.displays?.length?appStore.displays:["APP_IPHONE_67"],fonts=await loadFonts(images.fonts,root),outputDir=projectFile(appStore.outputDir??"resources/app-store/screenshots",root);await mkdir(outputDir,{recursive:!0});const shared={outputDir,titleFont:fonts.title,bodyFont:fonts.body,brand:appStore.brand,drawMark:(await markPainter(appStore.mark,root))?.draw,markPlate:appStore.markPlate===!1?void 0:color(appStore.markPlate),background:background(appStore.background,root),color:color(appStore.color),mutedColor:color(appStore.mutedColor),device:device(appStore.device),layout:appStore.layout,format:appStore.format??"png",quality:appStore.quality},results={};for(const display of displays){const slides=declared.filter((slide)=>!slide.displays?.length||slide.displays.includes(display)).map((slide)=>({capture:requireProjectFile(slide.capture,root,`Capture for the "${slide.headline}" slide`),headline:slide.headline,subheadline:slide.subheadline,background:background(slide.background,root)}));if(!slides.length)continue;if(slides.length>APP_STORE_MAX_SCREENSHOTS)throw Error(`[image] ${display} has ${slides.length} slides; App Store Connect accepts at most ${APP_STORE_MAX_SCREENSHOTS}`);const rendered=await generateAppStoreScreenshots({...shared,slides,displayTypes:[display]});results[display]=rendered[display]??[]}return results}
1
+ import{mkdir}from"node:fs/promises";import process from"node:process";import{APP_STORE_MAX_SCREENSHOTS,generateAppStoreScreenshots}from"ts-images";import{loadFonts}from"./fonts";import{background,color,device,markPainter,projectFile,requireProjectFile,themed}from"./theme";export async function generateAppStoreScreenshotSet(images,root=process.cwd()){if(images.appStore?.enabled!==true||!images.appStore.slides?.length)return{};const appStore=themed(images,images.appStore);const declared=images.appStore.slides;const displays=appStore.displays?.length?appStore.displays:["APP_IPHONE_67"];const fonts=await loadFonts(images.fonts,root);const outputDir=projectFile(appStore.outputDir??"resources/app-store/screenshots",root);await mkdir(outputDir,{recursive:true});const shared={outputDir,titleFont:fonts.title,bodyFont:fonts.body,brand:appStore.brand,drawMark:(await markPainter(appStore.mark,root))?.draw,markPlate:appStore.markPlate===false?undefined:color(appStore.markPlate),background:background(appStore.background,root),color:color(appStore.color),mutedColor:color(appStore.mutedColor),device:device(appStore.device),layout:appStore.layout,format:appStore.format??"png",quality:appStore.quality};const results={};for(const display of displays){const slides=declared.filter((slide)=>!slide.displays?.length||slide.displays.includes(display)).map((slide)=>({capture:requireProjectFile(slide.capture,root,`Capture for the "${slide.headline}" slide`),headline:slide.headline,subheadline:slide.subheadline,background:background(slide.background,root)}));if(!slides.length)continue;if(slides.length>APP_STORE_MAX_SCREENSHOTS)throw new Error(`[image] ${display} has ${slides.length} slides; App Store Connect accepts at most ${APP_STORE_MAX_SCREENSHOTS}`);const rendered=await generateAppStoreScreenshots({...shared,slides,displayTypes:[display]});results[display]=rendered[display]??[]}return results}
package/dist/fonts.js CHANGED
@@ -1,5 +1,5 @@
1
- import{existsSync}from"node:fs";import{readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import process from"node:process";import{loadFont}from"ts-images";export function resolveFontPath(value,root=process.cwd()){if(isAbsolute(value))return value;const local=resolve(root,value);if(existsSync(local))return local;try{return Bun.resolveSync(value,root)}catch{throw Error(`[image] Font not found: ${value}
2
- Looked for ${local} and for a module resolvable from ${root}.
3
- Set \`images.fonts.title\` in config/images.ts to a TrueType (.ttf) file. OpenType/CFF (.otf) and WOFF2 are not TrueType outlines and cannot be read.`)}}const SAMPLE_CHARACTERS="AaEeHhNnOoRrSsTt0123";export function drawsGlyphs(font){for(const character of SAMPLE_CHARACTERS){const glyphId=font.glyphIdFor(character.codePointAt(0));if(glyphId>0&&font.outline(glyphId).some((contour)=>contour.length>0))return!0}return!1}function loadDrawableFont(bytes,path,option){const font=loadFont(bytes);if(!drawsGlyphs(font))throw Error(`[image] Font draws no glyphs: ${path}
4
- It loaded, and it reports ${font.glyphCount} glyph(s), but every outline for common Latin characters is empty - a card drawn with it would be a background and no text, written successfully and silently wrong.
5
- Set \`images.fonts.${option}\` in config/images.ts to a TrueType face with drawable outlines. Bitmap-only faces and .ttf files wrapping OpenType/CFF outlines both look like this.`);return font}export async function loadFonts(fonts,root=process.cwd()){if(!fonts?.title)throw Error("[image] No font configured. Set `images.fonts.title` in config/images.ts to a TrueType (.ttf) file - generated cards and screenshots draw real glyphs and cannot fall back to a system face.");const titlePath=resolveFontPath(fonts.title,root),title=loadDrawableFont(new Uint8Array(await readFile(titlePath)),titlePath,"title");let body=title;if(fonts.body){const bodyPath=resolveFontPath(fonts.body,root);body=loadDrawableFont(new Uint8Array(await readFile(bodyPath)),bodyPath,"body")}return{title,body}}
1
+ import{existsSync}from"node:fs";import{readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import process from"node:process";import{loadFont}from"ts-images";export function resolveFontPath(value,root=process.cwd()){if(isAbsolute(value))return value;const local=resolve(root,value);if(existsSync(local))return local;try{return Bun.resolveSync(value,root)}catch{throw new Error(`[image] Font not found: ${value}
2
+ `+`Looked for ${local} and for a module resolvable from ${root}.
3
+ `+`Set \`images.fonts.title\` in config/images.ts to a TrueType (.ttf) file. `+`OpenType/CFF (.otf) and WOFF2 are not TrueType outlines and cannot be read.`)}}const SAMPLE_CHARACTERS="AaEeHhNnOoRrSsTt0123";export function drawsGlyphs(font){for(const character of SAMPLE_CHARACTERS){const glyphId=font.glyphIdFor(character.codePointAt(0));if(glyphId>0&&font.outline(glyphId).some((contour)=>contour.length>0))return true}return false}function loadDrawableFont(bytes,path,option){const font=loadFont(bytes);if(!drawsGlyphs(font)){throw new Error(`[image] Font draws no glyphs: ${path}
4
+ `+`It loaded, and it reports ${font.glyphCount} glyph(s), but every outline for `+`common Latin characters is empty - a card drawn with it would be a background `+`and no text, written successfully and silently wrong.
5
+ `+`Set \`images.fonts.${option}\` in config/images.ts to a TrueType face with `+`drawable outlines. Bitmap-only faces and .ttf files wrapping OpenType/CFF `+`outlines both look like this.`)}return font}export async function loadFonts(fonts,root=process.cwd()){if(!fonts?.title){throw new Error("[image] No font configured. Set `images.fonts.title` in config/images.ts to a TrueType (.ttf) file - "+"generated cards and screenshots draw real glyphs and cannot fall back to a system face.")}const titlePath=resolveFontPath(fonts.title,root);const title=loadDrawableFont(new Uint8Array(await readFile(titlePath)),titlePath,"title");let body=title;if(fonts.body){const bodyPath=resolveFontPath(fonts.body,root);body=loadDrawableFont(new Uint8Array(await readFile(bodyPath)),bodyPath,"body")}return{title,body}}
package/dist/generate.js CHANGED
@@ -1 +1 @@
1
- import process from"node:process";import{generateAppIconSet}from"./app-icons";import{generateAppStoreScreenshotSet}from"./app-store";import{generateSocialCardSet}from"./social";export async function generateImages(images,options={}){const root=options.root??process.cwd(),wanted=(target)=>!options.only?.length||options.only.includes(target);return{social:wanted("social")?await generateSocialCardSet(images,root):[],appStore:wanted("app-store")?await generateAppStoreScreenshotSet(images,root):{},appIcons:wanted("app-icons")?await generateAppIconSet(images,root):{icons:[],favicons:[]}}}export function countGeneratedImages(result){return{social:result.social.reduce((total,card)=>total+Object.keys(card.files).length,0),appStore:Object.values(result.appStore).reduce((total,paths)=>total+(paths?.length??0),0),appIcons:result.appIcons.icons.reduce((total,set)=>total+set.sizes.length,0)+result.appIcons.favicons.length}}
1
+ import process from"node:process";import{generateAppIconSet}from"./app-icons";import{generateAppStoreScreenshotSet}from"./app-store";import{generateSocialCardSet}from"./social";export async function generateImages(images,options={}){const root=options.root??process.cwd();const wanted=(target)=>!options.only?.length||options.only.includes(target);return{social:wanted("social")?await generateSocialCardSet(images,root):[],appStore:wanted("app-store")?await generateAppStoreScreenshotSet(images,root):{},appIcons:wanted("app-icons")?await generateAppIconSet(images,root):{icons:[],favicons:[]}}}export function countGeneratedImages(result){return{social:result.social.reduce((total,card)=>total+Object.keys(card.files).length,0),appStore:Object.values(result.appStore).reduce((total,paths)=>total+(paths?.length??0),0),appIcons:result.appIcons.icons.reduce((total,set)=>total+set.sizes.length,0)+result.appIcons.favicons.length}}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{createHash,createHmac,randomUUID,timingSafeEqual}from"node:crypto";import{mkdir,readFile,rename,stat,writeFile}from"node:fs/promises";import{readFileSync}from"node:fs";import{basename,dirname,extname,isAbsolute,relative,resolve}from"node:path";import{decode,encode,imageToSplatHash,resize}from"ts-images";export*from"./app-icons";export*from"./app-store";export*from"./fonts";export*from"./generate";export*from"./social";export*from"./splash";export*from"./theme";export*from"./upload";const mime={avif:"image/avif",webp:"image/webp",jpeg:"image/jpeg",png:"image/png"};function integer(name,value,min,max){if(!Number.isInteger(value)||value<min||value>max)throw TypeError(`${name} must be between ${min} and ${max}`)}let codecs;function codecFingerprint(){if(codecs!==void 0)return codecs;const version=(name,from)=>{try{return JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,from),"utf8")).version??"?"}catch{return"?"}};let imagesDir=import.meta.dir;try{imagesDir=dirname(Bun.resolveSync("ts-images/package.json",import.meta.dir))}catch{}codecs=[`ts-images@${version("ts-images",import.meta.dir)}`,`ts-webp@${version("@stacksjs/ts-webp",imagesDir)}`,`ts-avif@${version("@stacksjs/ts-avif",imagesDir)}`].join(",");return codecs}export function resolveImageSource(source,root=process.cwd()){const allowed=resolve(root),candidate=isAbsolute(source)?resolve(source):resolve(allowed,source),relation=relative(allowed,candidate);if(source.includes("\x00")||relation===".."||relation.startsWith("../")||isAbsolute(relation))throw Error("Image source must stay inside the configured root");return candidate}export class ImageBuilder{source;targetWidths=[480,768,1280,1920];targetFormats=["avif","webp","jpeg"];targetFit="inside";targetHeight;targetAspectRatio;targetPosition="center";includeOriginal=!0;targetStorage;targetQuality=82;options;constructor(source,options={}){this.source=source;const root=options.root??process.cwd();this.options={...options,root,outputDir:options.outputDir??resolve(root,"public/media/images"),publicPath:options.publicPath??"/media/images",concurrency:options.concurrency??4,upscale:options.upscale??!1}}widths(widths){if(!widths.length)throw TypeError("Image widths are required");widths.forEach((value)=>integer("Image width",value,1,16384));this.targetWidths=[...new Set(widths)].sort((a,b)=>a-b);return this}formats(formats){if(!formats.length)throw TypeError("Image formats are required");this.targetFormats=[...new Set(formats)];return this}fit(fit){this.targetFit=fit;return this}height(value){integer("Image height",value,1,16384);this.targetHeight=value;this.targetAspectRatio=void 0;return this}aspectRatio(value){if(!Number.isFinite(value)||value<=0||value>100)throw TypeError("Image aspect ratio must be between 0 and 100");this.targetAspectRatio=value;this.targetHeight=void 0;return this}position(value){this.targetPosition=value;return this}preset(value){const preset={avatar:{widths:[64,128,256,512],ratio:1,fit:"cover",original:!1},content:{widths:[320,640,960,1280,1920],fit:"inside",original:!0},hero:{widths:[640,1280,1920,2560],ratio:1.7777777777777777,fit:"cover",original:!0},thumbnail:{widths:[160,320,640],ratio:1.7777777777777777,fit:"cover",original:!1}}[value];this.targetWidths=[...preset.widths];this.targetFit=preset.fit;this.targetAspectRatio="ratio"in preset?preset.ratio:void 0;this.targetHeight=void 0;this.includeOriginal=preset.original;return this}quality(value){integer("Image quality",value,1,100);this.targetQuality=value;return this}original(include){this.includeOriginal=include;return this}output(dir,publicPath="/media/images"){this.options.outputDir=resolve(dir);this.options.publicPath=`/${publicPath.replace(/^\/+|\/+$/g,"")}`;return this}storage(adapter,prefix="media/images"){this.targetStorage={adapter,prefix:prefix.replace(/^\/+|\/+$/g,"")};return this}async generate(){integer("Image concurrency",this.options.concurrency,1,32);const sourcePath=resolveImageSource(this.source,this.options.root);if(this.options.authorize&&!await this.options.authorize(sourcePath,this.options.authorizationContext))throw Error("Image delivery is not authorized");const bytes=new Uint8Array(await readFile(sourcePath)),hash=createHash("sha256").update(bytes).digest("hex"),decoded=await decode(bytes),widths=this.targetWidths.filter((width)=>this.options.upscale||width<=decoded.width);if(this.includeOriginal&&!widths.includes(decoded.width))widths.push(decoded.width);const tasks=[...new Set(widths)].sort((a,b)=>a-b).flatMap((width)=>this.targetFormats.map((format)=>({width,format}))),variants=[];let cursor=0;await Promise.all(Array.from({length:Math.min(tasks.length,this.options.concurrency)},async()=>{while(cursor<tasks.length){const task=tasks[cursor++];variants.push(await this.variant(decoded,hash,sourcePath,task.width,task.format))}}));variants.sort((a,b)=>a.width-b.width||this.targetFormats.indexOf(a.format)-this.targetFormats.indexOf(b.format));return{source:{width:decoded.width,height:decoded.height,hash},variants,placeholder:Buffer.from(imageToSplatHash(decoded)).toString("base64url")}}async variant(source,hash,sourcePath,width,format){const height=this.targetHeight??(this.targetAspectRatio?Math.max(1,Math.round(width/this.targetAspectRatio)):void 0),output=width===source.width&&height===void 0?source:resize(source,{width,height,fit:this.targetFit,position:this.targetPosition});if(!this.options.upscale&&(output.width>source.width||output.height>source.height))throw TypeError(`Image variant ${output.width}x${output.height} would upscale the source`);const cacheKey=createHash("sha256").update(`${hash}:${width}:${height??"auto"}:${format}:${this.targetFit}:${this.targetPosition}:${this.targetQuality}:${codecFingerprint()}`).digest("hex"),filename=`${basename(sourcePath,extname(sourcePath)).replace(/[^a-zA-Z0-9_-]/g,"-")||"image"}-${output.width}x${output.height}-${cacheKey.slice(0,16)}.${format==="jpeg"?"jpg":format}`,path=resolve(this.options.outputDir,filename);if(this.targetStorage){const key=this.targetStorage.prefix?`${this.targetStorage.prefix}/${filename}`:filename;if(await this.targetStorage.adapter.fileExists(key)){const existing=await this.targetStorage.adapter.stat(key);return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const encoded=await encode(output,format,{quality:this.targetQuality,progressive:!0}),written=await this.targetStorage.adapter.write(key,encoded);return{width:output.width,height:output.height,bytes:written.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const existing=await stat(path).catch(()=>null);if(existing)return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey};const encoded=await encode(output,format,{quality:this.targetQuality,progressive:!0});await mkdir(this.options.outputDir,{recursive:!0});const temporary=`${path}.${process.pid}.${randomUUID()}.tmp`;await writeFile(temporary,encoded);await rename(temporary,path);return{width:output.width,height:output.height,bytes:encoded.byteLength,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey}}}export function image(source,options={}){return new ImageBuilder(source,options)}function accepted(accept,mimeType){const[type,subtype]=mimeType.split("/");let best=0;for(const item of accept.split(",")){const[range="*/*",...params]=item.trim().toLowerCase().split(";").map((value)=>value.trim()),[acceptedType,acceptedSubtype]=range.split("/");if(acceptedType!=="*"&&acceptedType!==type||acceptedSubtype!=="*"&&acceptedSubtype!==subtype)continue;const raw=params.find((param)=>param.startsWith("q="));best=Math.max(best,raw?Number.parseFloat(raw.slice(2))||0:1)}return best}export function negotiateImageVariant(variants,accept="*/*",width){const widths=[...new Set(variants.map((item)=>item.width))].sort((a,b)=>a-b),target=width===void 0?widths.at(-1):widths.find((value)=>value>=width)??widths.at(-1);return variants.filter((item)=>item.width===target).map((variant,index)=>({variant,index,q:accepted(accept||"*/*",variant.mimeType)})).filter((item)=>item.q>0).sort((a,b)=>b.q-a.q||a.index-b.index)[0]?.variant}export function imageResponseHeaders(variant){return{"Content-Type":variant.mimeType,"Content-Length":String(variant.bytes),"Cache-Control":"public, max-age=31536000, immutable",ETag:`"${variant.cacheKey}"`,Vary:"Accept","X-Image-Width":String(variant.width),"X-Image-Height":String(variant.height)}}export function signImageTransform(path,expires,secret){return createHmac("sha256",secret).update(`${path}
2
- ${expires}`).digest("base64url")}export function verifyImageTransform(path,expires,signature,secret,now=Date.now()){if(!Number.isInteger(expires)||expires*1000<=now)return!1;const expected=Buffer.from(signImageTransform(path,expires,secret)),actual=Buffer.from(signature);return expected.length===actual.length&&timingSafeEqual(expected,actual)}
1
+ import{createHash,createHmac,randomUUID,timingSafeEqual}from"node:crypto";import{mkdir,readFile,rename,stat,writeFile}from"node:fs/promises";import{readFileSync}from"node:fs";import{basename,dirname,extname,isAbsolute,relative,resolve}from"node:path";import{decode,encode,imageToSplatHash,resize}from"ts-images";export*from"./app-icons";export*from"./app-store";export*from"./fonts";export*from"./generate";export*from"./social";export*from"./splash";export*from"./theme";export*from"./upload";const mime={avif:"image/avif",webp:"image/webp",jpeg:"image/jpeg",png:"image/png"};function integer(name,value,min,max){if(!Number.isInteger(value)||value<min||value>max)throw new TypeError(`${name} must be between ${min} and ${max}`)}let codecs;function codecFingerprint(){if(codecs!==undefined)return codecs;const version=(name,from)=>{try{return JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,from),"utf8")).version??"?"}catch{return"?"}};let imagesDir=import.meta.dir;try{imagesDir=dirname(Bun.resolveSync("ts-images/package.json",import.meta.dir))}catch{}codecs=[`ts-images@${version("ts-images",import.meta.dir)}`,`ts-webp@${version("@stacksjs/ts-webp",imagesDir)}`,`ts-avif@${version("@stacksjs/ts-avif",imagesDir)}`].join(",");return codecs}export function resolveImageSource(source,root=process.cwd()){const allowed=resolve(root);const candidate=isAbsolute(source)?resolve(source):resolve(allowed,source);const relation=relative(allowed,candidate);if(source.includes("\x00")||relation===".."||relation.startsWith("../")||isAbsolute(relation))throw new Error("Image source must stay inside the configured root");return candidate}export class ImageBuilder{source;targetWidths=[480,768,1280,1920];targetFormats=["avif","webp","jpeg"];targetFit="inside";targetHeight;targetAspectRatio;targetPosition="center";includeOriginal=true;targetStorage;targetQuality=82;options;constructor(source,options={}){this.source=source;const root=options.root??process.cwd();this.options={...options,root,outputDir:options.outputDir??resolve(root,"public/media/images"),publicPath:options.publicPath??"/media/images",concurrency:options.concurrency??4,upscale:options.upscale??false}}widths(widths){if(!widths.length)throw new TypeError("Image widths are required");widths.forEach((value)=>integer("Image width",value,1,16384));this.targetWidths=[...new Set(widths)].sort((a,b)=>a-b);return this}formats(formats){if(!formats.length)throw new TypeError("Image formats are required");this.targetFormats=[...new Set(formats)];return this}fit(fit){this.targetFit=fit;return this}height(value){integer("Image height",value,1,16384);this.targetHeight=value;this.targetAspectRatio=undefined;return this}aspectRatio(value){if(!Number.isFinite(value)||value<=0||value>100)throw new TypeError("Image aspect ratio must be between 0 and 100");this.targetAspectRatio=value;this.targetHeight=undefined;return this}position(value){this.targetPosition=value;return this}preset(value){const presets={avatar:{widths:[64,128,256,512],ratio:1,fit:"cover",original:false},content:{widths:[320,640,960,1280,1920],fit:"inside",original:true},hero:{widths:[640,1280,1920,2560],ratio:16/9,fit:"cover",original:true},thumbnail:{widths:[160,320,640],ratio:16/9,fit:"cover",original:false}};const preset=presets[value];this.targetWidths=[...preset.widths];this.targetFit=preset.fit;this.targetAspectRatio="ratio"in preset?preset.ratio:undefined;this.targetHeight=undefined;this.includeOriginal=preset.original;return this}quality(value){integer("Image quality",value,1,100);this.targetQuality=value;return this}original(include){this.includeOriginal=include;return this}output(dir,publicPath="/media/images"){this.options.outputDir=resolve(dir);this.options.publicPath=`/${publicPath.replace(/^\/+|\/+$/g,"")}`;return this}storage(adapter,prefix="media/images"){this.targetStorage={adapter,prefix:prefix.replace(/^\/+|\/+$/g,"")};return this}async generate(){integer("Image concurrency",this.options.concurrency,1,32);const sourcePath=resolveImageSource(this.source,this.options.root);if(this.options.authorize&&!await this.options.authorize(sourcePath,this.options.authorizationContext))throw new Error("Image delivery is not authorized");const bytes=new Uint8Array(await readFile(sourcePath));const hash=createHash("sha256").update(bytes).digest("hex");const decoded=await decode(bytes);const widths=this.targetWidths.filter((width)=>this.options.upscale||width<=decoded.width);if(this.includeOriginal&&!widths.includes(decoded.width))widths.push(decoded.width);const tasks=[...new Set(widths)].sort((a,b)=>a-b).flatMap((width)=>this.targetFormats.map((format)=>({width,format})));const variants=[];let cursor=0;await Promise.all(Array.from({length:Math.min(tasks.length,this.options.concurrency)},async()=>{while(cursor<tasks.length){const task=tasks[cursor++];variants.push(await this.variant(decoded,hash,sourcePath,task.width,task.format))}}));variants.sort((a,b)=>a.width-b.width||this.targetFormats.indexOf(a.format)-this.targetFormats.indexOf(b.format));return{source:{width:decoded.width,height:decoded.height,hash},variants,placeholder:Buffer.from(imageToSplatHash(decoded)).toString("base64url")}}async variant(source,hash,sourcePath,width,format){const height=this.targetHeight??(this.targetAspectRatio?Math.max(1,Math.round(width/this.targetAspectRatio)):undefined);const output=width===source.width&&height===undefined?source:resize(source,{width,height,fit:this.targetFit,position:this.targetPosition});if(!this.options.upscale&&(output.width>source.width||output.height>source.height))throw new TypeError(`Image variant ${output.width}x${output.height} would upscale the source`);const cacheKey=createHash("sha256").update(`${hash}:${width}:${height??"auto"}:${format}:${this.targetFit}:${this.targetPosition}:${this.targetQuality}:${codecFingerprint()}`).digest("hex");const stem=basename(sourcePath,extname(sourcePath)).replace(/[^a-zA-Z0-9_-]/g,"-")||"image";const filename=`${stem}-${output.width}x${output.height}-${cacheKey.slice(0,16)}.${format==="jpeg"?"jpg":format}`;const path=resolve(this.options.outputDir,filename);if(this.targetStorage){const key=this.targetStorage.prefix?`${this.targetStorage.prefix}/${filename}`:filename;if(await this.targetStorage.adapter.fileExists(key)){const existing=await this.targetStorage.adapter.stat(key);return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const encoded=await encode(output,format,{quality:this.targetQuality,progressive:true});const written=await this.targetStorage.adapter.write(key,encoded);return{width:output.width,height:output.height,bytes:written.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const existing=await stat(path).catch(()=>null);if(existing)return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey};const encoded=await encode(output,format,{quality:this.targetQuality,progressive:true});await mkdir(this.options.outputDir,{recursive:true});const temporary=`${path}.${process.pid}.${randomUUID()}.tmp`;await writeFile(temporary,encoded);await rename(temporary,path);return{width:output.width,height:output.height,bytes:encoded.byteLength,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey}}}export function image(source,options={}){return new ImageBuilder(source,options)}function accepted(accept,mimeType){const[type,subtype]=mimeType.split("/");let best=0;for(const item of accept.split(",")){const[range="*/*",...params]=item.trim().toLowerCase().split(";").map((value)=>value.trim());const[acceptedType,acceptedSubtype]=range.split("/");if(acceptedType!=="*"&&acceptedType!==type||acceptedSubtype!=="*"&&acceptedSubtype!==subtype)continue;const raw=params.find((param)=>param.startsWith("q="));best=Math.max(best,raw?Number.parseFloat(raw.slice(2))||0:1)}return best}export function negotiateImageVariant(variants,accept="*/*",width){const widths=[...new Set(variants.map((item)=>item.width))].sort((a,b)=>a-b);const target=width===undefined?widths.at(-1):widths.find((value)=>value>=width)??widths.at(-1);return variants.filter((item)=>item.width===target).map((variant,index)=>({variant,index,q:accepted(accept||"*/*",variant.mimeType)})).filter((item)=>item.q>0).sort((a,b)=>b.q-a.q||a.index-b.index)[0]?.variant}export function imageResponseHeaders(variant){return{"Content-Type":variant.mimeType,"Content-Length":String(variant.bytes),"Cache-Control":"public, max-age=31536000, immutable",ETag:`"${variant.cacheKey}"`,Vary:"Accept","X-Image-Width":String(variant.width),"X-Image-Height":String(variant.height)}}export function signImageTransform(path,expires,secret){return createHmac("sha256",secret).update(`${path}
2
+ ${expires}`).digest("base64url")}export function verifyImageTransform(path,expires,signature,secret,now=Date.now()){if(!Number.isInteger(expires)||expires*1000<=now)return false;const expected=Buffer.from(signImageTransform(path,expires,secret));const actual=Buffer.from(signature);return expected.length===actual.length&&timingSafeEqual(expected,actual)}
package/dist/social.js CHANGED
@@ -1 +1 @@
1
- import{mkdir}from"node:fs/promises";import process from"node:process";import{generateSocialCards,renderSocialCard}from"ts-images";import{loadFonts}from"./fonts";import{background,color,device,markPainter,projectFile,requireProjectFile,themed}from"./theme";const PRESET_SIZES={og:{width:1200,height:630},twitter:{width:1200,height:600},square:{width:1200,height:1200},portrait:{width:1200,height:1500}};export function socialCardName(path){const trimmed=path.replace(/^\/+|\/+$/g,"");return trimmed===""?"og":trimmed.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}async function socialCardTheme(images,root){const social=themed(images,images.social),fonts=await loadFonts(images.fonts,root),mark=await markPainter(social.mark,root,{colorScheme:social.markColorScheme}),presets=social.presets?.length?social.presets:["og"];return{social,presets,deviceOptions:device(social.device),shared:{titleFont:fonts.title,bodyFont:fonts.body,brand:social.brand,drawMark:mark?.draw,markAspect:mark?.aspect,markPlate:social.markPlate===!1?null:color(social.markPlate),surface:background(social.background,root),color:color(social.color),mutedColor:color(social.mutedColor),accent:color(social.accent),format:social.format??"jpeg",quality:social.quality,presets}}}export function textSizes(set,page){return{titleSize:page?.titleSize??set?.titleSize,eyebrowSize:page?.eyebrowSize??set?.eyebrowSize,subtitleSize:page?.subtitleSize??set?.subtitleSize}}function cardForeground(shot,deviceOptions,root,label){if(!shot)return;return{image:requireProjectFile(shot,root,label),radius:deviceOptions?.radius,borderColor:deviceOptions?.borderColor,shadow:deviceOptions?.shadow,scale:deviceOptions?.scale}}export async function generateSocialCardSet(images,root=process.cwd()){if(images.social?.enabled!==!0)return[];const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root),outputDir=projectFile(social.outputDir??"public/social",root),publicPath=`/${(social.publicPath??"/social").replace(/^\/+|\/+$/g,"")}`;await mkdir(outputDir,{recursive:!0});const pages=social.pages?.length?social.pages:[{path:"/",title:social.brand??"Home"}],results=[];for(const page of pages){const name=socialCardName(page.path),shot=page.foreground??social.foreground,files=await generateSocialCards(outputDir,{...shared,...textSizes(social.text,page.text),name,title:page.title,eyebrow:page.eyebrow,subtitle:page.subtitle,foreground:cardForeground(shot,deviceOptions,root,`Product shot for ${page.path}`)}),urls=Object.fromEntries(Object.entries(files).map(([preset,file])=>[preset,`${publicPath}/${file.slice(file.lastIndexOf("/")+1)}`]));results.push({path:page.path,name,files,urls,width:PRESET_SIZES[presets[0]].width,height:PRESET_SIZES[presets[0]].height,title:page.title})}return results}export async function renderOnDemandSocialCard(images,card,root=process.cwd()){if(images.social?.enabled!==!0)return null;const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root),preset=card.preset??presets[0],{width,height}=PRESET_SIZES[preset],format=shared.format,{presets:_presets,...cardOptions}=shared;return{bytes:await renderSocialCard({...cardOptions,...textSizes(social.text),width,height,title:card.title,eyebrow:card.eyebrow,subtitle:card.subtitle,foreground:cardForeground(card.foreground??social.foreground,deviceOptions,root,"On-demand product shot")}),contentType:format==="jpeg"?"image/jpeg":`image/${format}`,width,height}}export function socialMetaTags(card,siteUrl,format="jpeg"){const primary=`${siteUrl.replace(/\/+$/,"")}${card.urls.og??Object.values(card.urls)[0]}`,mimeType=format==="jpeg"?"image/jpeg":`image/${format}`;return[`<meta property="og:image" content="${primary}">`,`<meta property="og:image:type" content="${mimeType}">`,`<meta property="og:image:width" content="${card.width}">`,`<meta property="og:image:height" content="${card.height}">`,`<meta property="og:image:alt" content="${escapeAttribute(card.title)}">`,'<meta name="twitter:card" content="summary_large_image">',`<meta name="twitter:image" content="${primary}">`,`<meta name="twitter:image:alt" content="${escapeAttribute(card.title)}">`]}function escapeAttribute(value){return value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}
1
+ import{mkdir}from"node:fs/promises";import process from"node:process";import{generateSocialCards,renderSocialCard}from"ts-images";import{loadFonts}from"./fonts";import{background,color,device,markPainter,projectFile,requireProjectFile,themed}from"./theme";const PRESET_SIZES={og:{width:1200,height:630},twitter:{width:1200,height:600},square:{width:1200,height:1200},portrait:{width:1200,height:1500}};export function socialCardName(path){const trimmed=path.replace(/^\/+|\/+$/g,"");return trimmed===""?"og":trimmed.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}async function socialCardTheme(images,root){const social=themed(images,images.social);const fonts=await loadFonts(images.fonts,root);const mark=await markPainter(social.mark,root,{colorScheme:social.markColorScheme});const presets=social.presets?.length?social.presets:["og"];return{social,presets,deviceOptions:device(social.device),shared:{titleFont:fonts.title,bodyFont:fonts.body,brand:social.brand,drawMark:mark?.draw,markAspect:mark?.aspect,markPlate:social.markPlate===false?null:color(social.markPlate),surface:background(social.background,root),color:color(social.color),mutedColor:color(social.mutedColor),accent:color(social.accent),format:social.format??"jpeg",quality:social.quality,presets}}}export function textSizes(set,page){return{titleSize:page?.titleSize??set?.titleSize,eyebrowSize:page?.eyebrowSize??set?.eyebrowSize,subtitleSize:page?.subtitleSize??set?.subtitleSize}}function cardForeground(shot,deviceOptions,root,label){if(!shot)return;return{image:requireProjectFile(shot,root,label),radius:deviceOptions?.radius,borderColor:deviceOptions?.borderColor,shadow:deviceOptions?.shadow,scale:deviceOptions?.scale}}export async function generateSocialCardSet(images,root=process.cwd()){if(images.social?.enabled!==true)return[];const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root);const outputDir=projectFile(social.outputDir??"public/social",root);const publicPath=`/${(social.publicPath??"/social").replace(/^\/+|\/+$/g,"")}`;await mkdir(outputDir,{recursive:true});const pages=social.pages?.length?social.pages:[{path:"/",title:social.brand??"Home"}];const results=[];for(const page of pages){const name=socialCardName(page.path);const shot=page.foreground??social.foreground;const files=await generateSocialCards(outputDir,{...shared,...textSizes(social.text,page.text),name,title:page.title,eyebrow:page.eyebrow,subtitle:page.subtitle,foreground:cardForeground(shot,deviceOptions,root,`Product shot for ${page.path}`)});const urls=Object.fromEntries(Object.entries(files).map(([preset,file])=>[preset,`${publicPath}/${file.slice(file.lastIndexOf("/")+1)}`]));results.push({path:page.path,name,files,urls,width:PRESET_SIZES[presets[0]].width,height:PRESET_SIZES[presets[0]].height,title:page.title})}return results}export async function renderOnDemandSocialCard(images,card,root=process.cwd()){if(images.social?.enabled!==true)return null;const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root);const preset=card.preset??presets[0];const{width,height}=PRESET_SIZES[preset];const format=shared.format;const{presets:_presets,...cardOptions}=shared;const bytes=await renderSocialCard({...cardOptions,...textSizes(social.text),width,height,title:card.title,eyebrow:card.eyebrow,subtitle:card.subtitle,foreground:cardForeground(card.foreground??social.foreground,deviceOptions,root,"On-demand product shot")});return{bytes,contentType:format==="jpeg"?"image/jpeg":`image/${format}`,width,height}}export function socialMetaTags(card,siteUrl,format="jpeg"){const base=siteUrl.replace(/\/+$/,"");const primary=`${base}${card.urls.og??Object.values(card.urls)[0]}`;const mimeType=format==="jpeg"?"image/jpeg":`image/${format}`;const tags=[`<meta property="og:image" content="${primary}">`,`<meta property="og:image:type" content="${mimeType}">`,`<meta property="og:image:width" content="${card.width}">`,`<meta property="og:image:height" content="${card.height}">`,`<meta property="og:image:alt" content="${escapeAttribute(card.title)}">`,`<meta name="twitter:card" content="summary_large_image">`,`<meta name="twitter:image" content="${primary}">`,`<meta name="twitter:image:alt" content="${escapeAttribute(card.title)}">`];return tags}function escapeAttribute(value){return value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}
package/dist/splash.js CHANGED
@@ -1 +1 @@
1
- import{existsSync,rmSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{generateSplashScreens}from"ts-images";import{projectFile}from"./theme";function requireProjectFile(path,root,key){const resolved=projectFile(path,root);if(!existsSync(resolved))throw Error(`[image] ${key} not found: ${path} (looked in ${resolved})`);return resolved}const CRAFT_DEFAULT_BACKGROUND="#000000",HEX=/^#[0-9a-f]{6}$/i;export function mobileSplashOptions(input,root=process.cwd()){const{platform,splash}=input;if(splash===!1)return null;if(platform==="ios"&&splash?.image)return null;const source=splash?.logo??input.appIcon;if(!source)return null;const key=`${platform}.splash`,logo=requireProjectFile(source,root,splash?.logo?`${key}.logo`:`${platform}.appIcon (the default ${key}.logo)`),logoDark=splash?.logoDark?requireProjectFile(splash.logoDark,root,`${key}.logoDark`):void 0;for(const[name,value]of[["backgroundColor",input.backgroundColor],["backgroundColorDark",input.backgroundColorDark],["splash.accent",splash?.accent||void 0]])if(value!==void 0&&!HEX.test(value))throw Error(`${platform}.${name} must be a #RRGGBB colour for the generated splash, not ${String(value)}`);if(splash?.text!==void 0&&!splash.font)throw Error(`${key}.text needs ${key}.font: the .ttf to set it in`);if(splash?.size!==void 0&&!(splash.size>0))throw Error(`${key}.size must be a positive number of points`);const background=input.backgroundColor??CRAFT_DEFAULT_BACKGROUND,dark=input.backgroundColorDark||logoDark?{background:input.backgroundColorDark??background,...logoDark?{logo:logoDark}:{}}:!1,accent=splash?.accent===!1?void 0:splash?.accent??input.tintColor,options={logo,light:{background},dark,shape:splash?.shape??(splash?.logo?"none":"rounded"),platforms:[platform]};if(accent)options.accent=accent;if(splash?.accent===!1)options.glow=!1;if(splash?.size!==void 0)options.size=splash.size;if(splash?.text)options.text={value:splash.text,font:requireProjectFile(splash.font,root,`${key}.font`),...splash.uppercase?{uppercase:!0}:{}};return options}export async function generateMobileSplash(input,outputDir,root=process.cwd()){const{platform,splash}=input;if(splash===!1)return null;if(platform==="ios"&&splash?.image)return{image:requireProjectFile(splash.image,root,"ios.splash.image"),imageDark:splash.imageDark?requireProjectFile(splash.imageDark,root,"ios.splash.imageDark"):void 0,generated:!1};const options=mobileSplashOptions(input,root);if(!options)return null;rmSync(join(outputDir,platform),{recursive:!0,force:!0});const result=await generateSplashScreens(options,outputDir);return platform==="ios"?{image:result.ios?.image,imageDark:result.ios?.imageDark,generated:!0}:{resources:result.android?.resources,generated:!0}}
1
+ import{existsSync,rmSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{generateSplashScreens}from"ts-images";import{projectFile}from"./theme";function requireProjectFile(path,root,key){const resolved=projectFile(path,root);if(!existsSync(resolved))throw new Error(`[image] ${key} not found: ${path} (looked in ${resolved})`);return resolved}const CRAFT_DEFAULT_BACKGROUND="#000000";const HEX=/^#[0-9a-f]{6}$/i;export function mobileSplashOptions(input,root=process.cwd()){const{platform,splash}=input;if(splash===false)return null;if(platform==="ios"&&splash?.image)return null;const source=splash?.logo??input.appIcon;if(!source)return null;const key=`${platform}.splash`;const logo=requireProjectFile(source,root,splash?.logo?`${key}.logo`:`${platform}.appIcon (the default ${key}.logo)`);const logoDark=splash?.logoDark?requireProjectFile(splash.logoDark,root,`${key}.logoDark`):undefined;for(const[name,value]of[["backgroundColor",input.backgroundColor],["backgroundColorDark",input.backgroundColorDark],[`splash.accent`,splash?.accent||undefined]]){if(value!==undefined&&!HEX.test(value))throw new Error(`${platform}.${name} must be a #RRGGBB colour for the generated splash, not ${String(value)}`)}if(splash?.text!==undefined&&!splash.font)throw new Error(`${key}.text needs ${key}.font: the .ttf to set it in`);if(splash?.size!==undefined&&!(splash.size>0))throw new Error(`${key}.size must be a positive number of points`);const background=input.backgroundColor??CRAFT_DEFAULT_BACKGROUND;const dark=input.backgroundColorDark||logoDark?{background:input.backgroundColorDark??background,...logoDark?{logo:logoDark}:{}}:false;const accent=splash?.accent===false?undefined:splash?.accent??input.tintColor;const options={logo,light:{background},dark,shape:splash?.shape??(splash?.logo?"none":"rounded"),platforms:[platform]};if(accent)options.accent=accent;if(splash?.accent===false)options.glow=false;if(splash?.size!==undefined)options.size=splash.size;if(splash?.text){options.text={value:splash.text,font:requireProjectFile(splash.font,root,`${key}.font`),...splash.uppercase?{uppercase:true}:{}}}return options}export async function generateMobileSplash(input,outputDir,root=process.cwd()){const{platform,splash}=input;if(splash===false)return null;if(platform==="ios"&&splash?.image){return{image:requireProjectFile(splash.image,root,"ios.splash.image"),imageDark:splash.imageDark?requireProjectFile(splash.imageDark,root,"ios.splash.imageDark"):undefined,generated:false}}const options=mobileSplashOptions(input,root);if(!options)return null;rmSync(join(outputDir,platform),{recursive:true,force:true});const result=await generateSplashScreens(options,outputDir);return platform==="ios"?{image:result.ios?.image,imageDark:result.ios?.imageDark,generated:true}:{resources:result.android?.resources,generated:true}}
package/dist/theme.js CHANGED
@@ -1,2 +1,2 @@
1
- import{existsSync}from"node:fs";import{readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import process from"node:process";import{parseSVG,rasterize}from"@stacksjs/ts-svg";import{createImageData,crop,decode,drawImage,parseColor}from"ts-images";export function projectFile(path,root=process.cwd()){return isAbsolute(path)?path:resolve(root,path)}export function requireProjectFile(path,root,describe){const resolved=projectFile(path,root);if(!existsSync(resolved))throw Error(`[image] ${describe} not found: ${path}
2
- Looked in ${resolved}. Capture it before generating - \`buddy generate:images\` frames existing captures, it does not take them.`);return resolved}export function color(value){return value===void 0?void 0:parseColor(value)}export function background(value,root=process.cwd()){if(!value)return;return{color:color(value.color),gradient:value.gradient&&{angle:value.gradient.angle,stops:value.gradient.stops.map((stop)=>({offset:stop.offset,color:parseColor(stop.color)}))},glows:value.glows?.map((glow)=>({...glow,color:parseColor(glow.color)})),image:value.image?projectFile(value.image,root):void 0}}export function device(value){if(!value)return;return{radius:value.radius,scale:value.scale,borderColor:color(value.borderColor),shadow:value.shadow===!1?void 0:{...value.shadow??{},color:color(value.shadow?.color)}}}function svgMark(source,colorScheme){const root=parseSVG(source,{colorScheme}),draw=(height)=>{const frame=rasterize(root,{height:Math.max(1,Math.round(height))}),image=createImageData(frame.width,frame.height);image.data.set(frame.data);return trimTransparentEdges(image)},SAMPLE=512,sample=draw(SAMPLE),fill=sample.height>0?sample.height/SAMPLE:1;return{render:(height)=>draw(height/fill),aspect:sample.height>0?sample.width/sample.height:1}}export async function markPainter(path,root=process.cwd(),options={}){if(!path)return;const file=projectFile(path,root);if(/\.svg$/i.test(file)){const{render,aspect}=svgMark(await readFile(file,"utf8"),options.colorScheme??"light");return{aspect,draw:(canvas,box)=>{const mark=render(box.size);drawImage(canvas,mark,{x:box.x,y:box.y,width:box.width??box.size*aspect,height:box.size,fit:"contain"})}}}const mark=trimTransparentEdges(await decode(new Uint8Array(await readFile(file)))),aspect=mark.height>0?mark.width/mark.height:1;return{aspect,draw:(canvas,box)=>{drawImage(canvas,mark,{x:box.x,y:box.y,width:box.width??box.size*aspect,height:box.size,fit:"contain"})}}}export function trimTransparentEdges(image,alphaThreshold=8){let{width:left,height:top}=image,right=-1,bottom=-1;for(let y=0;y<image.height;y++)for(let x=0;x<image.width;x++)if((image.data[(y*image.width+x)*4+3]??0)>alphaThreshold){if(x<left)left=x;if(x>right)right=x;if(y<top)top=y;if(y>bottom)bottom=y}if(right<0||left===0&&top===0&&right===image.width-1&&bottom===image.height-1)return image;return crop(image,{left,top,width:right-left+1,height:bottom-top+1})}export function themed(images,section){return{...section??{},background:section?.background??images.background,color:section?.color??images.color,mutedColor:section?.mutedColor??images.mutedColor,accent:section?.accent??images.accent,device:section?.device??images.device,brand:section?.brand??images.brand,mark:section?.mark??images.mark,markPlate:section?.markPlate!==void 0?section.markPlate:images.markPlate}}
1
+ import{existsSync}from"node:fs";import{readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import process from"node:process";import{parseSVG,rasterize}from"@stacksjs/ts-svg";import{createImageData,crop,decode,drawImage,parseColor}from"ts-images";export function projectFile(path,root=process.cwd()){return isAbsolute(path)?path:resolve(root,path)}export function requireProjectFile(path,root,describe){const resolved=projectFile(path,root);if(!existsSync(resolved))throw new Error(`[image] ${describe} not found: ${path}
2
+ Looked in ${resolved}. Capture it before generating - \`buddy generate:images\` frames existing captures, it does not take them.`);return resolved}export function color(value){return value===undefined?undefined:parseColor(value)}export function background(value,root=process.cwd()){if(!value)return;return{color:color(value.color),gradient:value.gradient&&{angle:value.gradient.angle,stops:value.gradient.stops.map((stop)=>({offset:stop.offset,color:parseColor(stop.color)}))},glows:value.glows?.map((glow)=>({...glow,color:parseColor(glow.color)})),image:value.image?projectFile(value.image,root):undefined}}export function device(value){if(!value)return;return{radius:value.radius,scale:value.scale,borderColor:color(value.borderColor),shadow:value.shadow===false?undefined:{...value.shadow??{},color:color(value.shadow?.color)}}}function svgMark(source,colorScheme){const root=parseSVG(source,{colorScheme});const draw=(height)=>{const frame=rasterize(root,{height:Math.max(1,Math.round(height))});const image=createImageData(frame.width,frame.height);image.data.set(frame.data);return trimTransparentEdges(image)};const SAMPLE=512;const sample=draw(SAMPLE);const fill=sample.height>0?sample.height/SAMPLE:1;return{render:(height)=>draw(height/fill),aspect:sample.height>0?sample.width/sample.height:1}}export async function markPainter(path,root=process.cwd(),options={}){if(!path)return;const file=projectFile(path,root);if(/\.svg$/i.test(file)){const{render,aspect}=svgMark(await readFile(file,"utf8"),options.colorScheme??"light");return{aspect,draw:(canvas,box)=>{const mark=render(box.size);drawImage(canvas,mark,{x:box.x,y:box.y,width:box.width??box.size*aspect,height:box.size,fit:"contain"})}}}const mark=trimTransparentEdges(await decode(new Uint8Array(await readFile(file))));const aspect=mark.height>0?mark.width/mark.height:1;return{aspect,draw:(canvas,box)=>{drawImage(canvas,mark,{x:box.x,y:box.y,width:box.width??box.size*aspect,height:box.size,fit:"contain"})}}}export function trimTransparentEdges(image,alphaThreshold=8){let left=image.width;let top=image.height;let right=-1;let bottom=-1;for(let y=0;y<image.height;y++){for(let x=0;x<image.width;x++){if((image.data[(y*image.width+x)*4+3]??0)>alphaThreshold){if(x<left)left=x;if(x>right)right=x;if(y<top)top=y;if(y>bottom)bottom=y}}}if(right<0||left===0&&top===0&&right===image.width-1&&bottom===image.height-1)return image;return crop(image,{left,top,width:right-left+1,height:bottom-top+1})}export function themed(images,section){return{...section??{},background:section?.background??images.background,color:section?.color??images.color,mutedColor:section?.mutedColor??images.mutedColor,accent:section?.accent??images.accent,device:section?.device??images.device,brand:section?.brand??images.brand,mark:section?.mark??images.mark,markPlate:section?.markPlate!==undefined?section.markPlate:images.markPlate}}
package/dist/upload.js CHANGED
@@ -1 +1 @@
1
- import{decode,encode,getMetadata}from"ts-images";export async function sanitizeImageUpload(bytes,options={}){const maxBytes=options.maxBytes??12582912,maxPixels=options.maxPixels??40000000;if(!Number.isSafeInteger(maxBytes)||maxBytes<=0||!Number.isSafeInteger(maxPixels)||maxPixels<=0)throw RangeError("Image limits must be positive whole numbers");if(!bytes.byteLength||bytes.byteLength>maxBytes)throw RangeError("Image exceeds the upload byte limit");const metadata=await getMetadata(bytes),sourceFormat=String(metadata.format).toLowerCase(),format=sourceFormat==="jpg"?"jpeg":sourceFormat;if(format!=="jpeg"&&format!=="png"&&format!=="webp")throw TypeError("Send a JPEG, PNG or WebP photo");if(!Number.isSafeInteger(metadata.width)||!Number.isSafeInteger(metadata.height)||metadata.width<=0||metadata.height<=0||metadata.width*metadata.height>maxPixels)throw RangeError("Image exceeds the decoded pixel limit");const source=await decode(bytes,{applyOrientation:!0}),pixels={width:source.width,height:source.height,data:source.data,colorSpace:source.colorSpace,hasAlpha:source.hasAlpha,bitDepth:source.bitDepth},output=await encode(pixels,format,{quality:90});if(output.byteLength>maxBytes)throw RangeError("Normalized image exceeds the upload byte limit");return{bytes:output,width:source.width,height:source.height,format}}
1
+ import{decode,encode,getMetadata}from"ts-images";export async function sanitizeImageUpload(bytes,options={}){const maxBytes=options.maxBytes??12*1024*1024;const maxPixels=options.maxPixels??40000000;if(!Number.isSafeInteger(maxBytes)||maxBytes<=0||!Number.isSafeInteger(maxPixels)||maxPixels<=0)throw new RangeError("Image limits must be positive whole numbers");if(!bytes.byteLength||bytes.byteLength>maxBytes)throw new RangeError("Image exceeds the upload byte limit");const metadata=await getMetadata(bytes);const sourceFormat=String(metadata.format).toLowerCase();const format=sourceFormat==="jpg"?"jpeg":sourceFormat;if(format!=="jpeg"&&format!=="png"&&format!=="webp")throw new TypeError("Send a JPEG, PNG or WebP photo");if(!Number.isSafeInteger(metadata.width)||!Number.isSafeInteger(metadata.height)||metadata.width<=0||metadata.height<=0||metadata.width*metadata.height>maxPixels)throw new RangeError("Image exceeds the decoded pixel limit");const source=await decode(bytes,{applyOrientation:true});const pixels={width:source.width,height:source.height,data:source.data,colorSpace:source.colorSpace,hasAlpha:source.hasAlpha,bitDepth:source.bitDepth};const output=await encode(pixels,format,{quality:90});if(output.byteLength>maxBytes)throw new RangeError("Normalized image exceeds the upload byte limit");return{bytes:output,width:source.width,height:source.height,format}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/image",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.514",
5
+ "version": "0.75.518",
6
6
  "description": "Native responsive image delivery for Stacks.",
7
7
  "author": "Chris Breuer",
8
8
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@stacksjs/ts-svg": "^0.1.5",
35
- "@stacksjs/types": "0.75.514",
35
+ "@stacksjs/types": "0.75.518",
36
36
  "ts-images": "^0.2.33"
37
37
  },
38
38
  "devDependencies": {