@softistx/image 0.0.0-stage → 0.6.1
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/LICENSE +21 -0
- package/README.md +551 -2
- package/dist/chunks/index-b71y3faz.js +20 -0
- package/dist/chunks/index-b71y3faz.js.map +10 -0
- package/dist/chunks/index-pj79f6q4.js +732 -0
- package/dist/chunks/index-pj79f6q4.js.map +23 -0
- package/dist/chunks/index-wfsrqqk2.js +16 -0
- package/dist/chunks/index-wfsrqqk2.js.map +10 -0
- package/dist/crop/crop-png.d.ts +39 -0
- package/dist/crop/crop-png.d.ts.map +1 -0
- package/dist/crop/from-query.d.ts +11 -0
- package/dist/crop/from-query.d.ts.map +1 -0
- package/dist/crop/png-chunks.d.ts +29 -0
- package/dist/crop/png-chunks.d.ts.map +1 -0
- package/dist/crop/png.d.ts +24 -0
- package/dist/crop/png.d.ts.map +1 -0
- package/dist/crop/row-assembler.d.ts +17 -0
- package/dist/crop/row-assembler.d.ts.map +1 -0
- package/dist/crop/unfilter.d.ts +10 -0
- package/dist/crop/unfilter.d.ts.map +1 -0
- package/dist/errors/image-error.d.ts +49 -0
- package/dist/errors/image-error.d.ts.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +42 -0
- package/dist/index.js.map +11 -0
- package/dist/input/read-input.d.ts +10 -0
- package/dist/input/read-input.d.ts.map +1 -0
- package/dist/input/sniff.d.ts +9 -0
- package/dist/input/sniff.d.ts.map +1 -0
- package/dist/pdf/index.d.ts +3 -0
- package/dist/pdf/index.d.ts.map +1 -0
- package/dist/pdf/index.js +166 -0
- package/dist/pdf/index.js.map +10 -0
- package/dist/pdf/render-pdf-page.d.ts +56 -0
- package/dist/pdf/render-pdf-page.d.ts.map +1 -0
- package/dist/process/bun-errors.d.ts +8 -0
- package/dist/process/bun-errors.d.ts.map +1 -0
- package/dist/process/geometry.d.ts +49 -0
- package/dist/process/geometry.d.ts.map +1 -0
- package/dist/process/process.d.ts +23 -0
- package/dist/process/process.d.ts.map +1 -0
- package/dist/render/render-image.d.ts +61 -0
- package/dist/render/render-image.d.ts.map +1 -0
- package/dist/s3/bind-image-store.d.ts +27 -0
- package/dist/s3/bind-image-store.d.ts.map +1 -0
- package/dist/s3/index.d.ts +4 -0
- package/dist/s3/index.d.ts.map +1 -0
- package/dist/s3/index.js +73 -0
- package/dist/s3/index.js.map +11 -0
- package/dist/s3/types.d.ts +61 -0
- package/dist/s3/types.d.ts.map +1 -0
- package/dist/s3/upload-image.d.ts +23 -0
- package/dist/s3/upload-image.d.ts.map +1 -0
- package/dist/set/define-image-set.d.ts +25 -0
- package/dist/set/define-image-set.d.ts.map +1 -0
- package/dist/set/limit.d.ts +7 -0
- package/dist/set/limit.d.ts.map +1 -0
- package/dist/set/options.d.ts +104 -0
- package/dist/set/options.d.ts.map +1 -0
- package/dist/set/runtime.d.ts +7 -0
- package/dist/set/runtime.d.ts.map +1 -0
- package/dist/set/types.d.ts +60 -0
- package/dist/set/types.d.ts.map +1 -0
- package/dist/set/whole.d.ts +3 -0
- package/dist/set/whole.d.ts.map +1 -0
- package/docs/README.md +13 -0
- package/docs/guide/pdf.md +60 -0
- package/docs/guide/processing.md +313 -0
- package/docs/guide/rendering.md +88 -0
- package/docs/guide/storing.md +219 -0
- package/docs/roadmap.md +71 -0
- package/docs/troubleshooting.md +724 -0
- package/package.json +90 -5
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/crop/png.ts", "../src/crop/png-chunks.ts", "../src/crop/unfilter.ts", "../src/crop/row-assembler.ts", "../src/crop/crop-png.ts", "../src/input/read-input.ts", "../src/input/sniff.ts", "../src/set/whole.ts", "../src/process/geometry.ts", "../src/set/options.ts", "../src/process/bun-errors.ts", "../src/process/process.ts", "../src/set/limit.ts", "../src/render/render-image.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { promisify } from 'node:util';\nimport { deflate } from 'node:zlib';\n\nconst deflateAsync = promisify(deflate);\n\n/** Decoded pixels, row after row, `channels` bytes each: RGB or RGBA. */\nexport type RawImage = {\n\twidth: number;\n\theight: number;\n\tchannels: 3 | 4;\n\tpixels: Uint8Array;\n};\n\n/** The eight bytes every PNG starts with. */\nexport const PNG_SIGNATURE: readonly number[] = [\n\t0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,\n];\n\n/** One PNG chunk: length, type, data and CRC. */\nexport function chunk(type: string, data: Uint8Array): Uint8Array {\n\tconst out = new Uint8Array(12 + data.length);\n\tconst view = new DataView(out.buffer);\n\tview.setUint32(0, data.length);\n\tfor (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);\n\tout.set(data, 8);\n\tview.setUint32(\n\t\t8 + data.length,\n\t\tBun.hash.crc32(out.subarray(4, 8 + data.length)) >>> 0,\n\t);\n\treturn out;\n}\n\n/**\n * A PNG of these pixels: IHDR, one IDAT (filter 0 on every row) and IEND,\n * with their CRCs, and nothing else, so no metadata can be in it.\n *\n * The deflate runs on zlib's thread pool, not the main thread: a large crop\n * stopped the event loop for 1.1 s synchronously (`[4096]` on 36 MP; 0.3 s\n * after). It costs memory, though: the async encode adds memory at the peak,\n * because the deflate input and output are held together; the figures above,\n * measured on the async build, include it. It is level 1, since this PNG only lives for one pipeline\n * step (it is decoded again at once), so speed beats size.\n */\nexport async function encodePng(image: RawImage): Promise<Uint8Array> {\n\tconst { width, height, channels, pixels } = image;\n\tconst stride = width * channels;\n\tconst raw = new Uint8Array((stride + 1) * height);\n\tfor (let y = 0; y < height; y++) {\n\t\traw.set(\n\t\t\tpixels.subarray(y * stride, (y + 1) * stride),\n\t\t\ty * (stride + 1) + 1,\n\t\t);\n\t}\n\tconst header = new Uint8Array(13);\n\tconst view = new DataView(header.buffer);\n\tview.setUint32(0, width);\n\tview.setUint32(4, height);\n\theader[8] = 8;\n\theader[9] = channels === 4 ? 6 : 2;\n\tconst parts = [\n\t\tnew Uint8Array(PNG_SIGNATURE),\n\t\tchunk('IHDR', header),\n\t\tchunk('IDAT', await deflateAsync(raw, { level: 1 })),\n\t\tchunk('IEND', new Uint8Array(0)),\n\t];\n\tconst out = new Uint8Array(parts.reduce((n, part) => n + part.length, 0));\n\tlet at = 0;\n\tfor (const part of parts) {\n\t\tout.set(part, at);\n\t\tat += part.length;\n\t}\n\treturn out;\n}\n",
|
|
6
|
+
"import { ImageError } from '../errors/image-error';\nimport { PNG_SIGNATURE } from './png';\n\nexport function refuse(why: string): ImageError {\n\treturn new ImageError(\n\t\t'UNDECODABLE',\n\t\t'decode',\n\t\t`the PNG cannot be read: ${why}`,\n\t);\n}\n\n/** What the header says, once it is checked against what this reader takes. */\nexport type PngHeader = {\n\twidth: number;\n\theight: number;\n\t/** Samples per pixel as stored: 1 (grey), 2, 3 or 4. */\n\tsamples: number;\n};\n\n/** The chunk at `at`: its type, a view of its data, and where the next starts. */\nexport function chunkAt(\n\tbytes: Uint8Array,\n\tat: number,\n): { type: string; data: Uint8Array; next: number } {\n\tif (at + 12 > bytes.length) throw refuse('no IEND chunk');\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\tconst length = view.getUint32(at);\n\tif (at + 12 + length > bytes.length) throw refuse('a chunk is cut short');\n\treturn {\n\t\ttype: String.fromCharCode(...bytes.subarray(at + 4, at + 8)),\n\t\tdata: bytes.subarray(at + 8, at + 8 + length),\n\t\tnext: at + 12 + length,\n\t};\n}\n\n/**\n * The signature and the header: 8-bit, not interlaced, grey, grey with\n * alpha, RGB or RGBA. `maxPixels` refuses a header that claims more, as\n * `TOO_LARGE` with the reason `pixels`, before anything is inflated.\n */\nexport function readHeader(bytes: Uint8Array, maxPixels?: number): PngHeader {\n\tif (!PNG_SIGNATURE.every((value, i) => bytes[i] === value)) {\n\t\tthrow refuse('no PNG signature');\n\t}\n\tconst first = chunkAt(bytes, 8);\n\tif (first.type !== 'IHDR' || first.data.length !== 13) {\n\t\tthrow refuse('no IHDR chunk');\n\t}\n\tconst header = first.data;\n\tconst view = new DataView(header.buffer, header.byteOffset, 13);\n\tconst width = view.getUint32(0);\n\tconst height = view.getUint32(4);\n\tif (width < 1 || height < 1 || width > 0x7fffffff || height > 0x7fffffff) {\n\t\tthrow refuse('the size is not valid');\n\t}\n\tif (maxPixels !== undefined && width * height > maxPixels) {\n\t\tthrow new ImageError(\n\t\t\t'TOO_LARGE',\n\t\t\t'pixels',\n\t\t\t`the PNG has ${width}x${height} pixels, over the ${maxPixels} limit`,\n\t\t);\n\t}\n\tif (header[8] !== 8) throw refuse('only 8-bit samples are read');\n\tif (header[12] !== 0) throw refuse('an interlaced PNG is not read');\n\tconst samples = { 0: 1, 2: 3, 4: 2, 6: 4 }[header[9] as 0 | 2 | 4 | 6];\n\tif (samples === undefined) {\n\t\tthrow refuse('this colour type (a palette, for one) is not read');\n\t}\n\treturn { width, height, samples };\n}\n\n/**\n * The zlib stream of the file as a stream of views of its IDAT payloads, read\n * lazily and never copied. A damaged chunk errors the stream with its\n * `ImageError`. `onCancel` is called when the reader gives up before the end,\n * a seam for a spec that proves an early stop releases the stream.\n */\nexport function idatStream(\n\tbytes: Uint8Array,\n\tonCancel?: () => void,\n): ReadableStream<Uint8Array> {\n\tlet at = 8;\n\tlet sawData = false;\n\treturn new ReadableStream<Uint8Array>({\n\t\tpull(controller) {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst found = chunkAt(bytes, at);\n\t\t\t\t\tat = found.next;\n\t\t\t\t\tif (found.type === 'IDAT') {\n\t\t\t\t\t\tsawData = true;\n\t\t\t\t\t\tcontroller.enqueue(found.data);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (found.type === 'IEND') {\n\t\t\t\t\t\tif (!sawData) throw refuse('no IDAT chunk');\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t},\n\t\tcancel() {\n\t\t\tonCancel?.();\n\t\t},\n\t});\n}\n",
|
|
7
|
+
"/**\n * Undoes one PNG row filter (spec section 9), in place. `row` holds the\n * filtered bytes of one row, `previous` the unfiltered row above it (all zero\n * for the first row), both `stride` bytes long from `offset`; `bpp` is the\n * bytes per pixel.\n *\n * Returns `false` for a filter type the spec does not define.\n */\nexport function unfilterRow(\n\ttype: number,\n\trow: Uint8Array,\n\tprevious: Uint8Array,\n\toffset: number,\n\tstride: number,\n\tbpp: number,\n): boolean {\n\tconst end = offset + stride;\n\tswitch (type) {\n\t\tcase 0:\n\t\t\treturn true;\n\t\tcase 1:\n\t\t\tfor (let i = offset + bpp; i < end; i++) {\n\t\t\t\trow[i] = ((row[i] as number) + (row[i - bpp] as number)) & 0xff;\n\t\t\t}\n\t\t\treturn true;\n\t\tcase 2:\n\t\t\tfor (let i = offset; i < end; i++) {\n\t\t\t\trow[i] = ((row[i] as number) + (previous[i] as number)) & 0xff;\n\t\t\t}\n\t\t\treturn true;\n\t\tcase 3:\n\t\t\tfor (let i = offset; i < end; i++) {\n\t\t\t\tconst left = i - bpp >= offset ? (row[i - bpp] as number) : 0;\n\t\t\t\trow[i] =\n\t\t\t\t\t((row[i] as number) + ((left + (previous[i] as number)) >> 1)) & 0xff;\n\t\t\t}\n\t\t\treturn true;\n\t\tcase 4:\n\t\t\tfor (let i = offset; i < end; i++) {\n\t\t\t\tconst has = i - bpp >= offset;\n\t\t\t\tconst left = has ? (row[i - bpp] as number) : 0;\n\t\t\t\tconst upLeft = has ? (previous[i - bpp] as number) : 0;\n\t\t\t\trow[i] =\n\t\t\t\t\t((row[i] as number) + paeth(left, previous[i] as number, upLeft)) &\n\t\t\t\t\t0xff;\n\t\t\t}\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction paeth(a: number, b: number, c: number): number {\n\tconst p = a + b - c;\n\tconst pa = Math.abs(p - a);\n\tconst pb = Math.abs(p - b);\n\tconst pc = Math.abs(p - c);\n\tif (pa <= pb && pa <= pc) return a;\n\treturn pb <= pc ? b : c;\n}\n",
|
|
8
|
+
"import { refuse } from './png-chunks';\nimport { unfilterRow } from './unfilter';\n\n/**\n * Turns inflated bytes, in chunks of any size, into unfiltered rows. It holds\n * the row above and the row being filled (`stride + 1` bytes each, the filter\n * byte first) and nothing else.\n *\n * `feed(part)` calls `onRow(row, y)` for each finished row, `row` being the\n * buffer with the filter byte at 0 and the pixels from 1; the buffer is\n * reused, so `onRow` copies what it keeps. `onRow` returns `false` to stop:\n * `feed` then returns `false` too and reads no further. A refusal is thrown as\n * an `ImageError`: an unknown filter, or more rows than the header promises.\n */\nexport function createRowAssembler(\n\tstride: number,\n\theight: number,\n\tbpp: number,\n\tonRow: (row: Uint8Array, y: number) => boolean,\n) {\n\tlet previous = new Uint8Array(stride + 1);\n\tlet current = new Uint8Array(stride + 1);\n\tlet filled = 0;\n\tlet y = 0;\n\n\treturn {\n\t\t/** The rows finished so far. */\n\t\tget rows() {\n\t\t\treturn y;\n\t\t},\n\t\tfeed(part: Uint8Array): boolean {\n\t\t\tlet at = 0;\n\t\t\twhile (at < part.length) {\n\t\t\t\tif (y >= height) {\n\t\t\t\t\tthrow refuse('the pixel data is longer than the header says');\n\t\t\t\t}\n\t\t\t\tconst take = Math.min(part.length - at, stride + 1 - filled);\n\t\t\t\tcurrent.set(part.subarray(at, at + take), filled);\n\t\t\t\tfilled += take;\n\t\t\t\tat += take;\n\t\t\t\tif (filled < stride + 1) continue;\n\t\t\t\tif (\n\t\t\t\t\t!unfilterRow(current[0] as number, current, previous, 1, stride, bpp)\n\t\t\t\t) {\n\t\t\t\t\tthrow refuse('a row has an unknown filter');\n\t\t\t\t}\n\t\t\t\tconst more = onRow(current, y);\n\t\t\t\t[previous, current] = [current, previous];\n\t\t\t\tfilled = 0;\n\t\t\t\ty++;\n\t\t\t\tif (!more) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\t};\n}\n",
|
|
9
|
+
"import { ImageError } from '../errors/image-error';\nimport type { RawImage } from './png';\nimport { idatStream, type PngHeader, readHeader, refuse } from './png-chunks';\nimport { createRowAssembler } from './row-assembler';\n\n/** A rectangle of pixels: `(x, y)` is its top-left corner. */\nexport type Region = { x: number; y: number; width: number; height: number };\n\nfunction checkRegion(region: Region, header: PngHeader): void {\n\tconst { x, y, width, height } = region;\n\tif (\n\t\t![x, y, width, height].every(Number.isInteger) ||\n\t\tx < 0 ||\n\t\ty < 0 ||\n\t\twidth < 1 ||\n\t\theight < 1 ||\n\t\tx + width > header.width ||\n\t\ty + height > header.height\n\t) {\n\t\tthrow new RangeError(\n\t\t\t`a ${width}x${height} region at (${x}, ${y}) does not fit a ${header.width}x${header.height} image`,\n\t\t);\n\t}\n}\n\n/** Copies columns of an unfiltered row into the output, widening grey. */\nfunction copyColumns(\n\trow: Uint8Array,\n\tregion: Region,\n\tsamples: number,\n\tout: Uint8Array,\n\toutRow: number,\n): void {\n\tconst from = 1 + region.x * samples;\n\tif (samples >= 3) {\n\t\tout.set(row.subarray(from, from + region.width * samples), outRow);\n\t\treturn;\n\t}\n\tconst channels = samples === 1 ? 3 : 4;\n\tfor (let i = 0; i < region.width; i++) {\n\t\tconst grey = row[from + i * samples] as number;\n\t\tconst at = outRow + i * channels;\n\t\tout[at] = grey;\n\t\tout[at + 1] = grey;\n\t\tout[at + 2] = grey;\n\t\tif (channels === 4) out[at + 3] = row[from + i * samples + 1] as number;\n\t}\n}\n\n/**\n * Reads a region of what `Bun.Image(...).png()` emits (8-bit, not\n * interlaced, grey, grey with alpha, RGB or RGBA, any of the five filters)\n * while the PNG inflates, and stops after the region's last row. Grey is\n * widened to RGB, grey with alpha to RGBA. Only two rows (the one above and\n * the current one) are ever held, plus the region's own pixels, and the\n * IDAT payloads are read in place, so the cost does not grow with the image.\n * Every other chunk (colour profile, EXIF, text) is read past and dropped,\n * which is how a re-encode strips them.\n *\n * The input is Bun's own PNG, never the user's bytes, so the rest of the file\n * is trusted once the region is read: a cut file, a missing IEND, a bad CRC\n * or a bad zlib checksum after the region's last row is **not seen**. Only a\n * region that reaches the image's last row reads on to the end of the zlib\n * stream, checking its checksum and that no data is left over.\n *\n * `region` is a rectangle, or a function of the header's size, for a caller\n * that knows the region only once it knows the size. `maxPixels` refuses a\n * PNG whose header claims more pixels, before anything is inflated:\n * `TOO_LARGE` with the reason `pixels`. Inflated data longer than the header\n * promises is refused, as far as the stream is read.\n *\n * `onCancel` is called when the read stops before the end of the IDAT data\n * (the region's last row is not the image's), after the stream is cancelled;\n * it exists so a spec can see that the stream is released.\n */\nexport async function cropPng(\n\tbytes: Uint8Array,\n\tregion: Region | ((size: { width: number; height: number }) => Region),\n\tmaxPixels?: number,\n\tonCancel?: () => void,\n): Promise<RawImage> {\n\tconst header = readHeader(bytes, maxPixels);\n\tconst wanted = typeof region === 'function' ? region(header) : region;\n\tcheckRegion(wanted, header);\n\tconst { width, height, samples } = header;\n\tconst channels = samples === 1 || samples === 3 ? 3 : 4;\n\tconst lastRow = wanted.y + wanted.height - 1;\n\tconst out = new Uint8Array(wanted.width * wanted.height * channels);\n\n\tconst rows = createRowAssembler(\n\t\twidth * samples,\n\t\theight,\n\t\tsamples,\n\t\t(row, y) => {\n\t\t\tif (y >= wanted.y) {\n\t\t\t\tconst outRow = (y - wanted.y) * wanted.width * channels;\n\t\t\t\tcopyColumns(row, wanted, samples, out, outRow);\n\t\t\t}\n\t\t\t// Past the region's last row there is nothing left to read, unless it is\n\t\t\t// the last row of the image: then the rest is checked.\n\t\t\treturn y < lastRow || lastRow === height - 1;\n\t\t},\n\t);\n\tconst inflate = new DecompressionStream('deflate') as unknown as {\n\t\treadable: ReadableStream<Uint8Array>;\n\t\twritable: WritableStream<Uint8Array>;\n\t};\n\tconst reader = idatStream(bytes, onCancel).pipeThrough(inflate).getReader();\n\ttry {\n\t\tfor (;;) {\n\t\t\tlet part: Awaited<ReturnType<typeof reader.read>>;\n\t\t\ttry {\n\t\t\t\tpart = await reader.read();\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof ImageError) throw error;\n\t\t\t\tthrow refuse('the pixel data is not valid zlib');\n\t\t\t}\n\t\t\tif (part.done) {\n\t\t\t\tif (rows.rows < height) {\n\t\t\t\t\tthrow refuse('the pixel data is shorter than the header says');\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!rows.feed(part.value)) break;\n\t\t}\n\t\treturn {\n\t\t\twidth: wanted.width,\n\t\t\theight: wanted.height,\n\t\t\tchannels,\n\t\t\tpixels: out,\n\t\t};\n\t} finally {\n\t\tawait reader.cancel().catch(() => undefined);\n\t}\n}\n",
|
|
10
|
+
"import { ImageError } from '../errors/image-error';\n\nexport type ImageInput =\n\t| Uint8Array\n\t| ArrayBuffer\n\t| Blob\n\t| ReadableStream<Uint8Array>;\n\nfunction tooLarge(maxBytes: number): ImageError {\n\treturn new ImageError(\n\t\t'TOO_LARGE',\n\t\t'bytes',\n\t\t`the upload is over ${maxBytes} bytes`,\n\t);\n}\n\nasync function readStream(\n\tstream: ReadableStream<Uint8Array>,\n\tmaxBytes: number,\n): Promise<Uint8Array> {\n\tconst reader = stream.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet total = 0;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!(value instanceof Uint8Array)) {\n\t\t\t\tawait reader.cancel().catch(() => undefined);\n\t\t\t\tthrow new TypeError('a stream chunk must be a Uint8Array');\n\t\t\t}\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel().catch(() => undefined);\n\t\t\t\tthrow tooLarge(maxBytes);\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\tconst bytes = new Uint8Array(total);\n\tlet at = 0;\n\tfor (const chunk of chunks) {\n\t\tbytes.set(chunk, at);\n\t\tat += chunk.byteLength;\n\t}\n\treturn bytes;\n}\n\n/**\n * The upload's bytes, refused as soon as they pass `maxBytes`. A size known\n * up front (bytes, a buffer, a `Blob`) is checked before anything is read, and\n * a `Blob`'s again once read; a `Blob` of no known size and a stream are\n * read chunk by chunk and cancelled at the chunk that crosses the cap, so no\n * more than the cap plus one chunk is ever held.\n */\nexport async function readInput(\n\tinput: ImageInput,\n\tmaxBytes: number,\n): Promise<Uint8Array> {\n\tif (input instanceof Uint8Array) {\n\t\tif (input.byteLength > maxBytes) throw tooLarge(maxBytes);\n\t\treturn input;\n\t}\n\tif (input instanceof ArrayBuffer) {\n\t\tif (input.byteLength > maxBytes) throw tooLarge(maxBytes);\n\t\treturn new Uint8Array(input);\n\t}\n\tif (input instanceof Blob) {\n\t\t// Bun's `S3File` is a Blob whose size is NaN: no comparison with it is\n\t\t// true, so a size that is not a number is read through the cap instead.\n\t\tif (!Number.isFinite(input.size))\n\t\t\treturn readStream(input.stream(), maxBytes);\n\t\tif (!(input.size <= maxBytes)) throw tooLarge(maxBytes);\n\t\tconst buffer = await input.arrayBuffer();\n\t\t// The size was only a claim: what was read is checked again.\n\t\tif (buffer.byteLength > maxBytes) throw tooLarge(maxBytes);\n\t\treturn new Uint8Array(buffer);\n\t}\n\tif (input instanceof ReadableStream) return readStream(input, maxBytes);\n\tthrow new TypeError(\n\t\t'image input must be a Uint8Array, an ArrayBuffer, a Blob or a ReadableStream of Uint8Array',\n\t);\n}\n",
|
|
11
|
+
"import { PNG_SIGNATURE } from '../crop/png';\n\nexport type SniffedFormat = 'jpeg' | 'png' | 'webp' | 'heic';\n\n/** Brands of an ISO-BMFF `ftyp` box that mean a HEIF image Bun can decode. */\nconst HEIC_BRANDS = new Set(['heic', 'heix', 'hevc', 'hevx', 'mif1', 'msf1']);\n\n/** AVIF shares `mif1` with HEIC, so its own brands refuse the file. */\nconst AVIF_BRANDS = new Set(['avif', 'avis']);\n\nfunction startsWith(\n\tbytes: Uint8Array,\n\tsignature: readonly number[],\n\tat = 0,\n): boolean {\n\treturn (\n\t\tbytes.length >= at + signature.length &&\n\t\tsignature.every((value, i) => bytes[at + i] === value)\n\t);\n}\n\nfunction ascii(bytes: Uint8Array, at: number, length: number): string {\n\treturn String.fromCharCode(...bytes.subarray(at, at + length));\n}\n\n/**\n * The brands of the `ftyp` box at offset 4: the major brand, then every\n * compatible brand the box declares, the box size bounded by the buffer.\n */\nfunction brandsOf(bytes: Uint8Array): string[] {\n\tif (bytes.length < 12 || ascii(bytes, 4, 4) !== 'ftyp') return [];\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\tconst end = Math.min(bytes.length, Math.max(view.getUint32(0), 16));\n\tconst brands = [ascii(bytes, 8, 4)];\n\t// Skip the major brand (8) and the minor version (12): the rest are 4 bytes each.\n\tfor (let at = 16; at + 4 <= end; at += 4) brands.push(ascii(bytes, at, 4));\n\treturn brands;\n}\n\n/**\n * The format the first bytes announce, or `undefined`. Magic bytes only: a\n * file name and a declared content type are what the uploader chose. Short or\n * truncated input is `undefined`, never an error. AVIF is refused here, since\n * it is not an accepted input.\n */\nexport function sniffFormat(bytes: Uint8Array): SniffedFormat | undefined {\n\tif (startsWith(bytes, [0xff, 0xd8, 0xff])) return 'jpeg';\n\tif (startsWith(bytes, PNG_SIGNATURE)) return 'png';\n\tif (\n\t\tbytes.length >= 12 &&\n\t\tascii(bytes, 0, 4) === 'RIFF' &&\n\t\tascii(bytes, 8, 4) === 'WEBP'\n\t) {\n\t\treturn 'webp';\n\t}\n\tconst brands = brandsOf(bytes);\n\tif (brands.some((brand) => AVIF_BRANDS.has(brand))) return undefined;\n\tif (brands.some((brand) => HEIC_BRANDS.has(brand))) return 'heic';\n\treturn undefined;\n}\n",
|
|
12
|
+
"/** Whether the value is a whole number from `min` (default 0) to `max` (default: no limit). */\nexport function isWhole(\n\tvalue: unknown,\n\tmin = 0,\n\tmax = Number.POSITIVE_INFINITY,\n): value is number {\n\treturn (\n\t\ttypeof value === 'number' &&\n\t\tNumber.isInteger(value) &&\n\t\tvalue >= min &&\n\t\tvalue <= max\n\t);\n}\n",
|
|
13
|
+
"import { ImageError } from '../errors/image-error';\nimport type { CropBox } from '../set/types';\nimport { isWhole } from '../set/whole';\n\n/** The size of an image, in pixels. */\nexport type Dimensions = { width: number; height: number };\n\n/**\n * How much to shrink before cropping: enough that the crop keeps twice the\n * largest variant (so the last resize still has pixels to average), never\n * more than 1, since a source is never enlarged.\n */\nexport function shrinkScale(cropSide: number, largestSize: number): number {\n\treturn Math.min(1, (2 * largestSize) / cropSide);\n}\n\n/** The size the shrunk image has: at least one pixel on each side. */\nexport function scaledDimensions(\n\t{ width, height }: Dimensions,\n\tscale: number,\n): Dimensions {\n\treturn {\n\t\twidth: Math.max(1, Math.round(width * scale)),\n\t\theight: Math.max(1, Math.round(height * scale)),\n\t};\n}\n\n/** The square of side `min(width, height)` in the middle of the image. */\nexport function centredCrop({ width, height }: Dimensions): CropBox {\n\tconst size = Math.min(width, height);\n\treturn {\n\t\tx: Math.floor((width - size) / 2),\n\t\ty: Math.floor((height - size) / 2),\n\t\tsize,\n\t};\n}\n\n/**\n * Refuses a crop that is not three whole non-negative numbers, as an\n * `ImageError` (`INVALID_CROP`): the crop can come from a request.\n */\nexport function assertCropShape(crop: CropBox): void {\n\tif (\n\t\ttypeof crop !== 'object' ||\n\t\tcrop === null ||\n\t\t![crop.x, crop.y, crop.size].every((value) => isWhole(value))\n\t) {\n\t\tthrow new ImageError(\n\t\t\t'INVALID_CROP',\n\t\t\t'crop',\n\t\t\t'a crop is { x, y, size }, three whole numbers of 0 or more',\n\t\t);\n\t}\n}\n\n/** Refuses a crop that is not inside the (oriented) image (`INVALID_CROP`). */\nexport function assertCropFits(crop: CropBox, image: Dimensions): void {\n\tif (\n\t\tcrop.size < 1 ||\n\t\tcrop.x + crop.size > image.width ||\n\t\tcrop.y + crop.size > image.height\n\t) {\n\t\tthrow new ImageError(\n\t\t\t'INVALID_CROP',\n\t\t\t'crop',\n\t\t\t`a ${crop.size}px crop at (${crop.x}, ${crop.y}) does not fit the ${image.width}x${image.height} image`,\n\t\t);\n\t}\n}\n\n/**\n * The crop in the shrunk image's pixels: each number rounded, then clamped so\n * the square stays inside it (rounding can overshoot an edge by a pixel).\n */\nexport function scaleCrop(\n\tcrop: CropBox,\n\tscale: number,\n\tshrunk: Dimensions,\n): CropBox {\n\tconst size = Math.max(\n\t\t1,\n\t\tMath.min(Math.round(crop.size * scale), shrunk.width, shrunk.height),\n\t);\n\tconst clamp = (value: number, room: number) =>\n\t\tMath.max(0, Math.min(Math.round(value * scale), room - size));\n\treturn {\n\t\tx: clamp(crop.x, shrunk.width),\n\t\ty: clamp(crop.y, shrunk.height),\n\t\tsize,\n\t};\n}\n\n/** A rectangle to keep: `(x, y)` is its top-left corner, in pixels. */\nexport type Rect = { x: number; y: number; width: number; height: number };\n\n/**\n * Refuses a rectangle that is not four whole numbers (`x`, `y` of 0 or more,\n * `width`, `height` of 1 or more) or does not fit the (oriented) image, as an\n * `ImageError` (`INVALID_CROP`): the crop can come from a request.\n */\nexport function assertRectFits(crop: Rect, image: Dimensions): void {\n\tconst ok =\n\t\ttypeof crop === 'object' &&\n\t\tcrop !== null &&\n\t\tisWhole(crop.x) &&\n\t\tisWhole(crop.y) &&\n\t\tisWhole(crop.width, 1) &&\n\t\tisWhole(crop.height, 1);\n\tif (!ok) {\n\t\tthrow new ImageError(\n\t\t\t'INVALID_CROP',\n\t\t\t'crop',\n\t\t\t'a crop is { x, y, width, height }, whole numbers: x and y of 0 or more, width and height of 1 or more',\n\t\t);\n\t}\n\tif (\n\t\tcrop.x + crop.width > image.width ||\n\t\tcrop.y + crop.height > image.height\n\t) {\n\t\tthrow new ImageError(\n\t\t\t'INVALID_CROP',\n\t\t\t'crop',\n\t\t\t`a ${crop.width}x${crop.height} crop at (${crop.x}, ${crop.y}) does not fit the ${image.width}x${image.height} image`,\n\t\t);\n\t}\n}\n\n/**\n * How much to shrink before cropping a rectangle: enough that the crop keeps\n * twice the target on both sides, never more than 1.\n */\nexport function shrinkScaleFor(crop: Dimensions, target: Dimensions): number {\n\treturn Math.min(\n\t\t1,\n\t\tMath.max(\n\t\t\t(2 * target.width) / crop.width,\n\t\t\t(2 * target.height) / crop.height,\n\t\t),\n\t);\n}\n\n/** The rectangle in the shrunk image's pixels, rounded and clamped inside it. */\nexport function scaleRect(crop: Rect, scale: number, shrunk: Dimensions): Rect {\n\tconst size = (value: number, room: number) =>\n\t\tMath.max(1, Math.min(Math.round(value * scale), room));\n\tconst width = size(crop.width, shrunk.width);\n\tconst height = size(crop.height, shrunk.height);\n\tconst place = (value: number, room: number) =>\n\t\tMath.max(0, Math.min(Math.round(value * scale), room));\n\treturn {\n\t\tx: place(crop.x, shrunk.width - width),\n\t\ty: place(crop.y, shrunk.height - height),\n\t\twidth,\n\t\theight,\n\t};\n}\n",
|
|
14
|
+
"import { isWhole } from './whole';\n\n/** The variants' format. */\nexport type ImageFormat = 'webp' | 'png';\n\n/** The content type of each format: the one place the two are paired. */\nexport const CONTENT_TYPES = Object.freeze({\n\twebp: 'image/webp',\n\tpng: 'image/png',\n} as const);\n\n/** A variant's content type, following its set's format `F`. */\nexport type ImageContentType<F extends ImageFormat = ImageFormat> =\n\t(typeof CONTENT_TYPES)[F];\n\n/** The content type of a format: `image/webp` or `image/png`. */\nexport function contentTypeOf<F extends ImageFormat>(\n\tformat: F,\n): ImageContentType<F> {\n\treturn CONTENT_TYPES[format];\n}\n\n/** The options a WebP set takes beside the common ones. */\ntype WebpOutput = {\n\t/** The variants' format. Default `'webp'`. */\n\tformat?: 'webp';\n\t/** Lossless WebP. Default `false`, lossy at `quality`. */\n\tlossless?: boolean;\n\t/**\n\t * The WebP quality, 1 to 100. Default 80. With `lossless`, it trades\n\t * encoding time for size instead of losing detail.\n\t */\n\tquality?: number;\n};\n\n/**\n * A PNG set: each size encoded once to PNG from the decoded upload. `quality`\n * and `lossless` are WebP's, so they are refused here.\n */\ntype PngOutput = {\n\tformat: 'png';\n\tlossless?: never;\n\tquality?: never;\n};\n\n/** What `defineImageSet` takes; every field has a default. */\nexport type ImageSetOptions = (WebpOutput | PngOutput) & {\n\t/**\n\t * The square sides to produce, in pixels: a non-empty list of unique whole\n\t * numbers from 1 to 4096. Default `[256, 64]`.\n\t */\n\tsizes?: readonly number[];\n\t/**\n\t * The upload's byte limit, a whole number of 1 or more. Default 5 MiB,\n\t * which admits most 12 MP photos but refuses most 48 MP phone JPEGs (about\n\t * 11 MB). Raise it with `maxPixels`: `maxBytes: 12 * 1024 * 1024`.\n\t */\n\tmaxBytes?: number;\n\t/**\n\t * The most pixels (width × height) an upload may claim, a whole number of\n\t * 1 or more. Default 25 000 000, which covers a 24 MP phone's output. A\n\t * 48 MP image is admitted only by raising this, and its JPEG (about 11 MB)\n\t * is refused by the default `maxBytes` first: raise both.\n\t *\n\t * **Memory.** One call peaks at about Bun's decode of the source (4 bytes\n\t * per pixel) + the intermediate PNG + the crop square, about\n\t * 4 × (2 × the largest size)² bytes. A centred crop with the default sizes\n\t * is cheap (17 to 18 MB measured, at 12 to 49 MP). The expensive path is a\n\t * small caller `crop` on a big image, or large `sizes`. Measured on\n\t * Bun 1.4.3, photo-like JPEGs, one call: a 256 px crop on 25 MP grows the\n\t * process by about 150 MB (2.7 s), on 36 MP about 210 MB (4 s), on 49 MP\n\t * about 280 MB (5.4 s); `sizes: [4096]` on 49 MP about 0.9 to 1.3 GB (9 s) and `[2048]` about\n\t * 460 to 530 MB (3 s).\n\t *\n\t * **Bun 1.4.3 holds on to each `png()` output** (about the size of that\n\t * PNG per call) until a later collection, so sequential worst-case calls\n\t * climb before the memory falls back: 70 calls with a small crop climbed to\n\t * about 720 MB at 25 MP and to over 1.6 GB at 36 MP. Lowering `maxPixels`\n\t * is the lever that shrinks both.\n\t */\n\tmaxPixels?: number;\n\t/**\n\t * The smallest side an upload, or a crop of it, may have. Default: the\n\t * largest of `sizes`, so no variant is ever enlarged.\n\t */\n\tminSide?: number;\n\t/**\n\t * How many `process` calls of this set decode at once, a whole number from\n\t * 1 to 64. Default 2. The others wait their turn, in order, after their\n\t * bytes are read and their format sniffed. It limits the calls in flight,\n\t * **not the memory**: Bun holds each `png()` output until a later\n\t * collection (see `maxPixels`), so memory can pass `concurrency` × one\n\t * call's peak. Measured on Bun 1.4.3, photo-like JPEG, 36 MP with a 256 px\n\t * crop, 4 calls at once grew the process by about 770 MB with `concurrency`\n\t * 4, 510 MB with 2 and 330 MB with 1.\n\t *\n\t * **The wait queue is not bounded**, and each waiting call holds its\n\t * upload's bytes (up to `maxBytes`). A server that can receive more uploads\n\t * than it decodes should cap them before they reach `process`.\n\t */\n\tconcurrency?: number;\n};\n\n/** The options with every default applied. */\nexport type ResolvedOptions = {\n\treadonly sizes: readonly number[];\n\treadonly maxBytes: number;\n\treadonly maxPixels: number;\n\treadonly minSide: number;\n\treadonly quality: number;\n\treadonly concurrency: number;\n\treadonly format: ImageFormat;\n\treadonly lossless: boolean;\n};\n\nconst DEFAULT_SIZES: readonly number[] = [256, 64];\nconst DEFAULT_MAX_BYTES = 5 * 1024 * 1024;\nconst DEFAULT_MAX_PIXELS = 25_000_000;\nconst DEFAULT_QUALITY = 80;\nconst DEFAULT_CONCURRENCY = 2;\nconst MAX_CONCURRENCY = 64;\nconst MAX_SIZE = 4096;\n\nfunction whole(name: string, value: unknown, min: number, max?: number) {\n\tif (!isWhole(value, min, max)) {\n\t\tconst range = max === undefined ? `${min} or more` : `${min} to ${max}`;\n\t\tthrow new TypeError(\n\t\t\t`${name} must be a whole number of ${range}, got ${String(value)}`,\n\t\t);\n\t}\n\treturn value;\n}\n\nfunction checkSizes(sizes: unknown): readonly number[] {\n\tif (!Array.isArray(sizes) || sizes.length === 0) {\n\t\tthrow new TypeError('sizes must be a non-empty array of whole numbers');\n\t}\n\tfor (const size of sizes) whole('sizes[]', size, 1, MAX_SIZE);\n\tif (new Set(sizes).size !== sizes.length) {\n\t\tthrow new TypeError(`sizes must be unique, got [${sizes.join(', ')}]`);\n\t}\n\treturn Object.freeze([...sizes]);\n}\n\nfunction checkFormat(format: unknown): ImageFormat {\n\tif (format !== 'webp' && format !== 'png') {\n\t\tthrow new TypeError(\n\t\t\t`format must be 'webp' or 'png', got ${String(format)}`,\n\t\t);\n\t}\n\treturn format;\n}\n\nfunction checkLossless(lossless: unknown): boolean {\n\tif (typeof lossless !== 'boolean') {\n\t\tthrow new TypeError(`lossless must be a boolean, got ${String(lossless)}`);\n\t}\n\treturn lossless;\n}\n\n/** `quality` and `lossless` are WebP's: given beside `format: 'png'`, a `TypeError`. */\nfunction checkPngOptions(options: Record<string, unknown>): void {\n\tfor (const name of ['lossless', 'quality']) {\n\t\tif (options[name] !== undefined) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${name} applies to WebP only: a PNG is always lossless`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** The options with their defaults, or a `TypeError` naming the bad one. */\nexport function resolveOptions(options: ImageSetOptions = {}): ResolvedOptions {\n\tconst sizes = checkSizes(options.sizes ?? DEFAULT_SIZES);\n\tconst format = checkFormat(options.format ?? 'webp');\n\tif (format === 'png') checkPngOptions(options);\n\treturn Object.freeze({\n\t\tsizes,\n\t\tmaxBytes: whole('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES, 1),\n\t\tmaxPixels: whole('maxPixels', options.maxPixels ?? DEFAULT_MAX_PIXELS, 1),\n\t\tminSide: whole('minSide', options.minSide ?? Math.max(...sizes), 1),\n\t\tquality: whole('quality', options.quality ?? DEFAULT_QUALITY, 1, 100),\n\t\tconcurrency: whole(\n\t\t\t'concurrency',\n\t\t\toptions.concurrency ?? DEFAULT_CONCURRENCY,\n\t\t\t1,\n\t\t\tMAX_CONCURRENCY,\n\t\t),\n\t\tformat,\n\t\tlossless: checkLossless(options.lossless ?? false),\n\t});\n}\n",
|
|
15
|
+
"import type { ImageErrorCode, ImageErrorReason } from '../errors/image-error';\nimport { ImageError } from '../errors/image-error';\nimport type { SniffedFormat } from '../input/sniff';\n\nfunction refusal(\n\tcode: ImageErrorCode,\n\treason: ImageErrorReason,\n\tmessage: string,\n\tcause: unknown,\n): ImageError {\n\tconst error = new ImageError(code, reason, message);\n\terror.cause = cause;\n\treturn error;\n}\n\n/**\n * Bun's `error.code` on a `Bun.Image` rejection, as this package's\n * `ImageError`; any other error comes back untouched, so a bug or an\n * out-of-memory is never taken for a bad upload. Bun's error is the `cause`.\n */\nexport function mapBunError(error: unknown, format: SniffedFormat): unknown {\n\tconst code = (error as { code?: unknown } | null)?.code;\n\tswitch (code) {\n\t\tcase 'ERR_IMAGE_TOO_MANY_PIXELS':\n\t\t\treturn refusal(\n\t\t\t\t'TOO_LARGE',\n\t\t\t\t'pixels',\n\t\t\t\t'the image has too many pixels',\n\t\t\t\terror,\n\t\t\t);\n\t\tcase 'ERR_IMAGE_FORMAT_UNSUPPORTED':\n\t\t\treturn format === 'heic'\n\t\t\t\t? refusal(\n\t\t\t\t\t\t'UNSUPPORTED_TYPE',\n\t\t\t\t\t\t'heic-unavailable',\n\t\t\t\t\t\t'this machine cannot decode HEIC (Linux cannot)',\n\t\t\t\t\t\terror,\n\t\t\t\t\t)\n\t\t\t\t: refusal(\n\t\t\t\t\t\t'UNSUPPORTED_TYPE',\n\t\t\t\t\t\t'format',\n\t\t\t\t\t\t`this machine cannot decode ${format}`,\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\tcase 'ERR_IMAGE_DECODE_FAILED':\n\t\tcase 'ERR_IMAGE_UNKNOWN_FORMAT':\n\t\t\treturn refusal(\n\t\t\t\t'UNDECODABLE',\n\t\t\t\t'decode',\n\t\t\t\t`the ${format} image cannot be decoded`,\n\t\t\t\terror,\n\t\t\t);\n\t\tdefault:\n\t\t\treturn error;\n\t}\n}\n",
|
|
16
|
+
"import { cropPng } from '../crop/crop-png';\nimport { encodePng } from '../crop/png';\nimport { ImageError } from '../errors/image-error';\nimport { type ImageInput, readInput } from '../input/read-input';\nimport { type SniffedFormat, sniffFormat } from '../input/sniff';\nimport { contentTypeOf, type ResolvedOptions } from '../set/options';\nimport type {\n\tCropBox,\n\tImageVariant,\n\tProcessedImage,\n\tProcessOptions,\n} from '../set/types';\nimport { mapBunError } from './bun-errors';\nimport {\n\tassertCropFits,\n\tassertCropShape,\n\tcentredCrop,\n\ttype Dimensions,\n\tscaleCrop,\n\tscaledDimensions,\n\tshrinkScale,\n} from './geometry';\n\n/** Runs a Bun pipeline step, its refusals turned into `ImageError`. */\nexport async function guarded<T>(\n\tformat: SniffedFormat,\n\tstep: () => Promise<T>,\n): Promise<T> {\n\ttry {\n\t\treturn await step();\n\t} catch (error) {\n\t\tthrow mapBunError(error, format);\n\t}\n}\n\n/** The oriented size: `metadata()` reports it after EXIF rotation (measured). */\nexport async function readDimensions(\n\tbytes: Uint8Array,\n\tformat: SniffedFormat,\n\tmaxPixels: number,\n): Promise<Dimensions> {\n\tconst { width, height } = await guarded(format, () =>\n\t\tnew Bun.Image(bytes, { maxPixels, autoOrient: true }).metadata(),\n\t);\n\treturn { width, height };\n}\n\n/**\n * The image shrunk once, as a PNG at Bun's default level. That level gives\n * the smallest PNG, and Bun 1.4.3 holds each `png()` output until a later\n * collection, so the smallest PNG is the least memory held: a 36 MP photo\n * gave a 45 MB PNG at the default level and 146 MB at level 0 (Bun 1.4.3,\n * photo-like JPEG), and a process\n * grew by about the PNG's size per call (measured). Level 0 is faster, but\n * its bigger output is what stays. Even so, sequential calls with a small\n * crop climb before the memory falls back (see `maxPixels`).\n */\nexport function shrink(\n\tbytes: Uint8Array,\n\tformat: SniffedFormat,\n\timage: Dimensions,\n\tscale: number,\n\tmaxPixels: number,\n): Promise<Uint8Array> {\n\treturn guarded(format, () => {\n\t\tlet pipeline = new Bun.Image(bytes, { maxPixels, autoOrient: true });\n\t\tif (scale < 1) {\n\t\t\tconst to = scaledDimensions(image, scale);\n\t\t\tpipeline = pipeline.resize(to.width, to.height, { fit: 'fill' });\n\t\t}\n\t\treturn pipeline.png().bytes();\n\t});\n}\n\n/**\n * One size, encoded once from the decoded square: WebP at `quality` (with\n * `lossless` only when asked, so the default call is the one it always was),\n * or PNG at Bun's default level.\n */\nfunction variantOf(\n\tsquare: Uint8Array,\n\tsize: number,\n\t{ format, quality, lossless }: ResolvedOptions,\n): Promise<ImageVariant> {\n\treturn guarded('png', () => {\n\t\tconst resized = new Bun.Image(square).resize(size, size, { fit: 'fill' });\n\t\tif (format === 'png') return resized.png().bytes();\n\t\treturn resized.webp(lossless ? { quality, lossless } : { quality }).bytes();\n\t}).then((bytes) => ({\n\t\tsize,\n\t\twidth: size,\n\t\theight: size,\n\t\tcontentType: contentTypeOf(format),\n\t\tbytes,\n\t}));\n}\n\n/**\n * The crop as a PNG. The shrunk PNG is read while it inflates, keeping two\n * rows and the crop, so the full-size pixels are never held (see\n * `cropPng`); only the PNG bytes and the crop are live together.\n */\nasync function cropToPng(\n\tbytes: Uint8Array,\n\tformat: SniffedFormat,\n\timage: Dimensions,\n\tbox: CropBox,\n\toptions: ResolvedOptions,\n): Promise<Uint8Array> {\n\tconst scale = shrinkScale(box.size, Math.max(...options.sizes));\n\tconst square = await cropPng(\n\t\tawait shrink(bytes, format, image, scale, options.maxPixels),\n\t\t(shrunk) => {\n\t\t\tconst { x, y, size } = scaleCrop(box, scale, shrunk);\n\t\t\treturn { x, y, width: size, height: size };\n\t\t},\n\t\toptions.maxPixels,\n\t);\n\treturn await encodePng(square);\n}\n\n/** The pipeline behind `ImageSet.process`; the steps are in docs/guide/processing.md. */\nexport async function processImage(\n\tinput: ImageInput,\n\t{ crop }: ProcessOptions,\n\toptions: ResolvedOptions,\n\tlimit: <T>(task: () => Promise<T>) => Promise<T>,\n): Promise<ProcessedImage> {\n\tconst bytes = await readInput(input, options.maxBytes);\n\tconst format = sniffFormat(bytes);\n\tif (format === undefined) {\n\t\tthrow new ImageError(\n\t\t\t'UNSUPPORTED_TYPE',\n\t\t\t'format',\n\t\t\t'the upload is not a JPEG, PNG, WebP or HEIC',\n\t\t);\n\t}\n\t// From here on the call decodes pixels: `concurrency` of them at a time.\n\treturn limit(async () => {\n\t\tconst image = await readDimensions(bytes, format, options.maxPixels);\n\n\t\tif (crop !== undefined) {\n\t\t\tassertCropShape(crop);\n\t\t\tassertCropFits(crop, image);\n\t\t}\n\t\tconst box = crop ?? centredCrop(image);\n\t\tif (box.size < options.minSide) {\n\t\t\tthrow new ImageError(\n\t\t\t\t'TOO_SMALL',\n\t\t\t\t'dimensions',\n\t\t\t\tcrop\n\t\t\t\t\t? `the crop is ${crop.size}px, under the ${options.minSide}px minimum`\n\t\t\t\t\t: `the image is ${image.width}x${image.height}, under ${options.minSide}px on its short side`,\n\t\t\t);\n\t\t}\n\n\t\tconst squarePng = await cropToPng(bytes, format, image, box, options);\n\t\tconst variants = await Promise.all(\n\t\t\toptions.sizes.map((size) => variantOf(squarePng, size, options)),\n\t\t);\n\t\treturn { source: { format, ...image }, variants };\n\t});\n}\n",
|
|
17
|
+
"/**\n * A FIFO semaphore: `limit(task)` runs the task once fewer than `max` tasks\n * are running, tasks starting in the order they were submitted. A task that\n * throws frees its place, and its error is the caller's.\n */\nexport function createLimit(\n\tmax: number,\n): <T>(task: () => Promise<T>) => Promise<T> {\n\tlet running = 0;\n\tconst waiting: (() => void)[] = [];\n\n\tconst release = () => {\n\t\tconst next = waiting.shift();\n\t\tif (next) next();\n\t\telse running--;\n\t};\n\n\treturn async <T>(task: () => Promise<T>): Promise<T> => {\n\t\tif (running < max) running++;\n\t\t// The place passes straight to the next waiter, so `running` is exact.\n\t\telse await new Promise<void>((resolve) => waiting.push(resolve));\n\t\ttry {\n\t\t\treturn await task();\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t};\n}\n",
|
|
18
|
+
"import { cropPng } from '../crop/crop-png';\nimport { encodePng } from '../crop/png';\nimport { ImageError } from '../errors/image-error';\nimport { type ImageInput, readInput } from '../input/read-input';\nimport { type SniffedFormat, sniffFormat } from '../input/sniff';\nimport {\n\tassertRectFits,\n\ttype Dimensions,\n\ttype Rect,\n\tscaleRect,\n\tshrinkScaleFor,\n} from '../process/geometry';\nimport { guarded, readDimensions, shrink } from '../process/process';\nimport { createLimit } from '../set/limit';\nimport { isWhole } from '../set/whole';\n\n/** The formats `renderImage` writes. */\nexport type RenderFormat = 'jpeg' | 'webp' | 'png';\n\n/** The content type of each render format. */\nexport const RENDER_CONTENT_TYPES = Object.freeze({\n\tjpeg: 'image/jpeg',\n\twebp: 'image/webp',\n\tpng: 'image/png',\n} as const);\n\n/** A rectangle to keep, in pixels of the auto-oriented picture. */\nexport type CropRect = Rect;\n\nexport type RenderOptions<F extends RenderFormat = RenderFormat> = {\n\t/** The rectangle to keep. Default: the whole (upright) picture. */\n\tcrop?: CropRect;\n\t/** The output width, 1 to 8192. The crop is never enlarged to it. */\n\twidth: number;\n\t/** The output height, 1 to 8192. The crop is never enlarged to it. */\n\theight: number;\n\tformat: F;\n\t/** JPEG or WebP quality, 1 to 100. Default 80. Refused with `png`. */\n\tquality?: number;\n\t/** The upload's byte limit. Default 5 MiB. */\n\tmaxBytes?: number;\n\t/** The most pixels the upload may claim. Default 25 000 000. */\n\tmaxPixels?: number;\n\t/** Aborts the call: it rejects with the signal's reason. */\n\tsignal?: AbortSignal;\n};\n\nexport type RenderedImage<F extends RenderFormat = RenderFormat> = {\n\t/** The upload as read: its format and its oriented size. */\n\tsource: { format: SniffedFormat; width: number; height: number };\n\tbytes: Uint8Array;\n\twidth: number;\n\theight: number;\n\tcontentType: (typeof RENDER_CONTENT_TYPES)[F];\n};\n\nconst DEFAULT_MAX_BYTES = 5 * 1024 * 1024;\nconst DEFAULT_MAX_PIXELS = 25_000_000;\nconst DEFAULT_QUALITY = 80;\nconst MAX_SIDE = 8192;\n\n/** Calls of `renderImage` decode two at a time, like a set's default. */\nconst limit = createLimit(2);\n\nfunction whole(name: string, value: unknown, min: number, max?: number) {\n\tif (!isWhole(value, min, max)) {\n\t\tconst range = max === undefined ? `${min} or more` : `${min} to ${max}`;\n\t\tthrow new TypeError(\n\t\t\t`${name} must be a whole number of ${range}, got ${String(value)}`,\n\t\t);\n\t}\n\treturn value;\n}\n\nfunction checkOptions(options: RenderOptions) {\n\tconst { format } = options;\n\tif (format !== 'jpeg' && format !== 'webp' && format !== 'png') {\n\t\tthrow new TypeError(\n\t\t\t`format must be 'jpeg', 'webp' or 'png', got ${String(format)}`,\n\t\t);\n\t}\n\tif (format === 'png' && options.quality !== undefined) {\n\t\tthrow new TypeError(\n\t\t\t'quality applies to JPEG and WebP only: a PNG is always lossless',\n\t\t);\n\t}\n\treturn {\n\t\twidth: whole('width', options.width, 1, MAX_SIDE),\n\t\theight: whole('height', options.height, 1, MAX_SIDE),\n\t\tquality: whole('quality', options.quality ?? DEFAULT_QUALITY, 1, 100),\n\t\tmaxBytes: whole('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES, 1),\n\t\tmaxPixels: whole('maxPixels', options.maxPixels ?? DEFAULT_MAX_PIXELS, 1),\n\t};\n}\n\nfunction encode(\n\tbytes: Uint8Array,\n\tsourceFormat: SniffedFormat,\n\ttarget: Dimensions,\n\t{ format, quality, maxPixels, upright }: Encoding,\n): Promise<Uint8Array> {\n\treturn guarded(sourceFormat, () => {\n\t\t// `autoOrient` only for the original upload: the intermediate PNG is upright.\n\t\tconst resized = new Bun.Image(bytes, {\n\t\t\tmaxPixels,\n\t\t\tautoOrient: upright,\n\t\t}).resize(target.width, target.height, { fit: 'fill' });\n\t\tif (format === 'png') return resized.png().bytes();\n\t\tif (format === 'jpeg') return resized.jpeg({ quality }).bytes();\n\t\treturn resized.webp({ quality }).bytes();\n\t});\n}\n\ntype Encoding = {\n\tformat: RenderFormat;\n\tquality: number;\n\tmaxPixels: number;\n\tupright: boolean;\n};\n\n/** The crop as an upright PNG, read from the shrunk picture without holding its pixels. */\nasync function cropToPng(\n\tbytes: Uint8Array,\n\tformat: SniffedFormat,\n\timage: Dimensions,\n\tcrop: Rect,\n\ttarget: Dimensions,\n\tmaxPixels: number,\n): Promise<Uint8Array> {\n\tconst scale = shrinkScaleFor(crop, target);\n\tconst shrunk = await shrink(bytes, format, image, scale, maxPixels);\n\tconst region = await cropPng(\n\t\tshrunk,\n\t\t(size) => scaleRect(crop, scale, size),\n\t\tmaxPixels,\n\t);\n\treturn encodePng(region);\n}\n\nconst coversImage = (crop: Rect, image: Dimensions) =>\n\tcrop.x === 0 &&\n\tcrop.y === 0 &&\n\tcrop.width === image.width &&\n\tcrop.height === image.height;\n\n/**\n * One picture from an upload: checked by its first bytes, the optional\n * rectangle `crop` kept, resized to `width` x `height` (never enlarged) and\n * encoded as JPEG, WebP or PNG with every metadata stripped. Same limits,\n * orientation and refusals as `ImageSet.process`; `INVALID_CROP` for a\n * rectangle that is badly shaped or outside the picture, `TOO_SMALL` when the\n * crop is smaller than `width` x `height` on either side.\n *\n * ```ts\n * const { bytes, contentType } = await renderImage(blob, {\n * crop: { x: 0, y: 120, width: 1600, height: 900 },\n * width: 800,\n * height: 450,\n * format: 'jpeg',\n * });\n * ```\n */\nexport async function renderImage<F extends RenderFormat>(\n\tinput: ImageInput,\n\toptions: RenderOptions<F>,\n): Promise<RenderedImage<F>> {\n\tconst { width, height, quality, maxBytes, maxPixels } = checkOptions(options);\n\tconst { signal, crop } = options;\n\tsignal?.throwIfAborted();\n\tconst bytes = await readInput(input, maxBytes);\n\tsignal?.throwIfAborted();\n\tconst format = sniffFormat(bytes);\n\tif (format === undefined) {\n\t\tthrow new ImageError(\n\t\t\t'UNSUPPORTED_TYPE',\n\t\t\t'format',\n\t\t\t'the upload is not a JPEG, PNG, WebP or HEIC',\n\t\t);\n\t}\n\treturn limit(async () => {\n\t\tsignal?.throwIfAborted();\n\t\tconst image = await readDimensions(bytes, format, maxPixels);\n\t\tsignal?.throwIfAborted();\n\t\tif (crop !== undefined) assertRectFits(crop, image);\n\t\tconst kept = crop ?? image;\n\t\tif (kept.width < width || kept.height < height) {\n\t\t\tthrow new ImageError(\n\t\t\t\t'TOO_SMALL',\n\t\t\t\t'dimensions',\n\t\t\t\t`the ${crop ? 'crop' : 'image'} is ${kept.width}x${kept.height}, under the ${width}x${height} asked for`,\n\t\t\t);\n\t\t}\n\t\tconst target = { width, height };\n\t\tconst encoding = { format: options.format, quality, maxPixels };\n\t\tlet out: Uint8Array;\n\t\tif (crop === undefined || coversImage(crop, image)) {\n\t\t\tout = await encode(bytes, format, target, { ...encoding, upright: true });\n\t\t} else {\n\t\t\tconst png = await cropToPng(\n\t\t\t\tbytes,\n\t\t\t\tformat,\n\t\t\t\timage,\n\t\t\t\tcrop,\n\t\t\t\ttarget,\n\t\t\t\tmaxPixels,\n\t\t\t);\n\t\t\tsignal?.throwIfAborted();\n\t\t\tout = await encode(png, 'png', target, { ...encoding, upright: false });\n\t\t}\n\t\tsignal?.throwIfAborted();\n\t\treturn {\n\t\t\tsource: { format, ...image },\n\t\t\tbytes: out,\n\t\t\twidth,\n\t\t\theight,\n\t\t\tcontentType: RENDER_CONTENT_TYPES[options.format],\n\t\t};\n\t});\n}\n"
|
|
19
|
+
],
|
|
20
|
+
"mappings": ";;;;;AAAA;AACA;AAEA,IAAM,eAAe,UAAU,OAAO;AAW/B,IAAM,gBAAmC;AAAA,EAC/C;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAC3C;AAGO,SAAS,KAAK,CAAC,MAAc,MAA8B;AAAA,EACjE,MAAM,MAAM,IAAI,WAAW,KAAK,KAAK,MAAM;AAAA,EAC3C,MAAM,OAAO,IAAI,SAAS,IAAI,MAAM;AAAA,EACpC,KAAK,UAAU,GAAG,KAAK,MAAM;AAAA,EAC7B,SAAS,IAAI,EAAG,IAAI,GAAG;AAAA,IAAK,IAAI,IAAI,KAAK,KAAK,WAAW,CAAC;AAAA,EAC1D,IAAI,IAAI,MAAM,CAAC;AAAA,EACf,KAAK,UACJ,IAAI,KAAK,QACT,IAAI,KAAK,MAAM,IAAI,SAAS,GAAG,IAAI,KAAK,MAAM,C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AAM,YAAY;AAAA,IACxB,QAAQ,eAAe;AAAA,IACvB,MAAM,QAAQ,MAAM,eAAe,OAAO,QAAQ,SAAS;AAAA,IAC3D,QAAQ,eAAe;AAAA,IACvB,IAAI,SAAS;AAAA,MAAW,eAAe,MAAM,KAAK;AAAA,IAClD,MAAM,OAAO,QAAQ;AAAA,IACrB,IAAI,KAAK,QAAQ,SAAS,KAAK,SAAS,QAAQ;AAAA,MAC/C,MAAM,IAAI,YACT,aACA,cACA,OAAO,OAAO,SAAS,cAAc,KAAK,SAAS,KAAK,qBAAqB,SAAS,kBACvF;AAAA,IACD;AAAA,IACA,MAAM,SAAS,EAAE,OAAO,OAAO;AAAA,IAC/B,MAAM,WAAW,EAAE,QAAQ,QAAQ,QAAQ,SAAS,UAAU;AAAA,IAC9D,IAAI;AAAA,IACJ,IAAI,SAAS,aAAa,YAAY,MAAM,KAAK,GAAG;AAAA,MACnD,MAAM,MAAM,OAAO,OAAO,QAAQ,QAAQ,KAAK,UAAU,SAAS,KAAK,CAAC;AAAA,IACzE,EAAE,KAAK;AAAA,MACN,MAAM,MAAM,MAAM,WACjB,OACA,QACA,OACA,MACA,QACA,SACD;AAAA,MACA,QAAQ,eAAe;AAAA,MACvB,MAAM,MAAM,OAAO,KAAK,OAAO,QAAQ,KAAK,UAAU,SAAS,MAAM,CAAC;AAAA;AAAA,IAEvE,QAAQ,eAAe;AAAA,IACvB,OAAO;AAAA,MACN,QAAQ,EAAE,WAAW,MAAM;AAAA,MAC3B,OAAO;AAAA,MACP;AAAA,MACA;AAAA,MACA,aAAa,qBAAqB,QAAQ;AAAA,IAC3C;AAAA,GACA;AAAA;",
|
|
21
|
+
"debugId": "2CB4825C6688F53D64756E2164756E21",
|
|
22
|
+
"names": []
|
|
23
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// src/errors/image-error.ts
|
|
2
|
+
class ImageError2 extends Error {
|
|
3
|
+
code;
|
|
4
|
+
reason;
|
|
5
|
+
constructor(code, reason, message) {
|
|
6
|
+
super(message ?? `${code}: ${reason}`);
|
|
7
|
+
this.name = "ImageError";
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.reason = reason;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export { ImageError2 };
|
|
14
|
+
|
|
15
|
+
//# debugId=BEDE6C38667D0C8864756E2164756E21
|
|
16
|
+
//# sourceMappingURL=index-wfsrqqk2.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/errors/image-error.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * What went wrong. Each one is in the README's Errors table, and each\n * message it carries has an entry in `docs/troubleshooting.md`, headed by its\n * text.\n */\nexport type ImageErrorCode =\n\t/** The upload is bigger than the byte or pixel limit. */\n\t| 'TOO_LARGE'\n\t/**\n\t * The bytes are not a JPEG, PNG, WebP or HEIC, judged by their first bytes\n\t * and never by a file name or a declared content type — or a HEIC this\n\t * machine cannot decode.\n\t */\n\t| 'UNSUPPORTED_TYPE'\n\t/** The bytes look like an accepted format but cannot be decoded. */\n\t| 'UNDECODABLE'\n\t/** The image is smaller than the smallest side the caller asked for. */\n\t| 'TOO_SMALL'\n\t/**\n\t * The `crop` the caller sent is not three whole numbers of 0 or more, or\n\t * does not fit the image. It can come from a request, so it is a refusal\n\t * to answer with a 4xx, not a bug to answer with a 500.\n\t */\n\t| 'INVALID_CROP';\n\n/**\n * Why a refusal happened, for a caller that answers differently per cause.\n *\n * - `bytes`: the upload is over the byte limit.\n * - `pixels`: the image claims more pixels than the limit.\n * - `format`: the first bytes match no accepted format, or this machine\n * cannot decode the format they announce.\n * - `heic-unavailable`: a HEIC, on a machine whose Bun cannot decode one\n * (Linux; HEIC decodes on macOS and Windows only).\n * - `decode`: the format is right and the content is damaged or unsupported.\n * - `dimensions`: the image is under the smallest side asked for.\n * - `crop`: the crop is badly shaped, or does not fit the image.\n */\nexport type ImageErrorReason =\n\t| 'bytes'\n\t| 'pixels'\n\t| 'format'\n\t| 'heic-unavailable'\n\t| 'decode'\n\t| 'dimensions'\n\t| 'crop';\n\n/**\n * This package's error class for refusals. Every one of them is thrown\n * before anything is stored. A message names the cause and the limit, never\n * the uploaded bytes.\n */\nexport class ImageError extends Error {\n\treadonly code: ImageErrorCode;\n\treadonly reason: ImageErrorReason;\n\n\tconstructor(\n\t\tcode: ImageErrorCode,\n\t\treason: ImageErrorReason,\n\t\tmessage?: string,\n\t) {\n\t\tsuper(message ?? `${code}: ${reason}`);\n\t\tthis.name = 'ImageError';\n\t\tthis.code = code;\n\t\tthis.reason = reason;\n\t}\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AAoDO,MAAM,oBAAmB,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EAET,WAAW,CACV,MACA,QACA,SACC;AAAA,IACD,MAAM,WAAW,GAAG,SAAS,QAAQ;AAAA,IACrC,KAAK,OAAO;AAAA,IACZ,KAAK,OAAO;AAAA,IACZ,KAAK,SAAS;AAAA;AAEhB;",
|
|
8
|
+
"debugId": "BEDE6C38667D0C8864756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { RawImage } from './png.js';
|
|
2
|
+
/** A rectangle of pixels: `(x, y)` is its top-left corner. */
|
|
3
|
+
export type Region = {
|
|
4
|
+
x: number;
|
|
5
|
+
y: number;
|
|
6
|
+
width: number;
|
|
7
|
+
height: number;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Reads a region of what `Bun.Image(...).png()` emits (8-bit, not
|
|
11
|
+
* interlaced, grey, grey with alpha, RGB or RGBA, any of the five filters)
|
|
12
|
+
* while the PNG inflates, and stops after the region's last row. Grey is
|
|
13
|
+
* widened to RGB, grey with alpha to RGBA. Only two rows (the one above and
|
|
14
|
+
* the current one) are ever held, plus the region's own pixels, and the
|
|
15
|
+
* IDAT payloads are read in place, so the cost does not grow with the image.
|
|
16
|
+
* Every other chunk (colour profile, EXIF, text) is read past and dropped,
|
|
17
|
+
* which is how a re-encode strips them.
|
|
18
|
+
*
|
|
19
|
+
* The input is Bun's own PNG, never the user's bytes, so the rest of the file
|
|
20
|
+
* is trusted once the region is read: a cut file, a missing IEND, a bad CRC
|
|
21
|
+
* or a bad zlib checksum after the region's last row is **not seen**. Only a
|
|
22
|
+
* region that reaches the image's last row reads on to the end of the zlib
|
|
23
|
+
* stream, checking its checksum and that no data is left over.
|
|
24
|
+
*
|
|
25
|
+
* `region` is a rectangle, or a function of the header's size, for a caller
|
|
26
|
+
* that knows the region only once it knows the size. `maxPixels` refuses a
|
|
27
|
+
* PNG whose header claims more pixels, before anything is inflated:
|
|
28
|
+
* `TOO_LARGE` with the reason `pixels`. Inflated data longer than the header
|
|
29
|
+
* promises is refused, as far as the stream is read.
|
|
30
|
+
*
|
|
31
|
+
* `onCancel` is called when the read stops before the end of the IDAT data
|
|
32
|
+
* (the region's last row is not the image's), after the stream is cancelled;
|
|
33
|
+
* it exists so a spec can see that the stream is released.
|
|
34
|
+
*/
|
|
35
|
+
export declare function cropPng(bytes: Uint8Array, region: Region | ((size: {
|
|
36
|
+
width: number;
|
|
37
|
+
height: number;
|
|
38
|
+
}) => Region), maxPixels?: number, onCancel?: () => void): Promise<RawImage>;
|
|
39
|
+
//# sourceMappingURL=crop-png.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crop-png.d.ts","sourceRoot":"","sources":["../../src/crop/crop-png.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAItC,8DAA8D;AAC9D,MAAM,MAAM,MAAM,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AA2C7E;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,OAAO,CAC5B,KAAK,EAAE,UAAU,EACjB,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,KAAK,MAAM,CAAC,EACtE,SAAS,CAAC,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,MAAM,IAAI,GACnB,OAAO,CAAC,QAAQ,CAAC,CAsDnB"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { CropBox } from '../set/types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The square crop an upload route reads from `?x=&y=&size=`.
|
|
4
|
+
*
|
|
5
|
+
* - None of the three present: `undefined`, the default centred crop.
|
|
6
|
+
* - Otherwise a `CropBox`, where a missing, blank or non-numeric value is
|
|
7
|
+
* `NaN`. Nothing is validated here: the set refuses it as `INVALID_CROP`,
|
|
8
|
+
* a refusal to answer with a 4xx.
|
|
9
|
+
*/
|
|
10
|
+
export declare function cropFromQuery(params: URLSearchParams): CropBox | undefined;
|
|
11
|
+
//# sourceMappingURL=from-query.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"from-query.d.ts","sourceRoot":"","sources":["../../src/crop/from-query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAS5C;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,GAAG,SAAS,CAO1E"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { ImageError } from '../errors/image-error.js';
|
|
2
|
+
export declare function refuse(why: string): ImageError;
|
|
3
|
+
/** What the header says, once it is checked against what this reader takes. */
|
|
4
|
+
export type PngHeader = {
|
|
5
|
+
width: number;
|
|
6
|
+
height: number;
|
|
7
|
+
/** Samples per pixel as stored: 1 (grey), 2, 3 or 4. */
|
|
8
|
+
samples: number;
|
|
9
|
+
};
|
|
10
|
+
/** The chunk at `at`: its type, a view of its data, and where the next starts. */
|
|
11
|
+
export declare function chunkAt(bytes: Uint8Array, at: number): {
|
|
12
|
+
type: string;
|
|
13
|
+
data: Uint8Array;
|
|
14
|
+
next: number;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The signature and the header: 8-bit, not interlaced, grey, grey with
|
|
18
|
+
* alpha, RGB or RGBA. `maxPixels` refuses a header that claims more, as
|
|
19
|
+
* `TOO_LARGE` with the reason `pixels`, before anything is inflated.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readHeader(bytes: Uint8Array, maxPixels?: number): PngHeader;
|
|
22
|
+
/**
|
|
23
|
+
* The zlib stream of the file as a stream of views of its IDAT payloads, read
|
|
24
|
+
* lazily and never copied. A damaged chunk errors the stream with its
|
|
25
|
+
* `ImageError`. `onCancel` is called when the reader gives up before the end,
|
|
26
|
+
* a seam for a spec that proves an early stop releases the stream.
|
|
27
|
+
*/
|
|
28
|
+
export declare function idatStream(bytes: Uint8Array, onCancel?: () => void): ReadableStream<Uint8Array>;
|
|
29
|
+
//# sourceMappingURL=png-chunks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"png-chunks.d.ts","sourceRoot":"","sources":["../../src/crop/png-chunks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAGnD,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAM9C;AAED,+EAA+E;AAC/E,MAAM,MAAM,SAAS,GAAG;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,kFAAkF;AAClF,wBAAgB,OAAO,CACtB,KAAK,EAAE,UAAU,EACjB,EAAE,EAAE,MAAM,GACR;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAUlD;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CA6B3E;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CACzB,KAAK,EAAE,UAAU,EACjB,QAAQ,CAAC,EAAE,MAAM,IAAI,GACnB,cAAc,CAAC,UAAU,CAAC,CA4B5B"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Decoded pixels, row after row, `channels` bytes each: RGB or RGBA. */
|
|
2
|
+
export type RawImage = {
|
|
3
|
+
width: number;
|
|
4
|
+
height: number;
|
|
5
|
+
channels: 3 | 4;
|
|
6
|
+
pixels: Uint8Array;
|
|
7
|
+
};
|
|
8
|
+
/** The eight bytes every PNG starts with. */
|
|
9
|
+
export declare const PNG_SIGNATURE: readonly number[];
|
|
10
|
+
/** One PNG chunk: length, type, data and CRC. */
|
|
11
|
+
export declare function chunk(type: string, data: Uint8Array): Uint8Array;
|
|
12
|
+
/**
|
|
13
|
+
* A PNG of these pixels: IHDR, one IDAT (filter 0 on every row) and IEND,
|
|
14
|
+
* with their CRCs, and nothing else, so no metadata can be in it.
|
|
15
|
+
*
|
|
16
|
+
* The deflate runs on zlib's thread pool, not the main thread: a large crop
|
|
17
|
+
* stopped the event loop for 1.1 s synchronously (`[4096]` on 36 MP; 0.3 s
|
|
18
|
+
* after). It costs memory, though: the async encode adds memory at the peak,
|
|
19
|
+
* because the deflate input and output are held together; the figures above,
|
|
20
|
+
* measured on the async build, include it. It is level 1, since this PNG only lives for one pipeline
|
|
21
|
+
* step (it is decoded again at once), so speed beats size.
|
|
22
|
+
*/
|
|
23
|
+
export declare function encodePng(image: RawImage): Promise<Uint8Array>;
|
|
24
|
+
//# sourceMappingURL=png.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"png.d.ts","sourceRoot":"","sources":["../../src/crop/png.ts"],"names":[],"mappings":"AAKA,yEAAyE;AACzE,MAAM,MAAM,QAAQ,GAAG;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC;IAChB,MAAM,EAAE,UAAU,CAAC;CACnB,CAAC;AAEF,6CAA6C;AAC7C,eAAO,MAAM,aAAa,EAAE,SAAS,MAAM,EAE1C,CAAC;AAEF,iDAAiD;AACjD,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,UAAU,CAWhE;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CA6BpE"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns inflated bytes, in chunks of any size, into unfiltered rows. It holds
|
|
3
|
+
* the row above and the row being filled (`stride + 1` bytes each, the filter
|
|
4
|
+
* byte first) and nothing else.
|
|
5
|
+
*
|
|
6
|
+
* `feed(part)` calls `onRow(row, y)` for each finished row, `row` being the
|
|
7
|
+
* buffer with the filter byte at 0 and the pixels from 1; the buffer is
|
|
8
|
+
* reused, so `onRow` copies what it keeps. `onRow` returns `false` to stop:
|
|
9
|
+
* `feed` then returns `false` too and reads no further. A refusal is thrown as
|
|
10
|
+
* an `ImageError`: an unknown filter, or more rows than the header promises.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createRowAssembler(stride: number, height: number, bpp: number, onRow: (row: Uint8Array, y: number) => boolean): {
|
|
13
|
+
/** The rows finished so far. */
|
|
14
|
+
readonly rows: number;
|
|
15
|
+
feed(part: Uint8Array): boolean;
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=row-assembler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"row-assembler.d.ts","sourceRoot":"","sources":["../../src/crop/row-assembler.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,CAAC,EAAE,MAAM,KAAK,OAAO;IAQ7C,gCAAgC;;eAIrB,UAAU,GAAG,OAAO;EAyBhC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Undoes one PNG row filter (spec section 9), in place. `row` holds the
|
|
3
|
+
* filtered bytes of one row, `previous` the unfiltered row above it (all zero
|
|
4
|
+
* for the first row), both `stride` bytes long from `offset`; `bpp` is the
|
|
5
|
+
* bytes per pixel.
|
|
6
|
+
*
|
|
7
|
+
* Returns `false` for a filter type the spec does not define.
|
|
8
|
+
*/
|
|
9
|
+
export declare function unfilterRow(type: number, row: Uint8Array, previous: Uint8Array, offset: number, stride: number, bpp: number): boolean;
|
|
10
|
+
//# sourceMappingURL=unfilter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unfilter.d.ts","sourceRoot":"","sources":["../../src/crop/unfilter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAC1B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,UAAU,EACf,QAAQ,EAAE,UAAU,EACpB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,GACT,OAAO,CAmCT"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What went wrong. Each one is in the README's Errors table, and each
|
|
3
|
+
* message it carries has an entry in `docs/troubleshooting.md`, headed by its
|
|
4
|
+
* text.
|
|
5
|
+
*/
|
|
6
|
+
export type ImageErrorCode =
|
|
7
|
+
/** The upload is bigger than the byte or pixel limit. */
|
|
8
|
+
'TOO_LARGE'
|
|
9
|
+
/**
|
|
10
|
+
* The bytes are not a JPEG, PNG, WebP or HEIC, judged by their first bytes
|
|
11
|
+
* and never by a file name or a declared content type — or a HEIC this
|
|
12
|
+
* machine cannot decode.
|
|
13
|
+
*/
|
|
14
|
+
| 'UNSUPPORTED_TYPE'
|
|
15
|
+
/** The bytes look like an accepted format but cannot be decoded. */
|
|
16
|
+
| 'UNDECODABLE'
|
|
17
|
+
/** The image is smaller than the smallest side the caller asked for. */
|
|
18
|
+
| 'TOO_SMALL'
|
|
19
|
+
/**
|
|
20
|
+
* The `crop` the caller sent is not three whole numbers of 0 or more, or
|
|
21
|
+
* does not fit the image. It can come from a request, so it is a refusal
|
|
22
|
+
* to answer with a 4xx, not a bug to answer with a 500.
|
|
23
|
+
*/
|
|
24
|
+
| 'INVALID_CROP';
|
|
25
|
+
/**
|
|
26
|
+
* Why a refusal happened, for a caller that answers differently per cause.
|
|
27
|
+
*
|
|
28
|
+
* - `bytes`: the upload is over the byte limit.
|
|
29
|
+
* - `pixels`: the image claims more pixels than the limit.
|
|
30
|
+
* - `format`: the first bytes match no accepted format, or this machine
|
|
31
|
+
* cannot decode the format they announce.
|
|
32
|
+
* - `heic-unavailable`: a HEIC, on a machine whose Bun cannot decode one
|
|
33
|
+
* (Linux; HEIC decodes on macOS and Windows only).
|
|
34
|
+
* - `decode`: the format is right and the content is damaged or unsupported.
|
|
35
|
+
* - `dimensions`: the image is under the smallest side asked for.
|
|
36
|
+
* - `crop`: the crop is badly shaped, or does not fit the image.
|
|
37
|
+
*/
|
|
38
|
+
export type ImageErrorReason = 'bytes' | 'pixels' | 'format' | 'heic-unavailable' | 'decode' | 'dimensions' | 'crop';
|
|
39
|
+
/**
|
|
40
|
+
* This package's error class for refusals. Every one of them is thrown
|
|
41
|
+
* before anything is stored. A message names the cause and the limit, never
|
|
42
|
+
* the uploaded bytes.
|
|
43
|
+
*/
|
|
44
|
+
export declare class ImageError extends Error {
|
|
45
|
+
readonly code: ImageErrorCode;
|
|
46
|
+
readonly reason: ImageErrorReason;
|
|
47
|
+
constructor(code: ImageErrorCode, reason: ImageErrorReason, message?: string);
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=image-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-error.d.ts","sourceRoot":"","sources":["../../src/errors/image-error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,cAAc;AACzB,yDAAyD;AACvD,WAAW;AACb;;;;GAIG;GACD,kBAAkB;AACpB,oEAAoE;GAClE,aAAa;AACf,wEAAwE;GACtE,WAAW;AACb;;;;GAIG;GACD,cAAc,CAAC;AAElB;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,gBAAgB,GACzB,OAAO,GACP,QAAQ,GACR,QAAQ,GACR,kBAAkB,GAClB,QAAQ,GACR,YAAY,GACZ,MAAM,CAAC;AAEV;;;;GAIG;AACH,qBAAa,UAAW,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC;gBAGjC,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE,gBAAgB,EACxB,OAAO,CAAC,EAAE,MAAM;CAOjB"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { cropFromQuery } from './crop/from-query.js';
|
|
2
|
+
export type { ImageErrorCode, ImageErrorReason } from './errors/image-error.js';
|
|
3
|
+
export { ImageError } from './errors/image-error.js';
|
|
4
|
+
export type { ImageInput } from './input/read-input.js';
|
|
5
|
+
export type { CropRect, RenderedImage, RenderFormat, RenderOptions, } from './render/render-image.js';
|
|
6
|
+
export { renderImage } from './render/render-image.js';
|
|
7
|
+
export { defineImageSet } from './set/define-image-set.js';
|
|
8
|
+
export type { ImageContentType, ImageFormat, ImageSetOptions, } from './set/options.js';
|
|
9
|
+
export type { CropBox, ImageSet, ImageVariant, ProcessedImage, ProcessOptions, } from './set/types.js';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,YAAY,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,YAAY,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,YAAY,EACX,QAAQ,EACR,aAAa,EACb,YAAY,EACZ,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,YAAY,EACX,gBAAgB,EAChB,WAAW,EACX,eAAe,GACf,MAAM,eAAe,CAAC;AACvB,YAAY,EACX,OAAO,EACP,QAAQ,EACR,YAAY,EACZ,cAAc,EACd,cAAc,GACd,MAAM,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import {
|
|
2
|
+
contentTypeOf,
|
|
3
|
+
resolveOptions,
|
|
4
|
+
processImage,
|
|
5
|
+
createLimit,
|
|
6
|
+
renderImage2
|
|
7
|
+
} from "./chunks/index-pj79f6q4.js";
|
|
8
|
+
import {
|
|
9
|
+
cropFromQuery2
|
|
10
|
+
} from "./chunks/index-b71y3faz.js";
|
|
11
|
+
import {
|
|
12
|
+
ImageError2
|
|
13
|
+
} from "./chunks/index-wfsrqqk2.js";
|
|
14
|
+
// src/set/runtime.ts
|
|
15
|
+
function assertBunImage(bun) {
|
|
16
|
+
if (typeof bun === "undefined" || bun === null || typeof bun.Image !== "function") {
|
|
17
|
+
throw new TypeError("@softistx/image needs Bun 1.4.1 or later, where Bun.Image exists");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/set/define-image-set.ts
|
|
22
|
+
function defineImageSet(options = {}) {
|
|
23
|
+
assertBunImage(typeof Bun === "undefined" ? undefined : Bun);
|
|
24
|
+
const resolved = resolveOptions(options);
|
|
25
|
+
const limit = createLimit(resolved.concurrency);
|
|
26
|
+
const format = resolved.format;
|
|
27
|
+
return {
|
|
28
|
+
sizes: resolved.sizes,
|
|
29
|
+
format,
|
|
30
|
+
contentType: contentTypeOf(format),
|
|
31
|
+
process: (input, processOptions = {}) => processImage(input, processOptions, resolved, limit)
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
ImageError2 as ImageError,
|
|
36
|
+
cropFromQuery2 as cropFromQuery,
|
|
37
|
+
defineImageSet,
|
|
38
|
+
renderImage2 as renderImage
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
//# debugId=89A7FB280E362ADA64756E2164756E21
|
|
42
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/set/runtime.ts", "../src/set/define-image-set.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Throws a clear `TypeError` when the runtime has no `Bun.Image` (Bun older\n * than 1.4.1, or not Bun at all). Takes the `Bun` global as an argument so it\n * can be tested without touching the real one.\n */\nexport function assertBunImage(bun: unknown): void {\n\tif (\n\t\ttypeof bun === 'undefined' ||\n\t\tbun === null ||\n\t\ttypeof (bun as { Image?: unknown }).Image !== 'function'\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'@softistx/image needs Bun 1.4.1 or later, where Bun.Image exists',\n\t\t);\n\t}\n}\n",
|
|
6
|
+
"import { processImage } from '../process/process';\nimport { createLimit } from './limit';\nimport {\n\tcontentTypeOf,\n\ttype ImageFormat,\n\ttype ImageSetOptions,\n\tresolveOptions,\n} from './options';\nimport { assertBunImage } from './runtime';\nimport type { ImageSet } from './types';\n\n/**\n * An image set: what to make of an upload, defined once.\n *\n * ```ts\n * const avatars = defineImageSet({ sizes: [256, 64] });\n * const { variants } = await avatars.process(await request.blob());\n * ```\n *\n * The set's type follows `options.format`: `defineImageSet()` is an\n * `ImageSet<'webp'>`, `defineImageSet({ format: 'png' })` an `ImageSet<'png'>`.\n *\n * Throws a `TypeError` on a Bun older than 1.4.1, where `Bun.Image` is missing.\n * Invalid options throw a `TypeError` here, naming the option.\n */\nexport function defineImageSet(\n\toptions?: ImageSetOptions & { format?: 'webp' },\n): ImageSet<'webp'>;\nexport function defineImageSet<F extends ImageFormat>(\n\toptions: ImageSetOptions & { format: F },\n): ImageSet<F>;\n/** Options whose format is only known as `ImageFormat`: a set of either. */\nexport function defineImageSet(options?: ImageSetOptions): ImageSet;\nexport function defineImageSet(options: ImageSetOptions = {}): ImageSet {\n\tassertBunImage(typeof Bun === 'undefined' ? undefined : Bun);\n\tconst resolved = resolveOptions(options);\n\tconst limit = createLimit(resolved.concurrency);\n\t// The overloads tie the set's type to `options.format`, which\n\t// `resolveOptions` checked: no type argument can name another format,\n\t// since only the overload that takes `F` from a given `format` is generic.\n\tconst format = resolved.format;\n\treturn {\n\t\tsizes: resolved.sizes,\n\t\tformat,\n\t\tcontentType: contentTypeOf(format),\n\t\tprocess: (input, processOptions = {}) =>\n\t\t\tprocessImage(input, processOptions, resolved, limit),\n\t};\n}\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";;;;;;;;;;;;;;AAKO,SAAS,cAAc,CAAC,KAAoB;AAAA,EAClD,IACC,OAAO,QAAQ,eACf,QAAQ,QACR,OAAQ,IAA4B,UAAU,YAC7C;AAAA,IACD,MAAM,IAAI,UACT,kEACD;AAAA,EACD;AAAA;;;ACmBM,SAAS,cAAc,CAAC,UAA2B,CAAC,GAAa;AAAA,EACvE,eAAe,OAAO,QAAQ,cAAc,YAAY,GAAG;AAAA,EAC3D,MAAM,WAAW,eAAe,OAAO;AAAA,EACvC,MAAM,QAAQ,YAAY,SAAS,WAAW;AAAA,EAI9C,MAAM,SAAS,SAAS;AAAA,EACxB,OAAO;AAAA,IACN,OAAO,SAAS;AAAA,IAChB;AAAA,IACA,aAAa,cAAc,MAAM;AAAA,IACjC,SAAS,CAAC,OAAO,iBAAiB,CAAC,MAClC,aAAa,OAAO,gBAAgB,UAAU,KAAK;AAAA,EACrD;AAAA;",
|
|
9
|
+
"debugId": "89A7FB280E362ADA64756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type ImageInput = Uint8Array | ArrayBuffer | Blob | ReadableStream<Uint8Array>;
|
|
2
|
+
/**
|
|
3
|
+
* The upload's bytes, refused as soon as they pass `maxBytes`. A size known
|
|
4
|
+
* up front (bytes, a buffer, a `Blob`) is checked before anything is read, and
|
|
5
|
+
* a `Blob`'s again once read; a `Blob` of no known size and a stream are
|
|
6
|
+
* read chunk by chunk and cancelled at the chunk that crosses the cap, so no
|
|
7
|
+
* more than the cap plus one chunk is ever held.
|
|
8
|
+
*/
|
|
9
|
+
export declare function readInput(input: ImageInput, maxBytes: number): Promise<Uint8Array>;
|
|
10
|
+
//# sourceMappingURL=read-input.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read-input.d.ts","sourceRoot":"","sources":["../../src/input/read-input.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,UAAU,GACnB,UAAU,GACV,WAAW,GACX,IAAI,GACJ,cAAc,CAAC,UAAU,CAAC,CAAC;AA4C9B;;;;;;GAMG;AACH,wBAAsB,SAAS,CAC9B,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,MAAM,GACd,OAAO,CAAC,UAAU,CAAC,CAwBrB"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type SniffedFormat = 'jpeg' | 'png' | 'webp' | 'heic';
|
|
2
|
+
/**
|
|
3
|
+
* The format the first bytes announce, or `undefined`. Magic bytes only: a
|
|
4
|
+
* file name and a declared content type are what the uploader chose. Short or
|
|
5
|
+
* truncated input is `undefined`, never an error. AVIF is refused here, since
|
|
6
|
+
* it is not an accepted input.
|
|
7
|
+
*/
|
|
8
|
+
export declare function sniffFormat(bytes: Uint8Array): SniffedFormat | undefined;
|
|
9
|
+
//# sourceMappingURL=sniff.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sniff.d.ts","sourceRoot":"","sources":["../../src/input/sniff.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;AAqC7D;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,aAAa,GAAG,SAAS,CAcxE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pdf/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACX,QAAQ,EACR,gBAAgB,EAChB,gBAAgB,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC"}
|