react-smart-copy 1.12.0 → 1.13.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/README.md CHANGED
@@ -29,6 +29,7 @@ ID PLT-29018 [Copy]
29
29
  - **`react-smart-copy/structured`**: copy your own objects and paste them back as the same typed, validated objects in another tab or app, the way design tools do. Versioned, with migrations, and works with Zod, Valibot or ArkType
30
30
  - **`react-smart-copy/markdown`**: paste from Google Docs, Word, Notion or any web page into a Markdown field and get clean Markdown, with undo intact: `<textarea onPaste={pasteAsMarkdown} />`
31
31
  - **`react-smart-copy/code`**: copy code blocks the way developers expect (a terminal session copies as its commands, gutters and prompts stay behind, colours survive in Docs and Slack), paste code cleaned and indented, and catch Trojan Source, invisible identifiers and lookalike letters
32
+ - **`react-smart-copy/image`**: get pasted photos and screenshots ready to upload. It removes GPS location, camera data and hidden thumbnails without touching a pixel, and fits size and byte limits, re-encoding only when it has to
32
33
  - **`react-smart-copy/capture`**: copy an `<svg>` or any piece of your UI as a PNG
33
34
  - Every failure is a typed, classified error. Nothing silently no-ops
34
35
  - Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
@@ -49,6 +50,7 @@ This package only promises what browsers actually support.
49
50
  | Your app's own data (typed) | ✅ | `react-smart-copy/structured`: a web custom format, a custom type and an HTML envelope, so every browser and paste path gets one |
50
51
  | Rich text as Markdown | ✅ paste | `react-smart-copy/markdown`: CommonMark + GFM from Docs, Word, web pages and mail; plain-text pastes stay untouched |
51
52
  | Code (blocks, sessions, diffs) | ✅ | `react-smart-copy/code`: plain text plus monospaced, highlighted HTML; commands without prompts or output; Trojan Source checks on paste |
53
+ | Pasted images, made safe | ✅ paste | `react-smart-copy/image`: removes location and camera metadata losslessly; resizes and compresses under a byte budget |
52
54
  | SVG (icons, charts, logos) | ✅ as PNG | `svgToPngBlob()` from `react-smart-copy/capture` rasterises natively, no dependency. Raw SVG is not a clipboard image format |
53
55
  | A section of your UI as an image | ✅ bring a rasteriser | Browsers have no "screenshot this element" API. `captureElement()` wraps one you choose (e.g. `modern-screenshot`) with limits and checks |
54
56
  | Files (PDF, DOCX, ZIP) | ❌ | Not writable to the system clipboard by any browser API |
@@ -615,7 +617,7 @@ coercing schema (`z.coerce.date()`), or convert in `encode`.
615
617
  `react-smart-copy/markdown` turns what people paste into comment boxes, editors and CMS
616
618
  fields into clean Markdown: headings, bold and italic, links, lists (nested and task
617
619
  lists), tables, code blocks and quotes, from Google Docs, Word, Notion, GitHub, web pages
618
- and mail. No dependencies, about 7.3 kB.
620
+ and mail. No dependencies, about 7.6 kB.
619
621
 
620
622
  ```tsx
621
623
  import { pasteAsMarkdown } from "react-smart-copy/markdown";
@@ -756,6 +758,87 @@ inertly and only its text is used.
756
758
  | `html` / `language` (copy) | `true` / none | add the HTML flavour; `class="language-…"` on `<code>` |
757
759
  | `indentToCursor` / `onPaste` (`pasteAsCode`) | `true` / none | |
758
760
 
761
+ ## Pasted images: private and small
762
+
763
+ `react-smart-copy/image` gets pasted and dropped images ready to upload. A photo from a
764
+ phone usually carries the exact location it was taken, the device and its serial number,
765
+ and an embedded preview that can show what was cropped out. This module removes that
766
+ data, and makes the image fit your size and byte limits. No dependencies, about 7.3 kB
767
+ (about 4.8 kB for the server-safe `stripMetadata` and `readImageInfo`).
768
+
769
+ ```ts
770
+ import { usePaste } from "react-smart-copy";
771
+ import { prepareImage } from "react-smart-copy/image";
772
+
773
+ usePaste({
774
+ accept: ["image"],
775
+ onPaste: async ({ imageFiles }) => {
776
+ const image = await prepareImage(imageFiles[0], { maxWidth: 2048, maxBytes: 1_000_000 });
777
+ upload(image.file); // a File named like the original, metadata removed
778
+ if (image.original.info.metadata.includes("gps")) notice("Location removed from the photo.");
779
+ },
780
+ });
781
+ ```
782
+
783
+ **Lossless whenever it can be.** When only the metadata has to go, nothing is
784
+ re-encoded. JPEG, PNG, WebP and GIF are rewritten without their metadata, and every
785
+ pixel stays the same, so screenshots stay sharp and photos lose no quality. The image is
786
+ decoded and encoded again only when it has to change: to fit `maxWidth`, `maxHeight`,
787
+ `maxPixels` or `maxBytes`, to change its format, or because it is AVIF or HEIC.
788
+
789
+ **What is removed:** Exif (camera, lens, dates, serial numbers), the GPS location, embedded
790
+ thumbnails, XMP (edit history, authors), IPTC (captions, credits), comments, PNG text chunks,
791
+ multi-picture and depth images (MPF), content credentials (C2PA), and data appended after
792
+ the image (motion-photo videos). The colour profile is kept (`keepColorProfile: false`
793
+ removes it). The orientation is kept in a 26-byte Exif block holding nothing else, so a
794
+ photo still displays the right way up (`keepOrientation: false` removes it).
795
+
796
+ **Fits a byte budget.** For `maxBytes`, JPEG and WebP search for the highest quality that
797
+ fits (down to `minQuality`, 0.5 by default), and only then reduce the size. A screenshot
798
+ stays PNG when it fits. When it doesn't, `type: "auto"` turns it into WebP, or JPEG where
799
+ the browser can't encode WebP. If the limit can't be met, you get a `too-large` error,
800
+ never a file that is still too big. Large reductions are drawn in halving steps, so text
801
+ and edges stay clean.
802
+
803
+ **Safe with hostile files.** The format is read from the bytes, never from the file name
804
+ or the claimed type. Sizes come from the header and are checked against
805
+ `maxInputPixels` (100 million) *before* decoding, which stops decompression bombs. Every
806
+ parser read is bounded by its own box or chunk. Fuzz tests feed random and mutated files
807
+ to every parser. Animations keep every frame by default (`animated: "keep"`): a resize
808
+ they would need is a `too-large` error, `"first-frame"` makes a still image, and
809
+ `"reject"` refuses them. Every failure is a typed error: `too-large`,
810
+ `unsupported-format`, `unsupported` (re-encoding outside a browser), `timeout` or
811
+ `aborted` (`signal`).
812
+
813
+ ```ts
814
+ import { readImageInfo, stripMetadata } from "react-smart-copy/image";
815
+
816
+ // Anywhere, including the server (Node 18+): no decoding, no canvas.
817
+ const info = await readImageInfo(file);
818
+ // { format: "jpeg", width: 4032, height: 3024, orientation: 6, animated: false,
819
+ // metadata: ["exif", "gps", "thumbnail", "icc", "other"] }
820
+
821
+ const { blob, removed } = await stripMetadata(file); // bit-for-bit the same picture
822
+ ```
823
+
824
+ | Option (`prepareImage`) | Default | |
825
+ | ----------------------- | ------- | - |
826
+ | `maxWidth` / `maxHeight` | none | only ever makes images smaller |
827
+ | `maxPixels` | 16,777,216 | Safari's canvas limit |
828
+ | `maxBytes` | none | quality first, then size; `too-large` when it can't |
829
+ | `type` | `"auto"` | `"image/jpeg"`, `"image/png"` or `"image/webp"` |
830
+ | `quality` / `minQuality` | 0.85 / 0.5 | JPEG and WebP |
831
+ | `background` | `"#fff"` | under transparent pixels in JPEG |
832
+ | `animated` | `"keep"` | `"first-frame"` or `"reject"` |
833
+ | `keepColorProfile` | `true` | re-encoded images are written in sRGB |
834
+ | `maxInputPixels` / `maxInputBytes` | 100,000,000 / 100 MiB | checked before decoding |
835
+ | `timeoutMs` / `signal` | 30 s / none | |
836
+ | `environment` | the browser | your own decoder (e.g. WebAssembly HEIC) or a test double |
837
+
838
+ `width` and `height` in the result are the displayed size. Browsers turn JPEG and PNG by
839
+ their orientation, and Chromium doesn't turn WebP. `removed` is read back from the
840
+ output, not assumed, because some browsers' encoders add their own colour profile.
841
+
759
842
  ## Only one "Copied" at a time
760
843
 
761
844
  Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
@@ -1205,7 +1288,8 @@ embedded webviews. Where a capability is missing you get a typed error, never a
1205
1288
  - ~~**1.9** `react-smart-copy/table` — Excel- and Sheets-ready copy and paste, AG Grid and TanStack Table adapters, typed record import~~ shipped
1206
1289
  - ~~**1.10** `react-smart-copy/structured` — typed, versioned, validated application data on the clipboard~~ shipped
1207
1290
  - ~~**1.11** `react-smart-copy/markdown` — paste rich content as Markdown, with undo intact~~ shipped
1208
- - **1.12** `react-smart-copy/code` — copy code blocks and sessions cleanly, paste code safely, detect Trojan Source and homoglyphs
1291
+ - ~~**1.12** `react-smart-copy/code` — copy code blocks and sessions cleanly, paste code safely, detect Trojan Source and homoglyphs~~ shipped
1292
+ - **1.13** `react-smart-copy/image` — pasted images without location or camera metadata, fitted to size and byte limits
1209
1293
 
1210
1294
  Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
1211
1295
 
@@ -1213,7 +1297,7 @@ Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://supr
1213
1297
 
1214
1298
  ```bash
1215
1299
  npm install
1216
- npm run verify # lint, types, 1,100+ tests at 100% coverage, build, publint + attw, size budgets
1300
+ npm run verify # lint, types, tests at 100% coverage, build, publint + attw, consumer types, size budgets
1217
1301
  npm run changeset # describe your change for the changelog
1218
1302
  npm run site:preview # docs site at http://localhost:3000
1219
1303
  ```
package/dist/code.cjs CHANGED
@@ -107,12 +107,64 @@ const TABLE = /* @__PURE__ */ new Map([
107
107
  [8725, rule("confusable-punctuation", "warning", "/", "DIVISION SLASH")],
108
108
  [894, rule("confusable-punctuation", "warning", ";", "GREEK QUESTION MARK")]
109
109
  ]);
110
- /**
111
- * Latin lookalikes for Cyrillic and Greek letters: these make a homoglyph attack.
112
- * Pairs of (letter, lookalike), written as escapes so this file holds no homoglyphs itself.
113
- */
114
- const LOOKALIKE_PAIRS = "аaеeіiјjоoрpсcуyхxѕsԁdԛqԝwһhӏlАAВBЕEКKМMНHОOРPСCТTХXУYІIЈJЅSԀDԚQԜWҺHӀIαaοoνvρpιiυuχxΑAΒBΕEΖZΗHΙIΚKΜMΝNΟOΡPΤTΥYΧX";
115
- const LOOKALIKES = /* @__PURE__ */ new Map(/* @__PURE__ */ Array.from({ length: 56 }, (_, at) => [LOOKALIKE_PAIRS.charAt(at * 2), LOOKALIKE_PAIRS.charAt(at * 2 + 1)]));
110
+ const LOOKALIKES = /* @__PURE__ */ new Map(/* @__PURE__ */ [
111
+ [1072, "a"],
112
+ [1077, "e"],
113
+ [1110, "i"],
114
+ [1112, "j"],
115
+ [1086, "o"],
116
+ [1088, "p"],
117
+ [1089, "c"],
118
+ [1091, "y"],
119
+ [1093, "x"],
120
+ [1109, "s"],
121
+ [1281, "d"],
122
+ [1307, "q"],
123
+ [1309, "w"],
124
+ [1211, "h"],
125
+ [1231, "l"],
126
+ [1040, "A"],
127
+ [1042, "B"],
128
+ [1045, "E"],
129
+ [1050, "K"],
130
+ [1052, "M"],
131
+ [1053, "H"],
132
+ [1054, "O"],
133
+ [1056, "P"],
134
+ [1057, "C"],
135
+ [1058, "T"],
136
+ [1061, "X"],
137
+ [1059, "Y"],
138
+ [1030, "I"],
139
+ [1032, "J"],
140
+ [1029, "S"],
141
+ [1280, "D"],
142
+ [1306, "Q"],
143
+ [1308, "W"],
144
+ [1210, "H"],
145
+ [1216, "I"],
146
+ [945, "a"],
147
+ [959, "o"],
148
+ [957, "v"],
149
+ [961, "p"],
150
+ [953, "i"],
151
+ [965, "u"],
152
+ [967, "x"],
153
+ [913, "A"],
154
+ [914, "B"],
155
+ [917, "E"],
156
+ [918, "Z"],
157
+ [919, "H"],
158
+ [921, "I"],
159
+ [922, "K"],
160
+ [924, "M"],
161
+ [925, "N"],
162
+ [927, "O"],
163
+ [929, "P"],
164
+ [932, "T"],
165
+ [933, "Y"],
166
+ [935, "X"]
167
+ ].map(([codePoint, latin]) => [String.fromCharCode(codePoint), latin]));
116
168
  const LATIN = /\p{Script=Latin}/u;
117
169
  const FOREIGN = /[\p{Script=Cyrillic}\p{Script=Greek}]/u;
118
170
  const FOREIGN_LETTER = /^[\p{Script=Cyrillic}\p{Script=Greek}]$/u;