Skip to content

prism ​

@c9up/prism: image processing for ream on a Rust engine: inspect, resize, crop, rotate, composite, watermark, filter and convert images, serve responsive variants, draw QR codes and Swiss QR-bills. Guide: Images.

Installation ​

bash
pnpm add @c9up/prism
ream configure @c9up/prism

ream configure @c9up/prism adds the provider, the IMAGE_MAX_PIXELS variable, and writes config/images.ts. @c9up/ream is an optional peer.

The native engine comes as one small package per platform, @c9up/prism-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/prism lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the engine would be left out.

There is no JavaScript fallback. Without the engine, the first image operation throws E_PRISM_NATIVE_REQUIRED, and its message names the package to install, for example @c9up/prism-linux-x64-gnu.

Entry points ​

ImportContents
@c9up/prismPrism and its Pipeline, defineConfig, the image endpoint, qrcode, the types and the error classes.
@c9up/prism/providerPrismProvider (default export).
@c9up/prism/services/mainThe application's Prism (default export), usable once the provider booted.
@c9up/prism/configureconfigure(codemods), run by ream configure @c9up/prism.
@c9up/prism/testingfakeImages().
@c9up/prism/swissqrbill/pdfSwissQRBill and SwissQRCode drawn into a PDFKit document.
@c9up/prism/swissqrbill/svgSwissQRBill and SwissQRCode as SVG.
@c9up/prism/swissqrbill/utilsIBAN, reference and amount helpers, unit conversions.
@c9up/prism/swissqrbill/errorsValidationError and its codes.
@c9up/prism/swissqrbill/typesThe QR-bill data and option types.

Exports ​

@c9up/prism ​

ExportKindDescription
PrismclassThe image engine an application holds.
PipelineclassOperations queued over one image, run once on toBuffer.
defineConfigfunctionTypes config/images.ts.
registerImageRoutefunctionMounts the image transformation endpoint.
DEFAULT_WIDTHSconstThe widths the endpoint allows by default.
ImageHttpContext, ImageRouterinterfaceThe HTTP context and router the endpoint needs.
qrcodeconsttoString, toBuffer, toDataURL: QR codes as SVG or images.
QRCodeOptions and the other QRCode* typestypeThe QR code options.
isNativeAvailablefunctionWhether the Rust engine is loaded.
errorsnamespaceThe package's errors, one class per code, see Errors. Each is a flare Exception with a string code.
PRISM_CODESconstThe engine's codes, without the E_PRISM_ prefix.
PrismCodetypeOne of PRISM_CODES.
PrismConfig, Limits, ImageServingConfigtypeThe configuration.
ReadableFormat, ImageFormattypeThe formats the engine reads and writes.
MetadatatypeWhat inspect returns.
OperationtypeOne queued operation, a union on kind.
OutputOptionstypeOptions of toBuffer.
ResizeOptions, CropOptions, CompositeOptions, WatermarkTextOptions, ThumbnailOptions, SharpenOptions, ConvertColorSpaceOptionstypeOperation options.
Fit, Colour, ColorSpacetypeOption values.

Prism ​

MemberSignatureDescription
constructornew Prism(config?: PrismConfig)
configconfig(): PrismConfigThe configuration it was built with.
inspectinspect(bytes: Buffer, limits?: Limits): MetadataIdentifies the image from its content and describes it without decoding the pixels.
editedit(bytes: Buffer): PipelineStarts a pipeline over an encoded image.

Pipeline ​

Every operation queues and returns this; nothing touches the engine until toBuffer or toFormat, which decode, run every operation and encode once.

MemberSignatureDescription
resizeresize(options: ResizeOptions): this{ width?, height?, fit? }, fit defaulting to 'cover'.
cropcrop(options: CropOptions): this{ x, y, width, height }.
rotaterotate(degrees: number): thisA multiple of 90; negative and over-360 values are normalised.
flipflip(axis: 'horizontal' | 'vertical'): this
compositecomposite(options: CompositeOptions): thisOverlays an encoded image at x, y (signed, default 0) with opacity 0–1 (default 1); the overlay goes through the same guards as the input.
watermarkTextwatermarkText(options: WatermarkTextOptions): thisDraws text with font (the font's bytes; none is bundled), size (default 32), color (default opaque white), x, y.
thumbnailthumbnail(options: ThumbnailOptions): thisFast box downscale, { width?, height?, exact? }; softer than resize.
blurblur(sigma: number): thisGaussian blur.
fastBlurfastBlur(sigma: number): thisBox-approximated blur, far cheaper.
sharpensharpen(options: SharpenOptions): thisUnsharp mask: sigma above 0 up to 100, threshold 0–65535 (default 0).
brightenbrighten(value: number): this-255 to 255.
contrastcontrast(value: number): this-255 to 255.
hueRotatehueRotate(value: number): thisDegrees; wraps.
invertinvert(): this
grayscalegrayscale(): this
filter3x3filter3x3(kernel: readonly number[]): thisA 3×3 convolution, row-major, exactly nine values.
convertColorSpaceconvertColorSpace(options: ConvertColorSpaceOptions): thisConverts the samples to a colour space; from overrides what the file claims.
operationsoperations(): readonly Operation[]The operations queued so far.
toBuffertoBuffer(output: OutputOptions): Promise<Buffer>Runs everything and encodes, in one of the instance's concurrency slots; waits for a slot when they are all taken.
toFormattoFormat(format: ImageFormat, quality?: number): Promise<Buffer>toBuffer naming only the format.
OutputOptions fieldTypeDefaultDescription
formatImageFormatrequired
qualitynumberconfig quality, else 82An integer 1–100, for formats with a quality setting.
backgroundColouropaque whiteWhat transparency is blended against for a format without alpha.
depth8 | 168Bits per channel; only PNG and TIFF carry 16, others narrow it back. A 16-bit source is narrowed to 8 bits right after decoding unless depth is 16.
effortnumber4AVIF CPU effort, 0 (fastest) to 9.
TypeValues
ReadableFormat'jpeg' | 'png' | 'webp' | 'gif' | 'bmp' | 'ico' | 'tiff' | 'tga' | 'qoi' | 'pnm' | 'dds' | 'farbfeld' | 'hdr' | 'openexr' | 'avif'
ImageFormatReadableFormat without 'dds' (readable, not writable).
Fit'fill' (exact size, distorts), 'contain' (fits inside), 'cover' (fills and crops, centred), 'inside' (as contain, never enlarges).
Colour{ r: number; g: number; b: number; a?: number }, 0–255.
ColorSpace'srgb' | 'linear-srgb' | 'display-p3' | 'dci-p3' | 'rec709'
Metadata fieldTypeDescription
width, heightnumberFrom the header.
orientedWidth, orientedHeightnumberAfter the EXIF orientation is applied.
orientationnumberEXIF orientation, 1–8; 1 when there is none.
formatImageFormat | stringEstablished from the content.
hasAlphaboolean
colorSpacestringThe colour space the file declares (srgb when it declares none).

Image endpoint ​

FunctionSignatureDescription
registerImageRouteregisterImageRoute(router: ImageRouter, images: Prism, config: ImageServingConfig): unknownMounts GET <path>?src=&w=&f=&q=; returns what the router returns, so middleware can be added. Behind authentication, set serve.cacheControl to 'private': the default public lets a shared cache store the image and serve it to anyone. Every axis is allow-listed and a request outside the lists is refused before any decode; answers carry no EXIF and a sandboxing CSP. The provider calls it when serve is configured.

DEFAULT_WIDTHS is 16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 960, 1080, 1280, 1668, 1920, 2048, 2560, 3200, 3840, 4480, 5120, 6016.

qrcode ​

MemberSignatureDescription
toStringtoString(text: string, options?: QRCodeToStringOptions): Promise<string>The QR code as an SVG document.
toBuffertoBuffer(text: string, options?: QRCodeToBufferOptions): Promise<Buffer>PNG by default, or WebP, AVIF, SVG (type); rendererOpts.quality 1–100 for WebP and AVIF (default 100).
toDataURLtoDataURL(text: string, options?: QRCodeToDataURLOptions): Promise<string>A data: URL for an <img src>.
QRCodeOptions fieldTypeDefaultDescription
errorCorrectionLevelQRCodeErrorCorrectionLevel'M', 'H' with a logoL, M, Q, H or low, medium, quartile, high.
versionnumbersmallest that fits1–40.
marginnumber4Quiet zone, in modules.
scalenumber4Pixels per module.
widthnumberSide in pixels; wins over scale once it holds the symbol.
color{ dark?: string; light?: string }black on whiteHex, #rgb to #rrggbbaa.
dotsOptionsQRCodeFigureOptions<QRCodeDotType>squaretype (square, dots, rounded, extra-rounded, classy, classy-rounded), color, gradient.
cornersSquareOptionsQRCodeFigureOptions<QRCodeCornerSquareType>as the modulesThe finders' frames.
cornersDotOptionsQRCodeFigureOptions<QRCodeCornerDotType>as the modulesThe finders' centres; dots is refused.
backgroundOptions{ round?: number; color?: string; gradient?: QRCodeGradient }round 0 (square) to 1 (circle).
imageUint8ArrayA logo: PNG, JPEG or WebP bytes.
imageOptions{ imageSize?: number; margin?: number; hideBackgroundDots?: boolean }0.4, 0, trueimageSize at most 0.5.

QRCodeGradient is { type?: 'linear' | 'radial'; rotation?: number; colorStops: Array<{ offset: number; color: string }> } with 1 to 16 stops. Anything drawn must keep a 3:1 contrast with the background. Invalid options are refused with E_PRISM_INVALID_QR_OPTION.

@c9up/prism/provider ​

ExportKindDescription
PrismProviderprovider (default)register() binds Prism from the images config (loading no binary); boot() publishes the service and mounts the image endpoint when serve is set and a router binding exists; shutdown() clears the service.

@c9up/prism/services/main ​

ExportKindDescription
defaultconstThe application's Prism. Any property access before the provider booted throws.

@c9up/prism/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: what ream configure @c9up/prism runs.

@c9up/prism/testing ​

ExportKindDescription
fakeImagesfunctionfakeImages(config?: PrismConfig): { images: Prism; restore: () => void }: publishes a real Prism on services/main for a test; restore() clears it.

@c9up/prism/swissqrbill/pdf ​

Draws into a PDFKit document the caller owns; PDFKit is not a dependency. The constructors clean and validate the data and encode the QR code, throwing ValidationError or E_PRISM_QR_TOO_LONG.

ExportSignatureDescription
SwissQRBillnew SwissQRBill(data: Data, options?: PDFOptions)The payment slip, 210 × 105 mm.
SwissQRBill.attachToattachTo(doc: PDFKitDocument, x?: number, y?: number): voidDraws the slip, at the page bottom by default; adds a slip-sized page when the current one has no room.
SwissQRBill.isSpaceSufficientstatic isSpaceSufficient(doc: PDFKitDocument, x?: number, y?: number): booleanWhether the slip fits at that position.
SwissQRBill.width, SwissQRBill.heightstatic readonly numberThe slip's size in points.
SwissQRCodenew SwissQRCode(data: Data, size?: number)The QR code alone, size in mm (default 46); attachTo(doc, x?, y?).
PDFKitDocument, PDFKitTextOptionsinterfaceThe part of a PDFKit document the bill draws with.
Data, PDFOptionstypeRe-exported from swissqrbill/types.

@c9up/prism/swissqrbill/svg ​

ExportSignatureDescription
SwissQRBillnew SwissQRBill(data: Data, options?: SVGOptions)The slip as SVG; toString(): string.
SwissQRCodenew SwissQRCode(data: Data, size?: number)The QR code alone as SVG; toString(): string.
Data, SVGOptionstypeRe-exported from swissqrbill/types.

@c9up/prism/swissqrbill/utils ​

FunctionSignature
isQRIBAN, isIBANValid(iban: string): boolean
formatIBAN(iban: string): string
isQRReference, isQRReferenceValid, isSCORReference, isSCORReferenceValid(reference: string): boolean
calculateQRReferenceChecksum, calculateSCORReferenceChecksum(reference: string): string
formatQRReference, formatSCORReference, formatReference(reference: string): string
getReferenceType(reference: string | undefined): 'NON' | 'QRR' | 'SCOR'
formatAmount(amount: number): string
mm2pt, pt2mm, mm2px, px2mm(value: number): number

@c9up/prism/swissqrbill/errors ​

ExportKindDescription
ValidationErrorerrorA QR-bill the Swiss rules refuse; a flare Exception. Its code is a key of ValidationErrors (such as ACCOUNT_IS_QR_IBAN_BUT_REFERENCE_IS_MISSING), not an E_ code.
ValidationErrorsconstEvery validation code and its message.
ValidationErrorCodetypekeyof typeof ValidationErrors.

@c9up/prism/swissqrbill/types ​

TypeShape
Data{ creditor: Creditor; currency: 'CHF' | 'EUR'; amount?: number; reference?: string; message?: string; additionalInformation?: string; av1?: string; av2?: string; debtor?: Debtor }
Debtor{ name: string; address: string; buildingNumber?: number | string; zip: number | string; city: string; country: string }
CreditorDebtor & { account: string }
SVGOptions{ fontName?: FontName; language?: Language; outlines?: boolean; renderAdditionalInformation?: boolean; scissors?: boolean }
PDFOptionsSVGOptions fields plus separate?: boolean
Language'DE' | 'EN' | 'FR' | 'IT' | 'RM' (default DE)
FontName'Arial' | 'Frutiger' | 'Helvetica' | 'Liberation Sans' (default Helvetica in a PDF, Arial in an SVG)
Currency'CHF' | 'EUR'

Configuration ​

config/images.ts, written by ream configure @c9up/prism:

OptionTypeDefaultDescription
limits.maxPixelsnumber50000000Largest decoded pixel count, checked before decoding against the header and against every frame of a GIF or an extended WebP. The generated config reads IMAGE_MAX_PIXELS.
limits.maxBytesnumber67108864 (64 MiB)Largest input accepted.
limits.maxMemorynumber536870912 (512 MiB)Largest working set of one pipeline, in bytes. Each step is refused with E_PRISM_MEMORY_LIMIT before it allocates when what it holds plus what it adds is over this. See Memory.
limits.allowedFormatsreadonly ReadableFormat[]['jpeg', 'png', 'webp']Formats this application decodes; an unknown name raises.
qualitynumber82Default output quality.
concurrencynumber2Pipelines one Prism runs at once; the others wait. A value that is not a positive integer reads as the default.
autoOrientbooleantrueApply the EXIF orientation on decode.
serveImageServingConfignoneMounts the image endpoint; absent, no route is added.
serve.pathstring'/__image'Route path.
serve.rootsreadonly string[]requiredAbsolute directories a src may resolve inside; an empty list is refused at boot.
serve.widthsreadonly number[]DEFAULT_WIDTHSWidths that may be requested.
serve.formatsreadonly ImageFormat[]AVIF, WebP, JPEG, PNGFormats that may be requested.
serve.qualitiesreadonly number[][serve.quality]Qualities that may be requested.
serve.qualitynumber82Quality when the request names none.
serve.cacheDirstringKeeps rendered variants on disk.
serve.memoryCacheBytesnumber32 MiBWithout cacheDir, the in-memory cache size; 0 turns it off.
serve.maxCacheBytesnumber1 GiBWith cacheDir, its size bound. Past it, the variants of sources that no longer exist go first, then the oldest written, down to nine tenths of it; 0 turns it off. A source a request finds missing loses its variants at once.
serve.maxAgenumberone yearmax-age, in seconds.
serve.cacheControl'public' | 'private' | false'public'Who may store an answer. 'private' for a route behind authentication; false sends no Cache-Control, for a middleware that sets its own. Refusals always say no-store.
serve.concurrencynumber2Renders run at once; keep it below UV_THREADPOOL_SIZE.
serve.queueLimitnumber64Renders allowed to wait; past it, 503 with Retry-After.
serve.effortnumber1AVIF encoding effort for the endpoint.

Memory ​

maxPixels bounds pixels, maxMemory bounds bytes. Each step adds what stays alive (the image it reads) to what it allocates, and is refused before allocating when the sum is over maxMemory:

StepCounted
DecodeDecoded buffer: pixels × bytes per pixel from the header (4 for 8-bit RGBA, 8 for 16-bit RGBA). Plus the frame buffer of a GIF (4 bytes per pixel of the first frame), the planes of a WebP (4 per pixel), 8 per pixel for an AVIF. Twice the decoded buffer when an EXIF orientation is applied.
resizeSource + float intermediate of source width × target height × 16 bytes + output (+ the crop of cover).
thumbnail, cropSource + output.
blur, fastBlur, sharpenSource + two copies.
Other filters, rotate, flipSource + one copy.
composite, watermarkTextBoth layers + an 8-bit RGBA copy of each.
EncodeImage + converted copy + output: 2 × 3 bytes per pixel for JPEG, 2 × 4 for PNG at 8 bits, 3 × 4 for WebP and AVIF.

Worked example: a 7071 × 7071 (50 MP) JPEG decodes to 150 MB of 8-bit RGB. Resized to 6016 wide, it holds 150 MB + 7071 × 6016 × 16 = 681 MB of floats + 109 MB of output: 940 MB, over the 512 MiB default, so it is refused with E_PRISM_MEMORY_LIMIT before the resize allocates anything. Resized to 1920 wide, it needs 150 + 217 + 11 MB and runs. A 50 MP 16-bit RGBA PNG decodes to 400 MB, and narrowing it to 8 bits adds 200 MB: it needs a maxMemory above 600 MB plus its steps. The most one Prism holds is concurrency × maxMemory: 1 GiB by default.

Container bindings ​

TokenResolves to
PrismThe Prism singleton.
'prism.images'The same instance.
'images'The same instance.

The string tokens are declared on ContainerBindings.

Errors ​

The E_PRISM_IMAGE_* codes are not thrown: the image endpoint answers them as { error: { code, message } } with the status shown. Every other code is a class of the errors namespace (import { errors } from '@c9up/prism'): a flare Exception with code and status. The engine refusals that mean the input is not an image prism takes (E_PRISM_EMPTY_INPUT, E_PRISM_INPUT_TOO_LARGE, E_PRISM_TOO_MANY_PIXELS, E_PRISM_MEMORY_LIMIT, E_PRISM_ZERO_DIMENSION, E_PRISM_UNKNOWN_FORMAT, E_PRISM_UNSUPPORTED_FORMAT, E_PRISM_FORMAT_NOT_ALLOWED, E_PRISM_UNREADABLE, E_PRISM_DECODE_FAILED) have status 422; the others 500.

CodeRaised when
E_PRISM_IMAGE_NO_SOURCEThe endpoint was called without src (400).
E_PRISM_IMAGE_WIDTH_NOT_ALLOWEDw is not a configured width (400).
E_PRISM_IMAGE_FORMAT_NOT_ALLOWEDf is not a configured format (400).
E_PRISM_IMAGE_QUALITY_NOT_ALLOWEDq is not a configured quality (400).
E_PRISM_IMAGE_NOT_FOUNDNo image at src (404).
E_PRISM_IMAGE_UNPROCESSABLEThe source is not an image the endpoint can serve (422).
E_PRISM_IMAGE_BUSYToo many renders are waiting (503).
E_PRISM_EMPTY_INPUTThe input is empty.
E_PRISM_INPUT_TOO_LARGEThe input is over maxBytes.
E_PRISM_TOO_MANY_PIXELSThe image (its header, or any GIF frame), or one an operation would build, is over maxPixels.
E_PRISM_MEMORY_LIMITA step would hold more than maxMemory bytes, see Memory.
E_PRISM_ZERO_DIMENSIONThe image has a zero width or height.
E_PRISM_UNKNOWN_FORMATThe bytes are not an image format prism recognises.
E_PRISM_UNSUPPORTED_FORMATThe format is recognised but not supported.
E_PRISM_FORMAT_NOT_ALLOWEDThe format is not in allowedFormats.
E_PRISM_UNREADABLEThe image cannot be read: a WebP bitstream whose size is not its frame's, an AVIF item located in more bytes than the file holds.
E_PRISM_DECODE_FAILEDDecoding failed.
E_PRISM_ENCODE_FAILEDEncoding the output failed.
E_PRISM_INVALID_GEOMETRYA crop outside the image, a target size of zero.
E_PRISM_INVALID_FONTA font cannot be used.
E_PRISM_COLOUR_SPACEA colour space cannot be named, or a conversion is refused.
E_PRISM_INVALID_OPERATIONAn operation lacks a field or has one out of range.
E_PRISM_QR_TOO_LONGMore text than a QR code can hold at the chosen level and version.
E_PRISM_INVALID_QR_OPTIONA QR code option is out of range, or a colour is not strict hex.
E_PRISM_INTERNAL_PANICThe engine panicked.
E_PRISM_ENGINEThe engine failed without a known code.
E_PRISM_NATIVE_REQUIREDThe Rust image engine is not loaded.
E_PRISM_NOT_BOOTEDThe services/main engine was used before PrismProvider booted or setPrism() was called.
E_PRISM_INVALID_CONFIGconfig/images.ts does not export a defineConfig({ ... }) config.
E_PRISM_INVALID_SERVE_CONFIGimages.serve declares no roots, one of its counts (concurrency, queueLimit, effort, memoryCacheBytes, maxCacheBytes…) is out of range, or cacheControl is not 'public', 'private' or false.
E_PRISM_INVALID_BINDINGThe container resolved something other than a Prism for the Prism token, or other than a router for router.

Migration ​

  • PrismError is gone: test error.code, or error instanceof errors.E_PRISM_* with import { errors } from '@c9up/prism'.
  • PrismNativeRequiredError becomes errors.E_PRISM_NATIVE_REQUIRED.
  • ValidationError (@c9up/prism/swissqrbill/errors) no longer extends PrismError; its code is unchanged.
  • An engine refusal of the input now has status 422 (see Errors).
  • A pipeline now holds at most limits.maxMemory bytes (512 MiB by default): a large image resized close to its own size can be refused with E_PRISM_MEMORY_LIMIT where it used to run. Raise maxMemory if your host has room for it; Memory gives the arithmetic.
  • inspect() now refuses with E_PRISM_MEMORY_LIMIT an image whose decoded buffer alone is over maxMemory, and with E_PRISM_TOO_MANY_PIXELS a GIF one of whose frames is over maxPixels, even when its screen is not.
  • A WebP whose bitstream does not have its frame's size, and an AVIF one of whose items is located in more bytes than the file, are refused with E_PRISM_UNREADABLE by inspect() too, not only when decoded.
  • A PNG whose metadata chunks (text, EXIF) hold more than about three times the file plus 4 MiB is refused with E_PRISM_UNREADABLE. An ICC profile over that is dropped, as before: no output carries one.
  • A 16-bit source is written at 8 bits per channel unless toBuffer asks for depth: 16. Pass depth: 16 to keep 16 bits in a PNG or a TIFF.
  • edit().toBuffer() now runs at most concurrency pipelines at once per Prism (2 by default); the others wait. Set concurrency in config/images.ts for more.
  • With serve.cacheDir, the cache is now bounded by serve.maxCacheBytes (1 GiB by default): variants of deleted sources and then the oldest ones are deleted. Set maxCacheBytes: 0 to keep everything.
  • The image endpoint answers a refused render from memory for the same source version and width, instead of decoding the file again.

See also ​