react-smart-copy 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +136 -23
- package/dist/capture.cjs +509 -0
- package/dist/capture.cjs.map +1 -0
- package/dist/capture.d.cts +142 -0
- package/dist/capture.d.ts +142 -0
- package/dist/capture.js +496 -0
- package/dist/capture.js.map +1 -0
- package/dist/core.cjs +579 -23
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +257 -9
- package/dist/core.d.ts +257 -9
- package/dist/core.js +564 -24
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +724 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +328 -12
- package/dist/index.d.ts +328 -12
- package/dist/index.js +706 -43
- package/dist/index.js.map +1 -1
- package/package.json +39 -10
package/dist/core.js
CHANGED
|
@@ -13,6 +13,7 @@ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
|
|
|
13
13
|
"permission-denied",
|
|
14
14
|
"not-focused",
|
|
15
15
|
"blob-generation-failed",
|
|
16
|
+
"timeout",
|
|
16
17
|
"unknown"
|
|
17
18
|
]);
|
|
18
19
|
/** Whether retrying the same payload could plausibly succeed. */
|
|
@@ -36,25 +37,35 @@ var CopyFailure = class extends Error {
|
|
|
36
37
|
function isCopyFailure(value) {
|
|
37
38
|
return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
|
|
38
39
|
}
|
|
40
|
+
/** Shorthand for throwing a classified failure. */
|
|
41
|
+
function copyFailure(type, message, cause) {
|
|
42
|
+
return new CopyFailure(createCopyError(type, message, cause));
|
|
43
|
+
}
|
|
39
44
|
function readString(value, key) {
|
|
40
45
|
if (typeof value !== "object" || value === null) return void 0;
|
|
41
46
|
const field = value[key];
|
|
42
47
|
return typeof field === "string" ? field : void 0;
|
|
43
48
|
}
|
|
44
|
-
/**
|
|
45
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
|
|
51
|
+
* `operation` only tailors the developer-facing message.
|
|
52
|
+
*/
|
|
53
|
+
function toCopyError(cause, operation = "write") {
|
|
46
54
|
if (isCopyFailure(cause)) return cause.copyError;
|
|
47
55
|
const name = readString(cause, "name");
|
|
48
56
|
const message = readString(cause, "message") ?? "";
|
|
57
|
+
const verb = operation === "read" ? "read" : "write";
|
|
49
58
|
switch (name) {
|
|
50
|
-
case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused",
|
|
59
|
+
case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused", `The document was not focused during the clipboard ${verb}.`, cause) : createCopyError("permission-denied", `Clipboard ${verb} permission was denied.`, cause);
|
|
51
60
|
case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
|
|
52
61
|
case "NotSupportedError":
|
|
53
62
|
case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
|
|
54
|
-
|
|
63
|
+
case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
|
|
64
|
+
case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
|
|
65
|
+
default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
|
|
55
66
|
}
|
|
56
67
|
}
|
|
57
|
-
const
|
|
68
|
+
const COPY_DESCRIPTIONS = {
|
|
58
69
|
unsupported: "Copying isn't supported in this browser.",
|
|
59
70
|
"insecure-context": "Copying requires a secure (HTTPS) connection.",
|
|
60
71
|
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
@@ -63,11 +74,34 @@ const DEFAULT_DESCRIPTIONS = {
|
|
|
63
74
|
"unsupported-format": "This content can't be copied in this browser.",
|
|
64
75
|
"blob-generation-failed": "The image couldn't be prepared for copying.",
|
|
65
76
|
"max-retries-exceeded": "Copying failed after several attempts.",
|
|
77
|
+
"no-content": "There is nothing to copy.",
|
|
78
|
+
"too-large": "This content is too large to copy.",
|
|
79
|
+
timeout: "Copying took too long. Try again.",
|
|
80
|
+
aborted: "Copying was cancelled.",
|
|
66
81
|
unknown: "Couldn't copy to the clipboard. Try again."
|
|
67
82
|
};
|
|
68
|
-
|
|
83
|
+
const PASTE_DESCRIPTIONS = {
|
|
84
|
+
unsupported: "Pasting isn't supported in this browser.",
|
|
85
|
+
"insecure-context": "Pasting requires a secure (HTTPS) connection.",
|
|
86
|
+
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
87
|
+
"not-focused": "The page lost focus while pasting. Try again.",
|
|
88
|
+
"invalid-payload": "The clipboard content couldn't be read.",
|
|
89
|
+
"unsupported-format": "This clipboard content isn't supported here.",
|
|
90
|
+
"blob-generation-failed": "The pasted image couldn't be read.",
|
|
91
|
+
"max-retries-exceeded": "Pasting failed after several attempts.",
|
|
92
|
+
"no-content": "The clipboard doesn't contain anything that can be pasted here.",
|
|
93
|
+
"too-large": "The clipboard content is too large to paste.",
|
|
94
|
+
timeout: "Pasting took too long. Try again.",
|
|
95
|
+
aborted: "Pasting was cancelled.",
|
|
96
|
+
unknown: "Couldn't read the clipboard. Try again."
|
|
97
|
+
};
|
|
98
|
+
/** Default English, user-facing sentence for a copy error. Replace for i18n. */
|
|
69
99
|
function describeCopyError(error) {
|
|
70
|
-
return
|
|
100
|
+
return COPY_DESCRIPTIONS[error.type];
|
|
101
|
+
}
|
|
102
|
+
/** Default English, user-facing sentence for a paste error. Replace for i18n. */
|
|
103
|
+
function describePasteError(error) {
|
|
104
|
+
return PASTE_DESCRIPTIONS[error.type];
|
|
71
105
|
}
|
|
72
106
|
//#endregion
|
|
73
107
|
//#region src/core/payload.ts
|
|
@@ -136,10 +170,82 @@ function serializeJson(payload) {
|
|
|
136
170
|
return text;
|
|
137
171
|
}
|
|
138
172
|
//#endregion
|
|
173
|
+
//#region src/core/mime.ts
|
|
174
|
+
/**
|
|
175
|
+
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
176
|
+
* clipboard is untrusted input, so types are normalised and validated before
|
|
177
|
+
* they are compared, and image types are confirmed from the bytes themselves.
|
|
178
|
+
*/
|
|
179
|
+
/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
|
|
180
|
+
const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
181
|
+
/** SVG is XML that can carry scripts; it is never matched by a wildcard. */
|
|
182
|
+
const SVG_MIME_TYPE = "image/svg+xml";
|
|
183
|
+
/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
|
|
184
|
+
function normalizeMimeType(value) {
|
|
185
|
+
const separator = value.indexOf(";");
|
|
186
|
+
const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
|
|
187
|
+
return MIME_SHAPE.test(base) ? base : null;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
|
|
191
|
+
* Wildcards never match `image/svg+xml`: accepting SVG must be explicit.
|
|
192
|
+
*/
|
|
193
|
+
function matchesMimePattern(mimeType, pattern) {
|
|
194
|
+
if (pattern === mimeType) return true;
|
|
195
|
+
if (mimeType === "image/svg+xml") return false;
|
|
196
|
+
if (pattern === "*/*") return true;
|
|
197
|
+
return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
|
|
198
|
+
}
|
|
199
|
+
/** Types whose clipboard data is text and is therefore surfaced as a `string`. */
|
|
200
|
+
function isTextualMimeType(mimeType) {
|
|
201
|
+
return mimeType.startsWith("text/") || mimeType === "image/svg+xml" || mimeType === "application/json" || mimeType === "application/xml";
|
|
202
|
+
}
|
|
203
|
+
const SNIFF_BYTES = 16;
|
|
204
|
+
function startsWith(bytes, signature, offset = 0) {
|
|
205
|
+
return signature.every((byte, index) => bytes[offset + index] === byte);
|
|
206
|
+
}
|
|
207
|
+
const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
|
|
208
|
+
const PNG = [
|
|
209
|
+
137,
|
|
210
|
+
80,
|
|
211
|
+
78,
|
|
212
|
+
71,
|
|
213
|
+
13,
|
|
214
|
+
10,
|
|
215
|
+
26,
|
|
216
|
+
10
|
|
217
|
+
];
|
|
218
|
+
const JPEG = [
|
|
219
|
+
255,
|
|
220
|
+
216,
|
|
221
|
+
255
|
|
222
|
+
];
|
|
223
|
+
const GIF = ascii("GIF8");
|
|
224
|
+
const RIFF = ascii("RIFF");
|
|
225
|
+
const WEBP = ascii("WEBP");
|
|
226
|
+
const BMP = ascii("BM");
|
|
227
|
+
const FTYP_AVIF = ascii("ftypavif");
|
|
228
|
+
const FTYP_AVIS = ascii("ftypavis");
|
|
229
|
+
/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
|
|
230
|
+
function sniffImageBytes(bytes) {
|
|
231
|
+
if (startsWith(bytes, PNG)) return "image/png";
|
|
232
|
+
if (startsWith(bytes, JPEG)) return "image/jpeg";
|
|
233
|
+
if (startsWith(bytes, GIF)) return "image/gif";
|
|
234
|
+
if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
|
|
235
|
+
if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
|
|
236
|
+
if (startsWith(bytes, BMP)) return "image/bmp";
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
|
|
240
|
+
async function sniffImageType(blob) {
|
|
241
|
+
const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
|
|
242
|
+
return sniffImageBytes(new Uint8Array(head));
|
|
243
|
+
}
|
|
244
|
+
//#endregion
|
|
139
245
|
//#region src/core/clipboard-adapter.ts
|
|
140
246
|
const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
|
|
141
247
|
const noop = () => void 0;
|
|
142
|
-
function defaultEnvironment() {
|
|
248
|
+
function defaultEnvironment$1() {
|
|
143
249
|
return typeof window === "undefined" ? void 0 : window;
|
|
144
250
|
}
|
|
145
251
|
function getRichClipboard(env, clipboard) {
|
|
@@ -177,6 +283,7 @@ async function writeImage(rich, source) {
|
|
|
177
283
|
} catch (error) {
|
|
178
284
|
throw await blob.then(noop, (inner) => inner) ?? error;
|
|
179
285
|
}
|
|
286
|
+
await blob;
|
|
180
287
|
}
|
|
181
288
|
async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
182
289
|
if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
@@ -216,16 +323,32 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
|
216
323
|
}
|
|
217
324
|
/** The default adapter: async Clipboard API with feature detection and honest errors. */
|
|
218
325
|
function createBrowserClipboardAdapter(options = {}) {
|
|
219
|
-
const getEnvironment = options.getEnvironment ?? defaultEnvironment;
|
|
326
|
+
const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
|
|
220
327
|
const degradeHtmlToText = options.degradeHtmlToText ?? true;
|
|
221
328
|
return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
|
|
222
329
|
}
|
|
223
330
|
//#endregion
|
|
331
|
+
//#region src/core/copy-coordinator.ts
|
|
332
|
+
function createCopyCoordinator() {
|
|
333
|
+
let active = null;
|
|
334
|
+
return {
|
|
335
|
+
activate: (member) => {
|
|
336
|
+
const previous = active;
|
|
337
|
+
active = member;
|
|
338
|
+
if (previous !== null && previous !== member) previous.release();
|
|
339
|
+
},
|
|
340
|
+
deactivate: (member) => {
|
|
341
|
+
if (active === member) active = null;
|
|
342
|
+
},
|
|
343
|
+
getActive: () => active
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
//#endregion
|
|
224
347
|
//#region src/core/copy-machine.ts
|
|
225
348
|
const DEFAULT_RESET_AFTER_MS = 2e3;
|
|
226
349
|
const DEFAULT_MAX_RETRIES = 3;
|
|
227
350
|
const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
228
|
-
const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
|
|
351
|
+
const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
|
|
229
352
|
status: "ignored",
|
|
230
353
|
reason: "in-flight"
|
|
231
354
|
});
|
|
@@ -242,7 +365,7 @@ function resolveMaxRetries(value) {
|
|
|
242
365
|
if (value === void 0 || !Number.isFinite(value)) return 3;
|
|
243
366
|
return Math.max(0, Math.floor(value));
|
|
244
367
|
}
|
|
245
|
-
function resolveResetDelay(value) {
|
|
368
|
+
function resolveResetDelay$1(value) {
|
|
246
369
|
if (value === false || value === Infinity) return null;
|
|
247
370
|
if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
|
|
248
371
|
return Math.max(0, value);
|
|
@@ -251,7 +374,7 @@ function resolveResetDelay(value) {
|
|
|
251
374
|
function canRetryState(state, maxRetries) {
|
|
252
375
|
return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
|
|
253
376
|
}
|
|
254
|
-
function reportCallbackError(error) {
|
|
377
|
+
function reportCallbackError$1(error) {
|
|
255
378
|
const scope = globalThis;
|
|
256
379
|
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
257
380
|
else setTimeout(() => {
|
|
@@ -259,16 +382,16 @@ function reportCallbackError(error) {
|
|
|
259
382
|
}, 0);
|
|
260
383
|
}
|
|
261
384
|
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
262
|
-
function invoke(fn, ...args) {
|
|
385
|
+
function invoke$1(fn, ...args) {
|
|
263
386
|
if (!fn) return;
|
|
264
387
|
try {
|
|
265
388
|
fn(...args);
|
|
266
389
|
} catch (error) {
|
|
267
|
-
reportCallbackError(error);
|
|
390
|
+
reportCallbackError$1(error);
|
|
268
391
|
}
|
|
269
392
|
}
|
|
270
|
-
let defaultAdapter;
|
|
271
|
-
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserClipboardAdapter());
|
|
393
|
+
let defaultAdapter$1;
|
|
394
|
+
const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
|
|
272
395
|
/** Framework-agnostic copy state machine. */
|
|
273
396
|
function createCopyMachine(options = {}) {
|
|
274
397
|
const read = typeof options === "function" ? options : () => options;
|
|
@@ -277,11 +400,27 @@ function createCopyMachine(options = {}) {
|
|
|
277
400
|
let generation = 0;
|
|
278
401
|
let resetTimer;
|
|
279
402
|
const now = () => (read().now ?? Date.now)();
|
|
403
|
+
let joined = null;
|
|
404
|
+
const member = { release: () => {
|
|
405
|
+
if (state.status === "copied") {
|
|
406
|
+
clearResetTimer();
|
|
407
|
+
setState(IDLE_STATE);
|
|
408
|
+
}
|
|
409
|
+
} };
|
|
280
410
|
const setState = (next) => {
|
|
281
411
|
if (next === state) return;
|
|
412
|
+
const previous = state;
|
|
282
413
|
state = next;
|
|
414
|
+
if (previous.status === "copied" && next.status !== "copied" && joined) {
|
|
415
|
+
joined.deactivate(member);
|
|
416
|
+
joined = null;
|
|
417
|
+
}
|
|
283
418
|
for (const listener of Array.from(listeners)) listener();
|
|
284
419
|
};
|
|
420
|
+
const joinCoordinator = () => {
|
|
421
|
+
joined = read().coordinator ?? null;
|
|
422
|
+
joined?.activate(member);
|
|
423
|
+
};
|
|
285
424
|
const clearResetTimer = () => {
|
|
286
425
|
if (resetTimer !== void 0) {
|
|
287
426
|
clearTimeout(resetTimer);
|
|
@@ -290,12 +429,12 @@ function createCopyMachine(options = {}) {
|
|
|
290
429
|
};
|
|
291
430
|
const scheduleReset = (copied) => {
|
|
292
431
|
clearResetTimer();
|
|
293
|
-
const delay = resolveResetDelay(read().resetAfterMs);
|
|
432
|
+
const delay = resolveResetDelay$1(read().resetAfterMs);
|
|
294
433
|
if (delay === null) return;
|
|
295
434
|
const remaining = Math.max(0, delay - (now() - copied.at));
|
|
296
435
|
resetTimer = setTimeout(() => {
|
|
297
436
|
resetTimer = void 0;
|
|
298
|
-
|
|
437
|
+
setState(IDLE_STATE);
|
|
299
438
|
}, remaining);
|
|
300
439
|
};
|
|
301
440
|
const settleError = (error, payload, retryCount) => {
|
|
@@ -305,14 +444,24 @@ function createCopyMachine(options = {}) {
|
|
|
305
444
|
error,
|
|
306
445
|
retryCount
|
|
307
446
|
});
|
|
308
|
-
invoke(read().onError, error, payload);
|
|
447
|
+
invoke$1(read().onError, error, payload);
|
|
309
448
|
};
|
|
310
449
|
const run = (source, retryCount) => {
|
|
311
450
|
clearResetTimer();
|
|
312
451
|
const current = ++generation;
|
|
313
452
|
let payload;
|
|
314
453
|
try {
|
|
315
|
-
|
|
454
|
+
const resolved = typeof source === "function" ? source() : source;
|
|
455
|
+
const resolvedUnknown = resolved;
|
|
456
|
+
if (resolvedUnknown !== null && typeof resolvedUnknown === "object" && typeof resolvedUnknown.then === "function") {
|
|
457
|
+
const error = createCopyError("invalid-payload", "The copy source function must be synchronous. Returning a Promise breaks the user-gesture window required for clipboard writes. Generate your content before calling copy().");
|
|
458
|
+
settleError(error, null, retryCount);
|
|
459
|
+
return Promise.resolve({
|
|
460
|
+
status: "error",
|
|
461
|
+
error
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
payload = normalizePayload(resolved);
|
|
316
465
|
} catch (cause) {
|
|
317
466
|
const error = createCopyError("invalid-payload", "The copy source function threw.", cause);
|
|
318
467
|
settleError(error, null, retryCount);
|
|
@@ -336,7 +485,7 @@ function createCopyMachine(options = {}) {
|
|
|
336
485
|
});
|
|
337
486
|
let pending;
|
|
338
487
|
try {
|
|
339
|
-
pending = (read().adapter ?? getDefaultAdapter()).write(payload);
|
|
488
|
+
pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
|
|
340
489
|
} catch (cause) {
|
|
341
490
|
pending = Promise.reject(cause);
|
|
342
491
|
}
|
|
@@ -348,8 +497,9 @@ function createCopyMachine(options = {}) {
|
|
|
348
497
|
at: now()
|
|
349
498
|
};
|
|
350
499
|
setState(copied);
|
|
500
|
+
joinCoordinator();
|
|
351
501
|
scheduleReset(copied);
|
|
352
|
-
invoke(read().onCopy, payload);
|
|
502
|
+
invoke$1(read().onCopy, payload);
|
|
353
503
|
}
|
|
354
504
|
return {
|
|
355
505
|
status: "copied",
|
|
@@ -364,7 +514,7 @@ function createCopyMachine(options = {}) {
|
|
|
364
514
|
};
|
|
365
515
|
});
|
|
366
516
|
};
|
|
367
|
-
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);
|
|
517
|
+
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
|
|
368
518
|
const retry = () => {
|
|
369
519
|
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
|
|
370
520
|
if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
|
|
@@ -406,6 +556,396 @@ function createCopyMachine(options = {}) {
|
|
|
406
556
|
};
|
|
407
557
|
}
|
|
408
558
|
//#endregion
|
|
409
|
-
|
|
559
|
+
//#region src/core/paste-reader.ts
|
|
560
|
+
const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
|
|
561
|
+
const DEFAULT_PASTE_MAX_BYTES = 33554432;
|
|
562
|
+
const DEFAULT_PASTE_MAX_ITEMS = 32;
|
|
563
|
+
const SHORTHANDS = /* @__PURE__ */ new Map([
|
|
564
|
+
["text", "text/plain"],
|
|
565
|
+
["html", "text/html"],
|
|
566
|
+
["image", "image/*"],
|
|
567
|
+
["any", "*/*"]
|
|
568
|
+
]);
|
|
569
|
+
const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
570
|
+
function resolvePattern(entry) {
|
|
571
|
+
if (typeof entry !== "string") return null;
|
|
572
|
+
const shorthand = SHORTHANDS.get(entry);
|
|
573
|
+
if (shorthand !== void 0) return shorthand;
|
|
574
|
+
if (entry === "*/*") return entry;
|
|
575
|
+
if (entry.endsWith("/*")) {
|
|
576
|
+
const type = entry.slice(0, -2).toLowerCase();
|
|
577
|
+
return TYPE_TOKEN.test(type) ? `${type}/*` : null;
|
|
578
|
+
}
|
|
579
|
+
return normalizeMimeType(entry);
|
|
580
|
+
}
|
|
581
|
+
function resolveLimit(value, fallback, name) {
|
|
582
|
+
if (value === void 0) return fallback;
|
|
583
|
+
if (value === Infinity || Number.isInteger(value) && value > 0) return value;
|
|
584
|
+
throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
|
|
585
|
+
}
|
|
586
|
+
/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
|
|
587
|
+
function resolvePasteReadOptions(options = {}) {
|
|
588
|
+
const accept = [];
|
|
589
|
+
for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
|
|
590
|
+
const pattern = resolvePattern(entry);
|
|
591
|
+
if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
|
|
592
|
+
if (!accept.includes(pattern)) accept.push(pattern);
|
|
593
|
+
}
|
|
594
|
+
if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
|
|
595
|
+
return {
|
|
596
|
+
accept,
|
|
597
|
+
maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
|
|
598
|
+
maxItems: resolveLimit(options.maxItems, 32, "maxItems")
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
/** Whether a normalised MIME type is allowed by the resolved `accept` list. */
|
|
602
|
+
function isAccepted(mimeType, options) {
|
|
603
|
+
return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
|
|
604
|
+
}
|
|
605
|
+
function createBudget(options) {
|
|
606
|
+
let bytes = 0;
|
|
607
|
+
let items = 0;
|
|
608
|
+
return { charge: (size) => {
|
|
609
|
+
items += 1;
|
|
610
|
+
bytes += size;
|
|
611
|
+
if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
|
|
612
|
+
if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
|
|
613
|
+
} };
|
|
614
|
+
}
|
|
615
|
+
const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
|
|
616
|
+
/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
|
|
617
|
+
function enforcePasteLimits(entries, options) {
|
|
618
|
+
const budget = createBudget(options);
|
|
619
|
+
for (const entry of entries) budget.charge(sizeOf(entry.data));
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Synchronously copies the accepted parts of a paste event's `DataTransfer`.
|
|
623
|
+
* It must run during the event: browsers empty the object afterwards.
|
|
624
|
+
*/
|
|
625
|
+
function snapshotDataTransfer(data, options) {
|
|
626
|
+
const entries = [];
|
|
627
|
+
const seen = /* @__PURE__ */ new Set();
|
|
628
|
+
for (const raw of Array.from(data.types)) {
|
|
629
|
+
const type = normalizeMimeType(raw);
|
|
630
|
+
if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
|
|
631
|
+
seen.add(type);
|
|
632
|
+
const text = data.getData(raw);
|
|
633
|
+
if (text.length > 0) entries.push({
|
|
634
|
+
type,
|
|
635
|
+
data: text,
|
|
636
|
+
file: false
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
for (const file of Array.from(data.files ?? [])) {
|
|
640
|
+
const type = normalizeMimeType(file.type) ?? "application/octet-stream";
|
|
641
|
+
if (isAccepted(type, options)) entries.push({
|
|
642
|
+
type,
|
|
643
|
+
data: file,
|
|
644
|
+
file: true
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
return entries;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Reads the accepted types from `navigator.clipboard.read()` items, enforcing
|
|
651
|
+
* the limits *before* decoding any text so an oversized paste is never buffered twice.
|
|
652
|
+
*/
|
|
653
|
+
async function collectClipboardItems(items, options) {
|
|
654
|
+
const budget = createBudget(options);
|
|
655
|
+
const entries = [];
|
|
656
|
+
const seen = /* @__PURE__ */ new Set();
|
|
657
|
+
for (const item of items) for (const raw of item.types) {
|
|
658
|
+
const type = normalizeMimeType(raw);
|
|
659
|
+
if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
|
|
660
|
+
seen.add(type);
|
|
661
|
+
let blob;
|
|
662
|
+
try {
|
|
663
|
+
blob = await item.getType(raw);
|
|
664
|
+
} catch {
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
667
|
+
if (blob.size === 0) continue;
|
|
668
|
+
budget.charge(blob.size);
|
|
669
|
+
entries.push({
|
|
670
|
+
type,
|
|
671
|
+
data: isTextualMimeType(type) ? await blob.text() : blob,
|
|
672
|
+
file: false
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
return entries;
|
|
676
|
+
}
|
|
677
|
+
function retype(entry, data, type) {
|
|
678
|
+
if (entry.file) {
|
|
679
|
+
const file = data;
|
|
680
|
+
return new File([file], file.name, {
|
|
681
|
+
type,
|
|
682
|
+
lastModified: file.lastModified
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
return data.slice(0, data.size, type);
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Verifies image bytes, then builds the result. Blobs that claim to be images
|
|
689
|
+
* but aren't (or whose real format is not accepted) are dropped. Throws
|
|
690
|
+
* `no-content` when nothing survives.
|
|
691
|
+
*/
|
|
692
|
+
async function finalizePaste(entries, source, options) {
|
|
693
|
+
const items = [];
|
|
694
|
+
const images = [];
|
|
695
|
+
const files = [];
|
|
696
|
+
let text = null;
|
|
697
|
+
let html = null;
|
|
698
|
+
for (const entry of entries) {
|
|
699
|
+
let { type, data } = entry;
|
|
700
|
+
if (typeof data === "string") {
|
|
701
|
+
if (type === "text/plain") text = data;
|
|
702
|
+
else if (type === "text/html") html = data;
|
|
703
|
+
} else if (type.startsWith("image/")) {
|
|
704
|
+
const actual = await sniffImageType(data);
|
|
705
|
+
if (actual === null || !isAccepted(actual, options)) continue;
|
|
706
|
+
if (actual !== type) {
|
|
707
|
+
data = retype(entry, data, actual);
|
|
708
|
+
type = actual;
|
|
709
|
+
}
|
|
710
|
+
images.push(data);
|
|
711
|
+
}
|
|
712
|
+
if (entry.file) files.push(data);
|
|
713
|
+
items.push({
|
|
714
|
+
type,
|
|
715
|
+
data
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
|
|
719
|
+
return {
|
|
720
|
+
source,
|
|
721
|
+
items,
|
|
722
|
+
text,
|
|
723
|
+
html,
|
|
724
|
+
images,
|
|
725
|
+
files
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
//#endregion
|
|
729
|
+
//#region src/core/paste-adapter.ts
|
|
730
|
+
function defaultEnvironment() {
|
|
731
|
+
return typeof window === "undefined" ? void 0 : window;
|
|
732
|
+
}
|
|
733
|
+
const canRead = (clipboard) => typeof clipboard.read === "function";
|
|
734
|
+
const canReadText = (clipboard) => typeof clipboard.readText === "function";
|
|
735
|
+
async function readPlainText(clipboard, options) {
|
|
736
|
+
let text;
|
|
737
|
+
try {
|
|
738
|
+
text = await clipboard.readText();
|
|
739
|
+
} catch (cause) {
|
|
740
|
+
throw new CopyFailure(toCopyError(cause, "read"));
|
|
741
|
+
}
|
|
742
|
+
const entries = text.length > 0 ? [{
|
|
743
|
+
type: "text/plain",
|
|
744
|
+
data: text,
|
|
745
|
+
file: false
|
|
746
|
+
}] : [];
|
|
747
|
+
enforcePasteLimits(entries, options);
|
|
748
|
+
return finalizePaste(entries, "clipboard", options);
|
|
749
|
+
}
|
|
750
|
+
async function readRich(clipboard, options) {
|
|
751
|
+
let items;
|
|
752
|
+
try {
|
|
753
|
+
items = await clipboard.read();
|
|
754
|
+
} catch (cause) {
|
|
755
|
+
throw new CopyFailure(toCopyError(cause, "read"));
|
|
756
|
+
}
|
|
757
|
+
return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
|
|
758
|
+
}
|
|
759
|
+
function readFromClipboard(env, options) {
|
|
760
|
+
if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
761
|
+
if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
|
|
762
|
+
const clipboard = env.navigator?.clipboard;
|
|
763
|
+
if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
|
|
764
|
+
const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
|
|
765
|
+
const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
|
|
766
|
+
if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
|
|
767
|
+
if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
|
|
768
|
+
throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
|
|
769
|
+
}
|
|
770
|
+
/** The default paste adapter: async Clipboard API with feature detection and honest errors. */
|
|
771
|
+
function createBrowserPasteAdapter(options = {}) {
|
|
772
|
+
const getEnvironment = options.getEnvironment ?? defaultEnvironment;
|
|
773
|
+
return { read: (resolved) => {
|
|
774
|
+
try {
|
|
775
|
+
return readFromClipboard(getEnvironment(), resolved);
|
|
776
|
+
} catch (cause) {
|
|
777
|
+
return Promise.reject(cause);
|
|
778
|
+
}
|
|
779
|
+
} };
|
|
780
|
+
}
|
|
781
|
+
//#endregion
|
|
782
|
+
//#region src/core/paste-machine.ts
|
|
783
|
+
const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
784
|
+
const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
|
|
785
|
+
const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
|
|
786
|
+
status: "ignored",
|
|
787
|
+
reason: "in-flight"
|
|
788
|
+
});
|
|
789
|
+
const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
|
|
790
|
+
status: "ignored",
|
|
791
|
+
reason: "no-accepted-content"
|
|
792
|
+
});
|
|
793
|
+
function resolveResetDelay(value) {
|
|
794
|
+
if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
|
|
795
|
+
return Math.max(0, value);
|
|
796
|
+
}
|
|
797
|
+
function reportCallbackError(error) {
|
|
798
|
+
const scope = globalThis;
|
|
799
|
+
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
800
|
+
else setTimeout(() => {
|
|
801
|
+
throw error;
|
|
802
|
+
}, 0);
|
|
803
|
+
}
|
|
804
|
+
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
805
|
+
function invoke(fn, ...args) {
|
|
806
|
+
if (!fn) return;
|
|
807
|
+
try {
|
|
808
|
+
fn(...args);
|
|
809
|
+
} catch (error) {
|
|
810
|
+
reportCallbackError(error);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
let defaultAdapter;
|
|
814
|
+
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
|
|
815
|
+
/** Framework-agnostic paste state machine. */
|
|
816
|
+
function createPasteMachine(options = {}) {
|
|
817
|
+
const read = typeof options === "function" ? options : () => options;
|
|
818
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
819
|
+
let state = PASTE_IDLE_STATE;
|
|
820
|
+
let generation = 0;
|
|
821
|
+
let resetTimer;
|
|
822
|
+
const now = () => (read().now ?? Date.now)();
|
|
823
|
+
const setState = (next) => {
|
|
824
|
+
if (next === state) return;
|
|
825
|
+
state = next;
|
|
826
|
+
for (const listener of Array.from(listeners)) listener();
|
|
827
|
+
};
|
|
828
|
+
const clearResetTimer = () => {
|
|
829
|
+
if (resetTimer !== void 0) {
|
|
830
|
+
clearTimeout(resetTimer);
|
|
831
|
+
resetTimer = void 0;
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
const scheduleReset = (readState) => {
|
|
835
|
+
clearResetTimer();
|
|
836
|
+
const delay = resolveResetDelay(read().resetAfterMs);
|
|
837
|
+
if (delay === null) return;
|
|
838
|
+
const remaining = Math.max(0, delay - (now() - readState.at));
|
|
839
|
+
resetTimer = setTimeout(() => {
|
|
840
|
+
resetTimer = void 0;
|
|
841
|
+
setState(PASTE_IDLE_STATE);
|
|
842
|
+
}, remaining);
|
|
843
|
+
};
|
|
844
|
+
/** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
|
|
845
|
+
const run = (produce) => {
|
|
846
|
+
clearResetTimer();
|
|
847
|
+
const current = ++generation;
|
|
848
|
+
setState(PASTE_READING_STATE);
|
|
849
|
+
let pending;
|
|
850
|
+
try {
|
|
851
|
+
pending = produce();
|
|
852
|
+
} catch (cause) {
|
|
853
|
+
pending = Promise.reject(cause);
|
|
854
|
+
}
|
|
855
|
+
return pending.then((result) => {
|
|
856
|
+
if (current === generation) {
|
|
857
|
+
const readState = {
|
|
858
|
+
status: "read",
|
|
859
|
+
result,
|
|
860
|
+
at: now()
|
|
861
|
+
};
|
|
862
|
+
setState(readState);
|
|
863
|
+
scheduleReset(readState);
|
|
864
|
+
invoke(read().onPaste, result);
|
|
865
|
+
}
|
|
866
|
+
return {
|
|
867
|
+
status: "read",
|
|
868
|
+
result
|
|
869
|
+
};
|
|
870
|
+
}, (cause) => {
|
|
871
|
+
const error = toCopyError(cause, "read");
|
|
872
|
+
if (current === generation) {
|
|
873
|
+
setState({
|
|
874
|
+
status: "error",
|
|
875
|
+
error
|
|
876
|
+
});
|
|
877
|
+
invoke(read().onError, error);
|
|
878
|
+
}
|
|
879
|
+
return {
|
|
880
|
+
status: "error",
|
|
881
|
+
error
|
|
882
|
+
};
|
|
883
|
+
});
|
|
884
|
+
};
|
|
885
|
+
const paste = () => {
|
|
886
|
+
if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
|
|
887
|
+
return run(() => {
|
|
888
|
+
const resolved = resolvePasteReadOptions(read());
|
|
889
|
+
return (read().adapter ?? getDefaultAdapter()).read(resolved);
|
|
890
|
+
});
|
|
891
|
+
};
|
|
892
|
+
const pasteEvent = (event) => {
|
|
893
|
+
const data = event.clipboardData;
|
|
894
|
+
if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
895
|
+
const current = read();
|
|
896
|
+
let resolved;
|
|
897
|
+
try {
|
|
898
|
+
resolved = resolvePasteReadOptions(current);
|
|
899
|
+
} catch (cause) {
|
|
900
|
+
const error = toCopyError(cause, "read");
|
|
901
|
+
++generation;
|
|
902
|
+
clearResetTimer();
|
|
903
|
+
setState({
|
|
904
|
+
status: "error",
|
|
905
|
+
error
|
|
906
|
+
});
|
|
907
|
+
invoke(current.onError, error);
|
|
908
|
+
return Promise.resolve({
|
|
909
|
+
status: "error",
|
|
910
|
+
error
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
const entries = snapshotDataTransfer(data, resolved);
|
|
914
|
+
if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
915
|
+
if (current.preventDefault !== false) event.preventDefault();
|
|
916
|
+
return run(() => {
|
|
917
|
+
enforcePasteLimits(entries, resolved);
|
|
918
|
+
return finalizePaste(entries, "event", resolved);
|
|
919
|
+
});
|
|
920
|
+
};
|
|
921
|
+
const reset = () => {
|
|
922
|
+
++generation;
|
|
923
|
+
clearResetTimer();
|
|
924
|
+
setState(PASTE_IDLE_STATE);
|
|
925
|
+
};
|
|
926
|
+
const connect = () => {
|
|
927
|
+
if (state.status === "read") scheduleReset(state);
|
|
928
|
+
return () => {
|
|
929
|
+
++generation;
|
|
930
|
+
clearResetTimer();
|
|
931
|
+
if (state.status === "reading") setState(PASTE_IDLE_STATE);
|
|
932
|
+
};
|
|
933
|
+
};
|
|
934
|
+
return {
|
|
935
|
+
getSnapshot: () => state,
|
|
936
|
+
subscribe: (listener) => {
|
|
937
|
+
listeners.add(listener);
|
|
938
|
+
return () => {
|
|
939
|
+
listeners.delete(listener);
|
|
940
|
+
};
|
|
941
|
+
},
|
|
942
|
+
paste,
|
|
943
|
+
pasteEvent,
|
|
944
|
+
reset,
|
|
945
|
+
connect
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
//#endregion
|
|
949
|
+
export { CopyFailure, DEFAULT_MAX_RETRIES, DEFAULT_PASTE_ACCEPT, DEFAULT_PASTE_MAX_BYTES, DEFAULT_PASTE_MAX_ITEMS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, PASTE_IDLE_STATE, SVG_MIME_TYPE, canRetryState, copyFailure, createBrowserClipboardAdapter, createBrowserPasteAdapter, createCopyCoordinator, createCopyError, createCopyMachine, createPasteMachine, describeCopyError, describePasteError, isBlob, isCopyFailure, isRetryableError, isTextualMimeType, matchesMimePattern, normalizeMimeType, normalizePayload, resolveMaxRetries, resolvePasteReadOptions, serializeJson, sniffImageBytes, sniffImageType, toCopyError, validatePayload };
|
|
410
950
|
|
|
411
951
|
//# sourceMappingURL=core.js.map
|