UNPKG

1.46 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { assert, u8aToU8a } from '@polkadot/util'; // re-export the type so *.d.ts files don't have ../src imports
4
5export function createDecode({
6 coder,
7 ipfs
8}, validate) {
9 return (value, ipfsCompat) => {
10 validate(value, ipfsCompat);
11 return coder.decode(ipfs && ipfsCompat ? value.substr(1) : value);
12 };
13}
14export function createEncode({
15 coder,
16 ipfs
17}) {
18 return (value, ipfsCompat) => {
19 const out = coder.encode(u8aToU8a(value));
20 return ipfs && ipfsCompat ? `${ipfs}${out}` : out;
21 };
22}
23export function createIs(validate) {
24 return (value, ipfsCompat) => {
25 try {
26 return validate(value, ipfsCompat);
27 } catch (error) {
28 return false;
29 }
30 };
31}
32export function createValidate({
33 chars,
34 ipfs,
35 type
36}) {
37 return (value, ipfsCompat) => {
38 assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`);
39
40 if (ipfs && ipfsCompat) {
41 assert(value[0] === ipfs, () => `Expected ipfs-compatible ${type} to start with '${ipfs}'`);
42 }
43
44 for (let i = ipfsCompat ? 1 : 0; i < value.length; i++) {
45 assert(chars.includes(value[i]) || value[i] === '=' && (i === value.length - 1 || !chars.includes(value[i + 1])), () => `Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
46 }
47
48 return true;
49 };
50}
\No newline at end of file