import { randomId } from 'lib/id' import ApiError from './errors/seamly-api-error' export function buildPayload(command, payload) { if (command !== 'message') { return payload } const { type, body } = payload let { transactionId } = payload if (!transactionId) { transactionId = randomId() } return { type, body, transactionId } } export const fetchApi = async ( input: string, init: RequestInit, ): Promise => { const url = new URL(input) const response = await fetch(url.href, { mode: 'cors', ...init }) if (!response.ok) { throw new ApiError( response.statusText || `Request failed with status: ${response.status}`, { status: response.status }, ) } return response } /** * Tries to get the time zone key directly from the operating system for those * environments that support the ECMAScript Internationalization API. * * Based on https://github.com/pellepim/jstimezonedetect/blob/master/jstz.main.js */ export function getTimeZone() { if ( !Intl || typeof Intl === 'undefined' || typeof Intl.DateTimeFormat === 'undefined' ) { return undefined } const format = Intl.DateTimeFormat() if ( typeof format === 'undefined' || typeof format.resolvedOptions === 'undefined' ) { return undefined } const timezone = format.resolvedOptions().timeZone // Ensure we get a valid timezone if (timezone && (timezone.indexOf('/') > -1 || timezone === 'UTC')) { return timezone } else { return undefined } }