react-smart-copy 1.9.0 → 1.10.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/README.md +89 -3
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.js.map +1 -1
- package/dist/core.cjs +43 -10
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +32 -4
- package/dist/core.d.ts +32 -4
- package/dist/core.js +41 -11
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +43 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -4
- package/dist/index.d.ts +32 -4
- package/dist/index.js +41 -11
- package/dist/index.js.map +1 -1
- package/dist/structured.cjs +552 -0
- package/dist/structured.cjs.map +1 -0
- package/dist/structured.d.cts +273 -0
- package/dist/structured.d.ts +273 -0
- package/dist/structured.js +545 -0
- package/dist/structured.js.map +1 -0
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +11 -0
- package/dist/testing.d.ts +11 -0
- package/dist/testing.js.map +1 -1
- package/package.json +42 -11
package/README.md
CHANGED
|
@@ -20,12 +20,13 @@ Phone +91 98xxx xxxxx [Copy]
|
|
|
20
20
|
ID PLT-29018 [Copy]
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
- **~3.
|
|
23
|
+
- **~3.5 kB** for `useCopy`, **~5.6 kB** for everything copy (min + brotli), zero runtime dependencies
|
|
24
24
|
- Copy text, rich HTML (with plain-text fallback), PNG images, JSON, multi-format
|
|
25
25
|
- **Paste** text, HTML and screenshots with `usePaste`: a Paste button or Ctrl/⌘+V, no permission prompt for keyboard paste
|
|
26
26
|
- **`<CopyGroup>`**: only one row shows "Copied" at a time
|
|
27
27
|
- **`useCopyInterceptor`**: control what Ctrl/⌘+C copies from your page — attribution, redaction, Excel-ready tables, no-copy zones
|
|
28
28
|
- **`react-smart-copy/table`**: copy rows that paste into Excel and Google Sheets as cells, and read pasted ranges back as typed records. Works with AG Grid, TanStack Table and any `<table>`
|
|
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
|
|
29
30
|
- **`react-smart-copy/capture`**: copy an `<svg>` or any piece of your UI as a PNG
|
|
30
31
|
- Every failure is a typed, classified error. Nothing silently no-ops
|
|
31
32
|
- Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
|
|
@@ -43,6 +44,7 @@ This package only promises what browsers actually support.
|
|
|
43
44
|
| JSON | ✅ | Serialised to text. JSON is not a native clipboard format |
|
|
44
45
|
| Tables (Excel, Sheets, Docs) | ✅ | `react-smart-copy/table`: an HTML table plus tab-separated text in one entry. Pasting reads both back |
|
|
45
46
|
| Several formats at once | ✅ | `kind: 'multi'`; each MIME type is checked with `ClipboardItem.supports()` first |
|
|
47
|
+
| 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 |
|
|
46
48
|
| SVG (icons, charts, logos) | ✅ as PNG | `svgToPngBlob()` from `react-smart-copy/capture` rasterises natively, no dependency. Raw SVG is not a clipboard image format |
|
|
47
49
|
| 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 |
|
|
48
50
|
| Files (PDF, DOCX, ZIP) | ❌ | Not writable to the system clipboard by any browser API |
|
|
@@ -163,6 +165,12 @@ copy({
|
|
|
163
165
|
copy(() => editor.getValue()); // resolved at click time, always the latest value
|
|
164
166
|
```
|
|
165
167
|
|
|
168
|
+
A `multi` item can be marked `optional: true`: it is written only when `ClipboardItem.supports()`
|
|
169
|
+
confirms its type, and skipped otherwise instead of failing the copy. That is how a web custom
|
|
170
|
+
format (`"web application/vnd.acme.rows+json"`, Chromium) rides along with HTML and text that
|
|
171
|
+
every browser writes. Copy and drag events skip web custom formats, which only the async
|
|
172
|
+
Clipboard API can write.
|
|
173
|
+
|
|
166
174
|
### Copying an image, including a piece of your UI
|
|
167
175
|
|
|
168
176
|
Pass a **function** that produces the Blob. It is called synchronously inside the click,
|
|
@@ -524,6 +532,80 @@ millions of cells. `toRecords` matches headers ignoring case, spacing and full-w
|
|
|
524
532
|
reports `missing` required columns and every cell whose `parse` threw, and never stops at the
|
|
525
533
|
first bad row.
|
|
526
534
|
|
|
535
|
+
## Structured data: copy objects, paste typed objects
|
|
536
|
+
|
|
537
|
+
`react-smart-copy/structured` puts your app's own data on the clipboard: invoice rows, a
|
|
538
|
+
dashboard widget, a form's configuration, a set of shapes. Paste it in another tab, another
|
|
539
|
+
window or another of your apps and you get the same typed objects back, validated against
|
|
540
|
+
your schema. Text editors, chat and mail get readable text and HTML instead. No dependencies,
|
|
541
|
+
about 1.9 kB for the copy side.
|
|
542
|
+
|
|
543
|
+
```tsx
|
|
544
|
+
import { z } from "zod"; // or Valibot, ArkType, any Standard Schema, or a plain function
|
|
545
|
+
import { useCopy, usePaste } from "react-smart-copy";
|
|
546
|
+
import { clipAccept, clipPayload, defineClipFormat, readClip } from "react-smart-copy/structured";
|
|
547
|
+
|
|
548
|
+
// Define each format once and share it between the copying and the pasting code.
|
|
549
|
+
export const InvoiceRows = defineClipFormat({
|
|
550
|
+
id: "acme.invoice-rows", // namespaced, stable: it names the clipboard type
|
|
551
|
+
version: 2,
|
|
552
|
+
schema: z.array(z.object({ id: z.string(), amount: z.number(), issued: z.coerce.date() })),
|
|
553
|
+
migrate: { 1: (rows) => upgradeFromV1(rows) }, // data from older deployments still pastes
|
|
554
|
+
text: (rows) => rows.map((row) => `${row.id}\t${row.amount}`).join("\n"),
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
function CopyRows({ rows }: { rows: Invoice[] }) {
|
|
558
|
+
const { copy } = useCopy();
|
|
559
|
+
return <button onClick={() => void copy(() => clipPayload(InvoiceRows, rows))}>Copy rows</button>;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function PasteRows({ onRows }: { onRows: (rows: Invoice[]) => void }) {
|
|
563
|
+
const { paste, targetProps } = usePaste<HTMLDivElement>({
|
|
564
|
+
accept: [...clipAccept(InvoiceRows), "text"],
|
|
565
|
+
onPaste: async (result) => {
|
|
566
|
+
const clip = await readClip(result, InvoiceRows);
|
|
567
|
+
switch (clip.status) {
|
|
568
|
+
case "ok": return onRows(clip.value); // typed, validated, migrated
|
|
569
|
+
case "invalid": return report(clip.issues); // [{ message, path }]
|
|
570
|
+
case "unsupported-version": return askToReload(); // written by a newer deployment
|
|
571
|
+
case "absent": return; // not ours: handle result.text if you like
|
|
572
|
+
}
|
|
573
|
+
},
|
|
574
|
+
});
|
|
575
|
+
return <div {...targetProps} tabIndex={0}>Paste rows here <button onClick={() => void paste()}>Paste</button></div>;
|
|
576
|
+
}
|
|
577
|
+
```
|
|
578
|
+
|
|
579
|
+
`clipPayload` works everywhere a payload does: `copy()`, a `useCopyInterceptor` transform (so
|
|
580
|
+
Ctrl/⌘+C on selected rows copies the objects) and a `useDragCopy` source. `readClip` reads from a
|
|
581
|
+
`PasteResult` (paste button, Ctrl/⌘+V, drops, `PasteField`), a raw `DataTransfer` or a payload.
|
|
582
|
+
Use `readClipSync` when you need the answer synchronously and your schema is synchronous.
|
|
583
|
+
|
|
584
|
+
**Why three carriers.** No single clipboard entry survives every path in every browser, so each
|
|
585
|
+
copy writes three and `readClip` takes the first that holds this format:
|
|
586
|
+
|
|
587
|
+
| Carrier | Written by | Read back by |
|
|
588
|
+
| ------- | ---------- | ------------ |
|
|
589
|
+
| `web application/vnd.<id>+json` | `copy()` in Chromium | the paste button (`clipboard.read()`), also across origins. Hidden from paste events |
|
|
590
|
+
| `application/vnd.<id>+json` | copy interceptor, drag | Ctrl/⌘+V and drops. Hidden from `clipboard.read()` |
|
|
591
|
+
| hidden envelope in `text/html` | every path | every path, every browser, including Safari and Firefox |
|
|
592
|
+
|
|
593
|
+
**Security.** The clipboard is untrusted input: any page or app can put any format on it, so
|
|
594
|
+
the data is never trusted, only checked.
|
|
595
|
+
|
|
596
|
+
- Each carrier is size-checked (`maxBytes`, default 8 MiB) before it is parsed or decoded
|
|
597
|
+
- Own `__proto__` keys are dropped while parsing, so merging pasted data can't swap a prototype
|
|
598
|
+
- Migrations run on untrusted data, then the schema validates the result; nothing unvalidated reaches `clip.value`
|
|
599
|
+
- The HTML carrier is found with a strict token match on a closed alphabet (`id;base64url`): no HTML parsing, no DOM
|
|
600
|
+
- Reading never throws for clipboard content: every outcome is a result
|
|
601
|
+
- The data is **not authenticated**. Validate it as you would a form submission, and check permissions server-side
|
|
602
|
+
- The HTML envelope travels wherever the HTML is pasted (a mail, a document), hidden but readable. Copy only what the user may share, or set `embedInHtml: false` (keyboard paste in Chromium and drops still work through the custom type)
|
|
603
|
+
|
|
604
|
+
**Copying is strict too.** The data must survive `JSON.stringify` unchanged: `NaN`, `Infinity`,
|
|
605
|
+
`BigInt`, `Map`, `Set`, functions and symbols throw an `invalid-payload` error naming the key
|
|
606
|
+
instead of turning silently into `null` or `{}`. Dates become ISO strings, so read them back with a
|
|
607
|
+
coercing schema (`z.coerce.date()`), or convert in `encode`.
|
|
608
|
+
|
|
527
609
|
## Only one "Copied" at a time
|
|
528
610
|
|
|
529
611
|
Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
|
|
@@ -617,6 +699,8 @@ Custom adapters resolve without `imageFiles` (`PasteReadResult`); the machine de
|
|
|
617
699
|
- `accept` defaults to `['text']`. Ask for `'html'`, `'image'`, exact types like `'application/pdf'`, or `'image/*'` explicitly
|
|
618
700
|
- Images are verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP); a "PNG" that isn't one is dropped
|
|
619
701
|
- SVG is never matched by a wildcard, it must be listed exactly as `'image/svg+xml'` (it is scriptable XML)
|
|
702
|
+
- Application data is never matched by a wildcard either: web custom formats (`'web application/vnd.acme.rows+json'`)
|
|
703
|
+
and `+json` types must be listed exactly, and arrive as strings. `clipAccept()` lists them for you
|
|
620
704
|
- `maxBytes` (default 32 MiB) and `maxItems` (default 32) are enforced before anything is decoded.
|
|
621
705
|
`maxBytes` counts UTF-8 bytes on every path, so `'日本'` costs 6 bytes whether it arrives
|
|
622
706
|
from a paste event, `readText()` or `read()`
|
|
@@ -953,7 +1037,8 @@ Plain text works wherever `navigator.clipboard.writeText` exists: Chromium 66+,
|
|
|
953
1037
|
Safari 13.1+. Rich HTML, PNG images and multi-format need `ClipboardItem`: Chromium 86+,
|
|
954
1038
|
Safari 13.1+, Firefox 127+. Keyboard paste (`targetProps`, `listenOnDocument`) and drag-and-drop
|
|
955
1039
|
(`dropTargetProps`, `PasteField.Zone`) work in every modern browser. The Paste button needs `navigator.clipboard.readText` (Chromium 66+, Safari 13.1+,
|
|
956
|
-
Firefox 125+) or `read()` for images (Chromium 86+, Safari 13.1+, Firefox 127+).
|
|
1040
|
+
Firefox 125+) or `read()` for images (Chromium 86+, Safari 13.1+, Firefox 127+). Web custom formats
|
|
1041
|
+
(`react-smart-copy/structured`'s first carrier) need Chromium 104+; elsewhere the HTML carrier is used. Check MDN for
|
|
957
1042
|
embedded webviews. Where a capability is missing you get a typed error, never a silent success.
|
|
958
1043
|
|
|
959
1044
|
## Roadmap
|
|
@@ -968,6 +1053,7 @@ embedded webviews. Where a capability is missing you get a typed error, never a
|
|
|
968
1053
|
- ~~**1.7** `useCopyInterceptor` / `registerCopyInterceptor` — attribution, redaction and no-copy zones for native Ctrl/⌘+C~~ shipped
|
|
969
1054
|
- ~~**1.8** `useDragCopy` / `registerDragCopy` — populate `DataTransfer` on drag-start; no Clipboard API needed~~ shipped
|
|
970
1055
|
- ~~**1.9** `react-smart-copy/table` — Excel- and Sheets-ready copy and paste, AG Grid and TanStack Table adapters, typed record import~~ shipped
|
|
1056
|
+
- **1.10** `react-smart-copy/structured` — typed, versioned, validated application data on the clipboard
|
|
971
1057
|
|
|
972
1058
|
Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
|
|
973
1059
|
|
|
@@ -975,7 +1061,7 @@ Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://supr
|
|
|
975
1061
|
|
|
976
1062
|
```bash
|
|
977
1063
|
npm install
|
|
978
|
-
npm run verify # lint, types,
|
|
1064
|
+
npm run verify # lint, types, 988 tests at 100% coverage, build, publint + attw, size budgets
|
|
979
1065
|
npm run changeset # describe your change for the changelog
|
|
980
1066
|
npm run site:preview # docs site at http://localhost:3000
|
|
981
1067
|
```
|
package/dist/capture.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capture.cjs","names":[],"sources":["../src/core/errors.ts","../src/capture/environment.ts","../src/capture/options.ts","../src/core/mime.ts","../src/core/payload.ts","../src/capture/deadline.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","import { copyFailure } from '../core/errors';\n\n/** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */\nexport interface DecodedImage {\n readonly source: unknown;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface PngTarget {\n /** Integer pixel size of the output. */\n readonly width: number;\n readonly height: number;\n /** CSS colour painted under the image, or `null` for transparency. */\n readonly background: string | null;\n}\n\n/**\n * Everything capture needs from the platform. The default uses the DOM;\n * inject your own for workers (OffscreenCanvas), native shells or tests.\n */\nexport interface CaptureEnvironment {\n readonly createObjectURL: (blob: Blob) => string;\n readonly revokeObjectURL: (url: string) => void;\n /** Serialises an `<svg>` element to markup. */\n readonly serializeSvg: (node: Element) => string;\n /** Decodes an image from a `blob:` or `data:` URL. */\n readonly loadImage: (url: string) => Promise<DecodedImage>;\n /** Draws the image scaled to `target` and encodes it as PNG. */\n readonly encodePng: (image: DecodedImage, target: PngTarget) => Promise<Blob>;\n}\n\nfunction loadImage(url: string): Promise<DecodedImage> {\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.decoding = 'async';\n image.onload = () => {\n resolve({ source: image, width: image.naturalWidth, height: image.naturalHeight });\n };\n image.onerror = () => {\n reject(copyFailure('blob-generation-failed', 'The image could not be decoded.'));\n };\n image.src = url;\n });\n}\n\nfunction encodePng(image: DecodedImage, target: PngTarget): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const canvas = document.createElement('canvas');\n canvas.width = target.width;\n canvas.height = target.height;\n const context = canvas.getContext('2d');\n if (!context) {\n reject(copyFailure('unsupported', 'Canvas 2D rendering is not available.'));\n return;\n }\n if (target.background !== null) {\n context.fillStyle = target.background;\n context.fillRect(0, 0, target.width, target.height);\n }\n context.drawImage(image.source as CanvasImageSource, 0, 0, target.width, target.height);\n // Throws SecurityError synchronously for tainted canvases; the executor turns that into a rejection.\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing (canvas too large?).'));\n }, 'image/png');\n });\n}\n\n/** The DOM-backed environment, or `null` outside a browser. */\nexport function getDefaultCaptureEnvironment(): CaptureEnvironment | null {\n if (\n typeof document === 'undefined' ||\n typeof Image !== 'function' ||\n typeof XMLSerializer !== 'function' ||\n typeof URL.createObjectURL !== 'function'\n ) {\n return null;\n }\n return {\n createObjectURL: (blob) => URL.createObjectURL(blob),\n revokeObjectURL: (url) => {\n URL.revokeObjectURL(url);\n },\n serializeSvg: (node) => new XMLSerializer().serializeToString(node),\n loadImage,\n encodePng,\n };\n}\n\nexport function resolveCaptureEnvironment(environment: CaptureEnvironment | undefined): CaptureEnvironment {\n const resolved = environment ?? getDefaultCaptureEnvironment();\n if (!resolved) {\n throw copyFailure('unsupported', 'Image capture needs a browser environment (document, Image, canvas).');\n }\n return resolved;\n}\n","import { copyFailure } from '../core/errors';\nimport type { CaptureEnvironment } from './environment';\n\nexport const DEFAULT_CAPTURE_SCALE = 2;\nexport const MAX_CAPTURE_SCALE = 10;\n/** 4096 × 4096: the canvas area limit of Safari/iOS, the strictest mainstream engine. */\nexport const DEFAULT_MAX_PIXELS = 16_777_216;\nexport const DEFAULT_CAPTURE_TIMEOUT_MS = 15_000;\n\nexport interface RenderOptions {\n /** Output width in CSS px (before `scale`). Omit to use the intrinsic size; set one side to keep the aspect ratio. */\n readonly width?: number;\n /** Output height in CSS px (before `scale`). */\n readonly height?: number;\n /** Pixel density multiplier, e.g. `window.devicePixelRatio`. Default 2 (crisp on HiDPI). Max 10. */\n readonly scale?: number;\n /** CSS colour under the image. Default `null` (transparent). */\n readonly background?: string | null;\n /** Refuse outputs larger than this many pixels (memory / DoS guard). Default 16 777 216. */\n readonly maxPixels?: number;\n /** Give up after this long. Default 15 000 ms. `Infinity` disables. */\n readonly timeoutMs?: number;\n /** Cancel the capture. */\n readonly signal?: AbortSignal;\n /** Platform hooks. Defaults to the DOM. */\n readonly environment?: CaptureEnvironment;\n}\n\nexport interface RenderSettings {\n readonly scale: number;\n readonly background: string | null;\n readonly maxPixels: number;\n readonly timeoutMs: number;\n}\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nconst isPositiveFinite = (value: number): boolean => Number.isFinite(value) && value > 0;\n\nexport function resolveRenderSettings(options: RenderOptions): RenderSettings {\n const scale = options.scale ?? DEFAULT_CAPTURE_SCALE;\n if (!isPositiveFinite(scale) || scale > MAX_CAPTURE_SCALE) {\n throw invalid(`\\`scale\\` must be > 0 and <= ${String(MAX_CAPTURE_SCALE)} (received ${String(scale)}).`);\n }\n const maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;\n if (!Number.isInteger(maxPixels) || maxPixels <= 0) {\n throw invalid(`\\`maxPixels\\` must be a positive integer (received ${String(maxPixels)}).`);\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_CAPTURE_TIMEOUT_MS;\n if (timeoutMs !== Infinity && !isPositiveFinite(timeoutMs)) {\n throw invalid(`\\`timeoutMs\\` must be > 0 or Infinity (received ${String(timeoutMs)}).`);\n }\n return { scale, background: options.background ?? null, maxPixels, timeoutMs };\n}\n\n/** Combines explicit `width`/`height` with an intrinsic size, keeping the aspect ratio when only one is set. */\nexport function resolveSize(intrinsic: Size | null, width: number | undefined, height: number | undefined): Size {\n for (const [name, value] of [\n ['width', width],\n ['height', height],\n ] as const) {\n if (value !== undefined && !isPositiveFinite(value)) {\n throw invalid(`\\`${name}\\` must be a positive number (received ${String(value)}).`);\n }\n }\n if (width !== undefined && height !== undefined) return { width, height };\n if (intrinsic === null) {\n throw invalid('The size to render is unknown: pass `width` and `height`, or give the source a size.');\n }\n if (width !== undefined) return { width, height: (width * intrinsic.height) / intrinsic.width };\n if (height !== undefined) return { width: (height * intrinsic.width) / intrinsic.height, height };\n return intrinsic;\n}\n\n/** Integer pixel size after scaling. Throws `too-large` past `maxPixels`. */\nexport function toPixelSize(size: Size, settings: Pick<RenderSettings, 'scale' | 'maxPixels'>): Size {\n const width = Math.max(1, Math.round(size.width * settings.scale));\n const height = Math.max(1, Math.round(size.height * settings.scale));\n assertPixelBudget(width, height, settings.maxPixels);\n return { width, height };\n}\n\nexport function assertPixelBudget(width: number, height: number, maxPixels: number): void {\n if (width * height > maxPixels) {\n throw copyFailure(\n 'too-large',\n `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \\`scale\\` or raise \\`maxPixels\\`.`,\n );\n }\n}\n","/**\n * MIME helpers shared by paste and capture. Everything that comes from the\n * clipboard is untrusted input, so types are normalised and validated before\n * they are compared, and image types are confirmed from the bytes themselves.\n */\n\n/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */\nconst MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\n/** SVG is XML that can carry scripts; it is never matched by a wildcard. */\nexport const SVG_MIME_TYPE = 'image/svg+xml';\n\n/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */\nexport function normalizeMimeType(value: string): string | null {\n const separator = value.indexOf(';');\n const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();\n return MIME_SHAPE.test(base) ? base : null;\n}\n\n/**\n * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\\/*`)?\n * Wildcards never match `image/svg+xml`: accepting SVG must be explicit.\n */\nexport function matchesMimePattern(mimeType: string, pattern: string): boolean {\n if (pattern === mimeType) return true;\n if (mimeType === SVG_MIME_TYPE) return false;\n if (pattern === '*/*') return true;\n return pattern.endsWith('/*') && mimeType.startsWith(pattern.slice(0, -1));\n}\n\n/** Types whose clipboard data is text and is therefore surfaced as a `string`. */\nexport function isTextualMimeType(mimeType: string): boolean {\n return (\n mimeType.startsWith('text/') ||\n mimeType === SVG_MIME_TYPE ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml'\n );\n}\n\n/** Raster image formats recognised from their leading bytes. */\nexport type RasterImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/avif';\n\nconst SNIFF_BYTES = 16;\n\nfunction startsWith(bytes: Uint8Array, signature: readonly number[], offset = 0): boolean {\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nconst ascii = (text: string): number[] => Array.from(text, (char) => char.charCodeAt(0));\n\nconst PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\nconst JPEG = [0xff, 0xd8, 0xff];\nconst GIF = ascii('GIF8');\nconst RIFF = ascii('RIFF');\nconst WEBP = ascii('WEBP');\nconst BMP = ascii('BM');\nconst FTYP_AVIF = ascii('ftypavif');\nconst FTYP_AVIS = ascii('ftypavis');\n\n/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */\nexport function sniffImageBytes(bytes: Uint8Array): RasterImageMimeType | null {\n if (startsWith(bytes, PNG)) return 'image/png';\n if (startsWith(bytes, JPEG)) return 'image/jpeg';\n if (startsWith(bytes, GIF)) return 'image/gif';\n if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return 'image/webp';\n if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return 'image/avif';\n if (startsWith(bytes, BMP)) return 'image/bmp';\n return null;\n}\n\n/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */\nexport async function sniffImageType(blob: Blob): Promise<RasterImageMimeType | null> {\n const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();\n return sniffImageBytes(new Uint8Array(head));\n}\n","import { CopyFailure, createCopyError, type CopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\n\n/** The only image MIME type with reliable cross-browser clipboard write support. */\nexport const IMAGE_MIME_TYPE = 'image/png';\n\n/**\n * An image as a Blob, a promise of one, or a function producing one.\n * Prefer the function form: it is invoked synchronously inside the user\n * gesture, which Safari requires for async image generation. The browser\n * adapter always passes an `OperationContext`: stop work once\n * `context.signal` aborts (reset, superseded, unmount). Optional in the type\n * so adapters that call sources themselves keep compiling.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);\n\nexport interface TextPayload {\n readonly kind: 'text';\n readonly value: string;\n}\n\nexport interface HtmlPayload {\n readonly kind: 'html';\n readonly html: string;\n /** Required plain-text fallback for targets that don't understand HTML. */\n readonly text: string;\n}\n\nexport interface ImagePayload {\n readonly kind: 'image';\n readonly blob: BlobSource;\n}\n\nexport interface JsonPayload {\n readonly kind: 'json';\n readonly value: unknown;\n /** `true` = 2-space indent, a number = that indent, falsy = compact. */\n readonly pretty?: boolean | number;\n}\n\nexport interface MultiPayloadItem {\n readonly mimeType: string;\n readonly data: string | Blob;\n}\n\nexport interface MultiPayload {\n readonly kind: 'multi';\n readonly items: readonly MultiPayloadItem[];\n}\n\nexport type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;\nexport type CopyPayloadKind = CopyPayload['kind'];\n\n/** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */\nexport type CopyInput = string | CopyPayload;\n\n/**\n * What `copy()` accepts. The function form is resolved synchronously at copy\n * time, so it always reads the latest value without re-rendering.\n */\nexport type CopySource = CopyInput | (() => CopyInput);\n\nexport function normalizePayload(input: CopyInput): CopyPayload {\n return typeof input === 'string' ? { kind: 'text', value: input } : input;\n}\n\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && value instanceof Blob) return true;\n const tag = Object.prototype.toString.call(value);\n return tag === '[object Blob]' || tag === '[object File]';\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/**\n * Structural validation. Typed callers can't produce most of these states,\n * but plain-JS callers and runtime data can, so the check is always on.\n */\nexport function validatePayload(payload: unknown): CopyError | null {\n if (typeof payload !== 'object' || payload === null) {\n return invalid('Copy input must be a string or a payload object.');\n }\n const candidate = payload as Record<string, unknown>;\n\n switch (candidate['kind']) {\n case 'text':\n return typeof candidate['value'] === 'string' && candidate['value'].length > 0\n ? null\n : invalid('Text payload must be a non-empty string.');\n case 'html':\n if (typeof candidate['html'] !== 'string' || candidate['html'].length === 0) {\n return invalid('HTML payload requires a non-empty `html` string.');\n }\n return typeof candidate['text'] === 'string' && candidate['text'].length > 0\n ? null\n : invalid('HTML payload requires a non-empty plain-text `text` fallback.');\n case 'image': {\n const source = candidate['blob'];\n return isBlob(source) || typeof source === 'function' || isThenable(source)\n ? null\n : invalid('Image payload requires a Blob, a Promise<Blob> or a function returning one.');\n }\n case 'json':\n return candidate['value'] === undefined ? invalid('JSON payload value is undefined.') : null;\n case 'multi': {\n const items = candidate['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const seen = new Set<string>();\n for (const item of items as unknown[]) {\n const entry = (typeof item === 'object' && item !== null ? item : {}) as Record<string, unknown>;\n const mimeType = entry['mimeType'];\n const data = entry['data'];\n if (typeof mimeType !== 'string' || mimeType.length === 0) {\n return invalid('Every multi item needs a non-empty `mimeType`.');\n }\n if (seen.has(mimeType)) return invalid(`Duplicate MIME type \"${mimeType}\" in multi payload.`);\n seen.add(mimeType);\n if (typeof data !== 'string' && !isBlob(data)) {\n return invalid(`Multi item \"${mimeType}\" must contain a string or a Blob.`);\n }\n }\n return null;\n }\n default:\n return invalid(`Unknown payload kind: ${String(candidate['kind'])}.`);\n }\n}\n\n/** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */\nexport function serializeJson(payload: JsonPayload): string {\n const indent =\n payload.pretty === true ? 2 : typeof payload.pretty === 'number' ? payload.pretty : undefined;\n // Typed as `string` by lib.d.ts, but returns undefined for functions, symbols and undefined.\n let text: unknown;\n try {\n text = JSON.stringify(payload.value, null, indent);\n } catch (cause) {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload could not be serialised (circular reference or BigInt?).', cause),\n );\n }\n if (typeof text !== 'string') {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload serialised to nothing (functions, symbols and undefined are not JSON).'),\n );\n }\n return text;\n}\n","import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n","import { copyFailure, isCopyFailure } from '../core/errors';\nimport { IMAGE_MIME_TYPE } from '../core/payload';\nimport { sniffImageType } from '../core/mime';\nimport { withDeadline } from './deadline';\nimport type { CaptureEnvironment } from './environment';\nimport { assertPixelBudget, type RenderSettings, type Size } from './options';\n\n/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */\nexport function classifyCaptureError(cause: unknown, label: string): unknown {\n return isCopyFailure(cause) ? cause : copyFailure('blob-generation-failed', `${label} failed.`, cause);\n}\n\n/**\n * Decodes an image Blob and re-encodes it as PNG at `target` (or its natural\n * size), within the deadline. The object URL is always revoked.\n */\nexport async function drawBlobToPng(\n blob: Blob,\n target: Size | null,\n settings: RenderSettings,\n environment: CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const url = environment.createObjectURL(blob);\n try {\n return await withDeadline(\n async () => {\n const image = await environment.loadImage(url);\n const size = target ?? { width: image.width, height: image.height };\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return environment.encodePng(image, { ...size, background: settings.background });\n },\n { timeoutMs: settings.timeoutMs, signal, label },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, label);\n } finally {\n environment.revokeObjectURL(url);\n }\n}\n\n/** Width and height from a PNG's IHDR chunk, read from the first 24 bytes only. */\nexport async function readPngSize(blob: Blob): Promise<Size | null> {\n const bytes = new Uint8Array(await blob.slice(0, 24).arrayBuffer());\n if (bytes.length < 24) return null;\n const view = new DataView(bytes.buffer);\n return { width: view.getUint32(16), height: view.getUint32(20) };\n}\n\n/**\n * Guarantees the clipboard-safe result: a real PNG (verified by its bytes),\n * typed `image/png`, within the pixel budget. Other raster formats are re-encoded.\n */\nexport async function ensurePng(\n blob: Blob,\n settings: RenderSettings,\n environment: () => CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const actual = await sniffImageType(blob);\n if (actual === null) {\n throw copyFailure('blob-generation-failed', `${label} did not produce an image.`);\n }\n if (actual !== IMAGE_MIME_TYPE) {\n return drawBlobToPng(blob, null, settings, environment(), signal, label);\n }\n const size = await readPngSize(blob);\n if (size === null) throw copyFailure('blob-generation-failed', `${label} produced a truncated PNG.`);\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return blob.type === IMAGE_MIME_TYPE ? blob : blob.slice(0, blob.size, IMAGE_MIME_TYPE);\n}\n","import { copyFailure } from '../core/errors';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { resolveCaptureEnvironment } from './environment';\nimport { drawBlobToPng } from './render';\nimport { resolveRenderSettings, resolveSize, toPixelSize, type RenderOptions, type Size } from './options';\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n/** Refuse absurd markup before handing it to the image decoder. 10 M characters. */\nexport const DEFAULT_MAX_SVG_LENGTH = 10_000_000;\n\nexport interface SvgToPngOptions extends RenderOptions {\n /** Max markup length in characters. Default 10 000 000. */\n readonly maxLength?: number;\n}\n\n// Both patterns are linear-time: untrusted markup must not be able to trigger catastrophic backtracking.\nconst SVG_OPEN = /<svg\\b/i;\nconst LENGTH = /^(\\d+(?:\\.\\d+)?|\\.\\d+)(?:px)?$/i;\n\n/** The first `<svg …>` tag, found with two linear scans. */\nfunction findRootTag(markup: string): string | null {\n const start = markup.search(SVG_OPEN);\n if (start === -1) return null;\n const end = markup.indexOf('>', start);\n return end === -1 ? null : markup.slice(start, end + 1);\n}\n\n// Pre-compiled attribute patterns for the three attributes we ever read.\n// Compiling at module load time and with fixed literal names eliminates any\n// risk of ReDoS from runtime-constructed RegExps.\nconst ATTR_PATTERNS: Readonly<Record<string, RegExp>> = /* @__PURE__ */ Object.freeze({\n width: /\\swidth\\s*=\\s*([\"'])(.*?)\\1/i,\n height: /\\sheight\\s*=\\s*([\"'])(.*?)\\1/i,\n viewBox: /\\sviewBox\\s*=\\s*([\"'])(.*?)\\1/i,\n xmlns: /\\sxmlns\\s*=\\s*([\"'])(.*?)\\1/i,\n});\n\nfunction readAttribute(tag: string, name: keyof typeof ATTR_PATTERNS): string | null {\n const pattern = ATTR_PATTERNS[name];\n /* c8 ignore next -- TypeScript enforces name is a key of ATTR_PATTERNS; guard is for JS callers only */\n if (!pattern) return null;\n const match = pattern.exec(tag);\n return match === null ? null : String(match[2]);\n}\n\nfunction parseLength(value: string | null): number | null {\n if (value === null) return null;\n const match = LENGTH.exec(value.trim());\n const number = match ? Number(match[1]) : NaN;\n return number > 0 ? number : null;\n}\n\n/** Intrinsic size from the root tag: `width`/`height` in px, else the `viewBox`. */\nexport function readSvgSize(markup: string): Size | null {\n const tag = findRootTag(markup);\n if (tag === null) return null;\n const width = parseLength(readAttribute(tag, 'width'));\n const height = parseLength(readAttribute(tag, 'height'));\n if (width !== null && height !== null) return { width, height };\n\n const raw = readAttribute(tag, 'viewBox');\n const viewBox = raw != null ? raw.trim().split(/[\\s,]+/).map(Number) : [];\n const [, , boxWidth = NaN, boxHeight = NaN] = viewBox;\n if (viewBox.length !== 4 || !(boxWidth > 0) || !(boxHeight > 0)) return null;\n if (width !== null) return { width, height: (width * boxHeight) / boxWidth };\n if (height !== null) return { width: (height * boxWidth) / boxHeight, height };\n return { width: boxWidth, height: boxHeight };\n}\n\n/** Adds the SVG namespace when missing; `<img>` refuses to decode SVG without it. */\nexport function ensureSvgNamespace(markup: string): string {\n const tag = findRootTag(markup);\n if (tag === null) throw copyFailure('invalid-payload', 'The markup has no <svg> root element.');\n if (readAttribute(tag, 'xmlns') !== null) return markup;\n return markup.replace(SVG_OPEN, `<svg xmlns=\"${SVG_NAMESPACE}\"`);\n}\n\nconst isSvgElement = (value: Element): boolean => value.localName === 'svg';\n\n/**\n * Rasterises SVG (an `<svg>` element or markup) to a PNG Blob, ready for\n * `copy({ kind: 'image', blob })`.\n *\n * Security: the SVG is decoded as an *image*, where browsers disable scripts,\n * event handlers and external resource loading, and it is never inserted into\n * the document. Size is capped in characters and pixels.\n */\nexport async function svgToPngBlob(source: Element | string, options: SvgToPngOptions = {}): Promise<Blob> {\n const environment = resolveCaptureEnvironment(options.environment);\n const settings = resolveRenderSettings(options);\n const maxLength = options.maxLength ?? DEFAULT_MAX_SVG_LENGTH;\n\n let intrinsic: Size | null = null;\n let markup: string;\n if (typeof source === 'string') {\n markup = source;\n } else {\n if (!isSvgElement(source)) throw copyFailure('invalid-payload', `Expected an <svg> element, got <${source.localName}>.`);\n const rect = source.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) intrinsic = { width: rect.width, height: rect.height };\n markup = environment.serializeSvg(source);\n }\n\n if (markup.length > maxLength) {\n throw copyFailure('too-large', `The SVG markup exceeds ${String(maxLength)} characters.`);\n }\n const prepared = ensureSvgNamespace(markup);\n const size = resolveSize(intrinsic ?? readSvgSize(prepared), options.width, options.height);\n const target = toPixelSize(size, settings);\n\n const blob = new Blob([prepared], { type: SVG_MIME_TYPE });\n return drawBlobToPng(blob, target, settings, environment, options.signal, 'SVG rasterisation');\n}\n","import { copyFailure } from '../core/errors';\nimport type { OperationContext } from '../core/machine-shared';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { isBlob, type ImagePayload } from '../core/payload';\nimport { withDeadline } from './deadline';\nimport { resolveCaptureEnvironment, type CaptureEnvironment } from './environment';\nimport {\n resolveRenderSettings,\n resolveSize,\n toPixelSize,\n type RenderOptions,\n type RenderSettings,\n type Size,\n} from './options';\nimport { classifyCaptureError, ensurePng } from './render';\nimport { svgToPngBlob } from './svg';\n\n/** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */\nexport interface CanvasLike {\n toBlob(callback: (blob: Blob | null) => void, type?: string, quality?: number): void;\n}\n\n/**\n * What a rasteriser may return: a Blob (any raster format), a canvas, or a\n * base64 `data:image/…` URL. Network URLs are refused (never fetched).\n */\nexport type RasterizeOutput = Blob | CanvasLike | string;\n\nexport interface RasterizeContext {\n /** Pixel density to render at. */\n readonly scale: number;\n /** CSS size of the element (or the requested size). */\n readonly width: number;\n readonly height: number;\n readonly backgroundColor: string | null;\n /** Fires on timeout or caller abort: stop work early if you can. */\n readonly signal: AbortSignal;\n}\n\n/**\n * Turns a DOM node into pixels. Bring your own engine, e.g.\n * `(node, { scale }) => domToBlob(node, { scale })` from `modern-screenshot`.\n */\nexport type Rasterizer = (node: Element, context: RasterizeContext) => PromiseLike<RasterizeOutput> | RasterizeOutput;\n\nexport interface CaptureElementOptions extends RenderOptions {\n /** Required for HTML elements. `<svg>` elements are rasterised natively when omitted. */\n readonly rasterize?: Rasterizer;\n}\n\nconst LABEL = 'Element capture';\nconst DATA_URL = /^data:(image\\/[a-z0-9.+-]+)((?:;[a-z0-9-]+=[a-z0-9.+-]+)*)(;base64)?,/i;\n\nfunction decodeBase64(payload: string, type: string): Blob {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned malformed base64.', cause);\n }\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);\n return new Blob([bytes], { type });\n}\n\nfunction canvasToBlob(canvas: CanvasLike): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing.'));\n }, 'image/png');\n });\n}\n\nconst isCanvasLike = (value: unknown): value is CanvasLike =>\n typeof value === 'object' && value !== null && typeof (value as { toBlob?: unknown }).toBlob === 'function';\n\nasync function toPng(\n output: unknown,\n options: CaptureElementOptions,\n settings: RenderSettings,\n size: Size,\n signal: AbortSignal,\n): Promise<Blob> {\n const environment = (): CaptureEnvironment => resolveCaptureEnvironment(options.environment);\n\n if (isBlob(output)) return ensurePng(output, settings, environment, signal, LABEL);\n if (isCanvasLike(output)) return ensurePng(await canvasToBlob(output), settings, environment, signal, LABEL);\n if (typeof output !== 'string') {\n throw copyFailure('blob-generation-failed', 'The rasteriser must return a Blob, a canvas or a data:image URL.');\n }\n\n const match = DATA_URL.exec(output);\n if (match === null) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned a string that is not a data:image URL.');\n }\n const type = String(match[1]).toLowerCase();\n const base64 = match[3] !== undefined;\n const body = output.slice(match[0].length);\n\n if (type === SVG_MIME_TYPE) {\n // e.g. modern-screenshot's domToSvg: rasterise it natively at the element's size.\n const markup = base64 ? await decodeBase64(body, type).text() : decodeURIComponent(body);\n return svgToPngBlob(markup, {\n ...settings,\n width: size.width,\n height: size.height,\n signal,\n environment: environment(),\n });\n }\n if (!base64) throw copyFailure('blob-generation-failed', 'Raster data URLs must be base64-encoded.');\n return ensurePng(decodeBase64(body, type), settings, environment, signal, LABEL);\n}\n\n/**\n * Captures an element as a PNG Blob, ready for `copy({ kind: 'image', blob })`.\n * Output is verified to be a real PNG within `maxPixels`, or a classified\n * `CopyFailure` is thrown (`invalid-payload`, `unsupported`, `too-large`,\n * `timeout`, `aborted`, `blob-generation-failed`).\n */\nexport async function captureElement(node: Element | null | undefined, options: CaptureElementOptions = {}): Promise<Blob> {\n if (!node) throw copyFailure('invalid-payload', 'There is no element to capture (is the ref attached yet?).');\n\n const { rasterize } = options;\n if (!rasterize) {\n if (node.localName === 'svg') return svgToPngBlob(node, options);\n throw copyFailure(\n 'unsupported',\n 'Capturing HTML needs a `rasterize` function, e.g. `domToBlob` from modern-screenshot. Only <svg> works without one.',\n );\n }\n\n const settings = resolveRenderSettings(options);\n const rect = node.getBoundingClientRect();\n const intrinsic = rect.width > 0 && rect.height > 0 ? { width: rect.width, height: rect.height } : null;\n const size = resolveSize(intrinsic, options.width, options.height);\n toPixelSize(size, settings); // Refuse before rendering anything.\n\n try {\n return await withDeadline(\n async (signal) => {\n const output = await rasterize(node, {\n scale: settings.scale,\n width: size.width,\n height: size.height,\n backgroundColor: settings.background,\n signal,\n });\n return toPng(output, options, settings, size, signal);\n },\n { timeoutMs: settings.timeoutMs, signal: options.signal, label: LABEL },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, LABEL);\n }\n}\n\n/**\n * A lazy `BlobSource` for `copy()`. Resolving the element at click time and\n * starting inside the gesture keeps Safari happy. Rasterising stops when the\n * copy is reset or its component unmounts, or when `options.signal` aborts.\n *\n * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })\n */\nexport function captureSource(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): (context?: OperationContext) => Promise<Blob> {\n return (context) => {\n const a = options.signal;\n const b = context?.signal;\n if (!a || !b) {\n const signal = a ?? b;\n return captureElement(getNode(), signal ? { ...options, signal } : options);\n }\n const any = (AbortSignal as { any?: (signals: AbortSignal[]) => AbortSignal }).any;\n if (typeof any === 'function') return captureElement(getNode(), { ...options, signal: any([a, b]) });\n\n // Older browsers: forward both, and detach once settled so a long-lived\n // caller signal doesn't accumulate a listener per copy.\n const controller = new AbortController();\n const onAbortA = (): void => {\n controller.abort(a.reason);\n };\n const onAbortB = (): void => {\n controller.abort(b.reason);\n };\n if (a.aborted) onAbortA();\n else if (b.aborted) onAbortB();\n a.addEventListener('abort', onAbortA);\n b.addEventListener('abort', onAbortB);\n return captureElement(getNode(), { ...options, signal: controller.signal }).finally(() => {\n a.removeEventListener('abort', onAbortA);\n b.removeEventListener('abort', onAbortB);\n });\n };\n}\n\n/** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */\nexport function captureImage(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): ImagePayload {\n return { kind: 'image', blob: captureSource(getNode, options) };\n}\n"],"mappings":";;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;;;;;AAmBA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,SAAgB,YAAY,MAAqB,SAAiB,OAA8B;CAC9F,OAAO,IAAI,YAAY,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAC9D;;;AC5DA,SAAS,UAAU,KAAoC;CACrD,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,QAAQ,IAAI,MAAM;EACxB,MAAM,WAAW;EACjB,MAAM,eAAe;GACnB,QAAQ;IAAE,QAAQ;IAAO,OAAO,MAAM;IAAc,QAAQ,MAAM;GAAc,CAAC;EACnF;EACA,MAAM,gBAAg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.ts","../src/capture/options.ts","../src/core/mime.ts","../src/core/payload.ts","../src/capture/deadline.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","import { copyFailure } from '../core/errors';\n\n/** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */\nexport interface DecodedImage {\n readonly source: unknown;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface PngTarget {\n /** Integer pixel size of the output. */\n readonly width: number;\n readonly height: number;\n /** CSS colour painted under the image, or `null` for transparency. */\n readonly background: string | null;\n}\n\n/**\n * Everything capture needs from the platform. The default uses the DOM;\n * inject your own for workers (OffscreenCanvas), native shells or tests.\n */\nexport interface CaptureEnvironment {\n readonly createObjectURL: (blob: Blob) => string;\n readonly revokeObjectURL: (url: string) => void;\n /** Serialises an `<svg>` element to markup. */\n readonly serializeSvg: (node: Element) => string;\n /** Decodes an image from a `blob:` or `data:` URL. */\n readonly loadImage: (url: string) => Promise<DecodedImage>;\n /** Draws the image scaled to `target` and encodes it as PNG. */\n readonly encodePng: (image: DecodedImage, target: PngTarget) => Promise<Blob>;\n}\n\nfunction loadImage(url: string): Promise<DecodedImage> {\n return new Promise((resolve, reject) => {\n const image = new Image();\n image.decoding = 'async';\n image.onload = () => {\n resolve({ source: image, width: image.naturalWidth, height: image.naturalHeight });\n };\n image.onerror = () => {\n reject(copyFailure('blob-generation-failed', 'The image could not be decoded.'));\n };\n image.src = url;\n });\n}\n\nfunction encodePng(image: DecodedImage, target: PngTarget): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const canvas = document.createElement('canvas');\n canvas.width = target.width;\n canvas.height = target.height;\n const context = canvas.getContext('2d');\n if (!context) {\n reject(copyFailure('unsupported', 'Canvas 2D rendering is not available.'));\n return;\n }\n if (target.background !== null) {\n context.fillStyle = target.background;\n context.fillRect(0, 0, target.width, target.height);\n }\n context.drawImage(image.source as CanvasImageSource, 0, 0, target.width, target.height);\n // Throws SecurityError synchronously for tainted canvases; the executor turns that into a rejection.\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing (canvas too large?).'));\n }, 'image/png');\n });\n}\n\n/** The DOM-backed environment, or `null` outside a browser. */\nexport function getDefaultCaptureEnvironment(): CaptureEnvironment | null {\n if (\n typeof document === 'undefined' ||\n typeof Image !== 'function' ||\n typeof XMLSerializer !== 'function' ||\n typeof URL.createObjectURL !== 'function'\n ) {\n return null;\n }\n return {\n createObjectURL: (blob) => URL.createObjectURL(blob),\n revokeObjectURL: (url) => {\n URL.revokeObjectURL(url);\n },\n serializeSvg: (node) => new XMLSerializer().serializeToString(node),\n loadImage,\n encodePng,\n };\n}\n\nexport function resolveCaptureEnvironment(environment: CaptureEnvironment | undefined): CaptureEnvironment {\n const resolved = environment ?? getDefaultCaptureEnvironment();\n if (!resolved) {\n throw copyFailure('unsupported', 'Image capture needs a browser environment (document, Image, canvas).');\n }\n return resolved;\n}\n","import { copyFailure } from '../core/errors';\nimport type { CaptureEnvironment } from './environment';\n\nexport const DEFAULT_CAPTURE_SCALE = 2;\nexport const MAX_CAPTURE_SCALE = 10;\n/** 4096 × 4096: the canvas area limit of Safari/iOS, the strictest mainstream engine. */\nexport const DEFAULT_MAX_PIXELS = 16_777_216;\nexport const DEFAULT_CAPTURE_TIMEOUT_MS = 15_000;\n\nexport interface RenderOptions {\n /** Output width in CSS px (before `scale`). Omit to use the intrinsic size; set one side to keep the aspect ratio. */\n readonly width?: number;\n /** Output height in CSS px (before `scale`). */\n readonly height?: number;\n /** Pixel density multiplier, e.g. `window.devicePixelRatio`. Default 2 (crisp on HiDPI). Max 10. */\n readonly scale?: number;\n /** CSS colour under the image. Default `null` (transparent). */\n readonly background?: string | null;\n /** Refuse outputs larger than this many pixels (memory / DoS guard). Default 16 777 216. */\n readonly maxPixels?: number;\n /** Give up after this long. Default 15 000 ms. `Infinity` disables. */\n readonly timeoutMs?: number;\n /** Cancel the capture. */\n readonly signal?: AbortSignal;\n /** Platform hooks. Defaults to the DOM. */\n readonly environment?: CaptureEnvironment;\n}\n\nexport interface RenderSettings {\n readonly scale: number;\n readonly background: string | null;\n readonly maxPixels: number;\n readonly timeoutMs: number;\n}\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nconst isPositiveFinite = (value: number): boolean => Number.isFinite(value) && value > 0;\n\nexport function resolveRenderSettings(options: RenderOptions): RenderSettings {\n const scale = options.scale ?? DEFAULT_CAPTURE_SCALE;\n if (!isPositiveFinite(scale) || scale > MAX_CAPTURE_SCALE) {\n throw invalid(`\\`scale\\` must be > 0 and <= ${String(MAX_CAPTURE_SCALE)} (received ${String(scale)}).`);\n }\n const maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;\n if (!Number.isInteger(maxPixels) || maxPixels <= 0) {\n throw invalid(`\\`maxPixels\\` must be a positive integer (received ${String(maxPixels)}).`);\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_CAPTURE_TIMEOUT_MS;\n if (timeoutMs !== Infinity && !isPositiveFinite(timeoutMs)) {\n throw invalid(`\\`timeoutMs\\` must be > 0 or Infinity (received ${String(timeoutMs)}).`);\n }\n return { scale, background: options.background ?? null, maxPixels, timeoutMs };\n}\n\n/** Combines explicit `width`/`height` with an intrinsic size, keeping the aspect ratio when only one is set. */\nexport function resolveSize(intrinsic: Size | null, width: number | undefined, height: number | undefined): Size {\n for (const [name, value] of [\n ['width', width],\n ['height', height],\n ] as const) {\n if (value !== undefined && !isPositiveFinite(value)) {\n throw invalid(`\\`${name}\\` must be a positive number (received ${String(value)}).`);\n }\n }\n if (width !== undefined && height !== undefined) return { width, height };\n if (intrinsic === null) {\n throw invalid('The size to render is unknown: pass `width` and `height`, or give the source a size.');\n }\n if (width !== undefined) return { width, height: (width * intrinsic.height) / intrinsic.width };\n if (height !== undefined) return { width: (height * intrinsic.width) / intrinsic.height, height };\n return intrinsic;\n}\n\n/** Integer pixel size after scaling. Throws `too-large` past `maxPixels`. */\nexport function toPixelSize(size: Size, settings: Pick<RenderSettings, 'scale' | 'maxPixels'>): Size {\n const width = Math.max(1, Math.round(size.width * settings.scale));\n const height = Math.max(1, Math.round(size.height * settings.scale));\n assertPixelBudget(width, height, settings.maxPixels);\n return { width, height };\n}\n\nexport function assertPixelBudget(width: number, height: number, maxPixels: number): void {\n if (width * height > maxPixels) {\n throw copyFailure(\n 'too-large',\n `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \\`scale\\` or raise \\`maxPixels\\`.`,\n );\n }\n}\n","/**\n * MIME helpers shared by paste and capture. Everything that comes from the\n * clipboard is untrusted input, so types are normalised and validated before\n * they are compared, and image types are confirmed from the bytes themselves.\n */\n\n/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */\nconst MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\n/** SVG is XML that can carry scripts; it is never matched by a wildcard. */\nexport const SVG_MIME_TYPE = 'image/svg+xml';\n\n/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */\nexport function normalizeMimeType(value: string): string | null {\n const separator = value.indexOf(';');\n const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();\n return MIME_SHAPE.test(base) ? base : null;\n}\n\n/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */\nexport const WEB_CUSTOM_FORMAT_PREFIX = 'web ';\n\n/** Whether a clipboard type is a web custom format (`web type/subtype`). */\nexport function isWebCustomFormat(type: string): boolean {\n return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;\n}\n\n/**\n * Like {@link normalizeMimeType}, but also accepts web custom formats\n * (`web type/subtype`), returned as `web ` + the normalised MIME type.\n */\nexport function normalizeClipboardType(value: string): string | null {\n if (!isWebCustomFormat(value)) return normalizeMimeType(value);\n const inner = normalizeMimeType(value.slice(4));\n return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;\n}\n\n/**\n * Types a wildcard never matches, so accepting them must be explicit:\n * `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types\n * (application-specific data that only the app that defined them should read).\n */\nfunction requiresExactMatch(mimeType: string): boolean {\n return mimeType === SVG_MIME_TYPE || isWebCustomFormat(mimeType) || mimeType.endsWith('+json');\n}\n\n/**\n * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\\/*`)?\n * Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.\n */\nexport function matchesMimePattern(mimeType: string, pattern: string): boolean {\n if (pattern === mimeType) return true;\n if (requiresExactMatch(mimeType)) return false;\n if (pattern === '*/*') return true;\n return pattern.endsWith('/*') && mimeType.startsWith(pattern.slice(0, -1));\n}\n\n/** Types whose clipboard data is text and is therefore surfaced as a `string`. */\nexport function isTextualMimeType(mimeType: string): boolean {\n const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;\n return (\n type.startsWith('text/') ||\n type === SVG_MIME_TYPE ||\n type === 'application/json' ||\n type === 'application/xml' ||\n type.endsWith('+json')\n );\n}\n\n/** Raster image formats recognised from their leading bytes. */\nexport type RasterImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/avif';\n\nconst SNIFF_BYTES = 16;\n\nfunction startsWith(bytes: Uint8Array, signature: readonly number[], offset = 0): boolean {\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nconst ascii = (text: string): number[] => Array.from(text, (char) => char.charCodeAt(0));\n\nconst PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\nconst JPEG = [0xff, 0xd8, 0xff];\nconst GIF = ascii('GIF8');\nconst RIFF = ascii('RIFF');\nconst WEBP = ascii('WEBP');\nconst BMP = ascii('BM');\nconst FTYP_AVIF = ascii('ftypavif');\nconst FTYP_AVIS = ascii('ftypavis');\n\n/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */\nexport function sniffImageBytes(bytes: Uint8Array): RasterImageMimeType | null {\n if (startsWith(bytes, PNG)) return 'image/png';\n if (startsWith(bytes, JPEG)) return 'image/jpeg';\n if (startsWith(bytes, GIF)) return 'image/gif';\n if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return 'image/webp';\n if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return 'image/avif';\n if (startsWith(bytes, BMP)) return 'image/bmp';\n return null;\n}\n\n/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */\nexport async function sniffImageType(blob: Blob): Promise<RasterImageMimeType | null> {\n const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();\n return sniffImageBytes(new Uint8Array(head));\n}\n","import { CopyFailure, createCopyError, type CopyError } from './errors';\nimport type { OperationContext } from './machine-shared';\n\n/** The only image MIME type with reliable cross-browser clipboard write support. */\nexport const IMAGE_MIME_TYPE = 'image/png';\n\n/**\n * An image as a Blob, a promise of one, or a function producing one.\n * Prefer the function form: it is invoked synchronously inside the user\n * gesture, which Safari requires for async image generation. The browser\n * adapter always passes an `OperationContext`: stop work once\n * `context.signal` aborts (reset, superseded, unmount). Optional in the type\n * so adapters that call sources themselves keep compiling.\n */\nexport type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);\n\nexport interface TextPayload {\n readonly kind: 'text';\n readonly value: string;\n}\n\nexport interface HtmlPayload {\n readonly kind: 'html';\n readonly html: string;\n /** Required plain-text fallback for targets that don't understand HTML. */\n readonly text: string;\n}\n\nexport interface ImagePayload {\n readonly kind: 'image';\n readonly blob: BlobSource;\n}\n\nexport interface JsonPayload {\n readonly kind: 'json';\n readonly value: unknown;\n /** `true` = 2-space indent, a number = that indent, falsy = compact. */\n readonly pretty?: boolean | number;\n}\n\nexport interface MultiPayloadItem {\n /**\n * The MIME type, or a web custom format (`web application/vnd.acme+json`).\n * Web custom formats are only written by the async Clipboard API; copy and drag\n * events skip them.\n */\n readonly mimeType: string;\n readonly data: string | Blob;\n /**\n * Skip this item, instead of failing the copy, when the browser cannot write its type.\n * An optional item is only written when `ClipboardItem.supports()` confirms the type.\n * At least one item must be written.\n */\n readonly optional?: boolean;\n}\n\nexport interface MultiPayload {\n readonly kind: 'multi';\n readonly items: readonly MultiPayloadItem[];\n}\n\nexport type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;\nexport type CopyPayloadKind = CopyPayload['kind'];\n\n/** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */\nexport type CopyInput = string | CopyPayload;\n\n/**\n * What `copy()` accepts. The function form is resolved synchronously at copy\n * time, so it always reads the latest value without re-rendering.\n */\nexport type CopySource = CopyInput | (() => CopyInput);\n\nexport function normalizePayload(input: CopyInput): CopyPayload {\n return typeof input === 'string' ? { kind: 'text', value: input } : input;\n}\n\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && value instanceof Blob) return true;\n const tag = Object.prototype.toString.call(value);\n return tag === '[object Blob]' || tag === '[object File]';\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nconst invalid = (message: string): CopyError => createCopyError('invalid-payload', message);\n\n/**\n * Structural validation. Typed callers can't produce most of these states,\n * but plain-JS callers and runtime data can, so the check is always on.\n */\nexport function validatePayload(payload: unknown): CopyError | null {\n if (typeof payload !== 'object' || payload === null) {\n return invalid('Copy input must be a string or a payload object.');\n }\n const candidate = payload as Record<string, unknown>;\n\n switch (candidate['kind']) {\n case 'text':\n return typeof candidate['value'] === 'string' && candidate['value'].length > 0\n ? null\n : invalid('Text payload must be a non-empty string.');\n case 'html':\n if (typeof candidate['html'] !== 'string' || candidate['html'].length === 0) {\n return invalid('HTML payload requires a non-empty `html` string.');\n }\n return typeof candidate['text'] === 'string' && candidate['text'].length > 0\n ? null\n : invalid('HTML payload requires a non-empty plain-text `text` fallback.');\n case 'image': {\n const source = candidate['blob'];\n return isBlob(source) || typeof source === 'function' || isThenable(source)\n ? null\n : invalid('Image payload requires a Blob, a Promise<Blob> or a function returning one.');\n }\n case 'json':\n return candidate['value'] === undefined ? invalid('JSON payload value is undefined.') : null;\n case 'multi': {\n const items = candidate['items'];\n if (!Array.isArray(items) || items.length === 0) {\n return invalid('Multi payload requires at least one item.');\n }\n const seen = new Set<string>();\n for (const item of items as unknown[]) {\n const entry = (typeof item === 'object' && item !== null ? item : {}) as Record<string, unknown>;\n const mimeType = entry['mimeType'];\n const data = entry['data'];\n if (typeof mimeType !== 'string' || mimeType.length === 0) {\n return invalid('Every multi item needs a non-empty `mimeType`.');\n }\n if (seen.has(mimeType)) return invalid(`Duplicate MIME type \"${mimeType}\" in multi payload.`);\n seen.add(mimeType);\n if (typeof data !== 'string' && !isBlob(data)) {\n return invalid(`Multi item \"${mimeType}\" must contain a string or a Blob.`);\n }\n }\n return null;\n }\n default:\n return invalid(`Unknown payload kind: ${String(candidate['kind'])}.`);\n }\n}\n\n/** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */\nexport function serializeJson(payload: JsonPayload): string {\n const indent =\n payload.pretty === true ? 2 : typeof payload.pretty === 'number' ? payload.pretty : undefined;\n // Typed as `string` by lib.d.ts, but returns undefined for functions, symbols and undefined.\n let text: unknown;\n try {\n text = JSON.stringify(payload.value, null, indent);\n } catch (cause) {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload could not be serialised (circular reference or BigInt?).', cause),\n );\n }\n if (typeof text !== 'string') {\n throw new CopyFailure(\n createCopyError('invalid-payload', 'JSON payload serialised to nothing (functions, symbols and undefined are not JSON).'),\n );\n }\n return text;\n}\n","import { copyFailure, type CopyFailure } from '../core/errors';\n\nexport interface DeadlineOptions {\n readonly timeoutMs: number;\n readonly signal?: AbortSignal | undefined;\n /** Used in messages: \"<label> timed out\". */\n readonly label: string;\n}\n\n/**\n * Runs `task` with a timeout and an optional caller `AbortSignal`. The task\n * receives a signal that fires on either, so cooperative work can stop early.\n * Rejects with classified `timeout` / `aborted` failures.\n */\nexport function withDeadline<T>(task: (signal: AbortSignal) => PromiseLike<T> | T, options: DeadlineOptions): Promise<T> {\n const { timeoutMs, label } = options;\n const external = options.signal;\n if (external?.aborted) {\n return Promise.reject(copyFailure('aborted', `${label} was aborted.`, external.reason));\n }\n\n const controller = new AbortController();\n return new Promise<T>((resolve, reject) => {\n const finish = (abort: boolean): void => {\n clearTimeout(timer);\n external?.removeEventListener('abort', onAbort);\n // Always signal downstream cooperative work to stop — whether we timed\n // out, were aborted, or resolved successfully. Without this, a task\n // that started a long operation keeps that operation alive after we've\n // already resolved, leaking resources until GC.\n /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */\n if (abort) controller.abort();\n };\n const fail = (failure: CopyFailure): void => {\n finish(true);\n reject(failure);\n };\n const onAbort = (): void => {\n fail(copyFailure('aborted', `${label} was aborted.`, (external as AbortSignal).reason));\n };\n const timer =\n timeoutMs === Infinity\n ? undefined\n : setTimeout(() => {\n fail(copyFailure('timeout', `${label} timed out after ${String(timeoutMs)} ms.`));\n }, timeoutMs);\n external?.addEventListener('abort', onAbort, { once: true });\n\n new Promise<T>((run) => {\n run(task(controller.signal));\n }).then(\n (value) => {\n finish(true);\n resolve(value);\n },\n (cause: unknown) => {\n finish(true);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- classified by the caller\n reject(cause);\n },\n );\n });\n}\n","import { copyFailure, isCopyFailure } from '../core/errors';\nimport { IMAGE_MIME_TYPE } from '../core/payload';\nimport { sniffImageType } from '../core/mime';\nimport { withDeadline } from './deadline';\nimport type { CaptureEnvironment } from './environment';\nimport { assertPixelBudget, type RenderSettings, type Size } from './options';\n\n/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */\nexport function classifyCaptureError(cause: unknown, label: string): unknown {\n return isCopyFailure(cause) ? cause : copyFailure('blob-generation-failed', `${label} failed.`, cause);\n}\n\n/**\n * Decodes an image Blob and re-encodes it as PNG at `target` (or its natural\n * size), within the deadline. The object URL is always revoked.\n */\nexport async function drawBlobToPng(\n blob: Blob,\n target: Size | null,\n settings: RenderSettings,\n environment: CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const url = environment.createObjectURL(blob);\n try {\n return await withDeadline(\n async () => {\n const image = await environment.loadImage(url);\n const size = target ?? { width: image.width, height: image.height };\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return environment.encodePng(image, { ...size, background: settings.background });\n },\n { timeoutMs: settings.timeoutMs, signal, label },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, label);\n } finally {\n environment.revokeObjectURL(url);\n }\n}\n\n/** Width and height from a PNG's IHDR chunk, read from the first 24 bytes only. */\nexport async function readPngSize(blob: Blob): Promise<Size | null> {\n const bytes = new Uint8Array(await blob.slice(0, 24).arrayBuffer());\n if (bytes.length < 24) return null;\n const view = new DataView(bytes.buffer);\n return { width: view.getUint32(16), height: view.getUint32(20) };\n}\n\n/**\n * Guarantees the clipboard-safe result: a real PNG (verified by its bytes),\n * typed `image/png`, within the pixel budget. Other raster formats are re-encoded.\n */\nexport async function ensurePng(\n blob: Blob,\n settings: RenderSettings,\n environment: () => CaptureEnvironment,\n signal: AbortSignal | undefined,\n label: string,\n): Promise<Blob> {\n const actual = await sniffImageType(blob);\n if (actual === null) {\n throw copyFailure('blob-generation-failed', `${label} did not produce an image.`);\n }\n if (actual !== IMAGE_MIME_TYPE) {\n return drawBlobToPng(blob, null, settings, environment(), signal, label);\n }\n const size = await readPngSize(blob);\n if (size === null) throw copyFailure('blob-generation-failed', `${label} produced a truncated PNG.`);\n assertPixelBudget(size.width, size.height, settings.maxPixels);\n return blob.type === IMAGE_MIME_TYPE ? blob : blob.slice(0, blob.size, IMAGE_MIME_TYPE);\n}\n","import { copyFailure } from '../core/errors';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { resolveCaptureEnvironment } from './environment';\nimport { drawBlobToPng } from './render';\nimport { resolveRenderSettings, resolveSize, toPixelSize, type RenderOptions, type Size } from './options';\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n/** Refuse absurd markup before handing it to the image decoder. 10 M characters. */\nexport const DEFAULT_MAX_SVG_LENGTH = 10_000_000;\n\nexport interface SvgToPngOptions extends RenderOptions {\n /** Max markup length in characters. Default 10 000 000. */\n readonly maxLength?: number;\n}\n\n// Both patterns are linear-time: untrusted markup must not be able to trigger catastrophic backtracking.\nconst SVG_OPEN = /<svg\\b/i;\nconst LENGTH = /^(\\d+(?:\\.\\d+)?|\\.\\d+)(?:px)?$/i;\n\n/** The first `<svg …>` tag, found with two linear scans. */\nfunction findRootTag(markup: string): string | null {\n const start = markup.search(SVG_OPEN);\n if (start === -1) return null;\n const end = markup.indexOf('>', start);\n return end === -1 ? null : markup.slice(start, end + 1);\n}\n\n// Pre-compiled attribute patterns for the three attributes we ever read.\n// Compiling at module load time and with fixed literal names eliminates any\n// risk of ReDoS from runtime-constructed RegExps.\nconst ATTR_PATTERNS: Readonly<Record<string, RegExp>> = /* @__PURE__ */ Object.freeze({\n width: /\\swidth\\s*=\\s*([\"'])(.*?)\\1/i,\n height: /\\sheight\\s*=\\s*([\"'])(.*?)\\1/i,\n viewBox: /\\sviewBox\\s*=\\s*([\"'])(.*?)\\1/i,\n xmlns: /\\sxmlns\\s*=\\s*([\"'])(.*?)\\1/i,\n});\n\nfunction readAttribute(tag: string, name: keyof typeof ATTR_PATTERNS): string | null {\n const pattern = ATTR_PATTERNS[name];\n /* c8 ignore next -- TypeScript enforces name is a key of ATTR_PATTERNS; guard is for JS callers only */\n if (!pattern) return null;\n const match = pattern.exec(tag);\n return match === null ? null : String(match[2]);\n}\n\nfunction parseLength(value: string | null): number | null {\n if (value === null) return null;\n const match = LENGTH.exec(value.trim());\n const number = match ? Number(match[1]) : NaN;\n return number > 0 ? number : null;\n}\n\n/** Intrinsic size from the root tag: `width`/`height` in px, else the `viewBox`. */\nexport function readSvgSize(markup: string): Size | null {\n const tag = findRootTag(markup);\n if (tag === null) return null;\n const width = parseLength(readAttribute(tag, 'width'));\n const height = parseLength(readAttribute(tag, 'height'));\n if (width !== null && height !== null) return { width, height };\n\n const raw = readAttribute(tag, 'viewBox');\n const viewBox = raw != null ? raw.trim().split(/[\\s,]+/).map(Number) : [];\n const [, , boxWidth = NaN, boxHeight = NaN] = viewBox;\n if (viewBox.length !== 4 || !(boxWidth > 0) || !(boxHeight > 0)) return null;\n if (width !== null) return { width, height: (width * boxHeight) / boxWidth };\n if (height !== null) return { width: (height * boxWidth) / boxHeight, height };\n return { width: boxWidth, height: boxHeight };\n}\n\n/** Adds the SVG namespace when missing; `<img>` refuses to decode SVG without it. */\nexport function ensureSvgNamespace(markup: string): string {\n const tag = findRootTag(markup);\n if (tag === null) throw copyFailure('invalid-payload', 'The markup has no <svg> root element.');\n if (readAttribute(tag, 'xmlns') !== null) return markup;\n return markup.replace(SVG_OPEN, `<svg xmlns=\"${SVG_NAMESPACE}\"`);\n}\n\nconst isSvgElement = (value: Element): boolean => value.localName === 'svg';\n\n/**\n * Rasterises SVG (an `<svg>` element or markup) to a PNG Blob, ready for\n * `copy({ kind: 'image', blob })`.\n *\n * Security: the SVG is decoded as an *image*, where browsers disable scripts,\n * event handlers and external resource loading, and it is never inserted into\n * the document. Size is capped in characters and pixels.\n */\nexport async function svgToPngBlob(source: Element | string, options: SvgToPngOptions = {}): Promise<Blob> {\n const environment = resolveCaptureEnvironment(options.environment);\n const settings = resolveRenderSettings(options);\n const maxLength = options.maxLength ?? DEFAULT_MAX_SVG_LENGTH;\n\n let intrinsic: Size | null = null;\n let markup: string;\n if (typeof source === 'string') {\n markup = source;\n } else {\n if (!isSvgElement(source)) throw copyFailure('invalid-payload', `Expected an <svg> element, got <${source.localName}>.`);\n const rect = source.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) intrinsic = { width: rect.width, height: rect.height };\n markup = environment.serializeSvg(source);\n }\n\n if (markup.length > maxLength) {\n throw copyFailure('too-large', `The SVG markup exceeds ${String(maxLength)} characters.`);\n }\n const prepared = ensureSvgNamespace(markup);\n const size = resolveSize(intrinsic ?? readSvgSize(prepared), options.width, options.height);\n const target = toPixelSize(size, settings);\n\n const blob = new Blob([prepared], { type: SVG_MIME_TYPE });\n return drawBlobToPng(blob, target, settings, environment, options.signal, 'SVG rasterisation');\n}\n","import { copyFailure } from '../core/errors';\nimport type { OperationContext } from '../core/machine-shared';\nimport { SVG_MIME_TYPE } from '../core/mime';\nimport { isBlob, type ImagePayload } from '../core/payload';\nimport { withDeadline } from './deadline';\nimport { resolveCaptureEnvironment, type CaptureEnvironment } from './environment';\nimport {\n resolveRenderSettings,\n resolveSize,\n toPixelSize,\n type RenderOptions,\n type RenderSettings,\n type Size,\n} from './options';\nimport { classifyCaptureError, ensurePng } from './render';\nimport { svgToPngBlob } from './svg';\n\n/** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */\nexport interface CanvasLike {\n toBlob(callback: (blob: Blob | null) => void, type?: string, quality?: number): void;\n}\n\n/**\n * What a rasteriser may return: a Blob (any raster format), a canvas, or a\n * base64 `data:image/…` URL. Network URLs are refused (never fetched).\n */\nexport type RasterizeOutput = Blob | CanvasLike | string;\n\nexport interface RasterizeContext {\n /** Pixel density to render at. */\n readonly scale: number;\n /** CSS size of the element (or the requested size). */\n readonly width: number;\n readonly height: number;\n readonly backgroundColor: string | null;\n /** Fires on timeout or caller abort: stop work early if you can. */\n readonly signal: AbortSignal;\n}\n\n/**\n * Turns a DOM node into pixels. Bring your own engine, e.g.\n * `(node, { scale }) => domToBlob(node, { scale })` from `modern-screenshot`.\n */\nexport type Rasterizer = (node: Element, context: RasterizeContext) => PromiseLike<RasterizeOutput> | RasterizeOutput;\n\nexport interface CaptureElementOptions extends RenderOptions {\n /** Required for HTML elements. `<svg>` elements are rasterised natively when omitted. */\n readonly rasterize?: Rasterizer;\n}\n\nconst LABEL = 'Element capture';\nconst DATA_URL = /^data:(image\\/[a-z0-9.+-]+)((?:;[a-z0-9-]+=[a-z0-9.+-]+)*)(;base64)?,/i;\n\nfunction decodeBase64(payload: string, type: string): Blob {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned malformed base64.', cause);\n }\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);\n return new Blob([bytes], { type });\n}\n\nfunction canvasToBlob(canvas: CanvasLike): Promise<Blob> {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) resolve(blob);\n else reject(copyFailure('blob-generation-failed', 'canvas.toBlob() produced nothing.'));\n }, 'image/png');\n });\n}\n\nconst isCanvasLike = (value: unknown): value is CanvasLike =>\n typeof value === 'object' && value !== null && typeof (value as { toBlob?: unknown }).toBlob === 'function';\n\nasync function toPng(\n output: unknown,\n options: CaptureElementOptions,\n settings: RenderSettings,\n size: Size,\n signal: AbortSignal,\n): Promise<Blob> {\n const environment = (): CaptureEnvironment => resolveCaptureEnvironment(options.environment);\n\n if (isBlob(output)) return ensurePng(output, settings, environment, signal, LABEL);\n if (isCanvasLike(output)) return ensurePng(await canvasToBlob(output), settings, environment, signal, LABEL);\n if (typeof output !== 'string') {\n throw copyFailure('blob-generation-failed', 'The rasteriser must return a Blob, a canvas or a data:image URL.');\n }\n\n const match = DATA_URL.exec(output);\n if (match === null) {\n throw copyFailure('blob-generation-failed', 'The rasteriser returned a string that is not a data:image URL.');\n }\n const type = String(match[1]).toLowerCase();\n const base64 = match[3] !== undefined;\n const body = output.slice(match[0].length);\n\n if (type === SVG_MIME_TYPE) {\n // e.g. modern-screenshot's domToSvg: rasterise it natively at the element's size.\n const markup = base64 ? await decodeBase64(body, type).text() : decodeURIComponent(body);\n return svgToPngBlob(markup, {\n ...settings,\n width: size.width,\n height: size.height,\n signal,\n environment: environment(),\n });\n }\n if (!base64) throw copyFailure('blob-generation-failed', 'Raster data URLs must be base64-encoded.');\n return ensurePng(decodeBase64(body, type), settings, environment, signal, LABEL);\n}\n\n/**\n * Captures an element as a PNG Blob, ready for `copy({ kind: 'image', blob })`.\n * Output is verified to be a real PNG within `maxPixels`, or a classified\n * `CopyFailure` is thrown (`invalid-payload`, `unsupported`, `too-large`,\n * `timeout`, `aborted`, `blob-generation-failed`).\n */\nexport async function captureElement(node: Element | null | undefined, options: CaptureElementOptions = {}): Promise<Blob> {\n if (!node) throw copyFailure('invalid-payload', 'There is no element to capture (is the ref attached yet?).');\n\n const { rasterize } = options;\n if (!rasterize) {\n if (node.localName === 'svg') return svgToPngBlob(node, options);\n throw copyFailure(\n 'unsupported',\n 'Capturing HTML needs a `rasterize` function, e.g. `domToBlob` from modern-screenshot. Only <svg> works without one.',\n );\n }\n\n const settings = resolveRenderSettings(options);\n const rect = node.getBoundingClientRect();\n const intrinsic = rect.width > 0 && rect.height > 0 ? { width: rect.width, height: rect.height } : null;\n const size = resolveSize(intrinsic, options.width, options.height);\n toPixelSize(size, settings); // Refuse before rendering anything.\n\n try {\n return await withDeadline(\n async (signal) => {\n const output = await rasterize(node, {\n scale: settings.scale,\n width: size.width,\n height: size.height,\n backgroundColor: settings.background,\n signal,\n });\n return toPng(output, options, settings, size, signal);\n },\n { timeoutMs: settings.timeoutMs, signal: options.signal, label: LABEL },\n );\n } catch (cause) {\n throw classifyCaptureError(cause, LABEL);\n }\n}\n\n/**\n * A lazy `BlobSource` for `copy()`. Resolving the element at click time and\n * starting inside the gesture keeps Safari happy. Rasterising stops when the\n * copy is reset or its component unmounts, or when `options.signal` aborts.\n *\n * @example copy({ kind: 'image', blob: captureSource(() => cardRef.current, { rasterize }) })\n */\nexport function captureSource(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): (context?: OperationContext) => Promise<Blob> {\n return (context) => {\n const a = options.signal;\n const b = context?.signal;\n if (!a || !b) {\n const signal = a ?? b;\n return captureElement(getNode(), signal ? { ...options, signal } : options);\n }\n const any = (AbortSignal as { any?: (signals: AbortSignal[]) => AbortSignal }).any;\n if (typeof any === 'function') return captureElement(getNode(), { ...options, signal: any([a, b]) });\n\n // Older browsers: forward both, and detach once settled so a long-lived\n // caller signal doesn't accumulate a listener per copy.\n const controller = new AbortController();\n const onAbortA = (): void => {\n controller.abort(a.reason);\n };\n const onAbortB = (): void => {\n controller.abort(b.reason);\n };\n if (a.aborted) onAbortA();\n else if (b.aborted) onAbortB();\n a.addEventListener('abort', onAbortA);\n b.addEventListener('abort', onAbortB);\n return captureElement(getNode(), { ...options, signal: controller.signal }).finally(() => {\n a.removeEventListener('abort', onAbortA);\n b.removeEventListener('abort', onAbortB);\n });\n };\n}\n\n/** Shorthand for `{ kind: 'image', blob: captureSource(getNode, options) }`. */\nexport function captureImage(\n getNode: () => Element | null | undefined,\n options: CaptureElementOptions = {},\n): ImagePayload {\n return { kind: 'image', blob: captureSource(getNode, options) };\n}\n"],"mappings":";;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;;;;;AAmBA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EA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