From e1281114ef159edb6900d28a741b0f07dde5e7d0 Mon Sep 17 00:00:00 2001 From: William Chong Date: Fri, 28 Jun 2024 09:28:38 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=B8=20Add=20cbor=20format=20auto=20det?= =?UTF-8?q?ect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.vue | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/app.vue b/app.vue index ccea876..1e883a9 100644 --- a/app.vue +++ b/app.vue @@ -8,7 +8,7 @@
- @@ -73,9 +73,15 @@ useHead({ ], }) -onMounted(() => { - jsonToCbor() -}) +function isBase64(input: string) { + const base64Pattern = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; + return base64Pattern.test(input); +} + +function isHex(input: string) { + const hexPattern = /^[0-9A-Fa-f]+$/; + return hexPattern.test(input); +} function stringToBuffer(input: string) { if (cborEncoding.value === 'base64') { @@ -87,6 +93,11 @@ function stringToBuffer(input: string) { function cborToJson() { try { + if (isBase64(cborValue.value) && !isHex(cborValue.value)) { + cborEncoding.value = 'base64' + } else if (!isBase64(cborValue.value) && isHex(cborValue.value)) { + cborEncoding.value = 'hex' + } const cbor = decode(stringToBuffer(cborValue.value)) jsonValue.value = JSON.stringify(cbor, null, 2) } catch (e) { @@ -106,8 +117,6 @@ function jsonToCbor() { cborValue.value = (e as Error).message } } - -watch(cborEncoding, () => jsonToCbor())