react-smart-copy 1.24.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.
- package/README.md +130 -1834
- package/dist/capture.cjs +3 -3
- package/dist/capture.d.cts +1 -1
- package/dist/capture.d.ts +1 -1
- package/dist/capture.js +3 -3
- package/dist/chunks/{clipboard-adapter-CtH4VELE.d.cts → clipboard-adapter-CfaIbZpv.d.cts} +2 -2
- package/dist/chunks/{clipboard-adapter-Ds0irroN.d.ts → clipboard-adapter-Chm6zq60.d.ts} +2 -2
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js → clipboard-adapter-CmKDTFdO.js} +3 -3
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js.map → clipboard-adapter-CmKDTFdO.js.map} +1 -1
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs → clipboard-adapter-UIFc_Qso.cjs} +3 -3
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs.map → clipboard-adapter-UIFc_Qso.cjs.map} +1 -1
- package/dist/chunks/{contrast-C6CVklEI.cjs → contrast-C9d8QuaF.cjs} +2 -2
- package/dist/chunks/{contrast-C6CVklEI.cjs.map → contrast-C9d8QuaF.cjs.map} +1 -1
- package/dist/chunks/{contrast-DpK2JIVu.js → contrast-DUaZq5SA.js} +2 -2
- package/dist/chunks/{contrast-DpK2JIVu.js.map → contrast-DUaZq5SA.js.map} +1 -1
- package/dist/chunks/{copy-interceptor-CZWzGOkL.d.cts → copy-interceptor-BClcHS_P.d.cts} +2 -2
- package/dist/chunks/{copy-interceptor-C6NABy1l.d.ts → copy-interceptor-D8c9EDnO.d.ts} +2 -2
- package/dist/chunks/{core-Cp2HSpaz.js → core-BH2uIumi.js} +5 -5
- package/dist/chunks/{core-Cp2HSpaz.js.map → core-BH2uIumi.js.map} +1 -1
- package/dist/chunks/{core-DYf_Lhbe.cjs → core-DmncxMt3.cjs} +5 -5
- package/dist/chunks/{core-DYf_Lhbe.cjs.map → core-DmncxMt3.cjs.map} +1 -1
- package/dist/chunks/{deadline-C29AlS_Q.js → deadline-CbwnZ3Oq.js} +2 -2
- package/dist/chunks/{deadline-C29AlS_Q.js.map → deadline-CbwnZ3Oq.js.map} +1 -1
- package/dist/chunks/{deadline-DkiB8ZHE.cjs → deadline-j2hD7JKz.cjs} +2 -2
- package/dist/chunks/{deadline-DkiB8ZHE.cjs.map → deadline-j2hD7JKz.cjs.map} +1 -1
- package/dist/chunks/{errors-9h8sdFFX.js → errors-CT-FfUtU.js} +2 -2
- package/dist/chunks/errors-CT-FfUtU.js.map +1 -0
- package/dist/chunks/{errors-BwOF6T_M.cjs → errors-DFmEAC4E.cjs} +2 -2
- package/dist/chunks/errors-DFmEAC4E.cjs.map +1 -0
- package/dist/chunks/{field-BHo5y-t_.js → field-CK3NxfkM.js} +43 -14
- package/dist/chunks/field-CK3NxfkM.js.map +1 -0
- package/dist/chunks/{field-Bytz2WfN.cjs → field-CNEcZqa9.cjs} +43 -14
- package/dist/chunks/field-CNEcZqa9.cjs.map +1 -0
- package/dist/chunks/{index-vz0iW5V2.d.cts → index-CqYzvxSN.d.cts} +4 -4
- package/dist/chunks/{index-mr7sSAgP.d.ts → index-Q_QeSwGr.d.ts} +4 -4
- package/dist/chunks/{paste-adapter--SPL4PRE.d.cts → paste-adapter-B6eucH3E.d.cts} +2 -2
- package/dist/chunks/{paste-adapter-uahXnTYk.d.ts → paste-adapter-CfIDT3mp.d.ts} +2 -2
- package/dist/chunks/{paste-reader-Bo01IMC_.cjs → paste-reader-BWQaYNaV.cjs} +2 -2
- package/dist/chunks/paste-reader-BWQaYNaV.cjs.map +1 -0
- package/dist/chunks/{paste-reader-D9i7yMXF.js → paste-reader-D6uOTDBM.js} +2 -2
- package/dist/chunks/paste-reader-D6uOTDBM.js.map +1 -0
- package/dist/chunks/{payload-DI5AorDz.js → payload-BWQ6sPtS.js} +3 -3
- package/dist/chunks/{payload-DI5AorDz.js.map → payload-BWQ6sPtS.js.map} +1 -1
- package/dist/chunks/{payload-DGw-JOo7.js → payload-BrQWGwyx.js} +2 -2
- package/dist/chunks/{payload-DGw-JOo7.js.map → payload-BrQWGwyx.js.map} +1 -1
- package/dist/chunks/{payload-Cl_8hCI5.d.ts → payload-CcvSx_Hq.d.ts} +4 -2
- package/dist/chunks/{payload-CcwKJ_bU.d.cts → payload-qkAWVXWA.d.cts} +4 -2
- package/dist/chunks/{payload-CUymxwim.cjs → payload-sBxkG7jH.cjs} +2 -2
- package/dist/chunks/{payload-CUymxwim.cjs.map → payload-sBxkG7jH.cjs.map} +1 -1
- package/dist/chunks/{payload-J6GjHuh3.cjs → payload-tTK6REua.cjs} +3 -3
- package/dist/chunks/{payload-J6GjHuh3.cjs.map → payload-tTK6REua.cjs.map} +1 -1
- package/dist/chunks/{share-Bop47Znn.js → share-CU91L4EK.js} +6 -6
- package/dist/chunks/{share-Bop47Znn.js.map → share-CU91L4EK.js.map} +1 -1
- package/dist/chunks/{share-e7FenIr2.d.ts → share-DVR_DhHc.d.ts} +3 -3
- package/dist/chunks/{share-C0esXvRK.d.cts → share-hIwth7Dh.d.cts} +3 -3
- package/dist/chunks/{share-ayDz974N.cjs → share-nx7M4Z0t.cjs} +6 -6
- package/dist/chunks/{share-ayDz974N.cjs.map → share-nx7M4Z0t.cjs.map} +1 -1
- package/dist/chunks/{url-D4PGsRm8.cjs → url-BrhVUwn7.cjs} +2 -2
- package/dist/chunks/{url-D4PGsRm8.cjs.map → url-BrhVUwn7.cjs.map} +1 -1
- package/dist/chunks/{url-BcMYVCXQ.js → url-COID0BLY.js} +2 -2
- package/dist/chunks/{url-BcMYVCXQ.js.map → url-COID0BLY.js.map} +1 -1
- package/dist/code.cjs +1 -1
- package/dist/code.cjs.map +1 -1
- package/dist/code.d.cts +1 -1
- package/dist/code.d.ts +1 -1
- package/dist/code.js +1 -1
- package/dist/code.js.map +1 -1
- package/dist/color.cjs +2 -2
- package/dist/color.d.cts +1 -1
- package/dist/color.d.ts +1 -1
- package/dist/color.js +2 -2
- package/dist/core.cjs +5 -5
- package/dist/core.d.cts +5 -5
- package/dist/core.d.ts +5 -5
- package/dist/core.js +5 -5
- package/dist/email.cjs +1 -1
- package/dist/email.cjs.map +1 -1
- package/dist/email.d.cts +1 -1
- package/dist/email.d.ts +1 -1
- package/dist/email.js +1 -1
- package/dist/email.js.map +1 -1
- package/dist/files.cjs +1 -1
- package/dist/files.cjs.map +1 -1
- package/dist/files.d.cts +3 -59
- package/dist/files.d.ts +3 -59
- package/dist/files.js +1 -1
- package/dist/files.js.map +1 -1
- package/dist/image.cjs +2 -2
- package/dist/image.cjs.map +1 -1
- package/dist/image.js +2 -2
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -19
- package/dist/index.d.ts +43 -19
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/link.cjs +3 -3
- package/dist/link.d.cts +1 -1
- package/dist/link.d.ts +1 -1
- package/dist/link.js +3 -3
- package/dist/markdown.cjs +1 -1
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.js +1 -1
- package/dist/markdown.js.map +1 -1
- package/dist/number.cjs +1 -1
- package/dist/number.d.cts +1 -1
- package/dist/number.d.ts +1 -1
- package/dist/number.js +1 -1
- package/dist/otp.cjs +1 -1
- package/dist/otp.js +1 -1
- package/dist/rich.cjs +3 -3
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +2 -2
- package/dist/rich.d.ts +2 -2
- package/dist/rich.js +3 -3
- package/dist/rich.js.map +1 -1
- package/dist/secrets.cjs +1 -1
- package/dist/secrets.cjs.map +1 -1
- package/dist/secrets.d.cts +1 -1
- package/dist/secrets.d.ts +1 -1
- package/dist/secrets.js +1 -1
- package/dist/secrets.js.map +1 -1
- package/dist/share.cjs +1 -1
- package/dist/share.d.cts +1 -1
- package/dist/share.d.ts +1 -1
- package/dist/share.js +1 -1
- package/dist/structured.cjs +2 -2
- package/dist/structured.cjs.map +1 -1
- package/dist/structured.js +2 -2
- package/dist/structured.js.map +1 -1
- package/dist/table.cjs +1 -1
- package/dist/table.cjs.map +1 -1
- package/dist/table.d.cts +1 -1
- package/dist/table.d.ts +1 -1
- package/dist/table.js +1 -1
- package/dist/table.js.map +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +2 -2
- package/package.json +6 -4
- package/dist/chunks/errors-9h8sdFFX.js.map +0 -1
- package/dist/chunks/errors-BwOF6T_M.cjs.map +0 -1
- package/dist/chunks/field-BHo5y-t_.js.map +0 -1
- package/dist/chunks/field-Bytz2WfN.cjs.map +0 -1
- package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +0 -1
- package/dist/chunks/paste-reader-D9i7yMXF.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-DFmEAC4E.cjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND: unique symbol = Symbol.for('react-smart-copy.CopyFailure');\n\n// The brand is declared here and set in the constructor: a class can't declare a symbol-named\n// property in a way its declaration file can be written from this file alone.\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- the constructor sets the brand\nexport interface CopyFailure {\n readonly [COPY_FAILURE_BRAND]: true;\n}\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- see the interface above\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n // An own, enumerable property, as a class field would be.\n (this as { [COPY_FAILURE_BRAND]: true })[COPY_FAILURE_BRAND] = true;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n"],"mappings":";;AA8CA,SAAgB,gBAAgB,MA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AAK;EACL,KAAK,aACH,OAAO,gBAAgB,sBAAsB,+CAA+C,KAAK;EACnG,KAAK,cACH,OAAO,gBAAgB,WAAW,iBAAiB,KAAK,gBAAgB,KAAK;EAC/E,KAAK,gBACH,OAAO,gBAAgB,WAAW,iBAAiB,KAAK,cAAc,KAAK;EAC7E,SACE,OAAO,gBAAgB,WAAW,WAAW,iBAAiB,KAAK,iCAAiC,KAAK;CAC7G;AACF;AAEA,MAAM,oBAA6D;CACjE,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,0BAA0B;CAC1B,wBAAwB;CACxB,cAAc;CACd,aAAa;CACb,SAAS;CACT,SAAS;CACT,SAAS;AACX;AAEA,MAAM,qBAA8D;CAClE,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,0BAA0B;CAC1B,wBAAwB;CACxB,cAAc;CACd,aAAa;CACb,SAAS;CACT,SAAS;CACT,SAAS;AACX;;AAGA,SAAgB,kBAAkB,OAA0B;CAC1D,OAAO,kBAAkB,MAAM;AACjC;;AAGA,MAAM,oBAAsE;CAC1E,mBAAmB;CACnB,cAAc;CACd,aAAa;CACb,SAAS;AACX;;;;;AAMA,SAAgB,mBAAmB,OAAkB,QAA8B;CACjF,QAAQ,WAAW,SAAS,kBAAkB,MAAM,QAAQ,KAAA,MAAc,mBAAmB,MAAM;AACrG"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as copyFailure } from "./errors-
|
|
2
|
+
import { n as copyFailure } from "./errors-CT-FfUtU.js";
|
|
3
3
|
import { t as asciiDigits } from "./digits-DkU-O9_A.js";
|
|
4
4
|
//#region src/otp/normalize.ts
|
|
5
5
|
/**
|
|
@@ -139,21 +139,49 @@ function lowerSameLength(text) {
|
|
|
139
139
|
}
|
|
140
140
|
return out;
|
|
141
141
|
}
|
|
142
|
-
/**
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
142
|
+
/**
|
|
143
|
+
* Every keyword in `lower`, by position. Found once for the whole text, so each number's
|
|
144
|
+
* nearest keyword is a short look among its neighbours, not a new search.
|
|
145
|
+
*/
|
|
146
|
+
function keywordsIn(lower) {
|
|
147
|
+
const found = [];
|
|
147
148
|
for (const keyword of KEYWORDS) {
|
|
148
149
|
const whole = /^[a-z0-9 -]+$/.test(keyword);
|
|
149
|
-
for (let at =
|
|
150
|
-
if (whole && (/[a-z]/.test(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
150
|
+
for (let at = lower.indexOf(keyword); at !== -1; at = lower.indexOf(keyword, at + 1)) {
|
|
151
|
+
if (whole && (/[a-z]/.test(lower.charAt(at - 1)) || /[a-z]/.test(lower.charAt(at + keyword.length)))) continue;
|
|
152
|
+
found.push({
|
|
153
|
+
from: at,
|
|
154
|
+
to: at + keyword.length
|
|
155
|
+
});
|
|
155
156
|
}
|
|
156
157
|
}
|
|
158
|
+
return found.sort((a, b) => a.from - b.from);
|
|
159
|
+
}
|
|
160
|
+
/** The index of the first keyword that starts at or after `position` (binary search). */
|
|
161
|
+
function firstFrom(keywords, position) {
|
|
162
|
+
let low = 0;
|
|
163
|
+
let high = keywords.length;
|
|
164
|
+
while (low < high) {
|
|
165
|
+
const middle = low + high >>> 1;
|
|
166
|
+
if (keywords[middle].from < position) low = middle + 1;
|
|
167
|
+
else high = middle;
|
|
168
|
+
}
|
|
169
|
+
return low;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The distance from the number at `start`-`end` to the nearest keyword within 60 characters
|
|
173
|
+
* before it or 40 after it: words before count closer.
|
|
174
|
+
*/
|
|
175
|
+
function keywordDistance(keywords, start, end) {
|
|
176
|
+
const windowEnd = end + 40;
|
|
177
|
+
let best = Infinity;
|
|
178
|
+
for (let index = firstFrom(keywords, start - 60); index < keywords.length; index += 1) {
|
|
179
|
+
const { from, to } = keywords[index];
|
|
180
|
+
if (from >= windowEnd) break;
|
|
181
|
+
if (to > windowEnd) continue;
|
|
182
|
+
if (to <= start) best = Math.min(best, start - to);
|
|
183
|
+
else if (from >= end) best = Math.min(best, from - end + 10);
|
|
184
|
+
}
|
|
157
185
|
return best;
|
|
158
186
|
}
|
|
159
187
|
/** The origin-bound line of the WebOTP format: `@host #code`, last in the message. */
|
|
@@ -198,6 +226,7 @@ function extractOtp(text, options = {}) {
|
|
|
198
226
|
}
|
|
199
227
|
const lower = lowerSameLength(normalized);
|
|
200
228
|
const pattern = alphabet === "numeric" ? NUMERIC : ALPHANUMERIC;
|
|
229
|
+
const keywords = keywordsIn(lower);
|
|
201
230
|
const candidates = [];
|
|
202
231
|
for (const match of normalized.matchAll(pattern)) {
|
|
203
232
|
const raw = match[2];
|
|
@@ -206,7 +235,7 @@ function extractOtp(text, options = {}) {
|
|
|
206
235
|
if (!fits(code) || alphabet === "alphanumeric" && !/\d/.test(code) || excluded(normalized, lower, start, start + raw.length)) continue;
|
|
207
236
|
candidates.push({
|
|
208
237
|
code,
|
|
209
|
-
distance: keywordDistance(
|
|
238
|
+
distance: keywordDistance(keywords, start, start + raw.length)
|
|
210
239
|
});
|
|
211
240
|
}
|
|
212
241
|
const near = candidates.filter((candidate) => candidate.distance <= 60);
|
|
@@ -532,4 +561,4 @@ function createOtpField(options = {}) {
|
|
|
532
561
|
//#endregion
|
|
533
562
|
export { normalizeOtpText as i, OTP_SCAN_LENGTH as n, extractOtp as r, createOtpField as t };
|
|
534
563
|
|
|
535
|
-
//# sourceMappingURL=field-
|
|
564
|
+
//# sourceMappingURL=field-CK3NxfkM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"field-CK3NxfkM.js","names":[],"sources":["../../src/otp/normalize.ts","../../src/otp/extract.ts","../../src/otp/state.ts","../../src/otp/web-otp.ts","../../src/otp/field.ts"],"sourcesContent":["import { asciiDigits } from '../core/digits';\n\n/** What a one-time code is made of. */\nexport type OtpAlphabet = 'numeric' | 'alphanumeric';\n\n/**\n * `text` with its digits in ASCII and, for alphanumeric codes, its letters in upper case:\n * full-width digits and letters, and Arabic-Indic, Devanagari and other scripts' digits,\n * become ASCII. Other characters are kept: callers decide what to drop.\n */\nexport function normalizeOtpText(text: string, alphabet: OtpAlphabet): string {\n const ascii = asciiDigits(text);\n return alphabet === 'alphanumeric' ? ascii.toUpperCase() : ascii;\n}\n\n/** Whether `char` (already normalized) can be part of a code. */\nexport function isOtpChar(char: string, alphabet: OtpAlphabet): boolean {\n return alphabet === 'numeric' ? char >= '0' && char <= '9' && char.length === 1 : /^[0-9A-Z]$/.test(char);\n}\n\n/** The characters of `text` that can be part of a code, normalized, in order. */\nexport function otpChars(text: string, alphabet: OtpAlphabet): string[] {\n return Array.from(normalizeOtpText(text, alphabet)).filter((char) => isOtpChar(char, alphabet));\n}\n","import { copyFailure } from '../core/errors';\nimport { normalizeOtpText, type OtpAlphabet } from './normalize';\n\n/** Text past this many characters is not read: a code is near the start of a message. */\nexport const OTP_SCAN_LENGTH = 100_000;\n\nexport interface ExtractOtpOptions {\n /** The code's length, or its range. Default 4 to 8. */\n readonly length?: number | { readonly min: number; readonly max: number };\n /** Default `'numeric'`. Alphanumeric codes are upper case: pasted letters are made so. */\n readonly alphabet?: OtpAlphabet;\n /**\n * Your site's host name, as in `example.com`. An origin-bound message (`@example.com #123456`,\n * the format the WebOTP API reads) for another host gives no code: it was not meant for you.\n */\n readonly domain?: string;\n}\n\n/**\n * Where the code was found.\n *\n * - `whole-text`: the text is the code (`482913`, `482 913`, `482-913`).\n * - `origin-bound`: the message's last line binds it to a site (`@example.com #482913`).\n * - `keyword`: next to a word such as \"code\", \"OTP\", \"verification\" or \"PIN\", in any of\n * many languages.\n * - `only-candidate`: the only number of the right length that is not a price, a date, a\n * time, a phone number or an order number.\n */\nexport type OtpSource = 'whole-text' | 'origin-bound' | 'keyword' | 'only-candidate';\n\nexport interface OtpMatch {\n /** The code: ASCII digits (and upper-case letters, for alphanumeric codes), no separators. */\n readonly code: string;\n readonly source: OtpSource;\n /** `medium` for `only-candidate`; `high` otherwise. */\n readonly confidence: 'high' | 'medium';\n /** The site an origin-bound message names; `null` otherwise. */\n readonly domain: string | null;\n}\n\ninterface Range {\n readonly min: number;\n readonly max: number;\n}\n\nfunction rangeOf(length: ExtractOtpOptions['length']): Range {\n const range = typeof length === 'number' ? { min: length, max: length } : (length ?? { min: 4, max: 8 });\n const valid = (value: number): boolean => Number.isInteger(value) && value >= 1 && value <= 32;\n if (!valid(range.min) || !valid(range.max) || range.min > range.max) {\n throw copyFailure('invalid-payload', 'length must be a whole number from 1 to 32, or a range of them.');\n }\n return range;\n}\n\n/**\n * Words next to a one-time code, lower case: English, Hindi, Spanish, Portuguese, French,\n * German, Italian, Dutch, Indonesian, Turkish, Polish, Russian, Ukrainian, Arabic, Hebrew,\n * Persian, Chinese, Japanese, Korean, Vietnamese and Thai.\n */\nconst KEYWORDS: readonly string[] = [\n 'code', 'otp', 'one-time', 'one time', 'passcode', 'password', 'pin', 'verification', 'verify', 'security', 'login', 'log in',\n 'sign-in', 'sign in', '2fa', 'two-factor', 'authentication', 'token',\n '\\u0913\\u091F\\u0940\\u092A\\u0940', '\\u0915\\u094B\\u0921', '\\u0938\\u0924\\u094D\\u092F\\u093E\\u092A\\u0928',\n 'c\\u00F3digo', 'codigo', 'clave', 'contrase\\u00F1a', 'senha', 'mot de passe', 'v\\u00E9rification', 'best\\u00E4tigungscode',\n 'kennwort', 'codice', 'verificatie', 'kode', 'kod', 'do\\u011Frulama', 'weryfikacyjny',\n '\\u043A\\u043E\\u0434', '\\u043F\\u0430\\u0440\\u043E\\u043B\\u044C', '\\u0440\\u0430\\u0437\\u043E\\u0432\\u044B\\u0439',\n '\\u0631\\u0645\\u0632', '\\u0643\\u0648\\u062F', '\\u0627\\u0644\\u062A\\u062D\\u0642\\u0642', '\\u05E7\\u05D5\\u05D3', '\\u06A9\\u062F',\n '\\u9A8C\\u8BC1\\u7801', '\\u9A57\\u8B49\\u78BC', '\\u6821\\u9A8C\\u7801', '\\u52D5\\u614B\\u78BC', '\\u8A8D\\u8A3C\\u30B3\\u30FC\\u30C9',\n '\\u78BA\\u8A8D\\u30B3\\u30FC\\u30C9', '\\u30EF\\u30F3\\u30BF\\u30A4\\u30E0', '\\u8A8D\\u8A3C\\u756A\\u53F7', '\\uC778\\uC99D\\uBC88\\uD638',\n '\\uC778\\uC99D', '\\uCF54\\uB4DC', 'm\\u00E3', 'x\\u00E1c th\\u1EF1c', '\\u0E23\\u0E2B\\u0E31\\u0E2A',\n];\n\n/** Codes that are not one-time codes, right before a number: postal codes, coupons, orders. */\nconst NOT_OTP = /(?:pin ?code|zip|postal|post code|promo|coupon|discount|voucher|referral|order|invoice|ref\\.?|account|a\\/c|flight|pnr|room|tracking)[\\s:#.-]{0,4}$/;\n\n/** Currencies and units around a number: it is an amount, not a code. */\nconst CURRENCY_BEFORE = /(?:[$\\u20AC\\u00A3\\u20B9\\u00A5\\u20A9\\u20BD\\u00A2]|\\brs\\.?|\\binr|\\busd|\\beur|\\bgbp)\\s?$/;\nconst AMOUNT_AFTER = /^\\s?(?:%|[$\\u20AC\\u00A3\\u20B9\\u00A5]|inr\\b|usd\\b|eur\\b|rs\\b|rupees\\b|dollars\\b|euros\\b)/;\n\nconst NUMERIC = /(^|[^\\p{L}\\p{N}_])(\\d{2,4}(?:[ -]\\d{2,4}){1,3}|\\d{1,12})(?![\\p{L}\\p{N}_])/gu;\nconst ALPHANUMERIC = /(^|[^\\p{L}\\p{N}_])([A-Z0-9]{2,6}(?:-[A-Z0-9]{2,6}){1,3}|[A-Z0-9]{1,12})(?![\\p{L}\\p{N}_])/gu;\n\nconst isDigit = (char: string | undefined): boolean => char !== undefined && char >= '0' && char <= '9';\n\n/**\n * Whether the number at `start`-`end` is something else: part of a longer number (a phone\n * number), a date, a time or a decimal, an amount, an order or reference number, or inside\n * a URL or an e-mail address.\n */\nfunction excluded(text: string, lower: string, start: number, end: number): boolean {\n const before = text[start - 1];\n const after = text[end];\n if ((before === ' ' || before === '-') && isDigit(text[start - 2])) return true;\n if ((after === ' ' || after === '-') && isDigit(text[end + 1])) return true;\n // A time, a date, a decimal or a version (`10:30`, `23/10`, `3.14`), and thousands (`2,500`).\n if (before !== undefined && ':/.'.includes(before) && isDigit(text[start - 2])) return true;\n if (after !== undefined && ':/.'.includes(after) && isDigit(text[end + 1])) return true;\n if ((before === ',' && isDigit(text[start - 2]) && /^\\d{3}(?!\\d)/.test(text.slice(start, start + 4))) || /^,\\d{3}(?!\\d)/.test(text.slice(end, end + 5))) return true;\n if (before === '+' || before === '#' || before === '(' || (before === ' ' && text[start - 2] === ')')) return true;\n const head = lower.slice(Math.max(0, start - 24), start);\n if (CURRENCY_BEFORE.test(head) || NOT_OTP.test(head) || AMOUNT_AFTER.test(lower.slice(end, end + 10))) return true;\n // The word around it, between white space (up to 256 characters each way, so a scan stays\n // linear): a URL, with a scheme or a bare host and path (`example.com/t/48291`), or an\n // e-mail address holds no code.\n let from = start;\n while (from > Math.max(0, start - 256) && !/\\s/.test(text[from - 1] as string)) from -= 1;\n let to = end;\n while (to < Math.min(text.length, end + 256) && !/\\s/.test(text[to] as string)) to += 1;\n return /@|:\\/\\/|www\\.|[\\p{L}\\p{N}-]\\.\\p{L}{2,}\\//iu.test(text.slice(from, to));\n}\n\n/** Lower case, one character for one: positions in it are positions in `text`. */\nfunction lowerSameLength(text: string): string {\n let out = '';\n for (const char of text) {\n const lower = char.toLowerCase();\n out += lower.length === char.length ? lower : char;\n }\n return out;\n}\n\n/** Where a keyword is in the text: its first character, and the one after its last. */\ninterface KeywordAt {\n readonly from: number;\n readonly to: number;\n}\n\n/**\n * Every keyword in `lower`, by position. Found once for the whole text, so each number's\n * nearest keyword is a short look among its neighbours, not a new search.\n */\nfunction keywordsIn(lower: string): KeywordAt[] {\n const found: KeywordAt[] = [];\n for (const keyword of KEYWORDS) {\n // Words in Latin script count only as whole words: `pin` is not in `spinning`.\n const whole = /^[a-z0-9 -]+$/.test(keyword);\n for (let at = lower.indexOf(keyword); at !== -1; at = lower.indexOf(keyword, at + 1)) {\n if (whole && (/[a-z]/.test(lower.charAt(at - 1)) || /[a-z]/.test(lower.charAt(at + keyword.length)))) continue;\n found.push({ from: at, to: at + keyword.length });\n }\n }\n return found.sort((a, b) => a.from - b.from);\n}\n\n/** The index of the first keyword that starts at or after `position` (binary search). */\nfunction firstFrom(keywords: readonly KeywordAt[], position: number): number {\n let low = 0;\n let high = keywords.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if ((keywords[middle] as KeywordAt).from < position) low = middle + 1;\n else high = middle;\n }\n return low;\n}\n\n/**\n * The distance from the number at `start`-`end` to the nearest keyword within 60 characters\n * before it or 40 after it: words before count closer.\n */\nfunction keywordDistance(keywords: readonly KeywordAt[], start: number, end: number): number {\n const windowEnd = end + 40;\n let best = Infinity;\n for (let index = firstFrom(keywords, start - 60); index < keywords.length; index += 1) {\n const { from, to } = keywords[index] as KeywordAt;\n if (from >= windowEnd) break;\n if (to > windowEnd) continue;\n // A keyword inside the number itself (as in `otp` of an alphanumeric code) does not count.\n if (to <= start) best = Math.min(best, start - to);\n else if (from >= end) best = Math.min(best, from - end + 10);\n }\n return best;\n}\n\n/** The origin-bound line of the WebOTP format: `@host #code`, last in the message. */\nconst ORIGIN_BOUND = /(?:^|\\n)@([a-z0-9.-]{1,253}(?::\\d{1,5})?) #([A-Za-z0-9]{1,32})(?: @[a-z0-9.-]{1,253}(?::\\d{1,5})?)?[ \\t]*$/i;\n\n/**\n * The one-time code in `text`: an SMS or e-mail people paste, or a code they copied. Digits\n * of any script and full-width characters are read as ASCII, and separators are dropped\n * (`482 913`, `482-913`).\n *\n * Prices, dates, times, phone numbers, order numbers and postal codes are never taken for a\n * code. When several numbers could be the code and no keyword points at one, the result is\n * `null`: guessing would fill in a wrong code.\n *\n * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32, or a reversed range.\n */\nexport function extractOtp(text: string, options: ExtractOtpOptions = {}): OtpMatch | null {\n const range = rangeOf(options.length);\n const alphabet = options.alphabet ?? 'numeric';\n const fits = (code: string): boolean => code.length >= range.min && code.length <= range.max && (alphabet === 'alphanumeric' || /^\\d+$/.test(code));\n const normalized = normalizeOtpText(text.slice(0, OTP_SCAN_LENGTH), alphabet);\n\n // The text is the code itself.\n const whole = normalized.trim();\n if (/^[0-9A-Z]{1,32}(?:[ -][0-9A-Z]{1,32}){0,7}$/.test(whole)) {\n const code = whole.replace(/[ -]/g, '');\n if (fits(code)) return { code, source: 'whole-text', confidence: 'high', domain: null };\n }\n\n // A message bound to a site, in the format the WebOTP API reads.\n // Read with its case kept: host names are lower case, and an alphanumeric code is upper-cased after.\n const bound = ORIGIN_BOUND.exec(normalizeOtpText(text.slice(0, OTP_SCAN_LENGTH), 'numeric').trimEnd());\n if (bound !== null) {\n const domain = (bound[1] as string).toLowerCase();\n const code = (bound[2] as string).toUpperCase();\n if (options.domain !== undefined && options.domain.toLowerCase() !== domain) return null;\n if (fits(code)) return { code, source: 'origin-bound', confidence: 'high', domain };\n }\n\n const lower = lowerSameLength(normalized);\n const pattern = alphabet === 'numeric' ? NUMERIC : ALPHANUMERIC;\n const keywords = keywordsIn(lower);\n const candidates: { readonly code: string; readonly distance: number }[] = [];\n for (const match of normalized.matchAll(pattern)) {\n const raw = match[2] as string;\n const start = match.index + (match[1] as string).length;\n const code = raw.replace(/[ -]/g, '');\n if (!fits(code) || (alphabet === 'alphanumeric' && !/\\d/.test(code)) || excluded(normalized, lower, start, start + raw.length)) continue;\n candidates.push({ code, distance: keywordDistance(keywords, start, start + raw.length) });\n }\n const near = candidates.filter((candidate) => candidate.distance <= 60);\n if (near.length > 0) {\n const best = near.reduce((a, b) => (b.distance < a.distance ? b : a));\n return { code: best.code, source: 'keyword', confidence: 'high', domain: null };\n }\n const distinct = new Set(candidates.map((candidate) => candidate.code));\n return distinct.size === 1 ? { code: [...distinct][0] as string, source: 'only-candidate', confidence: 'medium', domain: null } : null;\n}\n","import { extractOtp } from './extract';\nimport { otpChars, type OtpAlphabet } from './normalize';\n\n/** The characters in each box ('' for an empty one), and the box to focus next. */\nexport interface OtpStep {\n readonly chars: readonly string[];\n /** The box to focus after the change. */\n readonly focus: number;\n}\n\nexport interface OtpSettings {\n readonly length: number;\n readonly alphabet: OtpAlphabet;\n}\n\n/** Keys a code field handles itself. */\nexport type OtpKey = 'Backspace' | 'Delete' | 'ArrowLeft' | 'ArrowRight' | 'Home' | 'End';\n\nexport const emptyChars = (length: number): readonly string[] => Array.from({ length }, () => '');\n\nconst clamp = (index: number, length: number): number => Math.min(Math.max(index, 0), length - 1);\n\n/** `chars` with `text`'s characters written from `index` on, as far as they fit. */\nfunction write(chars: readonly string[], index: number, text: readonly string[], settings: OtpSettings): OtpStep {\n const next = [...chars];\n // A whole code (an SMS autofill into one box, a paste) fills the field from the start.\n const from = text.length >= settings.length ? 0 : clamp(index, settings.length);\n const count = Math.min(text.length, settings.length - from);\n for (let offset = 0; offset < count; offset += 1) next[from + offset] = text[offset] as string;\n return { chars: next, focus: clamp(from + count, settings.length) };\n}\n\n/**\n * What typing (or an autofill, or an input method) does to box `index`, whose value went\n * from `previous` to `value`. A character typed next to the one already there replaces it;\n * several characters fill the boxes after it; characters a code can't have are ignored.\n */\nexport function inputStep(chars: readonly string[], index: number, previous: string, value: string, settings: OtpSettings): OtpStep {\n let typed = value;\n // One character added beside the one the box held: the new one is what was typed.\n if (previous !== '' && value.length === previous.length + 1) {\n if (value.startsWith(previous)) typed = value.slice(previous.length);\n else if (value.endsWith(previous)) typed = value.slice(0, value.length - previous.length);\n }\n const text = otpChars(typed, settings.alphabet);\n if (text.length > 0) return write(chars, index, text, settings);\n if (value === '') {\n // The box was emptied (a cut, or a delete the browser did itself).\n const next = [...chars];\n next[index] = '';\n return { chars: next, focus: index };\n }\n return { chars, focus: index };\n}\n\n/** What pasting `text` into box `index` does: the code in it fills the field, wherever it is pasted. */\nexport function pasteStep(chars: readonly string[], index: number, text: string, settings: OtpSettings): OtpStep {\n const match = extractOtp(text, { length: settings.length, alphabet: settings.alphabet });\n if (match !== null) return write(chars, 0, Array.from(match.code), settings);\n const typed = otpChars(text, settings.alphabet);\n return typed.length > 0 && typed.length < settings.length ? write(chars, index, typed, settings) : { chars, focus: index };\n}\n\n/** What a navigation or deletion key does in box `index`. */\nexport function keyStep(chars: readonly string[], index: number, key: OtpKey, settings: OtpSettings): OtpStep {\n const last = settings.length - 1;\n switch (key) {\n case 'Backspace': {\n const next = [...chars];\n // An empty box: the one before it is cleared, as if the cursor were between them.\n const target = chars[index] === '' ? Math.max(0, index - 1) : index;\n next[target] = '';\n return { chars: next, focus: target };\n }\n case 'Delete': {\n const next = [...chars];\n next[index] = '';\n return { chars: next, focus: index };\n }\n case 'ArrowLeft':\n return { chars, focus: Math.max(0, index - 1) };\n case 'ArrowRight':\n return { chars, focus: Math.min(last, index + 1) };\n case 'Home':\n return { chars, focus: 0 };\n case 'End': {\n const empty = chars.indexOf('');\n return { chars, focus: empty === -1 ? last : empty };\n }\n }\n}\n\n/** A whole code set at once (from WebOTP, or by the app): its characters from the first box. */\nexport function setStep(code: string, settings: OtpSettings): OtpStep {\n return write(emptyChars(settings.length), 0, otpChars(code, settings.alphabet).slice(0, settings.length), settings);\n}\n","/**\n * Where filling a code from an SMS (the WebOTP API) stands.\n *\n * - `idle`: not asked for.\n * - `waiting`: the browser is waiting for an SMS that ends with `@your.host #code`.\n * - `received`: it came, and filled the field.\n * - `unsupported`: this browser has no WebOTP API (only Chrome on Android has).\n * - `failed`: the browser refused or gave up (no permission, a timeout, an insecure page).\n * - `aborted`: the field was detached before an SMS came.\n */\nexport type WebOtpStatus = 'idle' | 'waiting' | 'received' | 'unsupported' | 'failed' | 'aborted';\n\nexport type WebOtpResult = { readonly status: 'received'; readonly code: string } | { readonly status: 'unsupported' | 'failed' };\n\n/** The parts of the Credential Management API the WebOTP API adds. */\ninterface OtpCredentials {\n get(options: { readonly otp: { readonly transport: readonly string[] }; readonly signal: AbortSignal }): Promise<{ readonly code?: unknown } | null>;\n}\n\n/** Asks the browser for the code of an SMS sent to this device, until `signal` aborts. Never rejects. */\nexport async function receiveWebOtp(signal: AbortSignal): Promise<WebOtpResult> {\n const credentials = (globalThis as { navigator?: { credentials?: OtpCredentials } }).navigator?.credentials;\n if (typeof (globalThis as { OTPCredential?: unknown }).OTPCredential === 'undefined' || credentials === undefined) return { status: 'unsupported' };\n try {\n const credential = await credentials.get({ otp: { transport: ['sms'] }, signal });\n return typeof credential?.code === 'string' ? { status: 'received', code: credential.code } : { status: 'failed' };\n } catch {\n return { status: 'failed' };\n }\n}\n","import { copyFailure } from '../core/errors';\nimport { emptyChars, inputStep, keyStep, pasteStep, setStep, type OtpKey, type OtpSettings, type OtpStep } from './state';\nimport type { OtpAlphabet } from './normalize';\nimport { receiveWebOtp, type WebOtpStatus } from './web-otp';\n\nexport interface OtpFieldOptions {\n /** How many characters the code has: one box each. Default 6. */\n readonly length?: number;\n /** Default `'numeric'`. */\n readonly alphabet?: OtpAlphabet;\n /**\n * Each box's accessible name. Default `Digit 1 of 6` (`Character 1 of 6` for alphanumeric\n * codes). Name the group around the boxes too (`role=\"group\"` with a label).\n */\n readonly label?: (index: number, length: number) => string;\n /**\n * Fill the code from an SMS with the WebOTP API, where the browser has it (Chrome on\n * Android): the message must end with `@your.host #code`. Asked for when the boxes are\n * attached; cancelled when they are detached, or when the code is typed. Default `false`.\n */\n readonly webOtp?: boolean;\n /** Called when the value changes. */\n readonly onChange?: (snapshot: OtpSnapshot) => void;\n /** Called when every box is filled, with the code. Again after an edit fills them anew. */\n readonly onComplete?: (code: string) => void;\n}\n\nexport interface OtpSnapshot {\n /** Each box's character: `''` for an empty box. */\n readonly chars: readonly string[];\n /** The characters typed so far, in order, without gaps. */\n readonly value: string;\n /** Every box holds a character: `value` is the code. */\n readonly complete: boolean;\n /** Where filling the code from an SMS stands. `idle` unless `webOtp` is on. */\n readonly webOtp: WebOtpStatus;\n}\n\n/** The field's functions are bound: pass them around freely (`onClick={field.clear}`). */\nexport interface OtpField {\n /**\n * Wires up the boxes (one `<input>` each, in order): their typing, pasting, autofill,\n * keys, focus and attributes. Returns a function that undoes it. Boxes are wired to one\n * field at a time: attaching again first detaches the previous boxes.\n */\n readonly attach: (inputs: readonly HTMLInputElement[]) => () => void;\n /** The current state. A new object after each change, the same one otherwise. */\n readonly getSnapshot: () => OtpSnapshot;\n /** Calls `listener` after each change. Returns a function that stops it. */\n readonly subscribe: (listener: () => void) => () => void;\n /** Fills the boxes with `code` from the first (characters a code can't have are dropped). */\n readonly setValue: (code: string) => void;\n /** Empties every box and focuses the first. */\n readonly clear: () => void;\n /** Focuses the first empty box (or the last, when all are filled). */\n readonly focus: () => void;\n}\n\nconst KEYS: ReadonlySet<string> = new Set<OtpKey>(['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Home', 'End']);\n\n/**\n * A one-time code field over a row of single-character boxes, without a framework:\n * typing moves to the next box, Backspace to the one before; pasting a code, or an SMS\n * holding one, fills every box from any of them; an SMS autofill into the first box\n * (iOS, Android) fills them all. `useOtpField` is this, for React.\n *\n * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32.\n */\nexport function createOtpField(options: OtpFieldOptions = {}): OtpField {\n const length = options.length ?? 6;\n if (!Number.isInteger(length) || length < 1 || length > 32) throw copyFailure('invalid-payload', 'length must be a whole number from 1 to 32.');\n const settings: OtpSettings = { length, alphabet: options.alphabet ?? 'numeric' };\n const listeners = new Set<() => void>();\n let snapshot: OtpSnapshot = { chars: emptyChars(length), value: '', complete: false, webOtp: 'idle' };\n let boxes: readonly HTMLInputElement[] = [];\n let detach: (() => void) | null = null;\n let webOtpAbort: AbortController | null = null;\n\n /** Stops waiting for an SMS, with how it ended. */\n function stopWebOtp(status: WebOtpStatus): void {\n if (webOtpAbort === null) return;\n webOtpAbort.abort();\n webOtpAbort = null;\n publish({ ...snapshot, webOtp: status });\n }\n\n function publish(next: OtpSnapshot): void {\n snapshot = next;\n options.onChange?.(next);\n for (const listener of [...listeners]) listener();\n }\n\n function render(step: OtpStep, focus: boolean): void {\n boxes.forEach((box, index) => {\n const char = step.chars[index] as string;\n if (box.value !== char) box.value = char;\n });\n if (focus) {\n const box = boxes[step.focus];\n box?.focus();\n box?.select();\n }\n const same = step.chars.every((char, index) => char === snapshot.chars[index]);\n if (same) return;\n const value = step.chars.join('');\n const complete = step.chars.every((char) => char !== '');\n publish({ ...snapshot, chars: step.chars, value, complete });\n // Only a change gets here: a complete field's code is a new one.\n if (complete) {\n // The code is in: an SMS that comes later must not replace it.\n stopWebOtp('aborted');\n options.onComplete?.(value);\n }\n }\n\n function wire(inputs: readonly HTMLInputElement[]): () => void {\n const stops: (() => void)[] = [];\n const on = <K extends keyof HTMLElementEventMap>(target: HTMLInputElement, type: K, handler: (event: HTMLElementEventMap[K]) => void): void => {\n target.addEventListener(type, handler);\n stops.push(() => {\n target.removeEventListener(type, handler);\n });\n };\n const label = options.label ?? ((index: number, total: number) => `${settings.alphabet === 'numeric' ? 'Digit' : 'Character'} ${String(index + 1)} of ${String(total)}`);\n inputs.forEach((input, index) => {\n const restore = ['autocomplete', 'inputmode', 'aria-label', 'autocapitalize', 'spellcheck', 'pattern'].map((name) => [name, input.getAttribute(name)] as const);\n stops.push(() => {\n for (const [name, value] of restore) {\n if (value === null) input.removeAttribute(name);\n else input.setAttribute(name, value);\n }\n });\n // Only the first box takes the SMS autofill: browsers put the whole code there.\n input.setAttribute('autocomplete', index === 0 ? 'one-time-code' : 'off');\n input.setAttribute('inputmode', settings.alphabet === 'numeric' ? 'numeric' : 'text');\n input.setAttribute('aria-label', label(index, length));\n input.setAttribute('autocapitalize', settings.alphabet === 'numeric' ? 'off' : 'characters');\n input.setAttribute('spellcheck', 'false');\n if (settings.alphabet === 'numeric') input.setAttribute('pattern', '[0-9]*');\n else input.removeAttribute('pattern');\n input.value = snapshot.chars[index] as string;\n\n // Selecting the box's character on focus makes typing replace it.\n on(input, 'focus', () => {\n input.select();\n });\n on(input, 'keydown', (event) => {\n if (!KEYS.has(event.key) || event.altKey || event.ctrlKey || event.metaKey) return;\n event.preventDefault();\n render(keyStep(snapshot.chars, index, event.key as OtpKey, settings), true);\n });\n on(input, 'beforeinput', (event) => {\n // A delete in an empty box (soft keyboards send no Backspace key): go back, as Backspace does.\n if (event.inputType.startsWith('delete') && input.value === '') {\n event.preventDefault();\n render(keyStep(snapshot.chars, index, 'Backspace', settings), true);\n }\n });\n on(input, 'input', () => {\n // The box showed its character in `snapshot` until this input: that is what was there before.\n render(inputStep(snapshot.chars, index, snapshot.chars[index] as string, input.value, settings), true);\n });\n on(input, 'paste', (event) => {\n event.preventDefault();\n const text = event.clipboardData?.getData('text/plain') ?? '';\n render(pasteStep(snapshot.chars, index, text, settings), true);\n });\n });\n\n if (options.webOtp === true && !snapshot.complete) {\n const abort = new AbortController();\n webOtpAbort = abort;\n publish({ ...snapshot, webOtp: 'waiting' });\n void receiveWebOtp(abort.signal).then((result) => {\n if (abort.signal.aborted) return;\n webOtpAbort = null;\n if (result.status === 'received') render(setStep(result.code, settings), false);\n publish({ ...snapshot, webOtp: result.status });\n });\n }\n return () => {\n for (const stop of stops) stop();\n stopWebOtp('aborted');\n };\n }\n\n const field: OtpField = {\n attach: (inputs) => {\n detach?.();\n boxes = [...inputs];\n const undo = wire(boxes);\n let attached = true;\n detach = () => {\n if (!attached) return;\n attached = false;\n undo();\n boxes = [];\n detach = null;\n };\n return detach;\n },\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n setValue: (code) => {\n render(setStep(code, settings), false);\n },\n clear: () => {\n render({ chars: emptyChars(length), focus: 0 }, true);\n },\n focus: () => {\n const empty = snapshot.chars.indexOf('');\n boxes[empty === -1 ? length - 1 : empty]?.focus();\n },\n };\n return field;\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,iBAAiB,MAAc,UAA+B;CAC5E,MAAM,QAAQ,YAAY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AC3B;EACF;EACA,WAAW,SAAS;GAClB,OAAO,QAAQ,MAAM,QAAQ,GAAG,KAAK;EACvC;EACA,aAAa;GACX,OAAO;IAAE,OAAO,WAAW,MAAM;IAAG,OAAO;GAAE,GAAG,IAAI;EACtD;EACA,aAAa;GACX,MAAM,QAAQ,SAAS,MAAM,QAAQ,EAAE;GACvC,MAAM,UAAU,KAAK,SAAS,IAAI,MAAM,EAAE,MAAM;EAClD;CAES;AACb"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
2
|
+
const require_errors = require("./errors-DFmEAC4E.cjs");
|
|
3
3
|
const require_digits = require("./digits-BUEvSVrs.cjs");
|
|
4
4
|
//#region src/otp/normalize.ts
|
|
5
5
|
/**
|
|
@@ -139,21 +139,49 @@ function lowerSameLength(text) {
|
|
|
139
139
|
}
|
|
140
140
|
return out;
|
|
141
141
|
}
|
|
142
|
-
/**
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
142
|
+
/**
|
|
143
|
+
* Every keyword in `lower`, by position. Found once for the whole text, so each number's
|
|
144
|
+
* nearest keyword is a short look among its neighbours, not a new search.
|
|
145
|
+
*/
|
|
146
|
+
function keywordsIn(lower) {
|
|
147
|
+
const found = [];
|
|
147
148
|
for (const keyword of KEYWORDS) {
|
|
148
149
|
const whole = /^[a-z0-9 -]+$/.test(keyword);
|
|
149
|
-
for (let at =
|
|
150
|
-
if (whole && (/[a-z]/.test(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
150
|
+
for (let at = lower.indexOf(keyword); at !== -1; at = lower.indexOf(keyword, at + 1)) {
|
|
151
|
+
if (whole && (/[a-z]/.test(lower.charAt(at - 1)) || /[a-z]/.test(lower.charAt(at + keyword.length)))) continue;
|
|
152
|
+
found.push({
|
|
153
|
+
from: at,
|
|
154
|
+
to: at + keyword.length
|
|
155
|
+
});
|
|
155
156
|
}
|
|
156
157
|
}
|
|
158
|
+
return found.sort((a, b) => a.from - b.from);
|
|
159
|
+
}
|
|
160
|
+
/** The index of the first keyword that starts at or after `position` (binary search). */
|
|
161
|
+
function firstFrom(keywords, position) {
|
|
162
|
+
let low = 0;
|
|
163
|
+
let high = keywords.length;
|
|
164
|
+
while (low < high) {
|
|
165
|
+
const middle = low + high >>> 1;
|
|
166
|
+
if (keywords[middle].from < position) low = middle + 1;
|
|
167
|
+
else high = middle;
|
|
168
|
+
}
|
|
169
|
+
return low;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The distance from the number at `start`-`end` to the nearest keyword within 60 characters
|
|
173
|
+
* before it or 40 after it: words before count closer.
|
|
174
|
+
*/
|
|
175
|
+
function keywordDistance(keywords, start, end) {
|
|
176
|
+
const windowEnd = end + 40;
|
|
177
|
+
let best = Infinity;
|
|
178
|
+
for (let index = firstFrom(keywords, start - 60); index < keywords.length; index += 1) {
|
|
179
|
+
const { from, to } = keywords[index];
|
|
180
|
+
if (from >= windowEnd) break;
|
|
181
|
+
if (to > windowEnd) continue;
|
|
182
|
+
if (to <= start) best = Math.min(best, start - to);
|
|
183
|
+
else if (from >= end) best = Math.min(best, from - end + 10);
|
|
184
|
+
}
|
|
157
185
|
return best;
|
|
158
186
|
}
|
|
159
187
|
/** The origin-bound line of the WebOTP format: `@host #code`, last in the message. */
|
|
@@ -198,6 +226,7 @@ function extractOtp(text, options = {}) {
|
|
|
198
226
|
}
|
|
199
227
|
const lower = lowerSameLength(normalized);
|
|
200
228
|
const pattern = alphabet === "numeric" ? NUMERIC : ALPHANUMERIC;
|
|
229
|
+
const keywords = keywordsIn(lower);
|
|
201
230
|
const candidates = [];
|
|
202
231
|
for (const match of normalized.matchAll(pattern)) {
|
|
203
232
|
const raw = match[2];
|
|
@@ -206,7 +235,7 @@ function extractOtp(text, options = {}) {
|
|
|
206
235
|
if (!fits(code) || alphabet === "alphanumeric" && !/\d/.test(code) || excluded(normalized, lower, start, start + raw.length)) continue;
|
|
207
236
|
candidates.push({
|
|
208
237
|
code,
|
|
209
|
-
distance: keywordDistance(
|
|
238
|
+
distance: keywordDistance(keywords, start, start + raw.length)
|
|
210
239
|
});
|
|
211
240
|
}
|
|
212
241
|
const near = candidates.filter((candidate) => candidate.distance <= 60);
|
|
@@ -555,4 +584,4 @@ Object.defineProperty(exports, "normalizeOtpText", {
|
|
|
555
584
|
}
|
|
556
585
|
});
|
|
557
586
|
|
|
558
|
-
//# sourceMappingURL=field-
|
|
587
|
+
//# sourceMappingURL=field-CNEcZqa9.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"field-CNEcZqa9.cjs","names":["asciiDigits","copyFailure","copyFailure"],"sources":["../../src/otp/normalize.ts","../../src/otp/extract.ts","../../src/otp/state.ts","../../src/otp/web-otp.ts","../../src/otp/field.ts"],"sourcesContent":["import { asciiDigits } from '../core/digits';\n\n/** What a one-time code is made of. */\nexport type OtpAlphabet = 'numeric' | 'alphanumeric';\n\n/**\n * `text` with its digits in ASCII and, for alphanumeric codes, its letters in upper case:\n * full-width digits and letters, and Arabic-Indic, Devanagari and other scripts' digits,\n * become ASCII. Other characters are kept: callers decide what to drop.\n */\nexport function normalizeOtpText(text: string, alphabet: OtpAlphabet): string {\n const ascii = asciiDigits(text);\n return alphabet === 'alphanumeric' ? ascii.toUpperCase() : ascii;\n}\n\n/** Whether `char` (already normalized) can be part of a code. */\nexport function isOtpChar(char: string, alphabet: OtpAlphabet): boolean {\n return alphabet === 'numeric' ? char >= '0' && char <= '9' && char.length === 1 : /^[0-9A-Z]$/.test(char);\n}\n\n/** The characters of `text` that can be part of a code, normalized, in order. */\nexport function otpChars(text: string, alphabet: OtpAlphabet): string[] {\n return Array.from(normalizeOtpText(text, alphabet)).filter((char) => isOtpChar(char, alphabet));\n}\n","import { copyFailure } from '../core/errors';\nimport { normalizeOtpText, type OtpAlphabet } from './normalize';\n\n/** Text past this many characters is not read: a code is near the start of a message. */\nexport const OTP_SCAN_LENGTH = 100_000;\n\nexport interface ExtractOtpOptions {\n /** The code's length, or its range. Default 4 to 8. */\n readonly length?: number | { readonly min: number; readonly max: number };\n /** Default `'numeric'`. Alphanumeric codes are upper case: pasted letters are made so. */\n readonly alphabet?: OtpAlphabet;\n /**\n * Your site's host name, as in `example.com`. An origin-bound message (`@example.com #123456`,\n * the format the WebOTP API reads) for another host gives no code: it was not meant for you.\n */\n readonly domain?: string;\n}\n\n/**\n * Where the code was found.\n *\n * - `whole-text`: the text is the code (`482913`, `482 913`, `482-913`).\n * - `origin-bound`: the message's last line binds it to a site (`@example.com #482913`).\n * - `keyword`: next to a word such as \"code\", \"OTP\", \"verification\" or \"PIN\", in any of\n * many languages.\n * - `only-candidate`: the only number of the right length that is not a price, a date, a\n * time, a phone number or an order number.\n */\nexport type OtpSource = 'whole-text' | 'origin-bound' | 'keyword' | 'only-candidate';\n\nexport interface OtpMatch {\n /** The code: ASCII digits (and upper-case letters, for alphanumeric codes), no separators. */\n readonly code: string;\n readonly source: OtpSource;\n /** `medium` for `only-candidate`; `high` otherwise. */\n readonly confidence: 'high' | 'medium';\n /** The site an origin-bound message names; `null` otherwise. */\n readonly domain: string | null;\n}\n\ninterface Range {\n readonly min: number;\n readonly max: number;\n}\n\nfunction rangeOf(length: ExtractOtpOptions['length']): Range {\n const range = typeof length === 'number' ? { min: length, max: length } : (length ?? { min: 4, max: 8 });\n const valid = (value: number): boolean => Number.isInteger(value) && value >= 1 && value <= 32;\n if (!valid(range.min) || !valid(range.max) || range.min > range.max) {\n throw copyFailure('invalid-payload', 'length must be a whole number from 1 to 32, or a range of them.');\n }\n return range;\n}\n\n/**\n * Words next to a one-time code, lower case: English, Hindi, Spanish, Portuguese, French,\n * German, Italian, Dutch, Indonesian, Turkish, Polish, Russian, Ukrainian, Arabic, Hebrew,\n * Persian, Chinese, Japanese, Korean, Vietnamese and Thai.\n */\nconst KEYWORDS: readonly string[] = [\n 'code', 'otp', 'one-time', 'one time', 'passcode', 'password', 'pin', 'verification', 'verify', 'security', 'login', 'log in',\n 'sign-in', 'sign in', '2fa', 'two-factor', 'authentication', 'token',\n '\\u0913\\u091F\\u0940\\u092A\\u0940', '\\u0915\\u094B\\u0921', '\\u0938\\u0924\\u094D\\u092F\\u093E\\u092A\\u0928',\n 'c\\u00F3digo', 'codigo', 'clave', 'contrase\\u00F1a', 'senha', 'mot de passe', 'v\\u00E9rification', 'best\\u00E4tigungscode',\n 'kennwort', 'codice', 'verificatie', 'kode', 'kod', 'do\\u011Frulama', 'weryfikacyjny',\n '\\u043A\\u043E\\u0434', '\\u043F\\u0430\\u0440\\u043E\\u043B\\u044C', '\\u0440\\u0430\\u0437\\u043E\\u0432\\u044B\\u0439',\n '\\u0631\\u0645\\u0632', '\\u0643\\u0648\\u062F', '\\u0627\\u0644\\u062A\\u062D\\u0642\\u0642', '\\u05E7\\u05D5\\u05D3', '\\u06A9\\u062F',\n '\\u9A8C\\u8BC1\\u7801', '\\u9A57\\u8B49\\u78BC', '\\u6821\\u9A8C\\u7801', '\\u52D5\\u614B\\u78BC', '\\u8A8D\\u8A3C\\u30B3\\u30FC\\u30C9',\n '\\u78BA\\u8A8D\\u30B3\\u30FC\\u30C9', '\\u30EF\\u30F3\\u30BF\\u30A4\\u30E0', '\\u8A8D\\u8A3C\\u756A\\u53F7', '\\uC778\\uC99D\\uBC88\\uD638',\n '\\uC778\\uC99D', '\\uCF54\\uB4DC', 'm\\u00E3', 'x\\u00E1c th\\u1EF1c', '\\u0E23\\u0E2B\\u0E31\\u0E2A',\n];\n\n/** Codes that are not one-time codes, right before a number: postal codes, coupons, orders. */\nconst NOT_OTP = /(?:pin ?code|zip|postal|post code|promo|coupon|discount|voucher|referral|order|invoice|ref\\.?|account|a\\/c|flight|pnr|room|tracking)[\\s:#.-]{0,4}$/;\n\n/** Currencies and units around a number: it is an amount, not a code. */\nconst CURRENCY_BEFORE = /(?:[$\\u20AC\\u00A3\\u20B9\\u00A5\\u20A9\\u20BD\\u00A2]|\\brs\\.?|\\binr|\\busd|\\beur|\\bgbp)\\s?$/;\nconst AMOUNT_AFTER = /^\\s?(?:%|[$\\u20AC\\u00A3\\u20B9\\u00A5]|inr\\b|usd\\b|eur\\b|rs\\b|rupees\\b|dollars\\b|euros\\b)/;\n\nconst NUMERIC = /(^|[^\\p{L}\\p{N}_])(\\d{2,4}(?:[ -]\\d{2,4}){1,3}|\\d{1,12})(?![\\p{L}\\p{N}_])/gu;\nconst ALPHANUMERIC = /(^|[^\\p{L}\\p{N}_])([A-Z0-9]{2,6}(?:-[A-Z0-9]{2,6}){1,3}|[A-Z0-9]{1,12})(?![\\p{L}\\p{N}_])/gu;\n\nconst isDigit = (char: string | undefined): boolean => char !== undefined && char >= '0' && char <= '9';\n\n/**\n * Whether the number at `start`-`end` is something else: part of a longer number (a phone\n * number), a date, a time or a decimal, an amount, an order or reference number, or inside\n * a URL or an e-mail address.\n */\nfunction excluded(text: string, lower: string, start: number, end: number): boolean {\n const before = text[start - 1];\n const after = text[end];\n if ((before === ' ' || before === '-') && isDigit(text[start - 2])) return true;\n if ((after === ' ' || after === '-') && isDigit(text[end + 1])) return true;\n // A time, a date, a decimal or a version (`10:30`, `23/10`, `3.14`), and thousands (`2,500`).\n if (before !== undefined && ':/.'.includes(before) && isDigit(text[start - 2])) return true;\n if (after !== undefined && ':/.'.includes(after) && isDigit(text[end + 1])) return true;\n if ((before === ',' && isDigit(text[start - 2]) && /^\\d{3}(?!\\d)/.test(text.slice(start, start + 4))) || /^,\\d{3}(?!\\d)/.test(text.slice(end, end + 5))) return true;\n if (before === '+' || before === '#' || before === '(' || (before === ' ' && text[start - 2] === ')')) return true;\n const head = lower.slice(Math.max(0, start - 24), start);\n if (CURRENCY_BEFORE.test(head) || NOT_OTP.test(head) || AMOUNT_AFTER.test(lower.slice(end, end + 10))) return true;\n // The word around it, between white space (up to 256 characters each way, so a scan stays\n // linear): a URL, with a scheme or a bare host and path (`example.com/t/48291`), or an\n // e-mail address holds no code.\n let from = start;\n while (from > Math.max(0, start - 256) && !/\\s/.test(text[from - 1] as string)) from -= 1;\n let to = end;\n while (to < Math.min(text.length, end + 256) && !/\\s/.test(text[to] as string)) to += 1;\n return /@|:\\/\\/|www\\.|[\\p{L}\\p{N}-]\\.\\p{L}{2,}\\//iu.test(text.slice(from, to));\n}\n\n/** Lower case, one character for one: positions in it are positions in `text`. */\nfunction lowerSameLength(text: string): string {\n let out = '';\n for (const char of text) {\n const lower = char.toLowerCase();\n out += lower.length === char.length ? lower : char;\n }\n return out;\n}\n\n/** Where a keyword is in the text: its first character, and the one after its last. */\ninterface KeywordAt {\n readonly from: number;\n readonly to: number;\n}\n\n/**\n * Every keyword in `lower`, by position. Found once for the whole text, so each number's\n * nearest keyword is a short look among its neighbours, not a new search.\n */\nfunction keywordsIn(lower: string): KeywordAt[] {\n const found: KeywordAt[] = [];\n for (const keyword of KEYWORDS) {\n // Words in Latin script count only as whole words: `pin` is not in `spinning`.\n const whole = /^[a-z0-9 -]+$/.test(keyword);\n for (let at = lower.indexOf(keyword); at !== -1; at = lower.indexOf(keyword, at + 1)) {\n if (whole && (/[a-z]/.test(lower.charAt(at - 1)) || /[a-z]/.test(lower.charAt(at + keyword.length)))) continue;\n found.push({ from: at, to: at + keyword.length });\n }\n }\n return found.sort((a, b) => a.from - b.from);\n}\n\n/** The index of the first keyword that starts at or after `position` (binary search). */\nfunction firstFrom(keywords: readonly KeywordAt[], position: number): number {\n let low = 0;\n let high = keywords.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if ((keywords[middle] as KeywordAt).from < position) low = middle + 1;\n else high = middle;\n }\n return low;\n}\n\n/**\n * The distance from the number at `start`-`end` to the nearest keyword within 60 characters\n * before it or 40 after it: words before count closer.\n */\nfunction keywordDistance(keywords: readonly KeywordAt[], start: number, end: number): number {\n const windowEnd = end + 40;\n let best = Infinity;\n for (let index = firstFrom(keywords, start - 60); index < keywords.length; index += 1) {\n const { from, to } = keywords[index] as KeywordAt;\n if (from >= windowEnd) break;\n if (to > windowEnd) continue;\n // A keyword inside the number itself (as in `otp` of an alphanumeric code) does not count.\n if (to <= start) best = Math.min(best, start - to);\n else if (from >= end) best = Math.min(best, from - end + 10);\n }\n return best;\n}\n\n/** The origin-bound line of the WebOTP format: `@host #code`, last in the message. */\nconst ORIGIN_BOUND = /(?:^|\\n)@([a-z0-9.-]{1,253}(?::\\d{1,5})?) #([A-Za-z0-9]{1,32})(?: @[a-z0-9.-]{1,253}(?::\\d{1,5})?)?[ \\t]*$/i;\n\n/**\n * The one-time code in `text`: an SMS or e-mail people paste, or a code they copied. Digits\n * of any script and full-width characters are read as ASCII, and separators are dropped\n * (`482 913`, `482-913`).\n *\n * Prices, dates, times, phone numbers, order numbers and postal codes are never taken for a\n * code. When several numbers could be the code and no keyword points at one, the result is\n * `null`: guessing would fill in a wrong code.\n *\n * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32, or a reversed range.\n */\nexport function extractOtp(text: string, options: ExtractOtpOptions = {}): OtpMatch | null {\n const range = rangeOf(options.length);\n const alphabet = options.alphabet ?? 'numeric';\n const fits = (code: string): boolean => code.length >= range.min && code.length <= range.max && (alphabet === 'alphanumeric' || /^\\d+$/.test(code));\n const normalized = normalizeOtpText(text.slice(0, OTP_SCAN_LENGTH), alphabet);\n\n // The text is the code itself.\n const whole = normalized.trim();\n if (/^[0-9A-Z]{1,32}(?:[ -][0-9A-Z]{1,32}){0,7}$/.test(whole)) {\n const code = whole.replace(/[ -]/g, '');\n if (fits(code)) return { code, source: 'whole-text', confidence: 'high', domain: null };\n }\n\n // A message bound to a site, in the format the WebOTP API reads.\n // Read with its case kept: host names are lower case, and an alphanumeric code is upper-cased after.\n const bound = ORIGIN_BOUND.exec(normalizeOtpText(text.slice(0, OTP_SCAN_LENGTH), 'numeric').trimEnd());\n if (bound !== null) {\n const domain = (bound[1] as string).toLowerCase();\n const code = (bound[2] as string).toUpperCase();\n if (options.domain !== undefined && options.domain.toLowerCase() !== domain) return null;\n if (fits(code)) return { code, source: 'origin-bound', confidence: 'high', domain };\n }\n\n const lower = lowerSameLength(normalized);\n const pattern = alphabet === 'numeric' ? NUMERIC : ALPHANUMERIC;\n const keywords = keywordsIn(lower);\n const candidates: { readonly code: string; readonly distance: number }[] = [];\n for (const match of normalized.matchAll(pattern)) {\n const raw = match[2] as string;\n const start = match.index + (match[1] as string).length;\n const code = raw.replace(/[ -]/g, '');\n if (!fits(code) || (alphabet === 'alphanumeric' && !/\\d/.test(code)) || excluded(normalized, lower, start, start + raw.length)) continue;\n candidates.push({ code, distance: keywordDistance(keywords, start, start + raw.length) });\n }\n const near = candidates.filter((candidate) => candidate.distance <= 60);\n if (near.length > 0) {\n const best = near.reduce((a, b) => (b.distance < a.distance ? b : a));\n return { code: best.code, source: 'keyword', confidence: 'high', domain: null };\n }\n const distinct = new Set(candidates.map((candidate) => candidate.code));\n return distinct.size === 1 ? { code: [...distinct][0] as string, source: 'only-candidate', confidence: 'medium', domain: null } : null;\n}\n","import { extractOtp } from './extract';\nimport { otpChars, type OtpAlphabet } from './normalize';\n\n/** The characters in each box ('' for an empty one), and the box to focus next. */\nexport interface OtpStep {\n readonly chars: readonly string[];\n /** The box to focus after the change. */\n readonly focus: number;\n}\n\nexport interface OtpSettings {\n readonly length: number;\n readonly alphabet: OtpAlphabet;\n}\n\n/** Keys a code field handles itself. */\nexport type OtpKey = 'Backspace' | 'Delete' | 'ArrowLeft' | 'ArrowRight' | 'Home' | 'End';\n\nexport const emptyChars = (length: number): readonly string[] => Array.from({ length }, () => '');\n\nconst clamp = (index: number, length: number): number => Math.min(Math.max(index, 0), length - 1);\n\n/** `chars` with `text`'s characters written from `index` on, as far as they fit. */\nfunction write(chars: readonly string[], index: number, text: readonly string[], settings: OtpSettings): OtpStep {\n const next = [...chars];\n // A whole code (an SMS autofill into one box, a paste) fills the field from the start.\n const from = text.length >= settings.length ? 0 : clamp(index, settings.length);\n const count = Math.min(text.length, settings.length - from);\n for (let offset = 0; offset < count; offset += 1) next[from + offset] = text[offset] as string;\n return { chars: next, focus: clamp(from + count, settings.length) };\n}\n\n/**\n * What typing (or an autofill, or an input method) does to box `index`, whose value went\n * from `previous` to `value`. A character typed next to the one already there replaces it;\n * several characters fill the boxes after it; characters a code can't have are ignored.\n */\nexport function inputStep(chars: readonly string[], index: number, previous: string, value: string, settings: OtpSettings): OtpStep {\n let typed = value;\n // One character added beside the one the box held: the new one is what was typed.\n if (previous !== '' && value.length === previous.length + 1) {\n if (value.startsWith(previous)) typed = value.slice(previous.length);\n else if (value.endsWith(previous)) typed = value.slice(0, value.length - previous.length);\n }\n const text = otpChars(typed, settings.alphabet);\n if (text.length > 0) return write(chars, index, text, settings);\n if (value === '') {\n // The box was emptied (a cut, or a delete the browser did itself).\n const next = [...chars];\n next[index] = '';\n return { chars: next, focus: index };\n }\n return { chars, focus: index };\n}\n\n/** What pasting `text` into box `index` does: the code in it fills the field, wherever it is pasted. */\nexport function pasteStep(chars: readonly string[], index: number, text: string, settings: OtpSettings): OtpStep {\n const match = extractOtp(text, { length: settings.length, alphabet: settings.alphabet });\n if (match !== null) return write(chars, 0, Array.from(match.code), settings);\n const typed = otpChars(text, settings.alphabet);\n return typed.length > 0 && typed.length < settings.length ? write(chars, index, typed, settings) : { chars, focus: index };\n}\n\n/** What a navigation or deletion key does in box `index`. */\nexport function keyStep(chars: readonly string[], index: number, key: OtpKey, settings: OtpSettings): OtpStep {\n const last = settings.length - 1;\n switch (key) {\n case 'Backspace': {\n const next = [...chars];\n // An empty box: the one before it is cleared, as if the cursor were between them.\n const target = chars[index] === '' ? Math.max(0, index - 1) : index;\n next[target] = '';\n return { chars: next, focus: target };\n }\n case 'Delete': {\n const next = [...chars];\n next[index] = '';\n return { chars: next, focus: index };\n }\n case 'ArrowLeft':\n return { chars, focus: Math.max(0, index - 1) };\n case 'ArrowRight':\n return { chars, focus: Math.min(last, index + 1) };\n case 'Home':\n return { chars, focus: 0 };\n case 'End': {\n const empty = chars.indexOf('');\n return { chars, focus: empty === -1 ? last : empty };\n }\n }\n}\n\n/** A whole code set at once (from WebOTP, or by the app): its characters from the first box. */\nexport function setStep(code: string, settings: OtpSettings): OtpStep {\n return write(emptyChars(settings.length), 0, otpChars(code, settings.alphabet).slice(0, settings.length), settings);\n}\n","/**\n * Where filling a code from an SMS (the WebOTP API) stands.\n *\n * - `idle`: not asked for.\n * - `waiting`: the browser is waiting for an SMS that ends with `@your.host #code`.\n * - `received`: it came, and filled the field.\n * - `unsupported`: this browser has no WebOTP API (only Chrome on Android has).\n * - `failed`: the browser refused or gave up (no permission, a timeout, an insecure page).\n * - `aborted`: the field was detached before an SMS came.\n */\nexport type WebOtpStatus = 'idle' | 'waiting' | 'received' | 'unsupported' | 'failed' | 'aborted';\n\nexport type WebOtpResult = { readonly status: 'received'; readonly code: string } | { readonly status: 'unsupported' | 'failed' };\n\n/** The parts of the Credential Management API the WebOTP API adds. */\ninterface OtpCredentials {\n get(options: { readonly otp: { readonly transport: readonly string[] }; readonly signal: AbortSignal }): Promise<{ readonly code?: unknown } | null>;\n}\n\n/** Asks the browser for the code of an SMS sent to this device, until `signal` aborts. Never rejects. */\nexport async function receiveWebOtp(signal: AbortSignal): Promise<WebOtpResult> {\n const credentials = (globalThis as { navigator?: { credentials?: OtpCredentials } }).navigator?.credentials;\n if (typeof (globalThis as { OTPCredential?: unknown }).OTPCredential === 'undefined' || credentials === undefined) return { status: 'unsupported' };\n try {\n const credential = await credentials.get({ otp: { transport: ['sms'] }, signal });\n return typeof credential?.code === 'string' ? { status: 'received', code: credential.code } : { status: 'failed' };\n } catch {\n return { status: 'failed' };\n }\n}\n","import { copyFailure } from '../core/errors';\nimport { emptyChars, inputStep, keyStep, pasteStep, setStep, type OtpKey, type OtpSettings, type OtpStep } from './state';\nimport type { OtpAlphabet } from './normalize';\nimport { receiveWebOtp, type WebOtpStatus } from './web-otp';\n\nexport interface OtpFieldOptions {\n /** How many characters the code has: one box each. Default 6. */\n readonly length?: number;\n /** Default `'numeric'`. */\n readonly alphabet?: OtpAlphabet;\n /**\n * Each box's accessible name. Default `Digit 1 of 6` (`Character 1 of 6` for alphanumeric\n * codes). Name the group around the boxes too (`role=\"group\"` with a label).\n */\n readonly label?: (index: number, length: number) => string;\n /**\n * Fill the code from an SMS with the WebOTP API, where the browser has it (Chrome on\n * Android): the message must end with `@your.host #code`. Asked for when the boxes are\n * attached; cancelled when they are detached, or when the code is typed. Default `false`.\n */\n readonly webOtp?: boolean;\n /** Called when the value changes. */\n readonly onChange?: (snapshot: OtpSnapshot) => void;\n /** Called when every box is filled, with the code. Again after an edit fills them anew. */\n readonly onComplete?: (code: string) => void;\n}\n\nexport interface OtpSnapshot {\n /** Each box's character: `''` for an empty box. */\n readonly chars: readonly string[];\n /** The characters typed so far, in order, without gaps. */\n readonly value: string;\n /** Every box holds a character: `value` is the code. */\n readonly complete: boolean;\n /** Where filling the code from an SMS stands. `idle` unless `webOtp` is on. */\n readonly webOtp: WebOtpStatus;\n}\n\n/** The field's functions are bound: pass them around freely (`onClick={field.clear}`). */\nexport interface OtpField {\n /**\n * Wires up the boxes (one `<input>` each, in order): their typing, pasting, autofill,\n * keys, focus and attributes. Returns a function that undoes it. Boxes are wired to one\n * field at a time: attaching again first detaches the previous boxes.\n */\n readonly attach: (inputs: readonly HTMLInputElement[]) => () => void;\n /** The current state. A new object after each change, the same one otherwise. */\n readonly getSnapshot: () => OtpSnapshot;\n /** Calls `listener` after each change. Returns a function that stops it. */\n readonly subscribe: (listener: () => void) => () => void;\n /** Fills the boxes with `code` from the first (characters a code can't have are dropped). */\n readonly setValue: (code: string) => void;\n /** Empties every box and focuses the first. */\n readonly clear: () => void;\n /** Focuses the first empty box (or the last, when all are filled). */\n readonly focus: () => void;\n}\n\nconst KEYS: ReadonlySet<string> = new Set<OtpKey>(['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Home', 'End']);\n\n/**\n * A one-time code field over a row of single-character boxes, without a framework:\n * typing moves to the next box, Backspace to the one before; pasting a code, or an SMS\n * holding one, fills every box from any of them; an SMS autofill into the first box\n * (iOS, Android) fills them all. `useOtpField` is this, for React.\n *\n * @throws {CopyFailure} `invalid-payload` for a `length` that is not 1 to 32.\n */\nexport function createOtpField(options: OtpFieldOptions = {}): OtpField {\n const length = options.length ?? 6;\n if (!Number.isInteger(length) || length < 1 || length > 32) throw copyFailure('invalid-payload', 'length must be a whole number from 1 to 32.');\n const settings: OtpSettings = { length, alphabet: options.alphabet ?? 'numeric' };\n const listeners = new Set<() => void>();\n let snapshot: OtpSnapshot = { chars: emptyChars(length), value: '', complete: false, webOtp: 'idle' };\n let boxes: readonly HTMLInputElement[] = [];\n let detach: (() => void) | null = null;\n let webOtpAbort: AbortController | null = null;\n\n /** Stops waiting for an SMS, with how it ended. */\n function stopWebOtp(status: WebOtpStatus): void {\n if (webOtpAbort === null) return;\n webOtpAbort.abort();\n webOtpAbort = null;\n publish({ ...snapshot, webOtp: status });\n }\n\n function publish(next: OtpSnapshot): void {\n snapshot = next;\n options.onChange?.(next);\n for (const listener of [...listeners]) listener();\n }\n\n function render(step: OtpStep, focus: boolean): void {\n boxes.forEach((box, index) => {\n const char = step.chars[index] as string;\n if (box.value !== char) box.value = char;\n });\n if (focus) {\n const box = boxes[step.focus];\n box?.focus();\n box?.select();\n }\n const same = step.chars.every((char, index) => char === snapshot.chars[index]);\n if (same) return;\n const value = step.chars.join('');\n const complete = step.chars.every((char) => char !== '');\n publish({ ...snapshot, chars: step.chars, value, complete });\n // Only a change gets here: a complete field's code is a new one.\n if (complete) {\n // The code is in: an SMS that comes later must not replace it.\n stopWebOtp('aborted');\n options.onComplete?.(value);\n }\n }\n\n function wire(inputs: readonly HTMLInputElement[]): () => void {\n const stops: (() => void)[] = [];\n const on = <K extends keyof HTMLElementEventMap>(target: HTMLInputElement, type: K, handler: (event: HTMLElementEventMap[K]) => void): void => {\n target.addEventListener(type, handler);\n stops.push(() => {\n target.removeEventListener(type, handler);\n });\n };\n const label = options.label ?? ((index: number, total: number) => `${settings.alphabet === 'numeric' ? 'Digit' : 'Character'} ${String(index + 1)} of ${String(total)}`);\n inputs.forEach((input, index) => {\n const restore = ['autocomplete', 'inputmode', 'aria-label', 'autocapitalize', 'spellcheck', 'pattern'].map((name) => [name, input.getAttribute(name)] as const);\n stops.push(() => {\n for (const [name, value] of restore) {\n if (value === null) input.removeAttribute(name);\n else input.setAttribute(name, value);\n }\n });\n // Only the first box takes the SMS autofill: browsers put the whole code there.\n input.setAttribute('autocomplete', index === 0 ? 'one-time-code' : 'off');\n input.setAttribute('inputmode', settings.alphabet === 'numeric' ? 'numeric' : 'text');\n input.setAttribute('aria-label', label(index, length));\n input.setAttribute('autocapitalize', settings.alphabet === 'numeric' ? 'off' : 'characters');\n input.setAttribute('spellcheck', 'false');\n if (settings.alphabet === 'numeric') input.setAttribute('pattern', '[0-9]*');\n else input.removeAttribute('pattern');\n input.value = snapshot.chars[index] as string;\n\n // Selecting the box's character on focus makes typing replace it.\n on(input, 'focus', () => {\n input.select();\n });\n on(input, 'keydown', (event) => {\n if (!KEYS.has(event.key) || event.altKey || event.ctrlKey || event.metaKey) return;\n event.preventDefault();\n render(keyStep(snapshot.chars, index, event.key as OtpKey, settings), true);\n });\n on(input, 'beforeinput', (event) => {\n // A delete in an empty box (soft keyboards send no Backspace key): go back, as Backspace does.\n if (event.inputType.startsWith('delete') && input.value === '') {\n event.preventDefault();\n render(keyStep(snapshot.chars, index, 'Backspace', settings), true);\n }\n });\n on(input, 'input', () => {\n // The box showed its character in `snapshot` until this input: that is what was there before.\n render(inputStep(snapshot.chars, index, snapshot.chars[index] as string, input.value, settings), true);\n });\n on(input, 'paste', (event) => {\n event.preventDefault();\n const text = event.clipboardData?.getData('text/plain') ?? '';\n render(pasteStep(snapshot.chars, index, text, settings), true);\n });\n });\n\n if (options.webOtp === true && !snapshot.complete) {\n const abort = new AbortController();\n webOtpAbort = abort;\n publish({ ...snapshot, webOtp: 'waiting' });\n void receiveWebOtp(abort.signal).then((result) => {\n if (abort.signal.aborted) return;\n webOtpAbort = null;\n if (result.status === 'received') render(setStep(result.code, settings), false);\n publish({ ...snapshot, webOtp: result.status });\n });\n }\n return () => {\n for (const stop of stops) stop();\n stopWebOtp('aborted');\n };\n }\n\n const field: OtpField = {\n attach: (inputs) => {\n detach?.();\n boxes = [...inputs];\n const undo = wire(boxes);\n let attached = true;\n detach = () => {\n if (!attached) return;\n attached = false;\n undo();\n boxes = [];\n detach = null;\n };\n return detach;\n },\n getSnapshot: () => snapshot,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n setValue: (code) => {\n render(setStep(code, settings), false);\n },\n clear: () => {\n render({ chars: emptyChars(length), focus: 0 }, true);\n },\n focus: () => {\n const empty = snapshot.chars.indexOf('');\n boxes[empty === -1 ? length - 1 : empty]?.focus();\n },\n };\n return field;\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,iBAAiB,MAAc,UAA+B;CAC5E,MAAM,QAAQA,eAAAA,YAAY,IAAI;CAC9B,OAAO,aAAa,iBAAiB,MAAM,YAAY,IAAI;AAC7D;;AAGA,SAAgB,UAAU,MAAc,UAAgC;CACtE,OAAO,aAAa,YAAY,QAAQ,OAAO,QAAQ,OAAO,KAAK,WAAW,IAAI,aAAa,KAAK,IAAI;AAC1G;;AAGA,SAAgB,SAAS,MAAc,UAAiC;CACtE,OAAO,MAAM,KAAK,iBAAiB,MAAM,QAAQ,CAAC,CAAC,CAAC,QAAQ,SAAS,UAAU,MAAM,QAAQ,CAAC;AAChG;;;;ACnBA,MAAa,kBAAkB;AAyC/B,SAAS,QAAQ,QAA4C;CAC3D,MAAM,QAAQ,OAAO,WAAW,WAAW;EAAE,KAAK;EAAQ,KAAK;CAAO,IAAK,UAAU;EAAE,KAAK;EAAG,KAAK;CAAE;CACtG,MAAM,SAAS,UAA2B,OAAO,UAAU,KAAK,KAAK,SAAS,KAAK,SAAS;CAC5F,IAAI,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,MAAM,GAAG,KAAK,MAAM,MAAM,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AAM,WAAW;IAChD,IAAI,MAAM,OAAO,SAAS;IAC1B,cAAc;IACd,IAAI,OAAO,WAAW,YAAY,OAAO,QAAQ,OAAO,MAAM,QAAQ,GAAG,KAAK;IAC9E,QAAQ;KAAE,GAAG;KAAU,QAAQ,OAAO;IAAO,CAAC;GAChD,CAAC;EACH;EACA,aAAa;GACX,KAAK,MAAM,QAAQ,OAAO,KAAK;GAC/B,WAAW,SAAS;EACtB;CACF;CAmCA,OAAO;EAhCL,SAAS,WAAW;GAClB,SAAS;GACT,QAAQ,CAAC,GAAG,MAAM;GAClB,MAAM,OAAO,KAAK,KAAK;GACvB,IAAI,WAAW;GACf,eAAe;IACb,IAAI,CAAC,UAAU;IACf,WAAW;IACX,KAAK;IACL,QAAQ,CAAC;IACT,SAAS;GACX;GACA,OAAO;EACT;EACA,mBAAmB;EACnB,YAAY,aAAa;GACvB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,WAAW,SAAS;GAClB,OAAO,QAAQ,MAAM,QAAQ,GAAG,KAAK;EACvC;EACA,aAAa;GACX,OAAO;IAAE,OAAO,WAAW,MAAM;IAAG,OAAO;GAAE,GAAG,IAAI;EACtD;EACA,aAAa;GACX,MAAM,QAAQ,SAAS,MAAM,QAAQ,EAAE;GACvC,MAAM,UAAU,KAAK,SAAS,IAAI,MAAM,EAAE,MAAM;EAClD;CAES;AACb"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as CopySource, f as TextPayload, l as JsonPayload, o as HtmlPayload, r as CopyPayload, v as CopyError } from "./payload-
|
|
2
|
+
import { a as CopySource, f as TextPayload, l as JsonPayload, o as HtmlPayload, r as CopyPayload, v as CopyError } from "./payload-qkAWVXWA.cjs";
|
|
3
3
|
import { d as PasteReadOptions, m as PasteSource, o as DataTransferLike$1, p as PasteResult } from "./paste-reader-DcXnRWQr.cjs";
|
|
4
|
-
import { n as ClipboardAdapter } from "./clipboard-adapter-
|
|
5
|
-
import { n as PasteAdapter } from "./paste-adapter
|
|
4
|
+
import { n as ClipboardAdapter } from "./clipboard-adapter-CfaIbZpv.cjs";
|
|
5
|
+
import { n as PasteAdapter } from "./paste-adapter-B6eucH3E.cjs";
|
|
6
6
|
//#region src/core/mime.d.ts
|
|
7
7
|
/**
|
|
8
8
|
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
@@ -423,4 +423,4 @@ declare function canRetryPasteState(state: PasteState, maxRetries?: number): boo
|
|
|
423
423
|
declare function createPasteMachine(options?: PasteMachineOptionsSource): PasteMachine;
|
|
424
424
|
//#endregion
|
|
425
425
|
export { SVG_MIME_TYPE as $, RegisterDragCopyResult as A, CopyState as B, DragCopyPayload as C, DragEffectAllowed as D, DragCopyStatus as E, CopyIgnoredReason as F, IDLE_STATE as G, CopyingState as H, CopyMachine as I, createCopyMachine as J, IdleState as K, CopyMachineOptions as L, registerDragCopy as M, CopiedState as N, DragMultiPayload as O, CopyCancelReason as P, RasterImageMimeType as Q, CopyMachineOptionsSource as R, DragCopyPassReason as S, DragCopyState as T, DEFAULT_RESET_AFTER_MS as U, CopyStatus as V, ErrorState as W, CopyCoordinatorMember as X, CopyCoordinator as Y, createCopyCoordinator as Z, createPasteMachine as _, PasteEventLike as a, normalizeMimeType as at, DragCopyOptions as b, PasteMachine as c, PasteOutcome as d, WEB_CUSTOM_FORMAT_PREFIX as et, PasteReadState as f, canRetryPasteState as g, PasteStatus as h, PasteErrorState as i, normalizeClipboardType as it, applyDragCopy as j, DragStartEventLike as k, PasteMachineOptions as l, PasteState as m, PasteCancelReason as n, isWebCustomFormat as nt, PasteIdleState as o, sniffImageBytes as ot, PasteReadingState as p, canRetryState as q, PasteDropEventLike as r, matchesMimePattern as rt, PasteIgnoredReason as s, sniffImageType as st, PASTE_IDLE_STATE as t, isTextualMimeType as tt, PasteMachineOptionsSource as u, DragCopyDecision as v, DragCopySource as w, DragCopyOutcome as x, DragCopyItem as y, CopyOutcome as z };
|
|
426
|
-
//# sourceMappingURL=index-
|
|
426
|
+
//# sourceMappingURL=index-CqYzvxSN.d.cts.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
|
-
import { a as CopySource, f as TextPayload, l as JsonPayload, o as HtmlPayload, r as CopyPayload, v as CopyError } from "./payload-
|
|
2
|
+
import { a as CopySource, f as TextPayload, l as JsonPayload, o as HtmlPayload, r as CopyPayload, v as CopyError } from "./payload-CcvSx_Hq.js";
|
|
3
3
|
import { d as PasteReadOptions, m as PasteSource, o as DataTransferLike$1, p as PasteResult } from "./paste-reader-DcXnRWQr.js";
|
|
4
|
-
import { n as ClipboardAdapter } from "./clipboard-adapter-
|
|
5
|
-
import { n as PasteAdapter } from "./paste-adapter-
|
|
4
|
+
import { n as ClipboardAdapter } from "./clipboard-adapter-Chm6zq60.js";
|
|
5
|
+
import { n as PasteAdapter } from "./paste-adapter-CfIDT3mp.js";
|
|
6
6
|
//#region src/core/mime.d.ts
|
|
7
7
|
/**
|
|
8
8
|
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
@@ -423,4 +423,4 @@ declare function canRetryPasteState(state: PasteState, maxRetries?: number): boo
|
|
|
423
423
|
declare function createPasteMachine(options?: PasteMachineOptionsSource): PasteMachine;
|
|
424
424
|
//#endregion
|
|
425
425
|
export { SVG_MIME_TYPE as $, RegisterDragCopyResult as A, CopyState as B, DragCopyPayload as C, DragEffectAllowed as D, DragCopyStatus as E, CopyIgnoredReason as F, IDLE_STATE as G, CopyingState as H, CopyMachine as I, createCopyMachine as J, IdleState as K, CopyMachineOptions as L, registerDragCopy as M, CopiedState as N, DragMultiPayload as O, CopyCancelReason as P, RasterImageMimeType as Q, CopyMachineOptionsSource as R, DragCopyPassReason as S, DragCopyState as T, DEFAULT_RESET_AFTER_MS as U, CopyStatus as V, ErrorState as W, CopyCoordinatorMember as X, CopyCoordinator as Y, createCopyCoordinator as Z, createPasteMachine as _, PasteEventLike as a, normalizeMimeType as at, DragCopyOptions as b, PasteMachine as c, PasteOutcome as d, WEB_CUSTOM_FORMAT_PREFIX as et, PasteReadState as f, canRetryPasteState as g, PasteStatus as h, PasteErrorState as i, normalizeClipboardType as it, applyDragCopy as j, DragStartEventLike as k, PasteMachineOptions as l, PasteState as m, PasteCancelReason as n, isWebCustomFormat as nt, PasteIdleState as o, sniffImageBytes as ot, PasteReadingState as p, canRetryState as q, PasteDropEventLike as r, matchesMimePattern as rt, PasteIgnoredReason as s, sniffImageType as st, PASTE_IDLE_STATE as t, isTextualMimeType as tt, PasteMachineOptionsSource as u, DragCopyDecision as v, DragCopySource as w, DragCopyOutcome as x, DragCopyItem as y, CopyOutcome as z };
|
|
426
|
-
//# sourceMappingURL=index-
|
|
426
|
+
//# sourceMappingURL=index-Q_QeSwGr.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { k as OperationContext } from "./payload-
|
|
2
|
+
import { k as OperationContext } from "./payload-qkAWVXWA.cjs";
|
|
3
3
|
import { f as PasteReadResult, h as ResolvedPasteReadOptions, t as ClipboardItemLike } from "./paste-reader-DcXnRWQr.cjs";
|
|
4
4
|
//#region src/core/paste-adapter.d.ts
|
|
5
5
|
/** Minimal structural view of `navigator.clipboard` for reading. */
|
|
@@ -32,4 +32,4 @@ interface BrowserPasteAdapterOptions {
|
|
|
32
32
|
declare function createBrowserPasteAdapter(options?: BrowserPasteAdapterOptions): PasteAdapter;
|
|
33
33
|
//#endregion
|
|
34
34
|
export { createBrowserPasteAdapter as a, PasteEnvironment as i, PasteAdapter as n, PasteClipboardLike as r, BrowserPasteAdapterOptions as t };
|
|
35
|
-
//# sourceMappingURL=paste-adapter
|
|
35
|
+
//# sourceMappingURL=paste-adapter-B6eucH3E.d.cts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { k as OperationContext } from "./payload-
|
|
2
|
+
import { k as OperationContext } from "./payload-CcvSx_Hq.js";
|
|
3
3
|
import { f as PasteReadResult, h as ResolvedPasteReadOptions, t as ClipboardItemLike } from "./paste-reader-DcXnRWQr.js";
|
|
4
4
|
//#region src/core/paste-adapter.d.ts
|
|
5
5
|
/** Minimal structural view of `navigator.clipboard` for reading. */
|
|
@@ -32,4 +32,4 @@ interface BrowserPasteAdapterOptions {
|
|
|
32
32
|
declare function createBrowserPasteAdapter(options?: BrowserPasteAdapterOptions): PasteAdapter;
|
|
33
33
|
//#endregion
|
|
34
34
|
export { createBrowserPasteAdapter as a, PasteEnvironment as i, PasteAdapter as n, PasteClipboardLike as r, BrowserPasteAdapterOptions as t };
|
|
35
|
-
//# sourceMappingURL=paste-adapter-
|
|
35
|
+
//# sourceMappingURL=paste-adapter-CfIDT3mp.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
2
|
+
const require_errors = require("./errors-DFmEAC4E.cjs");
|
|
3
3
|
const require_mime = require("./mime--LB7kdqG.cjs");
|
|
4
4
|
//#region src/core/paste-reader.ts
|
|
5
5
|
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
@@ -286,4 +286,4 @@ Object.defineProperty(exports, "utf8ByteLength", {
|
|
|
286
286
|
}
|
|
287
287
|
});
|
|
288
288
|
|
|
289
|
-
//# sourceMappingURL=paste-reader-
|
|
289
|
+
//# sourceMappingURL=paste-reader-BWQaYNaV.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paste-reader-BWQaYNaV.cjs","names":["normalizeClipboardType","copyFailure","matchesMimePattern","isTextualMimeType","normalizeMimeType","sniffImageType"],"sources":["../../src/core/paste-reader.ts"],"sourcesContent":["import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES: number = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n"],"mappings":";;;;;AA4EA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;AAIA,MAAa,uBAA+D,uBAAO,OAAO,CAAC,MAAM,CAAU;AAC3G,MAAa,0BAAkC;AAC/C,MAAa,0BAA0B;AAEvC,MAAM,6BAA0D,IAAI,IAAI;CACtE,CAAC,QAAQ,YAAY;CACrB,CAAC,QAAQ,WAAW;CACpB,CAAC,SAAS,SAAS;CACnB,CAAC,OAAO,KAAK;AACf,CAAC;AAED,MAAM,aAAa;AAEnB,SAAS,eAAe,OAA+B;CACrD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,YAAY,WAAW,IAAI,KAAK;CACtC,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,MAAM,SAAS,IAAI,GAAG;EACxB,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,YAAY;EAC5C,OAAO,WAAW,KAAK,IAAI,IAAI,GAAG,KAAK,MAAM;CAC/C;CACA,OAAOA,aAAAA,uBAAuB,KAAK;AACrC;AAEA,SAAS,aA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;GAAE;GAAM,cAAc,KAAK;EAAa,CAAC;CAC9E;CACA,OAAO,KAAK,MAAM,GAAG,KAAK,MAAM,IAAI;AACtC;;;;;;AAOA,eAAsB,cACpB,SACA,QACA,SAC0B;CAC1B,MAAM,QAAqB,CAAC;CAC5B,MAAM,SAAiB,CAAC;CACxB,MAAM,QAAgB,CAAC;CACvB,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAE1B,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,EAAE,MAAM,SAAS;EAErB,IAAI,OAAO,SAAS,UAAU;GAE5B,IAAI,SAAS,cAAc,OAAO;QAC7B,IAAI,SAAS,aAAa,OAAO;EACxC,OAAO,IAAI,KAAK,WAAW,QAAQ,GAAG;GACpC,MAAM,SAAS,MAAME,aAAAA,eAAe,IAAI;GACxC,IAAI,WAAW,QAAQ,CAAC,WAAW,QAAQ,OAAO,GAAG;GACrD,IAAI,WAAW,MAAM;IACnB,OAAO,OAAO,OAAO,MAAM,MAAM;IACjC,OAAO;GACT;GACA,OAAO,KAAK,IAAI;EAClB;EAEA,IAAI,MAAM,MAAM,MAAM,KAAK,IAAY;EACvC,MAAM,KAAK;GAAE;GAAM;EAAK,CAAC;CAC3B;CAEA,IAAI,MAAM,WAAW,GACnB,MAAMJ,eAAAA,YAAY,cAAc,kDAAkD;CAEpF,OAAO;EAAE;EAAQ;EAAO;EAAM;EAAM;EAAQ;CAAM;AACpD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as copyFailure } from "./errors-
|
|
2
|
+
import { n as copyFailure } from "./errors-CT-FfUtU.js";
|
|
3
3
|
import { a as matchesMimePattern, l as sniffImageType, o as normalizeClipboardType, r as isTextualMimeType, s as normalizeMimeType } from "./mime-aa-HA2dm.js";
|
|
4
4
|
//#region src/core/paste-reader.ts
|
|
5
5
|
/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */
|
|
@@ -221,4 +221,4 @@ async function finalizePaste(entries, source, options) {
|
|
|
221
221
|
//#endregion
|
|
222
222
|
export { collectClipboardItems as a, finalizePaste as c, utf8ByteLength as d, canAcceptDrag as i, resolvePasteReadOptions as l, DEFAULT_PASTE_MAX_BYTES as n, completePasteResult as o, DEFAULT_PASTE_MAX_ITEMS as r, enforcePasteLimits as s, DEFAULT_PASTE_ACCEPT as t, snapshotDataTransfer as u };
|
|
223
223
|
|
|
224
|
-
//# sourceMappingURL=paste-reader-
|
|
224
|
+
//# sourceMappingURL=paste-reader-D6uOTDBM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paste-reader-D6uOTDBM.js","names":[],"sources":["../../src/core/paste-reader.ts"],"sourcesContent":["import { copyFailure } from './errors';\nimport { isTextualMimeType, matchesMimePattern, normalizeClipboardType, normalizeMimeType, sniffImageType } from './mime';\n\n/* ------------------------------------------------------------------ Types */\n\n/** Friendly names for the common cases. */\nexport type PasteAcceptShorthand = 'text' | 'html' | 'image' | 'any';\n\n/**\n * What a paste may contain, in any order: a shorthand, an exact MIME type\n * (`'image/png'`), a web custom format (`'web application/vnd.acme+json'`) or a\n * wildcard (`'image/*'`, `'*\\/*'`). `image/svg+xml` (scriptable XML), web custom\n * formats and `+json` types are only accepted when listed exactly.\n */\nexport type PasteAccept = PasteAcceptShorthand | `${string}/${string}`;\n\nexport interface PasteLimits {\n /**\n * Total size cap across all accepted items, in UTF-8 bytes. Strings are measured as\n * they would be encoded, matching `Blob.size`, so every paste path counts the same way.\n * Default 32 MiB.\n */\n readonly maxBytes?: number;\n /** Max number of accepted items (types + files). Default 32. */\n readonly maxItems?: number;\n}\n\nexport interface PasteReadOptions extends PasteLimits {\n /** Default `['text']` (plain text only): the safest choice. */\n readonly accept?: readonly PasteAccept[];\n}\n\n/** Validated, normalised options that adapters receive. */\nexport interface ResolvedPasteReadOptions {\n /** Normalised patterns: `type/subtype`, `type/*` or `*\\/*`. */\n readonly accept: readonly string[];\n readonly maxBytes: number;\n readonly maxItems: number;\n}\n\n/** Where the content came from: a Clipboard API read, a `paste` event, or a drag-and-drop `drop` event. */\nexport type PasteSource = 'clipboard' | 'event' | 'drop';\n\n/** One accepted clipboard entry. Textual types are decoded to `string`, everything else stays a `Blob`. */\nexport interface PasteItem {\n readonly type: string;\n readonly data: string | Blob;\n}\n\n/**\n * Everything the paste produced. Treat all of it as untrusted user input:\n * in particular never inject `html` into the DOM without sanitising it.\n */\nexport interface PasteResult {\n readonly source: PasteSource;\n /** Every accepted entry, in clipboard order. */\n readonly items: readonly PasteItem[];\n /** `text/plain`, when accepted and present. */\n readonly text: string | null;\n /** `text/html`, when accepted and present. UNTRUSTED markup: sanitise before rendering. */\n readonly html: string | null;\n /** Raster images, verified from their bytes (PNG, JPEG, GIF, WebP, AVIF, BMP), typed accordingly. */\n readonly images: readonly Blob[];\n /** Files from a paste event (e.g. copied in the OS file manager). Includes image files. */\n readonly files: readonly File[];\n /**\n * The entries of `files` that are also in `images`: verified image files, keeping their\n * names, ready for `FormData`. Derived by the paste machine, so it is always consistent.\n */\n readonly imageFiles: readonly File[];\n}\n\n/** What a {@link PasteAdapter} resolves with. `imageFiles` is derived from it by the machine. */\nexport type PasteReadResult = Omit<PasteResult, 'imageFiles'>;\n\n/** Adds the derived fields to an adapter's result. Any `imageFiles` it carried is recomputed. */\nexport function completePasteResult(result: PasteReadResult): PasteResult {\n const images = new Set<Blob>(result.images);\n return { ...result, imageFiles: result.files.filter((file) => images.has(file)) };\n}\n\n/* -------------------------------------------------------- Option handling */\n\nexport const DEFAULT_PASTE_ACCEPT: readonly PasteAccept[] = /* @__PURE__ */ Object.freeze(['text'] as const);\nexport const DEFAULT_PASTE_MAX_BYTES: number = 32 * 1024 * 1024;\nexport const DEFAULT_PASTE_MAX_ITEMS = 32;\n\nconst SHORTHANDS: ReadonlyMap<string, string> = /* @__PURE__ */ new Map([\n ['text', 'text/plain'],\n ['html', 'text/html'],\n ['image', 'image/*'],\n ['any', '*/*'],\n]);\n\nconst TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;\n\nfunction resolvePattern(entry: unknown): string | null {\n if (typeof entry !== 'string') return null;\n const shorthand = SHORTHANDS.get(entry);\n if (shorthand !== undefined) return shorthand;\n if (entry === '*/*') return entry;\n if (entry.endsWith('/*')) {\n const type = entry.slice(0, -2).toLowerCase();\n return TYPE_TOKEN.test(type) ? `${type}/*` : null;\n }\n return normalizeClipboardType(entry);\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\n/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */\nexport function resolvePasteReadOptions(options: PasteReadOptions = {}): ResolvedPasteReadOptions {\n const accept: string[] = [];\n for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {\n const pattern = resolvePattern(entry);\n if (pattern === null) throw copyFailure('invalid-payload', `Invalid \\`accept\\` entry: ${JSON.stringify(entry)}.`);\n if (!accept.includes(pattern)) accept.push(pattern);\n }\n if (accept.length === 0) throw copyFailure('invalid-payload', '`accept` must list at least one type.');\n return {\n accept,\n maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, 'maxBytes'),\n maxItems: resolveLimit(options.maxItems, DEFAULT_PASTE_MAX_ITEMS, 'maxItems'),\n };\n}\n\n/** Whether a normalised MIME type is allowed by the resolved `accept` list. */\nexport function isAccepted(mimeType: string, options: ResolvedPasteReadOptions): boolean {\n return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));\n}\n\n/* -------------------------------------------------------------- Entries */\n\n/** An accepted, not-yet-verified entry. */\nexport interface PasteEntry {\n readonly type: string;\n readonly data: string | Blob;\n /** Came from `DataTransfer.files`, i.e. `data` is a `File`. */\n readonly file: boolean;\n}\n\ninterface Budget {\n readonly charge: (size: number) => void;\n}\n\nfunction createBudget(options: ResolvedPasteReadOptions): Budget {\n let bytes = 0;\n let items = 0;\n return {\n charge: (size) => {\n items += 1;\n bytes += size;\n if (items > options.maxItems) {\n throw copyFailure('too-large', `The paste has more than ${String(options.maxItems)} accepted items.`);\n }\n if (bytes > options.maxBytes) {\n throw copyFailure('too-large', `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);\n }\n },\n };\n}\n\n/**\n * UTF-8 byte length of a string, without allocating an encoded copy.\n * Lone surrogates count 3 bytes, as `TextEncoder` / `Blob` encode them as U+FFFD.\n */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i += 1) {\n const unit = text.charCodeAt(i);\n if (unit < 0x80) bytes += 1;\n else if (unit < 0x800) bytes += 2;\n else if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i += 1;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** Strings are measured as UTF-8, the same unit `Blob.size` reports for clipboard items. */\nconst sizeOf = (data: string | Blob): number => (typeof data === 'string' ? utf8ByteLength(data) : data.size);\n\n/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */\nexport function enforcePasteLimits(entries: readonly PasteEntry[], options: ResolvedPasteReadOptions): void {\n const budget = createBudget(options);\n for (const entry of entries) budget.charge(sizeOf(entry.data));\n}\n\n/** Structural view of a `DataTransferItem`: only what is readable while dragging. */\nexport interface DataTransferItemLike {\n /** `'string'` or `'file'`. */\n readonly kind: string;\n readonly type: string;\n}\n\n/** Structural view of `DataTransfer` (paste and drop events). */\nexport interface DataTransferLike {\n readonly types: ArrayLike<string>;\n getData(format: string): string;\n readonly files?: ArrayLike<File> | null;\n readonly items?: ArrayLike<DataTransferItemLike> | null;\n}\n\n/**\n * Whether a drag in progress could drop anything `accept`s. Uses only what\n * browsers expose before the drop (item kinds and types, never the data).\n * A file whose type is not known yet (some browsers hide it while dragging)\n * counts as a maybe: the drop itself is checked against `accept`.\n */\nexport function canAcceptDrag(data: DataTransferLike, options: ResolvedPasteReadOptions): boolean {\n // Without an item list, a file is only known as the type \"Files\": treat it as an untyped file.\n const items = data.items ?? Array.from(data.types, (type) => (type === 'Files' ? { kind: 'file', type: '' } : { kind: 'string', type }));\n return Array.from(items).some(({ kind, type: raw }) => {\n const file = kind === 'file';\n const type = normalizeClipboardType(raw);\n if (type === null) return file;\n return (file || isTextualMimeType(type)) && isAccepted(type, options);\n });\n}\n\n/**\n * Synchronously copies the accepted parts of a paste event's `DataTransfer`.\n * It must run during the event: browsers empty the object afterwards.\n */\nexport function snapshotDataTransfer(data: DataTransferLike, options: ResolvedPasteReadOptions): PasteEntry[] {\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const raw of Array.from(data.types)) {\n const type = normalizeClipboardType(raw);\n // Binary types are delivered through `files`; `getData` only returns strings.\n if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n const text = data.getData(raw);\n if (text.length > 0) entries.push({ type, data: text, file: false });\n }\n\n for (const file of Array.from(data.files ?? [])) {\n const type = normalizeMimeType(file.type) ?? 'application/octet-stream';\n if (isAccepted(type, options)) entries.push({ type, data: file, file: true });\n }\n\n return entries;\n}\n\n/** Structural view of a `ClipboardItem` as returned by `navigator.clipboard.read()`. */\nexport interface ClipboardItemLike {\n readonly types: readonly string[];\n getType(type: string): Promise<Blob>;\n}\n\n/**\n * Reads the accepted types from `navigator.clipboard.read()` items, enforcing\n * the limits *before* decoding any text so an oversized paste is never buffered twice.\n */\nexport async function collectClipboardItems(\n items: readonly ClipboardItemLike[],\n options: ResolvedPasteReadOptions,\n signal?: AbortSignal,\n): Promise<PasteEntry[]> {\n const budget = createBudget(options);\n const entries: PasteEntry[] = [];\n const seen = new Set<string>();\n\n for (const item of items) {\n for (const raw of item.types) {\n const type = normalizeClipboardType(raw);\n if (type === null || seen.has(type) || !isAccepted(type, options)) continue;\n seen.add(type);\n\n let blob: Blob;\n try {\n blob = await item.getType(raw);\n } catch {\n // Chromium lists some types it then refuses to hand over; skip them, don't fail the paste.\n continue;\n }\n // Cancelled (reset, superseded, unmounted) while waiting: don't decode the rest.\n if (signal?.aborted) throw copyFailure('aborted', 'The paste was cancelled.');\n if (blob.size === 0) continue;\n budget.charge(blob.size);\n entries.push({ type, data: isTextualMimeType(type) ? await blob.text() : blob, file: false });\n }\n }\n return entries;\n}\n\n/* ------------------------------------------------------------ Finalising */\n\nfunction retype(entry: PasteEntry, data: Blob, type: string): Blob {\n if (entry.file) {\n const file = data as File;\n return new File([file], file.name, { type, lastModified: file.lastModified });\n }\n return data.slice(0, data.size, type);\n}\n\n/**\n * Verifies image bytes, then builds the result. Blobs that claim to be images\n * but aren't (or whose real format is not accepted) are dropped. Throws\n * `no-content` when nothing survives.\n */\nexport async function finalizePaste(\n entries: readonly PasteEntry[],\n source: PasteSource,\n options: ResolvedPasteReadOptions,\n): Promise<PasteReadResult> {\n const items: PasteItem[] = [];\n const images: Blob[] = [];\n const files: File[] = [];\n let text: string | null = null;\n let html: string | null = null;\n\n for (const entry of entries) {\n let { type, data } = entry;\n\n if (typeof data === 'string') {\n // Types are de-duplicated upstream, so each of these is seen at most once.\n if (type === 'text/plain') text = data;\n else if (type === 'text/html') html = data;\n } else if (type.startsWith('image/')) {\n const actual = await sniffImageType(data);\n if (actual === null || !isAccepted(actual, options)) continue;\n if (actual !== type) {\n data = retype(entry, data, actual);\n type = actual;\n }\n images.push(data);\n }\n\n if (entry.file) files.push(data as File);\n items.push({ type, data });\n }\n\n if (items.length === 0) {\n throw copyFailure('no-content', 'The content holds nothing that matches `accept`.');\n }\n return { source, items, text, html, images, files };\n}\n"],"mappings":";;;;;AA4EA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,SAAS,IAAI,IAAU,OAAO,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAQ,YAAY,OAAO,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI,CAAC;CAAE;AAClF;AA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