Skip to content

Commit

Permalink
Fix dynamic import of atmosphere
Browse files Browse the repository at this point in the history
Fixes #2867
  • Loading branch information
krissvaa committed Nov 13, 2024
1 parent 62fa608 commit 33b8cc7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
25 changes: 11 additions & 14 deletions packages/ts/frontend/src/FluxConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import {
type ServerMessage,
} from './FluxMessages.js';

let atmosphere: Atmosphere.Atmosphere;

export enum State {
ACTIVE = 'active',
INACTIVE = 'inactive',
Expand Down Expand Up @@ -73,6 +71,15 @@ type EndpointInfo = {
reconnect?(): ActionOnLostSubscription | void;
};

const initAtmosphere = async () => {
if (!import.meta.env.VITE_SW_CONTEXT) {
return await import('atmosphere.js').then((module) => module.default);
}
return undefined;
};

const atmosphere: Atmosphere.Atmosphere | undefined = await initAtmosphere();

/**
* A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods.
*/
Expand All @@ -91,17 +98,7 @@ export class FluxConnection extends EventTarget {

constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {
super();
if (!import.meta.env['VITE_SW_CONTEXT']) {
import('atmosphere.js')
.then((module) => {
atmosphere = module.default;
this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});
})
.catch((error) => {
// eslint-disable-next-line no-console
console.error('Failed to load atmosphere', error);
});
}
this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});
}

#resubscribeIfWasClosed() {
Expand Down Expand Up @@ -198,7 +195,7 @@ export class FluxConnection extends EventTarget {
const extraHeaders = self.document ? getCsrfTokenHeadersForEndpointRequest(self.document) : {};
const pushUrl = 'HILLA/push';
const url = prefix.length === 0 ? pushUrl : (prefix.endsWith('/') ? prefix : `${prefix}/`) + pushUrl;
this.#socket = atmosphere.subscribe?.({
this.#socket = atmosphere?.subscribe?.({
contentType: 'application/json; charset=UTF-8',
enableProtocol: true,
transport: 'websocket',
Expand Down
2 changes: 1 addition & 1 deletion packages/ts/frontend/src/vite-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

// eslint-disable-next-line import/unambiguous
interface ImportMetaEnv {
readonly VITE_SW_CONTEXT: boolean;
readonly VITE_SW_CONTEXT?: boolean;
}

interface ImportMeta {
Expand Down

0 comments on commit 33b8cc7

Please sign in to comment.