@corti/embedded-web 0.1.0-alpha.3 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,12 +15,6 @@ A web component and React component library that provides an embedded interface
15
15
  npm install @corti/embedded-web
16
16
  ```
17
17
 
18
- The package provides a web component by default. For React usage, also install React as a peer dependency:
19
-
20
- ```bash
21
- npm install react @types/react
22
- ```
23
-
24
18
  ## Usage
25
19
 
26
20
  ### Web Component
@@ -55,6 +49,21 @@ await myComponent.navigate('/interactions/123');
55
49
  await myComponent.show()
56
50
  ```
57
51
 
52
+ #### Generic Event Listener (Web Component)
53
+
54
+ Use `embedded-event` as the canonical event stream for web component integrations.
55
+
56
+ - Event detail shape is `{ name: string; payload: unknown }`.
57
+ - Full event catalog and payload details are documented at:
58
+ - https://docs.corti.ai/assistant/events
59
+
60
+ ```js
61
+ myComponent.addEventListener('embedded-event', event => {
62
+ const { detail } = event;
63
+ console.log(detail.name, detail.payload);
64
+ });
65
+ ```
66
+
58
67
  ### React Component
59
68
 
60
69
  ```tsx
@@ -62,33 +71,44 @@ import React, { useRef } from 'react';
62
71
  import {
63
72
  CortiEmbeddedReact,
64
73
  type CortiEmbeddedReactRef,
65
- type EmbeddedEventData,
74
+ useCortiEmbeddedApi,
75
+ useCortiEmbeddedStatus,
66
76
  } from '@corti/embedded-web/react';
67
77
 
68
78
  function App() {
69
79
  const cortiRef = useRef<CortiEmbeddedReactRef>(null);
80
+ const api = useCortiEmbeddedApi(cortiRef);
81
+ const { status } = useCortiEmbeddedStatus(cortiRef);
70
82
 
71
83
  const handleReady = () => {
72
84
  console.log('Corti component is ready!');
73
- cortiRef.current?.show();
74
85
  };
75
86
 
76
- const handleAuthChanged = (
77
- event: CustomEvent<EmbeddedEventData['auth-changed']>,
87
+ const handleEvent = (
88
+ event: CustomEvent<{ name: string; payload: unknown }>,
78
89
  ) => {
79
- console.log('User authenticated:', event.detail.user);
90
+ console.log('Event name:', event.detail.name);
91
+ console.log('Event payload:', event.detail.payload);
80
92
  };
81
93
 
82
94
  const handleAuth = async () => {
83
- if (!cortiRef.current) return;
84
-
85
95
  try {
86
- const user = await cortiRef.current.auth({
96
+ const user = await api.auth({
87
97
  access_token: 'your-token',
88
98
  token_type: 'Bearer',
89
99
  // ... rest of the token response
90
100
  });
91
101
  console.log('Authenticated:', user);
102
+
103
+ await api.configureSession({ defaultTemplateKey: 'soap_note' });
104
+ await api.createInteraction({
105
+ encounter: {
106
+ identifier: `encounter-${Date.now()}`,
107
+ status: 'planned',
108
+ type: 'first_consultation',
109
+ period: { startedAt: new Date().toISOString() },
110
+ },
111
+ });
92
112
  } catch (error) {
93
113
  console.error('Auth failed:', error);
94
114
  }
@@ -103,10 +123,12 @@ function App() {
103
123
  baseURL="https://assistant.eu.corti.app" // REQUIRED
104
124
  visibility="visible"
105
125
  onReady={handleReady}
126
+ onEvent={handleEvent}
127
+ onError={event => console.error('Embedded error:', event.detail)}
106
128
  style={{ width: '100%', height: '500px' }}
107
- // or use className
108
- className="w-full h-full"
109
129
  />
130
+
131
+ <pre>{JSON.stringify(status, null, 2)}</pre>
110
132
  </div>
111
133
  );
112
134
  }
@@ -130,11 +152,22 @@ component.hide();
130
152
 
131
153
  #### auth
132
154
 
155
+ Authentication is required before using the embedded app. The payload passed to
156
+ `component.auth(...)` should come directly from your identity provider token
157
+ response (for example, Keycloak/OIDC token endpoint response), plus `mode`.
158
+
159
+ - API details and payload shape: https://docs.corti.ai/assistant/api-reference#auth
160
+ - End-to-end authentication guidance: https://docs.corti.ai/assistant/authentication
161
+
162
+ Use user-based authentication (OAuth2/OIDC). Client-credentials-only flows are
163
+ not supported for the embedded app.
164
+
133
165
  ```javascript
134
166
  const authResponse = await component.auth({
135
- // Example: Keycloak-style token + mode
167
+ // Use the full token response from your IdP + mode
136
168
  access_token: 'YOUR_JWT',
137
169
  token_type: 'Bearer',
170
+ // include other token fields from your provider response (expires_in, refresh_token, etc.)
138
171
  mode: 'stateful',
139
172
  ...
140
173
  });
@@ -211,10 +244,10 @@ The component uses a `PostMessageHandler` utility class that:
211
244
 
212
245
  The React component (`CortiEmbeddedReact`) is available as an additional export and provides:
213
246
 
214
- - **All Web Component APIs**: Full access to all methods via ref
215
- - **React Event Handlers**: Native React event handling with proper typing
216
- - **TypeScript Support**: Complete type definitions
217
- - **Forward Ref**: Access to the underlying component instance
247
+ - **Hook-based API access**: `useCortiEmbeddedApi(ref)` exposes instance-bound methods (`auth`, `navigate`, `createInteraction`, etc.)
248
+ - **Generic event stream**: `onEvent` receives all embedded events as `{ name, payload }`
249
+ - **Status hook**: `useCortiEmbeddedStatus(ref)` keeps latest status/reactive state
250
+ - **Multi-instance safety**: API methods are scoped to the ref you pass
218
251
  - **React Props**: Standard React props like `className`, `style`, etc.
219
252
 
220
253
  ### React Component Import
@@ -223,44 +256,59 @@ The React component (`CortiEmbeddedReact`) is available as an additional export
223
256
  import {
224
257
  CortiEmbeddedReact,
225
258
  CortiEmbedded, // Web component also available
226
- type CortiEmbeddedReactProps,
227
259
  type CortiEmbeddedReactRef,
260
+ useCortiEmbeddedApi,
261
+ useCortiEmbeddedStatus,
228
262
  } from '@corti/embedded-web/react';
229
263
  ```
230
264
 
231
- ### Available Events (React)
265
+ ### Event Listener Setup
232
266
 
233
- - `onReady`: Component is ready to receive API calls
234
- - `onAuthChanged`: User authentication status changed
235
- - `onInteractionCreated`: New interaction was created
236
- - `onRecordingStarted` / `onRecordingStopped`: Recording status changes
237
- - `onDocumentGenerated` / `onDocumentUpdated`: Document events
238
- - `onNavigationChanged`: Navigation within the embedded UI changed
239
- - `onUsage`: Usage data (credits used)
240
- - `onError`: An error occurred
267
+ - Use `onEvent` for all embedded events.
268
+ - Event detail shape is `{ name: string; payload: unknown }`.
269
+ - Full event catalog and payload details are documented at:
270
+ - https://docs.corti.ai/assistant/events
271
+
272
+ ```tsx
273
+ <CortiEmbeddedReact
274
+ baseURL="https://assistant.eu.corti.app"
275
+ onEvent={event => {
276
+ console.log(event.detail.name, event.detail.payload);
277
+ }}
278
+ onReady={() => console.log('Ready')}
279
+ onError={event => console.error(event.detail)}
280
+ />
281
+ ```
241
282
 
242
- ### Event Data Access
283
+ ### API Methods (React)
243
284
 
244
- Events in React carry data in the `detail` property:
285
+ Use the API hook with the same component ref:
245
286
 
246
287
  ```tsx
247
- import type {
248
- EmbeddedEventData,
249
- CortiEmbeddedReactProps,
288
+ import React, { useRef } from 'react';
289
+ import {
290
+ CortiEmbeddedReact,
291
+ type CortiEmbeddedReactRef,
292
+ useCortiEmbeddedApi,
250
293
  } from '@corti/embedded-web/react';
251
294
 
252
- // Method 1: Use typed event handler interface
253
- const handleAuthChanged: CortiEmbeddedReactProps['onAuthChanged'] = event => {
254
- console.log('User:', event.detail.user);
255
- };
256
-
257
- // Method 2: Cast events manually
258
- const handleDocumentGenerated = (event: Event) => {
259
- const customEvent = event as CustomEvent<
260
- EmbeddedEventData['document-generated']
261
- >;
262
- console.log('Document:', customEvent.detail.document);
263
- };
295
+ function Example() {
296
+ const ref = useRef<CortiEmbeddedReactRef>(null);
297
+ const api = useCortiEmbeddedApi(ref);
298
+
299
+ const run = async () => {
300
+ await api.auth({ access_token: '...', token_type: 'Bearer', mode: 'stateful' });
301
+ const created = await api.createInteraction({ encounter: { ... } });
302
+ await api.navigate(`/session/${created.id}`);
303
+ };
304
+
305
+ return (
306
+ <>
307
+ <button onClick={() => void run()}>Run</button>
308
+ <CortiEmbeddedReact ref={ref} baseURL="https://assistant.eu.corti.app" />
309
+ </>
310
+ );
311
+ }
264
312
  ```
265
313
 
266
314
  For detailed React usage examples, see [docs/react-usage.md](./docs/react-usage.md).
@@ -1,6 +1,6 @@
1
1
  import type { Corti } from '@corti/sdk';
2
2
  import { LitElement, type PropertyValues } from 'lit';
3
- import type { ConfigureAppPayload, SetCredentialsPayload, AuthCredentials, ConfigureAppResponsePayload, CortiEmbeddedAPI, InteractionDetails, CreateInteractionPayload, SessionConfig, User, GetStatusResponsePayload } from './types';
3
+ import type { ConfigureAppPayload, SetCredentialsPayload, AuthCredentials, ConfigureAppResponse, CortiEmbeddedAPI, InteractionDetails, CreateInteractionPayload, SessionConfig, User, GetStatusResponse, GetTemplatesResponse } from './types';
4
4
  export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAPI {
5
5
  static styles: import("lit").CSSResult[];
6
6
  visibility: string;
@@ -11,6 +11,7 @@ export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAP
11
11
  disconnectedCallback(): void;
12
12
  private setupPostMessageHandler;
13
13
  private dispatchPublicEvent;
14
+ private dispatchEmbeddedEvent;
14
15
  private dispatchErrorEvent;
15
16
  private isRealIframeLoad;
16
17
  private handleIframeLoad;
@@ -60,13 +61,13 @@ export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAP
60
61
  * Get current component status
61
62
  * @returns Promise resolving to current status
62
63
  */
63
- getStatus(): Promise<GetStatusResponsePayload>;
64
+ getStatus(): Promise<GetStatusResponse>;
64
65
  /**
65
66
  * Configure the component
66
67
  * @param config Component configuration
67
68
  * @returns Promise that resolves when configuration is applied
68
69
  */
69
- configure(config: ConfigureAppPayload): Promise<ConfigureAppResponsePayload>;
70
+ configure(config: ConfigureAppPayload): Promise<ConfigureAppResponse>;
70
71
  /**
71
72
  * Set authentication credentials without triggering auth flow
72
73
  * @param credentials Authentication credentials to store
@@ -81,6 +82,10 @@ export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAP
81
82
  * Hide the embedded UI
82
83
  */
83
84
  hide(): void;
85
+ /**
86
+ * Get templates
87
+ */
88
+ getTemplates(): Promise<GetTemplatesResponse>;
84
89
  /**
85
90
  * Check the current status of the iframe and PostMessageHandler
86
91
  * Useful for debugging
@@ -54,47 +54,8 @@ export class CortiEmbedded extends LitElement {
54
54
  const iframe = this.getIframe();
55
55
  if (iframe?.contentWindow) {
56
56
  const callbacks = {
57
- onReady: () => {
58
- this.dispatchPublicEvent('ready', undefined);
59
- },
60
- onAuthChanged: payload => {
61
- this.dispatchPublicEvent('auth-changed', { user: payload.user });
62
- },
63
- onInteractionCreated: payload => {
64
- this.dispatchPublicEvent('interaction-created', {
65
- interaction: payload.interaction,
66
- });
67
- },
68
- onRecordingStarted: () => {
69
- this.dispatchPublicEvent('recording-started', undefined);
70
- },
71
- onRecordingStopped: () => {
72
- this.dispatchPublicEvent('recording-stopped', undefined);
73
- },
74
- onDocumentGenerated: payload => {
75
- this.dispatchPublicEvent('document-generated', {
76
- document: payload.document,
77
- });
78
- },
79
- onDocumentUpdated: payload => {
80
- this.dispatchPublicEvent('document-updated', {
81
- document: payload.document,
82
- });
83
- },
84
- onDocumentSynced: payload => {
85
- this.dispatchPublicEvent('document-synced', {
86
- document: payload.document,
87
- });
88
- },
89
- onNavigationChanged: payload => {
90
- this.dispatchPublicEvent('navigation-changed', {
91
- path: payload.path,
92
- });
93
- },
94
- onUsage: payload => {
95
- this.dispatchPublicEvent('usage', {
96
- creditsConsumed: payload.creditsConsumed,
97
- });
57
+ onEvent: event => {
58
+ this.dispatchEmbeddedEvent(event.name, event.payload);
98
59
  },
99
60
  onError: error => {
100
61
  this.dispatchErrorEvent(error);
@@ -111,6 +72,14 @@ export class CortiEmbedded extends LitElement {
111
72
  dispatchPublicEvent(event, data) {
112
73
  this.dispatchEvent(new CustomEvent(event, { detail: data }));
113
74
  }
75
+ dispatchEmbeddedEvent(rawEventName, payload) {
76
+ // Preserve raw DOM event passthrough for consumers listening directly.
77
+ this.dispatchPublicEvent(rawEventName, payload);
78
+ this.dispatchPublicEvent('embedded-event', {
79
+ name: rawEventName,
80
+ payload,
81
+ });
82
+ }
114
83
  dispatchErrorEvent(error) {
115
84
  this.dispatchPublicEvent('error', error);
116
85
  }
@@ -407,6 +376,23 @@ export class CortiEmbedded extends LitElement {
407
376
  hide() {
408
377
  this.visibility = 'hidden';
409
378
  }
379
+ /**
380
+ * Get templates
381
+ */
382
+ async getTemplates() {
383
+ if (!this.postMessageHandler) {
384
+ throw new Error('Component not ready');
385
+ }
386
+ try {
387
+ const response = await this.postMessageHandler.getTemplates();
388
+ return response;
389
+ }
390
+ catch (error) {
391
+ const formattedError = formatError(error, 'Failed to get templates');
392
+ this.dispatchErrorEvent(formattedError);
393
+ throw new Error(JSON.stringify(formattedError));
394
+ }
395
+ }
410
396
  /**
411
397
  * Check the current status of the iframe and PostMessageHandler
412
398
  * Useful for debugging
@@ -1 +1 @@
1
- {"version":3,"file":"CortiEmbedded.js","sourceRoot":"","sources":["../src/CortiEmbedded.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EAAE,IAAI,EAAE,UAAU,EAAuB,MAAM,KAAK,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAkB7C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EACL,kBAAkB,GAEnB,MAAM,+BAA+B,CAAC;AAEvC,MAAM,OAAO,aAAc,SAAQ,UAAU;IAA7C;;QAIE,eAAU,GAAG,QAAQ,CAAC;QAKd,uBAAkB,GAA8B,IAAI,CAAC;QAErD,sBAAiB,GAAkB,IAAI,CAAC;IAudlD,CAAC;IArdC,iBAAiB;QACf,KAAK,CAAC,iBAAiB,EAAE,CAAC;QAE1B,6BAA6B;QAC7B,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,IAAI,CAAC,kBAAkB,CAAC;gBACtB,OAAO,EAAE,qBAAqB;aAC/B,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QAED,+DAA+D;QAC/D,IAAI,CAAC;YACH,IAAI,CAAC,iBAAiB,GAAG,2BAA2B,CAAC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AAC,CAAC,gBAAgB;YAClB,CAAC,CAAC,iBAAiB;;KAExB,CAAC;IACJ,CAAC;;AAheM,oBAAM,GAAG,CAAC,UAAU,EAAE,eAAe,CAAC,AAAhC,CAAiC;AAG9C;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;iDACpB;AAGtB;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;8CACzB","sourcesContent":["/* eslint-disable no-console */\nimport type { Corti } from '@corti/sdk';\nimport { html, LitElement, type PropertyValues } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport type {\n AddFactsPayload,\n AuthPayload,\n ConfigureAppPayload,\n ConfigureSessionPayload,\n NavigatePayload,\n SetCredentialsPayload,\n AuthCredentials,\n ConfigureAppResponsePayload,\n CortiEmbeddedAPI,\n EmbeddedEventData,\n InteractionDetails,\n CreateInteractionPayload,\n SessionConfig,\n User,\n GetStatusResponsePayload,\n} from './types';\nimport { baseStyles } from './styles/base.js';\nimport { containerStyles } from './styles/container-styles.js';\nimport { validateAndNormalizeBaseURL } from './utils/baseUrl.js';\nimport { buildEmbeddedUrl, isRealEmbeddedLoad } from './utils/embedUrl.js';\nimport { formatError } from './utils/errorFormatter.js';\nimport {\n PostMessageHandler,\n type PostMessageHandlerCallbacks,\n} from './utils/PostMessageHandler.js';\n\nexport class CortiEmbedded extends LitElement implements CortiEmbeddedAPI {\n static styles = [baseStyles, containerStyles];\n\n @property({ type: String, reflect: true })\n visibility = 'hidden';\n\n @property({ type: String, reflect: true })\n baseURL!: string;\n\n private postMessageHandler: PostMessageHandler | null = null;\n\n private normalizedBaseURL: string | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n\n // Ensure baseURL is provided\n if (!this.baseURL) {\n this.dispatchErrorEvent({\n message: 'baseURL is required',\n });\n return;\n }\n\n // Validate and normalize the initial baseURL early (fail fast)\n try {\n this.normalizedBaseURL = validateAndNormalizeBaseURL(this.baseURL);\n } catch (error) {\n this.dispatchErrorEvent({\n message: (error as Error).message || 'Invalid baseURL',\n });\n throw error;\n }\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this.postMessageHandler) {\n this.postMessageHandler.destroy();\n this.postMessageHandler = null;\n }\n }\n\n private async setupPostMessageHandler() {\n // Prevent multiple setups\n if (this.postMessageHandler) {\n return;\n }\n\n const iframe = this.getIframe();\n\n if (iframe?.contentWindow) {\n const callbacks: PostMessageHandlerCallbacks = {\n onReady: () => {\n this.dispatchPublicEvent('ready', undefined);\n },\n onAuthChanged: payload => {\n this.dispatchPublicEvent('auth-changed', { user: payload.user });\n },\n onInteractionCreated: payload => {\n this.dispatchPublicEvent('interaction-created', {\n interaction: payload.interaction,\n });\n },\n onRecordingStarted: () => {\n this.dispatchPublicEvent('recording-started', undefined);\n },\n onRecordingStopped: () => {\n this.dispatchPublicEvent('recording-stopped', undefined);\n },\n onDocumentGenerated: payload => {\n this.dispatchPublicEvent('document-generated', {\n document: payload.document,\n });\n },\n onDocumentUpdated: payload => {\n this.dispatchPublicEvent('document-updated', {\n document: payload.document,\n });\n },\n onDocumentSynced: payload => {\n this.dispatchPublicEvent('document-synced', {\n document: payload.document,\n });\n },\n onNavigationChanged: payload => {\n this.dispatchPublicEvent('navigation-changed', {\n path: payload.path,\n });\n },\n onUsage: payload => {\n this.dispatchPublicEvent('usage', {\n creditsConsumed: payload.creditsConsumed,\n });\n },\n onError: error => {\n this.dispatchErrorEvent(error);\n },\n };\n\n this.postMessageHandler = new PostMessageHandler(iframe, callbacks);\n } else {\n this.dispatchErrorEvent({\n message: 'No iframe or contentWindow available',\n });\n }\n }\n\n private dispatchPublicEvent<K extends keyof EmbeddedEventData>(\n event: K,\n data: EmbeddedEventData[K],\n ) {\n this.dispatchEvent(new CustomEvent(event, { detail: data }));\n }\n\n private dispatchErrorEvent(error: {\n message: string;\n code?: string;\n details?: unknown;\n }) {\n this.dispatchPublicEvent('error', error);\n }\n\n private isRealIframeLoad(iframe: HTMLIFrameElement): boolean {\n const src = iframe.getAttribute('src') || '';\n if (!this.normalizedBaseURL) return false;\n return isRealEmbeddedLoad(src, this.normalizedBaseURL);\n }\n\n private async handleIframeLoad(event: Event) {\n const iframe = event.target as HTMLIFrameElement | null;\n if (!iframe) {\n return;\n }\n // Only initialize on real URL load, ignore about:blank\n if (!this.isRealIframeLoad(iframe)) {\n return;\n }\n try {\n await this.setupPostMessageHandler();\n } catch (error) {\n this.dispatchErrorEvent({\n message: `Failed to setup PostMessageHandler on iframe load: ${error}`,\n });\n }\n }\n\n private getIframe(): HTMLIFrameElement | null {\n return this.shadowRoot?.querySelector('iframe') || null;\n }\n\n protected updated(changedProps: PropertyValues) {\n super.updated(changedProps);\n if (changedProps.has('baseURL')) {\n // Validate baseURL and normalize; fail fast on invalid input\n try {\n this.normalizedBaseURL = validateAndNormalizeBaseURL(this.baseURL);\n } catch (error) {\n // Tear down and clear iframe to avoid keeping an old origin active\n if (this.postMessageHandler) {\n this.postMessageHandler.destroy();\n this.postMessageHandler = null;\n }\n const iframe = this.getIframe();\n if (iframe) {\n iframe.setAttribute('src', 'about:blank');\n }\n this.dispatchErrorEvent({\n message: (error as Error).message || 'Invalid baseURL',\n });\n return;\n }\n // Tear down existing handler and re-point iframe to new URL\n if (this.postMessageHandler) {\n this.postMessageHandler.destroy();\n this.postMessageHandler = null;\n }\n const iframe = this.getIframe();\n if (iframe) {\n const expected = this.normalizedBaseURL\n ? buildEmbeddedUrl(this.normalizedBaseURL)\n : '';\n if (iframe.getAttribute('src') !== expected) {\n iframe.setAttribute('src', expected);\n iframe.setAttribute(\n 'allow',\n `microphone ${expected}; camera ${expected}; device-capture ${expected}; display-capture ${expected}`,\n );\n }\n }\n }\n }\n\n // Public API Implementation\n /**\n * Authenticate with the Corti system\n * @param credentials Authentication credentials\n * @returns Promise resolving to user information\n */\n async auth(credentials: AuthCredentials): Promise<User> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: AuthPayload = {\n access_token: credentials.access_token,\n token_type: credentials.token_type,\n expires_at: credentials.expires_at,\n expires_in: credentials.expires_in,\n refresh_expires_in: credentials.refresh_expires_in,\n refresh_token: credentials.refresh_token,\n id_token: credentials.id_token,\n 'not-before-policy': credentials['not-before-policy'],\n session_state: credentials.session_state,\n scope: credentials.scope,\n profile: credentials.profile,\n mode: credentials.mode,\n };\n\n const user = await this.postMessageHandler.auth(payload);\n return user;\n } catch (error) {\n const formattedError = formatError(error, 'Authentication failed');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Create a new interaction\n * @param encounter Encounter request data\n * @returns Promise resolving to interaction details\n */\n async createInteraction(\n encounter: CreateInteractionPayload,\n ): Promise<InteractionDetails> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const response =\n await this.postMessageHandler.createInteraction(encounter);\n return {\n id: response.id,\n createdAt: response.createdAt,\n };\n } catch (error) {\n const formattedError = formatError(error, 'Failed to create interaction');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Configure the current session\n * @param config Session configuration\n * @returns Promise that resolves when configuration is complete\n */\n async configureSession(config: SessionConfig): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: ConfigureSessionPayload = {\n defaultLanguage: config.defaultLanguage,\n defaultOutputLanguage: config.defaultOutputLanguage,\n defaultTemplateKey: config.defaultTemplateKey,\n defaultMode: config.defaultMode,\n };\n\n await this.postMessageHandler.configureSession(payload);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to configure session');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Add facts to the current session\n * @param facts Array of facts to add\n * @returns Promise that resolves when facts are added\n */\n async addFacts(facts: Corti.FactsCreateInput[]): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: AddFactsPayload = { facts };\n await this.postMessageHandler.addFacts(payload);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to add facts');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Navigate to a specific path within the embedded UI\n * @param path Path to navigate to\n * @returns Promise that resolves when navigation is complete\n */\n async navigate(path: string): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: NavigatePayload = { path };\n await this.postMessageHandler.navigate(payload);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to navigate');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Start recording\n * @returns Promise that resolves when recording starts\n */\n async startRecording(): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n await this.postMessageHandler.startRecording();\n } catch (error) {\n const formattedError = formatError(error, 'Failed to start recording');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Stop recording\n * @returns Promise that resolves when recording stops\n */\n async stopRecording(): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n await this.postMessageHandler.stopRecording();\n } catch (error) {\n const formattedError = formatError(error, 'Failed to stop recording');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Get current component status\n * @returns Promise resolving to current status\n */\n async getStatus(): Promise<GetStatusResponsePayload> {\n if (!this.postMessageHandler) {\n return {\n auth: {\n isAuthenticated: false,\n user: undefined,\n },\n currentUrl: '',\n interaction: null,\n };\n }\n\n try {\n return await this.postMessageHandler.getStatus();\n } catch (error) {\n const formattedError = formatError(error, 'Failed to get status');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Configure the component\n * @param config Component configuration\n * @returns Promise that resolves when configuration is applied\n */\n async configure(\n config: ConfigureAppPayload,\n ): Promise<ConfigureAppResponsePayload> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n return await this.postMessageHandler.configure(config);\n } catch (error) {\n const formattedError = formatError(\n error,\n 'Failed to configure component',\n );\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Set authentication credentials without triggering auth flow\n * @param credentials Authentication credentials to store\n * @returns Promise that resolves when credentials are set\n */\n async setCredentials(credentials: SetCredentialsPayload): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n if (!credentials.password) {\n throw new Error('Password is required');\n }\n await this.postMessageHandler.setCredentials(credentials);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to set credentials');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Show the embedded UI\n */\n show(): void {\n this.visibility = 'visible';\n }\n\n /**\n * Hide the embedded UI\n */\n hide(): void {\n this.visibility = 'hidden';\n }\n\n /**\n * Check the current status of the iframe and PostMessageHandler\n * Useful for debugging\n * @deprecated Use getStatus() instead\n */\n getDebugStatus() {\n const iframe = this.getIframe();\n return {\n ready: iframe?.contentDocument?.readyState === 'complete',\n iframeExists: !!iframe,\n iframeSrc: iframe?.src,\n iframeContentWindow: !!iframe?.contentWindow,\n iframeContentDocument: !!iframe?.contentDocument,\n iframeReadyState: iframe?.contentDocument?.readyState,\n postMessageHandlerExists: !!this.postMessageHandler,\n postMessageHandlerReady: this.postMessageHandler?.ready || false,\n baseURL: this.baseURL,\n };\n }\n\n render() {\n // Don't render if baseURL is not provided\n if (!this.baseURL) {\n return html`<div>baseURL is required</div>`;\n }\n\n return html`\n <iframe\n src=${buildEmbeddedUrl(validateAndNormalizeBaseURL(this.baseURL))}\n title=\"Corti Embedded UI\"\n sandbox=${'allow-forms allow-modals allow-scripts allow-same-origin' as any}\n allow=\"microphone *; camera *; device-capture *; display-capture *\"\n @load=${(event: Event) => this.handleIframeLoad(event)}\n @unload=${() => this.postMessageHandler?.destroy()}\n style=${this.visibility === 'hidden'\n ? 'display: none;'\n : 'display: block;'}\n ></iframe>\n `;\n }\n}\n"]}
1
+ {"version":3,"file":"CortiEmbedded.js","sourceRoot":"","sources":["../src/CortiEmbedded.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EAAE,IAAI,EAAE,UAAU,EAAuB,MAAM,KAAK,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAkB7C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EACL,kBAAkB,GAEnB,MAAM,+BAA+B,CAAC;AAEvC,MAAM,OAAO,aAAc,SAAQ,UAAU;IAA7C;;QAIE,eAAU,GAAG,QAAQ,CAAC;QAKd,uBAAkB,GAA8B,IAAI,CAAC;QAErD,sBAAiB,GAAkB,IAAI,CAAC;IAuclD,CAAC;IArcC,iBAAiB;QACf,KAAK,CAAC,iBAAiB,EAAE,CAAC;QAE1B,6BAA6B;QAC7B,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,IAAI,CAAC,kBAAkB,CAAC;gBACtB,OAAO,EAAE,qBAAqB;aAC/B,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QAED,+DAA+D;QAC/D,IAAI,CAAC;YACH,IAAI,CAAC,iBAAiB,GAAG,2BAA2B,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACrE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAA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U;YACrD,wBAAwB,EAAE,CAAC,CAAC,IAAI,CAAC,kBAAkB;YACnD,uBAAuB,EAAE,IAAI,CAAC,kBAAkB,EAAE,KAAK,IAAI,KAAK;YAChE,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAC;IACJ,CAAC;IAED,MAAM;QACJ,0CAA0C;QAC1C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,OAAO,IAAI,CAAA,gCAAgC,CAAC;QAC9C,CAAC;QAED,OAAO,IAAI,CAAA;;cAED,gBAAgB,CAAC,2BAA2B,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;;kBAEvD,0DAAiE;;gBAEnE,CAAC,KAAY,EAAE,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC;kBAC5C,GAAG,EAAE,CAAC,IAAI,CAAC,kBAAkB,EAAE,OAAO,EAAE;gBAC1C,IAAI,CAAC,UAAU,KAAK,QAAQ;YAClC,CAAC,CAAC,gBAAgB;YAClB,CAAC,CAAC,iBAAiB;;KAExB,CAAC;IACJ,CAAC;;AAhdM,oBAAM,GAAG,CAAC,UAAU,EAAE,eAAe,CAAC,AAAhC,CAAiC;AAG9C;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;iDACpB;AAGtB;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;8CACzB","sourcesContent":["/* eslint-disable no-console */\nimport type { Corti } from '@corti/sdk';\nimport { html, LitElement, type PropertyValues } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport type {\n AddFactsPayload,\n AuthPayload,\n ConfigureAppPayload,\n ConfigureSessionPayload,\n NavigatePayload,\n SetCredentialsPayload,\n AuthCredentials,\n ConfigureAppResponse,\n CortiEmbeddedAPI,\n InteractionDetails,\n CreateInteractionPayload,\n SessionConfig,\n User,\n GetStatusResponse,\n GetTemplatesResponse,\n} from './types';\nimport { baseStyles } from './styles/base.js';\nimport { containerStyles } from './styles/container-styles.js';\nimport { validateAndNormalizeBaseURL } from './utils/baseUrl.js';\nimport { buildEmbeddedUrl, isRealEmbeddedLoad } from './utils/embedUrl.js';\nimport { formatError } from './utils/errorFormatter.js';\nimport {\n PostMessageHandler,\n type PostMessageHandlerCallbacks,\n} from './utils/PostMessageHandler.js';\n\nexport class CortiEmbedded extends LitElement implements CortiEmbeddedAPI {\n static styles = [baseStyles, containerStyles];\n\n @property({ type: String, reflect: true })\n visibility = 'hidden';\n\n @property({ type: String, reflect: true })\n baseURL!: string;\n\n private postMessageHandler: PostMessageHandler | null = null;\n\n private normalizedBaseURL: string | null = null;\n\n connectedCallback() {\n super.connectedCallback();\n\n // Ensure baseURL is provided\n if (!this.baseURL) {\n this.dispatchErrorEvent({\n message: 'baseURL is required',\n });\n return;\n }\n\n // Validate and normalize the initial baseURL early (fail fast)\n try {\n this.normalizedBaseURL = validateAndNormalizeBaseURL(this.baseURL);\n } catch (error) {\n this.dispatchErrorEvent({\n message: (error as Error).message || 'Invalid baseURL',\n });\n throw error;\n }\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this.postMessageHandler) {\n this.postMessageHandler.destroy();\n this.postMessageHandler = null;\n }\n }\n\n private async setupPostMessageHandler() {\n // Prevent multiple setups\n if (this.postMessageHandler) {\n return;\n }\n\n const iframe = this.getIframe();\n\n if (iframe?.contentWindow) {\n const callbacks: PostMessageHandlerCallbacks = {\n onEvent: event => {\n this.dispatchEmbeddedEvent(event.name, event.payload);\n },\n onError: error => {\n this.dispatchErrorEvent(error);\n },\n };\n\n this.postMessageHandler = new PostMessageHandler(iframe, callbacks);\n } else {\n this.dispatchErrorEvent({\n message: 'No iframe or contentWindow available',\n });\n }\n }\n\n private dispatchPublicEvent(event: string, data: unknown) {\n this.dispatchEvent(new CustomEvent(event, { detail: data }));\n }\n\n private dispatchEmbeddedEvent(rawEventName: string, payload: unknown) {\n // Preserve raw DOM event passthrough for consumers listening directly.\n this.dispatchPublicEvent(rawEventName, payload);\n\n this.dispatchPublicEvent('embedded-event', {\n name: rawEventName,\n payload,\n });\n }\n\n private dispatchErrorEvent(error: {\n message: string;\n code?: string;\n details?: unknown;\n }) {\n this.dispatchPublicEvent('error', error);\n }\n\n private isRealIframeLoad(iframe: HTMLIFrameElement): boolean {\n const src = iframe.getAttribute('src') || '';\n if (!this.normalizedBaseURL) return false;\n return isRealEmbeddedLoad(src, this.normalizedBaseURL);\n }\n\n private async handleIframeLoad(event: Event) {\n const iframe = event.target as HTMLIFrameElement | null;\n if (!iframe) {\n return;\n }\n // Only initialize on real URL load, ignore about:blank\n if (!this.isRealIframeLoad(iframe)) {\n return;\n }\n try {\n await this.setupPostMessageHandler();\n } catch (error) {\n this.dispatchErrorEvent({\n message: `Failed to setup PostMessageHandler on iframe load: ${error}`,\n });\n }\n }\n\n private getIframe(): HTMLIFrameElement | null {\n return this.shadowRoot?.querySelector('iframe') || null;\n }\n\n protected updated(changedProps: PropertyValues) {\n super.updated(changedProps);\n if (changedProps.has('baseURL')) {\n // Validate baseURL and normalize; fail fast on invalid input\n try {\n this.normalizedBaseURL = validateAndNormalizeBaseURL(this.baseURL);\n } catch (error) {\n // Tear down and clear iframe to avoid keeping an old origin active\n if (this.postMessageHandler) {\n this.postMessageHandler.destroy();\n this.postMessageHandler = null;\n }\n const iframe = this.getIframe();\n if (iframe) {\n iframe.setAttribute('src', 'about:blank');\n }\n this.dispatchErrorEvent({\n message: (error as Error).message || 'Invalid baseURL',\n });\n return;\n }\n // Tear down existing handler and re-point iframe to new URL\n if (this.postMessageHandler) {\n this.postMessageHandler.destroy();\n this.postMessageHandler = null;\n }\n const iframe = this.getIframe();\n if (iframe) {\n const expected = this.normalizedBaseURL\n ? buildEmbeddedUrl(this.normalizedBaseURL)\n : '';\n if (iframe.getAttribute('src') !== expected) {\n iframe.setAttribute('src', expected);\n iframe.setAttribute(\n 'allow',\n `microphone ${expected}; camera ${expected}; device-capture ${expected}; display-capture ${expected}`,\n );\n }\n }\n }\n }\n\n // Public API Implementation\n /**\n * Authenticate with the Corti system\n * @param credentials Authentication credentials\n * @returns Promise resolving to user information\n */\n async auth(credentials: AuthCredentials): Promise<User> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: AuthPayload = {\n access_token: credentials.access_token,\n token_type: credentials.token_type,\n expires_at: credentials.expires_at,\n expires_in: credentials.expires_in,\n refresh_expires_in: credentials.refresh_expires_in,\n refresh_token: credentials.refresh_token,\n id_token: credentials.id_token,\n 'not-before-policy': credentials['not-before-policy'],\n session_state: credentials.session_state,\n scope: credentials.scope,\n profile: credentials.profile,\n mode: credentials.mode,\n };\n\n const user = await this.postMessageHandler.auth(payload);\n return user;\n } catch (error) {\n const formattedError = formatError(error, 'Authentication failed');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Create a new interaction\n * @param encounter Encounter request data\n * @returns Promise resolving to interaction details\n */\n async createInteraction(\n encounter: CreateInteractionPayload,\n ): Promise<InteractionDetails> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const response =\n await this.postMessageHandler.createInteraction(encounter);\n return {\n id: response.id,\n createdAt: response.createdAt,\n };\n } catch (error) {\n const formattedError = formatError(error, 'Failed to create interaction');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Configure the current session\n * @param config Session configuration\n * @returns Promise that resolves when configuration is complete\n */\n async configureSession(config: SessionConfig): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: ConfigureSessionPayload = {\n defaultLanguage: config.defaultLanguage,\n defaultOutputLanguage: config.defaultOutputLanguage,\n defaultTemplateKey: config.defaultTemplateKey,\n defaultMode: config.defaultMode,\n };\n\n await this.postMessageHandler.configureSession(payload);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to configure session');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Add facts to the current session\n * @param facts Array of facts to add\n * @returns Promise that resolves when facts are added\n */\n async addFacts(facts: Corti.FactsCreateInput[]): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: AddFactsPayload = { facts };\n await this.postMessageHandler.addFacts(payload);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to add facts');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Navigate to a specific path within the embedded UI\n * @param path Path to navigate to\n * @returns Promise that resolves when navigation is complete\n */\n async navigate(path: string): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const payload: NavigatePayload = { path };\n await this.postMessageHandler.navigate(payload);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to navigate');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Start recording\n * @returns Promise that resolves when recording starts\n */\n async startRecording(): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n await this.postMessageHandler.startRecording();\n } catch (error) {\n const formattedError = formatError(error, 'Failed to start recording');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Stop recording\n * @returns Promise that resolves when recording stops\n */\n async stopRecording(): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n await this.postMessageHandler.stopRecording();\n } catch (error) {\n const formattedError = formatError(error, 'Failed to stop recording');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Get current component status\n * @returns Promise resolving to current status\n */\n async getStatus(): Promise<GetStatusResponse> {\n if (!this.postMessageHandler) {\n return {\n auth: {\n isAuthenticated: false,\n user: undefined,\n },\n currentUrl: '',\n interaction: null,\n };\n }\n\n try {\n return await this.postMessageHandler.getStatus();\n } catch (error) {\n const formattedError = formatError(error, 'Failed to get status');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Configure the component\n * @param config Component configuration\n * @returns Promise that resolves when configuration is applied\n */\n async configure(config: ConfigureAppPayload): Promise<ConfigureAppResponse> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n return await this.postMessageHandler.configure(config);\n } catch (error) {\n const formattedError = formatError(\n error,\n 'Failed to configure component',\n );\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Set authentication credentials without triggering auth flow\n * @param credentials Authentication credentials to store\n * @returns Promise that resolves when credentials are set\n */\n async setCredentials(credentials: SetCredentialsPayload): Promise<void> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n if (!credentials.password) {\n throw new Error('Password is required');\n }\n await this.postMessageHandler.setCredentials(credentials);\n } catch (error) {\n const formattedError = formatError(error, 'Failed to set credentials');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Show the embedded UI\n */\n show(): void {\n this.visibility = 'visible';\n }\n\n /**\n * Hide the embedded UI\n */\n hide(): void {\n this.visibility = 'hidden';\n }\n\n /**\n * Get templates\n */\n async getTemplates(): Promise<GetTemplatesResponse> {\n if (!this.postMessageHandler) {\n throw new Error('Component not ready');\n }\n\n try {\n const response = await this.postMessageHandler.getTemplates();\n return response;\n } catch (error) {\n const formattedError = formatError(error, 'Failed to get templates');\n this.dispatchErrorEvent(formattedError);\n throw new Error(JSON.stringify(formattedError));\n }\n }\n\n /**\n * Check the current status of the iframe and PostMessageHandler\n * Useful for debugging\n * @deprecated Use getStatus() instead\n */\n getDebugStatus() {\n const iframe = this.getIframe();\n return {\n ready: iframe?.contentDocument?.readyState === 'complete',\n iframeExists: !!iframe,\n iframeSrc: iframe?.src,\n iframeContentWindow: !!iframe?.contentWindow,\n iframeContentDocument: !!iframe?.contentDocument,\n iframeReadyState: iframe?.contentDocument?.readyState,\n postMessageHandlerExists: !!this.postMessageHandler,\n postMessageHandlerReady: this.postMessageHandler?.ready || false,\n baseURL: this.baseURL,\n };\n }\n\n render() {\n // Don't render if baseURL is not provided\n if (!this.baseURL) {\n return html`<div>baseURL is required</div>`;\n }\n\n return html`\n <iframe\n src=${buildEmbeddedUrl(validateAndNormalizeBaseURL(this.baseURL))}\n title=\"Corti Embedded UI\"\n sandbox=${'allow-forms allow-modals allow-scripts allow-same-origin' as any}\n allow=\"microphone *; camera *; device-capture *; display-capture *\"\n @load=${(event: Event) => this.handleIframeLoad(event)}\n @unload=${() => this.postMessageHandler?.destroy()}\n style=${this.visibility === 'hidden'\n ? 'display: none;'\n : 'display: block;'}\n ></iframe>\n `;\n }\n}\n"]}