import querystring from 'querystring'; import type com from '../../proto/index.js'; import { ConverterSet, ConverterType } from '../domain.js'; import { alignIfLegacy, encodeText, decodeText, URL_HASH_PREFIX, WIX_PROTOCOL, } from './converters-utils.js'; const WIX_IMAGE = 'image'; export const image: ConverterSet = { types: ['wix.common.Image'], [ConverterType.FROM_JSON]: { /** * currently wix.common.Image represents the deserialized object, so we're good. * in case it contains some serializable stuff (e.g. int64), we'll have to make some * modifications in the type. */ transform: (val: com.wix.common.Image) => { if (!val) { return; } let fileNameOrAltText = ''; if (val.filename || val.altText) { fileNameOrAltText = `/${encodeText(val.filename || val.altText)}`; } return val.id ? `wix:image://v1/${val.id}${fileNameOrAltText}${URL_HASH_PREFIX}originWidth=${val.width}&originHeight=${val.height}` : val.url; }, }, [ConverterType.TO_JSON]: { transform: (val: string): com.wix.common.Image | undefined => { if (!val) { return; } const alignedImage = alignIfLegacy(val, WIX_IMAGE); const { protocol, hash, pathname } = new URL(alignedImage); const { originHeight: height, originWidth: width } = querystring.parse( hash.replace(URL_HASH_PREFIX, ''), ); const [id, filenameOrAltText] = pathname .replace(`${WIX_IMAGE}://v1/`, '') .split('/'); const decodedFilenameOrAltText = decodeText(filenameOrAltText); if (protocol === WIX_PROTOCOL) { const res = { id, height: Number(height), width: Number(width) }; if (!decodedFilenameOrAltText) { return res; } return { ...res, altText: decodedFilenameOrAltText, filename: decodedFilenameOrAltText, url: val, }; } return { url: val }; }, }, };