@molecule/api-image-molecule
Provider bond · image · API (Node) · v1.1.0 · Apache-2.0
molecule.dev hosted image transformation — resize/crop/rotate/optimize/convert billed to your molecule project
npm install @molecule/api-image-moleculenpm · Source on GitHub · Implements @molecule/api-image
How it works
@molecule/api-image-molecule is a provider bond on the API (Node) side: it implements the image core interface (@molecule/api-image) with a concrete vendor or library behind it.
Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.
Works with: @molecule/api-image, @molecule/api-secrets
Secrets: MOLECULE_API_KEY
Reference
molecule.dev hosted image transformation — resize/crop/rotate/optimize/convert billed to your molecule project
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Type
provider
Installation
npm install @molecule/api-image-molecule @molecule/api-image @molecule/api-secrets
API
Interfaces
TransformResult
The transform response the hosted service returns.
interface TransformResult {
/** The transformed image, base64-encoded — no `data:` URL prefix. */
data: string
/** MIME type of the returned image. */
mimeType: string
/** Width in pixels. */
width: number
/** Height in pixels. */
height: number
/** Detected format (e.g. `'jpeg'`). */
format: string
/** Size in bytes. */
bytes: number
}
MoleculeImageConfig
Options for createProvider. Every field falls back to an env var,
so the zero-argument provider export works from .env alone.
interface MoleculeImageConfig {
/**
* The molecule project API key (`mk_…`), or the sandbox token molecule.dev
* writes for in-IDE apps (`mbk_…`). Defaults to `MOLECULE_API_KEY`.
*/
apiKey?: string
/**
* The hosted services base URL, without a trailing slash. Defaults to
* `MOLECULE_SERVICES_URL`, then `https://api.molecule.dev/api/v1/services`.
*/
servicesUrl?: string
/** Per-request timeout in milliseconds. Default 30000 — large images take a moment. */
timeoutMs?: number
}
ProcessEnv
Environment variables this provider reads.
interface ProcessEnv {
MOLECULE_API_KEY?: string
MOLECULE_SERVICES_URL?: string
}
Classes
MoleculeServiceError
Error thrown for a refused or failed hosted-service call.
class MoleculeServiceError extends Error {
/** HTTP status from molecule.dev. */
readonly status: number
/** Stable error key from molecule.dev. */
readonly errorKey: string | undefined
/**
* Create the error.
*
* @param message - Human-readable message.
* @param status - HTTP status.
* @param errorKey - Stable error key, when the service sent one.
* @param cause - The underlying error, if any.
*/
constructor(message: string, status: number, errorKey?: string, cause?: unknown) {
super(message, cause === undefined ? undefined : { cause })
this.name = 'MoleculeServiceError'
this.status = status
this.errorKey = errorKey
}
}
MoleculeImageProvider
Image transformation provider backed by molecule.dev's hosted service.
getMetadata is NOT implemented — the hosted service transforms images and
returns the final image's metadata with every response; read it there
(transform() on the raw class) instead of calling getMetadata.
class MoleculeImageProvider implements ImageProvider {
readonly name = 'molecule'
private readonly apiKey: string
private readonly servicesUrl: string
private readonly timeoutMs: number
/**
* Create the provider.
*
* @param config - Options; each falls back to its env var.
*/
constructor(config: MoleculeImageConfig = {}) {
this.apiKey = config.apiKey ?? process.env.MOLECULE_API_KEY ?? ''
this.servicesUrl = resolveServicesUrl(
config.servicesUrl ?? process.env.MOLECULE_SERVICES_URL ?? DEFAULT_SERVICES_URL,
)
this.timeoutMs = config.timeoutMs ?? 30_000
}
/**
* Runs an op pipeline against the hosted service and returns the decoded
* image. Prefer this over the per-method wrappers when chaining several
* operations — one round trip instead of one per step.
*
* @param input - The image bytes.
* @param ops - The pipeline steps, exactly the service's op shapes.
* @returns The transformed image plus its metadata.
*/
async transform(input: Buffer, ops: Array<Record<string, unknown>>): Promise<TransformResult> {
if (input.length === 0) {
throw new MoleculeServiceError(
'The image is empty.',
400,
'hostedServices.error.invalidInput',
)
}
if (input.length > IMAGE_SERVICE_LIMITS.maxImageBytes) {
throw new MoleculeServiceError(
`The image is ${input.length} bytes; the limit is ${IMAGE_SERVICE_LIMITS.maxImageBytes}.`,
413,
'hostedServices.error.inputTooLarge',
)
}
if (!Array.isArray(ops) || ops.length === 0) {
throw new MoleculeServiceError(
'"ops" must be a non-empty array of pipeline steps.',
400,
'hostedServices.error.invalidInput',
)
}
if (ops.length > IMAGE_SERVICE_LIMITS.maxOps) {
throw new MoleculeServiceError(
`${ops.length} ops is over the limit of ${IMAGE_SERVICE_LIMITS.maxOps}.`,
413,
'hostedServices.error.inputTooLarge',
)
}
return this.request({ image: input.toString('base64'), ops })
}
/** Runs a one-op resize pipeline through the hosted service. */
async resize(input: Buffer, options: ResizeOptions): Promise<Buffer> {
return this.transformToBuffer(input, [{ op: 'resize', ...options }])
}
/** Runs a one-op crop pipeline through the hosted service. */
async crop(input: Buffer, options: CropOptions): Promise<Buffer> {
return this.transformToBuffer(input, [{ op: 'crop', ...options }])
}
/** Runs a one-op convert pipeline through the hosted service. */
async convert(input: Buffer, format: ImageFormat, quality?: number): Promise<Buffer> {
return this.transformToBuffer(input, [
{ op: 'convert', format, ...(quality !== undefined ? { quality } : {}) },
])
}
/** Runs a one-op thumbnail pipeline through the hosted service. */
async thumbnail(input: Buffer, size: number): Promise<Buffer> {
return this.transformToBuffer(input, [{ op: 'thumbnail', size }])
}
/** Runs a one-op optimize pipeline through the hosted service. */
async optimize(input: Buffer, options?: OptimizeOptions): Promise<Buffer> {
return this.transformToBuffer(input, [{ op: 'optimize', ...(options ?? {}) }])
}
/** Runs a one-op rotate pipeline through the hosted service. */
async rotate(input: Buffer, options: RotateOptions): Promise<Buffer> {
return this.transformToBuffer(input, [{ op: 'rotate', ...options }])
}
/** Runs a one-op flip pipeline through the hosted service. */
async flip(input: Buffer): Promise<Buffer> {
return this.transformToBuffer(input, [{ op: 'flip' }])
}
/** Runs a one-op flop pipeline through the hosted service. */
async flop(input: Buffer): Promise<Buffer> {
return this.transformToBuffer(input, [{ op: 'flop' }])
}
/** Not hosted — the transform response already carries the result's metadata. */
getMetadata(): Promise<ImageMetadata> {
return Promise.reject(
new MoleculeServiceError(
"The hosted image service does not serve metadata-only reads — every transform() response carries the final image's width, height, format and bytes.",
400,
'hostedServices.error.invalidInput',
),
)
}
/** One pipeline call, decoded to bytes. */
private async transformToBuffer(
input: Buffer,
ops: Array<Record<string, unknown>>,
): Promise<Buffer> {
const result = await this.transform(input, ops)
return Buffer.from(result.data, 'base64')
}
/** One POST to the hosted service. */
private async request(body: Record<string, unknown>): Promise<TransformResult> {
if (!this.apiKey) {
throw new MoleculeServiceError(
'MOLECULE_API_KEY is not set. Create a project API key on molecule.dev (or with `mlcl apikey create`) and put it in the API .env.',
401,
'hostedServices.error.tokenInvalid',
)
}
const response = await fetch(`${this.servicesUrl}/image/transform`, {
method: 'POST',
headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(this.timeoutMs),
})
const text = await response.text()
let data: unknown
try {
data = text ? JSON.parse(text) : {}
} catch (error) {
throw new MoleculeServiceError(
`molecule.dev returned ${response.status} with a non-JSON body.`,
response.status,
undefined,
error,
)
}
if (!response.ok) {
const err = data as { error?: string; errorKey?: string }
const hint = HINTS[response.status]
throw new MoleculeServiceError(
`molecule.dev image/transform failed (${response.status}): ${err.error ?? 'error'}${hint ? ` ${hint}` : ''}`,
response.status,
err.errorKey,
)
}
return data as TransformResult
}
}
Functions
createProvider(config)
Create a hosted image transformation provider.
function createProvider(config?: MoleculeImageConfig): ImageProvider
config— Options; each falls back to its env var.
Returns: An ImageProvider backed by molecule.dev.
Constants
provider
The provider implementation (wire with setProvider).
const provider: ImageProvider
DEFAULT_SERVICES_URL
Default hosted services base URL.
const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'
IMAGE_SERVICE_LIMITS
Per-request limits of the hosted service (mirrored for local refusal).
const IMAGE_SERVICE_LIMITS: { readonly maxImageBytes: number; readonly maxOps: 6 }
imageMoleculeSecretDefinitions
Secret definitions required by the molecule.dev hosted image bond.
const imageMoleculeSecretDefinitions: SecretDefinition[]
Core Interface
Implements @molecule/api-image interface.
Bond Wiring
Setup function to register this provider with the core interface:
import { setProvider } from '@molecule/api-image'
import { provider } from '@molecule/api-image-molecule'
export function setupImageMolecule(): void {
setProvider(provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/api-image>=1.0.2@molecule/api-secrets^1.0.1
Environment Variables
MOLECULE_API_KEY(required) — molecule.dev project API key- Setup: Create one for your project with
mlcl apikey create --project <id> --name <name>(keys start with mk_). - Get it here: https://www.molecule.dev
- Example:
mk_...
- Setup: Create one for your project with
Runtime Dependencies
@molecule/api-image@molecule/api-secrets
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:
- Uploading an image through the UI produces the PROCESSED variant where the app uses one (thumbnail/resized/avatar) and it actually renders — check its rendered dimensions or transfer size against the original to confirm processing happened.
- Common input formats (JPEG, PNG, WebP) all round-trip to a rendered result.
- A corrupt or non-image file fails with a visible, readable error — not a server crash or a broken-image placeholder that persists.
- Any UI that shows image metadata (dimensions, size) matches the real file.
- Where optimization is wired, the served image is materially smaller than the uploaded original.