Spaces:
Running
Running
File size: 7,972 Bytes
b39afbe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 |
/**
* Copyright (c) 2023 MERCENARIES.AI PTE. LTD.
* All rights reserved.
*/
import OmniSDKShared from './OmniSDKShared';
import {
OmniSDKClientEvents,
type IOmniCScriptResult,
type IOmniClientChatMessage,
type IOmniClientRunClientScript,
type IOmniClientSignalIntentMessage,
type IOmniClientWindowMessage,
type IOmniHostSyncData,
type IOmniMessage,
OmniSDKClientMessages,
OmniSDKHostMessages,
OmniSDKStorageKeys,
type IOmniClientShowToastMessage,
type IOmniHostCustomEventMessage,
type IOmniHostChatMessageReceived,
type IOmniClientShowExtensionMessage,
type IOmniClientLoadRecipeMessage,
type IOmniClientShowTopBannerMessage
} from './types';
export default class OmniSDKClient extends OmniSDKShared {
options: any;
args: any;
token: string;
_extensionId: string;
constructor(extensionId: string) {
super();
this._isClient = true; // Indicate that this is a client instance
this._extensionId = extensionId;
const args = new URLSearchParams(location.search);
this.options = JSON.parse(args.get('o') || '{}');
this.args = JSON.parse(args.get('q') || '{}');
if (args.has('omniHash')) {
this.token = args.get('omniHash')!;
} else {
console.warn('No omniHash found in the query string, this is not a window opened by OmniHost');
this.token = extensionId + new Date().getTime().toString();
}
}
public get extensionId(): string {
return this._extensionId;
}
public init( {subscriptions}: {subscriptions: OmniSDKHostMessages[]} = {subscriptions: []}) {
console.log('OmniSDKClient initialized for ' + this.extensionId + '.');
// Loading intentmap from local storage
const intentMapString = window.localStorage.getItem(OmniSDKStorageKeys.INTENT_MAP);
if (intentMapString) {
const intentMap = JSON.parse(intentMapString);
if (intentMap && intentMap.length > 0) {
this.intentMap = new Map(intentMap);
}
}
this.addMessageHandler(OmniSDKHostMessages.CLIENT_SCRIPT_RESPONSE, this._handleClientScriptResponse);
this.addMessageHandler(OmniSDKHostMessages.SYNC_DATA, this._handleSyncData);
if (subscriptions.includes(OmniSDKHostMessages.CUSTOM_EVENT)) this.addMessageHandler(OmniSDKHostMessages.CUSTOM_EVENT, this._handleCustomEvent);
if (subscriptions.includes(OmniSDKHostMessages.CHAT_MESSAGE_RECEIVED)) this.addMessageHandler(OmniSDKHostMessages.CHAT_MESSAGE_RECEIVED, this._handleChatMessageReceived);
this.register();
return this;
}
public register(): void {
if (this.token) {
this.send({ type: OmniSDKClientMessages.REGISTRATION, token: this.token });
} else {
// Not a window opened by OmniHost`, messages won't be used.
}
}
public deregister(token: string): void {
this.send({ type: OmniSDKClientMessages.DEREGISTRATION, token: token });
}
public sendChatMessage(
content: string,
type: string = 'text/markdown',
attachments?: { [key: string]: any },
flags?: string[]
): void {
const message: IOmniClientChatMessage = {
type: OmniSDKClientMessages.SEND_CHAT_MESSAGE,
message: {
content,
type,
attachments,
flags
}
};
this.send(message);
}
// Runs a client script and responds with the result
public async runClientScript(scriptName: string, payload: any) {
const message: IOmniClientRunClientScript = {
type: OmniSDKClientMessages.RUN_CLIENT_SCRIPT,
script: scriptName,
args: payload,
invokeId: this.extensionId + new Date().getTime().toString()
};
return new Promise((resolve, reject) => {
this.send(message);
this.events.once(OmniSDKHostMessages.CLIENT_SCRIPT_RESPONSE + ':' + message.invokeId).then((result) => {
resolve(result);
});
});
}
private async _handleCustomEvent(message: IOmniMessage): Promise<void> {
if (message.type !== OmniSDKHostMessages.CUSTOM_EVENT) return;
const msg = message as IOmniHostCustomEventMessage;
if (msg.extensionId !== this.extensionId) return;
await this.events.emit(OmniSDKClientEvents.CUSTOM_EVENT, { eventId: msg.eventId, eventArgs: msg.eventArgs });
}
private async _handleSyncData(message: IOmniMessage): Promise<void> {
if (message.type !== OmniSDKHostMessages.SYNC_DATA) return; // type guard
const msg = message as IOmniHostSyncData;
this.intentMap = new Map(msg.frame);
await this.events.emit(OmniSDKClientEvents.DATA_UPDATED, [{ property: 'intentMap' }]);
}
private async _handleChatMessageReceived(message: IOmniMessage): Promise<void> {
if (message.type !== OmniSDKHostMessages.CHAT_MESSAGE_RECEIVED) return; // type guard
const msg = message as IOmniHostChatMessageReceived;
await this.events.emit(OmniSDKClientEvents.CHAT_MESSAGE_RECEIVED, [msg.message]);
}
private async _handleClientScriptResponse(message: IOmniMessage): Promise<void> {
if (message.type !== OmniSDKHostMessages.CLIENT_SCRIPT_RESPONSE) return; // type guard
const msg = message as IOmniCScriptResult;
await this.events.emit(OmniSDKHostMessages.CLIENT_SCRIPT_RESPONSE + ':' + msg.invokeId, msg.result);
}
public showExtension(
extensionId: string,
args: any,
page: string = '',
opts: any = {},
action: 'open' | 'close' = 'open'
) {
const msg: IOmniClientShowExtensionMessage = {
type: OmniSDKClientMessages.SHOW_EXTENSION,
extensionId,
action,
args,
page,
opts
};
this.send(msg);
}
public hide() {
const msg: IOmniClientWindowMessage = {
type: OmniSDKClientMessages.WINDOW_MESSAGE,
action: 'hide',
args: {}
};
this.send(msg);
}
public show() {
const msg: IOmniClientWindowMessage = {
type: OmniSDKClientMessages.WINDOW_MESSAGE,
action: 'show',
args: {}
};
this.send(msg);
}
public close() {
const msg: IOmniClientWindowMessage = {
type: OmniSDKClientMessages.WINDOW_MESSAGE,
action: 'close',
args: {}
};
this.send(msg);
}
public signalIntent(intent: 'show' | 'edit', target: string, payload: any, opts = {}): void {
const message: IOmniClientSignalIntentMessage = {
type: OmniSDKClientMessages.SIGNAL_INTENT,
intent,
target,
opts: opts || {},
payload
};
this.send(message);
}
public showToast(
message: string,
options: {
description?: string;
type?: 'default' | 'danger' | 'success' | 'warning' | 'info';
position?: string;
html?: string;
}
): void {
const msg: IOmniClientShowToastMessage = {
type: OmniSDKClientMessages.SHOW_TOAST,
message,
options
};
this.send(msg);
}
public showTopBanner(
bannerTitle: string,
bannerDescription: string,
options: {
link?: string;
}
): void {
const msg: IOmniClientShowTopBannerMessage = {
type: OmniSDKClientMessages.SHOW_TOP_BANNER,
bannerTitle,
bannerDescription,
options
};
this.send(msg);
}
public openRecipeInEditor(recipeId: string, recipeVersion: string): void {
const msg: IOmniClientLoadRecipeMessage = {
type: OmniSDKClientMessages.LOAD_RECIPE,
recipeId,
recipeVersion
};
this.send(msg);
}
public async runExtensionScript(scriptName: string, payload: any) {
const response = await this._httpClient.executeRequest(
`/api/v1/mercenaries/runscript/${this.extensionId}:` + scriptName,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
}
);
if (!response.ok) {
throw new Error('Server error: HTTP status ' + response.status);
}
const data = await response.json();
return data;
}
// You can add more handlers if required for other types of messages that the ClientSDK might receive from OmniHost
}
|