typepki-strconv 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +22 -0
  3. package/dist/import/conv.d.mts +193 -0
  4. package/dist/import/conv.d.mts.map +1 -0
  5. package/dist/import/conv_arybuf.d.mts +30 -0
  6. package/dist/import/conv_arybuf.d.mts.map +1 -0
  7. package/dist/import/conv_ba.d.mts +27 -0
  8. package/dist/import/conv_ba.d.mts.map +1 -0
  9. package/dist/import/conv_ip.d.mts +69 -0
  10. package/dist/import/conv_ip.d.mts.map +1 -0
  11. package/dist/import/conv_iso88591.d.mts +19 -0
  12. package/dist/import/conv_iso88591.d.mts.map +1 -0
  13. package/dist/import/conv_pem.d.mts +109 -0
  14. package/dist/import/conv_pem.d.mts.map +1 -0
  15. package/dist/import/conv_ucs2.d.mts +14 -0
  16. package/dist/import/conv_ucs2.d.mts.map +1 -0
  17. package/dist/import/conv_uricmp.d.mts +29 -0
  18. package/dist/import/conv_uricmp.d.mts.map +1 -0
  19. package/dist/import/conv_zulu.d.mts +120 -0
  20. package/dist/import/conv_zulu.d.mts.map +1 -0
  21. package/dist/import/index.d.mts +22 -0
  22. package/dist/import/index.d.mts.map +1 -0
  23. package/dist/import/index.mjs +4 -0
  24. package/dist/require/index.cjs +4 -0
  25. package/dist/require/index.d.cts +2 -0
  26. package/dist/require/index.d.cts.map +1 -0
  27. package/package.json +72 -0
  28. package/src/conv.mts +367 -0
  29. package/src/conv.test.mts +99 -0
  30. package/src/conv_arybuf.mts +53 -0
  31. package/src/conv_arybuf.test.mts +16 -0
  32. package/src/conv_ba.mts +52 -0
  33. package/src/conv_ip.mts +226 -0
  34. package/src/conv_iso88591.mts +63 -0
  35. package/src/conv_pem.mts +160 -0
  36. package/src/conv_ucs2.mts +47 -0
  37. package/src/conv_uricmp.mts +48 -0
  38. package/src/conv_uricmp.test.mts +16 -0
  39. package/src/conv_zulu.mts +208 -0
  40. package/src/conv_zulu.test.mts +49 -0
  41. package/src/index.cts +1 -0
  42. package/src/index.mts +100 -0
  43. package/tsconfig.json +19 -0
@@ -0,0 +1,120 @@
1
+ /**
2
+ * GeneralizedTime or UTCTime string to milliseconds from Unix origin
3
+ * @param sZulu - GeneralizedTime or UTCTime string (ex. 20170412235959.384Z)
4
+ * @return milliseconds from Unix origin time (i.e. Jan 1, 1970 0:00:00 UTC)
5
+ *
6
+ * @description
7
+ * This function converts from GeneralizedTime string (i.e. YYYYMMDDHHmmSSZ) or
8
+ * UTCTime string (i.e. YYMMDDHHmmSSZ) to milliseconds from Unix origin time
9
+ * (i.e. Jan 1 1970 0:00:00 UTC).
10
+ * Argument string may have fraction of seconds and
11
+ * its length is one or more digits such as "20170410235959.1234567Z".
12
+ * As for UTCTime, if year "YY" is equal or less than 49 then it is 20YY.
13
+ * If year "YY" is equal or greater than 50 then it is 19YY.
14
+ *
15
+ * @example
16
+ * zulutomsec( "071231235959Z") -> 1199145599000 #Mon, 31 Dec 2007 23:59:59 GMT
17
+ * zulutomsec( "071231235959.1Z") -> 1199145599100 #Mon, 31 Dec 2007 23:59:59 GMT
18
+ * zulutomsec( "071231235959.12345Z") -> 1199145599123 #Mon, 31 Dec 2007 23:59:59 GMT
19
+ * zulutomsec("20071231235959Z") -> 1199145599000 #Mon, 31 Dec 2007 23:59:59 GMT
20
+ * zulutomsec( "931231235959Z") -> -410227201000 #Mon, 31 Dec 1956 23:59:59 GMT
21
+ */
22
+ export declare function zulutomsec(sZulu: string): number;
23
+ /**
24
+ * Unix origin milliseconds GeneralizedTime string
25
+ * @param n - milliseconds from Unix origin time (i.e. Jan 1, 1970 0:00:00 UTC)
26
+ * @return GeneralizedTime string (ex. 20170412235959.384Z)
27
+ *
28
+ * @description
29
+ * This function converts from milliseconds of Unix origin time (ex. 1199145599000
30
+ * for 31 Dec 2007 23:59:59 GMT) to GeneralizedTime string (i.e. YYYYMMDDHHmmSSZ).
31
+ * The result string may have a fraction of second.
32
+ *
33
+ * @example
34
+ * msectozulu(1199145599000) -> "20071231235959Z" #Mon, 31 Dec 2007 23:59:59 GMT
35
+ * msectozulu(1199145599100) -> "20071231235959.1Z" #Mon, 31 Dec 2007 23:59:59.1 GMT
36
+ * msectozulu(1199145599123) -> "20071231235959.123Z" #Mon, 31 Dec 2007 23:59:59.123 GMT
37
+ */
38
+ export declare function msectozulu(n: number): string;
39
+ /**
40
+ * GeneralizedTime or UTCTime string to seconds from Unix origin
41
+ * @param s - GeneralizedTime or UTCTime string (ex. 20170412235959.384Z)
42
+ * @return seconds from Unix origin time (i.e. Jan 1, 1970 0:00:00 UTC)
43
+ *
44
+ * @description
45
+ * This function converts from GeneralizedTime string (i.e. YYYYMMDDHHmmSSZ) or
46
+ * UTCTime string (i.e. YYMMDDHHmmSSZ) to seconds from Unix origin time
47
+ * (i.e. Jan 1 1970 0:00:00 UTC). Argument string may have fraction of seconds
48
+ * however result value will be omitted.
49
+ * As for UTCTime, if year "YY" is equal or less than 49 then it is 20YY.
50
+ * If year "YY" is equal or greater than 50 then it is 19YY.
51
+ *
52
+ * @example
53
+ * zulutosec( "071231235959Z") -> 1199145599 #Mon, 31 Dec 2007 23:59:59 GMT
54
+ * zulutosec( "071231235959.1Z") -> 1199145599 #Mon, 31 Dec 2007 23:59:59 GMT
55
+ * zulutosec("20071231235959Z") -> 1199145599 #Mon, 31 Dec 2007 23:59:59 GMT
56
+ */
57
+ export declare function zulutosec(s: string): number;
58
+ /**
59
+ * GeneralizedTime or UTCTime string to Date object
60
+ * @param s - GeneralizedTime or UTCTime string (ex. 20170412235959.384Z)
61
+ * @return Date object for specified time
62
+ *
63
+ * @description
64
+ * This function converts from GeneralizedTime string (i.e. YYYYMMDDHHmmSSZ) or
65
+ * UTCTime string (i.e. YYMMDDHHmmSSZ) to Date object.
66
+ * Argument string may have fraction of seconds and
67
+ * its length is one or more digits such as "20170410235959.1234567Z".
68
+ * As for UTCTime, if year "YY" is equal or less than 49 then it is 20YY.
69
+ * If year "YY" is equal or greater than 50 then it is 19YY.
70
+ *
71
+ * @example
72
+ * zulutodate( "071231235959Z").toUTCString() -> "Mon, 31 Dec 2007 23:59:59 GMT"
73
+ * zulutodate( "071231235959.1Z").toUTCString() -> "Mon, 31 Dec 2007 23:59:59 GMT"
74
+ * zulutodate("20071231235959Z").toUTCString() -> "Mon, 31 Dec 2007 23:59:59 GMT"
75
+ * zulutodate( "071231235959.34Z").getMilliseconds() -> 340
76
+ */
77
+ export declare function zulutodate(s: string): Date;
78
+ /**
79
+ * Date object to zulu time string
80
+ * @param d - Date object for specified time
81
+ * @param flagUTCTime - if this is true year will be YY otherwise YYYY
82
+ * @param flagMilli - if this is true result concludes milliseconds
83
+ * @return GeneralizedTime or UTCTime string (ex. 20170412235959.384Z)
84
+ *
85
+ * @description
86
+ * This function converts from Date object to GeneralizedTime string (i.e. YYYYMMDDHHmmSSZ) or
87
+ * UTCTime string (i.e. YYMMDDHHmmSSZ).
88
+ * As for UTCTime, if year "YY" is equal or less than 49 then it is 20YY.
89
+ * If year "YY" is equal or greater than 50 then it is 19YY.
90
+ * If flagMilli is true its result concludes milliseconds such like
91
+ * "20170520235959.42Z".
92
+ *
93
+ * @example
94
+ * d = new Date(Date.UTC(2017,4,20,23,59,59,670));
95
+ * datetozulu(d) -> "20170520235959Z"
96
+ * datetozulu(d, true) -> "170520235959Z"
97
+ * datetozulu(d, false, true) -> "20170520235959.67Z"
98
+ */
99
+ export declare function datetozulu(d: Date, flagUTCTime?: boolean, flagMilli?: boolean): string;
100
+ /**
101
+ * GeneralizedTime or UTCTime string to GeneralizedTime
102
+ * @param s - GeneralizedTime or UTCTime string (ex. 20170412235959.384Z)
103
+ * @return GeneralizedTime
104
+ *
105
+ * @description
106
+ * This function converts UTCTime string (i.e. YYMMDDHHmmSSZ ) to
107
+ * GeneralizedTime (YYYYMMDDHHmmSSZ) when the argument 's' is UTCTime.
108
+ * Argument string may have fraction of seconds and
109
+ * its length is one or more digits such as "170410235959.1234567Z".
110
+ * As for UTCTime, if year "YY" is equal or less than 49 then it is 20YY.
111
+ * If year "YY" is equal or greater than 50 then it is 19YY.
112
+ *
113
+ * @example
114
+ * timetogen( "071231235959Z") -> "20071231235959Z"
115
+ * timetogen( "971231235959Z") -> "19971231235959Z"
116
+ * timetogen("20071231235959Z") -> "20071231235959Z"
117
+ * timetogen( "971231235959.123Z") -> "19971231235959.123Z"
118
+ */
119
+ export declare function timetogen(s: string): string;
120
+ //# sourceMappingURL=conv_zulu.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conv_zulu.d.mts","sourceRoot":"","sources":["../../src/conv_zulu.mts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAkChD;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAY5C;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3C;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAE1C;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,UAAU,CACxB,CAAC,EAAE,IAAI,EACP,WAAW,UAAQ,EACnB,SAAS,UAAQ,GAChB,MAAM,CAyBR;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAK3C"}
@@ -0,0 +1,22 @@
1
+ declare const VERSION: string;
2
+ export { VERSION };
3
+ import { BAtohex, BAtos, stoBA, stohex } from "./conv_ba.mts";
4
+ export { stohex, BAtohex, stoBA, BAtos };
5
+ import { Dictionary, aryval, b64tob64u, b64tohex, b64toutf8, b64utob64, b64utohex, b64utoutf8, binstrtobitstr, bitstrtobinstr, hextob64, hextob64u, hextorstr, hextoutf8, inttobitstr, namearraytobinstr, rstrtob64, rstrtohex, strpad, utf8tob64, utf8tob64u, utf8tohex } from "./conv.mts";
6
+ export { b64tohex, hextob64, b64toutf8, utf8tob64, b64utoutf8, utf8tob64u, hextoutf8, utf8tohex, b64utohex, hextob64u, b64tob64u, b64utob64, hextorstr, rstrtohex, binstrtobitstr, bitstrtobinstr, inttobitstr, strpad, namearraytobinstr, aryval, rstrtob64, };
7
+ export type { Dictionary };
8
+ import { iso88591hextoutf8, utf8toiso88591hex } from "./conv_iso88591.mts";
9
+ export { iso88591hextoutf8, utf8toiso88591hex };
10
+ import { b64nltohex, b64topem, foldnl, hextopem, pemtob64, pemtohex } from "./conv_pem.mts";
11
+ export { pemtohex, hextopem, pemtob64, b64topem, b64nltohex, foldnl };
12
+ import { ArrayBuffertohex, hextoArrayBuffer } from "./conv_arybuf.mts";
13
+ export { hextoArrayBuffer, ArrayBuffertohex };
14
+ import { datetozulu, msectozulu, timetogen, zulutodate, zulutomsec, zulutosec } from "./conv_zulu.mts";
15
+ export { zulutomsec, msectozulu, zulutosec, zulutodate, datetozulu, timetogen };
16
+ import { encodeURIComponentAll, hextouricmp, uricmptohex } from "./conv_uricmp.mts";
17
+ export { encodeURIComponentAll, hextouricmp, uricmptohex };
18
+ import { hextoip, hextoipv6, ipnetmask, ipprefixlen, iptohex, ipv6tohex } from "./conv_ip.mts";
19
+ export { ipv6tohex, hextoipv6, hextoip, iptohex, ipprefixlen, ipnetmask };
20
+ import { ucs2hextoutf8 } from "./conv_ucs2.mts";
21
+ export { ucs2hextoutf8 };
22
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/index.mts"],"names":[],"mappings":"AAAA,QAAA,MAAM,OAAO,EAAE,MAA+D,CAAC;AAC/E,OAAO,EAAE,OAAO,EAAE,CAAC;AAEnB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAEzC,OAAO,EACL,UAAU,EACV,MAAM,EACN,SAAS,EACT,QAAQ,EACR,SAAS,EACT,SAAS,EACT,SAAS,EACT,UAAU,EACV,cAAc,EACd,cAAc,EACd,QAAQ,EACR,SAAS,EACT,SAAS,EACT,SAAS,EACT,WAAW,EACX,iBAAiB,EACjB,SAAS,EACT,SAAS,EACT,MAAM,EACN,SAAS,EACT,UAAU,EACV,SAAS,EACV,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,SAAS,EACT,UAAU,EACV,UAAU,EACV,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,cAAc,EACd,cAAc,EACd,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,MAAM,EACN,SAAS,GACV,CAAC;AACF,YAAY,EAAE,UAAU,EAAE,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,CAAC;AAEhD,OAAO,EACL,UAAU,EACV,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,QAAQ,EACT,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;AAEtE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;AAE9C,OAAO,EACL,UAAU,EACV,UAAU,EACV,SAAS,EACT,UAAU,EACV,UAAU,EACV,SAAS,EACV,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;AAEhF,OAAO,EACL,qBAAqB,EACrB,WAAW,EACX,WAAW,EACZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC;AAE3D,OAAO,EACL,OAAO,EACP,SAAS,EACT,SAAS,EACT,WAAW,EACX,OAAO,EACP,SAAS,EACV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC;AAE1E,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1,4 @@
1
+ function x(r){return C(B(r))}function C(r){let t="";for(let e=0;e<r.length;e++){let n=r[e].toString(16);n.length===1&&(n=`0${n}`),t=t+n}return t}function B(r){let t=new Array;for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}function z(r){let t="";for(let e=0;e<r.length;e++)t=t+String.fromCharCode(r[e]);return t}function a(r){return Buffer.from(r,"base64").toString("hex")}function h(r){return Buffer.from(r,"hex").toString("base64")}function j(r){return Buffer.from(r,"base64").toString("utf8")}function N(r){return Buffer.from(r,"utf8").toString("base64")}function k(r){return Buffer.from($(r),"base64").toString("utf8")}function F(r){return b(Buffer.from(r,"utf8").toString("base64"))}function c(r){return Buffer.from(r,"hex").toString("utf8")}function m(r){return Buffer.from(r,"utf8").toString("hex")}function R(r){return a($(r))}function Z(r){return b(h(r))}function G(r){let t="";for(let e=0;e<r.length;e+=2){let n=parseInt(r.substr(e,2),16);t+=String.fromCharCode(n)}return t}function V(r){let t="";for(let e=0;e<r.length;e++)t+=`0${r.charCodeAt(e).toString(16)}`.slice(-2);return t}function _(r){return Buffer.from(r).toString("base64")}function b(r){let t=r;return t=t.replace(/\=/g,""),t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_"),t}function $(r){let t=r;return t.length%4===2?t=`${t}==`:t.length%4===3&&(t=`${t}=`),t=t.replace(/-/g,"+"),t=t.replace(/_/g,"/"),t}var L=r=>{if(r.match(/^[01]+$/)==null)return null;try{let t=parseInt(r,2);return E(t)}catch{return null}};function O(r){if(typeof r!="string"||r.length%2!==0||!r.match(/^[0-9a-f]+$/))return null;try{let t=parseInt(r.substr(0,2),16);if(t<0||7<t)return null;let e=r.substr(2),n="";for(let i=0;i<e.length;i+=2){let o=e.substr(i,2),s=parseInt(o,16).toString(2);s=`0000000${s}`.slice(-8),n+=s}return n.substr(0,n.length-t)}catch{return null}}function E(r){if(typeof r!="number"||r<0)return null;let t=Number(r).toString(2),e=8-t.length%8;e===8&&(e=0),t=t+U("",e,"0");let n=parseInt(t,2).toString(16);return n.length%2===1&&(n=`0${n}`),`0${e}`+n}var U=(r,t,e)=>{let n=e===void 0?"0":e;return r.length>=t?r:new Array(t-r.length+1).join(n)+r};function P(r,t){let e=0;for(let o=0;o<r.length;o++)e|=1<<t[r[o]];let n=e.toString(2),i="";for(let o=n.length-1;o>=0;o--)i+=n[o];return i}function Y(r,t,e){let n=r,i=t.split(".");for(let o=0;o<i.length&&n;o++){let s=i[o];if(typeof n=="object"&&"length"in n&&s.match(/^[0-9]+$/))n=n[parseInt(s)];else if(typeof n=="object"&&s in n)n=n[s];else return e}return n||n===!1?n:e}function q(r){return c(K(r))}function J(r){return Q(m(r))}function K(r){let t=r.match(/.{1,2}/g);if(t==null)return"";let e=[];for(let n=0;n<t.length;n++){let i=parseInt(t[n],16);161<=i&&i<=191?(e.push("c2"),e.push(t[n])):192<=i&&i<=255?(e.push("c3"),e.push((i-64).toString(16))):e.push(t[n])}return e.join("")}function Q(r){let t=r.match(/.{1,2}/g);if(t==null)return"";let e=[];for(let n=0;n<t.length;n++)if(t[n]==="c2")n++,e.push(t[n]);else if(t[n]==="c3"){n++;let i=parseInt(t[n],16)+64;e.push(i.toString(16))}else e.push(t[n]);return e.join("")}function W(r,t,e=`\r
2
+ `){return`-----BEGIN ${t}-----${e}${d(h(r),64)}${e}-----END ${t}-----${e}`}function X(r,t){return a(T(r,t))}function T(r,t){let e=r;if(e.indexOf("-----BEGIN ")===-1)throw new Error("can't find PEM header");return t!==void 0?(e=e.replace(new RegExp(`^[^-]*-----BEGIN ${t}-----`),""),e=e.replace(new RegExp(`-----END ${t}-----[^-]*$`),"")):(e=e.replace(/^[^-]*-----BEGIN [^-]+-----/,""),e=e.replace(/-----END [^-]+-----[^-]*$/,"")),e.replace(/\s+/g,"")}function H(r,t,e=`\r
3
+ `){return`-----BEGIN ${t}-----${e}${d(r,64,e)}${e}-----END ${t}-----${e}`}function tt(r){let t=r.replace(/[^0-9A-Za-z\/+=]*/g,"");return a(t)}function d(r,t,e=`\r
4
+ `){let n=r;return n=n.replace(new RegExp(`(.{${t}})`,"g"),`$1${e}`),n=n.replace(/\s+$/,""),n}function rt(r){if(r.length%2!==0)throw"input is not even length";if(r.match(/^[0-9A-Fa-f]+$/)==null)throw"input is not hexadecimal";let t=new ArrayBuffer(r.length/2),e=new DataView(t);for(let n=0;n<r.length/2;n++)e.setUint8(n,parseInt(r.substr(n*2,2),16));return t}function et(r){let t="",e=new DataView(r);for(let n=0;n<r.byteLength;n++)t+=`00${e.getUint8(n).toString(16)}`.slice(-2);return t}function y(r){let t=r,e,n,i,o,s,f,u,g,p;t=v(t);let l=t.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/);if(l)return e=parseInt(l[1]),n=parseInt(l[2])-1,i=parseInt(l[3]),o=parseInt(l[4]),s=parseInt(l[5]),f=parseInt(l[6]),u=0,g=l[7],g!==""&&(p=`${g.substr(1)}00`.substr(0,3),u=parseInt(p)),Date.UTC(e,n,i,o,s,f,u);throw new Error(`unsupported zulu format: ${t}`)}function nt(r){let t=new Date(r),e=`0000${t.getUTCFullYear()}`.slice(-4),n=`00${t.getUTCMonth()+1}`.slice(-2),i=`00${t.getUTCDate()}`.slice(-2),o=`00${t.getUTCHours()}`.slice(-2),s=`00${t.getUTCMinutes()}`.slice(-2),f=`00${t.getUTCSeconds()}`.slice(-2),u=`000${t.getUTCMilliseconds()}`.slice(-3);return u=u.replace(/0+$/,""),u=u!==""?`.${u}`:u,`${e+n+i+o+s+f+u}Z`}function ot(r){return Math.round(y(r)/1e3)}function it(r){return new Date(y(r))}function st(r,t=!1,e=!1){let n,i=r.getUTCFullYear();if(t){if(i<1950||2049<i)throw new Error(`not proper year for UTCTime: ${i}`);n=`${i}`.slice(-2)}else n=`000${i}`.slice(-4);if(n+=`0${r.getUTCMonth()+1}`.slice(-2),n+=`0${r.getUTCDate()}`.slice(-2),n+=`0${r.getUTCHours()}`.slice(-2),n+=`0${r.getUTCMinutes()}`.slice(-2),n+=`0${r.getUTCSeconds()}`.slice(-2),e){let o=r.getUTCMilliseconds();if(o!==0){let s=`00${o}`.slice(-3);s=s.replace(/0+$/g,""),n+=`.${s}`}}return n+="Z",n}function v(r){return r.match(/^[0-9]{12}Z$/)||r.match(/^[0-9]{12}[.][0-9]*Z$/)?r.match(/^[0-4]/)?`20${r}`:`19${r}`:r}function ut(r){return r.replace(/%/g,"")}function lt(r){return r.replace(/(..)/g,"%$1")}function ft(r){let t=encodeURIComponent(r),e="";for(let n=0;n<t.length;n++)t[n]==="%"?(e=e+t.substr(n,3),n=n+2):e=`${e}%${x(t[n])}`;return e}function w(r){let t=r,e="malformed IPv6 address";if(!t.match(/^[0-9A-Fa-f:]+$/))throw e;t=t.toLowerCase();let n=t.split(":").length-1;if(n<2)throw e;let i=":".repeat(7-n+2);t=t.replace("::",i);let o=t.split(":");if(o.length!==8)throw e;for(let s=0;s<8;s++)o[s]=`0000${o[s]}`.slice(-4);return o.join("")}function I(r){let t=r;if(!t.match(/^[0-9A-Fa-f]{32}$/))throw new Error(`malformed IPv6 address: ${t}`);t=t.toLowerCase();let e=t.match(/.{1,4}/g)||[];e=e.map(o=>o.replace(/^0+/,"")),e=e.map(o=>o===""?"0":o),t=`:${e.join(":")}:`;let n=t.match(/:(0:){2,}/g);if(n==null)return t.slice(1,-1);let i=n.sort().slice(-1)[0];return t=t.replace(i.substr(0,i.length-1),":"),t.substr(0,2)!=="::"&&(t=t.substr(1)),t.substr(-2,2)!=="::"&&(t=t.substr(0,t.length-1)),t}function D(r){let t=new Error("malformed hex value");if(!r.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw t;if(r.length===8){let e;try{return e=`${parseInt(r.substr(0,2),16)}.${parseInt(r.substr(2,2),16)}.${parseInt(r.substr(4,2),16)}.${parseInt(r.substr(6,2),16)}`,e}catch{throw t}}else if(r.length===16)try{return`${D(r.substr(0,8))}/${A(r.substr(8))}`}catch{throw t}else{if(r.length===32)return I(r);if(r.length===64)try{return`${I(r.substr(0,32))}/${A(r.substr(32))}`}catch{throw t}else return r}}function M(r){let t=r,e=new Error("malformed IP address");if(t=t.toLowerCase(),!t.match(/^[0-9a-f.:/]+$/))throw e;if(t.match(/^[0-9.]+$/)){let n=t.split(".");if(n.length!==4)throw e;let i="";try{for(let o=0;o<4;o++){let s=parseInt(n[o]);i+=`0${s.toString(16)}`.slice(-2)}return i}catch{throw e}}else if(t.match(/^[0-9.]+\/[0-9]+$/)){let n=t.split("/");return M(n[0])+S(parseInt(n[1]),32)}else{if(t.match(/^[0-9a-f:]+$/)&&t.indexOf(":")!==-1)return w(t);if(t.match(/^[0-9a-f:]+\/[0-9]+$/)&&t.indexOf(":")!==-1){let n=t.split("/");return w(n[0])+S(parseInt(n[1]),128)}else throw e}}function A(r){let t=new Error("malformed mask"),e;try{e=parseInt(r,16).toString(2)}catch{throw t}if(!e.match(/^1*0*$/))throw t;return e.replace(/0+$/,"").length}function S(r,t){if(t===32&&r===0)return"00000000";if(t===128&&r===0)return"00000000000000000000000000000000";let e=Array(r+1).join("1")+Array(t-r+1).join("0");return parseInt(e,2).toString(16)}function ct(r){function t(i){let o=parseInt(i.substr(0,2),16),s=parseInt(i.substr(2),16);if(o===0&&s<128)return String.fromCharCode(s);if(o<8){let p=192|(o&7)<<3|(s&192)>>6,l=128|s&63;return c(p.toString(16)+l.toString(16))}let f=224|(o&240)>>4,u=128|(o&15)<<2|(s&192)>>6,g=128|s&63;return c(f.toString(16)+u.toString(16)+g.toString(16))}let e=r.match(/.{4}/g);return e==null?"":e.map(t).join("")}var St="typepki-strconv 0.1.0 kjur.github.io/typepki-strconv";export{et as ArrayBuffertohex,C as BAtohex,z as BAtos,St as VERSION,Y as aryval,tt as b64nltohex,b as b64tob64u,a as b64tohex,H as b64topem,j as b64toutf8,$ as b64utob64,R as b64utohex,k as b64utoutf8,L as binstrtobitstr,O as bitstrtobinstr,st as datetozulu,ft as encodeURIComponentAll,d as foldnl,rt as hextoArrayBuffer,h as hextob64,Z as hextob64u,D as hextoip,I as hextoipv6,W as hextopem,G as hextorstr,lt as hextouricmp,c as hextoutf8,E as inttobitstr,S as ipnetmask,A as ipprefixlen,M as iptohex,w as ipv6tohex,q as iso88591hextoutf8,nt as msectozulu,P as namearraytobinstr,T as pemtob64,X as pemtohex,_ as rstrtob64,V as rstrtohex,B as stoBA,x as stohex,U as strpad,v as timetogen,ct as ucs2hextoutf8,ut as uricmptohex,N as utf8tob64,F as utf8tob64u,m as utf8tohex,J as utf8toiso88591hex,it as zulutodate,y as zulutomsec,ot as zulutosec};
@@ -0,0 +1,4 @@
1
+ "use strict";var E=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var St=Object.prototype.hasOwnProperty;var f=(r,t)=>()=>(r&&(t=r(r=0)),t);var Ct=(r,t)=>{for(var e in t)E(r,e,{get:t[e],enumerable:!0})},Bt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of At(t))!St.call(r,o)&&o!==e&&E(r,o,{get:()=>t[o],enumerable:!(n=It(t,o))||n.enumerable});return r};var Et=r=>Bt(E({},"__esModule",{value:!0}),r);function b(r){return U(T(r))}function U(r){let t="";for(let e=0;e<r.length;e++){let n=r[e].toString(16);n.length===1&&(n=`0${n}`),t=t+n}return t}function T(r){let t=new Array;for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}function F(r){let t="";for(let e=0;e<r.length;e++)t=t+String.fromCharCode(r[e]);return t}var v=f(()=>{"use strict"});function a(r){return Buffer.from(r,"base64").toString("hex")}function h(r){return Buffer.from(r,"hex").toString("base64")}function R(r){return Buffer.from(r,"base64").toString("utf8")}function Z(r){return Buffer.from(r,"utf8").toString("base64")}function G(r){return Buffer.from(y(r),"base64").toString("utf8")}function V(r){return d(Buffer.from(r,"utf8").toString("base64"))}function c(r){return Buffer.from(r,"hex").toString("utf8")}function $(r){return Buffer.from(r,"utf8").toString("hex")}function _(r){return a(y(r))}function L(r){return d(h(r))}function O(r){let t="";for(let e=0;e<r.length;e+=2){let n=parseInt(r.substr(e,2),16);t+=String.fromCharCode(n)}return t}function P(r){let t="";for(let e=0;e<r.length;e++)t+=`0${r.charCodeAt(e).toString(16)}`.slice(-2);return t}function Y(r){return Buffer.from(r).toString("base64")}function d(r){let t=r;return t=t.replace(/\=/g,""),t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_"),t}function y(r){let t=r;return t.length%4===2?t=`${t}==`:t.length%4===3&&(t=`${t}=`),t=t.replace(/-/g,"+"),t=t.replace(/_/g,"/"),t}function J(r){if(typeof r!="string"||r.length%2!==0||!r.match(/^[0-9a-f]+$/))return null;try{let t=parseInt(r.substr(0,2),16);if(t<0||7<t)return null;let e=r.substr(2),n="";for(let o=0;o<e.length;o+=2){let i=e.substr(o,2),s=parseInt(i,16).toString(2);s=`0000000${s}`.slice(-8),n+=s}return n.substr(0,n.length-t)}catch{return null}}function D(r){if(typeof r!="number"||r<0)return null;let t=Number(r).toString(2),e=8-t.length%8;e===8&&(e=0),t=t+M("",e,"0");let n=parseInt(t,2).toString(16);return n.length%2===1&&(n=`0${n}`),`0${e}`+n}function K(r,t){let e=0;for(let i=0;i<r.length;i++)e|=1<<t[r[i]];let n=e.toString(2),o="";for(let i=n.length-1;i>=0;i--)o+=n[i];return o}function Q(r,t,e){let n=r,o=t.split(".");for(let i=0;i<o.length&&n;i++){let s=o[i];if(typeof n=="object"&&"length"in n&&s.match(/^[0-9]+$/))n=n[parseInt(s)];else if(typeof n=="object"&&s in n)n=n[s];else return e}return n||n===!1?n:e}var q,M,x=f(()=>{"use strict";q=r=>{if(r.match(/^[01]+$/)==null)return null;try{let t=parseInt(r,2);return D(t)}catch{return null}};M=(r,t,e)=>{let n=e===void 0?"0":e;return r.length>=t?r:new Array(t-r.length+1).join(n)+r}});function W(r){return c(Ut(r))}function X(r){return Tt($(r))}function Ut(r){let t=r.match(/.{1,2}/g);if(t==null)return"";let e=[];for(let n=0;n<t.length;n++){let o=parseInt(t[n],16);161<=o&&o<=191?(e.push("c2"),e.push(t[n])):192<=o&&o<=255?(e.push("c3"),e.push((o-64).toString(16))):e.push(t[n])}return e.join("")}function Tt(r){let t=r.match(/.{1,2}/g);if(t==null)return"";let e=[];for(let n=0;n<t.length;n++)if(t[n]==="c2")n++,e.push(t[n]);else if(t[n]==="c3"){n++;let o=parseInt(t[n],16)+64;e.push(o.toString(16))}else e.push(t[n]);return e.join("")}var H=f(()=>{"use strict";x()});function tt(r,t,e=`\r
2
+ `){return`-----BEGIN ${t}-----${e}${w(h(r),64)}${e}-----END ${t}-----${e}`}function rt(r,t){return a(z(r,t))}function z(r,t){let e=r;if(e.indexOf("-----BEGIN ")===-1)throw new Error("can't find PEM header");return t!==void 0?(e=e.replace(new RegExp(`^[^-]*-----BEGIN ${t}-----`),""),e=e.replace(new RegExp(`-----END ${t}-----[^-]*$`),"")):(e=e.replace(/^[^-]*-----BEGIN [^-]+-----/,""),e=e.replace(/-----END [^-]+-----[^-]*$/,"")),e.replace(/\s+/g,"")}function et(r,t,e=`\r
3
+ `){return`-----BEGIN ${t}-----${e}${w(r,64,e)}${e}-----END ${t}-----${e}`}function nt(r){let t=r.replace(/[^0-9A-Za-z\/+=]*/g,"");return a(t)}function w(r,t,e=`\r
4
+ `){let n=r;return n=n.replace(new RegExp(`(.{${t}})`,"g"),`$1${e}`),n=n.replace(/\s+$/,""),n}var ot=f(()=>{"use strict";x()});function it(r){if(r.length%2!==0)throw"input is not even length";if(r.match(/^[0-9A-Fa-f]+$/)==null)throw"input is not hexadecimal";let t=new ArrayBuffer(r.length/2),e=new DataView(t);for(let n=0;n<r.length/2;n++)e.setUint8(n,parseInt(r.substr(n*2,2),16));return t}function st(r){let t="",e=new DataView(r);for(let n=0;n<r.byteLength;n++)t+=`00${e.getUint8(n).toString(16)}`.slice(-2);return t}var ut=f(()=>{"use strict"});function I(r){let t=r,e,n,o,i,s,g,u,p,m;t=j(t);let l=t.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/);if(l)return e=parseInt(l[1]),n=parseInt(l[2])-1,o=parseInt(l[3]),i=parseInt(l[4]),s=parseInt(l[5]),g=parseInt(l[6]),u=0,p=l[7],p!==""&&(m=`${p.substr(1)}00`.substr(0,3),u=parseInt(m)),Date.UTC(e,n,o,i,s,g,u);throw new Error(`unsupported zulu format: ${t}`)}function lt(r){let t=new Date(r),e=`0000${t.getUTCFullYear()}`.slice(-4),n=`00${t.getUTCMonth()+1}`.slice(-2),o=`00${t.getUTCDate()}`.slice(-2),i=`00${t.getUTCHours()}`.slice(-2),s=`00${t.getUTCMinutes()}`.slice(-2),g=`00${t.getUTCSeconds()}`.slice(-2),u=`000${t.getUTCMilliseconds()}`.slice(-3);return u=u.replace(/0+$/,""),u=u!==""?`.${u}`:u,`${e+n+o+i+s+g+u}Z`}function ft(r){return Math.round(I(r)/1e3)}function ct(r){return new Date(I(r))}function gt(r,t=!1,e=!1){let n,o=r.getUTCFullYear();if(t){if(o<1950||2049<o)throw new Error(`not proper year for UTCTime: ${o}`);n=`${o}`.slice(-2)}else n=`000${o}`.slice(-4);if(n+=`0${r.getUTCMonth()+1}`.slice(-2),n+=`0${r.getUTCDate()}`.slice(-2),n+=`0${r.getUTCHours()}`.slice(-2),n+=`0${r.getUTCMinutes()}`.slice(-2),n+=`0${r.getUTCSeconds()}`.slice(-2),e){let i=r.getUTCMilliseconds();if(i!==0){let s=`00${i}`.slice(-3);s=s.replace(/0+$/g,""),n+=`.${s}`}}return n+="Z",n}function j(r){return r.match(/^[0-9]{12}Z$/)||r.match(/^[0-9]{12}[.][0-9]*Z$/)?r.match(/^[0-4]/)?`20${r}`:`19${r}`:r}var at=f(()=>{"use strict"});function pt(r){return r.replace(/%/g,"")}function ht(r){return r.replace(/(..)/g,"%$1")}function xt(r){let t=encodeURIComponent(r),e="";for(let n=0;n<t.length;n++)t[n]==="%"?(e=e+t.substr(n,3),n=n+2):e=`${e}%${b(t[n])}`;return e}var mt=f(()=>{"use strict";v()});function A(r){let t=r,e="malformed IPv6 address";if(!t.match(/^[0-9A-Fa-f:]+$/))throw e;t=t.toLowerCase();let n=t.split(":").length-1;if(n<2)throw e;let o=":".repeat(7-n+2);t=t.replace("::",o);let i=t.split(":");if(i.length!==8)throw e;for(let s=0;s<8;s++)i[s]=`0000${i[s]}`.slice(-4);return i.join("")}function S(r){let t=r;if(!t.match(/^[0-9A-Fa-f]{32}$/))throw new Error(`malformed IPv6 address: ${t}`);t=t.toLowerCase();let e=t.match(/.{1,4}/g)||[];e=e.map(i=>i.replace(/^0+/,"")),e=e.map(i=>i===""?"0":i),t=`:${e.join(":")}:`;let n=t.match(/:(0:){2,}/g);if(n==null)return t.slice(1,-1);let o=n.sort().slice(-1)[0];return t=t.replace(o.substr(0,o.length-1),":"),t.substr(0,2)!=="::"&&(t=t.substr(1)),t.substr(-2,2)!=="::"&&(t=t.substr(0,t.length-1)),t}function N(r){let t=new Error("malformed hex value");if(!r.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw t;if(r.length===8){let e;try{return e=`${parseInt(r.substr(0,2),16)}.${parseInt(r.substr(2,2),16)}.${parseInt(r.substr(4,2),16)}.${parseInt(r.substr(6,2),16)}`,e}catch{throw t}}else if(r.length===16)try{return`${N(r.substr(0,8))}/${C(r.substr(8))}`}catch{throw t}else{if(r.length===32)return S(r);if(r.length===64)try{return`${S(r.substr(0,32))}/${C(r.substr(32))}`}catch{throw t}else return r}}function k(r){let t=r,e=new Error("malformed IP address");if(t=t.toLowerCase(),!t.match(/^[0-9a-f.:/]+$/))throw e;if(t.match(/^[0-9.]+$/)){let n=t.split(".");if(n.length!==4)throw e;let o="";try{for(let i=0;i<4;i++){let s=parseInt(n[i]);o+=`0${s.toString(16)}`.slice(-2)}return o}catch{throw e}}else if(t.match(/^[0-9.]+\/[0-9]+$/)){let n=t.split("/");return k(n[0])+B(parseInt(n[1]),32)}else{if(t.match(/^[0-9a-f:]+$/)&&t.indexOf(":")!==-1)return A(t);if(t.match(/^[0-9a-f:]+\/[0-9]+$/)&&t.indexOf(":")!==-1){let n=t.split("/");return A(n[0])+B(parseInt(n[1]),128)}else throw e}}function C(r){let t=new Error("malformed mask"),e;try{e=parseInt(r,16).toString(2)}catch{throw t}if(!e.match(/^1*0*$/))throw t;return e.replace(/0+$/,"").length}function B(r,t){if(t===32&&r===0)return"00000000";if(t===128&&r===0)return"00000000000000000000000000000000";let e=Array(r+1).join("1")+Array(t-r+1).join("0");return parseInt(e,2).toString(16)}var bt=f(()=>{"use strict"});function $t(r){function t(o){let i=parseInt(o.substr(0,2),16),s=parseInt(o.substr(2),16);if(i===0&&s<128)return String.fromCharCode(s);if(i<8){let m=192|(i&7)<<3|(s&192)>>6,l=128|s&63;return c(m.toString(16)+l.toString(16))}let g=224|(i&240)>>4,u=128|(i&15)<<2|(s&192)>>6,p=128|s&63;return c(g.toString(16)+u.toString(16)+p.toString(16))}let e=r.match(/.{4}/g);return e==null?"":e.map(t).join("")}var dt=f(()=>{"use strict";x()});var yt={};Ct(yt,{ArrayBuffertohex:()=>st,BAtohex:()=>U,BAtos:()=>F,VERSION:()=>vt,aryval:()=>Q,b64nltohex:()=>nt,b64tob64u:()=>d,b64tohex:()=>a,b64topem:()=>et,b64toutf8:()=>R,b64utob64:()=>y,b64utohex:()=>_,b64utoutf8:()=>G,binstrtobitstr:()=>q,bitstrtobinstr:()=>J,datetozulu:()=>gt,encodeURIComponentAll:()=>xt,foldnl:()=>w,hextoArrayBuffer:()=>it,hextob64:()=>h,hextob64u:()=>L,hextoip:()=>N,hextoipv6:()=>S,hextopem:()=>tt,hextorstr:()=>O,hextouricmp:()=>ht,hextoutf8:()=>c,inttobitstr:()=>D,ipnetmask:()=>B,ipprefixlen:()=>C,iptohex:()=>k,ipv6tohex:()=>A,iso88591hextoutf8:()=>W,msectozulu:()=>lt,namearraytobinstr:()=>K,pemtob64:()=>z,pemtohex:()=>rt,rstrtob64:()=>Y,rstrtohex:()=>P,stoBA:()=>T,stohex:()=>b,strpad:()=>M,timetogen:()=>j,ucs2hextoutf8:()=>$t,uricmptohex:()=>pt,utf8tob64:()=>Z,utf8tob64u:()=>V,utf8tohex:()=>$,utf8toiso88591hex:()=>X,zulutodate:()=>ct,zulutomsec:()=>I,zulutosec:()=>ft});var vt,wt=f(()=>{"use strict";v();x();H();ot();ut();at();mt();bt();dt();vt="typepki-strconv 0.1.0 kjur.github.io/typepki-strconv"});module.exports=(wt(),Et(yt));
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../src/index.cts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "typepki-strconv",
3
+ "version": "0.1.0",
4
+ "author": "Kenji Urushima <kenji.urushima@gmail.com>",
5
+ "description": "TypeScript string converters and utilities sub module for TypePKI library (beta)",
6
+ "homepage": "https://kjur.github.io/typepki-strconv",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/kjur/typepki-strconv.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/kjur/typepki-strconv/issues"
13
+ },
14
+ "keywords": [
15
+ "typepki",
16
+ "typescript",
17
+ "pki",
18
+ "string",
19
+ "converter",
20
+ "base64",
21
+ "hex",
22
+ "zulu",
23
+ "utf8"
24
+ ],
25
+ "license": "MIT",
26
+ "scripts": {
27
+ "deploy": "",
28
+ "build": "run-z build:transpile,build:esm,build:cjs",
29
+ "build:transpile": "bun build.mts",
30
+ "build:esm": "tsc --project tsconfig.build.esm.json",
31
+ "build:cjs": "tsc --project tsconfig.build.cjs.json",
32
+ "check": "run-z check:type,check:static",
33
+ "check:type": "tsc --noEmit",
34
+ "check:static": "biome check .",
35
+ "fix": "$npm_execpath run check:static --apply-unsafe",
36
+ "test": "bun test",
37
+ "precommit": "run-z check:type fix test build",
38
+ "prepublish": "attw --pack .",
39
+ "run-z": "run-z",
40
+ "doc": "typedoc --includeVersion --cleanOutputDir false --tsconfig ./tsconfig.typedoc.json --options ./typedoc.json src/index.mts"
41
+ },
42
+ "files": [
43
+ "src",
44
+ "dist",
45
+ "package.json",
46
+ "tsconfig.json",
47
+ "LICENSE"
48
+ ],
49
+ "exports": {
50
+ ".": {
51
+ "import": {
52
+ "types": "./dist/import/index.d.mts",
53
+ "default": "./dist/import/index.mjs"
54
+ },
55
+ "require": {
56
+ "types": "./dist/require/index.d.cts",
57
+ "default": "./dist/require/index.cjs"
58
+ }
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "@arethetypeswrong/cli": "^0.15.0",
63
+ "@biomejs/biome": "1.5.3",
64
+ "@changesets/cli": "^2.27.1",
65
+ "bun-types": "^1.0.15",
66
+ "esbuild": "^0.20.0",
67
+ "jest": "^29.7.0",
68
+ "run-z": "^2.0.0",
69
+ "typedoc": "^0.25.13",
70
+ "typescript": "^5.4.5"
71
+ }
72
+ }
package/src/conv.mts ADDED
@@ -0,0 +1,367 @@
1
+ // ==== hex / base64 ======================================
2
+ export function b64tohex(b64: string): string {
3
+ return Buffer.from(b64, "base64").toString("hex");
4
+ }
5
+
6
+ export function hextob64(hex: string): string {
7
+ return Buffer.from(hex, "hex").toString("base64");
8
+ }
9
+
10
+ // ==== utf8 / base64 =====================================
11
+ export function b64toutf8(b64: string): string {
12
+ return Buffer.from(b64, "base64").toString("utf8");
13
+ }
14
+
15
+ export function utf8tob64(u8: string): string {
16
+ return Buffer.from(u8, "utf8").toString("base64");
17
+ }
18
+
19
+ // ==== utf8 / base64u ====================================
20
+ export function b64utoutf8(b64u: string): string {
21
+ return Buffer.from(b64utob64(b64u), "base64").toString("utf8");
22
+ }
23
+
24
+ export function utf8tob64u(u8: string): string {
25
+ return b64tob64u(Buffer.from(u8, "utf8").toString("base64"));
26
+ }
27
+
28
+ // ==== hex / utf8 ========================================
29
+ export function hextoutf8(hex: string): string {
30
+ return Buffer.from(hex, "hex").toString("utf8");
31
+ }
32
+
33
+ export function utf8tohex(u8: string): string {
34
+ return Buffer.from(u8, "utf8").toString("hex");
35
+ }
36
+
37
+ // ==== hex / base64u =====================================
38
+ export function b64utohex(b64u: string): string {
39
+ return b64tohex(b64utob64(b64u));
40
+ }
41
+
42
+ export function hextob64u(hex: string): string {
43
+ return b64tob64u(hextob64(hex));
44
+ }
45
+
46
+ // ==== hex / rstr ========================================
47
+ /**
48
+ * convert a hexadecimal string to raw string
49
+ * @param hex hexadecimal string
50
+ * @return rawstring
51
+ * @see {@link rstrtohex}
52
+ * @example
53
+ * hextorstr("616161") -> "aaa"
54
+ * hextorstr("610061") -> "a\x00a"
55
+ */
56
+ export function hextorstr(hex: string): string {
57
+ let result = "";
58
+ for (let i = 0; i < hex.length; i += 2) {
59
+ const sByte = parseInt(hex.substr(i, 2), 16);
60
+ result += String.fromCharCode(sByte);
61
+ }
62
+ return result;
63
+ }
64
+
65
+ /**
66
+ * convert a raw string to a hexadecimal string
67
+ * @param s raw string
68
+ * @return hexadecimal string
69
+ * @see {@link hextorstr}
70
+ * @example
71
+ * rstrtohex("aaa") -> "616161"
72
+ * rstrtohex("a\x00a") -> "610061"
73
+ */
74
+ export function rstrtohex(s: string): string {
75
+ let result = "";
76
+ for (let i = 0; i < s.length; i++) {
77
+ result += `0${s.charCodeAt(i).toString(16)}`.slice(-2);
78
+ }
79
+ return result;
80
+ }
81
+
82
+ // ==== rstr / base64 =====================================
83
+ /**
84
+ * convert a raw string to a Base64 encoded string.
85
+ * @param s raw string
86
+ * @return Base64URL encoded string
87
+ * @example
88
+ * rstrtob64("aaa") -> "YWFh"
89
+ */
90
+ export function rstrtob64(s: string): string {
91
+ return Buffer.from(s).toString("base64");
92
+ }
93
+
94
+ // ==== base64 / base64url ================================
95
+ /**
96
+ * convert a Base64 encoded string to a Base64URL encoded string.
97
+ * @param sIn - Base64 encoded string
98
+ * @return Base64URL encoded string
99
+ * @see {@link b64utob64}
100
+ * @example
101
+ * b64tob64u("ab+c3f/==") &rarr; "ab-c3f_"
102
+ */
103
+ /*
104
+ * @name b64tob64u
105
+ * @function
106
+ */
107
+ export function b64tob64u(sIn: string): string {
108
+ let s: string = sIn;
109
+ s = s.replace(/\=/g, "");
110
+ s = s.replace(/\+/g, "-");
111
+ s = s.replace(/\//g, "_");
112
+ return s;
113
+ }
114
+
115
+ /**
116
+ * convert a Base64URL encoded string to a Base64 encoded string.
117
+ * @param sIn - Base64URL encoded string
118
+ * @return Base64 encoded string
119
+ * @see {@link b64tob64u}
120
+ * @example
121
+ * b64utob64("ab-c3f_") -> "ab+c3f/=="
122
+ */
123
+ export function b64utob64(sIn: string): string {
124
+ let s: string = sIn;
125
+ if (s.length % 4 === 2) s = `${s}==`;
126
+ else if (s.length % 4 === 3) s = `${s}=`;
127
+ s = s.replace(/-/g, "+");
128
+ s = s.replace(/_/g, "/");
129
+ return s;
130
+ }
131
+
132
+ // ==== binstr / bitstr ===================================
133
+ /**
134
+ * convert from binary string to hexadecimal string of ASN.1 BitString value with unused bit<br/>
135
+ * @param s binary string (ex. "101")
136
+ * @return hexadecimal string of ASN.1 BitString value with unused bit
137
+ * @see {@link bitstrtobinstr}
138
+ *
139
+ * @description
140
+ * This function converts from an binary string (ex. "101") to
141
+ * hexadecimal string of ASN.1 BitString value
142
+ * with unused bit (ex. "05a0"). <br/>
143
+ * When "s" is not binary string, this returns null.
144
+ *
145
+ * @example
146
+ * binstrtobitstr("101") -> "05a0"
147
+ * binstrtobitstr("001") -> "0520"
148
+ * binstrtobitstr("11001") -> "03c8"
149
+ * binstrtobitstr("101000001") -> "07a080"
150
+ * binstrtobitstr(101) -> null // not number
151
+ * binstrtobitstr("xyz") -> null // not binary string
152
+ */
153
+ export const binstrtobitstr = (s: string): string | null => {
154
+ if (s.match(/^[01]+$/) == null) return null;
155
+ try {
156
+ const n = parseInt(s, 2);
157
+ return inttobitstr(n);
158
+ } catch (ex) {
159
+ return null;
160
+ }
161
+ };
162
+
163
+ /**
164
+ * convert from hexadecimal string of ASN.1 BitString value with unused bit to binary string
165
+ * @param h - hexadecimal string of ASN.1 BitString value with unused bit
166
+ * @return binary string
167
+ * @see {@link binstrtobitstr}
168
+ * @see {@link inttobitstr}
169
+ *
170
+ * @description
171
+ * This function converts from hexadecimal string of ASN.1 BitString
172
+ * value with unused bit to its integer value. <br/>
173
+ * When an improper hexadecimal string of BitString value
174
+ * is applied, this returns null.
175
+ *
176
+ * @example
177
+ * bitstrtobinstr("05a0") -> "101"
178
+ * bitstrtobinstr("0520") -> "001"
179
+ * bitstrtobinstr("07a080") -> "101000001"
180
+ * bitstrtobinstr(502) -> null // non ASN.1 BitString value
181
+ * bitstrtobinstr("ff00") -> null // for improper BitString value
182
+ */
183
+ export function bitstrtobinstr(h: string): string | null {
184
+ if (typeof h !== "string") return null;
185
+ if (h.length % 2 !== 0) return null;
186
+ if (!h.match(/^[0-9a-f]+$/)) return null;
187
+ try {
188
+ const unusedBits = parseInt(h.substr(0, 2), 16);
189
+ if (unusedBits < 0 || 7 < unusedBits) return null;
190
+
191
+ const value = h.substr(2);
192
+ let bin = "";
193
+ for (let i = 0; i < value.length; i += 2) {
194
+ const hi = value.substr(i, 2);
195
+ let bi = parseInt(hi, 16).toString(2);
196
+ bi = `0000000${bi}`.slice(-8);
197
+ bin += bi;
198
+ }
199
+ return bin.substr(0, bin.length - unusedBits);
200
+ } catch (ex) {
201
+ return null;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * convert from integer value to hexadecimal string of ASN.1 BitString value with unused bit
207
+ * @param n integer value of ASN.1 BitString
208
+ * @return hexadecimal string of ASN.1 BitString value with unused bit
209
+ * @see bitstrtoint
210
+ *
211
+ * @description
212
+ * This function converts from an integer value to
213
+ * hexadecimal string of ASN.1 BitString value
214
+ * with unused bit. <br/>
215
+ * When "n" is not non-negative number, this returns null
216
+ *
217
+ * @example
218
+ * // 25 -> 11001b -> 11001000b unusedbit=03 -> 0xc8 unusedbit=03 -> "03c8"
219
+ * inttobitstr(25) -> "03c8"
220
+ * inttobitstr(-3) -> null
221
+ * inttobitstr("abc") -> null
222
+ * inttobitstr(parseInt("11001", 2)) -> "03c8"
223
+ * inttobitstr(parseInt("101", 2)) -> "05a0"
224
+ * inttobitstr(parseInt("101000001", 2)) -> "07a080"
225
+ */
226
+ /*
227
+ * @name inttobitstr
228
+ * @function
229
+ * @since jsrsasign 10.1.3 base64x 1.1.19
230
+ * @see KJUR.asn1.DERBitString
231
+ * @see ASN1HEX.getInt
232
+ */
233
+ export function inttobitstr(n: number): string | null {
234
+ if (typeof n !== "number") return null;
235
+ if (n < 0) return null;
236
+ let bValue = Number(n).toString(2);
237
+ let iUnusedbit = 8 - (bValue.length % 8);
238
+ if (iUnusedbit === 8) iUnusedbit = 0;
239
+ bValue = bValue + strpad("", iUnusedbit, "0");
240
+ let hValue = parseInt(bValue, 2).toString(16);
241
+ if (hValue.length % 2 === 1) hValue = `0${hValue}`;
242
+ const hUnusedbit = `0${iUnusedbit}`;
243
+ return hUnusedbit + hValue;
244
+ }
245
+
246
+ /*
247
+ * @name strpad
248
+ * @function
249
+ * @since jsrsasign 10.1.0 base64x 1.1.18
250
+ */
251
+ /**
252
+ * create padded string with specified length and padding string
253
+ * @param s input string
254
+ * @param len output string length
255
+ * @param defpadchar padding character (default is "0")
256
+ * @return padded string
257
+ * @example
258
+ * strpad("1234", 10, "0") -> "0000001234"
259
+ * strpad("1234", 10, " ") -> " 1234"
260
+ * strpad("1234", 10) -> "0000001234"
261
+ */
262
+ export const strpad = (s: string, len: number, defpadchar?: string): string => {
263
+ const padchar: string = defpadchar === undefined ? "0" : defpadchar;
264
+ if (s.length >= len) return s;
265
+ return new Array(len - s.length + 1).join(padchar) + s;
266
+ };
267
+
268
+ // =======================================================
269
+ /**
270
+ * represents JSON data structure
271
+ * @example
272
+ * let db: Dictionary<number> = { apple: 10, orange: 20 }
273
+ */
274
+ export interface Dictionary<Type> {
275
+ /**
276
+ * key string
277
+ */
278
+ [key: string]: Type;
279
+ }
280
+
281
+ /**
282
+ * convert array of names to bit string
283
+ * @param namearray array of name string
284
+ * @param namedb associative array of name and value
285
+ * @return binary string (ex. "110001")
286
+ *
287
+ * @description
288
+ * This function converts from an array of names to
289
+ * a binary string. DB value bit will be set.
290
+ * Note that ordering of namearray items
291
+ * will be ignored.
292
+ * This function may be useful to implement ASN.1 BitString such as KeyUsage.
293
+ *
294
+ * @example
295
+ * let db: Dictionary<number> = { a: 0, b: 3, c: 8, d: 9, e: 17, f: 19 };
296
+ * namearraytobinstr(['a', 'c', 'd'], db) -> '1000000011'
297
+ * namearraytobinstr(['c', 'b'], db) -> '000100001'
298
+ */
299
+ /*
300
+ * @name namearraytobinstr
301
+ * @function
302
+ * @since jsrsasign 10.5.21 base64x 1.1.27
303
+ * @see KJUR.asn1.x509.KeyUsage
304
+ * @see KJUR.asn1.tsp.PKIFailureInfo
305
+ */
306
+ export function namearraytobinstr(
307
+ namearray: Array<string>,
308
+ namedb: Dictionary<number>,
309
+ ): string {
310
+ let d = 0;
311
+ for (let i = 0; i < namearray.length; i++) {
312
+ d |= 1 << namedb[namearray[i]];
313
+ }
314
+
315
+ const s = d.toString(2);
316
+ let r = "";
317
+ for (let i = s.length - 1; i >= 0; i--) {
318
+ r += s[i];
319
+ }
320
+ return r;
321
+ }
322
+
323
+ /**
324
+ * get value of array by key name list<br/>
325
+ * @param valIn - array of associative array
326
+ * @param sKey - concatinated key list with dot (ex. 'type.name.0.info')
327
+ * @param defIn - default value if value is not found (OPTIONAL)
328
+ * @return value if found otherwise returns def
329
+ *
330
+ * @description
331
+ * This function returns the value of an array or associative array
332
+ * which referred by a concatinated key list string.
333
+ * If a value for key is not defined, it returns 'undefined' by default.
334
+ * When an optional argument 'def' is specified and a value for key is
335
+ * not defined, it returns a value of 'def'.
336
+ *
337
+ * @example
338
+ * let p = {
339
+ * fruit: apple,
340
+ * info: [
341
+ * { toy: 4 },
342
+ * { pen: 6 }
343
+ * ]
344
+ * };
345
+ * aryval(p, 'fruit') -> "apple"
346
+ * aryval(p, 'info') -> [{toy: 4},{pen: 6}]
347
+ * aryval(p, 'info.1') -> {pen: 6}
348
+ * aryval(p, 'info.1.pen') -> 6
349
+ * aryval(p, 'money.amount') -> undefined
350
+ * aryval(p, 'money.amount', null) -> null
351
+ */
352
+ export function aryval(valIn: any, sKey: string, defIn?: any): any {
353
+ let val: any = valIn;
354
+ const keys: string[] = sKey.split(".");
355
+ for (let i = 0; i < keys.length && val; i++) {
356
+ const key: string = keys[i];
357
+
358
+ if (typeof val === "object" && "length" in val && key.match(/^[0-9]+$/)) {
359
+ val = val[parseInt(key)];
360
+ } else if (typeof val === "object" && key in val) {
361
+ val = val[key];
362
+ } else {
363
+ return defIn;
364
+ }
365
+ }
366
+ return val || val === false ? val : defIn;
367
+ }