@stackonward/file
v0.0.2
Published
Framework-agnostic browser file validation — Result-typed, no UI or i18n
Maintainers
Readme
@stackonward/file
Framework-independent browser file validation and direct-to-storage upload helpers. Validation returns structured results so applications can own UI copy and localization.
Install
pnpm add @stackonward/fileValidate an image
import { validateImageFile } from "@stackonward/file";
const result = await validateImageFile(file, {
maxFileSizeMb: 5,
acceptedTypes: ["image/jpeg", "image/png", "image/webp"],
maxDimension: 4096,
minRatio: "1:1",
maxRatio: "16:9",
});
if (!result.valid) {
showValidationMessage(result.error.code);
}validateImageFile checks size, MIME type, decodability, dimensions, total
pixels, and aspect ratio in a deterministic order. validateVideoFile provides
the matching size, MIME, duration, and dimension flow for videos.
Upload to a presigned URL
import { normalizeUploadHeaders, uploadToPresignedUrl } from "@stackonward/file";
const headers = normalizeUploadHeaders(presign.headers, file.type);
await uploadToPresignedUrl(presign.uploadUrl, file, {
headers,
signal: controller.signal,
onProgress: (progress) => updateProgress(progress),
});The upload helper performs one browser XMLHttpRequest PUT so progress is
observable. It removes browser-managed Host and Content-Length headers and
ensures a content type is present. Presign and confirm operations remain owned
by the consuming backend contract.
Public API
| Area | Exports |
| ------------------------ | ------------------------------------------------------------------------------------- |
| Validation orchestration | validateImageFile, validateVideoFile |
| Pure validation | checkFileSize, checkFileType, checkImageConstraints, checkVideoConstraints |
| Browser metadata | getImageDimensions, getVideoMetadata |
| Upload | uploadToPresignedUrl, normalizeUploadHeaders, resolveStorageCategory |
| Contracts | FileValidationResult, FileValidationError, image/video configs and metadata types |
resolveStorageCategory maps MIME prefixes to image, video, audio, or
attachment. It classifies storage intent; it does not authorize an upload.
Failure and cancellation
- Decode failures return
IMAGE_DECODE_FAILEDorVIDEO_DECODE_FAILED. - Constraint failures return a typed error code with the values needed for consumer-owned messages.
- Upload non-2xx responses and transport failures reject the promise.
- An aborted signal rejects with an upload-cancelled error and aborts an in-flight XHR.
- No helper displays a toast, translates copy, or treats a failed upload as success.
Compatibility
- Modern browser APIs: File, Blob, FileReader, Image, HTMLVideoElement, URL, and XMLHttpRequest
- ESM with TypeScript declarations
- Pure constraint functions can run outside the browser
License
MIT
