@lexion-rte/image-tools 0.0.0-stage → 0.1.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @lexion-rte/image-tools
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 700e9d2: New package `@lexion-rte/image-tools`: safe base64 images for Lexion, with no dependencies (browsers, Electron, Node 18+). `sniffImageType` (magic bytes; never SVG), `toDataURL` / `dataURLToBytes` / `dataURLToBlob` with size limits (`maxBytes`, default 5 MB), allowed types and a check that the declared type matches the bytes, chunked `bytesToBase64`, `downscaleImage` (canvas resize and re-encode, browser and Electron), `createBase64Uploader` (an `upload` function for `Image` with `allowBase64`), and `extractRtfImages` (PNG/JPEG pictures from Word's RTF, skipping `\nonshppict` duplicates and WMF/EMF). Errors are `ImageToolsError` with a stable `code`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dario Espina
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ ![Lexion Logo](../../assets/images/logo.png)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This package is part of the Lexion framework-agnostic rich text editor.
4
+
5
+ Lexion is a framework-agnostic, headless rich text editor platform built on ProseMirror, designed to provide a shared core, reusable extensions, and framework-specific adapters.
6
+
7
+ # @lexion-rte/image-tools
8
+
9
+ Safe base64 images for Lexion: turns image bytes into `data:image/…;base64,…` URLs after checking what they really are, with size limits, optional downscaling, an `upload` function for the starter kit's `Image`, and extraction of pictures from RTF (Word's clipboard). No dependencies; runs in browsers, Electron and Node 18+ (except `downscaleImage`, which needs a canvas).
10
+
11
+ Uploading images to a server and storing their URLs is still the better default: base64 makes documents about a third larger than the images themselves. Use this package when documents must carry their images.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pnpm add @lexion-rte/image-tools
17
+ ```
18
+
19
+ ## Base64 images in the editor
20
+
21
+ ```ts
22
+ import { Image, StarterKit } from "@lexion-rte/starter-kit";
23
+ import { createBase64Uploader } from "@lexion-rte/image-tools";
24
+
25
+ const upload = createBase64Uploader({
26
+ maxBytes: 5 * 1024 * 1024,
27
+ downscale: { maxWidth: 2000, maxHeight: 2000, quality: 0.85 }
28
+ });
29
+
30
+ new LexionEditor({
31
+ extensions: [StarterKit.configure({ image: { allowBase64: true, upload } })]
32
+ });
33
+ ```
34
+
35
+ Pasted, dropped and picked images become `data:` URLs. Files that are not supported images (an SVG or HTML file renamed to `.png` included), that claim a different image type than their bytes, or that are too large are rejected with an `ImageToolsError`, so the editor drops the placeholder and calls `onUploadError`. The editor still checks every URL with `isSafeImageSrc`, so this package is never the only gate.
36
+
37
+ Suggested limits when every image is stored in the document: `maxBytes` 5 MB, downscale to a 2000 px longest side, JPEG quality 0.85 for photos (screenshots stay PNG).
38
+
39
+ ## API
40
+
41
+ | Function | What it does | Runs in |
42
+ | --- | --- | --- |
43
+ | `sniffImageType(bytes)` | `image/png`, `jpeg`, `gif`, `webp`, `avif` or `bmp` from the first bytes, else `null`. Never trusts a file name or MIME type; never returns SVG. | All |
44
+ | `checkImageBytes(bytes, options?)` | The sniffed type, or throws: empty, over `maxBytes`, unknown or not in `allowedTypes`, or a declared image type that differs. | All |
45
+ | `toDataURL(input, options?)` | `Blob`, `File`, `ArrayBuffer` or `Uint8Array` to `data:image/…;base64,…` after `checkImageBytes`. A `Blob`'s `type` is the declared type; the URL always uses the sniffed type. | All |
46
+ | `dataURLToBytes(url, options?)`, `dataURLToBlob(url, options?)` | The reverse, with the same checks, e.g. to send a base64 image to `upload`. | All |
47
+ | `bytesToBase64(bytes)`, `base64ToBytes(text)`, `blobToBytes(blob)` | Chunked encoding (no call-stack overflow on large images; `Buffer` in Node), strict decoding, and a `Blob`'s bytes. | All |
48
+ | `downscaleImage(blob, options?)` | Fits the image in `maxWidth` × `maxHeight` and re-encodes it with `createImageBitmap` and a canvas: `type` (default: JPEG and WebP stay, everything else becomes PNG), `quality` (`0.85`), `reencode` (re-encode even when it fits, which strips metadata such as EXIF GPS). | Browser, Electron |
49
+ | `createBase64Uploader(options?)` | `(file) => Promise<string>` for `Image` `upload`: `maxBytes`, `allowedTypes`, `downscale`. With `downscale`, the original's type is checked before decoding and the limit applies to the result. | All (downscale: browser) |
50
+ | `extractRtfImages(rtf, options?)` | PNG and JPEG `\pict` pictures (`\pngblip`, `\jpegblip`, hex or `\bin`) in document order, with their display size in px; skips `\nonshppict` duplicates, WMF/EMF, pictures whose bytes do not match, and pictures over `maxBytes`. Never throws. | All |
51
+
52
+ Defaults: `maxBytes` is `DEFAULT_MAX_IMAGE_BYTES` (5 MB). Errors are `ImageToolsError` with a `code`: `empty`, `too-large`, `unsupported-type`, `type-mismatch`, `invalid-data`, `unavailable`.
@@ -0,0 +1,24 @@
1
+ /** Image types this package recognizes. SVG is never one of them (it can carry script). */
2
+ export type ImageType = "image/png" | "image/jpeg" | "image/gif" | "image/webp" | "image/avif" | "image/bmp";
3
+ export declare const imageTypes: readonly ImageType[];
4
+ /**
5
+ * The image type from the file's first bytes (magic numbers), or `null`. Never trusts a file
6
+ * name or a declared MIME type, and never returns SVG.
7
+ */
8
+ export declare const sniffImageType: (bytes: Uint8Array) => ImageType | null;
9
+ /** Base64 of `bytes`, without a call-stack overflow on large images (uses `Buffer` in Node). */
10
+ export declare const bytesToBase64: (bytes: Uint8Array) => string;
11
+ /** Bytes of a base64 string (whitespace ignored). Throws on anything that is not base64. */
12
+ export declare const base64ToBytes: (base64: string) => Uint8Array;
13
+ /**
14
+ * The bytes of a `Blob`. Uses `blob.arrayBuffer()`, or `FileReader` where that is missing
15
+ * (older WebKit, jsdom).
16
+ */
17
+ export declare const blobToBytes: (blob: Blob) => Promise<Uint8Array>;
18
+ export type ImageToolsErrorCode = "empty" | "too-large" | "unsupported-type" | "type-mismatch" | "invalid-data" | "unavailable";
19
+ /** Why an image was rejected; `code` is stable, `message` is for people. */
20
+ export declare class ImageToolsError extends Error {
21
+ readonly code: ImageToolsErrorCode;
22
+ constructor(code: ImageToolsErrorCode, message: string);
23
+ }
24
+ //# sourceMappingURL=bytes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bytes.d.ts","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,MAAM,MAAM,SAAS,GACnB,WAAW,GAAG,YAAY,GAAG,WAAW,GAAG,YAAY,GAAG,YAAY,GAAG,WAAW,CAAC;AAEvF,eAAO,MAAM,UAAU,EAAE,SAAS,SAAS,EAO1C,CAAC;AAuCF;;;GAGG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,UAAU,KAAG,SAAS,GAAG,IAiB9D,CAAC;AAaF,gGAAgG;AAChG,eAAO,MAAM,aAAa,GAAI,OAAO,UAAU,KAAG,MAUjD,CAAC;AAIF,4FAA4F;AAC5F,eAAO,MAAM,aAAa,GAAI,QAAQ,MAAM,KAAG,UAe9C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,GAAU,MAAM,IAAI,KAAG,OAAO,CAAC,UAAU,CAUhE,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAC7B,OAAO,GAAG,WAAW,GAAG,kBAAkB,GAAG,eAAe,GAAG,cAAc,GAAG,aAAa,CAAC;AAEhG,4EAA4E;AAC5E,qBAAa,eAAgB,SAAQ,KAAK;IACxC,SAAgB,IAAI,EAAE,mBAAmB,CAAC;gBAEvB,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,MAAM;CAK9D"}
package/dist/bytes.js ADDED
@@ -0,0 +1,113 @@
1
+ export const imageTypes = [
2
+ "image/png",
3
+ "image/jpeg",
4
+ "image/gif",
5
+ "image/webp",
6
+ "image/avif",
7
+ "image/bmp"
8
+ ];
9
+ const startsWith = (bytes, signature, offset = 0) => bytes.length >= offset + signature.length &&
10
+ signature.every((byte, index) => bytes[offset + index] === byte);
11
+ const ascii = (text) => Array.from(text, (character) => character.charCodeAt(0));
12
+ const readUint32BE = (bytes, offset) => (bytes[offset] ?? 0) * 0x1000000 +
13
+ (((bytes[offset + 1] ?? 0) << 16) | ((bytes[offset + 2] ?? 0) << 8) | (bytes[offset + 3] ?? 0));
14
+ const readUint32LE = (bytes, offset) => (bytes[offset + 3] ?? 0) * 0x1000000 +
15
+ (((bytes[offset + 2] ?? 0) << 16) | ((bytes[offset + 1] ?? 0) << 8) | (bytes[offset] ?? 0));
16
+ /** An ISO BMFF `ftyp` box whose major or compatible brands include `avif` or `avis`. */
17
+ const isAvif = (bytes) => {
18
+ if (!startsWith(bytes, ascii("ftyp"), 4)) {
19
+ return false;
20
+ }
21
+ const boxSize = Math.min(readUint32BE(bytes, 0), bytes.length);
22
+ for (let offset = 8; offset + 4 <= boxSize; offset += 4) {
23
+ // Offset 12 is the minor version, not a brand.
24
+ if (offset !== 12 &&
25
+ (startsWith(bytes, ascii("avif"), offset) || startsWith(bytes, ascii("avis"), offset))) {
26
+ return true;
27
+ }
28
+ }
29
+ return false;
30
+ };
31
+ /** "BM" followed by a known DIB header size, so text starting with "BM" is not a bitmap. */
32
+ const isBmp = (bytes) => startsWith(bytes, ascii("BM")) &&
33
+ [12, 40, 52, 56, 64, 108, 124].includes(readUint32LE(bytes, 14));
34
+ /**
35
+ * The image type from the file's first bytes (magic numbers), or `null`. Never trusts a file
36
+ * name or a declared MIME type, and never returns SVG.
37
+ */
38
+ export const sniffImageType = (bytes) => {
39
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
40
+ return "image/png";
41
+ }
42
+ if (startsWith(bytes, [0xff, 0xd8, 0xff])) {
43
+ return "image/jpeg";
44
+ }
45
+ if (startsWith(bytes, ascii("GIF87a")) || startsWith(bytes, ascii("GIF89a"))) {
46
+ return "image/gif";
47
+ }
48
+ if (startsWith(bytes, ascii("RIFF")) && startsWith(bytes, ascii("WEBP"), 8)) {
49
+ return "image/webp";
50
+ }
51
+ if (isAvif(bytes)) {
52
+ return "image/avif";
53
+ }
54
+ return isBmp(bytes) ? "image/bmp" : null;
55
+ };
56
+ const nodeBuffer = () => (globalThis.Buffer ?? null);
57
+ /** Bytes per `String.fromCharCode` call: well below engines' argument limits. */
58
+ const chunkSize = 0x8000;
59
+ /** Base64 of `bytes`, without a call-stack overflow on large images (uses `Buffer` in Node). */
60
+ export const bytesToBase64 = (bytes) => {
61
+ const buffer = nodeBuffer();
62
+ if (buffer) {
63
+ return buffer.from(bytes).toString("base64");
64
+ }
65
+ let binary = "";
66
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
67
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
68
+ }
69
+ return btoa(binary);
70
+ };
71
+ const base64Pattern = /^[A-Za-z0-9+/]*={0,2}$/;
72
+ /** Bytes of a base64 string (whitespace ignored). Throws on anything that is not base64. */
73
+ export const base64ToBytes = (base64) => {
74
+ const compact = base64.replace(/\s+/g, "");
75
+ if (!base64Pattern.test(compact) || compact.length % 4 === 1) {
76
+ throw new ImageToolsError("invalid-data", "Not valid base64");
77
+ }
78
+ const buffer = nodeBuffer();
79
+ if (buffer) {
80
+ return new Uint8Array(buffer.from(compact, "base64"));
81
+ }
82
+ const binary = atob(compact);
83
+ const bytes = new Uint8Array(binary.length);
84
+ for (let index = 0; index < binary.length; index += 1) {
85
+ bytes[index] = binary.charCodeAt(index);
86
+ }
87
+ return bytes;
88
+ };
89
+ /**
90
+ * The bytes of a `Blob`. Uses `blob.arrayBuffer()`, or `FileReader` where that is missing
91
+ * (older WebKit, jsdom).
92
+ */
93
+ export const blobToBytes = async (blob) => {
94
+ if (typeof blob.arrayBuffer === "function") {
95
+ return new Uint8Array(await blob.arrayBuffer());
96
+ }
97
+ return new Promise((resolve, reject) => {
98
+ const reader = new FileReader();
99
+ reader.onload = () => resolve(new Uint8Array(reader.result));
100
+ reader.onerror = () => reject(new ImageToolsError("invalid-data", "Could not read the file"));
101
+ reader.readAsArrayBuffer(blob);
102
+ });
103
+ };
104
+ /** Why an image was rejected; `code` is stable, `message` is for people. */
105
+ export class ImageToolsError extends Error {
106
+ code;
107
+ constructor(code, message) {
108
+ super(message);
109
+ this.name = "ImageToolsError";
110
+ this.code = code;
111
+ }
112
+ }
113
+ //# sourceMappingURL=bytes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bytes.js","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":"AAIA,MAAM,CAAC,MAAM,UAAU,GAAyB;IAC9C,WAAW;IACX,YAAY;IACZ,WAAW;IACX,YAAY;IACZ,YAAY;IACZ,WAAW;CACZ,CAAC;AAEF,MAAM,UAAU,GAAG,CAAC,KAAiB,EAAE,SAA4B,EAAE,MAAM,GAAG,CAAC,EAAW,EAAE,CAC1F,KAAK,CAAC,MAAM,IAAI,MAAM,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C,WAAW,EAAE,CAAC,CAAC;IAClD,CAAC;IACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,MAAqB,CAAC,CAAC,CAAC;QAC5E,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,eAAe,CAAC,cAAc,EAAE,yBAAyB,CAAC,CAAC,CAAC;QAC9F,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACjC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAKF,4EAA4E;AAC5E,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxB,IAAI,CAAsB;IAE1C,YAAmB,IAAyB,EAAE,OAAe;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,41 @@
1
+ import { type ImageType } from "./bytes.js";
2
+ /** Default `maxBytes`: 5 MB per image. */
3
+ export declare const DEFAULT_MAX_IMAGE_BYTES: number;
4
+ export type ImageInput = Blob | ArrayBuffer | Uint8Array;
5
+ export interface ToDataURLOptions {
6
+ /** Largest image accepted, in bytes. Default `DEFAULT_MAX_IMAGE_BYTES` (5 MB). */
7
+ readonly maxBytes?: number;
8
+ /** Types accepted. Default every `ImageType`. */
9
+ readonly allowedTypes?: readonly ImageType[];
10
+ /**
11
+ * The MIME type the bytes claim to be (a `Blob`'s `type` is used when this is left out).
12
+ * When set to an image type, it must match the sniffed type.
13
+ */
14
+ readonly declaredType?: string;
15
+ }
16
+ /**
17
+ * Checks bytes and returns their sniffed type. Rejects empty or oversized input, unknown
18
+ * types (SVG and HTML included, whatever they are called), types not in `allowedTypes`, and
19
+ * a declared image type that differs from the sniffed one.
20
+ */
21
+ export declare const checkImageBytes: (bytes: Uint8Array, options?: Omit<ToDataURLOptions, "declaredType"> & {
22
+ readonly declaredType?: string | undefined;
23
+ }) => ImageType;
24
+ /**
25
+ * A `data:image/…;base64,…` URL for an image (`Blob`, `File`, `ArrayBuffer` or `Uint8Array`),
26
+ * after the checks of `checkImageBytes`. The type in the URL is always the sniffed one.
27
+ * Throws an `ImageToolsError`.
28
+ */
29
+ export declare const toDataURL: (input: ImageInput, options?: ToDataURLOptions) => Promise<string>;
30
+ /**
31
+ * The bytes and sniffed type of a base64 image `data:` URL. The URL's type must be an image
32
+ * type matching the bytes (same rules as `toDataURL`, including `maxBytes`). Throws an
33
+ * `ImageToolsError`.
34
+ */
35
+ export declare const dataURLToBytes: (url: string, options?: Omit<ToDataURLOptions, "declaredType">) => {
36
+ readonly bytes: Uint8Array;
37
+ readonly type: ImageType;
38
+ };
39
+ /** A `Blob` from a base64 image `data:` URL (for example to send it to `upload`). */
40
+ export declare const dataURLToBlob: (url: string, options?: Omit<ToDataURLOptions, "declaredType">) => Blob;
41
+ //# sourceMappingURL=data-url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-url.d.ts","sourceRoot":"","sources":["../src/data-url.ts"],"names":[],"mappings":"AAAA,OAAO,EAOL,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAEpB,0CAA0C;AAC1C,eAAO,MAAM,uBAAuB,QAAkB,CAAC;AAEvD,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,WAAW,GAAG,UAAU,CAAC;AAEzD,MAAM,WAAW,gBAAgB;IAC/B,kFAAkF;IAClF,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,iDAAiD;IACjD,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;IAC7C;;;OAGG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC;AAiBD;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAC1B,OAAO,UAAU,EACjB,UAAS,IAAI,CAAC,gBAAgB,EAAE,cAAc,CAAC,GAAG;IAChD,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACvC,KACL,SAuBF,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,SAAS,GACpB,OAAO,UAAU,EACjB,UAAS,gBAAqB,KAC7B,OAAO,CAAC,MAAM,CAOhB,CAAC;AAIF;;;;GAIG;AACH,eAAO,MAAM,cAAc,GACzB,KAAK,MAAM,EACX,UAAS,IAAI,CAAC,gBAAgB,EAAE,cAAc,CAAM,KACnD;IAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CAWxD,CAAC;AAEF,qFAAqF;AACrF,eAAO,MAAM,aAAa,GACxB,KAAK,MAAM,EACX,UAAS,IAAI,CAAC,gBAAgB,EAAE,cAAc,CAAM,KACnD,IAGF,CAAC"}
@@ -0,0 +1,76 @@
1
+ import { base64ToBytes, blobToBytes, bytesToBase64, ImageToolsError, imageTypes, sniffImageType } from "./bytes.js";
2
+ /** Default `maxBytes`: 5 MB per image. */
3
+ export const DEFAULT_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
4
+ const readBytes = async (input) => {
5
+ if (input instanceof Uint8Array) {
6
+ return input;
7
+ }
8
+ if (input instanceof ArrayBuffer) {
9
+ return new Uint8Array(input);
10
+ }
11
+ return blobToBytes(input);
12
+ };
13
+ const normalizeType = (type) => {
14
+ const lower = type.split(";")[0]?.trim().toLowerCase() ?? "";
15
+ return lower === "image/jpg" || lower === "image/pjpeg" ? "image/jpeg" : lower;
16
+ };
17
+ /**
18
+ * Checks bytes and returns their sniffed type. Rejects empty or oversized input, unknown
19
+ * types (SVG and HTML included, whatever they are called), types not in `allowedTypes`, and
20
+ * a declared image type that differs from the sniffed one.
21
+ */
22
+ export const checkImageBytes = (bytes, options = {}) => {
23
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
24
+ if (bytes.length === 0) {
25
+ throw new ImageToolsError("empty", "The image is empty");
26
+ }
27
+ if (bytes.length > maxBytes) {
28
+ throw new ImageToolsError("too-large", `The image is ${bytes.length} bytes; the limit is ${maxBytes}`);
29
+ }
30
+ const type = sniffImageType(bytes);
31
+ if (!type || !(options.allowedTypes ?? imageTypes).includes(type)) {
32
+ throw new ImageToolsError("unsupported-type", type ? `Images of type ${type} are not allowed` : "Not a supported image");
33
+ }
34
+ const declared = normalizeType(options.declaredType ?? "");
35
+ if (declared.startsWith("image/") && declared !== type) {
36
+ throw new ImageToolsError("type-mismatch", `The image claims to be ${declared} but is ${type}`);
37
+ }
38
+ return type;
39
+ };
40
+ /**
41
+ * A `data:image/…;base64,…` URL for an image (`Blob`, `File`, `ArrayBuffer` or `Uint8Array`),
42
+ * after the checks of `checkImageBytes`. The type in the URL is always the sniffed one.
43
+ * Throws an `ImageToolsError`.
44
+ */
45
+ export const toDataURL = async (input, options = {}) => {
46
+ const bytes = await readBytes(input);
47
+ const type = checkImageBytes(bytes, {
48
+ ...options,
49
+ declaredType: options.declaredType ?? (input instanceof Blob ? input.type : undefined)
50
+ });
51
+ return `data:${type};base64,${bytesToBase64(bytes)}`;
52
+ };
53
+ const dataURLPattern = /^data:([^;,]+)((?:;[^;,]+)*?);base64,(.*)$/is;
54
+ /**
55
+ * The bytes and sniffed type of a base64 image `data:` URL. The URL's type must be an image
56
+ * type matching the bytes (same rules as `toDataURL`, including `maxBytes`). Throws an
57
+ * `ImageToolsError`.
58
+ */
59
+ export const dataURLToBytes = (url, options = {}) => {
60
+ const match = dataURLPattern.exec(url.trim());
61
+ if (!match?.[1] || match[3] === undefined) {
62
+ throw new ImageToolsError("invalid-data", "Not a base64 data: URL");
63
+ }
64
+ const declared = normalizeType(match[1]);
65
+ if (!declared.startsWith("image/")) {
66
+ throw new ImageToolsError("unsupported-type", `Not an image: ${declared}`);
67
+ }
68
+ const bytes = base64ToBytes(match[3]);
69
+ return { bytes, type: checkImageBytes(bytes, { ...options, declaredType: declared }) };
70
+ };
71
+ /** A `Blob` from a base64 image `data:` URL (for example to send it to `upload`). */
72
+ export const dataURLToBlob = (url, options = {}) => {
73
+ const { bytes, type } = dataURLToBytes(url, options);
74
+ return new Blob([bytes], { type });
75
+ };
76
+ //# sourceMappingURL=data-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-url.js","sourceRoot":"","sources":["../src/data-url.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,WAAW,EACX,aAAa,EACb,eAAe,EACf,UAAU,EACV,cAAc,EAEf,MAAM,YAAY,CAAC;AAEpB,0CAA0C;AAC1C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAgBvD,MAAM,SAAS,GAAG,KAAK,EAAE,KAAiB,EAAuB,EAAE;IACjE,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;QAChC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,KAAK,YAAY,WAAW,EAAE,CAAC;QACjC,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IACD,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC;AAC5B,CAAC,CAAC;AAEF,MAAM,aAAa,GAAG,CAAC,IAAY,EAAU,EAAE;IAC7C,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC7D,OAAO,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,aAAa,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC;AACjF,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,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AI,EAAE,GAAG,cAAc,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACrD,OAAO,IAAI,IAAI,CAAC,CAAC,KAAiB,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;AACjD,CAAC,CAAC"}
@@ -0,0 +1,26 @@
1
+ export interface DownscaleOptions {
2
+ /** Longest width in px. Default no limit. */
3
+ readonly maxWidth?: number;
4
+ /** Longest height in px. Default no limit. */
5
+ readonly maxHeight?: number;
6
+ /**
7
+ * Output type. Default: JPEG stays JPEG, WebP stays WebP, everything else becomes PNG (so
8
+ * screenshots stay sharp).
9
+ */
10
+ readonly type?: "image/png" | "image/jpeg" | "image/webp";
11
+ /** Quality for JPEG and WebP, 0–1. Default `0.85`. */
12
+ readonly quality?: number;
13
+ /**
14
+ * Re-encode even when the image already fits, to strip metadata such as EXIF GPS
15
+ * positions. Default `false` (an image that fits is returned unchanged).
16
+ */
17
+ readonly reencode?: boolean;
18
+ }
19
+ /**
20
+ * Resizes an image to fit `maxWidth` × `maxHeight` (keeping its aspect ratio) and re-encodes
21
+ * it with `createImageBitmap` and a canvas. Browsers and Electron only. An image that already
22
+ * fits is returned as is, unless `reencode` is set. Throws an `ImageToolsError` with code
23
+ * `unavailable` where there is no `createImageBitmap` or canvas.
24
+ */
25
+ export declare const downscaleImage: (blob: Blob, options?: DownscaleOptions) => Promise<Blob>;
26
+ //# sourceMappingURL=downscale.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"downscale.d.ts","sourceRoot":"","sources":["../src/downscale.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,gBAAgB;IAC/B,6CAA6C;IAC7C,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,8CAA8C;IAC9C,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,WAAW,GAAG,YAAY,GAAG,YAAY,CAAC;IAC1D,sDAAsD;IACtD,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AA+DD;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GAAU,MAAM,IAAI,EAAE,UAAS,gBAAqB,KAAG,OAAO,CAAC,IAAI,CAoC7F,CAAC"}
@@ -0,0 +1,67 @@
1
+ import { blobToBytes, ImageToolsError, sniffImageType } from "./bytes.js";
2
+ const createCanvas = (width, height) => {
3
+ const globals = globalThis;
4
+ if (globals.OffscreenCanvas) {
5
+ return new globals.OffscreenCanvas(width, height);
6
+ }
7
+ if (globals.document) {
8
+ const canvas = globals.document.createElement("canvas");
9
+ canvas.width = width;
10
+ canvas.height = height;
11
+ return canvas;
12
+ }
13
+ throw new ImageToolsError("unavailable", "No canvas is available to resize images");
14
+ };
15
+ const canvasToBlob = (canvas, type, quality) => {
16
+ if (canvas.convertToBlob) {
17
+ return canvas.convertToBlob({ type, quality });
18
+ }
19
+ return new Promise((resolve, reject) => {
20
+ if (!canvas.toBlob) {
21
+ reject(new ImageToolsError("unavailable", "The canvas cannot encode images"));
22
+ return;
23
+ }
24
+ canvas.toBlob((blob) => blob
25
+ ? resolve(blob)
26
+ : reject(new ImageToolsError("invalid-data", "Could not encode the image")), type, quality);
27
+ });
28
+ };
29
+ const outputType = (input, wanted) => wanted ?? (input === "image/jpeg" || input === "image/webp" ? input : "image/png");
30
+ const limit = (value) => typeof value === "number" && value > 0 ? value : Number.POSITIVE_INFINITY;
31
+ /**
32
+ * Resizes an image to fit `maxWidth` × `maxHeight` (keeping its aspect ratio) and re-encodes
33
+ * it with `createImageBitmap` and a canvas. Browsers and Electron only. An image that already
34
+ * fits is returned as is, unless `reencode` is set. Throws an `ImageToolsError` with code
35
+ * `unavailable` where there is no `createImageBitmap` or canvas.
36
+ */
37
+ export const downscaleImage = async (blob, options = {}) => {
38
+ const decode = globalThis
39
+ .createImageBitmap;
40
+ if (!decode) {
41
+ throw new ImageToolsError("unavailable", "createImageBitmap is not available");
42
+ }
43
+ const inputType = sniffImageType(await blobToBytes(blob.slice(0, 64)));
44
+ if (!inputType) {
45
+ throw new ImageToolsError("unsupported-type", "Not a supported image");
46
+ }
47
+ const bitmap = await decode(blob);
48
+ try {
49
+ const scale = Math.min(1, limit(options.maxWidth) / bitmap.width, limit(options.maxHeight) / bitmap.height);
50
+ if (scale === 1 && !options.reencode) {
51
+ return blob;
52
+ }
53
+ const width = Math.max(1, Math.round(bitmap.width * scale));
54
+ const height = Math.max(1, Math.round(bitmap.height * scale));
55
+ const canvas = createCanvas(width, height);
56
+ const context = canvas.getContext("2d");
57
+ if (!context) {
58
+ throw new ImageToolsError("unavailable", "No 2D canvas context");
59
+ }
60
+ context.drawImage(bitmap, 0, 0, width, height);
61
+ return await canvasToBlob(canvas, outputType(inputType, options.type), Math.min(1, Math.max(0, options.quality ?? 0.85)));
62
+ }
63
+ finally {
64
+ bitmap.close?.();
65
+ }
66
+ };
67
+ //# sourceMappingURL=downscale.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"downscale.js","sourceRoot":"","sources":["../src/downscale.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAkB,MAAM,YAAY,CAAC;AAuC1F,MAAM,YAAY,GAAG,CAAC,KAAa,EAAE,MAAc,EAAa,EAAE;IAChE,MAAM,OAAO,GAAG,UAGf,CAAC;IACF,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;QAC5B,OAAO,IAAI,OAAO,CAAC,eAAe,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC;IACD,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;QACrB,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QACxD,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;QACrB,MAAM,CAAC,MAAM,GA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AC,OAAO,EAAE,CAAC;YACb,MAAM,IAAI,eAAe,CAAC,aAAa,EAAE,sBAAsB,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,MAAM,YAAY,CACvB,MAAM,EACN,UAAU,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,EACnC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAClD,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC;IACnB,CAAC;AACH,CAAC,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { type ToDataURLOptions } from "./data-url.js";
2
+ import { type DownscaleOptions } from "./downscale.js";
3
+ export { base64ToBytes, blobToBytes, bytesToBase64, ImageToolsError, imageTypes, sniffImageType, type ImageToolsErrorCode, type ImageType } from "./bytes.js";
4
+ export { checkImageBytes, DEFAULT_MAX_IMAGE_BYTES, dataURLToBlob, dataURLToBytes, toDataURL, type ImageInput, type ToDataURLOptions } from "./data-url.js";
5
+ export { downscaleImage, type DownscaleOptions } from "./downscale.js";
6
+ export { extractRtfImages, type ExtractRtfImagesOptions, type RtfImage } from "./rtf.js";
7
+ export interface Base64UploaderOptions extends Omit<ToDataURLOptions, "declaredType"> {
8
+ /**
9
+ * Resize (and re-encode) before encoding; `false` (default) keeps the file as it is.
10
+ * Browsers and Electron only. The size limit applies to the resized image.
11
+ */
12
+ readonly downscale?: DownscaleOptions | false;
13
+ }
14
+ /**
15
+ * An `upload` function for the starter kit's `Image` that turns pasted, dropped or picked
16
+ * images into base64 `data:` URLs, for apps that store images inside the document:
17
+ *
18
+ * ```ts
19
+ * Image.configure({ allowBase64: true, upload: createBase64Uploader({ maxBytes: 5_000_000 }) })
20
+ * ```
21
+ *
22
+ * Rejects (so the editor drops the placeholder) with an `ImageToolsError` for files that are
23
+ * not supported images, claim a different type, or are too large.
24
+ */
25
+ export declare const createBase64Uploader: (options?: Base64UploaderOptions) => (file: Blob) => Promise<string>;
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAA8B,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAClF,OAAO,EAAkB,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvE,OAAO,EACL,aAAa,EACb,WAAW,EACX,aAAa,EACb,eAAe,EACf,UAAU,EACV,cAAc,EACd,KAAK,mBAAmB,EACxB,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,cAAc,EACd,SAAS,EACT,KAAK,UAAU,EACf,KAAK,gBAAgB,EACtB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,cAAc,EAAE,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzF,MAAM,WAAW,qBAAsB,SAAQ,IAAI,CAAC,gBAAgB,EAAE,cAAc,CAAC;IACnF;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,GAAG,KAAK,CAAC;CAC/C;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,oBAAoB,GAC9B,UAAS,qBAA0B,MAC7B,MAAM,IAAI,KAAG,OAAO,CAAC,MAAM,CAajC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ import { blobToBytes } from "./bytes.js";
2
+ import { checkImageBytes, toDataURL } from "./data-url.js";
3
+ import { downscaleImage } from "./downscale.js";
4
+ export { base64ToBytes, blobToBytes, bytesToBase64, ImageToolsError, imageTypes, sniffImageType } from "./bytes.js";
5
+ export { checkImageBytes, DEFAULT_MAX_IMAGE_BYTES, dataURLToBlob, dataURLToBytes, toDataURL } from "./data-url.js";
6
+ export { downscaleImage } from "./downscale.js";
7
+ export { extractRtfImages } from "./rtf.js";
8
+ /**
9
+ * An `upload` function for the starter kit's `Image` that turns pasted, dropped or picked
10
+ * images into base64 `data:` URLs, for apps that store images inside the document:
11
+ *
12
+ * ```ts
13
+ * Image.configure({ allowBase64: true, upload: createBase64Uploader({ maxBytes: 5_000_000 }) })
14
+ * ```
15
+ *
16
+ * Rejects (so the editor drops the placeholder) with an `ImageToolsError` for files that are
17
+ * not supported images, claim a different type, or are too large.
18
+ */
19
+ export const createBase64Uploader = (options = {}) => async (file) => {
20
+ const { downscale = false, ...limits } = options;
21
+ if (!downscale) {
22
+ return toDataURL(file, limits);
23
+ }
24
+ // Check the original first (type only: the limit applies to the result), so a renamed
25
+ // SVG or HTML file never reaches the image decoder.
26
+ checkImageBytes(await blobToBytes(file), {
27
+ ...limits,
28
+ maxBytes: Number.POSITIVE_INFINITY,
29
+ declaredType: file.type
30
+ });
31
+ return toDataURL(await downscaleImage(file, downscale), { ...limits, declaredType: "" });
32
+ };
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAyB,MAAM,eAAe,CAAC;AAClF,OAAO,EAAE,cAAc,EAAyB,MAAM,gBAAgB,CAAC;AAEvE,OAAO,EACL,aAAa,EACb,WAAW,EACX,aAAa,EACb,eAAe,EACf,UAAU,EACV,cAAc,EAGf,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,cAAc,EACd,SAAS,EAGV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,cAAc,EAAyB,MAAM,gBAAgB,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAA+C,MAAM,UAAU,CAAC;AAUzF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAC/B,CAAC,UAAiC,EAAE,EAAE,EAAE,CACxC,KAAK,EAAE,IAAU,EAAmB,EAAE;IACpC,MAAM,EAAE,SAAS,GAAG,KAAK,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC;IACjD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACjC,CAAC;IACD,sFAAsF;IACtF,oDAAoD;IACpD,eAAe,CAAC,MAAM,WAAW,CAAC,IAAI,CAAC,EAAE;QACvC,GAAG,MAAM;QACT,QAAQ,EAAE,MAAM,CAAC,iBAAiB;QAClC,YAAY,EAAE,IAAI,CAAC,IAAI;KACxB,CAAC,CAAC;IACH,OAAO,SAAS,CAAC,MAAM,cAAc,CAAC,IAAI,EAAE,SAAS,CAAC,EAAE,EAAE,GAAG,MAAM,EAAE,YAAY,EAAE,EAAE,EAAE,CAAC,CAAC;AAC3F,CAAC,CAAC"}
package/dist/rtf.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ /** A PNG or JPEG picture found in RTF. */
2
+ export interface RtfImage {
3
+ readonly bytes: Uint8Array;
4
+ readonly type: "image/png" | "image/jpeg";
5
+ /** Display size in CSS px (`\picwgoal` × `\picscalex`), when the RTF gives one. */
6
+ readonly width: number | null;
7
+ readonly height: number | null;
8
+ }
9
+ export interface ExtractRtfImagesOptions {
10
+ /** Pictures larger than this, in bytes, are skipped. Default 5 MB. */
11
+ readonly maxBytes?: number;
12
+ }
13
+ /**
14
+ * PNG and JPEG pictures (`\pict` with `\pngblip` / `\jpegblip`) in RTF, such as Word puts on
15
+ * the clipboard, in document order. `\nonshppict` copies (duplicates for old readers) are
16
+ * skipped, and so are WMF/EMF/other formats, pictures whose bytes do not match their declared
17
+ * format, and pictures over `maxBytes`. Never throws on malformed RTF.
18
+ */
19
+ export declare const extractRtfImages: (rtf: string, options?: ExtractRtfImagesOptions) => RtfImage[];
20
+ //# sourceMappingURL=rtf.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rtf.d.ts","sourceRoot":"","sources":["../src/rtf.ts"],"names":[],"mappings":"AAGA,0CAA0C;AAC1C,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,YAAY,CAAC;IAC1C,mFAAmF;IACnF,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,MAAM,WAAW,uBAAuB;IACtC,sEAAsE;IACtE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAiCD;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,GAC3B,KAAK,MAAM,EACX,UAAS,uBAA4B,KACpC,QAAQ,EA4HV,CAAC"}