1
1
import { ClapOutputType } from '@aitube/clap'
2
2
3
3
/**
4
- * break a base64 string into sub-components
4
+ * break a base64 data uri string into sub-components
5
5
*/
6
6
export function getTypeAndExtension ( base64 : string = '' ) : {
7
7
// category eg. video, audio, text
@@ -15,17 +15,15 @@ export function getTypeAndExtension(base64: string = ''): {
15
15
16
16
outputType : ClapOutputType
17
17
} {
18
- // Regular expression to extract the MIME type and the base64 data
19
- const matches = base64 . match ( / ^ d a t a : ( [ A - Z a - z - + 0 - 9 / ] + ) ; b a s e 6 4 , ( .+ ) $ / )
20
-
21
- if ( ! matches || matches . length !== 3 ) {
22
- throw new Error ( 'Invalid base64 string' )
18
+ if ( ! base64 . startsWith ( 'data:' ) || ! base64 . includes ( 'base64,' ) ) {
19
+ throw new Error ( 'Invalid base64 data uri provided.' )
23
20
}
24
21
25
- const assetFileFormat = matches [ 1 ] || ''
22
+ const base64Index = base64 . indexOf ( 'base64,' )
23
+ const mimeType = base64 . slice ( 5 , base64Index - 1 )
26
24
27
25
// this should be enough for most media formats (jpeg, png, webp, mp4)
28
- const [ category , extension ] = assetFileFormat . split ( '/' )
26
+ const [ category , extension ] = mimeType . split ( '/' )
29
27
30
28
let outputType = ClapOutputType . TEXT
31
29
@@ -39,7 +37,7 @@ export function getTypeAndExtension(base64: string = ''): {
39
37
40
38
return {
41
39
category,
42
- assetFileFormat,
40
+ assetFileFormat : mimeType ,
43
41
extension,
44
42
outputType,
45
43
}
0 commit comments