style: eslint auto fixes

This commit is contained in:
Kevin Szuchet 2023-08-09 11:00:53 +02:00
parent 08b3e79581
commit 4db8360528
No known key found for this signature in database
GPG Key ID: 1E083BC33700E594
21 changed files with 181 additions and 224 deletions

View File

@ -1 +1 @@
export { default as LoginModal } from "decentraland-dapps/dist/containers/LoginModal"
export { default as LoginModal } from 'decentraland-dapps/dist/containers/LoginModal'

View File

@ -1,7 +1,7 @@
import React from "react"
import classNames from "classnames"
import { Props } from "./PageLayout.types"
import styles from "./PageLayout.module.css"
import React from 'react'
import classNames from 'classnames'
import { Props } from './PageLayout.types'
import styles from './PageLayout.module.css'
const PageLayout = ({ children, className }: Props) => {
return (

View File

@ -1,30 +1,24 @@
import { connect } from "react-redux";
import {
getAddress,
isConnecting,
} from "decentraland-dapps/dist/modules/wallet/selectors";
import { isLoggingIn } from "../../../modules/identity/selector";
import { getServer, getToken } from "../../../modules/conference/selector";
import { RootState } from "../../../modules/reducer";
import withRouter from "../../../utils/WithRouter";
import Conference from "./Conference";
import { MapDispatch, MapStateProps, OwnProps } from "./Conference.types";
import { connect } from 'react-redux'
import { getAddress, isConnecting } from 'decentraland-dapps/dist/modules/wallet/selectors'
import { getServer, getToken } from '../../../modules/conference/selector'
import { isLoggingIn } from '../../../modules/identity/selector'
import { RootState } from '../../../modules/reducer'
import withRouter from '../../../utils/WithRouter'
import Conference from './Conference'
import { MapDispatch, MapStateProps, OwnProps } from './Conference.types'
const mapStateToProps = (
state: RootState,
ownProps: OwnProps
): MapStateProps => {
const addressFromPath = ownProps.router.params.profileAddress;
const mapStateToProps = (state: RootState, ownProps: OwnProps): MapStateProps => {
const addressFromPath = ownProps.router.params.profileAddress
return {
profileAddress: addressFromPath?.toLowerCase(),
isLoading: isLoggingIn(state) || isConnecting(state),
loggedInAddress: getAddress(state)?.toLowerCase(),
server: getServer(state),
token: getToken(state),
};
};
token: getToken(state)
}
}
const mapDispatch = (_dispatch: MapDispatch): any => ({});
const mapDispatch = (_dispatch: MapDispatch): any => ({})
export default withRouter(connect(mapStateToProps, mapDispatch)(Conference));
export default withRouter(connect(mapStateToProps, mapDispatch)(Conference))

View File

@ -1,9 +1,9 @@
import React from "react"
import { Props } from "./Conference.types"
import { LiveKitRoom } from "@livekit/components-react"
import { VideoConference } from "../../VideoConference/Videoconference"
import "@livekit/components-styles"
import "./Conference.css"
import React from 'react'
import { LiveKitRoom } from '@livekit/components-react'
import '@livekit/components-styles'
import { VideoConference } from '../../VideoConference/Videoconference'
import { Props } from './Conference.types'
import './Conference.css'
export default function Conference(props: Props) {
const { token, server } = props

View File

@ -1,5 +1,5 @@
import { Dispatch } from "redux"
import { RouterProps } from "../../../utils/WithRouter"
import { Dispatch } from 'redux'
import { RouterProps } from '../../../utils/WithRouter'
export type Props = {
loggedInAddress?: string
@ -9,7 +9,7 @@ export type Props = {
token?: string
}
export type MapStateProps = Pick<Props, "loggedInAddress" | "isLoading" | "profileAddress" | "server" | "token">
export type MapStateProps = Pick<Props, 'loggedInAddress' | 'isLoading' | 'profileAddress' | 'server' | 'token'>
export type MapDispatch = Dispatch
type Params = {
profileAddress?: string

View File

@ -1,2 +1,2 @@
import Conference from "./Conference.container"
import Conference from './Conference.container'
export default Conference

View File

@ -1,8 +1,5 @@
import * as React from "react"
import type { WidgetState } from "@livekit/components-core"
import { isEqualTrackRef, isTrackReference, log, isWeb } from "@livekit/components-core"
import { RoomEvent, Track } from "livekit-client"
import type { TrackReferenceOrPlaceholder } from "@livekit/components-core"
import * as React from 'react'
import { isEqualTrackRef, isTrackReference, log, isWeb } from '@livekit/components-core'
import {
CarouselView,
Chat,
@ -17,9 +14,11 @@ import {
useCreateLayoutContext,
useParticipants,
usePinnedTracks,
useTracks,
} from "@livekit/components-react"
import { ParticipantTile } from "./ParticipantTile"
useTracks
} from '@livekit/components-react'
import { RoomEvent, Track } from 'livekit-client'
import { ParticipantTile } from './ParticipantTile'
import type { TrackReferenceOrPlaceholder, WidgetState } from '@livekit/components-core'
/**
* @public
@ -51,46 +50,42 @@ export function VideoConference({ chatMessageFormatter, ...props }: VideoConfere
const tracks = useTracks(
[
{ source: Track.Source.Camera, withPlaceholder: true },
{ source: Track.Source.ScreenShare, withPlaceholder: false },
{ source: Track.Source.ScreenShare, withPlaceholder: false }
],
{ updateOnlyOn: [RoomEvent.ActiveSpeakersChanged] }
)
const participants = useParticipants({
updateOnlyOn: [RoomEvent.ParticipantConnected, RoomEvent.ParticipantDisconnected],
updateOnlyOn: [RoomEvent.ParticipantConnected, RoomEvent.ParticipantDisconnected]
})
const widgetUpdate = (state: WidgetState) => {
log.debug("updating widget state", state)
log.debug('updating widget state', state)
setWidgetState(state)
}
const layoutContext = useCreateLayoutContext()
const screenShareTracks = tracks
.filter(isTrackReference)
.filter((track) => track.publication.source === Track.Source.ScreenShare)
const screenShareTracks = tracks.filter(isTrackReference).filter(track => track.publication.source === Track.Source.ScreenShare)
const focusTrack = usePinnedTracks(layoutContext)?.[0]
const carouselTracks = tracks.filter((track) => !isEqualTrackRef(track, focusTrack))
const carouselTracks = tracks.filter(track => !isEqualTrackRef(track, focusTrack))
React.useEffect(() => {
// If screen share tracks are published, and no pin is set explicitly, auto set the screen share.
if (screenShareTracks.length > 0 && lastAutoFocusedScreenShareTrack.current === null) {
log.debug("Auto set screen share focus:", { newScreenShareTrack: screenShareTracks[0] })
layoutContext.pin.dispatch?.({ msg: "set_pin", trackReference: screenShareTracks[0] })
log.debug('Auto set screen share focus:', { newScreenShareTrack: screenShareTracks[0] })
layoutContext.pin.dispatch?.({ msg: 'set_pin', trackReference: screenShareTracks[0] })
lastAutoFocusedScreenShareTrack.current = screenShareTracks[0]
} else if (
lastAutoFocusedScreenShareTrack.current &&
!screenShareTracks.some(
(track) => track.publication.trackSid === lastAutoFocusedScreenShareTrack.current?.publication?.trackSid
)
!screenShareTracks.some(track => track.publication.trackSid === lastAutoFocusedScreenShareTrack.current?.publication?.trackSid)
) {
log.debug("Auto clearing screen share focus.")
layoutContext.pin.dispatch?.({ msg: "clear_pin" })
log.debug('Auto clearing screen share focus.')
layoutContext.pin.dispatch?.({ msg: 'clear_pin' })
lastAutoFocusedScreenShareTrack.current = null
}
}, [screenShareTracks.map((ref) => ref.publication.trackSid).join(), focusTrack?.publication?.trackSid])
}, [screenShareTracks.map(ref => ref.publication.trackSid).join(), focusTrack?.publication?.trackSid])
return (
<div className="lk-video-conference" {...props}>
@ -119,7 +114,7 @@ export function VideoConference({ chatMessageFormatter, ...props }: VideoConfere
)}
<ControlBar controls={{ chat: true }} />
</div>
<Chat style={{ display: widgetState.showChat ? "flex" : "none" }} messageFormatter={chatMessageFormatter} />
<Chat style={{ display: widgetState.showChat ? 'flex' : 'none' }} messageFormatter={chatMessageFormatter} />
</LayoutContextProvider>
)}
<RoomAudioRenderer />

View File

@ -1,35 +1,35 @@
/* eslint-disable import/order */
import "semantic-ui-css/semantic.min.css"
import React from "react"
import ReactDOM from "react-dom"
import { Provider } from "react-redux"
import { RouterProvider, createBrowserRouter } from "react-router-dom"
import ModalProvider from "decentraland-dapps/dist/providers/ModalProvider"
import TranslationProvider from "decentraland-dapps/dist/providers/TranslationProvider"
import WalletProvider from "decentraland-dapps/dist/providers/WalletProvider"
import * as modals from "./components/Modals"
import ConnectToWorld from "./components/Pages/ConnectToWorld"
import SignInPage from "./components/Pages/SignInPage"
import { initStore } from "./modules/store"
import * as locales from "./modules/translation/locales"
import Conference from "./components/Pages/Conference"
import 'semantic-ui-css/semantic.min.css'
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { RouterProvider, createBrowserRouter } from 'react-router-dom'
import ModalProvider from 'decentraland-dapps/dist/providers/ModalProvider'
import TranslationProvider from 'decentraland-dapps/dist/providers/TranslationProvider'
import WalletProvider from 'decentraland-dapps/dist/providers/WalletProvider'
import * as modals from './components/Modals'
import ConnectToWorld from './components/Pages/ConnectToWorld'
import SignInPage from './components/Pages/SignInPage'
import { initStore } from './modules/store'
import * as locales from './modules/translation/locales'
import Conference from './components/Pages/Conference'
// These CSS styles must be defined last to avoid overriding other styles
import "decentraland-ui/dist/themes/alternative/light-theme.css"
import "./index.css"
import 'decentraland-ui/dist/themes/alternative/light-theme.css'
import './index.css'
const router = createBrowserRouter([
{
path: "/",
element: <ConnectToWorld />,
path: '/',
element: <ConnectToWorld />
},
{
path: "sign-in",
element: <SignInPage />,
path: 'sign-in',
element: <SignInPage />
},
{
path: "/meet/:server",
element: <Conference />,
},
path: '/meet/:server',
element: <Conference />
}
])
const component = (
@ -46,4 +46,4 @@ const component = (
</React.StrictMode>
)
ReactDOM.render(component, document.getElementById("root") as HTMLElement)
ReactDOM.render(component, document.getElementById('root') as HTMLElement)

View File

@ -1,9 +1,9 @@
import { createAction } from "@reduxjs/toolkit"
import { createAction } from '@reduxjs/toolkit'
export const setServer = createAction<{ server: string }>("Set Server")
export const setServer = createAction<{ server: string }>('Set Server')
export type SetServerAction = ReturnType<typeof setServer>
export const setToken = createAction<{ token: string }>("Set Token")
export const setToken = createAction<{ token: string }>('Set Token')
export type SetTokenAction = ReturnType<typeof setToken>

View File

@ -1,5 +1,5 @@
import { createReducer } from "@reduxjs/toolkit"
import { setServer, setToken } from "./action"
import { createReducer } from '@reduxjs/toolkit'
import { setServer, setToken } from './action'
export type ConferenceState = {
token: string
@ -7,11 +7,11 @@ export type ConferenceState = {
}
export const INITIAL_STATE: ConferenceState = {
token: "",
server: "",
token: '',
server: ''
}
export const conferenceReducer = createReducer<ConferenceState>(INITIAL_STATE, (builder) =>
export const conferenceReducer = createReducer<ConferenceState>(INITIAL_STATE, builder =>
builder
.addCase(setServer, (state, action) => {
state.server = action.payload.server

View File

@ -1,9 +1,9 @@
import { createSelector } from "@reduxjs/toolkit"
import { RootState } from "../reducer"
import { createSelector } from '@reduxjs/toolkit'
import { RootState } from '../reducer'
const getState = (state: RootState) => state.conference
export const getToken = (state: RootState) => getState(state).token
export const getServer = (state: RootState) => getState(state).server
export const isLoading = createSelector([getToken], (token) => !!token)
export const isLoading = createSelector([getToken], token => !!token)

View File

@ -1,19 +1,12 @@
import { configureStore, Reducer, Middleware, AnyAction, combineReducers, Store } from "@reduxjs/toolkit"
import { FeaturesState, featuresReducer as features } from "decentraland-dapps/dist/modules/features/reducer"
import { ModalState, modalReducer as modal } from "decentraland-dapps/dist/modules/modal/reducer"
import { ProfileState, profileReducer as profile } from "decentraland-dapps/dist/modules/profile/reducer"
import {
StorageState,
storageReducer as storage,
storageReducerWrapper,
} from "decentraland-dapps/dist/modules/storage/reducer"
import {
TranslationState,
translationReducer as translation,
} from "decentraland-dapps/dist/modules/translation/reducer"
import { WalletState, walletReducer as wallet } from "decentraland-dapps/dist/modules/wallet/reducer"
import { IdentityState, identityReducer as identity } from "./identity/reducer"
import { ConferenceState, conferenceReducer as conference } from "./conference/reducer"
import { configureStore, Reducer, Middleware, AnyAction, combineReducers, Store } from '@reduxjs/toolkit'
import { FeaturesState, featuresReducer as features } from 'decentraland-dapps/dist/modules/features/reducer'
import { ModalState, modalReducer as modal } from 'decentraland-dapps/dist/modules/modal/reducer'
import { ProfileState, profileReducer as profile } from 'decentraland-dapps/dist/modules/profile/reducer'
import { StorageState, storageReducer as storage, storageReducerWrapper } from 'decentraland-dapps/dist/modules/storage/reducer'
import { TranslationState, translationReducer as translation } from 'decentraland-dapps/dist/modules/translation/reducer'
import { WalletState, walletReducer as wallet } from 'decentraland-dapps/dist/modules/wallet/reducer'
import { ConferenceState, conferenceReducer as conference } from './conference/reducer'
import { IdentityState, identityReducer as identity } from './identity/reducer'
export const createRootReducer = (middlewares: Middleware[], preloadedState = {}) =>
configureStore({
@ -26,25 +19,19 @@ export const createRootReducer = (middlewares: Middleware[], preloadedState = {}
translation: translation as Reducer<TranslationState, AnyAction>,
profile,
identity,
conference,
conference
})
),
preloadedState,
middleware: (getDefaultMiddleware) =>
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
thunk: false,
serializableCheck: {
// Ignore these action types
ignoredActions: [
"[Request] Login",
"[Success] Login",
"Open modal",
"REDUX_PERSISTENCE_SAVE",
"REDUX_PERSISTENCE_LOAD",
],
ignoredPaths: ["modal", "identity"],
},
}).concat(middlewares),
ignoredActions: ['[Request] Login', '[Success] Login', 'Open modal', 'REDUX_PERSISTENCE_SAVE', 'REDUX_PERSISTENCE_LOAD'],
ignoredPaths: ['modal', 'identity']
}
}).concat(middlewares)
})
// We need to build the Store type manually due to the storageReducerWrapper function not propagating the type correctly

View File

@ -1,8 +1,8 @@
export const locations = {
root: () => "/",
root: () => '/',
account: (address: string) => `/accounts/${address}`,
signIn: (redirectTo?: string) => {
return `/sign-in${redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ""}`
return `/sign-in${redirectTo ? `?redirectTo=${encodeURIComponent(redirectTo)}` : ''}`
},
meet: (server: string, token: string) => `/meet/${server}?token${token}`,
meet: (server: string, token: string) => `/meet/${server}?token${token}`
}

View File

@ -1,12 +1,12 @@
import { all } from "redux-saga/effects"
import { createAnalyticsSaga } from "decentraland-dapps/dist/modules/analytics/sagas"
import { featuresSaga } from "decentraland-dapps/dist/modules/features/sagas"
import { createProfileSaga } from "decentraland-dapps/dist/modules/profile/sagas"
import { createWalletSaga } from "decentraland-dapps/dist/modules/wallet/sagas"
import { config } from "./config"
import { identitySaga } from "./identity/sagas"
import { modalSagas } from "./modal/sagas"
import { translationSaga } from "./translation/sagas"
import { all } from 'redux-saga/effects'
import { createAnalyticsSaga } from 'decentraland-dapps/dist/modules/analytics/sagas'
import { featuresSaga } from 'decentraland-dapps/dist/modules/features/sagas'
import { createProfileSaga } from 'decentraland-dapps/dist/modules/profile/sagas'
import { createWalletSaga } from 'decentraland-dapps/dist/modules/wallet/sagas'
import { config } from './config'
import { identitySaga } from './identity/sagas'
import { modalSagas } from './modal/sagas'
import { translationSaga } from './translation/sagas'
const analyticsSaga = createAnalyticsSaga()
@ -15,23 +15,23 @@ export function* rootSaga() {
analyticsSaga(),
createWalletSaga({
// eslint-disable-next-line @typescript-eslint/naming-convention
CHAIN_ID: Number(config.get("CHAIN_ID")),
CHAIN_ID: Number(config.get('CHAIN_ID')),
// eslint-disable-next-line @typescript-eslint/naming-convention
POLL_INTERVAL: 0,
// eslint-disable-next-line @typescript-eslint/naming-convention
TRANSACTIONS_API_URL: "https://transactions-api.decentraland.org/v1",
TRANSACTIONS_API_URL: 'https://transactions-api.decentraland.org/v1'
})(),
translationSaga(),
identitySaga(),
modalSagas(),
createProfileSaga({ peerUrl: config.get("PEER_URL") })(),
createProfileSaga({ peerUrl: config.get('PEER_URL') })(),
featuresSaga({
polling: {
apps: [
/* Application name here */
],
delay: 60000 /** 60 seconds */,
},
}),
delay: 60000 /** 60 seconds */
}
})
])
}

View File

@ -1,25 +1,25 @@
import { createLogger } from "redux-logger"
import createSagasMiddleware from "redux-saga"
import { Env } from "@dcl/ui-env"
import { createAnalyticsMiddleware } from "decentraland-dapps/dist/modules/analytics/middleware"
import { createStorageMiddleware } from "decentraland-dapps/dist/modules/storage/middleware"
import { config } from "./config"
import { createRootReducer } from "./reducer"
import { rootSaga } from "./saga"
import { createLogger } from 'redux-logger'
import createSagasMiddleware from 'redux-saga'
import { Env } from '@dcl/ui-env'
import { createAnalyticsMiddleware } from 'decentraland-dapps/dist/modules/analytics/middleware'
import { createStorageMiddleware } from 'decentraland-dapps/dist/modules/storage/middleware'
import { config } from './config'
import { createRootReducer } from './reducer'
import { rootSaga } from './saga'
export function initStore() {
const sagasMiddleware = createSagasMiddleware()
const isDev = config.is(Env.DEVELOPMENT)
const loggerMiddleware = createLogger({
collapsed: () => true,
predicate: (_: any, action) => isDev || action.type.includes("Failure"),
predicate: (_: any, action) => isDev || action.type.includes('Failure')
})
const analyticsMiddleware = createAnalyticsMiddleware(config.get("SEGMENT_API_KEY"))
const analyticsMiddleware = createAnalyticsMiddleware(config.get('SEGMENT_API_KEY'))
const { storageMiddleware, loadStorageMiddleware } = createStorageMiddleware({
storageKey: "profile", // this is the key used to save the state in localStorage (required)
paths: [["identity", "data"]], // array of paths from state to be persisted (optional)
actions: ["[Success] Login", "Logout"], // array of actions types that will trigger a SAVE (optional)
migrations: {}, // migration object that will migrate your localstorage (optional)
storageKey: 'profile', // this is the key used to save the state in localStorage (required)
paths: [['identity', 'data']], // array of paths from state to be persisted (optional)
actions: ['[Success] Login', 'Logout'], // array of actions types that will trigger a SAVE (optional)
migrations: {} // migration object that will migrate your localstorage (optional)
})
const store = createRootReducer([sagasMiddleware, loggerMiddleware, analyticsMiddleware, storageMiddleware])
if (isDev) {

View File

@ -1,22 +1,19 @@
import createSagasMiddleware from "redux-saga";
import { createStorageMiddleware } from "decentraland-dapps/dist/modules/storage/middleware";
import { createRootReducer } from "../modules/reducer";
import { rootSaga } from "../modules/saga";
import createSagasMiddleware from 'redux-saga'
import { createStorageMiddleware } from 'decentraland-dapps/dist/modules/storage/middleware'
import { createRootReducer } from '../modules/reducer'
import { rootSaga } from '../modules/saga'
export function initTestStore(preloadedState = {}) {
const sagasMiddleware = createSagasMiddleware();
const sagasMiddleware = createSagasMiddleware()
const { storageMiddleware, loadStorageMiddleware } = createStorageMiddleware({
storageKey: "profile", // this is the key used to save the state in localStorage (required)
paths: [["identity", "data"]], // array of paths from state to be persisted (optional)
storageKey: 'profile', // this is the key used to save the state in localStorage (required)
paths: [['identity', 'data']], // array of paths from state to be persisted (optional)
actions: [], // array of actions types that will trigger a SAVE (optional)
migrations: {}, // migration object that will migrate your localstorage (optional)
});
const store = createRootReducer(
[sagasMiddleware, storageMiddleware],
preloadedState
);
sagasMiddleware.run(rootSaga);
loadStorageMiddleware(store);
migrations: {} // migration object that will migrate your localstorage (optional)
})
const store = createRootReducer([sagasMiddleware, storageMiddleware], preloadedState)
sagasMiddleware.run(rootSaga)
loadStorageMiddleware(store)
return store;
return store
}

View File

@ -1,7 +1,7 @@
import { RequestManager } from "eth-connect"
import { createUnsafeIdentity } from "@dcl/crypto/dist/crypto"
import { FlatFetchInit, flatFetch } from "./flat-fetch"
import { AuthChain, AuthIdentity, Authenticator } from "@dcl/crypto"
import { RequestManager } from 'eth-connect'
import { AuthChain, AuthIdentity, Authenticator } from '@dcl/crypto'
import { createUnsafeIdentity } from '@dcl/crypto/dist/crypto'
import { FlatFetchInit, flatFetch } from './flat-fetch'
const ephemeralLifespanMinutes = 10_000
@ -16,10 +16,7 @@ export type ExplorerIdentity = {
signer: (message: string) => Promise<string>
}
export async function getUserAccount(
requestManager: RequestManager,
returnChecksum: boolean
): Promise<string | undefined> {
export async function getUserAccount(requestManager: RequestManager, returnChecksum: boolean): Promise<string | undefined> {
try {
const accounts = await requestManager.eth_accounts()
@ -33,25 +30,20 @@ export async function getUserAccount(
}
}
const AUTH_CHAIN_HEADER_PREFIX = "x-identity-auth-chain-"
const AUTH_TIMESTAMP_HEADER = "x-identity-timestamp"
const AUTH_METADATA_HEADER = "x-identity-metadata"
const AUTH_CHAIN_HEADER_PREFIX = 'x-identity-auth-chain-'
const AUTH_TIMESTAMP_HEADER = 'x-identity-timestamp'
const AUTH_METADATA_HEADER = 'x-identity-metadata'
export function getAuthChainSignature(
method: string,
path: string,
metadata: string,
chainProvider: (payload: string) => AuthChain
) {
export function getAuthChainSignature(method: string, path: string, metadata: string, chainProvider: (payload: string) => AuthChain) {
const timestamp = Date.now()
const payloadParts = [method.toLowerCase(), path.toLowerCase(), timestamp.toString(), metadata]
const payloadToSign = payloadParts.join(":").toLowerCase()
const payloadToSign = payloadParts.join(':').toLowerCase()
const authChain = chainProvider(payloadToSign)
return {
authChain,
metadata,
timestamp,
timestamp
}
}
@ -72,28 +64,23 @@ export function getSignedHeaders(
return headers
}
export function signedFetch(
url: string,
identity: AuthIdentity,
init?: FlatFetchInit,
additionalMetadata: Record<string, any> = {}
) {
export function signedFetch(url: string, identity: AuthIdentity, init?: FlatFetchInit, additionalMetadata: Record<string, any> = {}) {
const path = new URL(url).pathname
const actualInit = {
...init,
headers: {
...getSignedHeaders(
init?.method ?? "get",
init?.method ?? 'get',
path,
{
origin: location.origin,
...additionalMetadata,
...additionalMetadata
},
(payload) => Authenticator.signPayload(identity, payload)
payload => Authenticator.signPayload(identity, payload)
),
...init?.headers,
},
...init?.headers
}
} as FlatFetchInit
return flatFetch(url, actualInit)
@ -104,10 +91,7 @@ export function signedFetch(
// the ephemeral private key is used to sign the rest of the authChain and subsequent
// messages. this is a good way to not over-expose the real user accounts to excessive
// signing requests.
export async function identityFromSigner(
address: string,
signer: (message: string) => Promise<string>
): Promise<ExplorerIdentity> {
export async function identityFromSigner(address: string, signer: (message: string) => Promise<string>): Promise<ExplorerIdentity> {
const ephemeral = createUnsafeIdentity()
const authChain = await Authenticator.initializeAuthChain(address, ephemeral, ephemeralLifespanMinutes, signer)
@ -116,6 +100,6 @@ export async function identityFromSigner(
address,
signer,
authChain,
isGuest: true,
isGuest: true
}
}

View File

@ -1,19 +1,19 @@
import { useEffect, useState } from "react"
import { useEffect, useState } from 'react'
export function useServerUrl(region?: string) {
const [serverUrl, setServerUrl] = useState<string | undefined>()
useEffect(() => {
let endpoint = `/api/url`
let endpoint = '/api/url'
if (region) {
endpoint += `?region=${region}`
}
fetch(endpoint).then(async (res) => {
fetch(endpoint).then(async res => {
if (res.ok) {
const body = await res.json()
console.log(body)
setServerUrl(body.url)
} else {
throw Error("Error fetching server url, check server logs")
throw Error('Error fetching server url, check server logs')
}
})
})

View File

@ -7,14 +7,14 @@ type FlatFetchResponse = {
text?: string
}
type BodyType = "json" | "text"
type BodyType = 'json' | 'text'
export type FlatFetchInit = RequestInit & { responseBodyType?: BodyType }
export async function flatFetch(url: string, init?: FlatFetchInit): Promise<FlatFetchResponse> {
const response = await fetch(url, init)
const responseBodyType = init?.responseBodyType || "text"
const responseBodyType = init?.responseBodyType || 'text'
const headers: Record<string, string> = {}
@ -24,14 +24,14 @@ export async function flatFetch(url: string, init?: FlatFetchInit): Promise<Flat
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers,
headers
}
switch (responseBodyType) {
case "json":
case 'json':
flatFetchResponse.json = await response.json()
break
case "text":
case 'text':
flatFetchResponse.text = await response.text()
break
}

View File

@ -1,12 +1,12 @@
import { RoomServiceClient } from "livekit-server-sdk"
import { RoomServiceClient } from 'livekit-server-sdk'
export function getRoomClient(): RoomServiceClient {
checkKeys()
return new RoomServiceClient(getLiveKitURL())
return new RoomServiceClient(getLiveKitUrl())
}
export function getLiveKitURL(region?: string | string[]): string {
let targetKey = "LIVEKIT_URL"
export function getLiveKitUrl(region?: string | string[]): string {
let targetKey = 'LIVEKIT_URL'
if (region && !Array.isArray(region)) {
targetKey = `LIVEKIT_URL_${region}`.toUpperCase()
}
@ -18,10 +18,10 @@ export function getLiveKitURL(region?: string | string[]): string {
}
function checkKeys() {
if (typeof process.env.LIVEKIT_API_KEY === "undefined") {
throw new Error("LIVEKIT_API_KEY is not defined")
if (typeof process.env.LIVEKIT_API_KEY === 'undefined') {
throw new Error('LIVEKIT_API_KEY is not defined')
}
if (typeof process.env.LIVEKIT_API_SECRET === "undefined") {
throw new Error("LIVEKIT_API_SECRET is not defined")
if (typeof process.env.LIVEKIT_API_SECRET === 'undefined') {
throw new Error('LIVEKIT_API_SECRET is not defined')
}
}

View File

@ -1,4 +1,4 @@
import { LocalAudioTrack, LocalVideoTrack } from "livekit-client"
import { LocalAudioTrack, LocalVideoTrack } from 'livekit-client'
export interface SessionProps {
roomName: string