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/testing.d.cts
CHANGED
|
@@ -1,183 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
*/
|
|
7
|
-
interface OperationContext {
|
|
8
|
-
readonly signal: AbortSignal;
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
//#region src/core/paste-reader.d.ts
|
|
12
|
-
/** Validated, normalised options that adapters receive. */
|
|
13
|
-
interface ResolvedPasteReadOptions {
|
|
14
|
-
/** Normalised patterns: `type/subtype`, `type/*` or `*\/*`. */
|
|
15
|
-
readonly accept: readonly string[];
|
|
16
|
-
readonly maxBytes: number;
|
|
17
|
-
readonly maxItems: number;
|
|
18
|
-
}
|
|
19
|
-
/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */
|
|
20
|
-
type PasteSource = 'clipboard' | 'event' | 'drop';
|
|
21
|
-
/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */
|
|
22
|
-
interface PasteItem {
|
|
23
|
-
readonly type: string;
|
|
24
|
-
readonly data: string | Blob;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Everything the paste produced. Treat all of it as untrusted user input:
|
|
28
|
-
* in particular never inject `html` into the DOM without sanitising it.
|
|
29
|
-
*/
|
|
30
|
-
interface PasteResult {
|
|
31
|
-
readonly source: PasteSource;
|
|
32
|
-
/** Every accepted entry, in clipboard order. */
|
|
33
|
-
readonly items: readonly PasteItem[];
|
|
34
|
-
/** `text/plain`, when accepted and present. */
|
|
35
|
-
readonly text: string | null;
|
|
36
|
-
/** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */
|
|
37
|
-
readonly html: string | null;
|
|
38
|
-
/** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */
|
|
39
|
-
readonly images: readonly Blob[];
|
|
40
|
-
/** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
|
|
41
|
-
readonly files: readonly File[];
|
|
42
|
-
/**
|
|
43
|
-
* The entries of `files` that are also in `images`: verified image files, keeping their
|
|
44
|
-
* names, ready for `FormData`. Derived by the paste machine, so it is always consistent.
|
|
45
|
-
*/
|
|
46
|
-
readonly imageFiles: readonly File[];
|
|
47
|
-
}
|
|
48
|
-
/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */
|
|
49
|
-
type PasteReadResult = Omit<PasteResult, 'imageFiles'>;
|
|
50
|
-
//#endregion
|
|
51
|
-
//#region src/core/errors.d.ts
|
|
52
|
-
/**
|
|
53
|
-
* Every way a clipboard operation can fail, as a closed union.
|
|
54
|
-
*
|
|
55
|
-
* `CopyError.message` is developer-facing (logs, telemetry). For user-facing
|
|
56
|
-
* text use {@link describeCopyError} / {@link describePasteError}, or map
|
|
57
|
-
* `type` through your own i18n layer.
|
|
58
|
-
*/
|
|
59
|
-
type CopyErrorType =
|
|
60
|
-
/** No Clipboard API (old browser, server, locked-down webview). Not retryable. */
|
|
61
|
-
'unsupported' |
|
|
62
|
-
/** Page is not served over HTTPS/localhost. Not retryable. */
|
|
63
|
-
'insecure-context' |
|
|
64
|
-
/** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */
|
|
65
|
-
'permission-denied' |
|
|
66
|
-
/** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */
|
|
67
|
-
'not-focused' |
|
|
68
|
-
/** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */
|
|
69
|
-
'invalid-payload' |
|
|
70
|
-
/** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */
|
|
71
|
-
'unsupported-format' |
|
|
72
|
-
/** A lazy image source (or capture) threw, rejected or did not produce a Blob. */
|
|
73
|
-
'blob-generation-failed' |
|
|
74
|
-
/** `retry()` was called after `maxRetries` was reached. Terminal. */
|
|
75
|
-
'max-retries-exceeded' |
|
|
76
|
-
/** Paste: the clipboard held nothing matching `accept`. */
|
|
77
|
-
'no-content' |
|
|
78
|
-
/** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */
|
|
79
|
-
'too-large' |
|
|
80
|
-
/** An operation did not settle within its deadline. Retryable. */
|
|
81
|
-
'timeout' |
|
|
82
|
-
/** The caller aborted the operation through an `AbortSignal`. Not retryable. */
|
|
83
|
-
'aborted' |
|
|
84
|
-
/** Anything the platform threw that we could not classify. */
|
|
85
|
-
'unknown';
|
|
86
|
-
interface CopyError {
|
|
87
|
-
readonly type: CopyErrorType;
|
|
88
|
-
readonly message: string;
|
|
89
|
-
readonly cause?: unknown;
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Branded (not `instanceof`) so failures stay recognisable even when the core
|
|
93
|
-
* is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
|
|
94
|
-
*/
|
|
95
|
-
declare const COPY_FAILURE_BRAND: unique symbol;
|
|
96
|
-
/** Error thrown by adapters to carry a fully classified {@link CopyError}. */
|
|
97
|
-
export declare class CopyFailure extends Error {
|
|
98
|
-
readonly copyError: CopyError;
|
|
99
|
-
readonly [COPY_FAILURE_BRAND] = true;
|
|
100
|
-
constructor(copyError: CopyError);
|
|
101
|
-
}
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/core/payload.d.ts
|
|
104
|
-
/**
|
|
105
|
-
* An image as a Blob, a promise of one, or a function producing one.
|
|
106
|
-
* Prefer the function form: it is invoked synchronously inside the user
|
|
107
|
-
* gesture, which Safari requires for async image generation. The browser
|
|
108
|
-
* adapter always passes an `OperationContext`: stop work once
|
|
109
|
-
* `context.signal` aborts (reset, superseded, unmount). Optional in the type
|
|
110
|
-
* so adapters that call sources themselves keep compiling.
|
|
111
|
-
*/
|
|
112
|
-
type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
|
|
113
|
-
interface TextPayload {
|
|
114
|
-
readonly kind: 'text';
|
|
115
|
-
readonly value: string;
|
|
116
|
-
}
|
|
117
|
-
interface HtmlPayload {
|
|
118
|
-
readonly kind: 'html';
|
|
119
|
-
readonly html: string;
|
|
120
|
-
/** Required plain-text fallback for targets that don't understand HTML. */
|
|
121
|
-
readonly text: string;
|
|
122
|
-
}
|
|
123
|
-
interface ImagePayload {
|
|
124
|
-
readonly kind: 'image';
|
|
125
|
-
readonly blob: BlobSource;
|
|
126
|
-
}
|
|
127
|
-
interface JsonPayload {
|
|
128
|
-
readonly kind: 'json';
|
|
129
|
-
readonly value: unknown;
|
|
130
|
-
/** `true` = 2-space indent, a number = that indent, falsy = compact. */
|
|
131
|
-
readonly pretty?: boolean | number;
|
|
132
|
-
}
|
|
133
|
-
interface MultiPayloadItem {
|
|
134
|
-
/**
|
|
135
|
-
* The MIME type, or a web custom format (`web application/vnd.acme+json`).
|
|
136
|
-
* Web custom formats are only written by the async Clipboard API; copy and drag
|
|
137
|
-
* events skip them.
|
|
138
|
-
*/
|
|
139
|
-
readonly mimeType: string;
|
|
140
|
-
readonly data: string | Blob;
|
|
141
|
-
/**
|
|
142
|
-
* Skip this item, instead of failing the copy, when the browser cannot write its type.
|
|
143
|
-
* An optional item is only written when `ClipboardItem.supports()` confirms the type.
|
|
144
|
-
* At least one item must be written.
|
|
145
|
-
*/
|
|
146
|
-
readonly optional?: boolean;
|
|
147
|
-
}
|
|
148
|
-
interface MultiPayload {
|
|
149
|
-
readonly kind: 'multi';
|
|
150
|
-
readonly items: readonly MultiPayloadItem[];
|
|
151
|
-
}
|
|
152
|
-
type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;
|
|
153
|
-
//#endregion
|
|
154
|
-
//#region src/core/clipboard-adapter.d.ts
|
|
155
|
-
/**
|
|
156
|
-
* The only thing the state machine needs. Implement it to target Electron,
|
|
157
|
-
* a native bridge, a test double, or anything else.
|
|
158
|
-
*
|
|
159
|
-
* Contract: start the platform write synchronously (before any `await`) so the
|
|
160
|
-
* browser still sees the user gesture, and reject with a `CopyFailure` when you
|
|
161
|
-
* can classify the error. `context.signal` aborts when the copy is reset or its
|
|
162
|
-
* host unmounts; honour it to stop expensive work early.
|
|
163
|
-
*/
|
|
164
|
-
interface ClipboardAdapter {
|
|
165
|
-
write(payload: CopyPayload, context?: OperationContext): Promise<void>;
|
|
166
|
-
}
|
|
167
|
-
//#endregion
|
|
168
|
-
//#region src/core/paste-adapter.d.ts
|
|
169
|
-
/**
|
|
170
|
-
* Reads the system clipboard. Implement it for Electron, a native bridge or tests.
|
|
171
|
-
*
|
|
172
|
-
* Contract: call the platform API synchronously (before any `await`) so the
|
|
173
|
-
* browser still sees the user gesture, and reject with a `CopyFailure`.
|
|
174
|
-
* `context.signal` aborts when the read is superseded, reset, or its host
|
|
175
|
-
* unmounts; honour it to stop decoding early.
|
|
176
|
-
*/
|
|
177
|
-
interface PasteAdapter {
|
|
178
|
-
read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;
|
|
179
|
-
}
|
|
180
|
-
//#endregion
|
|
1
|
+
|
|
2
|
+
import { b as CopyFailure, r as CopyPayload, v as CopyError } from "./chunks/payload-CcwKJ_bU.cjs";
|
|
3
|
+
import { f as PasteReadResult, l as PasteItem, m as PasteSource, p as PasteResult } from "./chunks/paste-reader-DcXnRWQr.cjs";
|
|
4
|
+
import { n as ClipboardAdapter } from "./chunks/clipboard-adapter-CtH4VELE.cjs";
|
|
5
|
+
import { n as PasteAdapter } from "./chunks/paste-adapter--SPL4PRE.cjs";
|
|
181
6
|
//#region src/testing/index.d.ts
|
|
182
7
|
/**
|
|
183
8
|
* Input for {@link createPasteResult}: every field is optional so callers
|
|
@@ -316,5 +141,5 @@ export interface MockClipboardAdapter {
|
|
|
316
141
|
*/
|
|
317
142
|
export declare function createMockClipboardAdapter(): MockClipboardAdapter;
|
|
318
143
|
//#endregion
|
|
319
|
-
export type
|
|
144
|
+
export { type ClipboardAdapter, type CopyError, CopyFailure, type CopyPayload, type PasteAdapter, type PasteItem, type PasteReadResult, type PasteResult, type PasteSource };
|
|
320
145
|
//# sourceMappingURL=testing.d.cts.map
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,183 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
*/
|
|
7
|
-
interface OperationContext {
|
|
8
|
-
readonly signal: AbortSignal;
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
//#region src/core/paste-reader.d.ts
|
|
12
|
-
/** Validated, normalised options that adapters receive. */
|
|
13
|
-
interface ResolvedPasteReadOptions {
|
|
14
|
-
/** Normalised patterns: `type/subtype`, `type/*` or `*\/*`. */
|
|
15
|
-
readonly accept: readonly string[];
|
|
16
|
-
readonly maxBytes: number;
|
|
17
|
-
readonly maxItems: number;
|
|
18
|
-
}
|
|
19
|
-
/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */
|
|
20
|
-
type PasteSource = 'clipboard' | 'event' | 'drop';
|
|
21
|
-
/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */
|
|
22
|
-
interface PasteItem {
|
|
23
|
-
readonly type: string;
|
|
24
|
-
readonly data: string | Blob;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Everything the paste produced. Treat all of it as untrusted user input:
|
|
28
|
-
* in particular never inject `html` into the DOM without sanitising it.
|
|
29
|
-
*/
|
|
30
|
-
interface PasteResult {
|
|
31
|
-
readonly source: PasteSource;
|
|
32
|
-
/** Every accepted entry, in clipboard order. */
|
|
33
|
-
readonly items: readonly PasteItem[];
|
|
34
|
-
/** `text/plain`, when accepted and present. */
|
|
35
|
-
readonly text: string | null;
|
|
36
|
-
/** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */
|
|
37
|
-
readonly html: string | null;
|
|
38
|
-
/** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */
|
|
39
|
-
readonly images: readonly Blob[];
|
|
40
|
-
/** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */
|
|
41
|
-
readonly files: readonly File[];
|
|
42
|
-
/**
|
|
43
|
-
* The entries of `files` that are also in `images`: verified image files, keeping their
|
|
44
|
-
* names, ready for `FormData`. Derived by the paste machine, so it is always consistent.
|
|
45
|
-
*/
|
|
46
|
-
readonly imageFiles: readonly File[];
|
|
47
|
-
}
|
|
48
|
-
/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */
|
|
49
|
-
type PasteReadResult = Omit<PasteResult, 'imageFiles'>;
|
|
50
|
-
//#endregion
|
|
51
|
-
//#region src/core/errors.d.ts
|
|
52
|
-
/**
|
|
53
|
-
* Every way a clipboard operation can fail, as a closed union.
|
|
54
|
-
*
|
|
55
|
-
* `CopyError.message` is developer-facing (logs, telemetry). For user-facing
|
|
56
|
-
* text use {@link describeCopyError} / {@link describePasteError}, or map
|
|
57
|
-
* `type` through your own i18n layer.
|
|
58
|
-
*/
|
|
59
|
-
type CopyErrorType =
|
|
60
|
-
/** No Clipboard API (old browser, server, locked-down webview). Not retryable. */
|
|
61
|
-
'unsupported' |
|
|
62
|
-
/** Page is not served over HTTPS/localhost. Not retryable. */
|
|
63
|
-
'insecure-context' |
|
|
64
|
-
/** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */
|
|
65
|
-
'permission-denied' |
|
|
66
|
-
/** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */
|
|
67
|
-
'not-focused' |
|
|
68
|
-
/** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */
|
|
69
|
-
'invalid-payload' |
|
|
70
|
-
/** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */
|
|
71
|
-
'unsupported-format' |
|
|
72
|
-
/** A lazy image source (or capture) threw, rejected or did not produce a Blob. */
|
|
73
|
-
'blob-generation-failed' |
|
|
74
|
-
/** `retry()` was called after `maxRetries` was reached. Terminal. */
|
|
75
|
-
'max-retries-exceeded' |
|
|
76
|
-
/** Paste: the clipboard held nothing matching `accept`. */
|
|
77
|
-
'no-content' |
|
|
78
|
-
/** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */
|
|
79
|
-
'too-large' |
|
|
80
|
-
/** An operation did not settle within its deadline. Retryable. */
|
|
81
|
-
'timeout' |
|
|
82
|
-
/** The caller aborted the operation through an `AbortSignal`. Not retryable. */
|
|
83
|
-
'aborted' |
|
|
84
|
-
/** Anything the platform threw that we could not classify. */
|
|
85
|
-
'unknown';
|
|
86
|
-
interface CopyError {
|
|
87
|
-
readonly type: CopyErrorType;
|
|
88
|
-
readonly message: string;
|
|
89
|
-
readonly cause?: unknown;
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Branded (not `instanceof`) so failures stay recognisable even when the core
|
|
93
|
-
* is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
|
|
94
|
-
*/
|
|
95
|
-
declare const COPY_FAILURE_BRAND: unique symbol;
|
|
96
|
-
/** Error thrown by adapters to carry a fully classified {@link CopyError}. */
|
|
97
|
-
export declare class CopyFailure extends Error {
|
|
98
|
-
readonly copyError: CopyError;
|
|
99
|
-
readonly [COPY_FAILURE_BRAND] = true;
|
|
100
|
-
constructor(copyError: CopyError);
|
|
101
|
-
}
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/core/payload.d.ts
|
|
104
|
-
/**
|
|
105
|
-
* An image as a Blob, a promise of one, or a function producing one.
|
|
106
|
-
* Prefer the function form: it is invoked synchronously inside the user
|
|
107
|
-
* gesture, which Safari requires for async image generation. The browser
|
|
108
|
-
* adapter always passes an `OperationContext`: stop work once
|
|
109
|
-
* `context.signal` aborts (reset, superseded, unmount). Optional in the type
|
|
110
|
-
* so adapters that call sources themselves keep compiling.
|
|
111
|
-
*/
|
|
112
|
-
type BlobSource = Blob | PromiseLike<Blob> | ((context?: OperationContext) => Blob | PromiseLike<Blob>);
|
|
113
|
-
interface TextPayload {
|
|
114
|
-
readonly kind: 'text';
|
|
115
|
-
readonly value: string;
|
|
116
|
-
}
|
|
117
|
-
interface HtmlPayload {
|
|
118
|
-
readonly kind: 'html';
|
|
119
|
-
readonly html: string;
|
|
120
|
-
/** Required plain-text fallback for targets that don't understand HTML. */
|
|
121
|
-
readonly text: string;
|
|
122
|
-
}
|
|
123
|
-
interface ImagePayload {
|
|
124
|
-
readonly kind: 'image';
|
|
125
|
-
readonly blob: BlobSource;
|
|
126
|
-
}
|
|
127
|
-
interface JsonPayload {
|
|
128
|
-
readonly kind: 'json';
|
|
129
|
-
readonly value: unknown;
|
|
130
|
-
/** `true` = 2-space indent, a number = that indent, falsy = compact. */
|
|
131
|
-
readonly pretty?: boolean | number;
|
|
132
|
-
}
|
|
133
|
-
interface MultiPayloadItem {
|
|
134
|
-
/**
|
|
135
|
-
* The MIME type, or a web custom format (`web application/vnd.acme+json`).
|
|
136
|
-
* Web custom formats are only written by the async Clipboard API; copy and drag
|
|
137
|
-
* events skip them.
|
|
138
|
-
*/
|
|
139
|
-
readonly mimeType: string;
|
|
140
|
-
readonly data: string | Blob;
|
|
141
|
-
/**
|
|
142
|
-
* Skip this item, instead of failing the copy, when the browser cannot write its type.
|
|
143
|
-
* An optional item is only written when `ClipboardItem.supports()` confirms the type.
|
|
144
|
-
* At least one item must be written.
|
|
145
|
-
*/
|
|
146
|
-
readonly optional?: boolean;
|
|
147
|
-
}
|
|
148
|
-
interface MultiPayload {
|
|
149
|
-
readonly kind: 'multi';
|
|
150
|
-
readonly items: readonly MultiPayloadItem[];
|
|
151
|
-
}
|
|
152
|
-
type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;
|
|
153
|
-
//#endregion
|
|
154
|
-
//#region src/core/clipboard-adapter.d.ts
|
|
155
|
-
/**
|
|
156
|
-
* The only thing the state machine needs. Implement it to target Electron,
|
|
157
|
-
* a native bridge, a test double, or anything else.
|
|
158
|
-
*
|
|
159
|
-
* Contract: start the platform write synchronously (before any `await`) so the
|
|
160
|
-
* browser still sees the user gesture, and reject with a `CopyFailure` when you
|
|
161
|
-
* can classify the error. `context.signal` aborts when the copy is reset or its
|
|
162
|
-
* host unmounts; honour it to stop expensive work early.
|
|
163
|
-
*/
|
|
164
|
-
interface ClipboardAdapter {
|
|
165
|
-
write(payload: CopyPayload, context?: OperationContext): Promise<void>;
|
|
166
|
-
}
|
|
167
|
-
//#endregion
|
|
168
|
-
//#region src/core/paste-adapter.d.ts
|
|
169
|
-
/**
|
|
170
|
-
* Reads the system clipboard. Implement it for Electron, a native bridge or tests.
|
|
171
|
-
*
|
|
172
|
-
* Contract: call the platform API synchronously (before any `await`) so the
|
|
173
|
-
* browser still sees the user gesture, and reject with a `CopyFailure`.
|
|
174
|
-
* `context.signal` aborts when the read is superseded, reset, or its host
|
|
175
|
-
* unmounts; honour it to stop decoding early.
|
|
176
|
-
*/
|
|
177
|
-
interface PasteAdapter {
|
|
178
|
-
read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;
|
|
179
|
-
}
|
|
180
|
-
//#endregion
|
|
1
|
+
|
|
2
|
+
import { b as CopyFailure, r as CopyPayload, v as CopyError } from "./chunks/payload-Cl_8hCI5.js";
|
|
3
|
+
import { f as PasteReadResult, l as PasteItem, m as PasteSource, p as PasteResult } from "./chunks/paste-reader-DcXnRWQr.js";
|
|
4
|
+
import { n as ClipboardAdapter } from "./chunks/clipboard-adapter-Ds0irroN.js";
|
|
5
|
+
import { n as PasteAdapter } from "./chunks/paste-adapter-uahXnTYk.js";
|
|
181
6
|
//#region src/testing/index.d.ts
|
|
182
7
|
/**
|
|
183
8
|
* Input for {@link createPasteResult}: every field is optional so callers
|
|
@@ -316,5 +141,5 @@ export interface MockClipboardAdapter {
|
|
|
316
141
|
*/
|
|
317
142
|
export declare function createMockClipboardAdapter(): MockClipboardAdapter;
|
|
318
143
|
//#endregion
|
|
319
|
-
export type
|
|
144
|
+
export { type ClipboardAdapter, type CopyError, CopyFailure, type CopyPayload, type PasteAdapter, type PasteItem, type PasteReadResult, type PasteResult, type PasteSource };
|
|
320
145
|
//# sourceMappingURL=testing.d.ts.map
|
package/dist/testing.js
CHANGED
|
@@ -1,39 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
type,
|
|
5
|
-
message
|
|
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
|
-
//#endregion
|
|
27
|
-
//#region src/core/paste-reader.ts
|
|
28
|
-
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
29
|
-
function completePasteResult(result) {
|
|
30
|
-
const images = new Set(result.images);
|
|
31
|
-
return {
|
|
32
|
-
...result,
|
|
33
|
-
imageFiles: result.files.filter((file) => images.has(file))
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
//#endregion
|
|
1
|
+
|
|
2
|
+
import { r as createCopyError, t as CopyFailure } from "./chunks/errors-9h8sdFFX.js";
|
|
3
|
+
import { o as completePasteResult } from "./chunks/paste-reader-D9i7yMXF.js";
|
|
37
4
|
//#region src/testing/index.ts
|
|
38
5
|
/**
|
|
39
6
|
* Builds a complete, self-consistent {@link PasteResult} with sensible defaults.
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../src/core/errors.ts","../src/core/paste-reader.ts","../src/testing/index.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 './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n","/**\n * `react-smart-copy/testing`\n *\n * Test utilities for consumers of react-smart-copy.\n *\n * - {@link createPasteResult} — build a complete {@link PasteResult} with sensible defaults\n * so adding a new field in a future release never silently breaks your tests.\n * - {@link createMockPasteAdapter} — a controllable {@link PasteAdapter} for unit tests.\n * - {@link createMockClipboardAdapter} — a controllable {@link ClipboardAdapter} for unit tests.\n *\n * None of these modules import React or browser globals, so they work in Node / jsdom alike.\n *\n * @module\n */\n\nimport type { ClipboardAdapter } from '../core/clipboard-adapter';\nimport { CopyFailure, createCopyError, type CopyError } from '../core/errors';\nimport type { PasteAdapter } from '../core/paste-adapter';\nimport {\n completePasteResult,\n type PasteItem,\n type PasteReadResult,\n type PasteResult,\n type PasteSource,\n} from '../core/paste-reader';\nimport type { CopyPayload } from '../core/payload';\n\n/* ---------------------------------------------------------------- re-exports */\n\n// Re-export the things consumers most commonly need in their test files, so\n// they can use a single import path.\nexport type {\n ClipboardAdapter,\n CopyError,\n CopyPayload,\n PasteAdapter,\n PasteItem,\n PasteReadResult,\n PasteResult,\n PasteSource,\n};\nexport { CopyFailure };\n\n/* -------------------------------------------------------- createPasteResult */\n\n/**\n * Input for {@link createPasteResult}: every field is optional so callers\n * only specify what the test cares about.\n */\nexport interface PasteResultInit {\n readonly source?: PasteSource;\n readonly items?: readonly PasteItem[];\n readonly text?: string | null;\n readonly html?: string | null;\n readonly images?: readonly Blob[];\n readonly files?: readonly File[];\n}\n\n/**\n * Builds a complete, self-consistent {@link PasteResult} with sensible defaults.\n *\n * Prefer this over constructing `PasteResult` literals: when the library adds\n * a field (as it did in v1.3.0 and v1.4.0), your tests stay green without any\n * change on your end.\n *\n * ```ts\n * const result = createPasteResult({ text: 'hello', source: 'clipboard' });\n * // result.source → 'clipboard'\n * // result.text → 'hello'\n * // result.html → null\n * // result.images → []\n * // result.files → []\n * // result.imageFiles → []\n * // result.items → [{ type: 'text/plain', data: 'hello' }]\n * ```\n *\n * When `items` is not supplied it is derived from `text`, `html`, and `images`:\n * a `text/plain` entry for `text`, a `text/html` entry for `html`, and one\n * entry per image Blob. `imageFiles` is always computed from the intersection\n * of `images` and `files`, exactly as the machine does.\n *\n * @public\n */\nexport function createPasteResult(init: PasteResultInit = {}): PasteResult {\n const source: PasteSource = init.source ?? 'clipboard';\n const text: string | null = init.text ?? null;\n const html: string | null = init.html ?? null;\n const images: readonly Blob[] = init.images ?? [];\n const files: readonly File[] = init.files ?? [];\n\n let items: readonly PasteItem[];\n if (init.items !== undefined) {\n items = init.items;\n } else {\n const derived: PasteItem[] = [];\n if (text !== null) derived.push({ type: 'text/plain', data: text });\n if (html !== null) derived.push({ type: 'text/html', data: html });\n for (const blob of images) derived.push({ type: blob.type || 'image/png', data: blob });\n items = derived;\n }\n\n const partial: PasteReadResult = { source, items, text, html, images, files };\n return completePasteResult(partial);\n}\n\n/* -------------------------------------------------- createMockPasteAdapter */\n\n/**\n * A queue entry for the mock paste adapter: a {@link PasteReadResult} resolves\n * the next `read()` call; a {@link CopyError} rejects it.\n */\nexport type MockPasteEntry = PasteReadResult | CopyError;\n\n/**\n * The handle returned by {@link createMockPasteAdapter}.\n * @public\n */\nexport interface MockPasteAdapter {\n /** The adapter itself: pass this as `adapter` in machine / hook options. */\n readonly adapter: PasteAdapter;\n /**\n * Queue a successful result. When the adapter's `read()` is next called it\n * resolves with this value.\n */\n readonly queueResult: (result: PasteReadResult) => void;\n /**\n * Queue an error. When `read()` is next called it rejects with a\n * `CopyFailure` wrapping this error, which the machine maps to `error` state.\n */\n readonly queueError: (error: CopyError) => void;\n /**\n * How many times `read()` was called. Useful for asserting that the machine\n * did (or didn't) retry.\n */\n readonly readCount: () => number;\n /** Drain all pending queue entries and reset the read counter. */\n readonly reset: () => void;\n}\n\n/**\n * Creates a controllable paste adapter for unit tests.\n *\n * ```ts\n * const mock = createMockPasteAdapter();\n * mock.queueResult(createPasteResult({ text: 'hello' }));\n *\n * const machine = createPasteMachine({ adapter: mock.adapter });\n * await machine.paste();\n *\n * expect(machine.getSnapshot().status).toBe('read');\n * expect(mock.readCount()).toBe(1);\n * ```\n *\n * If `read()` is called when the queue is empty it rejects with a\n * `'no-content'` error so the machine transitions to `error` rather than\n * throwing.\n *\n * @public\n */\nexport function createMockPasteAdapter(): MockPasteAdapter {\n const queue: MockPasteEntry[] = [];\n let reads = 0;\n\n function isCopyError(entry: MockPasteEntry): entry is CopyError {\n return 'type' in entry && 'message' in entry && !('source' in entry);\n }\n\n const adapter: PasteAdapter = {\n read: (_options, context): Promise<PasteReadResult> => {\n reads += 1;\n\n if (context?.signal.aborted) {\n return Promise.reject(new CopyFailure(createCopyError('aborted', 'The paste was cancelled.')));\n }\n\n const entry = queue.shift();\n if (entry === undefined) {\n return Promise.reject(\n new CopyFailure(createCopyError('no-content', 'Mock paste adapter: queue is empty.')),\n );\n }\n\n if (isCopyError(entry)) {\n return Promise.reject(new CopyFailure(entry));\n }\n\n return Promise.resolve(entry);\n },\n };\n\n return {\n adapter,\n queueResult: (result) => { queue.push(result); },\n queueError: (error) => { queue.push(error); },\n readCount: () => reads,\n reset: () => {\n queue.length = 0;\n reads = 0;\n },\n };\n}\n\n/* ----------------------------------------------- createMockClipboardAdapter */\n\n/**\n * The handle returned by {@link createMockClipboardAdapter}.\n * @public\n */\nexport interface MockClipboardAdapter {\n /** The adapter itself: pass this as `adapter` in machine / hook options. */\n readonly adapter: ClipboardAdapter;\n /**\n * Queue a successful write. When `write()` is next called it resolves;\n * the payload the machine sends is captured in {@link lastPayload}.\n */\n readonly queueSuccess: () => void;\n /**\n * Queue a write error. When `write()` is next called it rejects with a\n * `CopyFailure` wrapping this error, which the machine maps to `error` state.\n */\n readonly queueError: (error: CopyError) => void;\n /**\n * The payload from the most recent `write()` call, or `undefined` if\n * `write()` has not been called yet (or after `reset()`).\n */\n readonly lastPayload: () => CopyPayload | undefined;\n /** How many times `write()` was called. */\n readonly writeCount: () => number;\n /** Drain pending queue entries and clear captured payload and write counter. */\n readonly reset: () => void;\n}\n\ntype ClipboardQueueEntry = { readonly ok: true } | { readonly ok: false; readonly error: CopyError };\n\n/**\n * Creates a controllable clipboard adapter for unit tests.\n *\n * ```ts\n * const mock = createMockClipboardAdapter();\n * mock.queueSuccess();\n *\n * const machine = createCopyMachine({ payload: 'hello', adapter: mock.adapter });\n * await machine.copy();\n *\n * expect(machine.getSnapshot().status).toBe('copied');\n * expect(mock.lastPayload()).toEqual({ kind: 'text', value: 'hello' });\n * ```\n *\n * If `write()` is called when the queue is empty it rejects with an `'unknown'`\n * error so the machine transitions to `error` rather than throwing.\n *\n * @public\n */\nexport function createMockClipboardAdapter(): MockClipboardAdapter {\n const queue: ClipboardQueueEntry[] = [];\n let writes = 0;\n let last: CopyPayload | undefined;\n\n const adapter: ClipboardAdapter = {\n write: (payload): Promise<void> => {\n writes += 1;\n last = payload;\n\n const entry = queue.shift();\n if (entry === undefined) {\n return Promise.reject(\n new CopyFailure(createCopyError('unknown', 'Mock clipboard adapter: queue is empty.')),\n );\n }\n\n if (!entry.ok) {\n return Promise.reject(new CopyFailure(entry.error));\n }\n return Promise.resolve();\n },\n };\n\n return {\n adapter,\n queueSuccess: () => { queue.push({ ok: true }); },\n queueError: (error) => { queue.push({ ok: false, error }); },\n lastPayload: () => last,\n writeCount: () => writes,\n reset: () => {\n queue.length = 0;\n writes = 0;\n last = undefined;\n },\n };\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;;;;ACHA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACIA,SAAgB,kBAAkB,OAAwB,CAAC,GAAgB;CACzE,MAAM,SAAsB,KAAK,UAAU;CAC3C,MAAM,OAAsB,KAAK,QAAQ;CACzC,MAAM,OAAsB,KAAK,QAAQ;CACzC,MAAM,SAA0B,KAAK,UAAU,CAAC;CAChD,MAAM,QAAyB,KAAK,SAAS,CAAC;CAE9C,IAAI;CACJ,IAAI,KAAK,UAAU,KAAA,GACjB,QAAQ,KAAK;MACR;EACL,MAAM,UAAuB,CAAC;EAC9B,IAAI,SAAS,MAAM,QAAQ,KAAK;GAAE,MAAM;GAAc,MAAM;EAAK,CAAC;EAClE,IAAI,SAAS,MAAM,QAAQ,KAAK;GAAE,MAAM;GAAa,MAAM;EAAK,CAAC;EACjE,KAAK,MAAM,QAAQ,QAAQ,QAAQ,KAAK;GAAE,MAAM,KAAK,QAAQ;GAAa,MAAM;EAAK,CAAC;EACtF,QAAQ;CACV;CAGA,OAAO,oBAAoB;EADQ;EAAQ;EAAO;EAAM;EAAM;EAAQ;CACrC,CAAC;AACpC;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,yBAA2C;CACzD,MAAM,QAA0B,CAAC;CACjC,IAAI,QAAQ;CAEZ,SAAS,YAAY,OAA2C;EAC9D,OAAO,UAAU,SAAS,aAAa,SAAS,EAAE,YAAY;CAChE;CAyBA,OAAO;EACL,SAAA,EAvBA,OAAO,UAAU,YAAsC;GACrD,SAAS;GAET,IAAI,SAAS,OAAO,SAClB,OAAO,QAAQ,OAAO,IAAI,YAAY,gBAAgB,WAAW,0BAA0B,CAAC,CAAC;GAG/F,MAAM,QAAQ,MAAM,MAAM;GAC1B,IAAI,UAAU,KAAA,GACZ,OAAO,QAAQ,OACb,IAAI,YAAY,gBAAgB,cAAc,qCAAqC,CAAC,CACtF;GAGF,IAAI,YAAY,KAAK,GACnB,OAAO,QAAQ,OAAO,IAAI,YAAY,KAAK,CAAC;GAG9C,OAAO,QAAQ,QAAQ,KAAK;EAC9B,EAIM;EACN,cAAc,WAAW;GAAE,MAAM,KAAK,MAAM;EAAG;EAC/C,aAAa,UAAU;GAAE,MAAM,KAAK,KAAK;EAAG;EAC5C,iBAAiB;EACjB,aAAa;GACX,MAAM,SAAS;GACf,QAAQ;EACV;CACF;AACF;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgB,6BAAmD;CACjE,MAAM,QAA+B,CAAC;CACtC,IAAI,SAAS;CACb,IAAI;CAqBJ,OAAO;EACL,SAAA,EAnBA,QAAQ,YAA2B;GACjC,UAAU;GACV,OAAO;GAEP,MAAM,QAAQ,MAAM,MAAM;GAC1B,IAAI,UAAU,KAAA,GACZ,OAAO,QAAQ,OACb,IAAI,YAAY,gBAAgB,WAAW,yCAAyC,CAAC,CACvF;GAGF,IAAI,CAAC,MAAM,IACT,OAAO,QAAQ,OAAO,IAAI,YAAY,MAAM,KAAK,CAAC;GAEpD,OAAO,QAAQ,QAAQ;EACzB,EAIM;EACN,oBAAoB;GAAE,MAAM,KAAK,EAAE,IAAI,KAAK,CAAC;EAAG;EAChD,aAAa,UAAU;GAAE,MAAM,KAAK;IAAE,IAAI;IAAO;GAAM,CAAC;EAAG;EAC3D,mBAAmB;EACnB,kBAAkB;EAClB,aAAa;GACX,MAAM,SAAS;GACf,SAAS;GACT,OAAO,KAAA;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing/index.ts"],"sourcesContent":["/**\n * `react-smart-copy/testing`\n *\n * Test utilities for consumers of react-smart-copy.\n *\n * - {@link createPasteResult} — build a complete {@link PasteResult} with sensible defaults\n * so adding a new field in a future release never silently breaks your tests.\n * - {@link createMockPasteAdapter} — a controllable {@link PasteAdapter} for unit tests.\n * - {@link createMockClipboardAdapter} — a controllable {@link ClipboardAdapter} for unit tests.\n *\n * None of these modules import React or browser globals, so they work in Node / jsdom alike.\n *\n * @module\n */\n\nimport type { ClipboardAdapter } from '../core/clipboard-adapter';\nimport { CopyFailure, createCopyError, type CopyError } from '../core/errors';\nimport type { PasteAdapter } from '../core/paste-adapter';\nimport {\n completePasteResult,\n type PasteItem,\n type PasteReadResult,\n type PasteResult,\n type PasteSource,\n} from '../core/paste-reader';\nimport type { CopyPayload } from '../core/payload';\n\n/* ---------------------------------------------------------------- re-exports */\n\n// Re-export the things consumers most commonly need in their test files, so\n// they can use a single import path.\nexport type {\n ClipboardAdapter,\n CopyError,\n CopyPayload,\n PasteAdapter,\n PasteItem,\n PasteReadResult,\n PasteResult,\n PasteSource,\n};\nexport { CopyFailure };\n\n/* -------------------------------------------------------- createPasteResult */\n\n/**\n * Input for {@link createPasteResult}: every field is optional so callers\n * only specify what the test cares about.\n */\nexport interface PasteResultInit {\n readonly source?: PasteSource;\n readonly items?: readonly PasteItem[];\n readonly text?: string | null;\n readonly html?: string | null;\n readonly images?: readonly Blob[];\n readonly files?: readonly File[];\n}\n\n/**\n * Builds a complete, self-consistent {@link PasteResult} with sensible defaults.\n *\n * Prefer this over constructing `PasteResult` literals: when the library adds\n * a field (as it did in v1.3.0 and v1.4.0), your tests stay green without any\n * change on your end.\n *\n * ```ts\n * const result = createPasteResult({ text: 'hello', source: 'clipboard' });\n * // result.source → 'clipboard'\n * // result.text → 'hello'\n * // result.html → null\n * // result.images → []\n * // result.files → []\n * // result.imageFiles → []\n * // result.items → [{ type: 'text/plain', data: 'hello' }]\n * ```\n *\n * When `items` is not supplied it is derived from `text`, `html`, and `images`:\n * a `text/plain` entry for `text`, a `text/html` entry for `html`, and one\n * entry per image Blob. `imageFiles` is always computed from the intersection\n * of `images` and `files`, exactly as the machine does.\n *\n * @public\n */\nexport function createPasteResult(init: PasteResultInit = {}): PasteResult {\n const source: PasteSource = init.source ?? 'clipboard';\n const text: string | null = init.text ?? null;\n const html: string | null = init.html ?? null;\n const images: readonly Blob[] = init.images ?? [];\n const files: readonly File[] = init.files ?? [];\n\n let items: readonly PasteItem[];\n if (init.items !== undefined) {\n items = init.items;\n } else {\n const derived: PasteItem[] = [];\n if (text !== null) derived.push({ type: 'text/plain', data: text });\n if (html !== null) derived.push({ type: 'text/html', data: html });\n for (const blob of images) derived.push({ type: blob.type || 'image/png', data: blob });\n items = derived;\n }\n\n const partial: PasteReadResult = { source, items, text, html, images, files };\n return completePasteResult(partial);\n}\n\n/* -------------------------------------------------- createMockPasteAdapter */\n\n/**\n * A queue entry for the mock paste adapter: a {@link PasteReadResult} resolves\n * the next `read()` call; a {@link CopyError} rejects it.\n */\nexport type MockPasteEntry = PasteReadResult | CopyError;\n\n/**\n * The handle returned by {@link createMockPasteAdapter}.\n * @public\n */\nexport interface MockPasteAdapter {\n /** The adapter itself: pass this as `adapter` in machine / hook options. */\n readonly adapter: PasteAdapter;\n /**\n * Queue a successful result. When the adapter's `read()` is next called it\n * resolves with this value.\n */\n readonly queueResult: (result: PasteReadResult) => void;\n /**\n * Queue an error. When `read()` is next called it rejects with a\n * `CopyFailure` wrapping this error, which the machine maps to `error` state.\n */\n readonly queueError: (error: CopyError) => void;\n /**\n * How many times `read()` was called. Useful for asserting that the machine\n * did (or didn't) retry.\n */\n readonly readCount: () => number;\n /** Drain all pending queue entries and reset the read counter. */\n readonly reset: () => void;\n}\n\n/**\n * Creates a controllable paste adapter for unit tests.\n *\n * ```ts\n * const mock = createMockPasteAdapter();\n * mock.queueResult(createPasteResult({ text: 'hello' }));\n *\n * const machine = createPasteMachine({ adapter: mock.adapter });\n * await machine.paste();\n *\n * expect(machine.getSnapshot().status).toBe('read');\n * expect(mock.readCount()).toBe(1);\n * ```\n *\n * If `read()` is called when the queue is empty it rejects with a\n * `'no-content'` error so the machine transitions to `error` rather than\n * throwing.\n *\n * @public\n */\nexport function createMockPasteAdapter(): MockPasteAdapter {\n const queue: MockPasteEntry[] = [];\n let reads = 0;\n\n function isCopyError(entry: MockPasteEntry): entry is CopyError {\n return 'type' in entry && 'message' in entry && !('source' in entry);\n }\n\n const adapter: PasteAdapter = {\n read: (_options, context): Promise<PasteReadResult> => {\n reads += 1;\n\n if (context?.signal.aborted) {\n return Promise.reject(new CopyFailure(createCopyError('aborted', 'The paste was cancelled.')));\n }\n\n const entry = queue.shift();\n if (entry === undefined) {\n return Promise.reject(\n new CopyFailure(createCopyError('no-content', 'Mock paste adapter: queue is empty.')),\n );\n }\n\n if (isCopyError(entry)) {\n return Promise.reject(new CopyFailure(entry));\n }\n\n return Promise.resolve(entry);\n },\n };\n\n return {\n adapter,\n queueResult: (result) => { queue.push(result); },\n queueError: (error) => { queue.push(error); },\n readCount: () => reads,\n reset: () => {\n queue.length = 0;\n reads = 0;\n },\n };\n}\n\n/* ----------------------------------------------- createMockClipboardAdapter */\n\n/**\n * The handle returned by {@link createMockClipboardAdapter}.\n * @public\n */\nexport interface MockClipboardAdapter {\n /** The adapter itself: pass this as `adapter` in machine / hook options. */\n readonly adapter: ClipboardAdapter;\n /**\n * Queue a successful write. When `write()` is next called it resolves;\n * the payload the machine sends is captured in {@link lastPayload}.\n */\n readonly queueSuccess: () => void;\n /**\n * Queue a write error. When `write()` is next called it rejects with a\n * `CopyFailure` wrapping this error, which the machine maps to `error` state.\n */\n readonly queueError: (error: CopyError) => void;\n /**\n * The payload from the most recent `write()` call, or `undefined` if\n * `write()` has not been called yet (or after `reset()`).\n */\n readonly lastPayload: () => CopyPayload | undefined;\n /** How many times `write()` was called. */\n readonly writeCount: () => number;\n /** Drain pending queue entries and clear captured payload and write counter. */\n readonly reset: () => void;\n}\n\ntype ClipboardQueueEntry = { readonly ok: true } | { readonly ok: false; readonly error: CopyError };\n\n/**\n * Creates a controllable clipboard adapter for unit tests.\n *\n * ```ts\n * const mock = createMockClipboardAdapter();\n * mock.queueSuccess();\n *\n * const machine = createCopyMachine({ payload: 'hello', adapter: mock.adapter });\n * await machine.copy();\n *\n * expect(machine.getSnapshot().status).toBe('copied');\n * expect(mock.lastPayload()).toEqual({ kind: 'text', value: 'hello' });\n * ```\n *\n * If `write()` is called when the queue is empty it rejects with an `'unknown'`\n * error so the machine transitions to `error` rather than throwing.\n *\n * @public\n */\nexport function createMockClipboardAdapter(): MockClipboardAdapter {\n const queue: ClipboardQueueEntry[] = [];\n let writes = 0;\n let last: CopyPayload | undefined;\n\n const adapter: ClipboardAdapter = {\n write: (payload): Promise<void> => {\n writes += 1;\n last = payload;\n\n const entry = queue.shift();\n if (entry === undefined) {\n return Promise.reject(\n new CopyFailure(createCopyError('unknown', 'Mock clipboard adapter: queue is empty.')),\n );\n }\n\n if (!entry.ok) {\n return Promise.reject(new CopyFailure(entry.error));\n }\n return Promise.resolve();\n },\n };\n\n return {\n adapter,\n queueSuccess: () => { queue.push({ ok: true }); },\n queueError: (error) => { queue.push({ ok: false, error }); },\n lastPayload: () => last,\n writeCount: () => writes,\n reset: () => {\n queue.length = 0;\n writes = 0;\n last = undefined;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,SAAgB,kBAAkB,OAAwB,CAAC,GAAgB;CACzE,MAAM,SAAsB,KAAK,UAAU;CAC3C,MAAM,OAAsB,KAAK,QAAQ;CACzC,MAAM,OAAsB,KAAK,QAAQ;CACzC,MAAM,SAA0B,KAAK,UAAU,CAAC;CAChD,MAAM,QAAyB,KAAK,SAAS,CAAC;CAE9C,IAAI;CACJ,IAAI,KAAK,UAAU,KAAA,GACjB,QAAQ,KAAK;MACR;EACL,MAAM,UAAuB,CAAC;EAC9B,IAAI,SAAS,MAAM,QAAQ,KAAK;GAAE,MAAM;GAAc,MAAM;EAAK,CAAC;EAClE,IAAI,SAAS,MAAM,QAAQ,KAAK;GAAE,MAAM;GAAa,MAAM;EAAK,CAAC;EACjE,KAAK,MAAM,QAAQ,QAAQ,QAAQ,KAAK;GAAE,MAAM,KAAK,QAAQ;GAAa,MAAM;EAAK,CAAC;EACtF,QAAQ;CACV;CAGA,OAAO,oBAAoB;EADQ;EAAQ;EAAO;EAAM;EAAM;EAAQ;CACrC,CAAC;AACpC;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,yBAA2C;CACzD,MAAM,QAA0B,CAAC;CACjC,IAAI,QAAQ;CAEZ,SAAS,YAAY,OAA2C;EAC9D,OAAO,UAAU,SAAS,aAAa,SAAS,EAAE,YAAY;CAChE;CAyBA,OAAO;EACL,SAAA,EAvBA,OAAO,UAAU,YAAsC;GACrD,SAAS;GAET,IAAI,SAAS,OAAO,SAClB,OAAO,QAAQ,OAAO,IAAI,YAAY,gBAAgB,WAAW,0BAA0B,CAAC,CAAC;GAG/F,MAAM,QAAQ,MAAM,MAAM;GAC1B,IAAI,UAAU,KAAA,GACZ,OAAO,QAAQ,OACb,IAAI,YAAY,gBAAgB,cAAc,qCAAqC,CAAC,CACtF;GAGF,IAAI,YAAY,KAAK,GACnB,OAAO,QAAQ,OAAO,IAAI,YAAY,KAAK,CAAC;GAG9C,OAAO,QAAQ,QAAQ,KAAK;EAC9B,EAIM;EACN,cAAc,WAAW;GAAE,MAAM,KAAK,MAAM;EAAG;EAC/C,aAAa,UAAU;GAAE,MAAM,KAAK,KAAK;EAAG;EAC5C,iBAAiB;EACjB,aAAa;GACX,MAAM,SAAS;GACf,QAAQ;EACV;CACF;AACF;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgB,6BAAmD;CACjE,MAAM,QAA+B,CAAC;CACtC,IAAI,SAAS;CACb,IAAI;CAqBJ,OAAO;EACL,SAAA,EAnBA,QAAQ,YAA2B;GACjC,UAAU;GACV,OAAO;GAEP,MAAM,QAAQ,MAAM,MAAM;GAC1B,IAAI,UAAU,KAAA,GACZ,OAAO,QAAQ,OACb,IAAI,YAAY,gBAAgB,WAAW,yCAAyC,CAAC,CACvF;GAGF,IAAI,CAAC,MAAM,IACT,OAAO,QAAQ,OAAO,IAAI,YAAY,MAAM,KAAK,CAAC;GAEpD,OAAO,QAAQ,QAAQ;EACzB,EAIM;EACN,oBAAoB;GAAE,MAAM,KAAK,EAAE,IAAI,KAAK,CAAC;EAAG;EAChD,aAAa,UAAU;GAAE,MAAM,KAAK;IAAE,IAAI;IAAO;GAAM,CAAC;EAAG;EAC3D,mBAAmB;EACnB,kBAAkB;EAClB,aAAa;GACX,MAAM,SAAS;GACf,SAAS;GACT,OAAO,KAAA;EACT;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-smart-copy",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Headless, type-safe clipboard interactions for React: copy and paste text, rich HTML, images, spreadsheet tables, typed application data, Markdown, code, privacy-safe images, links, sharing, colours
|
|
3
|
+
"version": "1.19.0",
|
|
4
|
+
"description": "Headless, type-safe clipboard interactions for React: copy and paste text, rich HTML, images, spreadsheet tables, typed application data, Markdown, code, privacy-safe images, links, sharing, colours, portable rich text and clean pastes from Word and Google Docs, with coordinated copy groups, SVG/DOM capture, Trojan Source and homoglyph detection, honest error states, retry and screen-reader announcements.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
7
7
|
"clipboard",
|
|
@@ -64,7 +64,15 @@
|
|
|
64
64
|
"email-html",
|
|
65
65
|
"html-sanitizer",
|
|
66
66
|
"outlook",
|
|
67
|
-
"gmail"
|
|
67
|
+
"gmail",
|
|
68
|
+
"paste-from-word",
|
|
69
|
+
"paste-from-google-docs",
|
|
70
|
+
"clean-html",
|
|
71
|
+
"tiptap",
|
|
72
|
+
"lexical",
|
|
73
|
+
"prosemirror",
|
|
74
|
+
"contenteditable",
|
|
75
|
+
"wysiwyg"
|
|
68
76
|
],
|
|
69
77
|
"license": "MIT",
|
|
70
78
|
"author": {
|
|
@@ -284,7 +292,7 @@
|
|
|
284
292
|
"verify": "npm run lint && npm run typecheck && npm run test:coverage && npm run build && node scripts/check-dist.js && npm run lint:package && npm run types:consumer && npm run size",
|
|
285
293
|
"changeset": "changeset",
|
|
286
294
|
"release": "npm run verify && changeset publish",
|
|
287
|
-
"site:build": "npm run build && node -
|
|
295
|
+
"site:build": "npm run build && node scripts/copy-site-lib.js && node scripts/build-changelog.js",
|
|
288
296
|
"site:preview": "npm run site:build && npx --yes serve site",
|
|
289
297
|
"test:coverage": "vitest run --coverage --exclude \"**/*.property.test.ts\" && npm run test:property",
|
|
290
298
|
"test:property": "vitest run property.test",
|
|
@@ -461,13 +469,37 @@
|
|
|
461
469
|
{
|
|
462
470
|
"name": "rich, all exports",
|
|
463
471
|
"path": "dist/rich.js",
|
|
464
|
-
"limit": "
|
|
472
|
+
"limit": "17 kB"
|
|
465
473
|
},
|
|
466
474
|
{
|
|
467
475
|
"name": "rich: richPayload",
|
|
468
476
|
"path": "dist/rich.js",
|
|
469
477
|
"import": "{ richPayload }",
|
|
470
478
|
"limit": "12 kB"
|
|
479
|
+
},
|
|
480
|
+
{
|
|
481
|
+
"name": "rich: pasteAsRich (paste side)",
|
|
482
|
+
"path": "dist/rich.js",
|
|
483
|
+
"import": "{ pasteAsRich }",
|
|
484
|
+
"limit": "16.6 kB"
|
|
485
|
+
},
|
|
486
|
+
{
|
|
487
|
+
"name": "An app using five entry points (one shared core)",
|
|
488
|
+
"path": [
|
|
489
|
+
"dist/index.js",
|
|
490
|
+
"dist/rich.js",
|
|
491
|
+
"dist/markdown.js",
|
|
492
|
+
"dist/link.js",
|
|
493
|
+
"dist/color.js"
|
|
494
|
+
],
|
|
495
|
+
"import": {
|
|
496
|
+
"dist/index.js": "{ useCopy, usePaste }",
|
|
497
|
+
"dist/rich.js": "{ richPayload }",
|
|
498
|
+
"dist/markdown.js": "{ pasteAsMarkdown }",
|
|
499
|
+
"dist/link.js": "{ linkPayload }",
|
|
500
|
+
"dist/color.js": "{ formatColor }"
|
|
501
|
+
},
|
|
502
|
+
"limit": "25 kB"
|
|
471
503
|
}
|
|
472
504
|
],
|
|
473
505
|
"publishConfig": {
|