react-smart-copy 1.4.0 → 1.6.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 +66 -1
- package/dist/testing.cjs +201 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +309 -0
- package/dist/testing.d.ts +309 -0
- package/dist/testing.js +197 -0
- package/dist/testing.js.map +1 -0
- package/package.json +19 -1
package/README.md
CHANGED
|
@@ -545,6 +545,70 @@ zone.addEventListener("dragover", (event) => {
|
|
|
545
545
|
zone.addEventListener("drop", (event) => void paster.dropEvent(event));
|
|
546
546
|
```
|
|
547
547
|
|
|
548
|
+
## Testing
|
|
549
|
+
|
|
550
|
+
`react-smart-copy/testing` ships utilities that keep consumer test suites
|
|
551
|
+
green across library upgrades. Every `PasteResult` field added in v1.3 and
|
|
552
|
+
v1.4 required updating hand-written result literals — these helpers absorb
|
|
553
|
+
future additions at the library level.
|
|
554
|
+
|
|
555
|
+
### `createPasteResult(init?)`
|
|
556
|
+
|
|
557
|
+
Builds a complete `PasteResult` from partial input. Every field defaults
|
|
558
|
+
sensibly, so adding a required field in a future release won't touch your tests.
|
|
559
|
+
|
|
560
|
+
```ts
|
|
561
|
+
import { createPasteResult } from "react-smart-copy/testing";
|
|
562
|
+
|
|
563
|
+
const result = createPasteResult({ text: "hello" });
|
|
564
|
+
// result.source → 'clipboard'
|
|
565
|
+
// result.text → 'hello'
|
|
566
|
+
// result.html → null
|
|
567
|
+
// result.images → []
|
|
568
|
+
// result.files → []
|
|
569
|
+
// result.imageFiles → []
|
|
570
|
+
// result.items → [{ type: 'text/plain', data: 'hello' }]
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
### `createMockPasteAdapter()`
|
|
574
|
+
|
|
575
|
+
A controllable `PasteAdapter` backed by a result queue. Queue entries
|
|
576
|
+
are consumed FIFO; an empty queue rejects with `'no-content'`.
|
|
577
|
+
|
|
578
|
+
```ts
|
|
579
|
+
import { createMockPasteAdapter, createPasteResult } from "react-smart-copy/testing";
|
|
580
|
+
import { createPasteMachine } from "react-smart-copy/core";
|
|
581
|
+
|
|
582
|
+
const mock = createMockPasteAdapter();
|
|
583
|
+
mock.queueResult(createPasteResult({ text: "hello" }));
|
|
584
|
+
mock.queueError(createCopyError("permission-denied", "blocked"));
|
|
585
|
+
|
|
586
|
+
const machine = createPasteMachine({ adapter: mock.adapter });
|
|
587
|
+
await machine.paste(); // → { status: 'read', result: … }
|
|
588
|
+
expect(mock.readCount()).toBe(1);
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
### `createMockClipboardAdapter()`
|
|
592
|
+
|
|
593
|
+
A controllable `ClipboardAdapter` for copy tests. Captures the last payload
|
|
594
|
+
the machine sent so you can assert on it.
|
|
595
|
+
|
|
596
|
+
```ts
|
|
597
|
+
import { createMockClipboardAdapter } from "react-smart-copy/testing";
|
|
598
|
+
import { createCopyMachine } from "react-smart-copy/core";
|
|
599
|
+
|
|
600
|
+
const mock = createMockClipboardAdapter();
|
|
601
|
+
mock.queueSuccess();
|
|
602
|
+
|
|
603
|
+
const machine = createCopyMachine({ adapter: mock.adapter });
|
|
604
|
+
await machine.copy("hello");
|
|
605
|
+
expect(mock.lastPayload()).toEqual({ kind: "text", value: "hello" });
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
The subpackage also re-exports the types most often needed in test files:
|
|
609
|
+
`CopyFailure`, `CopyError`, `PasteResult`, `PasteSource`, `ClipboardAdapter`,
|
|
610
|
+
and more — so a single import covers both utilities and type annotations.
|
|
611
|
+
|
|
548
612
|
## Custom adapters
|
|
549
613
|
|
|
550
614
|
```ts
|
|
@@ -583,6 +647,7 @@ embedded webviews. Where a capability is missing you get a typed error, never a
|
|
|
583
647
|
- ~~**1.2** Paste `retry()`, cancellation with `AbortSignal`, `PasteField.Preview`~~ shipped
|
|
584
648
|
- ~~**1.3** `onReset` / `onCancel` callbacks, UTF-8 `maxBytes` on every paste path, `PasteResult.imageFiles`~~ shipped
|
|
585
649
|
- ~~**1.4** Drag-and-drop through the paste pipeline: `dropTargetProps`, `isDragOver`, droppable `PasteField.Zone`~~ shipped
|
|
650
|
+
- ~~**1.5** `react-smart-copy/testing` — mock adapters and result builders so consumer tests stay green across releases~~ shipped
|
|
586
651
|
|
|
587
652
|
Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
|
|
588
653
|
|
|
@@ -590,7 +655,7 @@ Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://supr
|
|
|
590
655
|
|
|
591
656
|
```bash
|
|
592
657
|
npm install
|
|
593
|
-
npm run verify # lint, types,
|
|
658
|
+
npm run verify # lint, types, 495 tests at 100% coverage, build, publint + attw, size budgets
|
|
594
659
|
npm run changeset # describe your change for the changelog
|
|
595
660
|
npm run site:preview # docs site at http://localhost:3000
|
|
596
661
|
```
|
package/dist/testing.cjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/core/errors.ts
|
|
3
|
+
function createCopyError(type, message, cause) {
|
|
4
|
+
return cause === void 0 ? {
|
|
5
|
+
type,
|
|
6
|
+
message
|
|
7
|
+
} : {
|
|
8
|
+
type,
|
|
9
|
+
message,
|
|
10
|
+
cause
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Branded (not `instanceof`) so failures stay recognisable even when the core
|
|
15
|
+
* is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
|
|
16
|
+
*/
|
|
17
|
+
const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
|
|
18
|
+
/** Error thrown by adapters to carry a fully classified {@link CopyError}. */
|
|
19
|
+
var CopyFailure = class extends Error {
|
|
20
|
+
constructor(copyError) {
|
|
21
|
+
super(copyError.message);
|
|
22
|
+
this[COPY_FAILURE_BRAND] = true;
|
|
23
|
+
this.name = "CopyFailure";
|
|
24
|
+
this.copyError = copyError;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/core/paste-reader.ts
|
|
29
|
+
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
30
|
+
function completePasteResult(result) {
|
|
31
|
+
const images = new Set(result.images);
|
|
32
|
+
return {
|
|
33
|
+
...result,
|
|
34
|
+
imageFiles: result.files.filter((file) => images.has(file))
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/testing/index.ts
|
|
39
|
+
/**
|
|
40
|
+
* Builds a complete, self-consistent {@link PasteResult} with sensible defaults.
|
|
41
|
+
*
|
|
42
|
+
* Prefer this over constructing `PasteResult` literals: when the library adds
|
|
43
|
+
* a field (as it did in v1.3.0 and v1.4.0), your tests stay green without any
|
|
44
|
+
* change on your end.
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* const result = createPasteResult({ text: 'hello', source: 'clipboard' });
|
|
48
|
+
* // result.source → 'clipboard'
|
|
49
|
+
* // result.text → 'hello'
|
|
50
|
+
* // result.html → null
|
|
51
|
+
* // result.images → []
|
|
52
|
+
* // result.files → []
|
|
53
|
+
* // result.imageFiles → []
|
|
54
|
+
* // result.items → [{ type: 'text/plain', data: 'hello' }]
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* When `items` is not supplied it is derived from `text`, `html`, and `images`:
|
|
58
|
+
* a `text/plain` entry for `text`, a `text/html` entry for `html`, and one
|
|
59
|
+
* entry per image Blob. `imageFiles` is always computed from the intersection
|
|
60
|
+
* of `images` and `files`, exactly as the machine does.
|
|
61
|
+
*
|
|
62
|
+
* @public
|
|
63
|
+
*/
|
|
64
|
+
function createPasteResult(init = {}) {
|
|
65
|
+
const source = init.source ?? "clipboard";
|
|
66
|
+
const text = init.text ?? null;
|
|
67
|
+
const html = init.html ?? null;
|
|
68
|
+
const images = init.images ?? [];
|
|
69
|
+
const files = init.files ?? [];
|
|
70
|
+
let items;
|
|
71
|
+
if (init.items !== void 0) items = init.items;
|
|
72
|
+
else {
|
|
73
|
+
const derived = [];
|
|
74
|
+
if (text !== null) derived.push({
|
|
75
|
+
type: "text/plain",
|
|
76
|
+
data: text
|
|
77
|
+
});
|
|
78
|
+
if (html !== null) derived.push({
|
|
79
|
+
type: "text/html",
|
|
80
|
+
data: html
|
|
81
|
+
});
|
|
82
|
+
for (const blob of images) derived.push({
|
|
83
|
+
type: blob.type || "image/png",
|
|
84
|
+
data: blob
|
|
85
|
+
});
|
|
86
|
+
items = derived;
|
|
87
|
+
}
|
|
88
|
+
return completePasteResult({
|
|
89
|
+
source,
|
|
90
|
+
items,
|
|
91
|
+
text,
|
|
92
|
+
html,
|
|
93
|
+
images,
|
|
94
|
+
files
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Creates a controllable paste adapter for unit tests.
|
|
99
|
+
*
|
|
100
|
+
* ```ts
|
|
101
|
+
* const mock = createMockPasteAdapter();
|
|
102
|
+
* mock.queueResult(createPasteResult({ text: 'hello' }));
|
|
103
|
+
*
|
|
104
|
+
* const machine = createPasteMachine({ adapter: mock.adapter });
|
|
105
|
+
* await machine.paste();
|
|
106
|
+
*
|
|
107
|
+
* expect(machine.getSnapshot().status).toBe('read');
|
|
108
|
+
* expect(mock.readCount()).toBe(1);
|
|
109
|
+
* ```
|
|
110
|
+
*
|
|
111
|
+
* If `read()` is called when the queue is empty it rejects with a
|
|
112
|
+
* `'no-content'` error so the machine transitions to `error` rather than
|
|
113
|
+
* throwing.
|
|
114
|
+
*
|
|
115
|
+
* @public
|
|
116
|
+
*/
|
|
117
|
+
function createMockPasteAdapter() {
|
|
118
|
+
const queue = [];
|
|
119
|
+
let reads = 0;
|
|
120
|
+
function isCopyError(entry) {
|
|
121
|
+
return "type" in entry && "message" in entry && !("source" in entry);
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
adapter: { read: (_options, context) => {
|
|
125
|
+
reads += 1;
|
|
126
|
+
if (context?.signal.aborted) return Promise.reject(new CopyFailure(createCopyError("aborted", "The paste was cancelled.")));
|
|
127
|
+
const entry = queue.shift();
|
|
128
|
+
if (entry === void 0) return Promise.reject(new CopyFailure(createCopyError("no-content", "Mock paste adapter: queue is empty.")));
|
|
129
|
+
if (isCopyError(entry)) return Promise.reject(new CopyFailure(entry));
|
|
130
|
+
return Promise.resolve(entry);
|
|
131
|
+
} },
|
|
132
|
+
queueResult: (result) => {
|
|
133
|
+
queue.push(result);
|
|
134
|
+
},
|
|
135
|
+
queueError: (error) => {
|
|
136
|
+
queue.push(error);
|
|
137
|
+
},
|
|
138
|
+
readCount: () => reads,
|
|
139
|
+
reset: () => {
|
|
140
|
+
queue.length = 0;
|
|
141
|
+
reads = 0;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Creates a controllable clipboard adapter for unit tests.
|
|
147
|
+
*
|
|
148
|
+
* ```ts
|
|
149
|
+
* const mock = createMockClipboardAdapter();
|
|
150
|
+
* mock.queueSuccess();
|
|
151
|
+
*
|
|
152
|
+
* const machine = createCopyMachine({ payload: 'hello', adapter: mock.adapter });
|
|
153
|
+
* await machine.copy();
|
|
154
|
+
*
|
|
155
|
+
* expect(machine.getSnapshot().status).toBe('copied');
|
|
156
|
+
* expect(mock.lastPayload()).toEqual({ kind: 'text', value: 'hello' });
|
|
157
|
+
* ```
|
|
158
|
+
*
|
|
159
|
+
* If `write()` is called when the queue is empty it rejects with an `'unknown'`
|
|
160
|
+
* error so the machine transitions to `error` rather than throwing.
|
|
161
|
+
*
|
|
162
|
+
* @public
|
|
163
|
+
*/
|
|
164
|
+
function createMockClipboardAdapter() {
|
|
165
|
+
const queue = [];
|
|
166
|
+
let writes = 0;
|
|
167
|
+
let last;
|
|
168
|
+
return {
|
|
169
|
+
adapter: { write: (payload) => {
|
|
170
|
+
writes += 1;
|
|
171
|
+
last = payload;
|
|
172
|
+
const entry = queue.shift();
|
|
173
|
+
if (entry === void 0) return Promise.reject(new CopyFailure(createCopyError("unknown", "Mock clipboard adapter: queue is empty.")));
|
|
174
|
+
if (!entry.ok) return Promise.reject(new CopyFailure(entry.error));
|
|
175
|
+
return Promise.resolve();
|
|
176
|
+
} },
|
|
177
|
+
queueSuccess: () => {
|
|
178
|
+
queue.push({ ok: true });
|
|
179
|
+
},
|
|
180
|
+
queueError: (error) => {
|
|
181
|
+
queue.push({
|
|
182
|
+
ok: false,
|
|
183
|
+
error
|
|
184
|
+
});
|
|
185
|
+
},
|
|
186
|
+
lastPayload: () => last,
|
|
187
|
+
writeCount: () => writes,
|
|
188
|
+
reset: () => {
|
|
189
|
+
queue.length = 0;
|
|
190
|
+
writes = 0;
|
|
191
|
+
last = void 0;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
//#endregion
|
|
196
|
+
exports.CopyFailure = CopyFailure;
|
|
197
|
+
exports.createMockClipboardAdapter = createMockClipboardAdapter;
|
|
198
|
+
exports.createMockPasteAdapter = createMockPasteAdapter;
|
|
199
|
+
exports.createPasteResult = createPasteResult;
|
|
200
|
+
|
|
201
|
+
//# sourceMappingURL=testing.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing.cjs","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, 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'`) or a wildcard (`'image/*'`, `'*\\/*'`).\n * `image/svg+xml` is only accepted when listed exactly (it is scriptable XML).\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 normalizeMimeType(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 = normalizeMimeType(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 = normalizeMimeType(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 = normalizeMimeType(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;;;;ACJA,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACKA,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"}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
//#region src/core/machine-shared.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Passed to adapters and lazy sources as their last argument. `signal` aborts
|
|
4
|
+
* when the operation is superseded, `reset()`, or its host unmounts, so
|
|
5
|
+
* expensive work (rasterising, decoding) can stop early.
|
|
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
|
+
readonly mimeType: string;
|
|
135
|
+
readonly data: string | Blob;
|
|
136
|
+
}
|
|
137
|
+
interface MultiPayload {
|
|
138
|
+
readonly kind: 'multi';
|
|
139
|
+
readonly items: readonly MultiPayloadItem[];
|
|
140
|
+
}
|
|
141
|
+
type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/core/clipboard-adapter.d.ts
|
|
144
|
+
/**
|
|
145
|
+
* The only thing the state machine needs. Implement it to target Electron,
|
|
146
|
+
* a native bridge, a test double, or anything else.
|
|
147
|
+
*
|
|
148
|
+
* Contract: start the platform write synchronously (before any `await`) so the
|
|
149
|
+
* browser still sees the user gesture, and reject with a `CopyFailure` when you
|
|
150
|
+
* can classify the error. `context.signal` aborts when the copy is reset or its
|
|
151
|
+
* host unmounts; honour it to stop expensive work early.
|
|
152
|
+
*/
|
|
153
|
+
interface ClipboardAdapter {
|
|
154
|
+
write(payload: CopyPayload, context?: OperationContext): Promise<void>;
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
//#region src/core/paste-adapter.d.ts
|
|
158
|
+
/**
|
|
159
|
+
* Reads the system clipboard. Implement it for Electron, a native bridge or tests.
|
|
160
|
+
*
|
|
161
|
+
* Contract: call the platform API synchronously (before any `await`) so the
|
|
162
|
+
* browser still sees the user gesture, and reject with a `CopyFailure`.
|
|
163
|
+
* `context.signal` aborts when the read is superseded, reset, or its host
|
|
164
|
+
* unmounts; honour it to stop decoding early.
|
|
165
|
+
*/
|
|
166
|
+
interface PasteAdapter {
|
|
167
|
+
read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/testing/index.d.ts
|
|
171
|
+
/**
|
|
172
|
+
* Input for {@link createPasteResult}: every field is optional so callers
|
|
173
|
+
* only specify what the test cares about.
|
|
174
|
+
*/
|
|
175
|
+
export interface PasteResultInit {
|
|
176
|
+
readonly source?: PasteSource;
|
|
177
|
+
readonly items?: readonly PasteItem[];
|
|
178
|
+
readonly text?: string | null;
|
|
179
|
+
readonly html?: string | null;
|
|
180
|
+
readonly images?: readonly Blob[];
|
|
181
|
+
readonly files?: readonly File[];
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Builds a complete, self-consistent {@link PasteResult} with sensible defaults.
|
|
185
|
+
*
|
|
186
|
+
* Prefer this over constructing `PasteResult` literals: when the library adds
|
|
187
|
+
* a field (as it did in v1.3.0 and v1.4.0), your tests stay green without any
|
|
188
|
+
* change on your end.
|
|
189
|
+
*
|
|
190
|
+
* ```ts
|
|
191
|
+
* const result = createPasteResult({ text: 'hello', source: 'clipboard' });
|
|
192
|
+
* // result.source → 'clipboard'
|
|
193
|
+
* // result.text → 'hello'
|
|
194
|
+
* // result.html → null
|
|
195
|
+
* // result.images → []
|
|
196
|
+
* // result.files → []
|
|
197
|
+
* // result.imageFiles → []
|
|
198
|
+
* // result.items → [{ type: 'text/plain', data: 'hello' }]
|
|
199
|
+
* ```
|
|
200
|
+
*
|
|
201
|
+
* When `items` is not supplied it is derived from `text`, `html`, and `images`:
|
|
202
|
+
* a `text/plain` entry for `text`, a `text/html` entry for `html`, and one
|
|
203
|
+
* entry per image Blob. `imageFiles` is always computed from the intersection
|
|
204
|
+
* of `images` and `files`, exactly as the machine does.
|
|
205
|
+
*
|
|
206
|
+
* @public
|
|
207
|
+
*/
|
|
208
|
+
export declare function createPasteResult(init?: PasteResultInit): PasteResult;
|
|
209
|
+
/**
|
|
210
|
+
* A queue entry for the mock paste adapter: a {@link PasteReadResult} resolves
|
|
211
|
+
* the next `read()` call; a {@link CopyError} rejects it.
|
|
212
|
+
*/
|
|
213
|
+
export type MockPasteEntry = PasteReadResult | CopyError;
|
|
214
|
+
/**
|
|
215
|
+
* The handle returned by {@link createMockPasteAdapter}.
|
|
216
|
+
* @public
|
|
217
|
+
*/
|
|
218
|
+
export interface MockPasteAdapter {
|
|
219
|
+
/** The adapter itself: pass this as `adapter` in machine / hook options. */
|
|
220
|
+
readonly adapter: PasteAdapter;
|
|
221
|
+
/**
|
|
222
|
+
* Queue a successful result. When the adapter's `read()` is next called it
|
|
223
|
+
* resolves with this value.
|
|
224
|
+
*/
|
|
225
|
+
readonly queueResult: (result: PasteReadResult) => void;
|
|
226
|
+
/**
|
|
227
|
+
* Queue an error. When `read()` is next called it rejects with a
|
|
228
|
+
* `CopyFailure` wrapping this error, which the machine maps to `error` state.
|
|
229
|
+
*/
|
|
230
|
+
readonly queueError: (error: CopyError) => void;
|
|
231
|
+
/**
|
|
232
|
+
* How many times `read()` was called. Useful for asserting that the machine
|
|
233
|
+
* did (or didn't) retry.
|
|
234
|
+
*/
|
|
235
|
+
readonly readCount: () => number;
|
|
236
|
+
/** Drain all pending queue entries and reset the read counter. */
|
|
237
|
+
readonly reset: () => void;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Creates a controllable paste adapter for unit tests.
|
|
241
|
+
*
|
|
242
|
+
* ```ts
|
|
243
|
+
* const mock = createMockPasteAdapter();
|
|
244
|
+
* mock.queueResult(createPasteResult({ text: 'hello' }));
|
|
245
|
+
*
|
|
246
|
+
* const machine = createPasteMachine({ adapter: mock.adapter });
|
|
247
|
+
* await machine.paste();
|
|
248
|
+
*
|
|
249
|
+
* expect(machine.getSnapshot().status).toBe('read');
|
|
250
|
+
* expect(mock.readCount()).toBe(1);
|
|
251
|
+
* ```
|
|
252
|
+
*
|
|
253
|
+
* If `read()` is called when the queue is empty it rejects with a
|
|
254
|
+
* `'no-content'` error so the machine transitions to `error` rather than
|
|
255
|
+
* throwing.
|
|
256
|
+
*
|
|
257
|
+
* @public
|
|
258
|
+
*/
|
|
259
|
+
export declare function createMockPasteAdapter(): MockPasteAdapter;
|
|
260
|
+
/**
|
|
261
|
+
* The handle returned by {@link createMockClipboardAdapter}.
|
|
262
|
+
* @public
|
|
263
|
+
*/
|
|
264
|
+
export interface MockClipboardAdapter {
|
|
265
|
+
/** The adapter itself: pass this as `adapter` in machine / hook options. */
|
|
266
|
+
readonly adapter: ClipboardAdapter;
|
|
267
|
+
/**
|
|
268
|
+
* Queue a successful write. When `write()` is next called it resolves;
|
|
269
|
+
* the payload the machine sends is captured in {@link lastPayload}.
|
|
270
|
+
*/
|
|
271
|
+
readonly queueSuccess: () => void;
|
|
272
|
+
/**
|
|
273
|
+
* Queue a write error. When `write()` is next called it rejects with a
|
|
274
|
+
* `CopyFailure` wrapping this error, which the machine maps to `error` state.
|
|
275
|
+
*/
|
|
276
|
+
readonly queueError: (error: CopyError) => void;
|
|
277
|
+
/**
|
|
278
|
+
* The payload from the most recent `write()` call, or `undefined` if
|
|
279
|
+
* `write()` has not been called yet (or after `reset()`).
|
|
280
|
+
*/
|
|
281
|
+
readonly lastPayload: () => CopyPayload | undefined;
|
|
282
|
+
/** How many times `write()` was called. */
|
|
283
|
+
readonly writeCount: () => number;
|
|
284
|
+
/** Drain pending queue entries and clear captured payload and write counter. */
|
|
285
|
+
readonly reset: () => void;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Creates a controllable clipboard adapter for unit tests.
|
|
289
|
+
*
|
|
290
|
+
* ```ts
|
|
291
|
+
* const mock = createMockClipboardAdapter();
|
|
292
|
+
* mock.queueSuccess();
|
|
293
|
+
*
|
|
294
|
+
* const machine = createCopyMachine({ payload: 'hello', adapter: mock.adapter });
|
|
295
|
+
* await machine.copy();
|
|
296
|
+
*
|
|
297
|
+
* expect(machine.getSnapshot().status).toBe('copied');
|
|
298
|
+
* expect(mock.lastPayload()).toEqual({ kind: 'text', value: 'hello' });
|
|
299
|
+
* ```
|
|
300
|
+
*
|
|
301
|
+
* If `write()` is called when the queue is empty it rejects with an `'unknown'`
|
|
302
|
+
* error so the machine transitions to `error` rather than throwing.
|
|
303
|
+
*
|
|
304
|
+
* @public
|
|
305
|
+
*/
|
|
306
|
+
export declare function createMockClipboardAdapter(): MockClipboardAdapter;
|
|
307
|
+
//#endregion
|
|
308
|
+
export type { ClipboardAdapter, CopyError, CopyPayload, PasteAdapter, PasteItem, PasteReadResult, PasteResult, PasteSource };
|
|
309
|
+
//# sourceMappingURL=testing.d.cts.map
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
//#region src/core/machine-shared.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Passed to adapters and lazy sources as their last argument. `signal` aborts
|
|
4
|
+
* when the operation is superseded, `reset()`, or its host unmounts, so
|
|
5
|
+
* expensive work (rasterising, decoding) can stop early.
|
|
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
|
+
readonly mimeType: string;
|
|
135
|
+
readonly data: string | Blob;
|
|
136
|
+
}
|
|
137
|
+
interface MultiPayload {
|
|
138
|
+
readonly kind: 'multi';
|
|
139
|
+
readonly items: readonly MultiPayloadItem[];
|
|
140
|
+
}
|
|
141
|
+
type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/core/clipboard-adapter.d.ts
|
|
144
|
+
/**
|
|
145
|
+
* The only thing the state machine needs. Implement it to target Electron,
|
|
146
|
+
* a native bridge, a test double, or anything else.
|
|
147
|
+
*
|
|
148
|
+
* Contract: start the platform write synchronously (before any `await`) so the
|
|
149
|
+
* browser still sees the user gesture, and reject with a `CopyFailure` when you
|
|
150
|
+
* can classify the error. `context.signal` aborts when the copy is reset or its
|
|
151
|
+
* host unmounts; honour it to stop expensive work early.
|
|
152
|
+
*/
|
|
153
|
+
interface ClipboardAdapter {
|
|
154
|
+
write(payload: CopyPayload, context?: OperationContext): Promise<void>;
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
//#region src/core/paste-adapter.d.ts
|
|
158
|
+
/**
|
|
159
|
+
* Reads the system clipboard. Implement it for Electron, a native bridge or tests.
|
|
160
|
+
*
|
|
161
|
+
* Contract: call the platform API synchronously (before any `await`) so the
|
|
162
|
+
* browser still sees the user gesture, and reject with a `CopyFailure`.
|
|
163
|
+
* `context.signal` aborts when the read is superseded, reset, or its host
|
|
164
|
+
* unmounts; honour it to stop decoding early.
|
|
165
|
+
*/
|
|
166
|
+
interface PasteAdapter {
|
|
167
|
+
read(options: ResolvedPasteReadOptions, context?: OperationContext): Promise<PasteReadResult>;
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/testing/index.d.ts
|
|
171
|
+
/**
|
|
172
|
+
* Input for {@link createPasteResult}: every field is optional so callers
|
|
173
|
+
* only specify what the test cares about.
|
|
174
|
+
*/
|
|
175
|
+
export interface PasteResultInit {
|
|
176
|
+
readonly source?: PasteSource;
|
|
177
|
+
readonly items?: readonly PasteItem[];
|
|
178
|
+
readonly text?: string | null;
|
|
179
|
+
readonly html?: string | null;
|
|
180
|
+
readonly images?: readonly Blob[];
|
|
181
|
+
readonly files?: readonly File[];
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Builds a complete, self-consistent {@link PasteResult} with sensible defaults.
|
|
185
|
+
*
|
|
186
|
+
* Prefer this over constructing `PasteResult` literals: when the library adds
|
|
187
|
+
* a field (as it did in v1.3.0 and v1.4.0), your tests stay green without any
|
|
188
|
+
* change on your end.
|
|
189
|
+
*
|
|
190
|
+
* ```ts
|
|
191
|
+
* const result = createPasteResult({ text: 'hello', source: 'clipboard' });
|
|
192
|
+
* // result.source → 'clipboard'
|
|
193
|
+
* // result.text → 'hello'
|
|
194
|
+
* // result.html → null
|
|
195
|
+
* // result.images → []
|
|
196
|
+
* // result.files → []
|
|
197
|
+
* // result.imageFiles → []
|
|
198
|
+
* // result.items → [{ type: 'text/plain', data: 'hello' }]
|
|
199
|
+
* ```
|
|
200
|
+
*
|
|
201
|
+
* When `items` is not supplied it is derived from `text`, `html`, and `images`:
|
|
202
|
+
* a `text/plain` entry for `text`, a `text/html` entry for `html`, and one
|
|
203
|
+
* entry per image Blob. `imageFiles` is always computed from the intersection
|
|
204
|
+
* of `images` and `files`, exactly as the machine does.
|
|
205
|
+
*
|
|
206
|
+
* @public
|
|
207
|
+
*/
|
|
208
|
+
export declare function createPasteResult(init?: PasteResultInit): PasteResult;
|
|
209
|
+
/**
|
|
210
|
+
* A queue entry for the mock paste adapter: a {@link PasteReadResult} resolves
|
|
211
|
+
* the next `read()` call; a {@link CopyError} rejects it.
|
|
212
|
+
*/
|
|
213
|
+
export type MockPasteEntry = PasteReadResult | CopyError;
|
|
214
|
+
/**
|
|
215
|
+
* The handle returned by {@link createMockPasteAdapter}.
|
|
216
|
+
* @public
|
|
217
|
+
*/
|
|
218
|
+
export interface MockPasteAdapter {
|
|
219
|
+
/** The adapter itself: pass this as `adapter` in machine / hook options. */
|
|
220
|
+
readonly adapter: PasteAdapter;
|
|
221
|
+
/**
|
|
222
|
+
* Queue a successful result. When the adapter's `read()` is next called it
|
|
223
|
+
* resolves with this value.
|
|
224
|
+
*/
|
|
225
|
+
readonly queueResult: (result: PasteReadResult) => void;
|
|
226
|
+
/**
|
|
227
|
+
* Queue an error. When `read()` is next called it rejects with a
|
|
228
|
+
* `CopyFailure` wrapping this error, which the machine maps to `error` state.
|
|
229
|
+
*/
|
|
230
|
+
readonly queueError: (error: CopyError) => void;
|
|
231
|
+
/**
|
|
232
|
+
* How many times `read()` was called. Useful for asserting that the machine
|
|
233
|
+
* did (or didn't) retry.
|
|
234
|
+
*/
|
|
235
|
+
readonly readCount: () => number;
|
|
236
|
+
/** Drain all pending queue entries and reset the read counter. */
|
|
237
|
+
readonly reset: () => void;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Creates a controllable paste adapter for unit tests.
|
|
241
|
+
*
|
|
242
|
+
* ```ts
|
|
243
|
+
* const mock = createMockPasteAdapter();
|
|
244
|
+
* mock.queueResult(createPasteResult({ text: 'hello' }));
|
|
245
|
+
*
|
|
246
|
+
* const machine = createPasteMachine({ adapter: mock.adapter });
|
|
247
|
+
* await machine.paste();
|
|
248
|
+
*
|
|
249
|
+
* expect(machine.getSnapshot().status).toBe('read');
|
|
250
|
+
* expect(mock.readCount()).toBe(1);
|
|
251
|
+
* ```
|
|
252
|
+
*
|
|
253
|
+
* If `read()` is called when the queue is empty it rejects with a
|
|
254
|
+
* `'no-content'` error so the machine transitions to `error` rather than
|
|
255
|
+
* throwing.
|
|
256
|
+
*
|
|
257
|
+
* @public
|
|
258
|
+
*/
|
|
259
|
+
export declare function createMockPasteAdapter(): MockPasteAdapter;
|
|
260
|
+
/**
|
|
261
|
+
* The handle returned by {@link createMockClipboardAdapter}.
|
|
262
|
+
* @public
|
|
263
|
+
*/
|
|
264
|
+
export interface MockClipboardAdapter {
|
|
265
|
+
/** The adapter itself: pass this as `adapter` in machine / hook options. */
|
|
266
|
+
readonly adapter: ClipboardAdapter;
|
|
267
|
+
/**
|
|
268
|
+
* Queue a successful write. When `write()` is next called it resolves;
|
|
269
|
+
* the payload the machine sends is captured in {@link lastPayload}.
|
|
270
|
+
*/
|
|
271
|
+
readonly queueSuccess: () => void;
|
|
272
|
+
/**
|
|
273
|
+
* Queue a write error. When `write()` is next called it rejects with a
|
|
274
|
+
* `CopyFailure` wrapping this error, which the machine maps to `error` state.
|
|
275
|
+
*/
|
|
276
|
+
readonly queueError: (error: CopyError) => void;
|
|
277
|
+
/**
|
|
278
|
+
* The payload from the most recent `write()` call, or `undefined` if
|
|
279
|
+
* `write()` has not been called yet (or after `reset()`).
|
|
280
|
+
*/
|
|
281
|
+
readonly lastPayload: () => CopyPayload | undefined;
|
|
282
|
+
/** How many times `write()` was called. */
|
|
283
|
+
readonly writeCount: () => number;
|
|
284
|
+
/** Drain pending queue entries and clear captured payload and write counter. */
|
|
285
|
+
readonly reset: () => void;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Creates a controllable clipboard adapter for unit tests.
|
|
289
|
+
*
|
|
290
|
+
* ```ts
|
|
291
|
+
* const mock = createMockClipboardAdapter();
|
|
292
|
+
* mock.queueSuccess();
|
|
293
|
+
*
|
|
294
|
+
* const machine = createCopyMachine({ payload: 'hello', adapter: mock.adapter });
|
|
295
|
+
* await machine.copy();
|
|
296
|
+
*
|
|
297
|
+
* expect(machine.getSnapshot().status).toBe('copied');
|
|
298
|
+
* expect(mock.lastPayload()).toEqual({ kind: 'text', value: 'hello' });
|
|
299
|
+
* ```
|
|
300
|
+
*
|
|
301
|
+
* If `write()` is called when the queue is empty it rejects with an `'unknown'`
|
|
302
|
+
* error so the machine transitions to `error` rather than throwing.
|
|
303
|
+
*
|
|
304
|
+
* @public
|
|
305
|
+
*/
|
|
306
|
+
export declare function createMockClipboardAdapter(): MockClipboardAdapter;
|
|
307
|
+
//#endregion
|
|
308
|
+
export type { ClipboardAdapter, CopyError, CopyPayload, PasteAdapter, PasteItem, PasteReadResult, PasteResult, PasteSource };
|
|
309
|
+
//# sourceMappingURL=testing.d.ts.map
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
//#region src/core/errors.ts
|
|
2
|
+
function createCopyError(type, message, cause) {
|
|
3
|
+
return cause === void 0 ? {
|
|
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
|
|
37
|
+
//#region src/testing/index.ts
|
|
38
|
+
/**
|
|
39
|
+
* Builds a complete, self-consistent {@link PasteResult} with sensible defaults.
|
|
40
|
+
*
|
|
41
|
+
* Prefer this over constructing `PasteResult` literals: when the library adds
|
|
42
|
+
* a field (as it did in v1.3.0 and v1.4.0), your tests stay green without any
|
|
43
|
+
* change on your end.
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const result = createPasteResult({ text: 'hello', source: 'clipboard' });
|
|
47
|
+
* // result.source → 'clipboard'
|
|
48
|
+
* // result.text → 'hello'
|
|
49
|
+
* // result.html → null
|
|
50
|
+
* // result.images → []
|
|
51
|
+
* // result.files → []
|
|
52
|
+
* // result.imageFiles → []
|
|
53
|
+
* // result.items → [{ type: 'text/plain', data: 'hello' }]
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* When `items` is not supplied it is derived from `text`, `html`, and `images`:
|
|
57
|
+
* a `text/plain` entry for `text`, a `text/html` entry for `html`, and one
|
|
58
|
+
* entry per image Blob. `imageFiles` is always computed from the intersection
|
|
59
|
+
* of `images` and `files`, exactly as the machine does.
|
|
60
|
+
*
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
function createPasteResult(init = {}) {
|
|
64
|
+
const source = init.source ?? "clipboard";
|
|
65
|
+
const text = init.text ?? null;
|
|
66
|
+
const html = init.html ?? null;
|
|
67
|
+
const images = init.images ?? [];
|
|
68
|
+
const files = init.files ?? [];
|
|
69
|
+
let items;
|
|
70
|
+
if (init.items !== void 0) items = init.items;
|
|
71
|
+
else {
|
|
72
|
+
const derived = [];
|
|
73
|
+
if (text !== null) derived.push({
|
|
74
|
+
type: "text/plain",
|
|
75
|
+
data: text
|
|
76
|
+
});
|
|
77
|
+
if (html !== null) derived.push({
|
|
78
|
+
type: "text/html",
|
|
79
|
+
data: html
|
|
80
|
+
});
|
|
81
|
+
for (const blob of images) derived.push({
|
|
82
|
+
type: blob.type || "image/png",
|
|
83
|
+
data: blob
|
|
84
|
+
});
|
|
85
|
+
items = derived;
|
|
86
|
+
}
|
|
87
|
+
return completePasteResult({
|
|
88
|
+
source,
|
|
89
|
+
items,
|
|
90
|
+
text,
|
|
91
|
+
html,
|
|
92
|
+
images,
|
|
93
|
+
files
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Creates a controllable paste adapter for unit tests.
|
|
98
|
+
*
|
|
99
|
+
* ```ts
|
|
100
|
+
* const mock = createMockPasteAdapter();
|
|
101
|
+
* mock.queueResult(createPasteResult({ text: 'hello' }));
|
|
102
|
+
*
|
|
103
|
+
* const machine = createPasteMachine({ adapter: mock.adapter });
|
|
104
|
+
* await machine.paste();
|
|
105
|
+
*
|
|
106
|
+
* expect(machine.getSnapshot().status).toBe('read');
|
|
107
|
+
* expect(mock.readCount()).toBe(1);
|
|
108
|
+
* ```
|
|
109
|
+
*
|
|
110
|
+
* If `read()` is called when the queue is empty it rejects with a
|
|
111
|
+
* `'no-content'` error so the machine transitions to `error` rather than
|
|
112
|
+
* throwing.
|
|
113
|
+
*
|
|
114
|
+
* @public
|
|
115
|
+
*/
|
|
116
|
+
function createMockPasteAdapter() {
|
|
117
|
+
const queue = [];
|
|
118
|
+
let reads = 0;
|
|
119
|
+
function isCopyError(entry) {
|
|
120
|
+
return "type" in entry && "message" in entry && !("source" in entry);
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
adapter: { read: (_options, context) => {
|
|
124
|
+
reads += 1;
|
|
125
|
+
if (context?.signal.aborted) return Promise.reject(new CopyFailure(createCopyError("aborted", "The paste was cancelled.")));
|
|
126
|
+
const entry = queue.shift();
|
|
127
|
+
if (entry === void 0) return Promise.reject(new CopyFailure(createCopyError("no-content", "Mock paste adapter: queue is empty.")));
|
|
128
|
+
if (isCopyError(entry)) return Promise.reject(new CopyFailure(entry));
|
|
129
|
+
return Promise.resolve(entry);
|
|
130
|
+
} },
|
|
131
|
+
queueResult: (result) => {
|
|
132
|
+
queue.push(result);
|
|
133
|
+
},
|
|
134
|
+
queueError: (error) => {
|
|
135
|
+
queue.push(error);
|
|
136
|
+
},
|
|
137
|
+
readCount: () => reads,
|
|
138
|
+
reset: () => {
|
|
139
|
+
queue.length = 0;
|
|
140
|
+
reads = 0;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Creates a controllable clipboard adapter for unit tests.
|
|
146
|
+
*
|
|
147
|
+
* ```ts
|
|
148
|
+
* const mock = createMockClipboardAdapter();
|
|
149
|
+
* mock.queueSuccess();
|
|
150
|
+
*
|
|
151
|
+
* const machine = createCopyMachine({ payload: 'hello', adapter: mock.adapter });
|
|
152
|
+
* await machine.copy();
|
|
153
|
+
*
|
|
154
|
+
* expect(machine.getSnapshot().status).toBe('copied');
|
|
155
|
+
* expect(mock.lastPayload()).toEqual({ kind: 'text', value: 'hello' });
|
|
156
|
+
* ```
|
|
157
|
+
*
|
|
158
|
+
* If `write()` is called when the queue is empty it rejects with an `'unknown'`
|
|
159
|
+
* error so the machine transitions to `error` rather than throwing.
|
|
160
|
+
*
|
|
161
|
+
* @public
|
|
162
|
+
*/
|
|
163
|
+
function createMockClipboardAdapter() {
|
|
164
|
+
const queue = [];
|
|
165
|
+
let writes = 0;
|
|
166
|
+
let last;
|
|
167
|
+
return {
|
|
168
|
+
adapter: { write: (payload) => {
|
|
169
|
+
writes += 1;
|
|
170
|
+
last = payload;
|
|
171
|
+
const entry = queue.shift();
|
|
172
|
+
if (entry === void 0) return Promise.reject(new CopyFailure(createCopyError("unknown", "Mock clipboard adapter: queue is empty.")));
|
|
173
|
+
if (!entry.ok) return Promise.reject(new CopyFailure(entry.error));
|
|
174
|
+
return Promise.resolve();
|
|
175
|
+
} },
|
|
176
|
+
queueSuccess: () => {
|
|
177
|
+
queue.push({ ok: true });
|
|
178
|
+
},
|
|
179
|
+
queueError: (error) => {
|
|
180
|
+
queue.push({
|
|
181
|
+
ok: false,
|
|
182
|
+
error
|
|
183
|
+
});
|
|
184
|
+
},
|
|
185
|
+
lastPayload: () => last,
|
|
186
|
+
writeCount: () => writes,
|
|
187
|
+
reset: () => {
|
|
188
|
+
queue.length = 0;
|
|
189
|
+
writes = 0;
|
|
190
|
+
last = void 0;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
export { CopyFailure, createMockClipboardAdapter, createMockPasteAdapter, createPasteResult };
|
|
196
|
+
|
|
197
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +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, 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'`) or a wildcard (`'image/*'`, `'*\\/*'`).\n * `image/svg+xml` is only accepted when listed exactly (it is scriptable XML).\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 normalizeMimeType(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 = normalizeMimeType(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 = normalizeMimeType(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 = normalizeMimeType(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;;;;ACJA,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACKA,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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-smart-copy",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Headless, type-safe clipboard interactions for React: copy and paste text, rich HTML and images, coordinated copy groups, SVG/DOM capture, honest error states, retry, reveal-on-interaction and screen-reader announcements.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -44,6 +44,9 @@
|
|
|
44
44
|
],
|
|
45
45
|
"capture": [
|
|
46
46
|
"./dist/capture.d.ts"
|
|
47
|
+
],
|
|
48
|
+
"testing": [
|
|
49
|
+
"./dist/testing.d.ts"
|
|
47
50
|
]
|
|
48
51
|
}
|
|
49
52
|
},
|
|
@@ -78,6 +81,16 @@
|
|
|
78
81
|
"default": "./dist/capture.cjs"
|
|
79
82
|
}
|
|
80
83
|
},
|
|
84
|
+
"./testing": {
|
|
85
|
+
"import": {
|
|
86
|
+
"types": "./dist/testing.d.ts",
|
|
87
|
+
"default": "./dist/testing.js"
|
|
88
|
+
},
|
|
89
|
+
"require": {
|
|
90
|
+
"types": "./dist/testing.d.cts",
|
|
91
|
+
"default": "./dist/testing.cjs"
|
|
92
|
+
}
|
|
93
|
+
},
|
|
81
94
|
"./package.json": "./package.json"
|
|
82
95
|
},
|
|
83
96
|
"engines": {
|
|
@@ -140,6 +153,11 @@
|
|
|
140
153
|
"name": "capture, all exports",
|
|
141
154
|
"path": "dist/capture.js",
|
|
142
155
|
"limit": "3.6 kB"
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
"name": "testing, all exports",
|
|
159
|
+
"path": "dist/testing.js",
|
|
160
|
+
"limit": "1 kB"
|
|
143
161
|
}
|
|
144
162
|
],
|
|
145
163
|
"publishConfig": {
|