react-smart-copy 1.26.0 → 1.26.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/dist/capture.cjs +4 -4
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.js +4 -4
- package/dist/capture.js.map +1 -1
- package/dist/chunks/{clipboard-adapter-UIFc_Qso.cjs → clipboard-adapter-Bpuf5GmB.cjs} +3 -3
- package/dist/chunks/{clipboard-adapter-UIFc_Qso.cjs.map → clipboard-adapter-Bpuf5GmB.cjs.map} +1 -1
- package/dist/chunks/{clipboard-adapter-CmKDTFdO.js → clipboard-adapter-DyCmyZV9.js} +3 -3
- package/dist/chunks/{clipboard-adapter-CmKDTFdO.js.map → clipboard-adapter-DyCmyZV9.js.map} +1 -1
- package/dist/chunks/{contrast-C9d8QuaF.cjs → contrast-BatHkv8j.cjs} +2 -2
- package/dist/chunks/{contrast-C9d8QuaF.cjs.map → contrast-BatHkv8j.cjs.map} +1 -1
- package/dist/chunks/{contrast-DUaZq5SA.js → contrast-DnCunIr1.js} +2 -2
- package/dist/chunks/{contrast-DUaZq5SA.js.map → contrast-DnCunIr1.js.map} +1 -1
- package/dist/chunks/{core-D3GCO3yT.js → core-88XdCKaH.js} +5 -5
- package/dist/chunks/{core-D3GCO3yT.js.map → core-88XdCKaH.js.map} +1 -1
- package/dist/chunks/{core-t59Z4gdy.cjs → core-DF6jiigD.cjs} +5 -5
- package/dist/chunks/{core-t59Z4gdy.cjs.map → core-DF6jiigD.cjs.map} +1 -1
- package/dist/chunks/{deadline-j2hD7JKz.cjs → deadline-Cz6l-PDR.cjs} +14 -2
- package/dist/chunks/deadline-Cz6l-PDR.cjs.map +1 -0
- package/dist/chunks/{deadline-CbwnZ3Oq.js → deadline-DTAkra5B.js} +9 -3
- package/dist/chunks/deadline-DTAkra5B.js.map +1 -0
- package/dist/chunks/{errors-DFmEAC4E.cjs → errors-CF2EQNbc.cjs} +14 -2
- package/dist/chunks/errors-CF2EQNbc.cjs.map +1 -0
- package/dist/chunks/{errors-CT-FfUtU.js → errors-CGcMvbhJ.js} +9 -3
- package/dist/chunks/errors-CGcMvbhJ.js.map +1 -0
- package/dist/chunks/{field-B6SRWRbI.cjs → field-C8A5Yxln.cjs} +3 -3
- package/dist/chunks/{field-B6SRWRbI.cjs.map → field-C8A5Yxln.cjs.map} +1 -1
- package/dist/chunks/{field-DsRKkbav.js → field-CDCN9x0L.js} +3 -3
- package/dist/chunks/{field-DsRKkbav.js.map → field-CDCN9x0L.js.map} +1 -1
- package/dist/chunks/{limits-BP9R5wnr.js → limits-DvJZJn0V.js} +2 -2
- package/dist/chunks/{limits-BP9R5wnr.js.map → limits-DvJZJn0V.js.map} +1 -1
- package/dist/chunks/{limits-9wi1f6xT.cjs → limits-Vy-Xv26D.cjs} +2 -2
- package/dist/chunks/{limits-9wi1f6xT.cjs.map → limits-Vy-Xv26D.cjs.map} +1 -1
- package/dist/chunks/{paste-reader-BWQaYNaV.cjs → paste-reader-BL51Jt1y.cjs} +2 -2
- package/dist/chunks/{paste-reader-BWQaYNaV.cjs.map → paste-reader-BL51Jt1y.cjs.map} +1 -1
- package/dist/chunks/{paste-reader-D6uOTDBM.js → paste-reader-BpXOH_Px.js} +2 -2
- package/dist/chunks/{paste-reader-D6uOTDBM.js.map → paste-reader-BpXOH_Px.js.map} +1 -1
- package/dist/chunks/{payload-BrQWGwyx.js → payload-5uJedhwz.js} +2 -2
- package/dist/chunks/{payload-BrQWGwyx.js.map → payload-5uJedhwz.js.map} +1 -1
- package/dist/chunks/{payload-BWQ6sPtS.js → payload-DZnXoBmF.js} +3 -3
- package/dist/chunks/{payload-BWQ6sPtS.js.map → payload-DZnXoBmF.js.map} +1 -1
- package/dist/chunks/{payload-sBxkG7jH.cjs → payload-DjSSLonm.cjs} +2 -2
- package/dist/chunks/{payload-sBxkG7jH.cjs.map → payload-DjSSLonm.cjs.map} +1 -1
- package/dist/chunks/{payload-tTK6REua.cjs → payload-DzHhs6Ey.cjs} +3 -3
- package/dist/chunks/{payload-tTK6REua.cjs.map → payload-DzHhs6Ey.cjs.map} +1 -1
- package/dist/chunks/{share-nx7M4Z0t.cjs → share-Bk6MPmJg.cjs} +6 -6
- package/dist/chunks/{share-nx7M4Z0t.cjs.map → share-Bk6MPmJg.cjs.map} +1 -1
- package/dist/chunks/{share-CU91L4EK.js → share-tdlNQeje.js} +6 -6
- package/dist/chunks/{share-CU91L4EK.js.map → share-tdlNQeje.js.map} +1 -1
- package/dist/chunks/{url-BrhVUwn7.cjs → url-CL4YTCvM.cjs} +2 -2
- package/dist/chunks/{url-BrhVUwn7.cjs.map → url-CL4YTCvM.cjs.map} +1 -1
- package/dist/chunks/{url-COID0BLY.js → url-zB_krkuF.js} +2 -2
- package/dist/chunks/{url-COID0BLY.js.map → url-zB_krkuF.js.map} +1 -1
- package/dist/code.cjs +2 -2
- package/dist/code.js +2 -2
- package/dist/color.cjs +2 -2
- package/dist/color.js +2 -2
- package/dist/core.cjs +5 -5
- package/dist/core.js +5 -5
- package/dist/email.cjs +2 -2
- package/dist/email.js +2 -2
- package/dist/files.cjs +1 -1
- package/dist/files.js +1 -1
- package/dist/image.cjs +3 -3
- package/dist/image.cjs.map +1 -1
- package/dist/image.js +3 -3
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.js +7 -7
- package/dist/link.cjs +3 -3
- package/dist/link.js +3 -3
- package/dist/markdown.cjs +1 -1
- package/dist/markdown.js +1 -1
- package/dist/number.cjs +2 -2
- package/dist/number.js +2 -2
- package/dist/otp.cjs +1 -1
- package/dist/otp.js +1 -1
- package/dist/rich.cjs +3 -3
- package/dist/rich.js +3 -3
- package/dist/secrets.cjs +1 -1
- package/dist/secrets.js +1 -1
- package/dist/share.cjs +1 -1
- package/dist/share.js +1 -1
- package/dist/structured.cjs +2 -2
- package/dist/structured.js +2 -2
- package/dist/table.cjs +1 -1
- package/dist/table.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/deadline-CbwnZ3Oq.js.map +0 -1
- package/dist/chunks/deadline-j2hD7JKz.cjs.map +0 -1
- package/dist/chunks/errors-CT-FfUtU.js.map +0 -1
- package/dist/chunks/errors-DFmEAC4E.cjs.map +0 -1
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
|
|
2
|
+
//#region src/core/canvas-blocked.ts
|
|
3
|
+
/** A canvas that drew a cross-origin image without its consent refuses to hand out pixels: a `SecurityError`. */
|
|
4
|
+
function isCanvasBlocked(cause) {
|
|
5
|
+
return typeof cause === "object" && cause !== null && cause.name === "SecurityError";
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
2
8
|
//#region src/core/errors.ts
|
|
3
9
|
function createCopyError(type, message, cause) {
|
|
4
10
|
return cause === void 0 ? {
|
|
@@ -19,7 +25,7 @@ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
|
|
|
19
25
|
]);
|
|
20
26
|
/** Whether retrying the same payload could plausibly succeed. */
|
|
21
27
|
function isRetryableError(error) {
|
|
22
|
-
return RETRYABLE_ERRORS.has(error.type);
|
|
28
|
+
return RETRYABLE_ERRORS.has(error.type) && !(error.type === "blob-generation-failed" && isCanvasBlocked(error.cause));
|
|
23
29
|
}
|
|
24
30
|
/**
|
|
25
31
|
* Branded (not `instanceof`) so failures stay recognisable even when the core
|
|
@@ -145,6 +151,12 @@ Object.defineProperty(exports, "describePasteError", {
|
|
|
145
151
|
return describePasteError;
|
|
146
152
|
}
|
|
147
153
|
});
|
|
154
|
+
Object.defineProperty(exports, "isCanvasBlocked", {
|
|
155
|
+
enumerable: true,
|
|
156
|
+
get: function() {
|
|
157
|
+
return isCanvasBlocked;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
148
160
|
Object.defineProperty(exports, "isCopyFailure", {
|
|
149
161
|
enumerable: true,
|
|
150
162
|
get: function() {
|
|
@@ -164,4 +176,4 @@ Object.defineProperty(exports, "toCopyError", {
|
|
|
164
176
|
}
|
|
165
177
|
});
|
|
166
178
|
|
|
167
|
-
//# sourceMappingURL=errors-
|
|
179
|
+
//# sourceMappingURL=errors-CF2EQNbc.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-CF2EQNbc.cjs","names":[],"sources":["../../src/core/canvas-blocked.ts","../../src/core/errors.ts"],"sourcesContent":["/** A canvas that drew a cross-origin image without its consent refuses to hand out pixels: a `SecurityError`. */\nexport function isCanvasBlocked(cause: unknown): boolean {\n return typeof cause === 'object' && cause !== null && (cause as { name?: unknown }).name === 'SecurityError';\n}\n","import { isCanvasBlocked } from './canvas-blocked';\nimport 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 // A canvas that drew an image from another site cannot be read back, however often it is tried.\n return RETRYABLE_ERRORS.has(error.type) && !(error.type === 'blob-generation-failed' && isCanvasBlocked(error.cause));\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":";;;AACA,SAAgB,gBAAgB,OAAyB;CACvD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,SAAS;AAC/F;;;AC4CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAA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ACL,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,4 +1,10 @@
|
|
|
1
1
|
|
|
2
|
+
//#region src/core/canvas-blocked.ts
|
|
3
|
+
/** A canvas that drew a cross-origin image without its consent refuses to hand out pixels: a `SecurityError`. */
|
|
4
|
+
function isCanvasBlocked(cause) {
|
|
5
|
+
return typeof cause === "object" && cause !== null && cause.name === "SecurityError";
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
2
8
|
//#region src/core/errors.ts
|
|
3
9
|
function createCopyError(type, message, cause) {
|
|
4
10
|
return cause === void 0 ? {
|
|
@@ -19,7 +25,7 @@ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
|
|
|
19
25
|
]);
|
|
20
26
|
/** Whether retrying the same payload could plausibly succeed. */
|
|
21
27
|
function isRetryableError(error) {
|
|
22
|
-
return RETRYABLE_ERRORS.has(error.type);
|
|
28
|
+
return RETRYABLE_ERRORS.has(error.type) && !(error.type === "blob-generation-failed" && isCanvasBlocked(error.cause));
|
|
23
29
|
}
|
|
24
30
|
/**
|
|
25
31
|
* Branded (not `instanceof`) so failures stay recognisable even when the core
|
|
@@ -115,6 +121,6 @@ function describePasteError(error, source) {
|
|
|
115
121
|
return (source === "drop" ? DROP_DESCRIPTIONS[error.type] : void 0) ?? PASTE_DESCRIPTIONS[error.type];
|
|
116
122
|
}
|
|
117
123
|
//#endregion
|
|
118
|
-
export { describePasteError as a, toCopyError as c, describeCopyError as i, copyFailure as n, isCopyFailure as o, createCopyError as r, isRetryableError as s, CopyFailure as t };
|
|
124
|
+
export { describePasteError as a, toCopyError as c, describeCopyError as i, isCanvasBlocked as l, copyFailure as n, isCopyFailure as o, createCopyError as r, isRetryableError as s, CopyFailure as t };
|
|
119
125
|
|
|
120
|
-
//# sourceMappingURL=errors-
|
|
126
|
+
//# sourceMappingURL=errors-CGcMvbhJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-CGcMvbhJ.js","names":[],"sources":["../../src/core/canvas-blocked.ts","../../src/core/errors.ts"],"sourcesContent":["/** A canvas that drew a cross-origin image without its consent refuses to hand out pixels: a `SecurityError`. */\nexport function isCanvasBlocked(cause: unknown): boolean {\n return typeof cause === 'object' && cause !== null && (cause as { name?: unknown }).name === 'SecurityError';\n}\n","import { isCanvasBlocked } from './canvas-blocked';\nimport 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 // A canvas that drew an image from another site cannot be read back, however often it is tried.\n return RETRYABLE_ERRORS.has(error.type) && !(error.type === 'blob-generation-failed' && isCanvasBlocked(error.cause));\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":";;;AACA,SAAgB,gBAAgB,OAAyB;CACvD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,SAAS;AAC/F;;;AC4CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;AAEA,MAAM,mCAA+D,IAAI,IAAmB;CAC1F;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,iBAAiB,OAA2B;CAE1D,OAAO,iBAAiB,IAAI,MAAM,IAAI,KAAK,EAAE,MAAM,SAAS,4BAA4B,gBAAgB,MAAM,KAAK;AACrH;;;;;AAMA,MAAM,qBAAoC,OAAO,IAAI,8BAA8B;;AAWnF,IAAa,cAAb,cAAiC,MAAM;CAGrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EACvB,KAAK,OAAO;EACZ,KAAK,YAAY;EAEjB,KAAyC,sBAAsB;CACjE;AACF;AAEA,SAAgB,cAAc,OAAsC;CAClE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAuC,wBAAwB;AAEpE;;AAGA,S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;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,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
const require_errors = require("./errors-
|
|
3
|
-
const require_limits = require("./limits-
|
|
2
|
+
const require_errors = require("./errors-CF2EQNbc.cjs");
|
|
3
|
+
const require_limits = require("./limits-Vy-Xv26D.cjs");
|
|
4
4
|
const require_digits = require("./digits-BUEvSVrs.cjs");
|
|
5
5
|
//#region src/otp/normalize.ts
|
|
6
6
|
/**
|
|
@@ -595,4 +595,4 @@ Object.defineProperty(exports, "normalizeOtpText", {
|
|
|
595
595
|
}
|
|
596
596
|
});
|
|
597
597
|
|
|
598
|
-
//# sourceMappingURL=field-
|
|
598
|
+
//# sourceMappingURL=field-C8A5Yxln.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field-B6SRWRbI.cjs","names":["asciiDigits","copyFailure","positiveLimit","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 { positiveLimit } from '../core/limits';\nimport { normalizeOtpText, type OtpAlphabet } from './normalize';\n\n/** Text past this many characters is not read, unless `maxLength` allows it: a code is near the start of a message. */\nexport const DEFAULT_OTP_MAX_LENGTH = 100_000;\n/** @deprecated The old name of {@link DEFAULT_OTP_MAX_LENGTH}; removed in 2.0. */\nexport const OTP_SCAN_LENGTH: number = DEFAULT_OTP_MAX_LENGTH;\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 /** Read only this many characters of the text. Default {@link DEFAULT_OTP_MAX_LENGTH}. */\n readonly maxLength?: number;\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 * or a `maxLength` that is not a positive whole number.\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 scanned = text.slice(0, positiveLimit(options.maxLength, DEFAULT_OTP_MAX_LENGTH, 'maxLength'));\n const normalized = normalizeOtpText(scanned, 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(scanned, '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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AAC,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
|
+
{"version":3,"file":"field-C8A5Yxln.cjs","names":["asciiDigits","copyFailure","positiveLimit","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 { positiveLimit } from '../core/limits';\nimport { normalizeOtpText, type OtpAlphabet } from './normalize';\n\n/** Text past this many characters is not read, unless `maxLength` allows it: a code is near the start of a message. */\nexport const DEFAULT_OTP_MAX_LENGTH = 100_000;\n/** @deprecated The old name of {@link DEFAULT_OTP_MAX_LENGTH}; removed in 2.0. */\nexport const OTP_SCAN_LENGTH: number = DEFAULT_OTP_MAX_LENGTH;\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 /** Read only this many characters of the text. Default {@link DEFAULT_OTP_MAX_LENGTH}. */\n readonly maxLength?: number;\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 * or a `maxLength` that is not a positive whole number.\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 scanned = text.slice(0, positiveLimit(options.maxLength, DEFAULT_OTP_MAX_LENGTH, 'maxLength'));\n const normalized = normalizeOtpText(scanned, 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(scanned, '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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,MAAM,QAAQ,EAAE;GACvC,MAAM,UAAU,KAAK,SAAS,IAAI,MAAM,EAAE,MAAM;EAClD;CAES;AACb"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as copyFailure } from "./errors-
|
|
3
|
-
import { t as positiveLimit } from "./limits-
|
|
2
|
+
import { n as copyFailure } from "./errors-CGcMvbhJ.js";
|
|
3
|
+
import { t as positiveLimit } from "./limits-DvJZJn0V.js";
|
|
4
4
|
import { t as asciiDigits } from "./digits-DkU-O9_A.js";
|
|
5
5
|
//#region src/otp/normalize.ts
|
|
6
6
|
/**
|
|
@@ -566,4 +566,4 @@ function createOtpField(options = {}) {
|
|
|
566
566
|
//#endregion
|
|
567
567
|
export { normalizeOtpText as a, extractOtp as i, DEFAULT_OTP_MAX_LENGTH as n, OTP_SCAN_LENGTH as r, createOtpField as t };
|
|
568
568
|
|
|
569
|
-
//# sourceMappingURL=field-
|
|
569
|
+
//# sourceMappingURL=field-CDCN9x0L.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field-DsRKkbav.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 { positiveLimit } from '../core/limits';\nimport { normalizeOtpText, type OtpAlphabet } from './normalize';\n\n/** Text past this many characters is not read, unless `maxLength` allows it: a code is near the start of a message. */\nexport const DEFAULT_OTP_MAX_LENGTH = 100_000;\n/** @deprecated The old name of {@link DEFAULT_OTP_MAX_LENGTH}; removed in 2.0. */\nexport const OTP_SCAN_LENGTH: number = DEFAULT_OTP_MAX_LENGTH;\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 /** Read only this many characters of the text. Default {@link DEFAULT_OTP_MAX_LENGTH}. */\n readonly maxLength?: number;\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 * or a `maxLength` that is not a positive whole number.\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 scanned = text.slice(0, positiveLimit(options.maxLength, DEFAULT_OTP_MAX_LENGTH, 'maxLength'));\n const normalized = normalizeOtpText(scanned, 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(scanned, '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,IAAI;CAC9B,OAAO,aAAa,iBAAiB,MAAM,YAAY,IAAI;AAC7D;;AAGA,SAAgB,UAAU,MAAc,UAAgC;CACtE,OAAO,aAAa,YAAY,QAAQ,OA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vC;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
|
+
{"version":3,"file":"field-CDCN9x0L.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 { positiveLimit } from '../core/limits';\nimport { normalizeOtpText, type OtpAlphabet } from './normalize';\n\n/** Text past this many characters is not read, unless `maxLength` allows it: a code is near the start of a message. */\nexport const DEFAULT_OTP_MAX_LENGTH = 100_000;\n/** @deprecated The old name of {@link DEFAULT_OTP_MAX_LENGTH}; removed in 2.0. */\nexport const OTP_SCAN_LENGTH: number = DEFAULT_OTP_MAX_LENGTH;\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 /** Read only this many characters of the text. Default {@link DEFAULT_OTP_MAX_LENGTH}. */\n readonly maxLength?: number;\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 * or a `maxLength` that is not a positive whole number.\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 scanned = text.slice(0, positiveLimit(options.maxLength, DEFAULT_OTP_MAX_LENGTH, 'maxLength'));\n const normalized = normalizeOtpText(scanned, 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(scanned, '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,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;;;;AClBA,MAAa,yBAAyB;;AAEtC,MAAa,kBAA0B;AA2CvC,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,KA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AAQ,IAAI,gBAAgB;GAClC,cAAc;GACd,QAAQ;IAAE,GAAG;IAAU,QAAQ;GAAU,CAAC;GAC1C,cAAmB,MAAM,MAAM,CAAC,CAAC,MAAM,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,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { n as copyFailure } from "./errors-
|
|
2
|
+
import { n as copyFailure } from "./errors-CGcMvbhJ.js";
|
|
3
3
|
//#region src/core/limits.ts
|
|
4
4
|
/**
|
|
5
5
|
* A limit option read: `fallback` when it was not given, otherwise a positive whole number
|
|
@@ -15,4 +15,4 @@ function positiveLimit(value, fallback, name) {
|
|
|
15
15
|
//#endregion
|
|
16
16
|
export { positiveLimit as t };
|
|
17
17
|
|
|
18
|
-
//# sourceMappingURL=limits-
|
|
18
|
+
//# sourceMappingURL=limits-DvJZJn0V.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"limits-
|
|
1
|
+
{"version":3,"file":"limits-DvJZJn0V.js","names":[],"sources":["../../src/core/limits.ts"],"sourcesContent":["import { copyFailure } from './errors';\n\n/**\n * A limit option read: `fallback` when it was not given, otherwise a positive whole number\n * or `Infinity`. Every `max*` option of the library is checked by this one rule.\n *\n * @throws {CopyFailure} `invalid-payload` for zero, a negative or fractional number, or `NaN`.\n */\nexport function positiveLimit(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"],"mappings":";;;;;;;;;AAQA,SAAgB,cAAc,OAA2B,UAAkB,MAAsB;CAC/F,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,UAAU,YAAa,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAI,OAAO;CACzE,MAAM,YAAY,mBAAmB,KAAK,KAAK,sDAAsD,OAAO,KAAK,EAAE,GAAG;AACxH"}
|