From 6dffeddb0faa344028a182d487b72e35e13920fb Mon Sep 17 00:00:00 2001 From: Ryan Hinchey Date: Tue, 3 Sep 2024 15:30:19 -0400 Subject: [PATCH] feat: return data from connect() --- .changeset/four-hats-allow.md | 5 ++++ src/api.ts | 6 +++-- tests/connect.test.ts | 45 ++++++++++++++++++++++++++++++++++- 3 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 .changeset/four-hats-allow.md diff --git a/.changeset/four-hats-allow.md b/.changeset/four-hats-allow.md new file mode 100644 index 0000000..72d25cb --- /dev/null +++ b/.changeset/four-hats-allow.md @@ -0,0 +1,5 @@ +--- +'@crowdstrike/foundry-js': minor +--- + +return initial data from connect() diff --git a/src/api.ts b/src/api.ts index 3e21b2e..5f7bf44 100644 --- a/src/api.ts +++ b/src/api.ts @@ -92,11 +92,11 @@ export default class FalconApi { * * This establishes a connection to send messages between the extension and the Falcon Console. Only when established you will be able to call other APIs. */ - public async connect(): Promise { + public async connect(): Promise<{ origin: string; data?: DATA }> { const response = await this.bridge.postMessage({ type: 'connect' }); if (response !== undefined) { - const { origin, data } = response; + const { data, origin } = response; this.bridge.setOrigin(origin); this.data = data; @@ -107,6 +107,8 @@ export default class FalconApi { } this.resizeTracker = new ResizeTracker(this.bridge); + + return response; } /** diff --git a/tests/connect.test.ts b/tests/connect.test.ts index 2831a87..c3fd983 100644 --- a/tests/connect.test.ts +++ b/tests/connect.test.ts @@ -1,4 +1,4 @@ -import FalconApi from '../src'; +import FalconApi, { type LocalData } from '../src'; import { afterEach, beforeEach, expect, test } from 'vitest'; import type { @@ -46,6 +46,49 @@ test('it can connect to main thread', async () => { expect(api.isConnected).toEqual(true); }); +test('it returns data when connected', async () => { + const testData: LocalData = { + app: { + id: 'testid', + }, + user: { + uuid: '123', + username: 'johndoe', + }, + theme: 'theme-light', + cid: 'xxx', + locale: 'en-us', + }; + + const testOrigin = 'www.example.com'; + + // simulate ready answer coming back from main thread + window.parent.addEventListener( + 'message', + (message: MessageEvent>) => { + const response: MessageEnvelope = { + message: { + type: 'connect', + payload: { + origin: testOrigin, + data: testData, + }, + }, + meta: { + messageId: message.data.meta.messageId, + version: 'current', + }, + }; + + window.postMessage(response); + }, + ); + + const { data, origin } = await api.connect(); + expect(data).toEqual(testData); + expect(origin).toEqual(testOrigin); +}); + test('failed connect attempt will time out', async () => { await expect(api.connect()).rejects.toThrow(); });