react-smart-copy 1.17.2 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -5
- package/dist/capture.cjs +30 -153
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.d.cts +2 -25
- package/dist/capture.d.ts +2 -25
- package/dist/capture.js +5 -128
- package/dist/capture.js.map +1 -1
- package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs +102 -0
- package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs.map +1 -0
- package/dist/chunks/clipboard-adapter-CtH4VELE.d.cts +43 -0
- package/dist/chunks/clipboard-adapter-DEXkXxwV.js +97 -0
- package/dist/chunks/clipboard-adapter-DEXkXxwV.js.map +1 -0
- package/dist/chunks/clipboard-adapter-Ds0irroN.d.ts +43 -0
- package/dist/chunks/contrast-C6CVklEI.cjs +842 -0
- package/dist/chunks/contrast-C6CVklEI.cjs.map +1 -0
- package/dist/chunks/contrast-DpK2JIVu.js +789 -0
- package/dist/chunks/contrast-DpK2JIVu.js.map +1 -0
- package/dist/chunks/copy-interceptor-C6NABy1l.d.ts +141 -0
- package/dist/chunks/copy-interceptor-CZWzGOkL.d.cts +141 -0
- package/dist/chunks/core-Cp2HSpaz.js +1035 -0
- package/dist/chunks/core-Cp2HSpaz.js.map +1 -0
- package/dist/chunks/core-DYf_Lhbe.cjs +1142 -0
- package/dist/chunks/core-DYf_Lhbe.cjs.map +1 -0
- package/dist/chunks/deadline-C29AlS_Q.js +46 -0
- package/dist/chunks/deadline-C29AlS_Q.js.map +1 -0
- package/dist/chunks/deadline-DkiB8ZHE.cjs +51 -0
- package/dist/chunks/deadline-DkiB8ZHE.cjs.map +1 -0
- package/dist/chunks/errors-9h8sdFFX.js +120 -0
- package/dist/chunks/errors-9h8sdFFX.js.map +1 -0
- package/dist/chunks/errors-BwOF6T_M.cjs +167 -0
- package/dist/chunks/errors-BwOF6T_M.cjs.map +1 -0
- package/dist/chunks/index-mr7sSAgP.d.ts +426 -0
- package/dist/chunks/index-vz0iW5V2.d.cts +426 -0
- package/dist/chunks/inert-html-D75NyVvT.js +34 -0
- package/dist/chunks/inert-html-D75NyVvT.js.map +1 -0
- package/dist/chunks/inert-html-DyxjWDok.cjs +39 -0
- package/dist/chunks/inert-html-DyxjWDok.cjs.map +1 -0
- package/dist/chunks/mime--LB7kdqG.cjs +153 -0
- package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
- package/dist/chunks/mime-aa-HA2dm.js +100 -0
- package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
- package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
- package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
- package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
- package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
- package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
- package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
- package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
- package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
- package/dist/chunks/payload-CUymxwim.cjs +100 -0
- package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
- package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
- package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
- package/dist/chunks/payload-DGw-JOo7.js +71 -0
- package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
- package/dist/chunks/payload-DI5AorDz.js +103 -0
- package/dist/chunks/payload-DI5AorDz.js.map +1 -0
- package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
- package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
- package/dist/chunks/share-Bop47Znn.js +208 -0
- package/dist/chunks/share-Bop47Znn.js.map +1 -0
- package/dist/chunks/share-C0esXvRK.d.cts +115 -0
- package/dist/chunks/share-ayDz974N.cjs +231 -0
- package/dist/chunks/share-ayDz974N.cjs.map +1 -0
- package/dist/chunks/share-e7FenIr2.d.ts +115 -0
- package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
- package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
- package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
- package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
- package/dist/chunks/text-field-DUvrMMaK.js +66 -0
- package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
- package/dist/chunks/url-B9jdFGQy.cjs +86 -0
- package/dist/chunks/url-B9jdFGQy.cjs.map +1 -0
- package/dist/chunks/url-BcMYVCXQ.js +135 -0
- package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
- package/dist/chunks/url-D4PGsRm8.cjs +164 -0
- package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
- package/dist/chunks/url-DWdElCT3.d.cts +43 -0
- package/dist/chunks/url-DWdElCT3.d.ts +43 -0
- package/dist/chunks/url-vJaFPbNL.js +57 -0
- package/dist/chunks/url-vJaFPbNL.js.map +1 -0
- package/dist/code.cjs +22 -113
- package/dist/code.cjs.map +1 -1
- package/dist/code.d.cts +4 -28
- package/dist/code.d.ts +4 -28
- package/dist/code.js +5 -96
- package/dist/code.js.map +1 -1
- package/dist/color.cjs +21 -893
- package/dist/color.cjs.map +1 -1
- package/dist/color.d.cts +4 -28
- package/dist/color.d.ts +4 -28
- package/dist/color.js +4 -876
- package/dist/color.js.map +1 -1
- package/dist/core.cjs +52 -1659
- package/dist/core.d.cts +8 -878
- package/dist/core.d.ts +8 -878
- package/dist/core.js +7 -1614
- package/dist/image.cjs +23 -94
- package/dist/image.cjs.map +1 -1
- package/dist/image.d.cts +1 -0
- package/dist/image.d.ts +1 -0
- package/dist/image.js +3 -74
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +74 -2072
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -978
- package/dist/index.d.ts +8 -978
- package/dist/index.js +7 -2005
- package/dist/index.js.map +1 -1
- package/dist/link.cjs +26 -339
- package/dist/link.cjs.map +1 -1
- package/dist/link.d.cts +5 -83
- package/dist/link.d.ts +5 -83
- package/dist/link.js +7 -320
- package/dist/link.js.map +1 -1
- package/dist/markdown.cjs +19 -159
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.d.cts +3 -16
- package/dist/markdown.d.ts +3 -16
- package/dist/markdown.js +6 -146
- package/dist/markdown.js.map +1 -1
- package/dist/rich.cjs +1123 -940
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +101 -91
- package/dist/rich.d.ts +101 -91
- package/dist/rich.js +1099 -919
- package/dist/rich.js.map +1 -1
- package/dist/share.cjs +5 -640
- package/dist/share.d.cts +3 -248
- package/dist/share.d.ts +3 -248
- package/dist/share.js +1 -637
- package/dist/structured.cjs +13 -95
- package/dist/structured.cjs.map +1 -1
- package/dist/structured.d.cts +2 -11
- package/dist/structured.d.ts +2 -11
- package/dist/structured.js +4 -86
- package/dist/structured.js.map +1 -1
- package/dist/table.cjs +13 -40
- package/dist/table.cjs.map +1 -1
- package/dist/table.d.cts +2 -12
- package/dist/table.d.ts +2 -12
- package/dist/table.js +4 -31
- package/dist/table.js.map +1 -1
- package/dist/testing.cjs +10 -43
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +6 -181
- package/dist/testing.d.ts +6 -181
- package/dist/testing.js +3 -36
- package/dist/testing.js.map +1 -1
- package/package.json +37 -5
- package/dist/core.cjs.map +0 -1
- package/dist/core.js.map +0 -1
- package/dist/share.cjs.map +0 -1
- package/dist/share.js.map +0 -1
package/dist/structured.cjs
CHANGED
|
@@ -1,34 +1,8 @@
|
|
|
1
|
+
|
|
1
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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
|
-
/** Shorthand for throwing a classified failure. */
|
|
28
|
-
function copyFailure(type, message, cause) {
|
|
29
|
-
return new CopyFailure(createCopyError(type, message, cause));
|
|
30
|
-
}
|
|
31
|
-
//#endregion
|
|
3
|
+
const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
|
|
4
|
+
const require_mime = require("./chunks/mime--LB7kdqG.cjs");
|
|
5
|
+
const require_paste_reader = require("./chunks/paste-reader-Bo01IMC_.cjs");
|
|
32
6
|
//#region src/structured/guard.ts
|
|
33
7
|
/**
|
|
34
8
|
* Brands formats made by `defineClipFormat`. A registered symbol (not a WeakSet),
|
|
@@ -37,7 +11,7 @@ function copyFailure(type, message, cause) {
|
|
|
37
11
|
const CLIP_FORMAT_BRAND = Symbol.for("react-smart-copy.ClipFormat");
|
|
38
12
|
/** Throws an `invalid-payload` failure unless `format` came from `defineClipFormat`. */
|
|
39
13
|
function assertClipFormat(format) {
|
|
40
|
-
if (typeof format !== "object" || format === null || format[CLIP_FORMAT_BRAND] !== true) throw copyFailure("invalid-payload", "Expected a clip format created with defineClipFormat().");
|
|
14
|
+
if (typeof format !== "object" || format === null || format[CLIP_FORMAT_BRAND] !== true) throw require_errors.copyFailure("invalid-payload", "Expected a clip format created with defineClipFormat().");
|
|
41
15
|
}
|
|
42
16
|
//#endregion
|
|
43
17
|
//#region src/structured/format.ts
|
|
@@ -46,7 +20,7 @@ const DEFAULT_CLIP_MAX_BYTES = 8388608;
|
|
|
46
20
|
const ID_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)+$/;
|
|
47
21
|
const MAX_ID_LENGTH = 96;
|
|
48
22
|
const invalid$1 = (message) => {
|
|
49
|
-
throw copyFailure("invalid-payload", message);
|
|
23
|
+
throw require_errors.copyFailure("invalid-payload", message);
|
|
50
24
|
};
|
|
51
25
|
const isFunction = (value) => typeof value === "function";
|
|
52
26
|
/** Checked before the function form: some Standard Schemas (ArkType) are callable but never throw. */
|
|
@@ -146,9 +120,9 @@ function serializeEnvelope(format, data) {
|
|
|
146
120
|
json = JSON.stringify(data, strictReplacer);
|
|
147
121
|
} catch (cause) {
|
|
148
122
|
const reason = cause instanceof TypeError ? cause.message : "it could not be serialised (circular reference?).";
|
|
149
|
-
throw copyFailure("invalid-payload", `Clip "${format.id}" data is not JSON-safe: ${reason}`, cause);
|
|
123
|
+
throw require_errors.copyFailure("invalid-payload", `Clip "${format.id}" data is not JSON-safe: ${reason}`, cause);
|
|
150
124
|
}
|
|
151
|
-
if (typeof json !== "string") throw copyFailure("invalid-payload", `Clip "${format.id}" data serialised to nothing (undefined, a function or a symbol).`);
|
|
125
|
+
if (typeof json !== "string") throw require_errors.copyFailure("invalid-payload", `Clip "${format.id}" data serialised to nothing (undefined, a function or a symbol).`);
|
|
152
126
|
return `{"rsc":${String(ENVELOPE_SPEC)},"id":"${format.id}","v":${String(format.version)},"data":${json}}`;
|
|
153
127
|
}
|
|
154
128
|
/** Own `__proto__` keys are dropped while parsing, so merging pasted data can never swap a prototype. */
|
|
@@ -179,62 +153,6 @@ function parseEnvelope(text) {
|
|
|
179
153
|
};
|
|
180
154
|
}
|
|
181
155
|
//#endregion
|
|
182
|
-
//#region src/core/mime.ts
|
|
183
|
-
/**
|
|
184
|
-
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
185
|
-
* clipboard is untrusted input, so types are normalised and validated before
|
|
186
|
-
* they are compared, and image types are confirmed from the bytes themselves.
|
|
187
|
-
*/
|
|
188
|
-
/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
|
|
189
|
-
const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
190
|
-
/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
|
|
191
|
-
function normalizeMimeType(value) {
|
|
192
|
-
const separator = value.indexOf(";");
|
|
193
|
-
const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
|
|
194
|
-
return MIME_SHAPE.test(base) ? base : null;
|
|
195
|
-
}
|
|
196
|
-
/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */
|
|
197
|
-
const WEB_CUSTOM_FORMAT_PREFIX = "web ";
|
|
198
|
-
/** Whether a clipboard type is a web custom format (`web type/subtype`). */
|
|
199
|
-
function isWebCustomFormat(type) {
|
|
200
|
-
return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Like {@link normalizeMimeType}, but also accepts web custom formats
|
|
204
|
-
* (`web type/subtype`), returned as `web ` + the normalised MIME type.
|
|
205
|
-
*/
|
|
206
|
-
function normalizeClipboardType(value) {
|
|
207
|
-
if (!isWebCustomFormat(value)) return normalizeMimeType(value);
|
|
208
|
-
const inner = normalizeMimeType(value.slice(4));
|
|
209
|
-
return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;
|
|
210
|
-
}
|
|
211
|
-
const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
|
|
212
|
-
ascii("GIF8");
|
|
213
|
-
ascii("RIFF");
|
|
214
|
-
ascii("WEBP");
|
|
215
|
-
ascii("BM");
|
|
216
|
-
ascii("ftypavif");
|
|
217
|
-
ascii("ftypavis");
|
|
218
|
-
//#endregion
|
|
219
|
-
//#region src/core/paste-reader.ts
|
|
220
|
-
/**
|
|
221
|
-
* UTF-8 byte length of a string, without allocating an encoded copy.
|
|
222
|
-
* Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
|
|
223
|
-
*/
|
|
224
|
-
function utf8ByteLength(text) {
|
|
225
|
-
let bytes = 0;
|
|
226
|
-
for (let i = 0; i < text.length; i += 1) {
|
|
227
|
-
const unit = text.charCodeAt(i);
|
|
228
|
-
if (unit < 128) bytes += 1;
|
|
229
|
-
else if (unit < 2048) bytes += 2;
|
|
230
|
-
else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
|
|
231
|
-
bytes += 4;
|
|
232
|
-
i += 1;
|
|
233
|
-
} else bytes += 3;
|
|
234
|
-
}
|
|
235
|
-
return bytes;
|
|
236
|
-
}
|
|
237
|
-
//#endregion
|
|
238
156
|
//#region src/structured/base64url.ts
|
|
239
157
|
/**
|
|
240
158
|
* UTF-8 ⇄ base64url without padding. The alphabet (`A–Z a–z 0–9 - _`) needs no
|
|
@@ -293,11 +211,11 @@ function clipPayload(format, value) {
|
|
|
293
211
|
assertClipFormat(format);
|
|
294
212
|
const data = format.encode ? format.encode(value) : value;
|
|
295
213
|
const envelope = serializeEnvelope(format, data);
|
|
296
|
-
if (utf8ByteLength(envelope) > format.maxBytes) throw copyFailure("too-large", `Clip "${format.id}" data exceeds the ${String(format.maxBytes)}-byte limit.`);
|
|
214
|
+
if (require_paste_reader.utf8ByteLength(envelope) > format.maxBytes) throw require_errors.copyFailure("too-large", `Clip "${format.id}" data exceeds the ${String(format.maxBytes)}-byte limit.`);
|
|
297
215
|
const text = format.text ? format.text(value) : JSON.stringify(data, null, 2);
|
|
298
|
-
if (typeof text !== "string" || text.length === 0) throw copyFailure("invalid-payload", `Clip "${format.id}": \`text\` must return a non-empty string.`);
|
|
216
|
+
if (typeof text !== "string" || text.length === 0) throw require_errors.copyFailure("invalid-payload", `Clip "${format.id}": \`text\` must return a non-empty string.`);
|
|
299
217
|
const visible = format.html ? format.html(value) : textToHtml(text);
|
|
300
|
-
if (typeof visible !== "string") throw copyFailure("invalid-payload", `Clip "${format.id}": \`html\` must return a string.`);
|
|
218
|
+
if (typeof visible !== "string") throw require_errors.copyFailure("invalid-payload", `Clip "${format.id}": \`html\` must return a string.`);
|
|
301
219
|
const items = [{
|
|
302
220
|
mimeType: format.webMimeType,
|
|
303
221
|
data: envelope,
|
|
@@ -352,7 +270,7 @@ function invalid(carrier, issues, cause) {
|
|
|
352
270
|
function gather(source, format) {
|
|
353
271
|
const found = /* @__PURE__ */ new Map();
|
|
354
272
|
const consider = (raw, read) => {
|
|
355
|
-
const type = normalizeClipboardType(raw);
|
|
273
|
+
const type = require_mime.normalizeClipboardType(raw);
|
|
356
274
|
const carrier = type === format.webMimeType ? "web" : type === format.mimeType ? "custom" : type === "text/html" ? "html" : null;
|
|
357
275
|
if (carrier !== null && !found.has(carrier)) found.set(carrier, read());
|
|
358
276
|
};
|
|
@@ -391,7 +309,7 @@ function extract(candidate, text, format) {
|
|
|
391
309
|
} catch (cause) {
|
|
392
310
|
return invalid(carrier, [issue("The clip embedded in the HTML is corrupted.")], cause);
|
|
393
311
|
}
|
|
394
|
-
} else if (utf8ByteLength(text) > format.maxBytes) return tooLarge();
|
|
312
|
+
} else if (require_paste_reader.utf8ByteLength(text) > format.maxBytes) return tooLarge();
|
|
395
313
|
let envelope;
|
|
396
314
|
try {
|
|
397
315
|
envelope = parseEnvelope(json);
|
package/dist/structured.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured.cjs","names":["invalid"],"sources":["../src/core/errors.ts","../src/structured/guard.ts","../src/structured/format.ts","../src/structured/envelope.ts","../src/core/mime.ts","../src/core/paste-reader.ts","../src/structured/base64url.ts","../src/structured/write.ts","../src/structured/read.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","import { copyFailure } from '../core/errors';\n/**\n * Brands formats made by `defineClipFormat`. A registered symbol (not a WeakSet),\n * so a format still passes when the module is bundled twice (ESM and CJS copies).\n */\nexport const CLIP_FORMAT_BRAND = Symbol.for('react-smart-copy.ClipFormat');\n\n/** Throws an `invalid-payload` failure unless `format` came from `defineClipFormat`. */\nexport function assertClipFormat(format: unknown): void {\n if (typeof format !== 'object' || format === null || (format as Record<symbol, unknown>)[CLIP_FORMAT_BRAND] !== true) {\n throw copyFailure('invalid-payload', 'Expected a clip format created with defineClipFormat().');\n }\n}\n","import { copyFailure } from '../core/errors';\nimport { CLIP_FORMAT_BRAND } from './guard';\nimport type { InferSchemaOutput, StandardSchemaV1 } from './standard-schema';\n\n/** A plain validator: return the typed value, or throw when `data` is not valid. */\nexport type ClipValidator<Value> = (data: unknown) => Value;\n\n/**\n * Validates pasted data. A Standard Schema (Zod, Valibot, ArkType, Effect Schema, …)\n * or a plain function that returns the value or throws.\n */\nexport type ClipSchema<Value> = StandardSchemaV1<unknown, Value> | ClipValidator<Value>;\n\n/**\n * The value a schema produces. Standard Schemas are checked first: some (ArkType)\n * are also callable, and their call signature returns errors instead of throwing.\n */\nexport type ClipSchemaValue<Schema> = Schema extends StandardSchemaV1\n ? InferSchemaOutput<Schema>\n : Schema extends (data: unknown) => infer Value\n ? Value\n : never;\n\n/** Upgrades data written by version `n` to version `n + 1`. Receives untrusted data: check before use. */\nexport type ClipMigration = (data: unknown) => unknown;\n\nexport interface ClipFormatOptions<Value> {\n /**\n * A namespaced id: lower-case words separated by dots, e.g. `'acme.invoice-rows'`.\n * It names the clipboard type (`application/vnd.acme.invoice-rows+json`), so keep it\n * stable and specific to your app; two apps sharing an id can read each other's data.\n */\n readonly id: string;\n /** The data version this app writes. Positive integer, default `1`. Bump it when the shape changes. */\n readonly version?: number;\n /**\n * Validates what is pasted, after migrations. The clipboard is untrusted input:\n * anything (another app, another tab, a malicious page) can put this format on it.\n */\n readonly schema: ClipSchema<Value>;\n /**\n * Migrations from older versions, keyed by the version they upgrade *from*:\n * `{ 1: (v1) => v2 }`. A paste from a version with no migration path is reported\n * as `unsupported-version`.\n */\n readonly migrate?: Readonly<Record<number, ClipMigration>>;\n /**\n * Turns the value into JSON-ready data. Default: the value itself. The result must\n * survive `JSON.stringify` unchanged (no Map, Set, functions, NaN or Infinity);\n * Dates become ISO strings, so validate them back with a coercing schema.\n */\n readonly encode?: (value: Value) => unknown;\n /** Plain text for other apps (editors, chat, terminals). Default: the encoded data as indented JSON. */\n readonly text?: (value: Value) => string;\n /**\n * Visible HTML for rich targets (Docs, Word, mail). Treat it like any HTML you\n * generate: escape what you interpolate. Default: the plain text.\n */\n readonly html?: (value: Value) => string;\n /** Size cap of the serialised data, in UTF-8 bytes, enforced on copy and paste. Default 8 MiB. */\n readonly maxBytes?: number;\n /**\n * Also embed the data, hidden, in the copied HTML: the carrier that works for every\n * paste path in every browser (keyboard paste, drag-and-drop, Safari, Firefox).\n * The embedded data travels wherever the HTML is pasted (a mail, a document), so\n * copy only what the user may share. Default `true`.\n */\n readonly embedInHtml?: boolean;\n}\n\n/** A validated, frozen clipboard format. Create one with {@link defineClipFormat} and share it. */\nexport interface ClipFormat<Value> {\n readonly id: string;\n readonly version: number;\n /** The clipboard type for copy and drag events, e.g. `application/vnd.acme.invoice-rows+json`. */\n readonly mimeType: string;\n /** The async Clipboard API's web custom format: `web ` + {@link mimeType}. */\n readonly webMimeType: string;\n readonly schema: ClipSchema<Value>;\n readonly migrate: Readonly<Record<number, ClipMigration>>;\n readonly encode: ((value: Value) => unknown) | undefined;\n readonly text: ((value: Value) => string) | undefined;\n readonly html: ((value: Value) => string) | undefined;\n readonly maxBytes: number;\n readonly embedInHtml: boolean;\n}\n\n/** The parts of a format that do not depend on its value type. */\nexport type ClipFormatInfo = Pick<ClipFormat<unknown>, 'id' | 'version' | 'mimeType' | 'webMimeType' | 'maxBytes'>;\n\n/** The value type of a format: `ClipValue<typeof InvoiceRows>`. */\nexport type ClipValue<Format> = Format extends ClipFormat<infer Value> ? Value : never;\n\nexport const DEFAULT_CLIP_MAX_BYTES = 8 * 1024 * 1024;\n\n/** `namespace.name`: at least two dot-separated parts of lower-case letters, digits and inner hyphens. */\nconst ID_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\\.[a-z0-9]+(?:-[a-z0-9]+)*)+$/;\nconst MAX_ID_LENGTH = 96;\n\nconst invalid = (message: string): never => {\n throw copyFailure('invalid-payload', message);\n};\n\nconst isFunction = (value: unknown): value is (...args: never[]) => unknown => typeof value === 'function';\n\n/** Checked before the function form: some Standard Schemas (ArkType) are callable but never throw. */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return false;\n const props = (value as { readonly '~standard'?: { readonly version?: unknown; readonly validate?: unknown } })['~standard'];\n return typeof props === 'object' && props.version === 1 && isFunction(props.validate);\n}\n\nfunction optionalFunction<Fn>(value: Fn | undefined, name: string): Fn | undefined {\n if (value !== undefined && !isFunction(value)) invalid(`\\`${name}\\` must be a function.`);\n return value;\n}\n\nfunction resolveMigrations(migrate: unknown, version: number): Readonly<Record<number, ClipMigration>> {\n const steps = Object.create(null) as Record<number, ClipMigration>;\n if (migrate === undefined) return Object.freeze(steps);\n if (typeof migrate !== 'object' || migrate === null) return invalid('`migrate` must be an object of functions.');\n for (const [key, step] of Object.entries(migrate)) {\n const from = Number(key);\n if (!Number.isInteger(from) || from < 1 || from >= version || String(from) !== key) {\n invalid(`\\`migrate\\` key \"${key}\" must be a version from 1 to ${String(version - 1)}.`);\n }\n if (!isFunction(step)) invalid(`\\`migrate[${key}]\\` must be a function.`);\n steps[from] = step as ClipMigration;\n }\n return Object.freeze(steps);\n}\n\n/**\n * Defines a typed clipboard format: copy it with {@link clipPayload}, read it back\n * with {@link readClip}. Define each format once, at module level, and share it\n * between the copying and the pasting code.\n *\n * Throws an `invalid-payload` `CopyFailure` when the definition is invalid.\n *\n * @example\n * const InvoiceRows = defineClipFormat({\n * id: 'acme.invoice-rows',\n * version: 2,\n * schema: z.array(Invoice),\n * migrate: { 1: (rows) => upgradeV1(rows) },\n * text: (rows) => rows.map((row) => row.id).join('\\n'),\n * });\n */\nexport function defineClipFormat<Schema extends ClipSchema<unknown>>(\n options: Omit<ClipFormatOptions<ClipSchemaValue<Schema>>, 'schema'> & { readonly schema: Schema },\n): ClipFormat<ClipSchemaValue<Schema>> {\n type Value = ClipSchemaValue<Schema>;\n const { id, schema } = options;\n if (typeof id !== 'string' || id.length > MAX_ID_LENGTH || !ID_SHAPE.test(id)) {\n invalid(`Clip format id ${JSON.stringify(id)} must look like \"namespace.name\" (lower-case, at most ${String(MAX_ID_LENGTH)} characters).`);\n }\n const version = options.version ?? 1;\n if (!Number.isSafeInteger(version) || version < 1) invalid(`\\`version\\` must be a positive integer (received ${String(version)}).`);\n if (!isStandardSchema(schema) && !isFunction(schema)) {\n invalid('`schema` must be a Standard Schema (Zod, Valibot, ArkType, …) or a validator function.');\n }\n const maxBytes = options.maxBytes ?? DEFAULT_CLIP_MAX_BYTES;\n if (maxBytes !== Infinity && !(Number.isInteger(maxBytes) && maxBytes > 0)) {\n invalid(`\\`maxBytes\\` must be a positive integer or Infinity (received ${String(maxBytes)}).`);\n }\n const mimeType = `application/vnd.${id}+json`;\n const format: ClipFormat<Value> = {\n id,\n version,\n mimeType,\n webMimeType: `web ${mimeType}`,\n // `Schema` is exactly `ClipSchema<Value>` for its own value type; TypeScript cannot follow the conditional.\n schema: schema as ClipSchema<Value>,\n migrate: resolveMigrations(options.migrate, version),\n encode: optionalFunction(options.encode, 'encode'),\n text: optionalFunction(options.text, 'text'),\n html: optionalFunction(options.html, 'html'),\n maxBytes,\n embedInHtml: options.embedInHtml ?? true,\n };\n // Non-enumerable, so a spread copy (which could be edited out of sync) is not a format.\n Object.defineProperty(format, CLIP_FORMAT_BRAND, { value: true });\n return Object.freeze(format);\n}\n","import { copyFailure } from '../core/errors';\nimport type { ClipFormatInfo } from './format';\n\n/**\n * The wire format every carrier holds: `{\"rsc\":1,\"id\":…,\"v\":…,\"data\":…}`.\n * `rsc` is the envelope spec version; unknown extra keys are ignored for forward compatibility.\n */\nexport interface ClipEnvelope {\n readonly id: string;\n readonly version: number;\n readonly data: unknown;\n}\n\nconst ENVELOPE_SPEC = 1;\n\n/** The HTML attribute holding `id;base64url(envelope)`. Exported for documentation and tests. */\nexport const CLIP_HTML_ATTRIBUTE = 'data-rsc-clip';\n\nfunction describeKey(key: string): string {\n return key === '' ? 'The data' : `\"${key}\"`;\n}\n\n/**\n * Rejects what `JSON.stringify` would silently change or drop, so the value that\n * is pasted is the value that was copied. `undefined` object properties are allowed\n * (they are simply absent, which schemas treat as optional).\n */\nfunction strictReplacer(key: string, value: unknown): unknown {\n switch (typeof value) {\n case 'number':\n if (!Number.isFinite(value)) throw new TypeError(`${describeKey(key)} is ${String(value)}, which JSON turns into null.`);\n return value;\n case 'bigint':\n throw new TypeError(`${describeKey(key)} is a BigInt, which JSON cannot represent: encode it as a string.`);\n case 'function':\n case 'symbol':\n throw new TypeError(`${describeKey(key)} is a ${typeof value}, which JSON drops.`);\n case 'object':\n if (value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) {\n throw new TypeError(`${describeKey(key)} is a ${value.constructor.name}, which JSON turns into {}: encode it as an array or object.`);\n }\n return value;\n default:\n return value;\n }\n}\n\n/** Serialises `data` into an envelope. Throws a classified `invalid-payload` failure. */\nexport function serializeEnvelope(format: ClipFormatInfo, data: unknown): string {\n let json: unknown;\n try {\n json = JSON.stringify(data, strictReplacer);\n } catch (cause) {\n const reason = cause instanceof TypeError ? cause.message : 'it could not be serialised (circular reference?).';\n throw copyFailure('invalid-payload', `Clip \"${format.id}\" data is not JSON-safe: ${reason}`, cause);\n }\n if (typeof json !== 'string') {\n throw copyFailure('invalid-payload', `Clip \"${format.id}\" data serialised to nothing (undefined, a function or a symbol).`);\n }\n // `id` matches /^[a-z0-9.-]+$/ (checked by defineClipFormat), so it needs no JSON escaping.\n return `{\"rsc\":${String(ENVELOPE_SPEC)},\"id\":\"${format.id}\",\"v\":${String(format.version)},\"data\":${json}}`;\n}\n\n/** Own `__proto__` keys are dropped while parsing, so merging pasted data can never swap a prototype. */\nfunction dropProtoKeys(key: string, value: unknown): unknown {\n return key === '__proto__' ? undefined : value;\n}\n\nconst hasOwn = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key);\n\n/** Parses and checks an envelope. Throws a `TypeError` describing what is wrong. */\nexport function parseEnvelope(text: string): ClipEnvelope {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text, dropProtoKeys);\n } catch {\n throw new TypeError('The clipboard data is not valid JSON.');\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new TypeError('The clipboard data is not a clip envelope.');\n }\n const envelope = parsed as Record<string, unknown>;\n if (envelope['rsc'] !== ENVELOPE_SPEC) throw new TypeError('The clip envelope has an unknown spec version.');\n const id = envelope['id'];\n const version = envelope['v'];\n if (typeof id !== 'string') throw new TypeError('The clip envelope has no format id.');\n if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 1) {\n throw new TypeError('The clip envelope has an invalid version.');\n }\n if (!hasOwn(envelope, 'data')) throw new TypeError('The clip envelope has no data.');\n return { id, version, data: envelope['data'] };\n}\n","/**\n * MIME helpers shared by paste and capture. Everything that comes from the\n * clipboard is untrusted input, so types are normalised and validated before\n * they are compared, and image types are confirmed from the bytes themselves.\n */\n\n/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */\nconst MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\n/** SVG is XML that can carry scripts; it is never matched by a wildcard. */\nexport const SVG_MIME_TYPE = 'image/svg+xml';\n\n/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */\nexport function normalizeMimeType(value: string): string | null {\n const separator = value.indexOf(';');\n const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();\n return MIME_SHAPE.test(base) ? base : null;\n}\n\n/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */\nexport const WEB_CUSTOM_FORMAT_PREFIX = 'web ';\n\n/** Whether a clipboard type is a web custom format (`web type/subtype`). */\nexport function isWebCustomFormat(type: string): boolean {\n return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;\n}\n\n/**\n * Like {@link normalizeMimeType}, but also accepts web custom formats\n * (`web type/subtype`), returned as `web ` + the normalised MIME type.\n */\nexport function normalizeClipboardType(value: string): string | null {\n if (!isWebCustomFormat(value)) return normalizeMimeType(value);\n const inner = normalizeMimeType(value.slice(4));\n return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;\n}\n\n/**\n * Types a wildcard never matches, so accepting them must be explicit:\n * `image/svg+xml` (scriptable XML), web custom formats and structured `+json` types\n * (application-specific data that only the app that defined them should read).\n */\nfunction requiresExactMatch(mimeType: string): boolean {\n return mimeType === SVG_MIME_TYPE || isWebCustomFormat(mimeType) || mimeType.endsWith('+json');\n}\n\n/**\n * Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\\/*`)?\n * Wildcards never match `image/svg+xml`, web custom formats or `+json` types: those must be listed exactly.\n */\nexport function matchesMimePattern(mimeType: string, pattern: string): boolean {\n if (pattern === mimeType) return true;\n if (requiresExactMatch(mimeType)) return false;\n if (pattern === '*/*') return true;\n return pattern.endsWith('/*') && mimeType.startsWith(pattern.slice(0, -1));\n}\n\n/** Types whose clipboard data is text and is therefore surfaced as a `string`. */\nexport function isTextualMimeType(mimeType: string): boolean {\n const type = isWebCustomFormat(mimeType) ? mimeType.slice(4) : mimeType;\n return (\n type.startsWith('text/') ||\n type === SVG_MIME_TYPE ||\n type === 'application/json' ||\n type === 'application/xml' ||\n type.endsWith('+json')\n );\n}\n\n/** Raster image formats recognised from their leading bytes. */\nexport type RasterImageMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/bmp' | 'image/avif';\n\nconst SNIFF_BYTES = 16;\n\nfunction startsWith(bytes: Uint8Array, signature: readonly number[], offset = 0): boolean {\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nconst ascii = (text: string): number[] => Array.from(text, (char) => char.charCodeAt(0));\n\nconst PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\nconst JPEG = [0xff, 0xd8, 0xff];\nconst GIF = ascii('GIF8');\nconst RIFF = ascii('RIFF');\nconst WEBP = ascii('WEBP');\nconst BMP = ascii('BM');\nconst FTYP_AVIF = ascii('ftypavif');\nconst FTYP_AVIS = ascii('ftypavis');\n\n/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */\nexport function sniffImageBytes(bytes: Uint8Array): RasterImageMimeType | null {\n if (startsWith(bytes, PNG)) return 'image/png';\n if (startsWith(bytes, JPEG)) return 'image/jpeg';\n if (startsWith(bytes, GIF)) return 'image/gif';\n if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return 'image/webp';\n if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return 'image/avif';\n if (startsWith(bytes, BMP)) return 'image/bmp';\n return null;\n}\n\n/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */\nexport async function sniffImageType(blob: Blob): Promise<RasterImageMimeType | null> {\n const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();\n return sniffImageBytes(new Uint8Array(head));\n}\n","import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n","/**\n * UTF-8 ⇄ base64url without padding. The alphabet (`A–Z a–z 0–9 - _`) needs no\n * escaping in HTML attributes, survives every clipboard sanitiser we target, and is\n * a closed set, so the envelope can be found with a strict token match instead of\n * parsing untrusted HTML.\n */\n\nconst CHUNK = 0x8000;\n\nexport function encodeBase64Url(text: string): string {\n const bytes = new TextEncoder().encode(text);\n let binary = '';\n for (let start = 0; start < bytes.length; start += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(start, start + CHUNK));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nconst BASE64URL = /^[A-Za-z0-9_-]*$/;\n\n/** Decodes base64url to text. Throws on a malformed token or invalid UTF-8. */\nexport function decodeBase64Url(token: string): string {\n if (!BASE64URL.test(token) || token.length % 4 === 1) throw new TypeError('Malformed base64url token.');\n const padded = token.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (token.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n}\n\n/** Upper bound of the bytes a base64url token decodes to, without decoding it. */\nexport const decodedSize = (token: string): number => Math.floor((token.length * 3) / 4);\n","import { copyFailure } from '../core/errors';\nimport { utf8ByteLength } from '../core/paste-reader';\nimport { encodeBase64Url } from './base64url';\nimport { CLIP_HTML_ATTRIBUTE, serializeEnvelope } from './envelope';\nimport { assertClipFormat } from './guard';\nimport type { ClipFormat } from './format';\n\n/** One clipboard entry of a {@link ClipPayload}. Strings only, so it also works in copy and drag events. */\nexport interface ClipPayloadItem {\n readonly mimeType: string;\n readonly data: string;\n readonly optional?: boolean;\n}\n\n/**\n * A multi-format payload carrying a clip. Pass it to `copy()`, return it from a\n * `useCopyInterceptor` transform or a `useDragCopy` source: each path writes the\n * carriers it can.\n */\nexport interface ClipPayload {\n readonly kind: 'multi';\n readonly items: readonly ClipPayloadItem[];\n}\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' };\n\nconst escapeHtml = (text: string): string => text.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char] as string);\n\n/** Plain text as HTML: escaped, with line breaks kept (many targets drop `white-space` styles). */\nconst textToHtml = (text: string): string => escapeHtml(text).replace(/\\r\\n|\\r|\\n/g, '<br>');\n\n/**\n * Builds the payload that puts `value` on the clipboard in `format`, through three carriers:\n *\n * 1. `web application/vnd.<id>+json`: the async Clipboard API's web custom format\n * (Chromium). Read back by `navigator.clipboard.read()`, also across origins.\n * 2. `application/vnd.<id>+json`: written by copy and drag events, read back by\n * paste and drop events.\n * 3. A hidden envelope in `text/html`, which every paste path in every browser keeps.\n *\n * Plus `text/plain` (and visible HTML) for every other app. Carriers a browser\n * cannot write are skipped. {@link readClip} tries them in this order.\n *\n * Synchronous, so it can be built inside the user gesture. Throws a classified\n * `CopyFailure`: `invalid-payload` when the data is not JSON-safe, `too-large`\n * when it exceeds the format's `maxBytes`.\n */\nexport function clipPayload<Value>(format: ClipFormat<Value>, value: Value): ClipPayload {\n assertClipFormat(format);\n const data = format.encode ? format.encode(value) : value;\n const envelope = serializeEnvelope(format, data);\n if (utf8ByteLength(envelope) > format.maxBytes) {\n throw copyFailure('too-large', `Clip \"${format.id}\" data exceeds the ${String(format.maxBytes)}-byte limit.`);\n }\n\n const text: unknown = format.text ? format.text(value) : JSON.stringify(data, null, 2);\n if (typeof text !== 'string' || text.length === 0) {\n throw copyFailure('invalid-payload', `Clip \"${format.id}\": \\`text\\` must return a non-empty string.`);\n }\n const visible: unknown = format.html ? format.html(value) : textToHtml(text);\n if (typeof visible !== 'string') {\n throw copyFailure('invalid-payload', `Clip \"${format.id}\": \\`html\\` must return a string.`);\n }\n\n const items: ClipPayloadItem[] = [\n { mimeType: format.webMimeType, data: envelope, optional: true },\n { mimeType: format.mimeType, data: envelope, optional: true },\n ];\n const html = format.embedInHtml\n ? `<span ${CLIP_HTML_ATTRIBUTE}=\"${format.id};${encodeBase64Url(envelope)}\"></span>${visible}`\n : visible;\n if (html.length > 0) items.push({ mimeType: 'text/html', data: html });\n items.push({ mimeType: 'text/plain', data: text });\n return { kind: 'multi', items };\n}\n","import { normalizeClipboardType } from '../core/mime';\nimport type { PasteAccept } from '../core/paste-reader';\nimport { utf8ByteLength } from '../core/paste-reader';\nimport { decodeBase64Url, decodedSize } from './base64url';\nimport { parseEnvelope, type ClipEnvelope } from './envelope';\nimport { isStandardSchema, type ClipFormat, type ClipFormatInfo } from './format';\nimport { assertClipFormat } from './guard';\nimport type { StandardSchemaResult } from './standard-schema';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Which carrier the clip was read from, most to least specific. */\nexport type ClipCarrier = 'web' | 'custom' | 'html';\n\nexport interface ClipIssue {\n readonly message: string;\n /** Where in the data the problem is; empty for the data as a whole. */\n readonly path: readonly PropertyKey[];\n}\n\nexport interface ClipReadOk<Value> {\n readonly status: 'ok';\n /** The validated (and, if needed, migrated) value. */\n readonly value: Value;\n /** The version the data was written with; lower than the format's when it was migrated. */\n readonly version: number;\n readonly carrier: ClipCarrier;\n}\n\n/** The source holds no data in this format. */\nexport interface ClipReadAbsent {\n readonly status: 'absent';\n}\n\n/** Data in this format was found but is malformed, too large, failed a migration or failed the schema. */\nexport interface ClipReadInvalid {\n readonly status: 'invalid';\n readonly carrier: ClipCarrier;\n readonly issues: readonly ClipIssue[];\n /** What a migration or validator threw, if anything. */\n readonly cause?: unknown;\n}\n\n/** Written by a newer version of the app, or by an older one with no migration path. */\nexport interface ClipReadUnsupportedVersion {\n readonly status: 'unsupported-version';\n readonly carrier: ClipCarrier;\n readonly version: number;\n}\n\nexport type ClipReadResult<Value> = ClipReadOk<Value> | ClipReadAbsent | ClipReadInvalid | ClipReadUnsupportedVersion;\n\n/** An entry of a paste result (`type`) or of a clip payload (`mimeType`). */\nexport type ClipSourceItem =\n | { readonly type: string; readonly data: string | Blob }\n | { readonly mimeType: string; readonly data: string | Blob };\n\n/** The `DataTransfer` of a paste or drop event you handle yourself. */\nexport interface ClipDataTransfer {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n}\n\n/**\n * Where to read a clip from: a `PasteResult` (from `usePaste`, `PasteField` or a\n * paste adapter), a {@link ClipPayload} (round-trips, tests, in-app duplication), or\n * a raw `DataTransfer`.\n */\nexport type ClipSource = { readonly items: readonly ClipSourceItem[] } | ClipDataTransfer;\n\n/* -------------------------------------------------------------- Helpers */\n\ninterface Candidate {\n readonly carrier: ClipCarrier;\n readonly data: string | Blob;\n}\n\nconst CARRIERS: readonly ClipCarrier[] = ['web', 'custom', 'html'];\n\n/** Envelope tokens are scanned for at most this many times per HTML string. */\nconst MAX_HTML_TOKENS = 64;\n\nconst messageOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));\n\nconst isTransfer = (source: ClipSource): source is ClipDataTransfer =>\n typeof (source as Partial<ClipDataTransfer>).getData === 'function';\n\nconst issue = (message: string): ClipIssue => ({ message, path: [] });\n\nfunction invalid(carrier: ClipCarrier, issues: readonly ClipIssue[], cause?: unknown): ClipReadInvalid {\n return cause === undefined ? { status: 'invalid', carrier, issues } : { status: 'invalid', carrier, issues, cause };\n}\n\n/** The candidate entries in carrier order. Reads `DataTransfer` data only for types that match. */\nfunction gather(source: ClipSource, format: ClipFormatInfo): Candidate[] {\n const found = new Map<ClipCarrier, string | Blob>();\n const consider = (raw: string, read: () => string | Blob): void => {\n const type = normalizeClipboardType(raw);\n const carrier: ClipCarrier | null =\n type === format.webMimeType ? 'web' : type === format.mimeType ? 'custom' : type === 'text/html' ? 'html' : null;\n if (carrier !== null && !found.has(carrier)) found.set(carrier, read());\n };\n if (isTransfer(source)) {\n for (const type of Array.from(source.types)) consider(type, () => source.getData(type));\n } else {\n for (const item of source.items) consider('type' in item ? item.type : item.mimeType, () => item.data);\n }\n const candidates: Candidate[] = [];\n for (const carrier of CARRIERS) {\n const data = found.get(carrier);\n if (data !== undefined) candidates.push({ carrier, data });\n }\n return candidates;\n}\n\nfunction findHtmlToken(html: string, id: string): string | null {\n // The token alphabet is closed (id: [a-z0-9.-], data: base64url), so a strict match is exact:\n // no HTML parsing, no DOM, linear time. Quotes may be single or double.\n const pattern = /data-rsc-clip\\s*=\\s*([\"'])([a-z0-9.-]{1,96});([A-Za-z0-9_-]*)\\1/g;\n for (let scanned = 0; scanned < MAX_HTML_TOKENS; scanned += 1) {\n const match = pattern.exec(html);\n if (match === null) return null;\n if (match[2] === id) return match[3] as string;\n }\n return null;\n}\n\n/** The envelope a carrier holds, `null` when it holds none for this format, or why it is unusable. */\nfunction extract(candidate: Candidate, text: string, format: ClipFormatInfo): ClipEnvelope | ClipReadInvalid | null {\n const { carrier } = candidate;\n const tooLarge = (): ClipReadInvalid =>\n invalid(carrier, [issue(`The clip exceeds the ${String(format.maxBytes)}-byte limit.`)]);\n let json = text;\n if (carrier === 'html') {\n const token = findHtmlToken(text, format.id);\n if (token === null) return null;\n if (decodedSize(token) > format.maxBytes) return tooLarge();\n try {\n json = decodeBase64Url(token);\n } catch (cause) {\n return invalid(carrier, [issue('The clip embedded in the HTML is corrupted.')], cause);\n }\n } else if (utf8ByteLength(text) > format.maxBytes) {\n return tooLarge();\n }\n let envelope: ClipEnvelope;\n try {\n envelope = parseEnvelope(json);\n } catch (cause) {\n return invalid(carrier, [issue(messageOf(cause))], cause);\n }\n if (envelope.id !== format.id) {\n return invalid(carrier, [issue(`The clipboard holds \"${envelope.id}\" data under the \"${format.id}\" type.`)]);\n }\n return envelope;\n}\n\nfunction fromStandardResult<Value>(\n result: StandardSchemaResult<Value>,\n carrier: ClipCarrier,\n version: number,\n): ClipReadResult<Value> {\n if (typeof (result as unknown) !== 'object' || (result as unknown) === null) {\n return invalid(carrier, [issue('The schema returned a malformed result.')]);\n }\n if (result.issues !== undefined) {\n // Schemas are third-party code: read their issues defensively, never throw.\n const raw: unknown = result.issues;\n const issues = Array.from(Array.isArray(raw) ? (raw as unknown[]) : [], (item): ClipIssue => {\n const entry = (typeof item === 'object' && item !== null ? item : {}) as { message?: unknown; path?: unknown };\n // Array.from, not .map: some libraries' paths are Array subclasses, and the result must be a plain array.\n const path = Array.isArray(entry.path)\n ? Array.from(entry.path as unknown[], (segment) =>\n typeof segment === 'object' && segment !== null ? (segment as { key: PropertyKey }).key : (segment as PropertyKey),\n )\n : [];\n return { message: typeof entry.message === 'string' ? entry.message : 'Invalid value.', path };\n });\n return invalid(carrier, issues.length > 0 ? issues : [issue('The schema rejected the data.')]);\n }\n return { status: 'ok', value: result.value, version, carrier };\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n}\n\n/** Migrates and validates an envelope. Returns a promise only when the schema validates asynchronously. */\nfunction settle<Value>(\n envelope: ClipEnvelope,\n carrier: ClipCarrier,\n format: ClipFormat<Value>,\n): ClipReadResult<Value> | Promise<ClipReadResult<Value>> {\n const { version } = envelope;\n if (version > format.version) return { status: 'unsupported-version', carrier, version };\n\n let data = envelope.data;\n for (let from = version; from < format.version; from += 1) {\n const step = format.migrate[from];\n if (step === undefined) return { status: 'unsupported-version', carrier, version };\n try {\n data = step(data);\n } catch (cause) {\n return invalid(carrier, [issue(`Migrating from version ${String(from)} failed: ${messageOf(cause)}`)], cause);\n }\n }\n\n const { schema } = format;\n if (!isStandardSchema(schema)) {\n try {\n return { status: 'ok', value: schema(data), version, carrier };\n } catch (cause) {\n return invalid(carrier, [issue(messageOf(cause))], cause);\n }\n }\n let result: StandardSchemaResult<Value> | Promise<StandardSchemaResult<Value>>;\n try {\n result = schema['~standard'].validate(data);\n } catch (cause) {\n return invalid(carrier, [issue(`The schema threw: ${messageOf(cause)}`)], cause);\n }\n if (!isThenable(result)) return fromStandardResult(result, carrier, version);\n return Promise.resolve(result).then(\n (settled) => fromStandardResult(settled, carrier, version),\n (cause: unknown) => invalid(carrier, [issue(`The schema threw: ${messageOf(cause)}`)], cause),\n );\n}\n\n/* -------------------------------------------------------------- Reading */\n\n/**\n * Reads a clip of `format` from a paste, a drop or a clip payload: finds it in the\n * first carrier that holds one, migrates it from older versions, and validates it.\n * Never throws for clipboard content; every outcome is a {@link ClipReadResult}.\n *\n * Supports asynchronous schemas and `Blob` entries. When you need a result\n * synchronously and your schema is synchronous, use {@link readClipSync}.\n *\n * @example\n * onPaste: async (result) => {\n * const clip = await readClip(result, InvoiceRows);\n * if (clip.status === 'ok') addRows(clip.value);\n * }\n */\nexport async function readClip<Value>(source: ClipSource, format: ClipFormat<Value>): Promise<ClipReadResult<Value>> {\n assertClipFormat(format);\n let firstInvalid: ClipReadInvalid | null = null;\n for (const candidate of gather(source, format)) {\n let text: string;\n try {\n text = typeof candidate.data === 'string' ? candidate.data : await candidate.data.text();\n } catch (cause) {\n firstInvalid ??= invalid(candidate.carrier, [issue('The clipboard entry could not be read.')], cause);\n continue;\n }\n const envelope = extract(candidate, text, format);\n if (envelope === null) continue;\n if ('status' in envelope) {\n firstInvalid ??= envelope;\n continue;\n }\n return settle(envelope, candidate.carrier, format);\n }\n return firstInvalid ?? { status: 'absent' };\n}\n\n/**\n * Synchronous {@link readClip}, e.g. to decide inside a paste or drop handler.\n * `Blob` entries are skipped, and an asynchronous schema yields `invalid`.\n */\nexport function readClipSync<Value>(source: ClipSource, format: ClipFormat<Value>): ClipReadResult<Value> {\n assertClipFormat(format);\n let firstInvalid: ClipReadInvalid | null = null;\n for (const candidate of gather(source, format)) {\n if (typeof candidate.data !== 'string') continue;\n const envelope = extract(candidate, candidate.data, format);\n if (envelope === null) continue;\n if ('status' in envelope) {\n firstInvalid ??= envelope;\n continue;\n }\n const result = settle(envelope, candidate.carrier, format);\n if (!(result instanceof Promise)) return result;\n // `settle` turns rejections into results, so the discarded promise never rejects unhandled.\n return invalid(candidate.carrier, [issue('The schema validates asynchronously: use readClip().')]);\n }\n return firstInvalid ?? { status: 'absent' };\n}\n\n/**\n * The `accept` list that lets a paste or drop carry these formats: each format's\n * web custom format and clipboard type, plus HTML. Add `'text'` (or more) if you\n * also handle other content.\n *\n * @example\n * usePaste({ accept: [...clipAccept(InvoiceRows), 'text'], onPaste })\n */\nexport function clipAccept(...formats: readonly ClipFormatInfo[]): PasteAccept[] {\n const accept: PasteAccept[] = [];\n for (const format of formats) {\n assertClipFormat(format);\n accept.push(format.webMimeType as PasteAccept, format.mimeType as PasteAccept);\n }\n accept.push('html');\n return accept;\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,sBA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iB,MAAM;CACvB,IAAI,eAAuC;CAC3C,KAAK,MAAM,aAAa,OAAO,QAAQ,MAAM,GAAG;EAC9C,IAAI,OAAO,UAAU,SAAS,UAAU;EACxC,MAAM,WAAW,QAAQ,WAAW,UAAU,MAAM,MAAM;EAC1D,IAAI,aAAa,MAAM;EACvB,IAAI,YAAY,UAAU;GACxB,iBAAA,eAAiB;GACjB;EACF;EACA,MAAM,SAAS,OAAO,UAAU,UAAU,SAAS,MAAM;EACzD,IAAI,EAAE,kBAAkB,UAAU,OAAO;EAEzC,OAAO,QAAQ,UAAU,SAAS,CAAC,MAAM,sDAAsD,CAAC,CAAC;CACnG;CACA,OAAO,gBAAgB,EAAE,QAAQ,SAAS;AAC5C;;;;;;;;;AAUA,SAAgB,WAAW,GAAG,SAAmD;CAC/E,MAAM,SAAwB,CAAC;CAC/B,KAAK,MAAM,UAAU,SAAS;EAC5B,iBAAiB,MAAM;EACvB,OAAO,KAAK,OAAO,aAA4B,OAAO,QAAuB;CAC/E;CACA,OAAO,KAAK,MAAM;CAClB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"structured.cjs","names":["copyFailure","invalid","copyFailure","copyFailure","utf8ByteLength","copyFailure","normalizeClipboardType","utf8ByteLength"],"sources":["../src/structured/guard.ts","../src/structured/format.ts","../src/structured/envelope.ts","../src/structured/base64url.ts","../src/structured/write.ts","../src/structured/read.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\n/**\n * Brands formats made by `defineClipFormat`. A registered symbol (not a WeakSet),\n * so a format still passes when the module is bundled twice (ESM and CJS copies).\n */\nexport const CLIP_FORMAT_BRAND = Symbol.for('react-smart-copy.ClipFormat');\n\n/** Throws an `invalid-payload` failure unless `format` came from `defineClipFormat`. */\nexport function assertClipFormat(format: unknown): void {\n if (typeof format !== 'object' || format === null || (format as Record<symbol, unknown>)[CLIP_FORMAT_BRAND] !== true) {\n throw copyFailure('invalid-payload', 'Expected a clip format created with defineClipFormat().');\n }\n}\n","import { copyFailure } from '../core/errors';\nimport { CLIP_FORMAT_BRAND } from './guard';\nimport type { InferSchemaOutput, StandardSchemaV1 } from './standard-schema';\n\n/** A plain validator: return the typed value, or throw when `data` is not valid. */\nexport type ClipValidator<Value> = (data: unknown) => Value;\n\n/**\n * Validates pasted data. A Standard Schema (Zod, Valibot, ArkType, Effect Schema, …)\n * or a plain function that returns the value or throws.\n */\nexport type ClipSchema<Value> = StandardSchemaV1<unknown, Value> | ClipValidator<Value>;\n\n/**\n * The value a schema produces. Standard Schemas are checked first: some (ArkType)\n * are also callable, and their call signature returns errors instead of throwing.\n */\nexport type ClipSchemaValue<Schema> = Schema extends StandardSchemaV1\n ? InferSchemaOutput<Schema>\n : Schema extends (data: unknown) => infer Value\n ? Value\n : never;\n\n/** Upgrades data written by version `n` to version `n + 1`. Receives untrusted data: check before use. */\nexport type ClipMigration = (data: unknown) => unknown;\n\nexport interface ClipFormatOptions<Value> {\n /**\n * A namespaced id: lower-case words separated by dots, e.g. `'acme.invoice-rows'`.\n * It names the clipboard type (`application/vnd.acme.invoice-rows+json`), so keep it\n * stable and specific to your app; two apps sharing an id can read each other's data.\n */\n readonly id: string;\n /** The data version this app writes. Positive integer, default `1`. Bump it when the shape changes. */\n readonly version?: number;\n /**\n * Validates what is pasted, after migrations. The clipboard is untrusted input:\n * anything (another app, another tab, a malicious page) can put this format on it.\n */\n readonly schema: ClipSchema<Value>;\n /**\n * Migrations from older versions, keyed by the version they upgrade *from*:\n * `{ 1: (v1) => v2 }`. A paste from a version with no migration path is reported\n * as `unsupported-version`.\n */\n readonly migrate?: Readonly<Record<number, ClipMigration>>;\n /**\n * Turns the value into JSON-ready data. Default: the value itself. The result must\n * survive `JSON.stringify` unchanged (no Map, Set, functions, NaN or Infinity);\n * Dates become ISO strings, so validate them back with a coercing schema.\n */\n readonly encode?: (value: Value) => unknown;\n /** Plain text for other apps (editors, chat, terminals). Default: the encoded data as indented JSON. */\n readonly text?: (value: Value) => string;\n /**\n * Visible HTML for rich targets (Docs, Word, mail). Treat it like any HTML you\n * generate: escape what you interpolate. Default: the plain text.\n */\n readonly html?: (value: Value) => string;\n /** Size cap of the serialised data, in UTF-8 bytes, enforced on copy and paste. Default 8 MiB. */\n readonly maxBytes?: number;\n /**\n * Also embed the data, hidden, in the copied HTML: the carrier that works for every\n * paste path in every browser (keyboard paste, drag-and-drop, Safari, Firefox).\n * The embedded data travels wherever the HTML is pasted (a mail, a document), so\n * copy only what the user may share. Default `true`.\n */\n readonly embedInHtml?: boolean;\n}\n\n/** A validated, frozen clipboard format. Create one with {@link defineClipFormat} and share it. */\nexport interface ClipFormat<Value> {\n readonly id: string;\n readonly version: number;\n /** The clipboard type for copy and drag events, e.g. `application/vnd.acme.invoice-rows+json`. */\n readonly mimeType: string;\n /** The async Clipboard API's web custom format: `web ` + {@link mimeType}. */\n readonly webMimeType: string;\n readonly schema: ClipSchema<Value>;\n readonly migrate: Readonly<Record<number, ClipMigration>>;\n readonly encode: ((value: Value) => unknown) | undefined;\n readonly text: ((value: Value) => string) | undefined;\n readonly html: ((value: Value) => string) | undefined;\n readonly maxBytes: number;\n readonly embedInHtml: boolean;\n}\n\n/** The parts of a format that do not depend on its value type. */\nexport type ClipFormatInfo = Pick<ClipFormat<unknown>, 'id' | 'version' | 'mimeType' | 'webMimeType' | 'maxBytes'>;\n\n/** The value type of a format: `ClipValue<typeof InvoiceRows>`. */\nexport type ClipValue<Format> = Format extends ClipFormat<infer Value> ? Value : never;\n\nexport const DEFAULT_CLIP_MAX_BYTES = 8 * 1024 * 1024;\n\n/** `namespace.name`: at least two dot-separated parts of lower-case letters, digits and inner hyphens. */\nconst ID_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\\.[a-z0-9]+(?:-[a-z0-9]+)*)+$/;\nconst MAX_ID_LENGTH = 96;\n\nconst invalid = (message: string): never => {\n throw copyFailure('invalid-payload', message);\n};\n\nconst isFunction = (value: unknown): value is (...args: never[]) => unknown => typeof value === 'function';\n\n/** Checked before the function form: some Standard Schemas (ArkType) are callable but never throw. */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return false;\n const props = (value as { readonly '~standard'?: { readonly version?: unknown; readonly validate?: unknown } })['~standard'];\n return typeof props === 'object' && props.version === 1 && isFunction(props.validate);\n}\n\nfunction optionalFunction<Fn>(value: Fn | undefined, name: string): Fn | undefined {\n if (value !== undefined && !isFunction(value)) invalid(`\\`${name}\\` must be a function.`);\n return value;\n}\n\nfunction resolveMigrations(migrate: unknown, version: number): Readonly<Record<number, ClipMigration>> {\n const steps = Object.create(null) as Record<number, ClipMigration>;\n if (migrate === undefined) return Object.freeze(steps);\n if (typeof migrate !== 'object' || migrate === null) return invalid('`migrate` must be an object of functions.');\n for (const [key, step] of Object.entries(migrate)) {\n const from = Number(key);\n if (!Number.isInteger(from) || from < 1 || from >= version || String(from) !== key) {\n invalid(`\\`migrate\\` key \"${key}\" must be a version from 1 to ${String(version - 1)}.`);\n }\n if (!isFunction(step)) invalid(`\\`migrate[${key}]\\` must be a function.`);\n steps[from] = step as ClipMigration;\n }\n return Object.freeze(steps);\n}\n\n/**\n * Defines a typed clipboard format: copy it with {@link clipPayload}, read it back\n * with {@link readClip}. Define each format once, at module level, and share it\n * between the copying and the pasting code.\n *\n * Throws an `invalid-payload` `CopyFailure` when the definition is invalid.\n *\n * @example\n * const InvoiceRows = defineClipFormat({\n * id: 'acme.invoice-rows',\n * version: 2,\n * schema: z.array(Invoice),\n * migrate: { 1: (rows) => upgradeV1(rows) },\n * text: (rows) => rows.map((row) => row.id).join('\\n'),\n * });\n */\nexport function defineClipFormat<Schema extends ClipSchema<unknown>>(\n options: Omit<ClipFormatOptions<ClipSchemaValue<Schema>>, 'schema'> & { readonly schema: Schema },\n): ClipFormat<ClipSchemaValue<Schema>> {\n type Value = ClipSchemaValue<Schema>;\n const { id, schema } = options;\n if (typeof id !== 'string' || id.length > MAX_ID_LENGTH || !ID_SHAPE.test(id)) {\n invalid(`Clip format id ${JSON.stringify(id)} must look like \"namespace.name\" (lower-case, at most ${String(MAX_ID_LENGTH)} characters).`);\n }\n const version = options.version ?? 1;\n if (!Number.isSafeInteger(version) || version < 1) invalid(`\\`version\\` must be a positive integer (received ${String(version)}).`);\n if (!isStandardSchema(schema) && !isFunction(schema)) {\n invalid('`schema` must be a Standard Schema (Zod, Valibot, ArkType, …) or a validator function.');\n }\n const maxBytes = options.maxBytes ?? DEFAULT_CLIP_MAX_BYTES;\n if (maxBytes !== Infinity && !(Number.isInteger(maxBytes) && maxBytes > 0)) {\n invalid(`\\`maxBytes\\` must be a positive integer or Infinity (received ${String(maxBytes)}).`);\n }\n const mimeType = `application/vnd.${id}+json`;\n const format: ClipFormat<Value> = {\n id,\n version,\n mimeType,\n webMimeType: `web ${mimeType}`,\n // `Schema` is exactly `ClipSchema<Value>` for its own value type; TypeScript cannot follow the conditional.\n schema: schema as ClipSchema<Value>,\n migrate: resolveMigrations(options.migrate, version),\n encode: optionalFunction(options.encode, 'encode'),\n text: optionalFunction(options.text, 'text'),\n html: optionalFunction(options.html, 'html'),\n maxBytes,\n embedInHtml: options.embedInHtml ?? true,\n };\n // Non-enumerable, so a spread copy (which could be edited out of sync) is not a format.\n Object.defineProperty(format, CLIP_FORMAT_BRAND, { value: true });\n return Object.freeze(format);\n}\n","import { copyFailure } from '../core/errors';\nimport type { ClipFormatInfo } from './format';\n\n/**\n * The wire format every carrier holds: `{\"rsc\":1,\"id\":…,\"v\":…,\"data\":…}`.\n * `rsc` is the envelope spec version; unknown extra keys are ignored for forward compatibility.\n */\nexport interface ClipEnvelope {\n readonly id: string;\n readonly version: number;\n readonly data: unknown;\n}\n\nconst ENVELOPE_SPEC = 1;\n\n/** The HTML attribute holding `id;base64url(envelope)`. Exported for documentation and tests. */\nexport const CLIP_HTML_ATTRIBUTE = 'data-rsc-clip';\n\nfunction describeKey(key: string): string {\n return key === '' ? 'The data' : `\"${key}\"`;\n}\n\n/**\n * Rejects what `JSON.stringify` would silently change or drop, so the value that\n * is pasted is the value that was copied. `undefined` object properties are allowed\n * (they are simply absent, which schemas treat as optional).\n */\nfunction strictReplacer(key: string, value: unknown): unknown {\n switch (typeof value) {\n case 'number':\n if (!Number.isFinite(value)) throw new TypeError(`${describeKey(key)} is ${String(value)}, which JSON turns into null.`);\n return value;\n case 'bigint':\n throw new TypeError(`${describeKey(key)} is a BigInt, which JSON cannot represent: encode it as a string.`);\n case 'function':\n case 'symbol':\n throw new TypeError(`${describeKey(key)} is a ${typeof value}, which JSON drops.`);\n case 'object':\n if (value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) {\n throw new TypeError(`${describeKey(key)} is a ${value.constructor.name}, which JSON turns into {}: encode it as an array or object.`);\n }\n return value;\n default:\n return value;\n }\n}\n\n/** Serialises `data` into an envelope. Throws a classified `invalid-payload` failure. */\nexport function serializeEnvelope(format: ClipFormatInfo, data: unknown): string {\n let json: unknown;\n try {\n json = JSON.stringify(data, strictReplacer);\n } catch (cause) {\n const reason = cause instanceof TypeError ? cause.message : 'it could not be serialised (circular reference?).';\n throw copyFailure('invalid-payload', `Clip \"${format.id}\" data is not JSON-safe: ${reason}`, cause);\n }\n if (typeof json !== 'string') {\n throw copyFailure('invalid-payload', `Clip \"${format.id}\" data serialised to nothing (undefined, a function or a symbol).`);\n }\n // `id` matches /^[a-z0-9.-]+$/ (checked by defineClipFormat), so it needs no JSON escaping.\n return `{\"rsc\":${String(ENVELOPE_SPEC)},\"id\":\"${format.id}\",\"v\":${String(format.version)},\"data\":${json}}`;\n}\n\n/** Own `__proto__` keys are dropped while parsing, so merging pasted data can never swap a prototype. */\nfunction dropProtoKeys(key: string, value: unknown): unknown {\n return key === '__proto__' ? undefined : value;\n}\n\nconst hasOwn = (object: object, key: string): boolean => Object.prototype.hasOwnProperty.call(object, key);\n\n/** Parses and checks an envelope. Throws a `TypeError` describing what is wrong. */\nexport function parseEnvelope(text: string): ClipEnvelope {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text, dropProtoKeys);\n } catch {\n throw new TypeError('The clipboard data is not valid JSON.');\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new TypeError('The clipboard data is not a clip envelope.');\n }\n const envelope = parsed as Record<string, unknown>;\n if (envelope['rsc'] !== ENVELOPE_SPEC) throw new TypeError('The clip envelope has an unknown spec version.');\n const id = envelope['id'];\n const version = envelope['v'];\n if (typeof id !== 'string') throw new TypeError('The clip envelope has no format id.');\n if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 1) {\n throw new TypeError('The clip envelope has an invalid version.');\n }\n if (!hasOwn(envelope, 'data')) throw new TypeError('The clip envelope has no data.');\n return { id, version, data: envelope['data'] };\n}\n","/**\n * UTF-8 ⇄ base64url without padding. The alphabet (`A–Z a–z 0–9 - _`) needs no\n * escaping in HTML attributes, survives every clipboard sanitiser we target, and is\n * a closed set, so the envelope can be found with a strict token match instead of\n * parsing untrusted HTML.\n */\n\nconst CHUNK = 0x8000;\n\nexport function encodeBase64Url(text: string): string {\n const bytes = new TextEncoder().encode(text);\n let binary = '';\n for (let start = 0; start < bytes.length; start += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(start, start + CHUNK));\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nconst BASE64URL = /^[A-Za-z0-9_-]*$/;\n\n/** Decodes base64url to text. Throws on a malformed token or invalid UTF-8. */\nexport function decodeBase64Url(token: string): string {\n if (!BASE64URL.test(token) || token.length % 4 === 1) throw new TypeError('Malformed base64url token.');\n const padded = token.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (token.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n}\n\n/** Upper bound of the bytes a base64url token decodes to, without decoding it. */\nexport const decodedSize = (token: string): number => Math.floor((token.length * 3) / 4);\n","import { copyFailure } from '../core/errors';\nimport { utf8ByteLength } from '../core/paste-reader';\nimport { encodeBase64Url } from './base64url';\nimport { CLIP_HTML_ATTRIBUTE, serializeEnvelope } from './envelope';\nimport { assertClipFormat } from './guard';\nimport type { ClipFormat } from './format';\n\n/** One clipboard entry of a {@link ClipPayload}. Strings only, so it also works in copy and drag events. */\nexport interface ClipPayloadItem {\n readonly mimeType: string;\n readonly data: string;\n readonly optional?: boolean;\n}\n\n/**\n * A multi-format payload carrying a clip. Pass it to `copy()`, return it from a\n * `useCopyInterceptor` transform or a `useDragCopy` source: each path writes the\n * carriers it can.\n */\nexport interface ClipPayload {\n readonly kind: 'multi';\n readonly items: readonly ClipPayloadItem[];\n}\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' };\n\nconst escapeHtml = (text: string): string => text.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char] as string);\n\n/** Plain text as HTML: escaped, with line breaks kept (many targets drop `white-space` styles). */\nconst textToHtml = (text: string): string => escapeHtml(text).replace(/\\r\\n|\\r|\\n/g, '<br>');\n\n/**\n * Builds the payload that puts `value` on the clipboard in `format`, through three carriers:\n *\n * 1. `web application/vnd.<id>+json`: the async Clipboard API's web custom format\n * (Chromium). Read back by `navigator.clipboard.read()`, also across origins.\n * 2. `application/vnd.<id>+json`: written by copy and drag events, read back by\n * paste and drop events.\n * 3. A hidden envelope in `text/html`, which every paste path in every browser keeps.\n *\n * Plus `text/plain` (and visible HTML) for every other app. Carriers a browser\n * cannot write are skipped. {@link readClip} tries them in this order.\n *\n * Synchronous, so it can be built inside the user gesture. Throws a classified\n * `CopyFailure`: `invalid-payload` when the data is not JSON-safe, `too-large`\n * when it exceeds the format's `maxBytes`.\n */\nexport function clipPayload<Value>(format: ClipFormat<Value>, value: Value): ClipPayload {\n assertClipFormat(format);\n const data = format.encode ? format.encode(value) : value;\n const envelope = serializeEnvelope(format, data);\n if (utf8ByteLength(envelope) > format.maxBytes) {\n throw copyFailure('too-large', `Clip \"${format.id}\" data exceeds the ${String(format.maxBytes)}-byte limit.`);\n }\n\n const text: unknown = format.text ? format.text(value) : JSON.stringify(data, null, 2);\n if (typeof text !== 'string' || text.length === 0) {\n throw copyFailure('invalid-payload', `Clip \"${format.id}\": \\`text\\` must return a non-empty string.`);\n }\n const visible: unknown = format.html ? format.html(value) : textToHtml(text);\n if (typeof visible !== 'string') {\n throw copyFailure('invalid-payload', `Clip \"${format.id}\": \\`html\\` must return a string.`);\n }\n\n const items: ClipPayloadItem[] = [\n { mimeType: format.webMimeType, data: envelope, optional: true },\n { mimeType: format.mimeType, data: envelope, optional: true },\n ];\n const html = format.embedInHtml\n ? `<span ${CLIP_HTML_ATTRIBUTE}=\"${format.id};${encodeBase64Url(envelope)}\"></span>${visible}`\n : visible;\n if (html.length > 0) items.push({ mimeType: 'text/html', data: html });\n items.push({ mimeType: 'text/plain', data: text });\n return { kind: 'multi', items };\n}\n","import { normalizeClipboardType } from '../core/mime';\nimport type { PasteAccept } from '../core/paste-reader';\nimport { utf8ByteLength } from '../core/paste-reader';\nimport { decodeBase64Url, decodedSize } from './base64url';\nimport { parseEnvelope, type ClipEnvelope } from './envelope';\nimport { isStandardSchema, type ClipFormat, type ClipFormatInfo } from './format';\nimport { assertClipFormat } from './guard';\nimport type { StandardSchemaResult } from './standard-schema';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Which carrier the clip was read from, most to least specific. */\nexport type ClipCarrier = 'web' | 'custom' | 'html';\n\nexport interface ClipIssue {\n readonly message: string;\n /** Where in the data the problem is; empty for the data as a whole. */\n readonly path: readonly PropertyKey[];\n}\n\nexport interface ClipReadOk<Value> {\n readonly status: 'ok';\n /** The validated (and, if needed, migrated) value. */\n readonly value: Value;\n /** The version the data was written with; lower than the format's when it was migrated. */\n readonly version: number;\n readonly carrier: ClipCarrier;\n}\n\n/** The source holds no data in this format. */\nexport interface ClipReadAbsent {\n readonly status: 'absent';\n}\n\n/** Data in this format was found but is malformed, too large, failed a migration or failed the schema. */\nexport interface ClipReadInvalid {\n readonly status: 'invalid';\n readonly carrier: ClipCarrier;\n readonly issues: readonly ClipIssue[];\n /** What a migration or validator threw, if anything. */\n readonly cause?: unknown;\n}\n\n/** Written by a newer version of the app, or by an older one with no migration path. */\nexport interface ClipReadUnsupportedVersion {\n readonly status: 'unsupported-version';\n readonly carrier: ClipCarrier;\n readonly version: number;\n}\n\nexport type ClipReadResult<Value> = ClipReadOk<Value> | ClipReadAbsent | ClipReadInvalid | ClipReadUnsupportedVersion;\n\n/** An entry of a paste result (`type`) or of a clip payload (`mimeType`). */\nexport type ClipSourceItem =\n | { readonly type: string; readonly data: string | Blob }\n | { readonly mimeType: string; readonly data: string | Blob };\n\n/** The `DataTransfer` of a paste or drop event you handle yourself. */\nexport interface ClipDataTransfer {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n}\n\n/**\n * Where to read a clip from: a `PasteResult` (from `usePaste`, `PasteField` or a\n * paste adapter), a {@link ClipPayload} (round-trips, tests, in-app duplication), or\n * a raw `DataTransfer`.\n */\nexport type ClipSource = { readonly items: readonly ClipSourceItem[] } | ClipDataTransfer;\n\n/* -------------------------------------------------------------- Helpers */\n\ninterface Candidate {\n readonly carrier: ClipCarrier;\n readonly data: string | Blob;\n}\n\nconst CARRIERS: readonly ClipCarrier[] = ['web', 'custom', 'html'];\n\n/** Envelope tokens are scanned for at most this many times per HTML string. */\nconst MAX_HTML_TOKENS = 64;\n\nconst messageOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));\n\nconst isTransfer = (source: ClipSource): source is ClipDataTransfer =>\n typeof (source as Partial<ClipDataTransfer>).getData === 'function';\n\nconst issue = (message: string): ClipIssue => ({ message, path: [] });\n\nfunction invalid(carrier: ClipCarrier, issues: readonly ClipIssue[], cause?: unknown): ClipReadInvalid {\n return cause === undefined ? { status: 'invalid', carrier, issues } : { status: 'invalid', carrier, issues, cause };\n}\n\n/** The candidate entries in carrier order. Reads `DataTransfer` data only for types that match. */\nfunction gather(source: ClipSource, format: ClipFormatInfo): Candidate[] {\n const found = new Map<ClipCarrier, string | Blob>();\n const consider = (raw: string, read: () => string | Blob): void => {\n const type = normalizeClipboardType(raw);\n const carrier: ClipCarrier | null =\n type === format.webMimeType ? 'web' : type === format.mimeType ? 'custom' : type === 'text/html' ? 'html' : null;\n if (carrier !== null && !found.has(carrier)) found.set(carrier, read());\n };\n if (isTransfer(source)) {\n for (const type of Array.from(source.types)) consider(type, () => source.getData(type));\n } else {\n for (const item of source.items) consider('type' in item ? item.type : item.mimeType, () => item.data);\n }\n const candidates: Candidate[] = [];\n for (const carrier of CARRIERS) {\n const data = found.get(carrier);\n if (data !== undefined) candidates.push({ carrier, data });\n }\n return candidates;\n}\n\nfunction findHtmlToken(html: string, id: string): string | null {\n // The token alphabet is closed (id: [a-z0-9.-], data: base64url), so a strict match is exact:\n // no HTML parsing, no DOM, linear time. Quotes may be single or double.\n const pattern = /data-rsc-clip\\s*=\\s*([\"'])([a-z0-9.-]{1,96});([A-Za-z0-9_-]*)\\1/g;\n for (let scanned = 0; scanned < MAX_HTML_TOKENS; scanned += 1) {\n const match = pattern.exec(html);\n if (match === null) return null;\n if (match[2] === id) return match[3] as string;\n }\n return null;\n}\n\n/** The envelope a carrier holds, `null` when it holds none for this format, or why it is unusable. */\nfunction extract(candidate: Candidate, text: string, format: ClipFormatInfo): ClipEnvelope | ClipReadInvalid | null {\n const { carrier } = candidate;\n const tooLarge = (): ClipReadInvalid =>\n invalid(carrier, [issue(`The clip exceeds the ${String(format.maxBytes)}-byte limit.`)]);\n let json = text;\n if (carrier === 'html') {\n const token = findHtmlToken(text, format.id);\n if (token === null) return null;\n if (decodedSize(token) > format.maxBytes) return tooLarge();\n try {\n json = decodeBase64Url(token);\n } catch (cause) {\n return invalid(carrier, [issue('The clip embedded in the HTML is corrupted.')], cause);\n }\n } else if (utf8ByteLength(text) > format.maxBytes) {\n return tooLarge();\n }\n let envelope: ClipEnvelope;\n try {\n envelope = parseEnvelope(json);\n } catch (cause) {\n return invalid(carrier, [issue(messageOf(cause))], cause);\n }\n if (envelope.id !== format.id) {\n return invalid(carrier, [issue(`The clipboard holds \"${envelope.id}\" data under the \"${format.id}\" type.`)]);\n }\n return envelope;\n}\n\nfunction fromStandardResult<Value>(\n result: StandardSchemaResult<Value>,\n carrier: ClipCarrier,\n version: number,\n): ClipReadResult<Value> {\n if (typeof (result as unknown) !== 'object' || (result as unknown) === null) {\n return invalid(carrier, [issue('The schema returned a malformed result.')]);\n }\n if (result.issues !== undefined) {\n // Schemas are third-party code: read their issues defensively, never throw.\n const raw: unknown = result.issues;\n const issues = Array.from(Array.isArray(raw) ? (raw as unknown[]) : [], (item): ClipIssue => {\n const entry = (typeof item === 'object' && item !== null ? item : {}) as { message?: unknown; path?: unknown };\n // Array.from, not .map: some libraries' paths are Array subclasses, and the result must be a plain array.\n const path = Array.isArray(entry.path)\n ? Array.from(entry.path as unknown[], (segment) =>\n typeof segment === 'object' && segment !== null ? (segment as { key: PropertyKey }).key : (segment as PropertyKey),\n )\n : [];\n return { message: typeof entry.message === 'string' ? entry.message : 'Invalid value.', path };\n });\n return invalid(carrier, issues.length > 0 ? issues : [issue('The schema rejected the data.')]);\n }\n return { status: 'ok', value: result.value, version, carrier };\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n}\n\n/** Migrates and validates an envelope. Returns a promise only when the schema validates asynchronously. */\nfunction settle<Value>(\n envelope: ClipEnvelope,\n carrier: ClipCarrier,\n format: ClipFormat<Value>,\n): ClipReadResult<Value> | Promise<ClipReadResult<Value>> {\n const { version } = envelope;\n if (version > format.version) return { status: 'unsupported-version', carrier, version };\n\n let data = envelope.data;\n for (let from = version; from < format.version; from += 1) {\n const step = format.migrate[from];\n if (step === undefined) return { status: 'unsupported-version', carrier, version };\n try {\n data = step(data);\n } catch (cause) {\n return invalid(carrier, [issue(`Migrating from version ${String(from)} failed: ${messageOf(cause)}`)], cause);\n }\n }\n\n const { schema } = format;\n if (!isStandardSchema(schema)) {\n try {\n return { status: 'ok', value: schema(data), version, carrier };\n } catch (cause) {\n return invalid(carrier, [issue(messageOf(cause))], cause);\n }\n }\n let result: StandardSchemaResult<Value> | Promise<StandardSchemaResult<Value>>;\n try {\n result = schema['~standard'].validate(data);\n } catch (cause) {\n return invalid(carrier, [issue(`The schema threw: ${messageOf(cause)}`)], cause);\n }\n if (!isThenable(result)) return fromStandardResult(result, carrier, version);\n return Promise.resolve(result).then(\n (settled) => fromStandardResult(settled, carrier, version),\n (cause: unknown) => invalid(carrier, [issue(`The schema threw: ${messageOf(cause)}`)], cause),\n );\n}\n\n/* -------------------------------------------------------------- Reading */\n\n/**\n * Reads a clip of `format` from a paste, a drop or a clip payload: finds it in the\n * first carrier that holds one, migrates it from older versions, and validates it.\n * Never throws for clipboard content; every outcome is a {@link ClipReadResult}.\n *\n * Supports asynchronous schemas and `Blob` entries. When you need a result\n * synchronously and your schema is synchronous, use {@link readClipSync}.\n *\n * @example\n * onPaste: async (result) => {\n * const clip = await readClip(result, InvoiceRows);\n * if (clip.status === 'ok') addRows(clip.value);\n * }\n */\nexport async function readClip<Value>(source: ClipSource, format: ClipFormat<Value>): Promise<ClipReadResult<Value>> {\n assertClipFormat(format);\n let firstInvalid: ClipReadInvalid | null = null;\n for (const candidate of gather(source, format)) {\n let text: string;\n try {\n text = typeof candidate.data === 'string' ? candidate.data : await candidate.data.text();\n } catch (cause) {\n firstInvalid ??= invalid(candidate.carrier, [issue('The clipboard entry could not be read.')], cause);\n continue;\n }\n const envelope = extract(candidate, text, format);\n if (envelope === null) continue;\n if ('status' in envelope) {\n firstInvalid ??= envelope;\n continue;\n }\n return settle(envelope, candidate.carrier, format);\n }\n return firstInvalid ?? { status: 'absent' };\n}\n\n/**\n * Synchronous {@link readClip}, e.g. to decide inside a paste or drop handler.\n * `Blob` entries are skipped, and an asynchronous schema yields `invalid`.\n */\nexport function readClipSync<Value>(source: ClipSource, format: ClipFormat<Value>): ClipReadResult<Value> {\n assertClipFormat(format);\n let firstInvalid: ClipReadInvalid | null = null;\n for (const candidate of gather(source, format)) {\n if (typeof candidate.data !== 'string') continue;\n const envelope = extract(candidate, candidate.data, format);\n if (envelope === null) continue;\n if ('status' in envelope) {\n firstInvalid ??= envelope;\n continue;\n }\n const result = settle(envelope, candidate.carrier, format);\n if (!(result instanceof Promise)) return result;\n // `settle` turns rejections into results, so the discarded promise never rejects unhandled.\n return invalid(candidate.carrier, [issue('The schema validates asynchronously: use readClip().')]);\n }\n return firstInvalid ?? { status: 'absent' };\n}\n\n/**\n * The `accept` list that lets a paste or drop carry these formats: each format's\n * web custom format and clipboard type, plus HTML. Add `'text'` (or more) if you\n * also handle other content.\n *\n * @example\n * usePaste({ accept: [...clipAccept(InvoiceRows), 'text'], onPaste })\n */\nexport function clipAccept(...formats: readonly ClipFormatInfo[]): PasteAccept[] {\n const accept: PasteAccept[] = [];\n for (const format of formats) {\n assertClipFormat(format);\n accept.push(format.webMimeType as PasteAccept, format.mimeType as PasteAccept);\n }\n accept.push('html');\n return accept;\n}\n"],"mappings":";;;;;;;;;;AAKA,MAAa,oBAAoB,OAAO,IAAI,6BAA6B;;AAGzE,SAAgB,iBAAiB,QAAuB;CACtD,IAAI,OAAO,WAAW,YAAY,WAAW,QAAS,OAAmC,uBAAuB,MAC9G,MAAMA,eAAAA,YAAY,mBAAmB,yDAAyD;AAElG;;;ACiFA,MAAa,yBAAyB;;AAGtC,MAAM,WAAW;AACjB,MAAM,gBAAgB;AAEtB,MAAMC,aAAW,YAA2B;CAC1C,MAAMC,eAAAA,YAAY,mBAAmB,OAAO;AAC9C;AAEA,MAAM,cAAc,UAA2D,OAAO,UAAU;;AAGhG,SAAgB,iBAAiB,OAA2C;CAC1E,IAAK,OAAO,UAAU,YAAY,OAAO,UAAU,cAAe,UAAU,MAAM,OAAO;CACzF,MAAM,QAAS,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;;;;;;;AAUA,SAAgB,WAAW,GAAG,SAAmD;CAC/E,MAAM,SAAwB,CAAC;CAC/B,KAAK,MAAM,UAAU,SAAS;EAC5B,iBAAiB,MAAM;EACvB,OAAO,KAAK,OAAO,aAA4B,OAAO,QAAuB;CAC/E;CACA,OAAO,KAAK,MAAM;CAClB,OAAO;AACT"}
|
package/dist/structured.d.cts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
|
|
2
|
+
import { s as PasteAccept } from "./chunks/paste-reader-DcXnRWQr.cjs";
|
|
1
3
|
//#region src/structured/standard-schema.d.ts
|
|
2
4
|
/**
|
|
3
5
|
* The Standard Schema v1 interface (https://standardschema.dev), inlined so the
|
|
@@ -172,17 +174,6 @@ interface ClipPayload {
|
|
|
172
174
|
*/
|
|
173
175
|
export declare function clipPayload<Value>(format: ClipFormat<Value>, value: Value): ClipPayload;
|
|
174
176
|
//#endregion
|
|
175
|
-
//#region src/core/paste-reader.d.ts
|
|
176
|
-
/** Friendly names for the common cases. */
|
|
177
|
-
type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
|
|
178
|
-
/**
|
|
179
|
-
* What a paste may contain, in any order: a shorthand, an exact MIME type
|
|
180
|
-
* (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a
|
|
181
|
-
* wildcard (`'image/*'`, `'*\/*'`). `image/svg+xml` (scriptable XML), web custom
|
|
182
|
-
* formats and `+json` types are only accepted when listed exactly.
|
|
183
|
-
*/
|
|
184
|
-
type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
|
|
185
|
-
//#endregion
|
|
186
177
|
//#region src/structured/read.d.ts
|
|
187
178
|
/** Which carrier the clip was read from, most to least specific. */
|
|
188
179
|
type ClipCarrier = 'web' | 'custom' | 'html';
|
package/dist/structured.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
|
|
2
|
+
import { s as PasteAccept } from "./chunks/paste-reader-DcXnRWQr.js";
|
|
1
3
|
//#region src/structured/standard-schema.d.ts
|
|
2
4
|
/**
|
|
3
5
|
* The Standard Schema v1 interface (https://standardschema.dev), inlined so the
|
|
@@ -172,17 +174,6 @@ interface ClipPayload {
|
|
|
172
174
|
*/
|
|
173
175
|
export declare function clipPayload<Value>(format: ClipFormat<Value>, value: Value): ClipPayload;
|
|
174
176
|
//#endregion
|
|
175
|
-
//#region src/core/paste-reader.d.ts
|
|
176
|
-
/** Friendly names for the common cases. */
|
|
177
|
-
type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';
|
|
178
|
-
/**
|
|
179
|
-
* What a paste may contain, in any order: a shorthand, an exact MIME type
|
|
180
|
-
* (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a
|
|
181
|
-
* wildcard (`'image/*'`, `'*\/*'`). `image/svg+xml` (scriptable XML), web custom
|
|
182
|
-
* formats and `+json` types are only accepted when listed exactly.
|
|
183
|
-
*/
|
|
184
|
-
type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;
|
|
185
|
-
//#endregion
|
|
186
177
|
//#region src/structured/read.d.ts
|
|
187
178
|
/** Which carrier the clip was read from, most to least specific. */
|
|
188
179
|
type ClipCarrier = 'web' | 'custom' | 'html';
|
package/dist/structured.js
CHANGED
|
@@ -1,33 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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
|
-
/** Shorthand for throwing a classified failure. */
|
|
27
|
-
function copyFailure(type, message, cause) {
|
|
28
|
-
return new CopyFailure(createCopyError(type, message, cause));
|
|
29
|
-
}
|
|
30
|
-
//#endregion
|
|
1
|
+
|
|
2
|
+
import { n as copyFailure } from "./chunks/errors-9h8sdFFX.js";
|
|
3
|
+
import { o as normalizeClipboardType } from "./chunks/mime-aa-HA2dm.js";
|
|
4
|
+
import { d as utf8ByteLength } from "./chunks/paste-reader-D9i7yMXF.js";
|
|
31
5
|
//#region src/structured/guard.ts
|
|
32
6
|
/**
|
|
33
7
|
* Brands formats made by `defineClipFormat`. A registered symbol (not a WeakSet),
|
|
@@ -178,62 +152,6 @@ function parseEnvelope(text) {
|
|
|
178
152
|
};
|
|
179
153
|
}
|
|
180
154
|
//#endregion
|
|
181
|
-
//#region src/core/mime.ts
|
|
182
|
-
/**
|
|
183
|
-
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
184
|
-
* clipboard is untrusted input, so types are normalised and validated before
|
|
185
|
-
* they are compared, and image types are confirmed from the bytes themselves.
|
|
186
|
-
*/
|
|
187
|
-
/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
|
|
188
|
-
const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
189
|
-
/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
|
|
190
|
-
function normalizeMimeType(value) {
|
|
191
|
-
const separator = value.indexOf(";");
|
|
192
|
-
const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
|
|
193
|
-
return MIME_SHAPE.test(base) ? base : null;
|
|
194
|
-
}
|
|
195
|
-
/** Prefix of the async Clipboard API's web custom formats (`web application/vnd.acme+json`). */
|
|
196
|
-
const WEB_CUSTOM_FORMAT_PREFIX = "web ";
|
|
197
|
-
/** Whether a clipboard type is a web custom format (`web type/subtype`). */
|
|
198
|
-
function isWebCustomFormat(type) {
|
|
199
|
-
return type.slice(0, 4).toLowerCase() === WEB_CUSTOM_FORMAT_PREFIX;
|
|
200
|
-
}
|
|
201
|
-
/**
|
|
202
|
-
* Like {@link normalizeMimeType}, but also accepts web custom formats
|
|
203
|
-
* (`web type/subtype`), returned as `web ` + the normalised MIME type.
|
|
204
|
-
*/
|
|
205
|
-
function normalizeClipboardType(value) {
|
|
206
|
-
if (!isWebCustomFormat(value)) return normalizeMimeType(value);
|
|
207
|
-
const inner = normalizeMimeType(value.slice(4));
|
|
208
|
-
return inner === null ? null : WEB_CUSTOM_FORMAT_PREFIX + inner;
|
|
209
|
-
}
|
|
210
|
-
const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
|
|
211
|
-
ascii("GIF8");
|
|
212
|
-
ascii("RIFF");
|
|
213
|
-
ascii("WEBP");
|
|
214
|
-
ascii("BM");
|
|
215
|
-
ascii("ftypavif");
|
|
216
|
-
ascii("ftypavis");
|
|
217
|
-
//#endregion
|
|
218
|
-
//#region src/core/paste-reader.ts
|
|
219
|
-
/**
|
|
220
|
-
* UTF-8 byte length of a string, without allocating an encoded copy.
|
|
221
|
-
* Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.
|
|
222
|
-
*/
|
|
223
|
-
function utf8ByteLength(text) {
|
|
224
|
-
let bytes = 0;
|
|
225
|
-
for (let i = 0; i < text.length; i += 1) {
|
|
226
|
-
const unit = text.charCodeAt(i);
|
|
227
|
-
if (unit < 128) bytes += 1;
|
|
228
|
-
else if (unit < 2048) bytes += 2;
|
|
229
|
-
else if (unit >= 55296 && unit <= 56319 && i + 1 < text.length && (text.charCodeAt(i + 1) & 64512) === 56320) {
|
|
230
|
-
bytes += 4;
|
|
231
|
-
i += 1;
|
|
232
|
-
} else bytes += 3;
|
|
233
|
-
}
|
|
234
|
-
return bytes;
|
|
235
|
-
}
|
|
236
|
-
//#endregion
|
|
237
155
|
//#region src/structured/base64url.ts
|
|
238
156
|
/**
|
|
239
157
|
* UTF-8 ⇄ base64url without padding. The alphabet (`A–Z a–z 0–9 - _`) needs no
|