@corti/embedded-web 0.1.0-alpha.1 → 0.1.0

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.
Files changed (50) hide show
  1. package/README.md +69 -41
  2. package/dist/CortiEmbedded.d.ts +9 -5
  3. package/dist/CortiEmbedded.js +30 -40
  4. package/dist/CortiEmbedded.js.map +1 -1
  5. package/dist/bundle.js +7 -7
  6. package/dist/index.d.ts +2 -3
  7. package/dist/index.js +3 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/react/CortiEmbeddedReact.d.ts +38 -15
  10. package/dist/react/CortiEmbeddedReact.js +95 -15
  11. package/dist/react/CortiEmbeddedReact.js.map +1 -1
  12. package/dist/tsconfig.tsbuildinfo +1 -1
  13. package/dist/types/api.d.ts +152 -0
  14. package/dist/types/api.js +3 -0
  15. package/dist/types/api.js.map +1 -0
  16. package/dist/types/config.d.ts +26 -0
  17. package/dist/types/config.js +3 -0
  18. package/dist/types/config.js.map +1 -0
  19. package/dist/types/events.d.ts +28 -0
  20. package/dist/types/events.js +2 -0
  21. package/dist/types/events.js.map +1 -0
  22. package/dist/types/generated/interview-details.d.ts +159 -0
  23. package/dist/types/generated/interview-details.js +4 -0
  24. package/dist/types/generated/interview-details.js.map +1 -0
  25. package/dist/types/index.d.ts +6 -0
  26. package/dist/types/index.js +14 -0
  27. package/dist/types/index.js.map +1 -0
  28. package/dist/types/payloads.d.ts +61 -0
  29. package/dist/types/payloads.js +2 -0
  30. package/dist/types/payloads.js.map +1 -0
  31. package/dist/types/protocol.d.ts +111 -0
  32. package/dist/types/protocol.js +3 -0
  33. package/dist/types/protocol.js.map +1 -0
  34. package/dist/types/responses.d.ts +48 -0
  35. package/dist/types/responses.js +3 -0
  36. package/dist/types/responses.js.map +1 -0
  37. package/dist/utils/PostMessageHandler.d.ts +11 -17
  38. package/dist/utils/PostMessageHandler.js +29 -40
  39. package/dist/utils/PostMessageHandler.js.map +1 -1
  40. package/dist/web-bundle.js +4 -4
  41. package/dist/web-index.d.ts +1 -1
  42. package/dist/web-index.js +2 -0
  43. package/dist/web-index.js.map +1 -1
  44. package/package.json +4 -3
  45. package/dist/internal-types.d.ts +0 -231
  46. package/dist/internal-types.js +0 -2
  47. package/dist/internal-types.js.map +0 -1
  48. package/dist/public-types.d.ts +0 -238
  49. package/dist/public-types.js +0 -2
  50. package/dist/public-types.js.map +0 -1
package/README.md CHANGED
@@ -62,33 +62,44 @@ import React, { useRef } from 'react';
62
62
  import {
63
63
  CortiEmbeddedReact,
64
64
  type CortiEmbeddedReactRef,
65
- type EmbeddedEventData,
65
+ useCortiEmbeddedApi,
66
+ useCortiEmbeddedStatus,
66
67
  } from '@corti/embedded-web/react';
67
68
 
68
69
  function App() {
69
70
  const cortiRef = useRef<CortiEmbeddedReactRef>(null);
71
+ const api = useCortiEmbeddedApi(cortiRef);
72
+ const { status } = useCortiEmbeddedStatus(cortiRef);
70
73
 
71
74
  const handleReady = () => {
72
75
  console.log('Corti component is ready!');
73
- cortiRef.current?.show();
74
76
  };
75
77
 
76
- const handleAuthChanged = (
77
- event: CustomEvent<EmbeddedEventData['auth-changed']>,
78
+ const handleEvent = (
79
+ event: CustomEvent<{ name: string; payload: unknown }>,
78
80
  ) => {
79
- console.log('User authenticated:', event.detail.user);
81
+ console.log('Event name:', event.detail.name);
82
+ console.log('Event payload:', event.detail.payload);
80
83
  };
81
84
 
82
85
  const handleAuth = async () => {
83
- if (!cortiRef.current) return;
84
-
85
86
  try {
86
- const user = await cortiRef.current.auth({
87
+ const user = await api.auth({
87
88
  access_token: 'your-token',
88
89
  token_type: 'Bearer',
89
90
  // ... rest of the token response
90
91
  });
91
92
  console.log('Authenticated:', user);
93
+
94
+ await api.configureSession({ defaultTemplateKey: 'soap_note' });
95
+ await api.createInteraction({
96
+ encounter: {
97
+ identifier: `encounter-${Date.now()}`,
98
+ status: 'planned',
99
+ type: 'first_consultation',
100
+ period: { startedAt: new Date().toISOString() },
101
+ },
102
+ });
92
103
  } catch (error) {
93
104
  console.error('Auth failed:', error);
94
105
  }
@@ -103,10 +114,12 @@ function App() {
103
114
  baseURL="https://assistant.eu.corti.app" // REQUIRED
104
115
  visibility="visible"
105
116
  onReady={handleReady}
117
+ onEvent={handleEvent}
118
+ onError={event => console.error('Embedded error:', event.detail)}
106
119
  style={{ width: '100%', height: '500px' }}
107
- // or use className
108
- className="w-full h-full"
109
120
  />
121
+
122
+ <pre>{JSON.stringify(status, null, 2)}</pre>
110
123
  </div>
111
124
  );
112
125
  }
@@ -211,10 +224,10 @@ The component uses a `PostMessageHandler` utility class that:
211
224
 
212
225
  The React component (`CortiEmbeddedReact`) is available as an additional export and provides:
213
226
 
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
227
+ - **Hook-based API access**: `useCortiEmbeddedApi(ref)` exposes instance-bound methods (`auth`, `navigate`, `createInteraction`, etc.)
228
+ - **Generic event stream**: `onEvent` receives all embedded events as `{ name, payload }`
229
+ - **Status hook**: `useCortiEmbeddedStatus(ref)` keeps latest status/reactive state
230
+ - **Multi-instance safety**: API methods are scoped to the ref you pass
218
231
  - **React Props**: Standard React props like `className`, `style`, etc.
219
232
 
220
233
  ### React Component Import
@@ -223,44 +236,59 @@ The React component (`CortiEmbeddedReact`) is available as an additional export
223
236
  import {
224
237
  CortiEmbeddedReact,
225
238
  CortiEmbedded, // Web component also available
226
- type CortiEmbeddedReactProps,
227
239
  type CortiEmbeddedReactRef,
240
+ useCortiEmbeddedApi,
241
+ useCortiEmbeddedStatus,
228
242
  } from '@corti/embedded-web/react';
229
243
  ```
230
244
 
231
- ### Available Events (React)
245
+ ### Event Listener Setup
232
246
 
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
247
+ - Use `onEvent` for all embedded events.
248
+ - Event detail shape is `{ name: string; payload: unknown }`.
249
+ - Full event catalog and payload details are documented at:
250
+ - https://docs.corti.ai/assistant/events
241
251
 
242
- ### Event Data Access
252
+ ```tsx
253
+ <CortiEmbeddedReact
254
+ baseURL="https://assistant.eu.corti.app"
255
+ onEvent={event => {
256
+ console.log(event.detail.name, event.detail.payload);
257
+ }}
258
+ onReady={() => console.log('Ready')}
259
+ onError={event => console.error(event.detail)}
260
+ />
261
+ ```
262
+
263
+ ### API Methods (React)
243
264
 
244
- Events in React carry data in the `detail` property:
265
+ Use the API hook with the same component ref:
245
266
 
246
267
  ```tsx
247
- import type {
248
- EmbeddedEventData,
249
- CortiEmbeddedReactProps,
268
+ import React, { useRef } from 'react';
269
+ import {
270
+ CortiEmbeddedReact,
271
+ type CortiEmbeddedReactRef,
272
+ useCortiEmbeddedApi,
250
273
  } from '@corti/embedded-web/react';
251
274
 
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
- };
275
+ function Example() {
276
+ const ref = useRef<CortiEmbeddedReactRef>(null);
277
+ const api = useCortiEmbeddedApi(ref);
278
+
279
+ const run = async () => {
280
+ await api.auth({ access_token: '...', token_type: 'Bearer', mode: 'stateful' });
281
+ const created = await api.createInteraction({ encounter: { ... } });
282
+ await api.navigate(`/session/${created.id}`);
283
+ };
284
+
285
+ return (
286
+ <>
287
+ <button onClick={() => void run()}>Run</button>
288
+ <CortiEmbeddedReact ref={ref} baseURL="https://assistant.eu.corti.app" />
289
+ </>
290
+ );
291
+ }
264
292
  ```
265
293
 
266
294
  For detailed React usage examples, see [docs/react-usage.md](./docs/react-usage.md).
@@ -1,7 +1,6 @@
1
1
  import type { Corti } from '@corti/sdk';
2
2
  import { LitElement, type PropertyValues } from 'lit';
3
- import type { ConfigureAppPayload, SetCredentialsPayload } from './internal-types.js';
4
- import type { AuthCredentials, ComponentStatus, ConfigureAppResponsePayload, CortiEmbeddedAPI, InteractionDetails, InteractionPayload, SessionConfig, User } from './public-types.js';
3
+ import type { ConfigureAppPayload, SetCredentialsPayload, AuthCredentials, ConfigureAppResponse, CortiEmbeddedAPI, InteractionDetails, CreateInteractionPayload, SessionConfig, User, GetStatusResponse, GetTemplatesResponse } from './types';
5
4
  export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAPI {
6
5
  static styles: import("lit").CSSResult[];
7
6
  visibility: string;
@@ -12,6 +11,7 @@ export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAP
12
11
  disconnectedCallback(): void;
13
12
  private setupPostMessageHandler;
14
13
  private dispatchPublicEvent;
14
+ private dispatchEmbeddedEvent;
15
15
  private dispatchErrorEvent;
16
16
  private isRealIframeLoad;
17
17
  private handleIframeLoad;
@@ -28,7 +28,7 @@ export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAP
28
28
  * @param encounter Encounter request data
29
29
  * @returns Promise resolving to interaction details
30
30
  */
31
- createInteraction(encounter: InteractionPayload): Promise<InteractionDetails>;
31
+ createInteraction(encounter: CreateInteractionPayload): Promise<InteractionDetails>;
32
32
  /**
33
33
  * Configure the current session
34
34
  * @param config Session configuration
@@ -61,13 +61,13 @@ export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAP
61
61
  * Get current component status
62
62
  * @returns Promise resolving to current status
63
63
  */
64
- getStatus(): Promise<ComponentStatus>;
64
+ getStatus(): Promise<GetStatusResponse>;
65
65
  /**
66
66
  * Configure the component
67
67
  * @param config Component configuration
68
68
  * @returns Promise that resolves when configuration is applied
69
69
  */
70
- configure(config: ConfigureAppPayload): Promise<ConfigureAppResponsePayload>;
70
+ configure(config: ConfigureAppPayload): Promise<ConfigureAppResponse>;
71
71
  /**
72
72
  * Set authentication credentials without triggering auth flow
73
73
  * @param credentials Authentication credentials to store
@@ -82,6 +82,10 @@ export declare class CortiEmbedded extends LitElement implements CortiEmbeddedAP
82
82
  * Hide the embedded UI
83
83
  */
84
84
  hide(): void;
85
+ /**
86
+ * Get templates
87
+ */
88
+ getTemplates(): Promise<GetTemplatesResponse>;
85
89
  /**
86
90
  * Check the current status of the iframe and PostMessageHandler
87
91
  * Useful for debugging
@@ -54,42 +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
- onNavigationChanged: payload => {
85
- this.dispatchPublicEvent('navigation-changed', {
86
- path: payload.path,
87
- });
88
- },
89
- onUsage: payload => {
90
- this.dispatchPublicEvent('usage', {
91
- creditsConsumed: payload.creditsConsumed,
92
- });
57
+ onEvent: event => {
58
+ this.dispatchEmbeddedEvent(event.name, event.payload);
93
59
  },
94
60
  onError: error => {
95
61
  this.dispatchErrorEvent(error);
@@ -106,6 +72,14 @@ export class CortiEmbedded extends LitElement {
106
72
  dispatchPublicEvent(event, data) {
107
73
  this.dispatchEvent(new CustomEvent(event, { detail: data }));
108
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
+ }
109
83
  dispatchErrorEvent(error) {
110
84
  this.dispatchPublicEvent('error', error);
111
85
  }
@@ -334,13 +308,12 @@ export class CortiEmbedded extends LitElement {
334
308
  async getStatus() {
335
309
  if (!this.postMessageHandler) {
336
310
  return {
337
- ready: false,
338
311
  auth: {
339
- authenticated: false,
312
+ isAuthenticated: false,
340
313
  user: undefined,
341
314
  },
342
- currentUrl: undefined,
343
- interaction: undefined,
315
+ currentUrl: '',
316
+ interaction: null,
344
317
  };
345
318
  }
346
319
  try {
@@ -403,6 +376,23 @@ export class CortiEmbedded extends LitElement {
403
376
  hide() {
404
377
  this.visibility = 'hidden';
405
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
+ }
406
396
  /**
407
397
  * Check the current status of the iframe and PostMessageHandler
408
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;AAoB7C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C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BAAwB,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;;AA5dM,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} from './internal-types.js';\nimport type {\n AuthCredentials,\n ComponentStatus,\n ConfigureAppResponsePayload,\n CortiEmbeddedAPI,\n EmbeddedEventData,\n InteractionDetails,\n InteractionPayload,\n SessionConfig,\n User,\n} from './public-types.js';\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 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: InteractionPayload,\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<ComponentStatus> {\n if (!this.postMessageHandler) {\n return {\n ready: false,\n auth: {\n authenticated: false,\n user: undefined,\n },\n currentUrl: undefined,\n interaction: undefined,\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,+BA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M,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"]}