react-smart-copy 1.9.0 → 1.11.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.
@@ -0,0 +1,545 @@
1
+ //#region src/core/errors.ts
2
+ function createCopyError(type, message, cause) {
3
+ return cause === void 0 ? {
4
+ type,
5
+ message
6
+ } : {
7
+ type,
8
+ message,
9
+ cause
10
+ };
11
+ }
12
+ /**
13
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
14
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
15
+ */
16
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
17
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
18
+ var CopyFailure = class extends Error {
19
+ constructor(copyError) {
20
+ super(copyError.message);
21
+ this[COPY_FAILURE_BRAND] = true;
22
+ this.name = "CopyFailure";
23
+ this.copyError = copyError;
24
+ }
25
+ };
26
+ /** Shorthand for throwing a classified failure. */
27
+ function copyFailure(type, message, cause) {
28
+ return new CopyFailure(createCopyError(type, message, cause));
29
+ }
30
+ //#endregion
31
+ //#region src/structured/guard.ts
32
+ /**
33
+ * Brands formats made by `defineClipFormat`. A registered symbol (not a WeakSet),
34
+ * so a format still passes when the module is bundled twice (ESM and CJS copies).
35
+ */
36
+ const CLIP_FORMAT_BRAND = Symbol.for("react-smart-copy.ClipFormat");
37
+ /** Throws an `invalid-payload` failure unless `format` came from `defineClipFormat`. */
38
+ function assertClipFormat(format) {
39
+ if (typeof format !== "object" || format === null || format[CLIP_FORMAT_BRAND] !== true) throw copyFailure("invalid-payload", "Expected a clip format created with defineClipFormat().");
40
+ }
41
+ //#endregion
42
+ //#region src/structured/format.ts
43
+ const DEFAULT_CLIP_MAX_BYTES = 8388608;
44
+ /** `namespace.name`: at least two dot-separated parts of lower-case letters, digits and inner hyphens. */
45
+ const ID_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)+$/;
46
+ const MAX_ID_LENGTH = 96;
47
+ const invalid$1 = (message) => {
48
+ throw copyFailure("invalid-payload", message);
49
+ };
50
+ const isFunction = (value) => typeof value === "function";
51
+ /** Checked before the function form: some Standard Schemas (ArkType) are callable but never throw. */
52
+ function isStandardSchema(value) {
53
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
54
+ const props = value["~standard"];
55
+ return typeof props === "object" && props.version === 1 && isFunction(props.validate);
56
+ }
57
+ function optionalFunction(value, name) {
58
+ if (value !== void 0 && !isFunction(value)) invalid$1(`\`${name}\` must be a function.`);
59
+ return value;
60
+ }
61
+ function resolveMigrations(migrate, version) {
62
+ const steps = Object.create(null);
63
+ if (migrate === void 0) return Object.freeze(steps);
64
+ if (typeof migrate !== "object" || migrate === null) return invalid$1("`migrate` must be an object of functions.");
65
+ for (const [key, step] of Object.entries(migrate)) {
66
+ const from = Number(key);
67
+ if (!Number.isInteger(from) || from < 1 || from >= version || String(from) !== key) invalid$1(`\`migrate\` key "${key}" must be a version from 1 to ${String(version - 1)}.`);
68
+ if (!isFunction(step)) invalid$1(`\`migrate[${key}]\` must be a function.`);
69
+ steps[from] = step;
70
+ }
71
+ return Object.freeze(steps);
72
+ }
73
+ /**
74
+ * Defines a typed clipboard format: copy it with {@link clipPayload}, read it back
75
+ * with {@link readClip}. Define each format once, at module level, and share it
76
+ * between the copying and the pasting code.
77
+ *
78
+ * Throws an `invalid-payload` `CopyFailure` when the definition is invalid.
79
+ *
80
+ * @example
81
+ * const InvoiceRows = defineClipFormat({
82
+ * id: 'acme.invoice-rows',
83
+ * version: 2,
84
+ * schema: z.array(Invoice),
85
+ * migrate: { 1: (rows) => upgradeV1(rows) },
86
+ * text: (rows) => rows.map((row) => row.id).join('\n'),
87
+ * });
88
+ */
89
+ function defineClipFormat(options) {
90
+ const { id, schema } = options;
91
+ if (typeof id !== "string" || id.length > MAX_ID_LENGTH || !ID_SHAPE.test(id)) invalid$1(`Clip format id ${JSON.stringify(id)} must look like "namespace.name" (lower-case, at most ${String(MAX_ID_LENGTH)} characters).`);
92
+ const version = options.version ?? 1;
93
+ if (!Number.isSafeInteger(version) || version < 1) invalid$1(`\`version\` must be a positive integer (received ${String(version)}).`);
94
+ if (!isStandardSchema(schema) && !isFunction(schema)) invalid$1("`schema` must be a Standard Schema (Zod, Valibot, ArkType, …) or a validator function.");
95
+ const maxBytes = options.maxBytes ?? 8388608;
96
+ if (maxBytes !== Infinity && !(Number.isInteger(maxBytes) && maxBytes > 0)) invalid$1(`\`maxBytes\` must be a positive integer or Infinity (received ${String(maxBytes)}).`);
97
+ const mimeType = `application/vnd.${id}+json`;
98
+ const format = {
99
+ id,
100
+ version,
101
+ mimeType,
102
+ webMimeType: `web ${mimeType}`,
103
+ schema,
104
+ migrate: resolveMigrations(options.migrate, version),
105
+ encode: optionalFunction(options.encode, "encode"),
106
+ text: optionalFunction(options.text, "text"),
107
+ html: optionalFunction(options.html, "html"),
108
+ maxBytes,
109
+ embedInHtml: options.embedInHtml ?? true
110
+ };
111
+ Object.defineProperty(format, CLIP_FORMAT_BRAND, { value: true });
112
+ return Object.freeze(format);
113
+ }
114
+ //#endregion
115
+ //#region src/structured/envelope.ts
116
+ const ENVELOPE_SPEC = 1;
117
+ /** The HTML attribute holding `id;base64url(envelope)`. Exported for documentation and tests. */
118
+ const CLIP_HTML_ATTRIBUTE = "data-rsc-clip";
119
+ function describeKey(key) {
120
+ return key === "" ? "The data" : `"${key}"`;
121
+ }
122
+ /**
123
+ * Rejects what `JSON.stringify` would silently change or drop, so the value that
124
+ * is pasted is the value that was copied. `undefined` object properties are allowed
125
+ * (they are simply absent, which schemas treat as optional).
126
+ */
127
+ function strictReplacer(key, value) {
128
+ switch (typeof value) {
129
+ case "number":
130
+ if (!Number.isFinite(value)) throw new TypeError(`${describeKey(key)} is ${String(value)}, which JSON turns into null.`);
131
+ return value;
132
+ case "bigint": throw new TypeError(`${describeKey(key)} is a BigInt, which JSON cannot represent: encode it as a string.`);
133
+ case "function":
134
+ case "symbol": throw new TypeError(`${describeKey(key)} is a ${typeof value}, which JSON drops.`);
135
+ case "object":
136
+ if (value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) throw new TypeError(`${describeKey(key)} is a ${value.constructor.name}, which JSON turns into {}: encode it as an array or object.`);
137
+ return value;
138
+ default: return value;
139
+ }
140
+ }
141
+ /** Serialises `data` into an envelope. Throws a classified `invalid-payload` failure. */
142
+ function serializeEnvelope(format, data) {
143
+ let json;
144
+ try {
145
+ json = JSON.stringify(data, strictReplacer);
146
+ } catch (cause) {
147
+ const reason = cause instanceof TypeError ? cause.message : "it could not be serialised (circular reference?).";
148
+ throw copyFailure("invalid-payload", `Clip "${format.id}" data is not JSON-safe: ${reason}`, cause);
149
+ }
150
+ if (typeof json !== "string") throw copyFailure("invalid-payload", `Clip "${format.id}" data serialised to nothing (undefined, a function or a symbol).`);
151
+ return `{"rsc":${String(ENVELOPE_SPEC)},"id":"${format.id}","v":${String(format.version)},"data":${json}}`;
152
+ }
153
+ /** Own `__proto__` keys are dropped while parsing, so merging pasted data can never swap a prototype. */
154
+ function dropProtoKeys(key, value) {
155
+ return key === "__proto__" ? void 0 : value;
156
+ }
157
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
158
+ /** Parses and checks an envelope. Throws a `TypeError` describing what is wrong. */
159
+ function parseEnvelope(text) {
160
+ let parsed;
161
+ try {
162
+ parsed = JSON.parse(text, dropProtoKeys);
163
+ } catch {
164
+ throw new TypeError("The clipboard data is not valid JSON.");
165
+ }
166
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new TypeError("The clipboard data is not a clip envelope.");
167
+ const envelope = parsed;
168
+ if (envelope["rsc"] !== ENVELOPE_SPEC) throw new TypeError("The clip envelope has an unknown spec version.");
169
+ const id = envelope["id"];
170
+ const version = envelope["v"];
171
+ if (typeof id !== "string") throw new TypeError("The clip envelope has no format id.");
172
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 1) throw new TypeError("The clip envelope has an invalid version.");
173
+ if (!hasOwn(envelope, "data")) throw new TypeError("The clip envelope has no data.");
174
+ return {
175
+ id,
176
+ version,
177
+ data: envelope["data"]
178
+ };
179
+ }
180
+ //#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
+ //#region src/structured/base64url.ts
238
+ /**
239
+ * UTF-8 ⇄ base64url without padding. The alphabet (`A–Z a–z 0–9 - _`) needs no
240
+ * escaping in HTML attributes, survives every clipboard sanitiser we target, and is
241
+ * a closed set, so the envelope can be found with a strict token match instead of
242
+ * parsing untrusted HTML.
243
+ */
244
+ const CHUNK = 32768;
245
+ function encodeBase64Url(text) {
246
+ const bytes = new TextEncoder().encode(text);
247
+ let binary = "";
248
+ for (let start = 0; start < bytes.length; start += CHUNK) binary += String.fromCharCode(...bytes.subarray(start, start + CHUNK));
249
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
250
+ }
251
+ const BASE64URL = /^[A-Za-z0-9_-]*$/;
252
+ /** Decodes base64url to text. Throws on a malformed token or invalid UTF-8. */
253
+ function decodeBase64Url(token) {
254
+ if (!BASE64URL.test(token) || token.length % 4 === 1) throw new TypeError("Malformed base64url token.");
255
+ const padded = token.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - token.length % 4) % 4);
256
+ const binary = atob(padded);
257
+ const bytes = new Uint8Array(binary.length);
258
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
259
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
260
+ }
261
+ /** Upper bound of the bytes a base64url token decodes to, without decoding it. */
262
+ const decodedSize = (token) => Math.floor(token.length * 3 / 4);
263
+ //#endregion
264
+ //#region src/structured/write.ts
265
+ const HTML_ESCAPES = {
266
+ "&": "&amp;",
267
+ "<": "&lt;",
268
+ ">": "&gt;",
269
+ "\"": "&quot;",
270
+ "'": "&#39;"
271
+ };
272
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]);
273
+ /** Plain text as HTML: escaped, with line breaks kept (many targets drop `white-space` styles). */
274
+ const textToHtml = (text) => escapeHtml(text).replace(/\r\n|\r|\n/g, "<br>");
275
+ /**
276
+ * Builds the payload that puts `value` on the clipboard in `format`, through three carriers:
277
+ *
278
+ * 1. `web application/vnd.<id>+json`: the async Clipboard API's web custom format
279
+ * (Chromium). Read back by `navigator.clipboard.read()`, also across origins.
280
+ * 2. `application/vnd.<id>+json`: written by copy and drag events, read back by
281
+ * paste and drop events.
282
+ * 3. A hidden envelope in `text/html`, which every paste path in every browser keeps.
283
+ *
284
+ * Plus `text/plain` (and visible HTML) for every other app. Carriers a browser
285
+ * cannot write are skipped. {@link readClip} tries them in this order.
286
+ *
287
+ * Synchronous, so it can be built inside the user gesture. Throws a classified
288
+ * `CopyFailure`: `invalid-payload` when the data is not JSON-safe, `too-large`
289
+ * when it exceeds the format's `maxBytes`.
290
+ */
291
+ function clipPayload(format, value) {
292
+ assertClipFormat(format);
293
+ const data = format.encode ? format.encode(value) : value;
294
+ const envelope = serializeEnvelope(format, data);
295
+ if (utf8ByteLength(envelope) > format.maxBytes) throw copyFailure("too-large", `Clip "${format.id}" data exceeds the ${String(format.maxBytes)}-byte limit.`);
296
+ const text = format.text ? format.text(value) : JSON.stringify(data, null, 2);
297
+ if (typeof text !== "string" || text.length === 0) throw copyFailure("invalid-payload", `Clip "${format.id}": \`text\` must return a non-empty string.`);
298
+ const visible = format.html ? format.html(value) : textToHtml(text);
299
+ if (typeof visible !== "string") throw copyFailure("invalid-payload", `Clip "${format.id}": \`html\` must return a string.`);
300
+ const items = [{
301
+ mimeType: format.webMimeType,
302
+ data: envelope,
303
+ optional: true
304
+ }, {
305
+ mimeType: format.mimeType,
306
+ data: envelope,
307
+ optional: true
308
+ }];
309
+ const html = format.embedInHtml ? `<span ${CLIP_HTML_ATTRIBUTE}="${format.id};${encodeBase64Url(envelope)}"></span>${visible}` : visible;
310
+ if (html.length > 0) items.push({
311
+ mimeType: "text/html",
312
+ data: html
313
+ });
314
+ items.push({
315
+ mimeType: "text/plain",
316
+ data: text
317
+ });
318
+ return {
319
+ kind: "multi",
320
+ items
321
+ };
322
+ }
323
+ //#endregion
324
+ //#region src/structured/read.ts
325
+ const CARRIERS = [
326
+ "web",
327
+ "custom",
328
+ "html"
329
+ ];
330
+ /** Envelope tokens are scanned for at most this many times per HTML string. */
331
+ const MAX_HTML_TOKENS = 64;
332
+ const messageOf = (cause) => cause instanceof Error ? cause.message : String(cause);
333
+ const isTransfer = (source) => typeof source.getData === "function";
334
+ const issue = (message) => ({
335
+ message,
336
+ path: []
337
+ });
338
+ function invalid(carrier, issues, cause) {
339
+ return cause === void 0 ? {
340
+ status: "invalid",
341
+ carrier,
342
+ issues
343
+ } : {
344
+ status: "invalid",
345
+ carrier,
346
+ issues,
347
+ cause
348
+ };
349
+ }
350
+ /** The candidate entries in carrier order. Reads `DataTransfer` data only for types that match. */
351
+ function gather(source, format) {
352
+ const found = /* @__PURE__ */ new Map();
353
+ const consider = (raw, read) => {
354
+ const type = normalizeClipboardType(raw);
355
+ const carrier = type === format.webMimeType ? "web" : type === format.mimeType ? "custom" : type === "text/html" ? "html" : null;
356
+ if (carrier !== null && !found.has(carrier)) found.set(carrier, read());
357
+ };
358
+ if (isTransfer(source)) for (const type of Array.from(source.types)) consider(type, () => source.getData(type));
359
+ else for (const item of source.items) consider("type" in item ? item.type : item.mimeType, () => item.data);
360
+ const candidates = [];
361
+ for (const carrier of CARRIERS) {
362
+ const data = found.get(carrier);
363
+ if (data !== void 0) candidates.push({
364
+ carrier,
365
+ data
366
+ });
367
+ }
368
+ return candidates;
369
+ }
370
+ function findHtmlToken(html, id) {
371
+ const pattern = /data-rsc-clip\s*=\s*(["'])([a-z0-9.-]{1,96});([A-Za-z0-9_-]*)\1/g;
372
+ for (let scanned = 0; scanned < MAX_HTML_TOKENS; scanned += 1) {
373
+ const match = pattern.exec(html);
374
+ if (match === null) return null;
375
+ if (match[2] === id) return match[3];
376
+ }
377
+ return null;
378
+ }
379
+ /** The envelope a carrier holds, `null` when it holds none for this format, or why it is unusable. */
380
+ function extract(candidate, text, format) {
381
+ const { carrier } = candidate;
382
+ const tooLarge = () => invalid(carrier, [issue(`The clip exceeds the ${String(format.maxBytes)}-byte limit.`)]);
383
+ let json = text;
384
+ if (carrier === "html") {
385
+ const token = findHtmlToken(text, format.id);
386
+ if (token === null) return null;
387
+ if (decodedSize(token) > format.maxBytes) return tooLarge();
388
+ try {
389
+ json = decodeBase64Url(token);
390
+ } catch (cause) {
391
+ return invalid(carrier, [issue("The clip embedded in the HTML is corrupted.")], cause);
392
+ }
393
+ } else if (utf8ByteLength(text) > format.maxBytes) return tooLarge();
394
+ let envelope;
395
+ try {
396
+ envelope = parseEnvelope(json);
397
+ } catch (cause) {
398
+ return invalid(carrier, [issue(messageOf(cause))], cause);
399
+ }
400
+ if (envelope.id !== format.id) return invalid(carrier, [issue(`The clipboard holds "${envelope.id}" data under the "${format.id}" type.`)]);
401
+ return envelope;
402
+ }
403
+ function fromStandardResult(result, carrier, version) {
404
+ if (typeof result !== "object" || result === null) return invalid(carrier, [issue("The schema returned a malformed result.")]);
405
+ if (result.issues !== void 0) {
406
+ const raw = result.issues;
407
+ const issues = Array.from(Array.isArray(raw) ? raw : [], (item) => {
408
+ const entry = typeof item === "object" && item !== null ? item : {};
409
+ const path = Array.isArray(entry.path) ? Array.from(entry.path, (segment) => typeof segment === "object" && segment !== null ? segment.key : segment) : [];
410
+ return {
411
+ message: typeof entry.message === "string" ? entry.message : "Invalid value.",
412
+ path
413
+ };
414
+ });
415
+ return invalid(carrier, issues.length > 0 ? issues : [issue("The schema rejected the data.")]);
416
+ }
417
+ return {
418
+ status: "ok",
419
+ value: result.value,
420
+ version,
421
+ carrier
422
+ };
423
+ }
424
+ function isThenable(value) {
425
+ return typeof value === "object" && value !== null && typeof value.then === "function";
426
+ }
427
+ /** Migrates and validates an envelope. Returns a promise only when the schema validates asynchronously. */
428
+ function settle(envelope, carrier, format) {
429
+ const { version } = envelope;
430
+ if (version > format.version) return {
431
+ status: "unsupported-version",
432
+ carrier,
433
+ version
434
+ };
435
+ let data = envelope.data;
436
+ for (let from = version; from < format.version; from += 1) {
437
+ const step = format.migrate[from];
438
+ if (step === void 0) return {
439
+ status: "unsupported-version",
440
+ carrier,
441
+ version
442
+ };
443
+ try {
444
+ data = step(data);
445
+ } catch (cause) {
446
+ return invalid(carrier, [issue(`Migrating from version ${String(from)} failed: ${messageOf(cause)}`)], cause);
447
+ }
448
+ }
449
+ const { schema } = format;
450
+ if (!isStandardSchema(schema)) try {
451
+ return {
452
+ status: "ok",
453
+ value: schema(data),
454
+ version,
455
+ carrier
456
+ };
457
+ } catch (cause) {
458
+ return invalid(carrier, [issue(messageOf(cause))], cause);
459
+ }
460
+ let result;
461
+ try {
462
+ result = schema["~standard"].validate(data);
463
+ } catch (cause) {
464
+ return invalid(carrier, [issue(`The schema threw: ${messageOf(cause)}`)], cause);
465
+ }
466
+ if (!isThenable(result)) return fromStandardResult(result, carrier, version);
467
+ return Promise.resolve(result).then((settled) => fromStandardResult(settled, carrier, version), (cause) => invalid(carrier, [issue(`The schema threw: ${messageOf(cause)}`)], cause));
468
+ }
469
+ /**
470
+ * Reads a clip of `format` from a paste, a drop or a clip payload: finds it in the
471
+ * first carrier that holds one, migrates it from older versions, and validates it.
472
+ * Never throws for clipboard content; every outcome is a {@link ClipReadResult}.
473
+ *
474
+ * Supports asynchronous schemas and `Blob` entries. When you need a result
475
+ * synchronously and your schema is synchronous, use {@link readClipSync}.
476
+ *
477
+ * @example
478
+ * onPaste: async (result) => {
479
+ * const clip = await readClip(result, InvoiceRows);
480
+ * if (clip.status === 'ok') addRows(clip.value);
481
+ * }
482
+ */
483
+ async function readClip(source, format) {
484
+ assertClipFormat(format);
485
+ let firstInvalid = null;
486
+ for (const candidate of gather(source, format)) {
487
+ let text;
488
+ try {
489
+ text = typeof candidate.data === "string" ? candidate.data : await candidate.data.text();
490
+ } catch (cause) {
491
+ firstInvalid ?? (firstInvalid = invalid(candidate.carrier, [issue("The clipboard entry could not be read.")], cause));
492
+ continue;
493
+ }
494
+ const envelope = extract(candidate, text, format);
495
+ if (envelope === null) continue;
496
+ if ("status" in envelope) {
497
+ firstInvalid ?? (firstInvalid = envelope);
498
+ continue;
499
+ }
500
+ return settle(envelope, candidate.carrier, format);
501
+ }
502
+ return firstInvalid ?? { status: "absent" };
503
+ }
504
+ /**
505
+ * Synchronous {@link readClip}, e.g. to decide inside a paste or drop handler.
506
+ * `Blob` entries are skipped, and an asynchronous schema yields `invalid`.
507
+ */
508
+ function readClipSync(source, format) {
509
+ assertClipFormat(format);
510
+ let firstInvalid = null;
511
+ for (const candidate of gather(source, format)) {
512
+ if (typeof candidate.data !== "string") continue;
513
+ const envelope = extract(candidate, candidate.data, format);
514
+ if (envelope === null) continue;
515
+ if ("status" in envelope) {
516
+ firstInvalid ?? (firstInvalid = envelope);
517
+ continue;
518
+ }
519
+ const result = settle(envelope, candidate.carrier, format);
520
+ if (!(result instanceof Promise)) return result;
521
+ return invalid(candidate.carrier, [issue("The schema validates asynchronously: use readClip().")]);
522
+ }
523
+ return firstInvalid ?? { status: "absent" };
524
+ }
525
+ /**
526
+ * The `accept` list that lets a paste or drop carry these formats: each format's
527
+ * web custom format and clipboard type, plus HTML. Add `'text'` (or more) if you
528
+ * also handle other content.
529
+ *
530
+ * @example
531
+ * usePaste({ accept: [...clipAccept(InvoiceRows), 'text'], onPaste })
532
+ */
533
+ function clipAccept(...formats) {
534
+ const accept = [];
535
+ for (const format of formats) {
536
+ assertClipFormat(format);
537
+ accept.push(format.webMimeType, format.mimeType);
538
+ }
539
+ accept.push("html");
540
+ return accept;
541
+ }
542
+ //#endregion
543
+ export { CLIP_HTML_ATTRIBUTE, DEFAULT_CLIP_MAX_BYTES, clipAccept, clipPayload, defineClipFormat, readClip, readClipSync };
544
+
545
+ //# sourceMappingURL=structured.js.map