react-smart-copy 1.23.0 → 1.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +130 -1806
  2. package/dist/capture.cjs +3 -3
  3. package/dist/capture.d.cts +1 -1
  4. package/dist/capture.d.ts +1 -1
  5. package/dist/capture.js +3 -3
  6. package/dist/chunks/{clipboard-adapter-CtH4VELE.d.cts → clipboard-adapter-CfaIbZpv.d.cts} +2 -2
  7. package/dist/chunks/{clipboard-adapter-Ds0irroN.d.ts → clipboard-adapter-Chm6zq60.d.ts} +2 -2
  8. package/dist/chunks/{clipboard-adapter-DEXkXxwV.js → clipboard-adapter-CmKDTFdO.js} +3 -3
  9. package/dist/chunks/{clipboard-adapter-DEXkXxwV.js.map → clipboard-adapter-CmKDTFdO.js.map} +1 -1
  10. package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs → clipboard-adapter-UIFc_Qso.cjs} +3 -3
  11. package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs.map → clipboard-adapter-UIFc_Qso.cjs.map} +1 -1
  12. package/dist/chunks/{contrast-C6CVklEI.cjs → contrast-C9d8QuaF.cjs} +2 -2
  13. package/dist/chunks/{contrast-C6CVklEI.cjs.map → contrast-C9d8QuaF.cjs.map} +1 -1
  14. package/dist/chunks/{contrast-DpK2JIVu.js → contrast-DUaZq5SA.js} +2 -2
  15. package/dist/chunks/{contrast-DpK2JIVu.js.map → contrast-DUaZq5SA.js.map} +1 -1
  16. package/dist/chunks/{copy-interceptor-CZWzGOkL.d.cts → copy-interceptor-BClcHS_P.d.cts} +2 -2
  17. package/dist/chunks/{copy-interceptor-C6NABy1l.d.ts → copy-interceptor-D8c9EDnO.d.ts} +2 -2
  18. package/dist/chunks/{core-Cp2HSpaz.js → core-BH2uIumi.js} +5 -5
  19. package/dist/chunks/{core-Cp2HSpaz.js.map → core-BH2uIumi.js.map} +1 -1
  20. package/dist/chunks/{core-DYf_Lhbe.cjs → core-DmncxMt3.cjs} +5 -5
  21. package/dist/chunks/{core-DYf_Lhbe.cjs.map → core-DmncxMt3.cjs.map} +1 -1
  22. package/dist/chunks/{deadline-C29AlS_Q.js → deadline-CbwnZ3Oq.js} +2 -2
  23. package/dist/chunks/{deadline-C29AlS_Q.js.map → deadline-CbwnZ3Oq.js.map} +1 -1
  24. package/dist/chunks/{deadline-DkiB8ZHE.cjs → deadline-j2hD7JKz.cjs} +2 -2
  25. package/dist/chunks/{deadline-DkiB8ZHE.cjs.map → deadline-j2hD7JKz.cjs.map} +1 -1
  26. package/dist/chunks/{errors-9h8sdFFX.js → errors-CT-FfUtU.js} +2 -2
  27. package/dist/chunks/errors-CT-FfUtU.js.map +1 -0
  28. package/dist/chunks/{errors-BwOF6T_M.cjs → errors-DFmEAC4E.cjs} +2 -2
  29. package/dist/chunks/errors-DFmEAC4E.cjs.map +1 -0
  30. package/dist/chunks/{field-BHo5y-t_.js → field-CK3NxfkM.js} +43 -14
  31. package/dist/chunks/field-CK3NxfkM.js.map +1 -0
  32. package/dist/chunks/{field-Bytz2WfN.cjs → field-CNEcZqa9.cjs} +43 -14
  33. package/dist/chunks/field-CNEcZqa9.cjs.map +1 -0
  34. package/dist/chunks/{index-vz0iW5V2.d.cts → index-CqYzvxSN.d.cts} +4 -4
  35. package/dist/chunks/{index-mr7sSAgP.d.ts → index-Q_QeSwGr.d.ts} +4 -4
  36. package/dist/chunks/{paste-adapter--SPL4PRE.d.cts → paste-adapter-B6eucH3E.d.cts} +2 -2
  37. package/dist/chunks/{paste-adapter-uahXnTYk.d.ts → paste-adapter-CfIDT3mp.d.ts} +2 -2
  38. package/dist/chunks/{paste-reader-Bo01IMC_.cjs → paste-reader-BWQaYNaV.cjs} +2 -2
  39. package/dist/chunks/paste-reader-BWQaYNaV.cjs.map +1 -0
  40. package/dist/chunks/{paste-reader-D9i7yMXF.js → paste-reader-D6uOTDBM.js} +2 -2
  41. package/dist/chunks/paste-reader-D6uOTDBM.js.map +1 -0
  42. package/dist/chunks/{payload-DI5AorDz.js → payload-BWQ6sPtS.js} +3 -3
  43. package/dist/chunks/{payload-DI5AorDz.js.map → payload-BWQ6sPtS.js.map} +1 -1
  44. package/dist/chunks/{payload-DGw-JOo7.js → payload-BrQWGwyx.js} +2 -2
  45. package/dist/chunks/{payload-DGw-JOo7.js.map → payload-BrQWGwyx.js.map} +1 -1
  46. package/dist/chunks/{payload-Cl_8hCI5.d.ts → payload-CcvSx_Hq.d.ts} +4 -2
  47. package/dist/chunks/{payload-CcwKJ_bU.d.cts → payload-qkAWVXWA.d.cts} +4 -2
  48. package/dist/chunks/{payload-CUymxwim.cjs → payload-sBxkG7jH.cjs} +2 -2
  49. package/dist/chunks/{payload-CUymxwim.cjs.map → payload-sBxkG7jH.cjs.map} +1 -1
  50. package/dist/chunks/{payload-J6GjHuh3.cjs → payload-tTK6REua.cjs} +3 -3
  51. package/dist/chunks/{payload-J6GjHuh3.cjs.map → payload-tTK6REua.cjs.map} +1 -1
  52. package/dist/chunks/{share-Bop47Znn.js → share-CU91L4EK.js} +6 -6
  53. package/dist/chunks/{share-Bop47Znn.js.map → share-CU91L4EK.js.map} +1 -1
  54. package/dist/chunks/{share-e7FenIr2.d.ts → share-DVR_DhHc.d.ts} +3 -3
  55. package/dist/chunks/{share-C0esXvRK.d.cts → share-hIwth7Dh.d.cts} +3 -3
  56. package/dist/chunks/{share-ayDz974N.cjs → share-nx7M4Z0t.cjs} +6 -6
  57. package/dist/chunks/{share-ayDz974N.cjs.map → share-nx7M4Z0t.cjs.map} +1 -1
  58. package/dist/chunks/{url-D4PGsRm8.cjs → url-BrhVUwn7.cjs} +2 -2
  59. package/dist/chunks/{url-D4PGsRm8.cjs.map → url-BrhVUwn7.cjs.map} +1 -1
  60. package/dist/chunks/{url-BcMYVCXQ.js → url-COID0BLY.js} +2 -2
  61. package/dist/chunks/{url-BcMYVCXQ.js.map → url-COID0BLY.js.map} +1 -1
  62. package/dist/code.cjs +1 -1
  63. package/dist/code.cjs.map +1 -1
  64. package/dist/code.d.cts +1 -1
  65. package/dist/code.d.ts +1 -1
  66. package/dist/code.js +1 -1
  67. package/dist/code.js.map +1 -1
  68. package/dist/color.cjs +2 -2
  69. package/dist/color.d.cts +1 -1
  70. package/dist/color.d.ts +1 -1
  71. package/dist/color.js +2 -2
  72. package/dist/core.cjs +5 -5
  73. package/dist/core.d.cts +5 -5
  74. package/dist/core.d.ts +5 -5
  75. package/dist/core.js +5 -5
  76. package/dist/email.cjs +357 -0
  77. package/dist/email.cjs.map +1 -0
  78. package/dist/email.d.cts +163 -0
  79. package/dist/email.d.ts +163 -0
  80. package/dist/email.js +351 -0
  81. package/dist/email.js.map +1 -0
  82. package/dist/files.cjs +1 -1
  83. package/dist/files.cjs.map +1 -1
  84. package/dist/files.d.cts +3 -59
  85. package/dist/files.d.ts +3 -59
  86. package/dist/files.js +1 -1
  87. package/dist/files.js.map +1 -1
  88. package/dist/image.cjs +2 -2
  89. package/dist/image.cjs.map +1 -1
  90. package/dist/image.js +2 -2
  91. package/dist/image.js.map +1 -1
  92. package/dist/index.cjs +7 -7
  93. package/dist/index.cjs.map +1 -1
  94. package/dist/index.d.cts +43 -19
  95. package/dist/index.d.ts +43 -19
  96. package/dist/index.js +7 -7
  97. package/dist/index.js.map +1 -1
  98. package/dist/link.cjs +3 -3
  99. package/dist/link.d.cts +1 -1
  100. package/dist/link.d.ts +1 -1
  101. package/dist/link.js +3 -3
  102. package/dist/markdown.cjs +1 -1
  103. package/dist/markdown.cjs.map +1 -1
  104. package/dist/markdown.js +1 -1
  105. package/dist/markdown.js.map +1 -1
  106. package/dist/number.cjs +1 -1
  107. package/dist/number.d.cts +1 -1
  108. package/dist/number.d.ts +1 -1
  109. package/dist/number.js +1 -1
  110. package/dist/otp.cjs +1 -1
  111. package/dist/otp.js +1 -1
  112. package/dist/rich.cjs +3 -3
  113. package/dist/rich.cjs.map +1 -1
  114. package/dist/rich.d.cts +2 -2
  115. package/dist/rich.d.ts +2 -2
  116. package/dist/rich.js +3 -3
  117. package/dist/rich.js.map +1 -1
  118. package/dist/secrets.cjs +1 -1
  119. package/dist/secrets.cjs.map +1 -1
  120. package/dist/secrets.d.cts +1 -1
  121. package/dist/secrets.d.ts +1 -1
  122. package/dist/secrets.js +1 -1
  123. package/dist/secrets.js.map +1 -1
  124. package/dist/share.cjs +1 -1
  125. package/dist/share.d.cts +1 -1
  126. package/dist/share.d.ts +1 -1
  127. package/dist/share.js +1 -1
  128. package/dist/structured.cjs +2 -2
  129. package/dist/structured.cjs.map +1 -1
  130. package/dist/structured.js +2 -2
  131. package/dist/structured.js.map +1 -1
  132. package/dist/table.cjs +1 -1
  133. package/dist/table.cjs.map +1 -1
  134. package/dist/table.d.cts +1 -1
  135. package/dist/table.d.ts +1 -1
  136. package/dist/table.js +1 -1
  137. package/dist/table.js.map +1 -1
  138. package/dist/testing.cjs +2 -2
  139. package/dist/testing.d.cts +3 -3
  140. package/dist/testing.d.ts +3 -3
  141. package/dist/testing.js +2 -2
  142. package/package.json +35 -6
  143. package/dist/chunks/errors-9h8sdFFX.js.map +0 -1
  144. package/dist/chunks/errors-BwOF6T_M.cjs.map +0 -1
  145. package/dist/chunks/field-BHo5y-t_.js.map +0 -1
  146. package/dist/chunks/field-Bytz2WfN.cjs.map +0 -1
  147. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +0 -1
  148. package/dist/chunks/paste-reader-D9i7yMXF.js.map +0 -1
@@ -1 +1 @@
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>> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' };\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,W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vB,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: unique symbol = 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: number = 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>> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' };\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,oBAAmC,OAAO,IAAI,6BAA6B;;AAGxF,SAAgB,iBAAiB,QAAuB;CACtD,IAAI,OAAO,WAAW,YAAY,WAAW,QAAS,OAAmC,uBAAuB,MAC9G,MAAMA,eAAAA,YAAY,mBAAmB,yDAAyD;AAElG;;;ACiFA,MAAa,yBAAiC;;AAG9C,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,MAAiG;CAChH,OAAO,OAAO,UAAU,YAAY,MAAM,YAAY,KAAK,WAAW,MAAM,QAAQ;AACtF;AAEA,SAAS,iBAAqB,OAAuB,MAA8B;CACjF,IAAI,UAAU,KAAA,KAAa,CAAC,WAAW,KAAK,GAAG,UAA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ACA,OAAO,KAAK,MAAM;CAClB,OAAO;AACT"}
@@ -1,7 +1,7 @@
1
1
 
2
- import { n as copyFailure } from "./chunks/errors-9h8sdFFX.js";
2
+ import { n as copyFailure } from "./chunks/errors-CT-FfUtU.js";
3
3
  import { o as normalizeClipboardType } from "./chunks/mime-aa-HA2dm.js";
4
- import { d as utf8ByteLength } from "./chunks/paste-reader-D9i7yMXF.js";
4
+ import { d as utf8ByteLength } from "./chunks/paste-reader-D6uOTDBM.js";
5
5
  //#region src/structured/guard.ts
6
6
  /**
7
7
  * Brands formats made by `defineClipFormat`. A registered symbol (not a WeakSet),
@@ -1 +1 @@
1
- {"version":3,"file":"structured.js","names":["invalid"],"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>> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' };\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,MAAM,YAAY,mBAAmB,yDAAyD;AAElG;;;ACiFA,MAAa,yBAAyB;;AAGtC,MAAM,WAAW;AACjB,MAAM,gBAAgB;AAEtB,MAAMA,aAAW,YAA2B;CAC1C,MAAM,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,MAAiG;CAChH,OAAO,OAAO,UAAU,YAAY,MAAM,YAAY,KAAK,WAAW,MAAM,QAAQ;AACtF;AAEA,SAAS,iBAAqB,OAAuB,MAA8B;CACjF,IAAI,UAAU,KAAA,KAAa,CAAC,WAAW,KAAK,GAAG,UAAQ,KAAK,KAAK,uBAAuB;CACxF,OAAO;AACT;AAEA,SAAS,kBAAkB,SAAkB,SAA0D;CACrG,MAAM,QAAQ,OAAO,OAAO,IAAI;CAChC,IAAI,YAAY,KAAA,GAAW,OAAO,OAAO,OAAO,KAAK;C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;EACzF,SAAS,OAAO;GACd,iBAAA,eAAiB,QAAQ,UAAU,SAAS,CAAC,MAAM,wCAAwC,CAAC,GAAG,KAAK;GACpG;EACF;EACA,MAAM,WAAW,QAAQ,WAAW,MAAM,MAAM;EAChD,IAAI,aAAa,MAAM;EACvB,IAAI,YAAY,UAAU;GACxB,iBAAA,eAAiB;GACjB;EACF;EACA,OAAO,OAAO,UAAU,UAAU,SAAS,MAAM;CACnD;CACA,OAAO,gBAAgB,EAAE,QAAQ,SAAS;AAC5C;;;;;AAMA,SAAgB,aAAoB,QAAoB,QAAkD;CACxG,iBAAiB,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.js","names":["invalid"],"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: unique symbol = 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: number = 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>> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' };\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,oBAAmC,OAAO,IAAI,6BAA6B;;AAGxF,SAAgB,iBAAiB,QAAuB;CACtD,IAAI,OAAO,WAAW,YAAY,WAAW,QAAS,OAAmC,uBAAuB,MAC9G,MAAM,YAAY,m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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"}
package/dist/table.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
3
+ const require_errors = require("./chunks/errors-DFmEAC4E.cjs");
4
4
  const require_inert_html = require("./chunks/inert-html-DyxjWDok.cjs");
5
5
  //#region src/table/serialize.ts
6
6
  const DEFAULT_TABLE_MAX_CELLS = 1e6;