@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.
@@ -1,10 +1,10 @@
1
- import type { ConfigureAppPayload, ConfigureAppResponsePayload } from "./config.js";
2
- import type { AuthChangedEventPayload, DocumentEventPayload, ErrorEventPayload, InteractionCreatedEventPayload, NavigationChangedEventPayload, UsageEventPayload } from "./events.js";
3
- import type { EmbeddedInterviewDetails } from "./generated/interview-details.js";
4
- import type { AddFactsPayload, AuthPayload, AuthResponse, ConfigureSessionPayload, CreateInteractionPayload, CreateInteractionResponse, Fact, KeycloakTokenResponse, NavigatePayload, SetCredentialsPayload, UserInfo } from "./payloads.js";
5
- import type { DefaultMode } from "./protocol.js";
6
- export type { ConfigureAppPayload, ConfigureAppResponsePayload } from "./config.js";
7
- export type { UserInfo } from "./payloads.js";
1
+ import type { ConfigureAppPayload } from './config.js';
2
+ import type { AuthChangedEventPayload, DocumentEventPayload, ErrorEventPayload, InteractionCreatedEventPayload, NavigationChangedEventPayload, UsageEventPayload } from './events.js';
3
+ import type { AddFactsPayload, AuthPayload, ConfigureSessionPayload, CreateInteractionPayload, Fact, KeycloakTokenResponse, NavigatePayload, SetCredentialsPayload } from './payloads.js';
4
+ import type { DefaultMode } from './protocol.js';
5
+ import type { AuthResponse, ConfigureAppResponse, CreateInteractionResponse, GetStatusResponse, GetTemplatesResponse } from './responses.js';
6
+ export type { ConfigureAppPayload } from './config.js';
7
+ export type { UserInfo } from './responses.js';
8
8
  /**
9
9
  * Authentication credentials for Assistant
10
10
  */
@@ -32,30 +32,19 @@ export interface SessionConfig {
32
32
  defaultTemplateKey?: string;
33
33
  defaultMode?: DefaultMode;
34
34
  }
35
- /**
36
- * Status information about the embedded component
37
- */
38
- export interface GetStatusResponsePayload {
39
- auth: {
40
- isAuthenticated: boolean;
41
- user?: UserInfo;
42
- };
43
- currentUrl: string;
44
- interaction: EmbeddedInterviewDetails | null;
45
- }
46
35
  /**
47
36
  * Event data types for component events
48
37
  */
49
38
  export interface EmbeddedEventData {
50
39
  ready: undefined;
51
- "auth-changed": AuthChangedEventPayload;
52
- "interaction-created": InteractionCreatedEventPayload;
53
- "recording-started": undefined;
54
- "recording-stopped": undefined;
55
- "document-generated": DocumentEventPayload;
56
- "document-updated": DocumentEventPayload;
57
- "document-synced": DocumentEventPayload;
58
- "navigation-changed": NavigationChangedEventPayload;
40
+ 'auth-changed': AuthChangedEventPayload;
41
+ 'interaction-created': InteractionCreatedEventPayload;
42
+ 'recording-started': undefined;
43
+ 'recording-stopped': undefined;
44
+ 'document-generated': DocumentEventPayload;
45
+ 'document-updated': DocumentEventPayload;
46
+ 'document-synced': DocumentEventPayload;
47
+ 'navigation-changed': NavigationChangedEventPayload;
59
48
  usage: UsageEventPayload;
60
49
  error: ErrorEventPayload;
61
50
  }
@@ -64,12 +53,13 @@ export interface CortiEmbeddedV1API {
64
53
  createInteraction(payload: CreateInteractionPayload): Promise<CreateInteractionResponse>;
65
54
  addFacts(payload: AddFactsPayload): Promise<void>;
66
55
  configureSession(payload: ConfigureSessionPayload): Promise<void>;
67
- configure(payload: ConfigureAppPayload): Promise<ConfigureAppResponsePayload>;
56
+ configure(payload: ConfigureAppPayload): Promise<ConfigureAppResponse>;
68
57
  navigate(payload: NavigatePayload): Promise<void>;
69
58
  startRecording(): Promise<void>;
70
59
  stopRecording(): Promise<void>;
71
60
  setCredentials(payload: SetCredentialsPayload): Promise<void>;
72
- getStatus(): Promise<GetStatusResponsePayload>;
61
+ getStatus(): Promise<GetStatusResponse>;
62
+ getTemplates(): Promise<GetTemplatesResponse>;
73
63
  }
74
64
  export interface CortiEmbeddedWindowAPI {
75
65
  v1: CortiEmbeddedV1API;
@@ -131,13 +121,18 @@ export interface CortiEmbeddedAPI {
131
121
  * Get current component status
132
122
  * @returns Promise resolving to current status
133
123
  */
134
- getStatus(): Promise<GetStatusResponsePayload>;
124
+ getStatus(): Promise<GetStatusResponse>;
125
+ /**
126
+ * Get all templates available to the current user
127
+ * @returns Promise resolving to list of templates
128
+ */
129
+ getTemplates(): Promise<GetTemplatesResponse>;
135
130
  /**
136
131
  * Configure the application
137
132
  * @param config Application configuration
138
133
  * @returns Promise that resolves when configuration is applied
139
134
  */
140
- configure(config: ConfigureAppPayload): Promise<ConfigureAppResponsePayload>;
135
+ configure(config: ConfigureAppPayload): Promise<ConfigureAppResponse>;
141
136
  /**
142
137
  * Set authentication credentials without triggering auth flow
143
138
  * @param credentials Authentication credentials to store
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/types/api.ts"],"names":[],"mappings":"AAAA,qCAAqC","sourcesContent":["// Public API types for SDK consumers\n\nimport type { ConfigureAppPayload, ConfigureAppResponsePayload } from \"./config.js\";\nimport type {\n AuthChangedEventPayload,\n DocumentEventPayload,\n ErrorEventPayload,\n InteractionCreatedEventPayload,\n NavigationChangedEventPayload,\n UsageEventPayload,\n} from \"./events.js\";\nimport type { EmbeddedInterviewDetails } from \"./generated/interview-details.js\";\nimport type {\n AddFactsPayload,\n AuthPayload,\n AuthResponse,\n ConfigureSessionPayload,\n CreateInteractionPayload,\n CreateInteractionResponse,\n Fact,\n KeycloakTokenResponse,\n NavigatePayload,\n SetCredentialsPayload,\n UserInfo,\n} from \"./payloads.js\";\nimport type { DefaultMode } from \"./protocol.js\";\n\nexport type { ConfigureAppPayload, ConfigureAppResponsePayload } from \"./config.js\";\n// Re-export common types for public API\nexport type { UserInfo } from \"./payloads.js\";\n\n/**\n * Authentication credentials for Assistant\n */\nexport type AuthCredentials = AuthPayload;\n\n/**\n * User information returned from authentication\n */\nexport interface User {\n id: string;\n email: string;\n}\n\n/**\n * Details of a created interaction\n */\nexport interface InteractionDetails {\n id: string;\n createdAt: string;\n}\n\n/**\n * Session configuration options\n */\nexport interface SessionConfig {\n defaultLanguage?: string;\n defaultOutputLanguage?: string;\n defaultTemplateKey?: string;\n defaultMode?: DefaultMode;\n}\n\n/**\n * Status information about the embedded component\n */\nexport interface GetStatusResponsePayload {\n auth: {\n isAuthenticated: boolean;\n user?: UserInfo;\n };\n currentUrl: string;\n interaction: EmbeddedInterviewDetails | null;\n}\n\n/**\n * Event data types for component events\n */\nexport interface EmbeddedEventData {\n ready: undefined;\n \"auth-changed\": AuthChangedEventPayload;\n \"interaction-created\": InteractionCreatedEventPayload;\n \"recording-started\": undefined;\n \"recording-stopped\": undefined;\n \"document-generated\": DocumentEventPayload;\n \"document-updated\": DocumentEventPayload;\n \"document-synced\": DocumentEventPayload;\n \"navigation-changed\": NavigationChangedEventPayload;\n usage: UsageEventPayload;\n error: ErrorEventPayload;\n}\n\n// Window API Types\nexport interface CortiEmbeddedV1API {\n auth(payload: KeycloakTokenResponse): Promise<AuthResponse>;\n createInteraction(payload: CreateInteractionPayload): Promise<CreateInteractionResponse>;\n addFacts(payload: AddFactsPayload): Promise<void>;\n configureSession(payload: ConfigureSessionPayload): Promise<void>;\n configure(payload: ConfigureAppPayload): Promise<ConfigureAppResponsePayload>;\n navigate(payload: NavigatePayload): Promise<void>;\n startRecording(): Promise<void>;\n stopRecording(): Promise<void>;\n setCredentials(payload: SetCredentialsPayload): Promise<void>;\n getStatus(): Promise<GetStatusResponsePayload>;\n}\nexport interface CortiEmbeddedWindowAPI {\n v1: CortiEmbeddedV1API;\n}\n\n// Extend Window interface\ndeclare global {\n interface Window {\n CortiEmbedded?: CortiEmbeddedWindowAPI;\n }\n}\n\n/**\n * Event listener function type\n */\nexport type EventListener<T = unknown> = (data: T) => void;\n\n/**\n * Public API interface for the Corti Embedded component\n */\nexport interface CortiEmbeddedAPI {\n /**\n * Authenticate with the Corti system\n * @param credentials Authentication credentials\n * @returns Promise resolving to user information\n */\n auth(credentials: AuthCredentials): Promise<User>;\n\n /**\n * Create a new interaction\n * @param encounter Encounter request data\n * @returns Promise resolving to interaction details\n */\n createInteraction(encounter: CreateInteractionPayload): Promise<InteractionDetails>;\n\n /**\n * Configure the current session\n * @param config Session configuration\n * @returns Promise that resolves when configuration is complete\n */\n configureSession(config: SessionConfig): Promise<void>;\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 addFacts(facts: Fact[]): Promise<void>;\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 navigate(path: string): Promise<void>;\n\n /**\n * Start recording\n * @returns Promise that resolves when recording starts\n */\n startRecording(): Promise<void>;\n\n /**\n * Stop recording\n * @returns Promise that resolves when recording stops\n */\n stopRecording(): Promise<void>;\n\n /**\n * Get current component status\n * @returns Promise resolving to current status\n */\n getStatus(): Promise<GetStatusResponsePayload>;\n\n /**\n * Configure the application\n * @param config Application configuration\n * @returns Promise that resolves when configuration is applied\n */\n configure(config: ConfigureAppPayload): Promise<ConfigureAppResponsePayload>;\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 setCredentials(credentials: { password: string }): Promise<void>;\n\n /**\n * Show the embedded UI\n */\n show(): void;\n\n /**\n * Hide the embedded UI\n */\n hide(): void;\n}\n"]}
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/types/api.ts"],"names":[],"mappings":"AAAA,qCAAqC","sourcesContent":["// Public API types for SDK consumers\n\nimport type { ConfigureAppPayload } from './config.js';\nimport type {\n AuthChangedEventPayload,\n DocumentEventPayload,\n ErrorEventPayload,\n InteractionCreatedEventPayload,\n NavigationChangedEventPayload,\n UsageEventPayload,\n} from './events.js';\nimport type {\n AddFactsPayload,\n AuthPayload,\n ConfigureSessionPayload,\n CreateInteractionPayload,\n Fact,\n KeycloakTokenResponse,\n NavigatePayload,\n SetCredentialsPayload,\n} from './payloads.js';\nimport type { DefaultMode } from './protocol.js';\nimport type {\n AuthResponse,\n ConfigureAppResponse,\n CreateInteractionResponse,\n GetStatusResponse,\n GetTemplatesResponse,\n} from './responses.js';\n\nexport type { ConfigureAppPayload } from './config.js';\n// Re-export common types for public API\nexport type { UserInfo } from './responses.js';\n\n/**\n * Authentication credentials for Assistant\n */\nexport type AuthCredentials = AuthPayload;\n\n/**\n * User information returned from authentication\n */\nexport interface User {\n id: string;\n email: string;\n}\n\n/**\n * Details of a created interaction\n */\nexport interface InteractionDetails {\n id: string;\n createdAt: string;\n}\n\n/**\n * Session configuration options\n */\nexport interface SessionConfig {\n defaultLanguage?: string;\n defaultOutputLanguage?: string;\n defaultTemplateKey?: string;\n defaultMode?: DefaultMode;\n}\n\n/**\n * Event data types for component events\n */\nexport interface EmbeddedEventData {\n ready: undefined;\n 'auth-changed': AuthChangedEventPayload;\n 'interaction-created': InteractionCreatedEventPayload;\n 'recording-started': undefined;\n 'recording-stopped': undefined;\n 'document-generated': DocumentEventPayload;\n 'document-updated': DocumentEventPayload;\n 'document-synced': DocumentEventPayload;\n 'navigation-changed': NavigationChangedEventPayload;\n usage: UsageEventPayload;\n error: ErrorEventPayload;\n}\n\n// Window API Types\nexport interface CortiEmbeddedV1API {\n auth(payload: KeycloakTokenResponse): Promise<AuthResponse>;\n createInteraction(\n payload: CreateInteractionPayload,\n ): Promise<CreateInteractionResponse>;\n addFacts(payload: AddFactsPayload): Promise<void>;\n configureSession(payload: ConfigureSessionPayload): Promise<void>;\n configure(payload: ConfigureAppPayload): Promise<ConfigureAppResponse>;\n navigate(payload: NavigatePayload): Promise<void>;\n startRecording(): Promise<void>;\n stopRecording(): Promise<void>;\n setCredentials(payload: SetCredentialsPayload): Promise<void>;\n getStatus(): Promise<GetStatusResponse>;\n getTemplates(): Promise<GetTemplatesResponse>;\n}\nexport interface CortiEmbeddedWindowAPI {\n v1: CortiEmbeddedV1API;\n}\n\n// Extend Window interface\ndeclare global {\n interface Window {\n CortiEmbedded?: CortiEmbeddedWindowAPI;\n }\n}\n\n/**\n * Event listener function type\n */\nexport type EventListener<T = unknown> = (data: T) => void;\n\n/**\n * Public API interface for the Corti Embedded component\n */\nexport interface CortiEmbeddedAPI {\n /**\n * Authenticate with the Corti system\n * @param credentials Authentication credentials\n * @returns Promise resolving to user information\n */\n auth(credentials: AuthCredentials): Promise<User>;\n\n /**\n * Create a new interaction\n * @param encounter Encounter request data\n * @returns Promise resolving to interaction details\n */\n createInteraction(\n encounter: CreateInteractionPayload,\n ): Promise<InteractionDetails>;\n\n /**\n * Configure the current session\n * @param config Session configuration\n * @returns Promise that resolves when configuration is complete\n */\n configureSession(config: SessionConfig): Promise<void>;\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 addFacts(facts: Fact[]): Promise<void>;\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 navigate(path: string): Promise<void>;\n\n /**\n * Start recording\n * @returns Promise that resolves when recording starts\n */\n startRecording(): Promise<void>;\n\n /**\n * Stop recording\n * @returns Promise that resolves when recording stops\n */\n stopRecording(): Promise<void>;\n\n /**\n * Get current component status\n * @returns Promise resolving to current status\n */\n getStatus(): Promise<GetStatusResponse>;\n\n /**\n * Get all templates available to the current user\n * @returns Promise resolving to list of templates\n */\n getTemplates(): Promise<GetTemplatesResponse>;\n\n /**\n * Configure the application\n * @param config Application configuration\n * @returns Promise that resolves when configuration is applied\n */\n configure(config: ConfigureAppPayload): Promise<ConfigureAppResponse>;\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 setCredentials(credentials: { password: string }): Promise<void>;\n\n /**\n * Show the embedded UI\n */\n show(): void;\n\n /**\n * Hide the embedded UI\n */\n hide(): void;\n}\n"]}
@@ -24,9 +24,3 @@ export interface ConfigureAppPayload {
24
24
  locale?: Partial<LocaleConfig>;
25
25
  network?: Partial<NetworkConfig>;
26
26
  }
27
- export interface ConfigureAppResponsePayload {
28
- appearance: AppearanceConfig;
29
- features: FeaturesConfig;
30
- locale: LocaleConfig;
31
- network: NetworkConfig;
32
- }
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AAAA,iDAAiD","sourcesContent":["// Configuration types for the embedded component\n\nexport interface AppearanceConfig {\n primaryColor: string | null;\n}\n\nexport interface FeaturesConfig {\n interactionTitle: boolean;\n aiChat: boolean;\n documentFeedback: boolean;\n navigation: boolean;\n virtualMode: boolean;\n syncDocumentAction: boolean;\n templateEditor: boolean;\n}\n\nexport interface LocaleConfig {\n interfaceLanguage: string;\n dictationLanguage?: string | null;\n overrides?: Record<string, string>;\n}\n\nexport interface NetworkConfig {\n websocketBaseUrl?: string | null;\n}\n\nexport interface ConfigureAppPayload {\n appearance?: Partial<AppearanceConfig>;\n features?: Partial<FeaturesConfig>;\n locale?: Partial<LocaleConfig>;\n network?: Partial<NetworkConfig>;\n}\n\nexport interface ConfigureAppResponsePayload {\n appearance: AppearanceConfig;\n features: FeaturesConfig;\n locale: LocaleConfig;\n network: NetworkConfig;\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AAAA,iDAAiD","sourcesContent":["// Configuration types for the embedded component\n\nexport interface AppearanceConfig {\n primaryColor: string | null;\n}\n\nexport interface FeaturesConfig {\n interactionTitle: boolean;\n aiChat: boolean;\n documentFeedback: boolean;\n navigation: boolean;\n virtualMode: boolean;\n syncDocumentAction: boolean;\n templateEditor: boolean;\n}\n\nexport interface LocaleConfig {\n interfaceLanguage: string;\n dictationLanguage?: string | null;\n overrides?: Record<string, string>;\n}\n\nexport interface NetworkConfig {\n websocketBaseUrl?: string | null;\n}\n\nexport interface ConfigureAppPayload {\n appearance?: Partial<AppearanceConfig>;\n features?: Partial<FeaturesConfig>;\n locale?: Partial<LocaleConfig>;\n network?: Partial<NetworkConfig>;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { Corti } from "@corti/sdk";
2
- import type { UserInfo } from "./payloads.js";
2
+ import type { UserInfo } from "./responses.js";
3
3
  export interface NavigateEventPayload {
4
4
  interactionId: string;
5
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/types/events.ts"],"names":[],"mappings":"","sourcesContent":["// Event payload types for embedded component events\nimport type { Corti } from \"@corti/sdk\";\n\nimport type { UserInfo } from \"./payloads.js\";\n\nexport interface NavigateEventPayload {\n interactionId: string;\n}\n\nexport interface DocumentEventPayload {\n document: Corti.DocumentsGetResponse;\n}\n\nexport interface AuthChangedEventPayload {\n user: UserInfo;\n}\n\nexport interface InteractionCreatedEventPayload {\n interaction: {\n id: string;\n createdAt: string;\n };\n}\n\nexport interface NavigationChangedEventPayload {\n path: string;\n}\n\nexport interface ErrorEventPayload {\n message: string;\n code?: string;\n details?: unknown;\n}\n\nexport interface UsageEventPayload {\n creditsConsumed: number;\n}\n"]}
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/types/events.ts"],"names":[],"mappings":"","sourcesContent":["// Event payload types for embedded component events\nimport type { Corti } from \"@corti/sdk\";\n\nimport type { UserInfo } from \"./responses.js\";\n\nexport interface NavigateEventPayload {\n interactionId: string;\n}\n\nexport interface DocumentEventPayload {\n document: Corti.DocumentsGetResponse;\n}\n\nexport interface AuthChangedEventPayload {\n user: UserInfo;\n}\n\nexport interface InteractionCreatedEventPayload {\n interaction: {\n id: string;\n createdAt: string;\n };\n}\n\nexport interface NavigationChangedEventPayload {\n path: string;\n}\n\nexport interface ErrorEventPayload {\n message: string;\n code?: string;\n details?: unknown;\n}\n\nexport interface UsageEventPayload {\n creditsConsumed: number;\n}\n"]}
@@ -2,4 +2,5 @@ export * from "./api.js";
2
2
  export * from "./config.js";
3
3
  export * from "./events.js";
4
4
  export * from "./payloads.js";
5
+ export * from "./responses.js";
5
6
  export * from "./protocol.js";
@@ -7,6 +7,8 @@ export * from "./config.js";
7
7
  export * from "./events.js";
8
8
  // Payload types
9
9
  export * from "./payloads.js";
10
+ // Response types
11
+ export * from "./responses.js";
10
12
  // Protocol types
11
13
  export * from "./protocol.js";
12
14
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,yCAAyC;AAEzC,mBAAmB;AACnB,cAAc,UAAU,CAAC;AACzB,eAAe;AACf,cAAc,aAAa,CAAC;AAC5B,cAAc;AACd,cAAc,aAAa,CAAC;AAC5B,gBAAgB;AAChB,cAAc,eAAe,CAAC;AAC9B,iBAAiB;AACjB,cAAc,eAAe,CAAC","sourcesContent":["// Main exports for @corti/embedded-types\n\n// Public API types\nexport * from \"./api.js\";\n// Config types\nexport * from \"./config.js\";\n// Event types\nexport * from \"./events.js\";\n// Payload types\nexport * from \"./payloads.js\";\n// Protocol types\nexport * from \"./protocol.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,yCAAyC;AAEzC,mBAAmB;AACnB,cAAc,UAAU,CAAC;AACzB,eAAe;AACf,cAAc,aAAa,CAAC;AAC5B,cAAc;AACd,cAAc,aAAa,CAAC;AAC5B,gBAAgB;AAChB,cAAc,eAAe,CAAC;AAC9B,iBAAiB;AACjB,cAAc,gBAAgB,CAAC;AAC/B,iBAAiB;AACjB,cAAc,eAAe,CAAC","sourcesContent":["// Main exports for @corti/embedded-types\n\n// Public API types\nexport * from \"./api.js\";\n// Config types\nexport * from \"./config.js\";\n// Event types\nexport * from \"./events.js\";\n// Payload types\nexport * from \"./payloads.js\";\n// Response types\nexport * from \"./responses.js\";\n// Protocol types\nexport * from \"./protocol.js\";\n"]}
@@ -20,20 +20,6 @@ export interface KeycloakTokenResponse {
20
20
  export interface AuthPayload extends KeycloakTokenResponse {
21
21
  mode: AuthMode;
22
22
  }
23
- export interface UserInfo {
24
- id: string;
25
- email: string;
26
- name?: string;
27
- [key: string]: unknown;
28
- }
29
- export interface AuthResponse {
30
- user: UserInfo;
31
- }
32
- export interface CreateInteractionResponse {
33
- id: string;
34
- createdAt: string;
35
- status?: string;
36
- }
37
23
  export interface Fact {
38
24
  text: Corti.FactsCreateInput["text"];
39
25
  group: string;
@@ -1 +1 @@
1
- {"version":3,"file":"payloads.js","sourceRoot":"","sources":["../../src/types/payloads.ts"],"names":[],"mappings":"","sourcesContent":["// Payload types for embedded API requests and responses\nimport type { Corti } from \"@corti/sdk\";\n\nimport type { AuthMode, DefaultMode } from \"./protocol.js\";\n\n// Keycloak token structure\nexport interface KeycloakTokenResponse {\n access_token: string;\n token_type: string;\n expires_at?: number | null;\n expires_in?: number | null;\n refresh_expires_in?: number | null;\n refresh_token?: string;\n id_token?: string;\n \"not-before-policy\"?: number | null;\n session_state?: string;\n scope?: string;\n profile?: {\n name: string;\n email: string;\n sub: string;\n };\n}\n\n// Authentication payload\nexport interface AuthPayload extends KeycloakTokenResponse {\n mode: AuthMode;\n}\n\n// User info structure\nexport interface UserInfo {\n id: string;\n email: string;\n name?: string;\n [key: string]: unknown;\n}\n\n// Auth response\nexport interface AuthResponse {\n user: UserInfo;\n}\n\n// Create interaction response\nexport interface CreateInteractionResponse {\n id: string;\n createdAt: string;\n status?: string;\n}\n\n// Fact structure\nexport interface Fact {\n text: Corti.FactsCreateInput[\"text\"];\n group: string;\n source?: Corti.FactsCreateInput[\"source\"];\n}\n\n// Create interaction payload\nexport interface CreateInteractionPayload {\n assignedUserId?: Corti.InteractionsCreateRequest[\"assignedUserId\"] | null;\n encounter: {\n identifier: Corti.InteractionsCreateRequest[\"encounter\"][\"identifier\"];\n status: Corti.InteractionsCreateRequest[\"encounter\"][\"status\"];\n type: Corti.InteractionsCreateRequest[\"encounter\"][\"type\"];\n period: {\n startedAt: string;\n endedAt?: string;\n };\n title?: string;\n };\n patient?: {\n identifier?: Corti.InteractionsPatient[\"identifier\"];\n name?: string;\n birthDate?: string | null;\n gender?: Corti.InteractionsPatient[\"gender\"];\n };\n}\n\n// Add facts payload\nexport interface AddFactsPayload {\n facts: Fact[];\n}\n\n// Configure session payload\nexport interface ConfigureSessionPayload {\n defaultLanguage?: string;\n defaultOutputLanguage?: string;\n defaultTemplateKey?: string;\n defaultMode?: DefaultMode;\n}\n\n// Navigate payload\nexport interface NavigatePayload {\n path: string;\n}\n\n// Set credentials payload\nexport interface SetCredentialsPayload {\n password: string;\n}\n"]}
1
+ {"version":3,"file":"payloads.js","sourceRoot":"","sources":["../../src/types/payloads.ts"],"names":[],"mappings":"","sourcesContent":["// Payload types for embedded API requests and responses\nimport type { Corti } from \"@corti/sdk\";\n\nimport type { AuthMode, DefaultMode } from \"./protocol.js\";\n\n// Keycloak token structure\nexport interface KeycloakTokenResponse {\n access_token: string;\n token_type: string;\n expires_at?: number | null;\n expires_in?: number | null;\n refresh_expires_in?: number | null;\n refresh_token?: string;\n id_token?: string;\n \"not-before-policy\"?: number | null;\n session_state?: string;\n scope?: string;\n profile?: {\n name: string;\n email: string;\n sub: string;\n };\n}\n\n// Authentication payload\nexport interface AuthPayload extends KeycloakTokenResponse {\n mode: AuthMode;\n}\n\n// Fact structure\nexport interface Fact {\n text: Corti.FactsCreateInput[\"text\"];\n group: string;\n source?: Corti.FactsCreateInput[\"source\"];\n}\n\n// Create interaction payload\nexport interface CreateInteractionPayload {\n assignedUserId?: Corti.InteractionsCreateRequest[\"assignedUserId\"] | null;\n encounter: {\n identifier: Corti.InteractionsCreateRequest[\"encounter\"][\"identifier\"];\n status: Corti.InteractionsCreateRequest[\"encounter\"][\"status\"];\n type: Corti.InteractionsCreateRequest[\"encounter\"][\"type\"];\n period: {\n startedAt: string;\n endedAt?: string;\n };\n title?: string;\n };\n patient?: {\n identifier?: Corti.InteractionsPatient[\"identifier\"];\n name?: string;\n birthDate?: string | null;\n gender?: Corti.InteractionsPatient[\"gender\"];\n };\n}\n\n// Add facts payload\nexport interface AddFactsPayload {\n facts: Fact[];\n}\n\n// Configure session payload\nexport interface ConfigureSessionPayload {\n defaultLanguage?: string;\n defaultOutputLanguage?: string;\n defaultTemplateKey?: string;\n defaultMode?: DefaultMode;\n}\n\n// Navigate payload\nexport interface NavigatePayload {\n path: string;\n}\n\n// Set credentials payload\nexport interface SetCredentialsPayload {\n password: string;\n}\n"]}
@@ -2,7 +2,7 @@ export type APIVersion = "v1";
2
2
  export type MessageType = "CORTI_EMBEDDED" | "CORTI_EMBEDDED_RESPONSE" | "CORTI_EMBEDDED_EVENT";
3
3
  export type AuthMode = "stateless" | "stateful";
4
4
  export type DefaultMode = "virtual" | "in-person";
5
- export type EmbeddedAction = "auth" | "createInteraction" | "addFacts" | "configureSession" | "navigate" | "startRecording" | "stopRecording" | "getStatus" | "configure" | "setCredentials";
5
+ export type EmbeddedAction = "auth" | "createInteraction" | "addFacts" | "configureSession" | "navigate" | "startRecording" | "stopRecording" | "getStatus" | "getTemplates" | "configure" | "setCredentials";
6
6
  export type DeprecatedEmbeddedEvent = "ready" | "loaded" | "recordingStarted" | "recordingStopped" | "documentGenerated" | "documentUpdated" | "documentSynced" | "authChanged" | "interactionCreated" | "navigationChanged" | "usage";
7
7
  export interface BaseMessage {
8
8
  type: MessageType;
@@ -61,6 +61,9 @@ export interface StopRecordingRequest extends EmbeddedRequest {
61
61
  export interface GetStatusRequest extends EmbeddedRequest {
62
62
  action: "getStatus";
63
63
  }
64
+ export interface GetTemplatesRequest extends EmbeddedRequest {
65
+ action: "getTemplates";
66
+ }
64
67
  export interface ConfigureRequest extends EmbeddedRequest {
65
68
  action: "configure";
66
69
  }
@@ -100,7 +103,7 @@ export interface NavigationChangedEvent extends DeprecatedEmbeddedEventMessage {
100
103
  export interface UsageEvent extends DeprecatedEmbeddedEventMessage {
101
104
  event: "usage";
102
105
  }
103
- export type AnyEmbeddedRequest = AuthRequest | CreateInteractionRequest | AddFactsRequest | ConfigureSessionRequest | NavigateRequest | StartRecordingRequest | StopRecordingRequest | GetStatusRequest | ConfigureRequest | SetCredentialsRequest;
106
+ export type AnyEmbeddedRequest = AuthRequest | CreateInteractionRequest | AddFactsRequest | ConfigureSessionRequest | GetTemplatesRequest | NavigateRequest | StartRecordingRequest | StopRecordingRequest | GetStatusRequest | ConfigureRequest | SetCredentialsRequest;
104
107
  export type AnyEmbeddedResponse = EmbeddedResponse;
105
108
  export type AnyDeprecatedEmbeddedEvent = ReadyEvent | LoadedEvent | RecordingStartedEvent | RecordingStoppedEvent | DocumentGeneratedEvent | DocumentUpdatedEvent | DocumentSyncedEvent | AuthChangedEvent | InteractionCreatedEvent | NavigationChangedEvent | UsageEvent;
106
109
  export type AnyEvent = EmbeddedEventMessage | AnyDeprecatedEmbeddedEvent;
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/types/protocol.ts"],"names":[],"mappings":"AAAA,4FAA4F","sourcesContent":["// Protocol types for communication between parent applications and embedded Corti Assistant\n\nexport type APIVersion = \"v1\";\n\nexport type MessageType = \"CORTI_EMBEDDED\" | \"CORTI_EMBEDDED_RESPONSE\" | \"CORTI_EMBEDDED_EVENT\";\n\nexport type AuthMode = \"stateless\" | \"stateful\";\n\nexport type DefaultMode = \"virtual\" | \"in-person\";\n\nexport type EmbeddedAction =\n | \"auth\"\n | \"createInteraction\"\n | \"addFacts\"\n | \"configureSession\"\n | \"navigate\"\n | \"startRecording\"\n | \"stopRecording\"\n | \"getStatus\"\n | \"configure\"\n | \"setCredentials\";\n\nexport type DeprecatedEmbeddedEvent =\n | \"ready\"\n | \"loaded\"\n | \"recordingStarted\"\n | \"recordingStopped\"\n | \"documentGenerated\"\n | \"documentUpdated\"\n | \"documentSynced\"\n | \"authChanged\"\n | \"interactionCreated\"\n | \"navigationChanged\"\n | \"usage\";\n\n// Base Message Types\nexport interface BaseMessage {\n type: MessageType;\n version: APIVersion;\n}\n\nexport interface EmbeddedRequest extends BaseMessage {\n type: \"CORTI_EMBEDDED\";\n action: EmbeddedAction;\n requestId: string;\n payload?: unknown;\n}\n\nexport interface EmbeddedResponse extends BaseMessage {\n type: \"CORTI_EMBEDDED_RESPONSE\";\n action: EmbeddedAction;\n requestId: string;\n success: boolean;\n payload?: unknown;\n error?: string;\n errorCode?: string;\n errorDetails?: unknown;\n}\n\ninterface BaseEventMessage extends BaseMessage {\n type: \"CORTI_EMBEDDED_EVENT\";\n event: string | DeprecatedEmbeddedEvent;\n payload?: unknown;\n}\n\nexport interface DeprecatedEmbeddedEventMessage extends BaseEventMessage {\n event: DeprecatedEmbeddedEvent;\n deprecated: true;\n}\n\nexport interface EmbeddedEventMessage extends BaseEventMessage {\n payload: null | Record<string, unknown>;\n confidential: boolean;\n}\n\n// Specific Request Types\nexport interface AuthRequest extends EmbeddedRequest {\n action: \"auth\";\n}\n\nexport interface CreateInteractionRequest extends EmbeddedRequest {\n action: \"createInteraction\";\n}\n\nexport interface AddFactsRequest extends EmbeddedRequest {\n action: \"addFacts\";\n}\n\nexport interface ConfigureSessionRequest extends EmbeddedRequest {\n action: \"configureSession\";\n}\n\nexport interface NavigateRequest extends EmbeddedRequest {\n action: \"navigate\";\n}\n\nexport interface StartRecordingRequest extends EmbeddedRequest {\n action: \"startRecording\";\n}\n\nexport interface StopRecordingRequest extends EmbeddedRequest {\n action: \"stopRecording\";\n}\n\nexport interface GetStatusRequest extends EmbeddedRequest {\n action: \"getStatus\";\n}\n\nexport interface ConfigureRequest extends EmbeddedRequest {\n action: \"configure\";\n}\n\nexport interface SetCredentialsRequest extends EmbeddedRequest {\n action: \"setCredentials\";\n}\n\n// Event Types\nexport interface ReadyEvent extends DeprecatedEmbeddedEventMessage {\n event: \"ready\";\n}\n\nexport interface LoadedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"loaded\";\n}\n\nexport interface RecordingStartedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"recordingStarted\";\n}\n\nexport interface RecordingStoppedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"recordingStopped\";\n}\n\nexport interface DocumentGeneratedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"documentGenerated\";\n}\n\nexport interface DocumentUpdatedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"documentUpdated\";\n}\n\nexport interface DocumentSyncedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"documentSynced\";\n}\n\nexport interface AuthChangedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"authChanged\";\n}\n\nexport interface InteractionCreatedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"interactionCreated\";\n}\n\nexport interface NavigationChangedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"navigationChanged\";\n}\n\nexport interface UsageEvent extends DeprecatedEmbeddedEventMessage {\n event: \"usage\";\n}\n\n// Request/Response/Event type unions\nexport type AnyEmbeddedRequest =\n | AuthRequest\n | CreateInteractionRequest\n | AddFactsRequest\n | ConfigureSessionRequest\n | NavigateRequest\n | StartRecordingRequest\n | StopRecordingRequest\n | GetStatusRequest\n | ConfigureRequest\n | SetCredentialsRequest;\n\nexport type AnyEmbeddedResponse = EmbeddedResponse;\n\nexport type AnyDeprecatedEmbeddedEvent =\n | ReadyEvent\n | LoadedEvent\n | RecordingStartedEvent\n | RecordingStoppedEvent\n | DocumentGeneratedEvent\n | DocumentUpdatedEvent\n | DocumentSyncedEvent\n | AuthChangedEvent\n | InteractionCreatedEvent\n | NavigationChangedEvent\n | UsageEvent;\n\nexport type AnyEvent = EmbeddedEventMessage | AnyDeprecatedEmbeddedEvent;\n\nexport type AnyEmbeddedMessage =\n | AnyEmbeddedRequest\n | AnyEmbeddedResponse\n | AnyDeprecatedEmbeddedEvent;\n"]}
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/types/protocol.ts"],"names":[],"mappings":"AAAA,4FAA4F","sourcesContent":["// Protocol types for communication between parent applications and embedded Corti Assistant\n\nexport type APIVersion = \"v1\";\n\nexport type MessageType = \"CORTI_EMBEDDED\" | \"CORTI_EMBEDDED_RESPONSE\" | \"CORTI_EMBEDDED_EVENT\";\n\nexport type AuthMode = \"stateless\" | \"stateful\";\n\nexport type DefaultMode = \"virtual\" | \"in-person\";\n\nexport type EmbeddedAction =\n | \"auth\"\n | \"createInteraction\"\n | \"addFacts\"\n | \"configureSession\"\n | \"navigate\"\n | \"startRecording\"\n | \"stopRecording\"\n | \"getStatus\"\n | \"getTemplates\"\n | \"configure\"\n | \"setCredentials\";\n\nexport type DeprecatedEmbeddedEvent =\n | \"ready\"\n | \"loaded\"\n | \"recordingStarted\"\n | \"recordingStopped\"\n | \"documentGenerated\"\n | \"documentUpdated\"\n | \"documentSynced\"\n | \"authChanged\"\n | \"interactionCreated\"\n | \"navigationChanged\"\n | \"usage\";\n\n// Base Message Types\nexport interface BaseMessage {\n type: MessageType;\n version: APIVersion;\n}\n\nexport interface EmbeddedRequest extends BaseMessage {\n type: \"CORTI_EMBEDDED\";\n action: EmbeddedAction;\n requestId: string;\n payload?: unknown;\n}\n\nexport interface EmbeddedResponse extends BaseMessage {\n type: \"CORTI_EMBEDDED_RESPONSE\";\n action: EmbeddedAction;\n requestId: string;\n success: boolean;\n payload?: unknown;\n error?: string;\n errorCode?: string;\n errorDetails?: unknown;\n}\n\ninterface BaseEventMessage extends BaseMessage {\n type: \"CORTI_EMBEDDED_EVENT\";\n event: string | DeprecatedEmbeddedEvent;\n payload?: unknown;\n}\n\nexport interface DeprecatedEmbeddedEventMessage extends BaseEventMessage {\n event: DeprecatedEmbeddedEvent;\n deprecated: true;\n}\n\nexport interface EmbeddedEventMessage extends BaseEventMessage {\n payload: null | Record<string, unknown>;\n confidential: boolean;\n}\n\n// Specific Request Types\nexport interface AuthRequest extends EmbeddedRequest {\n action: \"auth\";\n}\n\nexport interface CreateInteractionRequest extends EmbeddedRequest {\n action: \"createInteraction\";\n}\n\nexport interface AddFactsRequest extends EmbeddedRequest {\n action: \"addFacts\";\n}\n\nexport interface ConfigureSessionRequest extends EmbeddedRequest {\n action: \"configureSession\";\n}\n\nexport interface NavigateRequest extends EmbeddedRequest {\n action: \"navigate\";\n}\n\nexport interface StartRecordingRequest extends EmbeddedRequest {\n action: \"startRecording\";\n}\n\nexport interface StopRecordingRequest extends EmbeddedRequest {\n action: \"stopRecording\";\n}\n\nexport interface GetStatusRequest extends EmbeddedRequest {\n action: \"getStatus\";\n}\n\nexport interface GetTemplatesRequest extends EmbeddedRequest {\n action: \"getTemplates\";\n}\n\nexport interface ConfigureRequest extends EmbeddedRequest {\n action: \"configure\";\n}\n\nexport interface SetCredentialsRequest extends EmbeddedRequest {\n action: \"setCredentials\";\n}\n\n// Event Types\nexport interface ReadyEvent extends DeprecatedEmbeddedEventMessage {\n event: \"ready\";\n}\n\nexport interface LoadedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"loaded\";\n}\n\nexport interface RecordingStartedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"recordingStarted\";\n}\n\nexport interface RecordingStoppedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"recordingStopped\";\n}\n\nexport interface DocumentGeneratedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"documentGenerated\";\n}\n\nexport interface DocumentUpdatedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"documentUpdated\";\n}\n\nexport interface DocumentSyncedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"documentSynced\";\n}\n\nexport interface AuthChangedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"authChanged\";\n}\n\nexport interface InteractionCreatedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"interactionCreated\";\n}\n\nexport interface NavigationChangedEvent extends DeprecatedEmbeddedEventMessage {\n event: \"navigationChanged\";\n}\n\nexport interface UsageEvent extends DeprecatedEmbeddedEventMessage {\n event: \"usage\";\n}\n\n// Request/Response/Event type unions\nexport type AnyEmbeddedRequest =\n | AuthRequest\n | CreateInteractionRequest\n | AddFactsRequest\n | ConfigureSessionRequest\n | GetTemplatesRequest\n | NavigateRequest\n | StartRecordingRequest\n | StopRecordingRequest\n | GetStatusRequest\n | ConfigureRequest\n | SetCredentialsRequest;\n\nexport type AnyEmbeddedResponse = EmbeddedResponse;\n\nexport type AnyDeprecatedEmbeddedEvent =\n | ReadyEvent\n | LoadedEvent\n | RecordingStartedEvent\n | RecordingStoppedEvent\n | DocumentGeneratedEvent\n | DocumentUpdatedEvent\n | DocumentSyncedEvent\n | AuthChangedEvent\n | InteractionCreatedEvent\n | NavigationChangedEvent\n | UsageEvent;\n\nexport type AnyEvent = EmbeddedEventMessage | AnyDeprecatedEmbeddedEvent;\n\nexport type AnyEmbeddedMessage =\n | AnyEmbeddedRequest\n | AnyEmbeddedResponse\n | AnyDeprecatedEmbeddedEvent;\n"]}
@@ -0,0 +1,48 @@
1
+ import type { AppearanceConfig, FeaturesConfig, LocaleConfig, NetworkConfig } from "./config.js";
2
+ import type { EmbeddedInterviewDetails } from "./generated/interview-details.js";
3
+ export interface UserInfo {
4
+ id: string;
5
+ email: string;
6
+ name?: string;
7
+ [key: string]: unknown;
8
+ }
9
+ export interface AuthResponse {
10
+ user: UserInfo;
11
+ }
12
+ export interface CreateInteractionResponse {
13
+ id: string;
14
+ createdAt: string;
15
+ status?: string;
16
+ }
17
+ export interface EmbeddedTemplate {
18
+ id: string;
19
+ name: string;
20
+ description?: string;
21
+ language: {
22
+ code: string;
23
+ name: string;
24
+ locale?: string;
25
+ };
26
+ sections: Array<{
27
+ id: string;
28
+ title: string;
29
+ }>;
30
+ isCustom: boolean;
31
+ }
32
+ export interface GetStatusResponse {
33
+ auth: {
34
+ isAuthenticated: boolean;
35
+ user?: UserInfo;
36
+ };
37
+ currentUrl: string;
38
+ interaction: EmbeddedInterviewDetails | null;
39
+ }
40
+ export interface GetTemplatesResponse {
41
+ templates: EmbeddedTemplate[];
42
+ }
43
+ export interface ConfigureAppResponse {
44
+ appearance: AppearanceConfig;
45
+ features: FeaturesConfig;
46
+ locale: LocaleConfig;
47
+ network: NetworkConfig;
48
+ }
@@ -0,0 +1,3 @@
1
+ // Response types for embedded API
2
+ export {};
3
+ //# sourceMappingURL=responses.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responses.js","sourceRoot":"","sources":["../../src/types/responses.ts"],"names":[],"mappings":"AAAA,kCAAkC","sourcesContent":["// Response types for embedded API\n\nimport type { AppearanceConfig, FeaturesConfig, LocaleConfig, NetworkConfig } from \"./config.js\";\nimport type { EmbeddedInterviewDetails } from \"./generated/interview-details.js\";\n\nexport interface UserInfo {\n id: string;\n email: string;\n name?: string;\n [key: string]: unknown;\n}\n\nexport interface AuthResponse {\n user: UserInfo;\n}\n\nexport interface CreateInteractionResponse {\n id: string;\n createdAt: string;\n status?: string;\n}\n\nexport interface EmbeddedTemplate {\n id: string;\n name: string;\n description?: string;\n language: {\n code: string;\n name: string;\n locale?: string;\n };\n sections: Array<{\n id: string;\n title: string;\n }>;\n isCustom: boolean;\n}\n\nexport interface GetStatusResponse {\n auth: {\n isAuthenticated: boolean;\n user?: UserInfo;\n };\n currentUrl: string;\n interaction: EmbeddedInterviewDetails | null;\n}\n\nexport interface GetTemplatesResponse {\n templates: EmbeddedTemplate[];\n}\n\nexport interface ConfigureAppResponse {\n appearance: AppearanceConfig;\n features: FeaturesConfig;\n locale: LocaleConfig;\n network: NetworkConfig;\n}\n"]}
@@ -1,15 +1,9 @@
1
- import type { AddFactsPayload, AuthPayload, AuthResponse, ConfigureAppPayload, ConfigureAppResponsePayload, ConfigureSessionPayload, CreateInteractionPayload, CreateInteractionResponse, EmbeddedRequest, EmbeddedResponse, EmbeddedEventData, GetStatusResponsePayload, NavigatePayload, SetCredentialsPayload, DocumentEventPayload } from '../types';
1
+ import type { AddFactsPayload, AuthPayload, AuthResponse, ConfigureAppPayload, ConfigureAppResponse, ConfigureSessionPayload, CreateInteractionPayload, CreateInteractionResponse, EmbeddedRequest, EmbeddedResponse, GetStatusResponse, NavigatePayload, SetCredentialsPayload, GetTemplatesResponse } from '../types';
2
2
  export interface PostMessageHandlerCallbacks {
3
- onReady?: () => void;
4
- onAuthChanged?: (payload: any) => void;
5
- onInteractionCreated?: (payload: any) => void;
6
- onRecordingStarted?: () => void;
7
- onRecordingStopped?: () => void;
8
- onDocumentGenerated?: (payload: DocumentEventPayload) => void;
9
- onDocumentUpdated?: (payload: DocumentEventPayload) => void;
10
- onDocumentSynced?: (payload: DocumentEventPayload) => void;
11
- onNavigationChanged?: (payload: any) => void;
12
- onUsage?: (payload: EmbeddedEventData['usage']) => void;
3
+ onEvent?: (event: {
4
+ name: string;
5
+ payload: unknown;
6
+ }) => void;
13
7
  onError?: (error: {
14
8
  message: string;
15
9
  code?: string;
@@ -92,19 +86,24 @@ export declare class PostMessageHandler {
92
86
  * Helper method to get current status
93
87
  * @returns Promise that resolves with current status
94
88
  */
95
- getStatus(): Promise<GetStatusResponsePayload>;
89
+ getStatus(): Promise<GetStatusResponse>;
96
90
  /**
97
91
  * Helper method to configure the component
98
92
  * @param payload - Component configuration payload
99
93
  * @returns Promise that resolves when configuration is applied
100
94
  */
101
- configure(payload: ConfigureAppPayload): Promise<ConfigureAppResponsePayload>;
95
+ configure(payload: ConfigureAppPayload): Promise<ConfigureAppResponse>;
102
96
  /**
103
97
  * Helper method to set credentials without triggering auth flow
104
98
  * @param payload - Credentials payload
105
99
  * @returns Promise that resolves when credentials are set
106
100
  */
107
101
  setCredentials(payload: SetCredentialsPayload): Promise<void>;
102
+ /**
103
+ * Helper method to get templates
104
+ * @returns Promise that resolves with a list of templates
105
+ */
106
+ getTemplates(): Promise<GetTemplatesResponse>;
108
107
  private static generateRequestId;
109
108
  /**
110
109
  * Derive the trusted origin from the iframe src (constructed from baseURL).
@@ -35,45 +35,15 @@ export class PostMessageHandler {
35
35
  const eventType = eventData.event;
36
36
  const { payload } = eventData;
37
37
  // Handle ready-like events
38
- if (eventType === 'ready' || eventType === 'loaded') {
38
+ if (eventType === 'ready' ||
39
+ eventType === 'loaded' ||
40
+ eventType === 'embedded.ready') {
39
41
  this.isReady = true;
40
42
  }
41
- // Handle specific events with callbacks
42
- switch (eventType) {
43
- case 'embedded.ready':
44
- this.callbacks.onReady?.();
45
- break;
46
- case 'authChanged':
47
- this.callbacks.onAuthChanged?.(payload);
48
- break;
49
- case 'embedded.interactionCreated':
50
- this.callbacks.onInteractionCreated?.(payload);
51
- break;
52
- case 'recording.started':
53
- this.callbacks.onRecordingStarted?.();
54
- break;
55
- case 'recording.stopped':
56
- this.callbacks.onRecordingStopped?.();
57
- break;
58
- case 'document.generated':
59
- this.callbacks.onDocumentGenerated?.(payload);
60
- break;
61
- case 'document.updated':
62
- this.callbacks.onDocumentUpdated?.(payload);
63
- break;
64
- case 'document.synced':
65
- this.callbacks.onDocumentSynced?.(payload);
66
- break;
67
- case 'embedded.navigated':
68
- this.callbacks.onNavigationChanged?.(payload);
69
- break;
70
- case 'account.creditsConsumed':
71
- this.callbacks.onUsage?.(payload);
72
- break;
73
- default:
74
- console.warn(`Unhandled event type: ${eventType}`);
75
- break;
76
- }
43
+ this.callbacks.onEvent?.({
44
+ name: eventType,
45
+ payload,
46
+ });
77
47
  }
78
48
  handleResponse(data) {
79
49
  const pendingRequest = this.pendingRequests.get(data.requestId);
@@ -131,7 +101,9 @@ export class PostMessageHandler {
131
101
  if (event.source === this.iframe.contentWindow &&
132
102
  event.origin === this.getTrustedOrigin() &&
133
103
  event.data?.type === 'CORTI_EMBEDDED_EVENT' &&
134
- event.data.event === 'ready') {
104
+ (event.data.event === 'ready' ||
105
+ event.data.event === 'loaded' ||
106
+ event.data.event === 'embedded.ready')) {
135
107
  clearTimeout(timeoutId);
136
108
  window.removeEventListener('message', readyListener);
137
109
  resolve();
@@ -198,7 +170,6 @@ export class PostMessageHandler {
198
170
  action: 'auth',
199
171
  payload,
200
172
  });
201
- this.isReady = false;
202
173
  if (response.payload && response.success) {
203
174
  return response.payload.user;
204
175
  }
@@ -330,6 +301,21 @@ export class PostMessageHandler {
330
301
  payload,
331
302
  });
332
303
  }
304
+ /**
305
+ * Helper method to get templates
306
+ * @returns Promise that resolves with a list of templates
307
+ */
308
+ async getTemplates() {
309
+ const response = await this.postMessage({
310
+ type: 'CORTI_EMBEDDED',
311
+ version: 'v1',
312
+ action: 'getTemplates',
313
+ });
314
+ if (response.payload && response.success) {
315
+ return response.payload;
316
+ }
317
+ throw new Error(response.error);
318
+ }
333
319
  static generateRequestId() {
334
320
  return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
335
321
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PostMessageHandler.js","sourceRoot":"","sources":["../../src/utils/PostMessageHandler.ts"],"names":[],"mappings":"AAqCA,MAAM,OAAO,kBAAkB;IAc7B,YACE,MAAyB,EACzB,YAAyC,EAAE;QAfrC,oBAAe,GAAG,IAAI,GAAG,EAG9B,CAAC;QAEI,oBAAe,GAA2C,IAAI,CAAC;QAI/D,YAAO,GAAG,KAAK,CAAC;QAQtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC9B,CAAC;IAEO,oBAAoB;QAC1B,IAAI,CAAC,eAAe,GAAG,CAAC,KAAmB,EAAE,EAAE;YAC7C,uCAAuC;YACvC,IAAI,KAAK,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE,CAAC;gBAC/C,OAAO;YACT,CAAC;YAED,oDAAoD;YACpD,MAAM,aAAa,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC9C,IAAI,CAAC,aAAa,IAAI,KAAK,CAAC,MAAM,KAAK,aAAa,EAAE,CAAC;gBACrD,OAAO;YACT,CAAC;YAED,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;YAEvB,kCAAkC;YAClC,IAAI,IAAI,EAAE,IAAI,KAAK,sBAAsB,EAAE,CAAC;gBAC1C,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;gBACvB,OAAO;YACT,CAAC;YAED,mDAAmD;YACnD,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;gBAC/D,IAAI,CAAC,cAAc,CAAC,IAAI,CAA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ourcesContent":["import type {\n AddFactsPayload,\n AnyEvent,\n AuthPayload,\n AuthResponse,\n ConfigureAppPayload,\n ConfigureAppResponsePayload,\n ConfigureSessionPayload,\n CreateInteractionPayload,\n CreateInteractionResponse,\n EmbeddedRequest,\n EmbeddedResponse,\n EmbeddedEventData,\n GetStatusResponsePayload,\n NavigatePayload,\n SetCredentialsPayload,\n DocumentEventPayload,\n} from '../types';\n\nexport interface PostMessageHandlerCallbacks {\n onReady?: () => void;\n onAuthChanged?: (payload: any) => void;\n onInteractionCreated?: (payload: any) => void;\n onRecordingStarted?: () => void;\n onRecordingStopped?: () => void;\n onDocumentGenerated?: (payload: DocumentEventPayload) => void;\n onDocumentUpdated?: (payload: DocumentEventPayload) => void;\n onDocumentSynced?: (payload: DocumentEventPayload) => void;\n onNavigationChanged?: (payload: any) => void;\n onUsage?: (payload: EmbeddedEventData['usage']) => void;\n onError?: (error: {\n message: string;\n code?: string;\n details?: unknown;\n }) => void;\n}\n\nexport class PostMessageHandler {\n private pendingRequests = new Map<\n string,\n { resolve: (value: any) => void; reject: (reason: any) => void }\n >();\n\n private messageListener: ((event: MessageEvent) => void) | null = null;\n\n private iframe: HTMLIFrameElement;\n\n private isReady = false;\n\n private callbacks: PostMessageHandlerCallbacks;\n\n constructor(\n iframe: HTMLIFrameElement,\n callbacks: PostMessageHandlerCallbacks = {},\n ) {\n this.iframe = iframe;\n this.callbacks = callbacks;\n this.setupMessageListener();\n }\n\n private setupMessageListener() {\n this.messageListener = (event: MessageEvent) => {\n // Only handle messages from our iframe\n if (event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Enforce origin to match the trusted iframe origin\n const trustedOrigin = this.getTrustedOrigin();\n if (!trustedOrigin || event.origin !== trustedOrigin) {\n return;\n }\n\n const { data } = event;\n\n // Check for Corti embedded events\n if (data?.type === 'CORTI_EMBEDDED_EVENT') {\n this.handleEvent(data);\n return;\n }\n\n // Check if this is a response to a pending request\n if (data.requestId && this.pendingRequests.has(data.requestId)) {\n this.handleResponse(data);\n }\n };\n\n window.addEventListener('message', this.messageListener);\n }\n\n private handleEvent(eventData: AnyEvent): void {\n const eventType = (eventData as any).event;\n const { payload } = eventData;\n\n // Handle ready-like events\n if (eventType === 'ready' || eventType === 'loaded') {\n this.isReady = true;\n }\n\n // Handle specific events with callbacks\n switch (eventType) {\n case 'embedded.ready':\n this.callbacks.onReady?.();\n break;\n case 'authChanged':\n this.callbacks.onAuthChanged?.(payload);\n break;\n case 'embedded.interactionCreated':\n this.callbacks.onInteractionCreated?.(payload);\n break;\n case 'recording.started':\n this.callbacks.onRecordingStarted?.();\n break;\n case 'recording.stopped':\n this.callbacks.onRecordingStopped?.();\n break;\n case 'document.generated':\n this.callbacks.onDocumentGenerated?.(\n payload as EmbeddedEventData['document-generated'],\n );\n break;\n case 'document.updated':\n this.callbacks.onDocumentUpdated?.(\n payload as EmbeddedEventData['document-updated'],\n );\n break;\n case 'document.synced':\n this.callbacks.onDocumentSynced?.(\n payload as EmbeddedEventData['document-synced'],\n );\n break;\n case 'embedded.navigated':\n this.callbacks.onNavigationChanged?.(\n payload as EmbeddedEventData['navigation-changed'],\n );\n break;\n case 'account.creditsConsumed':\n this.callbacks.onUsage?.(payload as EmbeddedEventData['usage']);\n break;\n default:\n console.warn(`Unhandled event type: ${eventType}`);\n break;\n }\n }\n\n private handleResponse(data: any): void {\n const pendingRequest = this.pendingRequests.get(data.requestId);\n if (pendingRequest) {\n const { resolve, reject } = pendingRequest;\n this.pendingRequests.delete(data.requestId);\n\n if (data.success === false || data.error) {\n const error = {\n message: data.error || 'Request failed',\n code: data.errorCode,\n details: data.errorDetails,\n };\n this.callbacks.onError?.(error);\n reject(error);\n } else {\n resolve(data);\n }\n }\n }\n\n destroy() {\n if (this.messageListener) {\n window.removeEventListener('message', this.messageListener);\n this.messageListener = null;\n }\n this.pendingRequests.clear();\n }\n\n /**\n * Update callbacks after construction\n */\n updateCallbacks(callbacks: PostMessageHandlerCallbacks) {\n this.callbacks = { ...this.callbacks, ...callbacks };\n }\n\n /**\n * Check if the iframe is ready to receive postMessages\n */\n get ready(): boolean {\n return this.isReady;\n }\n\n /**\n * Wait for the iframe to be ready\n * @param timeout - Optional timeout in milliseconds (default: 30000ms)\n * @returns Promise that resolves when ready\n */\n async waitForReady(timeout = 30000): Promise<void> {\n if (this.isReady) {\n return Promise.resolve();\n }\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error('Timeout waiting for iframe to be ready'));\n }, timeout);\n\n // Create a one-time listener for the ready event\n const readyListener = (event: MessageEvent) => {\n if (\n event.source === this.iframe.contentWindow &&\n event.origin === this.getTrustedOrigin() &&\n event.data?.type === 'CORTI_EMBEDDED_EVENT' &&\n event.data.event === 'ready'\n ) {\n clearTimeout(timeoutId);\n window.removeEventListener('message', readyListener);\n resolve();\n }\n };\n\n window.addEventListener('message', readyListener);\n });\n }\n\n /**\n * Sends a postMessage to the iframe and returns a Promise that resolves with the response\n * @param message - The message to send\n * @param timeout - Optional timeout in milliseconds (default: 10000ms)\n * @returns Promise that resolves with the response\n */\n async postMessage(\n message: Omit<EmbeddedRequest, 'requestId'>,\n timeout = 10000,\n ): Promise<EmbeddedResponse> {\n if (!this.iframe.contentWindow) {\n throw new Error('Iframe not ready');\n }\n\n // Ensure the iframe has signaled readiness before sending\n await this.waitForReady();\n\n const { contentWindow } = this.iframe;\n const requestId = PostMessageHandler.generateRequestId();\n\n return new Promise((resolve, reject) => {\n // Set up timeout\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(requestId);\n reject(new Error('Request timeout'));\n }, timeout);\n\n // Store the promise handlers\n const handlers = {\n resolve: (value: any) => {\n clearTimeout(timeoutId);\n resolve(value);\n },\n reject: (reason: any) => {\n clearTimeout(timeoutId);\n reject(reason);\n },\n };\n\n this.pendingRequests.set(requestId, handlers);\n\n // Send the message\n const fullMessage: EmbeddedRequest = {\n ...message,\n requestId,\n };\n\n const targetOrigin = this.getTrustedOrigin();\n if (!targetOrigin) {\n this.pendingRequests.delete(requestId);\n reject(new Error('Cannot determine trusted origin for postMessage'));\n return;\n }\n contentWindow.postMessage(fullMessage, targetOrigin);\n });\n }\n\n /**\n * Helper method to send an auth message and return clean user data\n * @param payload - Auth payload\n * @returns Promise that resolves with user data\n */\n async auth(payload: AuthPayload): Promise<AuthResponse['user']> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'auth',\n payload,\n });\n this.isReady = false;\n\n if (response.payload && response.success) {\n return (response.payload as AuthResponse).user;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to configure a session\n * @param payload - Session configuration payload\n * @returns Promise that resolves when configuration is complete\n */\n async configureSession(payload: ConfigureSessionPayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'configureSession',\n payload,\n });\n }\n\n /**\n * Helper method to navigate to a specific path\n * @param payload - Navigation payload\n * @returns Promise that resolves when navigation is complete\n */\n async navigate(payload: NavigatePayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'navigate',\n payload,\n });\n }\n\n /**\n * Helper method to add facts to the session\n * @param payload - Facts payload\n * @returns Promise that resolves when facts are added\n */\n async addFacts(payload: AddFactsPayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'addFacts',\n payload,\n });\n }\n\n /**\n * Helper method to create a new interaction and return clean interaction data\n * @param payload - Interaction creation payload\n * @returns Promise that resolves with interaction details\n */\n async createInteraction(\n payload: CreateInteractionPayload,\n ): Promise<CreateInteractionResponse> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'createInteraction',\n payload,\n });\n\n if (response.payload && response.success) {\n return response.payload as CreateInteractionResponse;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to start recording\n * @returns Promise that resolves when recording starts\n */\n async startRecording(): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'startRecording',\n payload: {},\n });\n }\n\n /**\n * Helper method to stop recording\n * @returns Promise that resolves when recording stops\n */\n async stopRecording(): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'stopRecording',\n payload: {},\n });\n }\n\n /**\n * Helper method to get current status\n * @returns Promise that resolves with current status\n */\n async getStatus(): Promise<GetStatusResponsePayload> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'getStatus',\n payload: {},\n });\n\n if (response.payload && response.success) {\n return response.payload as GetStatusResponsePayload;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to configure the component\n * @param payload - Component configuration payload\n * @returns Promise that resolves when configuration is applied\n */\n async configure(\n payload: ConfigureAppPayload,\n ): Promise<ConfigureAppResponsePayload> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'configure',\n payload,\n });\n\n if (response.payload && response.success) {\n return response.payload as ConfigureAppResponsePayload;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to set credentials without triggering auth flow\n * @param payload - Credentials payload\n * @returns Promise that resolves when credentials are set\n */\n async setCredentials(payload: SetCredentialsPayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'setCredentials',\n payload,\n });\n }\n\n private static generateRequestId(): string {\n return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Derive the trusted origin from the iframe src (constructed from baseURL).\n * Returns null if it cannot be determined.\n */\n private getTrustedOrigin(): string | null {\n try {\n // If iframe.src is relative, URL() will resolve against the current location.\n // Embeds should provide an absolute baseURL; enforcing strict origin here.\n const src = this.iframe.getAttribute('src') || this.iframe.src;\n if (!src) return null;\n const url = new URL(src, window.location.href);\n return url.origin;\n } catch {\n return null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"PostMessageHandler.js","sourceRoot":"","sources":["../../src/utils/PostMessageHand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,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;IACxE,CAAC;IAED;;;OAGG;IACK,gBAAgB;QACtB,IAAI,CAAC;YACH,8EAA8E;YAC9E,2EAA2E;YAC3E,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC;YAC/D,IAAI,CAAC,GAAG;gBAAE,OAAO,IAAI,CAAC;YACtB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YAC/C,OAAO,GAAG,CAAC,MAAM,CAAC;QACpB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n AddFactsPayload,\n AnyEvent,\n AuthPayload,\n AuthResponse,\n ConfigureAppPayload,\n ConfigureAppResponse,\n ConfigureSessionPayload,\n CreateInteractionPayload,\n CreateInteractionResponse,\n EmbeddedRequest,\n EmbeddedResponse,\n GetStatusResponse,\n NavigatePayload,\n SetCredentialsPayload,\n GetTemplatesResponse,\n} from '../types';\n\nexport interface PostMessageHandlerCallbacks {\n onEvent?: (event: { name: string; payload: unknown }) => void;\n onError?: (error: {\n message: string;\n code?: string;\n details?: unknown;\n }) => void;\n}\n\nexport class PostMessageHandler {\n private pendingRequests = new Map<\n string,\n { resolve: (value: any) => void; reject: (reason: any) => void }\n >();\n\n private messageListener: ((event: MessageEvent) => void) | null = null;\n\n private iframe: HTMLIFrameElement;\n\n private isReady = false;\n\n private callbacks: PostMessageHandlerCallbacks;\n\n constructor(\n iframe: HTMLIFrameElement,\n callbacks: PostMessageHandlerCallbacks = {},\n ) {\n this.iframe = iframe;\n this.callbacks = callbacks;\n this.setupMessageListener();\n }\n\n private setupMessageListener() {\n this.messageListener = (event: MessageEvent) => {\n // Only handle messages from our iframe\n if (event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Enforce origin to match the trusted iframe origin\n const trustedOrigin = this.getTrustedOrigin();\n if (!trustedOrigin || event.origin !== trustedOrigin) {\n return;\n }\n\n const { data } = event;\n\n // Check for Corti embedded events\n if (data?.type === 'CORTI_EMBEDDED_EVENT') {\n this.handleEvent(data);\n return;\n }\n\n // Check if this is a response to a pending request\n if (data.requestId && this.pendingRequests.has(data.requestId)) {\n this.handleResponse(data);\n }\n };\n\n window.addEventListener('message', this.messageListener);\n }\n\n private handleEvent(eventData: AnyEvent): void {\n const eventType = (eventData as any).event;\n const { payload } = eventData;\n\n // Handle ready-like events\n if (\n eventType === 'ready' ||\n eventType === 'loaded' ||\n eventType === 'embedded.ready'\n ) {\n this.isReady = true;\n }\n\n this.callbacks.onEvent?.({\n name: eventType,\n payload,\n });\n }\n\n private handleResponse(data: any): void {\n const pendingRequest = this.pendingRequests.get(data.requestId);\n if (pendingRequest) {\n const { resolve, reject } = pendingRequest;\n this.pendingRequests.delete(data.requestId);\n\n if (data.success === false || data.error) {\n const error = {\n message: data.error || 'Request failed',\n code: data.errorCode,\n details: data.errorDetails,\n };\n this.callbacks.onError?.(error);\n reject(error);\n } else {\n resolve(data);\n }\n }\n }\n\n destroy() {\n if (this.messageListener) {\n window.removeEventListener('message', this.messageListener);\n this.messageListener = null;\n }\n this.pendingRequests.clear();\n }\n\n /**\n * Update callbacks after construction\n */\n updateCallbacks(callbacks: PostMessageHandlerCallbacks) {\n this.callbacks = { ...this.callbacks, ...callbacks };\n }\n\n /**\n * Check if the iframe is ready to receive postMessages\n */\n get ready(): boolean {\n return this.isReady;\n }\n\n /**\n * Wait for the iframe to be ready\n * @param timeout - Optional timeout in milliseconds (default: 30000ms)\n * @returns Promise that resolves when ready\n */\n async waitForReady(timeout = 30000): Promise<void> {\n if (this.isReady) {\n return Promise.resolve();\n }\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error('Timeout waiting for iframe to be ready'));\n }, timeout);\n\n // Create a one-time listener for the ready event\n const readyListener = (event: MessageEvent) => {\n if (\n event.source === this.iframe.contentWindow &&\n event.origin === this.getTrustedOrigin() &&\n event.data?.type === 'CORTI_EMBEDDED_EVENT' &&\n (event.data.event === 'ready' ||\n event.data.event === 'loaded' ||\n event.data.event === 'embedded.ready')\n ) {\n clearTimeout(timeoutId);\n window.removeEventListener('message', readyListener);\n resolve();\n }\n };\n\n window.addEventListener('message', readyListener);\n });\n }\n\n /**\n * Sends a postMessage to the iframe and returns a Promise that resolves with the response\n * @param message - The message to send\n * @param timeout - Optional timeout in milliseconds (default: 10000ms)\n * @returns Promise that resolves with the response\n */\n async postMessage(\n message: Omit<EmbeddedRequest, 'requestId'>,\n timeout = 10000,\n ): Promise<EmbeddedResponse> {\n if (!this.iframe.contentWindow) {\n throw new Error('Iframe not ready');\n }\n\n // Ensure the iframe has signaled readiness before sending\n await this.waitForReady();\n\n const { contentWindow } = this.iframe;\n const requestId = PostMessageHandler.generateRequestId();\n\n return new Promise((resolve, reject) => {\n // Set up timeout\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(requestId);\n reject(new Error('Request timeout'));\n }, timeout);\n\n // Store the promise handlers\n const handlers = {\n resolve: (value: any) => {\n clearTimeout(timeoutId);\n resolve(value);\n },\n reject: (reason: any) => {\n clearTimeout(timeoutId);\n reject(reason);\n },\n };\n\n this.pendingRequests.set(requestId, handlers);\n\n // Send the message\n const fullMessage: EmbeddedRequest = {\n ...message,\n requestId,\n };\n\n const targetOrigin = this.getTrustedOrigin();\n if (!targetOrigin) {\n this.pendingRequests.delete(requestId);\n reject(new Error('Cannot determine trusted origin for postMessage'));\n return;\n }\n contentWindow.postMessage(fullMessage, targetOrigin);\n });\n }\n\n /**\n * Helper method to send an auth message and return clean user data\n * @param payload - Auth payload\n * @returns Promise that resolves with user data\n */\n async auth(payload: AuthPayload): Promise<AuthResponse['user']> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'auth',\n payload,\n });\n\n if (response.payload && response.success) {\n return (response.payload as AuthResponse).user;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to configure a session\n * @param payload - Session configuration payload\n * @returns Promise that resolves when configuration is complete\n */\n async configureSession(payload: ConfigureSessionPayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'configureSession',\n payload,\n });\n }\n\n /**\n * Helper method to navigate to a specific path\n * @param payload - Navigation payload\n * @returns Promise that resolves when navigation is complete\n */\n async navigate(payload: NavigatePayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'navigate',\n payload,\n });\n }\n\n /**\n * Helper method to add facts to the session\n * @param payload - Facts payload\n * @returns Promise that resolves when facts are added\n */\n async addFacts(payload: AddFactsPayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'addFacts',\n payload,\n });\n }\n\n /**\n * Helper method to create a new interaction and return clean interaction data\n * @param payload - Interaction creation payload\n * @returns Promise that resolves with interaction details\n */\n async createInteraction(\n payload: CreateInteractionPayload,\n ): Promise<CreateInteractionResponse> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'createInteraction',\n payload,\n });\n\n if (response.payload && response.success) {\n return response.payload as CreateInteractionResponse;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to start recording\n * @returns Promise that resolves when recording starts\n */\n async startRecording(): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'startRecording',\n payload: {},\n });\n }\n\n /**\n * Helper method to stop recording\n * @returns Promise that resolves when recording stops\n */\n async stopRecording(): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'stopRecording',\n payload: {},\n });\n }\n\n /**\n * Helper method to get current status\n * @returns Promise that resolves with current status\n */\n async getStatus(): Promise<GetStatusResponse> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'getStatus',\n payload: {},\n });\n\n if (response.payload && response.success) {\n return response.payload as GetStatusResponse;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to configure the component\n * @param payload - Component configuration payload\n * @returns Promise that resolves when configuration is applied\n */\n async configure(payload: ConfigureAppPayload): Promise<ConfigureAppResponse> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'configure',\n payload,\n });\n\n if (response.payload && response.success) {\n return response.payload as ConfigureAppResponse;\n }\n throw new Error(response.error);\n }\n\n /**\n * Helper method to set credentials without triggering auth flow\n * @param payload - Credentials payload\n * @returns Promise that resolves when credentials are set\n */\n async setCredentials(payload: SetCredentialsPayload): Promise<void> {\n await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'setCredentials',\n payload,\n });\n }\n\n /**\n * Helper method to get templates\n * @returns Promise that resolves with a list of templates\n */\n async getTemplates(): Promise<GetTemplatesResponse> {\n const response = await this.postMessage({\n type: 'CORTI_EMBEDDED',\n version: 'v1',\n action: 'getTemplates',\n });\n\n if (response.payload && response.success) {\n return response.payload as GetTemplatesResponse;\n }\n throw new Error(response.error);\n }\n\n private static generateRequestId(): string {\n return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Derive the trusted origin from the iframe src (constructed from baseURL).\n * Returns null if it cannot be determined.\n */\n private getTrustedOrigin(): string | null {\n try {\n // If iframe.src is relative, URL() will resolve against the current location.\n // Embeds should provide an absolute baseURL; enforcing strict origin here.\n const src = this.iframe.getAttribute('src') || this.iframe.src;\n if (!src) return null;\n const url = new URL(src, window.location.href);\n return url.origin;\n } catch {\n return null;\n }\n }\n}\n"]}