react-smart-copy 1.17.2 → 1.19.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 +86 -5
- package/dist/capture.cjs +30 -153
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.d.cts +2 -25
- package/dist/capture.d.ts +2 -25
- package/dist/capture.js +5 -128
- package/dist/capture.js.map +1 -1
- package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs +102 -0
- package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs.map +1 -0
- package/dist/chunks/clipboard-adapter-CtH4VELE.d.cts +43 -0
- package/dist/chunks/clipboard-adapter-DEXkXxwV.js +97 -0
- package/dist/chunks/clipboard-adapter-DEXkXxwV.js.map +1 -0
- package/dist/chunks/clipboard-adapter-Ds0irroN.d.ts +43 -0
- package/dist/chunks/contrast-C6CVklEI.cjs +842 -0
- package/dist/chunks/contrast-C6CVklEI.cjs.map +1 -0
- package/dist/chunks/contrast-DpK2JIVu.js +789 -0
- package/dist/chunks/contrast-DpK2JIVu.js.map +1 -0
- package/dist/chunks/copy-interceptor-C6NABy1l.d.ts +141 -0
- package/dist/chunks/copy-interceptor-CZWzGOkL.d.cts +141 -0
- package/dist/chunks/core-Cp2HSpaz.js +1035 -0
- package/dist/chunks/core-Cp2HSpaz.js.map +1 -0
- package/dist/chunks/core-DYf_Lhbe.cjs +1142 -0
- package/dist/chunks/core-DYf_Lhbe.cjs.map +1 -0
- package/dist/chunks/deadline-C29AlS_Q.js +46 -0
- package/dist/chunks/deadline-C29AlS_Q.js.map +1 -0
- package/dist/chunks/deadline-DkiB8ZHE.cjs +51 -0
- package/dist/chunks/deadline-DkiB8ZHE.cjs.map +1 -0
- package/dist/chunks/errors-9h8sdFFX.js +120 -0
- package/dist/chunks/errors-9h8sdFFX.js.map +1 -0
- package/dist/chunks/errors-BwOF6T_M.cjs +167 -0
- package/dist/chunks/errors-BwOF6T_M.cjs.map +1 -0
- package/dist/chunks/index-mr7sSAgP.d.ts +426 -0
- package/dist/chunks/index-vz0iW5V2.d.cts +426 -0
- package/dist/chunks/inert-html-D75NyVvT.js +34 -0
- package/dist/chunks/inert-html-D75NyVvT.js.map +1 -0
- package/dist/chunks/inert-html-DyxjWDok.cjs +39 -0
- package/dist/chunks/inert-html-DyxjWDok.cjs.map +1 -0
- package/dist/chunks/mime--LB7kdqG.cjs +153 -0
- package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
- package/dist/chunks/mime-aa-HA2dm.js +100 -0
- package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
- package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
- package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
- package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
- package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
- package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
- package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
- package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
- package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
- package/dist/chunks/payload-CUymxwim.cjs +100 -0
- package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
- package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
- package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
- package/dist/chunks/payload-DGw-JOo7.js +71 -0
- package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
- package/dist/chunks/payload-DI5AorDz.js +103 -0
- package/dist/chunks/payload-DI5AorDz.js.map +1 -0
- package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
- package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
- package/dist/chunks/share-Bop47Znn.js +208 -0
- package/dist/chunks/share-Bop47Znn.js.map +1 -0
- package/dist/chunks/share-C0esXvRK.d.cts +115 -0
- package/dist/chunks/share-ayDz974N.cjs +231 -0
- package/dist/chunks/share-ayDz974N.cjs.map +1 -0
- package/dist/chunks/share-e7FenIr2.d.ts +115 -0
- package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
- package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
- package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
- package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
- package/dist/chunks/text-field-DUvrMMaK.js +66 -0
- package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
- package/dist/chunks/url-B9jdFGQy.cjs +86 -0
- package/dist/chunks/url-B9jdFGQy.cjs.map +1 -0
- package/dist/chunks/url-BcMYVCXQ.js +135 -0
- package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
- package/dist/chunks/url-D4PGsRm8.cjs +164 -0
- package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
- package/dist/chunks/url-DWdElCT3.d.cts +43 -0
- package/dist/chunks/url-DWdElCT3.d.ts +43 -0
- package/dist/chunks/url-vJaFPbNL.js +57 -0
- package/dist/chunks/url-vJaFPbNL.js.map +1 -0
- package/dist/code.cjs +22 -113
- package/dist/code.cjs.map +1 -1
- package/dist/code.d.cts +4 -28
- package/dist/code.d.ts +4 -28
- package/dist/code.js +5 -96
- package/dist/code.js.map +1 -1
- package/dist/color.cjs +21 -893
- package/dist/color.cjs.map +1 -1
- package/dist/color.d.cts +4 -28
- package/dist/color.d.ts +4 -28
- package/dist/color.js +4 -876
- package/dist/color.js.map +1 -1
- package/dist/core.cjs +52 -1659
- package/dist/core.d.cts +8 -878
- package/dist/core.d.ts +8 -878
- package/dist/core.js +7 -1614
- package/dist/image.cjs +23 -94
- package/dist/image.cjs.map +1 -1
- package/dist/image.d.cts +1 -0
- package/dist/image.d.ts +1 -0
- package/dist/image.js +3 -74
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +74 -2072
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -978
- package/dist/index.d.ts +8 -978
- package/dist/index.js +7 -2005
- package/dist/index.js.map +1 -1
- package/dist/link.cjs +26 -339
- package/dist/link.cjs.map +1 -1
- package/dist/link.d.cts +5 -83
- package/dist/link.d.ts +5 -83
- package/dist/link.js +7 -320
- package/dist/link.js.map +1 -1
- package/dist/markdown.cjs +19 -159
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.d.cts +3 -16
- package/dist/markdown.d.ts +3 -16
- package/dist/markdown.js +6 -146
- package/dist/markdown.js.map +1 -1
- package/dist/rich.cjs +1123 -940
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +101 -91
- package/dist/rich.d.ts +101 -91
- package/dist/rich.js +1099 -919
- package/dist/rich.js.map +1 -1
- package/dist/share.cjs +5 -640
- package/dist/share.d.cts +3 -248
- package/dist/share.d.ts +3 -248
- package/dist/share.js +1 -637
- package/dist/structured.cjs +13 -95
- package/dist/structured.cjs.map +1 -1
- package/dist/structured.d.cts +2 -11
- package/dist/structured.d.ts +2 -11
- package/dist/structured.js +4 -86
- package/dist/structured.js.map +1 -1
- package/dist/table.cjs +13 -40
- package/dist/table.cjs.map +1 -1
- package/dist/table.d.cts +2 -12
- package/dist/table.d.ts +2 -12
- package/dist/table.js +4 -31
- package/dist/table.js.map +1 -1
- package/dist/testing.cjs +10 -43
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +6 -181
- package/dist/testing.d.ts +6 -181
- package/dist/testing.js +3 -36
- package/dist/testing.js.map +1 -1
- package/package.json +37 -5
- package/dist/core.cjs.map +0 -1
- package/dist/core.js.map +0 -1
- package/dist/share.cjs.map +0 -1
- package/dist/share.js.map +0 -1
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/** 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;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,SAAgB,Y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,GAAG;GAAS,QAAQ,WAAW;EAAO,CAAC,CAAC,CAAC,cAAc;GACxF,EAAE,oBAAoB,SAAS,QAAQ;GACvC,EAAE,oBAAoB,SAAS,QAAQ;EACzC,CAAC;CACH;AACF;;AAGA,SAAgB,aACd,SACA,UAAiC,CAAC,GACpB;CACd,OAAO;EAAE,MAAM;EAAS,MAAM,cAAc,SAAS,OAAO;CAAE;AAChE"}
|
|
1
|
+
{"version":3,"file":"capture.cjs","names":["copyFailure","copyFailure","isCopyFailure","copyFailure","withDeadline","sniffImageType","IMAGE_MIME_TYPE","copyFailure","SVG_MIME_TYPE","copyFailure","isBlob","withDeadline"],"sources":["../src/capture/environment.ts","../src/capture/options.ts","../src/capture/render.ts","../src/capture/svg.ts","../src/capture/element.ts"],"sourcesContent":["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","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":";;;;;;;AAgCA,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,gBAAgB;GACpB,OAAOA,eAAAA,YAAY,0BAA0B,iCAAiC,CAAC;EACjF;EACA,MAAM,MAAM;CACd,CAAC;AACH;AAEA,SAAS,UAAU,OAAqB,QAAkC;CACxE,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,SAAS,cAAc,QAAQ;EAC9C,OAAO,QAAQ,OAAO;EACtB,OAAO,SAAS,OAAO;EACvB,MAAM,UAAU,OAAO,WAAW,IAAI;EACtC,IAAI,CAAC,SAAS;GACZ,OAAOA,eAAAA,YAAY,eAAe,uCAAuC,CAAC;GAC1E;EACF;EACA,IAAI,OAAO,eAAe,MAAM;GAC9B,QAAQ,YAAY,OAAO;GAC3B,QAAQ,SAAS,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;EACpD;EACA,QAAQ,UAAU,MAAM,QAA6B,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;EAEtF,OAAO,QAAQ,SAAS;GACtB,I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.d.ts
|
|
2
4
|
/** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */
|
|
3
5
|
interface DecodedImage {
|
|
@@ -80,31 +82,6 @@ export declare function ensureSvgNamespace(markup: string): string;
|
|
|
80
82
|
*/
|
|
81
83
|
export declare function svgToPngBlob(source: Element | string, options?: SvgToPngOptions): Promise<Blob>;
|
|
82
84
|
//#endregion
|
|
83
|
-
//#region src/core/machine-shared.d.ts
|
|
84
|
-
/**
|
|
85
|
-
* Passed to adapters and lazy sources as their last argument. `signal` aborts
|
|
86
|
-
* when the operation is superseded, `reset()`, or its host unmounts, so
|
|
87
|
-
* expensive work (rasterising, decoding) can stop early.
|
|
88
|
-
*/
|
|
89
|
-
interface OperationContext {
|
|
90
|
-
readonly signal: AbortSignal;
|
|
91
|
-
}
|
|
92
|
-
//#endregion
|
|
93
|
-
//#region src/core/payload.d.ts
|
|
94
|
-
/**
|
|
95
|
-
* An image as a Blob, a promise of one, or a function producing one.
|
|
96
|
-
* Prefer the function form: it is invoked synchronously inside the user
|
|
97
|
-
* gesture, which Safari requires for async image generation. The browser
|
|
98
|
-
* adapter always passes an `OperationContext`: stop work once
|
|
99
|
-
* `context.signal` aborts (reset, superseded, unmount). Optional in the type
|
|
100
|
-
* so adapters that call sources themselves keep compiling.
|
|
101
|
-
*/
|
|
102
|
-
type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
|
|
103
|
-
interface ImagePayload {
|
|
104
|
-
readonly kind: 'image';
|
|
105
|
-
readonly blob: BlobSource;
|
|
106
|
-
}
|
|
107
|
-
//#endregion
|
|
108
85
|
//#region src/capture/element.d.ts
|
|
109
86
|
/** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */
|
|
110
87
|
interface CanvasLike {
|
package/dist/capture.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
|
|
2
|
+
import { c as ImagePayload, k as OperationContext } from "./chunks/payload-Cl_8hCI5.js";
|
|
1
3
|
//#region src/capture/environment.d.ts
|
|
2
4
|
/** A decoded image, ready to be drawn. `source` is platform-specific (an `HTMLImageElement` in browsers). */
|
|
3
5
|
interface DecodedImage {
|
|
@@ -80,31 +82,6 @@ export declare function ensureSvgNamespace(markup: string): string;
|
|
|
80
82
|
*/
|
|
81
83
|
export declare function svgToPngBlob(source: Element | string, options?: SvgToPngOptions): Promise<Blob>;
|
|
82
84
|
//#endregion
|
|
83
|
-
//#region src/core/machine-shared.d.ts
|
|
84
|
-
/**
|
|
85
|
-
* Passed to adapters and lazy sources as their last argument. `signal` aborts
|
|
86
|
-
* when the operation is superseded, `reset()`, or its host unmounts, so
|
|
87
|
-
* expensive work (rasterising, decoding) can stop early.
|
|
88
|
-
*/
|
|
89
|
-
interface OperationContext {
|
|
90
|
-
readonly signal: AbortSignal;
|
|
91
|
-
}
|
|
92
|
-
//#endregion
|
|
93
|
-
//#region src/core/payload.d.ts
|
|
94
|
-
/**
|
|
95
|
-
* An image as a Blob, a promise of one, or a function producing one.
|
|
96
|
-
* Prefer the function form: it is invoked synchronously inside the user
|
|
97
|
-
* gesture, which Safari requires for async image generation. The browser
|
|
98
|
-
* adapter always passes an `OperationContext`: stop work once
|
|
99
|
-
* `context.signal` aborts (reset, superseded, unmount). Optional in the type
|
|
100
|
-
* so adapters that call sources themselves keep compiling.
|
|
101
|
-
*/
|
|
102
|
-
type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
|
|
103
|
-
interface ImagePayload {
|
|
104
|
-
readonly kind: 'image';
|
|
105
|
-
readonly blob: BlobSource;
|
|
106
|
-
}
|
|
107
|
-
//#endregion
|
|
108
85
|
//#region src/capture/element.d.ts
|
|
109
86
|
/** Anything with `canvas.toBlob()`: `HTMLCanvasElement`, or a compatible object. */
|
|
110
87
|
interface CanvasLike {
|
package/dist/capture.js
CHANGED
|
@@ -1,36 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
} : {
|
|
7
|
-
type,
|
|
8
|
-
message,
|
|
9
|
-
cause
|
|
10
|
-
};
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Branded (not `instanceof`) so failures stay recognisable even when the core
|
|
14
|
-
* is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
|
|
15
|
-
*/
|
|
16
|
-
const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
|
|
17
|
-
/** Error thrown by adapters to carry a fully classified {@link CopyError}. */
|
|
18
|
-
var CopyFailure = class extends Error {
|
|
19
|
-
constructor(copyError) {
|
|
20
|
-
super(copyError.message);
|
|
21
|
-
this[COPY_FAILURE_BRAND] = true;
|
|
22
|
-
this.name = "CopyFailure";
|
|
23
|
-
this.copyError = copyError;
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
function isCopyFailure(value) {
|
|
27
|
-
return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
|
|
28
|
-
}
|
|
29
|
-
/** Shorthand for throwing a classified failure. */
|
|
30
|
-
function copyFailure(type, message, cause) {
|
|
31
|
-
return new CopyFailure(createCopyError(type, message, cause));
|
|
32
|
-
}
|
|
33
|
-
//#endregion
|
|
1
|
+
|
|
2
|
+
import { n as copyFailure, o as isCopyFailure } from "./chunks/errors-9h8sdFFX.js";
|
|
3
|
+
import { n as isBlob, t as IMAGE_MIME_TYPE } from "./chunks/payload-DGw-JOo7.js";
|
|
4
|
+
import { l as sniffImageType, t as SVG_MIME_TYPE } from "./chunks/mime-aa-HA2dm.js";
|
|
5
|
+
import { t as withDeadline } from "./chunks/deadline-C29AlS_Q.js";
|
|
34
6
|
//#region src/capture/environment.ts
|
|
35
7
|
function loadImage(url) {
|
|
36
8
|
return new Promise((resolve, reject) => {
|
|
@@ -143,101 +115,6 @@ function assertPixelBudget(width, height, maxPixels) {
|
|
|
143
115
|
if (width * height > maxPixels) throw copyFailure("too-large", `A ${String(width)}×${String(height)} image exceeds the ${String(maxPixels)}-pixel limit. Lower \`scale\` or raise \`maxPixels\`.`);
|
|
144
116
|
}
|
|
145
117
|
//#endregion
|
|
146
|
-
//#region src/core/mime.ts
|
|
147
|
-
/** SVG is XML that can carry scripts; it is never matched by a wildcard. */
|
|
148
|
-
const SVG_MIME_TYPE = "image/svg+xml";
|
|
149
|
-
const SNIFF_BYTES = 16;
|
|
150
|
-
function startsWith(bytes, signature, offset = 0) {
|
|
151
|
-
return signature.every((byte, index) => bytes[offset + index] === byte);
|
|
152
|
-
}
|
|
153
|
-
const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
|
|
154
|
-
const PNG = [
|
|
155
|
-
137,
|
|
156
|
-
80,
|
|
157
|
-
78,
|
|
158
|
-
71,
|
|
159
|
-
13,
|
|
160
|
-
10,
|
|
161
|
-
26,
|
|
162
|
-
10
|
|
163
|
-
];
|
|
164
|
-
const JPEG = [
|
|
165
|
-
255,
|
|
166
|
-
216,
|
|
167
|
-
255
|
|
168
|
-
];
|
|
169
|
-
const GIF = ascii("GIF8");
|
|
170
|
-
const RIFF = ascii("RIFF");
|
|
171
|
-
const WEBP = ascii("WEBP");
|
|
172
|
-
const BMP = ascii("BM");
|
|
173
|
-
const FTYP_AVIF = ascii("ftypavif");
|
|
174
|
-
const FTYP_AVIS = ascii("ftypavis");
|
|
175
|
-
/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
|
|
176
|
-
function sniffImageBytes(bytes) {
|
|
177
|
-
if (startsWith(bytes, PNG)) return "image/png";
|
|
178
|
-
if (startsWith(bytes, JPEG)) return "image/jpeg";
|
|
179
|
-
if (startsWith(bytes, GIF)) return "image/gif";
|
|
180
|
-
if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
|
|
181
|
-
if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
|
|
182
|
-
if (startsWith(bytes, BMP)) return "image/bmp";
|
|
183
|
-
return null;
|
|
184
|
-
}
|
|
185
|
-
/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
|
|
186
|
-
async function sniffImageType(blob) {
|
|
187
|
-
const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
|
|
188
|
-
return sniffImageBytes(new Uint8Array(head));
|
|
189
|
-
}
|
|
190
|
-
//#endregion
|
|
191
|
-
//#region src/core/payload.ts
|
|
192
|
-
/** The only image MIME type with reliable cross-browser clipboard write support. */
|
|
193
|
-
const IMAGE_MIME_TYPE = "image/png";
|
|
194
|
-
function isBlob(value) {
|
|
195
|
-
if (typeof Blob !== "undefined" && value instanceof Blob) return true;
|
|
196
|
-
const tag = Object.prototype.toString.call(value);
|
|
197
|
-
return tag === "[object Blob]" || tag === "[object File]";
|
|
198
|
-
}
|
|
199
|
-
//#endregion
|
|
200
|
-
//#region src/capture/deadline.ts
|
|
201
|
-
/**
|
|
202
|
-
* Runs `task` with a timeout and an optional caller `AbortSignal`. The task
|
|
203
|
-
* receives a signal that fires on either, so cooperative work can stop early.
|
|
204
|
-
* Rejects with classified `timeout` / `aborted` failures.
|
|
205
|
-
*/
|
|
206
|
-
function withDeadline(task, options) {
|
|
207
|
-
const { timeoutMs, label } = options;
|
|
208
|
-
const external = options.signal;
|
|
209
|
-
if (external?.aborted) return Promise.reject(copyFailure("aborted", `${label} was aborted.`, external.reason));
|
|
210
|
-
const controller = new AbortController();
|
|
211
|
-
return new Promise((resolve, reject) => {
|
|
212
|
-
const finish = (abort) => {
|
|
213
|
-
clearTimeout(timer);
|
|
214
|
-
external?.removeEventListener("abort", onAbort);
|
|
215
|
-
/* c8 ignore next -- abort=false path is never used; kept for future API flexibility */
|
|
216
|
-
if (abort) controller.abort();
|
|
217
|
-
};
|
|
218
|
-
const fail = (failure) => {
|
|
219
|
-
finish(true);
|
|
220
|
-
reject(failure);
|
|
221
|
-
};
|
|
222
|
-
const onAbort = () => {
|
|
223
|
-
fail(copyFailure("aborted", `${label} was aborted.`, external.reason));
|
|
224
|
-
};
|
|
225
|
-
const timer = timeoutMs === Infinity ? void 0 : setTimeout(() => {
|
|
226
|
-
fail(copyFailure("timeout", `${label} timed out after ${String(timeoutMs)} ms.`));
|
|
227
|
-
}, timeoutMs);
|
|
228
|
-
external?.addEventListener("abort", onAbort, { once: true });
|
|
229
|
-
new Promise((run) => {
|
|
230
|
-
run(task(controller.signal));
|
|
231
|
-
}).then((value) => {
|
|
232
|
-
finish(true);
|
|
233
|
-
resolve(value);
|
|
234
|
-
}, (cause) => {
|
|
235
|
-
finish(true);
|
|
236
|
-
reject(cause);
|
|
237
|
-
});
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
//#endregion
|
|
241
118
|
//#region src/capture/render.ts
|
|
242
119
|
/** Maps anything unexpected to `blob-generation-failed`, keeping already-classified failures. */
|
|
243
120
|
function classifyCaptureError(cause, label) {
|