@callimacus/thamyr 4.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,514 @@
1
+ # Thamyr SDK Documentation
2
+
3
+ ## Overview
4
+
5
+ Thamyr is the AI agent within Callimacus that is designed to generate and arrange dynamic, intuitive user interfaces that adapt to user intent and context. By leveraging proprietary AI algorithms, Thamyr transcends traditional typographic approaches to website design, creating a more immersive and context-sensitive experience for users.
6
+
7
+ ## Core Concepts
8
+
9
+ ### 1. Story
10
+ A Story is the overarching structure that encapsulates a user's journey, intent, and context. It is made up of multiple Chapters, each representing a distinct part of the interaction. Stories ensure continuity by preserving the user's intent and context, allowing Thamyr to maintain relevance across different interactions.
11
+
12
+ ### 2. Chapter
13
+ A Chapter is a component of a Story that responds to specific user actions or inputs. Each chapter is generated in response to an inputEvent and can evolve based on prior interactions.
14
+
15
+ ### 3. InputEvent
16
+ An inputEvent is any user interaction that triggers Thamyr to respond. Input events can be:
17
+
18
+ - A click on an element of the website.
19
+ - A user query (written or audio).
20
+
21
+ ### 4. Response
22
+ Thamyr processes input events to produce a response, which is made up of different types of blocks. These blocks are the building blocks of the UI and represent different forms of content.
23
+
24
+ ## Blocks
25
+
26
+ A Block is a unit of content generated by Thamyr in response to a user input. Each block can be one of the following types:
27
+
28
+ - **Text Block**: A simple textual response or message.
29
+ - **Image**: A visual representation, such as a single image.
30
+ - **Gallery**: A collection of images displayed together.
31
+ - **Video**: A media block containing a video.
32
+ - **Rich Media**: A block that can contain complex content, such as embedded elements or interactive features.
33
+ - **Topic**: A block that introduces a new subject or theme related to the context.
34
+ - **Custom Element**: A user-defined block type that can be customized to meet specific needs or functionalities.
35
+
36
+ ## How Thamyr Works
37
+
38
+ **Receiving Input**: When an inputEvent occurs (e.g., a user clicks on a button or asks a question), Thamyr receives and processes it.
39
+ **Generating the Story**: Based on the input event, Thamyr identifies the appropriate Chapter within the Story and produces a relevant response.
40
+ **Creating Blocks**: Thamyr's response consists of one or more blocks, which are then arranged to create the best possible user interface for the given context.
41
+
42
+ ---
43
+
44
+ ## Technical Setup
45
+
46
+ ### Prerequisites
47
+
48
+ Before you begin, ensure that you have the following:
49
+
50
+ * **GitHub Account**: You must have a GitHub account to access and contribute to the project.
51
+ * **Git and Node.js**: Ensure you have Git and Node.js installed on your local machine.
52
+ * **nvm (Node Version Manager)**: This project uses `nvm` to manage Node.js versions. Make sure you have [nvm](https://github.com/nvm-sh/nvm) installed.
53
+
54
+ ### Cloning the Repository
55
+
56
+ 1. **Access the Repository**: After being granted access to the repository, you will receive a link to clone it. Use the following command to clone the repository to your local machine:
57
+
58
+ ```bash
59
+ git clone https://github.com/your-org/your-repo.git
60
+ ```
61
+
62
+ 2. **Navigate to the Repository**:
63
+
64
+ ```bash
65
+ cd your-repo
66
+ ```
67
+
68
+ ### Installing the Correct Node Version
69
+
70
+ 1. **Install Node Version**: The repository contains a `.nvmrc` file that specifies the Node.js version to be used. To install the correct version, run the following command:
71
+
72
+ ```bash
73
+ nvm install
74
+ ```
75
+
76
+ This will automatically install the version of Node.js specified in the `.nvmrc` file.
77
+
78
+ 2. **Use the Correct Version**: Once the installation is complete, you can use the specified Node version by running:
79
+
80
+ ```bash
81
+ nvm use
82
+ ```
83
+
84
+ ### Branching and Development Workflow
85
+
86
+ 1. **Create a Development Branch**: The main branch is used for production, so create a new branch for any feature or bug fix. Branches must follow the naming convention:
87
+
88
+ ```
89
+ branch.repo.gymnasium.callimacus.ai
90
+ ```
91
+
92
+ Example:
93
+
94
+ ```bash
95
+ git checkout -b new-feature.repo.gymnasium.callimacus.ai
96
+ ```
97
+
98
+ This ensures that each branch has a unique URL when deployed.
99
+
100
+ 2. **Make Changes**: Develop and test your changes locally. Be sure to follow the project's coding conventions.
101
+
102
+ 3. **Commit Messages**: Commit messages must follow the guidelines outlined in the [Conventional Commits specification](https://www.conventionalcommits.org/). This helps ensure a consistent commit history and automated versioning.
103
+
104
+ Example commit message:
105
+
106
+ ```
107
+ feat(button): add primary button style
108
+ ```
109
+
110
+ 4. **Push Changes**: After completing your work, commit your changes and push them to GitHub:
111
+
112
+ ```bash
113
+ git add .
114
+ git commit -m "feat(new-feature): implement new feature"
115
+ git push origin new-feature.repo.gymnasium.callimacus.ai
116
+ ```
117
+
118
+ ### Credentials Management
119
+
120
+ 1. **Basic HTTP Authentication**: All deployed URLs are protected by basic HTTP authentication. You can manage the credentials for these URLs via the **Callimacus Backoffice**.
121
+
122
+ 2. **Client ID**: Callimacus requires a Client ID (`cal-pk-…`) for authentication to function properly. To use it, initialize the Callimacus instance with your Client ID as shown below:
123
+
124
+ ```javascript
125
+ const instance = new Thamyr({
126
+ clientId: import.meta.env.VITE_CALLIMACUS_CLIENT_ID,
127
+ });
128
+ ```
129
+
130
+ You can manage and retrieve your Client ID via the **Callimacus Backoffice**. Make sure to securely store the Client ID and use it in the appropriate environment variables (`VITE_CALLIMACUS_CLIENT_ID`).
131
+
132
+ ### Code Quality Checks
133
+
134
+ Before merging your code into the `main` branch, ensure that your code passes the quality checks. These checks include:
135
+
136
+ * **Linting**: To check the code style and ensure best practices.
137
+ * **Code Coverage**: To ensure adequate testing and test coverage for your changes.
138
+
139
+ The quality checks are automatically run through the CI pipeline when a pull request (PR) is created. However, you can run them locally before pushing your changes:
140
+
141
+ ```bash
142
+ npm run build && npm run lint && npm run test
143
+ ```
144
+
145
+ * **Linting**: This command will check for code style issues.
146
+ * **Testing**: This command will run tests to verify that your code behaves as expected.
147
+
148
+ ### Creating a Pull Request (PR)
149
+
150
+ 1. **Open a PR**: Once your code is ready, create a pull request (PR) from your branch (e.g., `new-feature.repo.gymnasium.callimacus.ai`) to the `main` branch.
151
+
152
+ 2. **Passing Quality Checks**: Ensure that the CI pipeline passes all checks (linting, tests, and coverage) before merging. You can monitor the PR’s status for any errors or failed checks.
153
+
154
+ 3. **Merge to Main**: After the PR passes all checks and gets reviewed, you can merge it into the `main` branch. This will trigger the deployment to production.
155
+
156
+ ### Deployment
157
+
158
+ * **Frontend Hosting**: The frontend is automatically hosted by Callimacus. Once merged to the `main` branch, the latest changes will be deployed to the production environment.
159
+ * **Preview Environments**: Each branch you create will automatically have a unique preview URL under the format `branch.repo.gymnasium.callimacus.ai`.
160
+
161
+ ### Troubleshooting
162
+
163
+ * **Quality Check Failures**: If your PR fails any quality checks, review the error messages in the CI pipeline. Typically, these errors are related to linting or failing tests. Run `npm run lint` and `npm run test` locally to identify and fix issues before pushing again.
164
+ * **Branch Naming Issues**: Ensure that your branch name follows the correct format. If the branch name does not match the required pattern, it may not be deployed to a preview environment.
165
+ * **Merge Conflicts**: If you encounter merge conflicts, resolve them by pulling the latest changes from the `main` branch and updating your feature branch:
166
+
167
+ ```bash
168
+ git pull origin main
169
+ ```
170
+
171
+ ---
172
+
173
+ ## How to Use the Thamyr SDK
174
+
175
+ ### Setup and Initialization
176
+
177
+ To use the Thamyr SDK in your project, follow these steps:
178
+
179
+ 1. **Install the SDK**: First, you need to install the Thamyr SDK package. Run the following command in your project directory:
180
+
181
+ ```bash
182
+ npm install @callimacus/thamyr
183
+ ```
184
+
185
+ 2. **Initialize Thamyr**: In your React component, initialize the `Thamyr` instance with your Client ID, which is required for API interaction. The Client ID is typically stored in an environment variable for security purposes.
186
+
187
+ Example:
188
+
189
+ ```javascript
190
+ import { useEffect, useRef, useState } from 'react';
191
+ import { Thamyr, ThamyrResponseType } from '@callimacus/thamyr';
192
+
193
+ function App() {
194
+ const [chapters, setChapters] = useState([]);
195
+ const thamyrRef = useRef(null);
196
+
197
+ useEffect(() => {
198
+ const instance = new Thamyr({
199
+ clientId: import.meta.env.VITE_CALLIMACUS_CLIENT_ID,
200
+ });
201
+
202
+ thamyrRef.current = instance;
203
+
204
+ instance.onResponse(response => {
205
+ if (response.type === ThamyrResponseType.CHAPTER_EVENT) {
206
+ setChapters(prev => {
207
+ const existingIndex = prev.findIndex(c => c.id === response.chapter.id);
208
+ if (existingIndex !== -1) {
209
+ const updated = [...prev];
210
+ updated[existingIndex] = response.chapter;
211
+ return updated;
212
+ } else {
213
+ return [...prev, response.chapter];
214
+ }
215
+ });
216
+ }
217
+ });
218
+ }, []);
219
+ }
220
+ ```
221
+
222
+ > **Tip**: Building with React? `@callimacus/thamyr-react` wraps this SDK in hooks (`useInitThamyr({clientId})`, `useThamyr`, `useConnection`, `useOnResponse`, `useOnConnectionChange`, `useOnError`, `useApi`, `useCart`, `useSkesis`, `useSitemap`, `useCallimacusStore`, plus `useVoiceRecorder` and `useTtsAudio` for voice input and text-to-speech playback) so you never manage the instance yourself.
223
+
224
+ ### Sending User Input
225
+
226
+ To trigger interactions and send user input, you'll need to handle user events like text input or clicks. In the example below, we send a question as an input event.
227
+
228
+ 1. **Handle User Input**: Collect user input (e.g., from a text box) and send it to Thamyr as an input event.
229
+
230
+ ```javascript
231
+ import { UserInteractionType, SLInputEventType } from '@callimacus/thamyr';
232
+
233
+ const handleAsk = () => {
234
+ const inputSL = {
235
+ type: SLInputEventType.question, // Type of input event
236
+ data: { value: inputText } // User's input text
237
+ };
238
+ setInputText("Type your next question");
239
+
240
+ thamyrRef.current?.sendUserInteraction(UserInteractionType.CREATE_ROUND, {
241
+ inputEvent: inputSL,
242
+ });
243
+ };
244
+ ```
245
+
246
+ 2. **Triggering User Interaction**: When the user presses the Enter key, you send the question to Thamyr.
247
+
248
+ ```javascript
249
+ const handleKeyDown = (e) => {
250
+ if (e.key === "Enter") {
251
+ e.preventDefault();
252
+ handleAsk();
253
+ }
254
+ };
255
+ ```
256
+
257
+ ### Rendering Blocks
258
+
259
+ Thamyr responds with different types of content blocks based on the input events. You can render these blocks in your UI using a switch-case structure or dynamic rendering.
260
+
261
+ In the provided code, blocks are rendered based on their type. For example:
262
+
263
+ * **Text Block**: Displayed as plain text.
264
+ * **Image Block**: Displayed as an image.
265
+ * **Video Block**: Displayed as a video.
266
+
267
+ Here's an example of how to render different block types:
268
+
269
+ ```javascript
270
+ const BlockRenderer = ({ block }) => {
271
+ switch (block.type) {
272
+ case "demosthenesResponse":
273
+ return <TextBlock data={block.data} />;
274
+ case "image":
275
+ return <ImageBlock data={block.data} />;
276
+ case "video":
277
+ return <VideoBlock data={block.data} />;
278
+ case "gallery":
279
+ return <GalleryNew data={block.data} />;
280
+ default:
281
+ return <div>Unsupported block type: {block.type}</div>;
282
+ }
283
+ };
284
+ ```
285
+
286
+ ### Full Example of Block Rendering in Action
287
+
288
+ ```javascript
289
+ return (
290
+ <div className="App">
291
+ <div>
292
+ {chapters.length > 0 ? (
293
+ chapters.map((item, idx) => (
294
+ item.status === ChapterStatus.understandingQuery ? (
295
+ <p key={idx + 1}>Loading...</p>
296
+ ) : (
297
+ <div key={idx + 1}>
298
+ {item.blocks?.map(block => (
299
+ <BlockRenderer key={block.id} block={block} />
300
+ ))}
301
+ </div>
302
+ )
303
+ ))
304
+ ) : <p key={0}></p>}
305
+ </div>
306
+ <input
307
+ type="text"
308
+ value={inputText}
309
+ onChange={e => setInputText(e.target.value)}
310
+ placeholder="Type your question"
311
+ onKeyDown={handleKeyDown}
312
+ />
313
+ </div>
314
+ );
315
+ ```
316
+
317
+ (`ChapterStatus` is exported from `@callimacus/thamyr`.)
318
+
319
+ ### Example of a Block Component (ImageBlock)
320
+
321
+ ```javascript
322
+ const ImageBlock = ({ data }) => {
323
+ return <img src={data.url} alt={data.content} className="rounded-lg shadow-lg" />;
324
+ };
325
+
326
+ export default ImageBlock;
327
+ ```
328
+
329
+ ---
330
+
331
+ ## API Namespaces
332
+
333
+ The Thamyr SDK organizes its APIs into logical namespaces for better code organization and discoverability.
334
+
335
+ ### Available Namespaces
336
+
337
+ - **`content`** - Pages, topics, and documents
338
+ - **`stories`** - Story sharing
339
+ - **`products`** - Product recommendations and similarity
340
+ - **`whisper`** - Whisper messages
341
+ - **`analytics`** - Event tracking and analytics
342
+ - **`cart`** - Shopping cart operations
343
+ - **`skesis`** - Similar and related skesis items
344
+ - **`sitemap`** - Site map retrieval
345
+
346
+ The `content`, `stories`, `products`, `whisper`, `analytics`, `cart` and `skesis` methods mirror the platform API one-to-one: each takes a single parameters object (parameterless reads like `cart.getCart` take none), resolves `{data, error, response}`, and new endpoints appear as methods automatically with SDK releases. The `sitemap` namespace keeps its classic signature (a promise that resolves to the value directly).
347
+
348
+ ### Working with Results
349
+
350
+ Platform API calls resolve `{data, error, response}` and never throw on HTTP errors — check `error` (or `response.status`) instead of wrapping calls in try/catch:
351
+
352
+ ```typescript
353
+ const thamyr = new Thamyr({
354
+ clientId: import.meta.env.VITE_CALLIMACUS_CLIENT_ID,
355
+ });
356
+
357
+ const { data: page, error } = await thamyr.content.getPage({ language: 'en', id: 'home' });
358
+
359
+ if (error) {
360
+ console.error('Could not load page:', error);
361
+ } else {
362
+ renderPage(page);
363
+ }
364
+ ```
365
+
366
+ "Not found" is a value too: on a 404, `data` is `undefined`, `error` carries the body and `response.status === 404`; on a network failure `response` is `undefined`. If you prefer exceptions, opt in per call with the second options argument (the first on parameterless methods such as `cart.getCart`): the result narrows to `{ data, request, response }` and the rejection is a `ThamyrHttpError` (since 4.1.0), an `Error` with `status`, `body`, `response` and `request`:
367
+
368
+ ```typescript
369
+ import { ThamyrHttpError } from '@callimacus/thamyr';
370
+
371
+ const { data: page } = await thamyr.content.getPage({ language: 'en', id: 'home' }, { throwOnError: true });
372
+
373
+ try {
374
+ await thamyr.cart.addItemToCart({ productId }, { throwOnError: true });
375
+ } catch (error) {
376
+ if (error instanceof ThamyrHttpError && error.status === 500) retryOnce();
377
+ }
378
+ ```
379
+
380
+ ### Content API
381
+
382
+ Access pages, topics, and documents. `language` is required — pass your locale explicitly:
383
+
384
+ ```typescript
385
+ // Get a page by ID
386
+ const { data: page } = await thamyr.content.getPage({ language: 'en', id: 'home' });
387
+
388
+ // List topics
389
+ const { data: topics } = await thamyr.content.listTopics({ language: 'en' });
390
+
391
+ // Get the contents of a topic
392
+ const { data: contents } = await thamyr.content.getTopicContents({ language: 'en', idOrSlug: 'running' });
393
+
394
+ // Get a document by slug, group, or sitemap path
395
+ const { data: bySlug } = await thamyr.content.getDocumentBySlug({ language: 'en', slug: 'about-us' });
396
+ const { data: byGroup } = await thamyr.content.getDocumentByGroup({ language: 'en', groupId: 'group-42' });
397
+ const { data: byPath } = await thamyr.content.getDocumentByPath({ path: '/en/about-us' });
398
+ ```
399
+
400
+ ### Stories API
401
+
402
+ Share a story and retrieve shared stories:
403
+
404
+ ```typescript
405
+ // Create a shareable link for a story
406
+ const { data: share } = await thamyr.stories.share({ id: 'story-123' });
407
+
408
+ // Get a shared story
409
+ const { data: shared } = await thamyr.stories.getShared({ id: 'share-id-123' });
410
+ ```
411
+
412
+ ### Products API
413
+
414
+ Get product recommendations and similar items:
415
+
416
+ ```typescript
417
+ // Get similar products — deprecated in favour of thamyr.skesis.similar; stays for all of 4.x, removed only after a product-shaped skesis read exists
418
+ const { data: similar } = await thamyr.products.getSimilar({ productId: 'product-123', topK: 10 });
419
+
420
+ // Get product recommendations — deprecated: use thamyr.skesis.related
421
+ const { data: recommendations } = await thamyr.products.getRecommendations({ productId: 'product-123' });
422
+ ```
423
+
424
+ ### Whisper API
425
+
426
+ Fetch the latest whisper for a story (a 404 simply means there is none yet):
427
+
428
+ ```typescript
429
+ const { data, response } = await thamyr.whisper.getLast({ storyId: 'story-123' });
430
+
431
+ if (response.status !== 404) {
432
+ showWhisper(data?.whisper);
433
+ }
434
+ ```
435
+
436
+ ### Analytics API
437
+
438
+ Track an event for a single content item:
439
+
440
+ ```typescript
441
+ void thamyr.analytics.trackEvent({
442
+ storyId: 'story-123',
443
+ eventName: 'content_click',
444
+ content: 'doc-42',
445
+ });
446
+ ```
447
+
448
+ Track a “generic” event (no content id) — omit `content` if you don’t have content associated with the event:
449
+
450
+ ```typescript
451
+ void thamyr.analytics.trackEvent({
452
+ storyId: 'story-123',
453
+ eventName: 'button_click',
454
+ payload: { buttonId: 'cta-primary', timestamp: Date.now() },
455
+ });
456
+ ```
457
+
458
+ Track both content and custom payload:
459
+
460
+ ```typescript
461
+ void thamyr.analytics.trackEvent({
462
+ storyId: 'story-123',
463
+ eventName: 'content_click',
464
+ content: 'doc-42',
465
+ payload: {
466
+ source: 'carousel',
467
+ position: 2,
468
+ highlighted: true,
469
+ },
470
+ });
471
+ ```
472
+
473
+ ### Cart API
474
+
475
+ Manage shopping cart operations. Like every contract namespace, cart methods take a flat parameters object and resolve the `{data, error, response}` envelope — the basket is `data`, and HTTP failures arrive as `error`, never as a rejection. The basket shape is Salesforce's own published SFCC schema (`Basket`).
476
+
477
+ ```typescript
478
+ // Get current cart
479
+ const {data: cart, error} = await thamyr.cart.getCart();
480
+
481
+ // Add item to cart
482
+ const {data: updated} = await thamyr.cart.addItemToCart({productId: 'product-123'});
483
+
484
+ // Remove item from cart
485
+ await thamyr.cart.removeItemFromCart({productId: 'product-123'});
486
+
487
+ // Update product quantity
488
+ await thamyr.cart.updateProductQuantity({productId: 'product-123', quantity: 5});
489
+ ```
490
+
491
+ ### Skesis and Sitemap APIs
492
+
493
+ ```typescript
494
+ // Similar and related skesis items
495
+ const { data: similar } = await thamyr.skesis.similar({ anchorId: 'item-123', topK: 4 });
496
+ const { data: related } = await thamyr.skesis.related({ anchorId: 'item-123' });
497
+
498
+ // Full site map
499
+ const sitemap = await thamyr.sitemap.getSitemap();
500
+ ```
501
+
502
+ ### Upgrading from 1.x, 2.x or 3.x
503
+
504
+ The wire protocol has not changed since v1: any major talks to the same server, and every break is compile-time except three things the guide calls out: error handling, retries, and the constructor rejecting an empty or relative `endpoint` at startup (4.0.2).
505
+
506
+ | From | What breaks | Where |
507
+ | --- | --- | --- |
508
+ | 1.x | `@callimacus/common` imports, `accessToken`, the flat wrappers, positional REST arguments, axios-style errors | [Coming from v1](https://docs.callimacus.ai/thamyr-sdk/8-migration#coming-from-v1) |
509
+ | 2.x | `thamyr.cart.*` positional arguments and bare `Basket` results, `CartAPI` | [Migrating to v3](https://docs.callimacus.ai/thamyr-sdk/8-migration#cart-becomes-a-contract-namespace-v300) |
510
+ | 3.x | `SkesisAPI`, positional `skesis.*`, `products.*` deprecated (kept through 4.x), `endpoint` validated (4.0.2), `basketId` required (4.0.3) | [Migrating to v4](https://docs.callimacus.ai/thamyr-sdk/8-migration#migrating-to-v4) |
511
+
512
+ The same guide ships inside this package as `MIGRATION.md`, next to `CHANGELOG.md` and `CHANGELOG.core.md` (the docs site needs a Callimacus account).
513
+
514
+ ---
@@ -0,0 +1,9 @@
1
+ /*!
2
+ * Copyright © 2025–2026 Solomei AI SRL. All rights reserved.
3
+ *
4
+ * Proprietary software, licensed for use by Callimacus customers only.
5
+ * See LICENSE.md for the full terms.
6
+ *
7
+ */
8
+ import{callimacusService as n,createContractClient as e,logger as t,CallimacusApi as o,UserInteractionType as s,SLInputEventType as r}from"@callimacus/thamyr-core";export*from"@callimacus/thamyr-core";class a{onConnectionStatusChangeCallback;onResponseCallback;onErrorCallback;onClientInfoCallback;constructor(e={}){const{autoConnect:t=!0,url:o="wss://localhost:4000",token:s,callbacks:r,uiObserver:a}=e;this.onConnectionStatusChangeCallback=r?.onConnectionStatusChange,this.onResponseCallback=r?.onResponse,this.onErrorCallback=r?.onError,this.onClientInfoCallback=r?.onClientInfo,void 0!==a&&n.configureUiObserver(a),this.setupEventListeners(),t&&this.connect(o,s)}setupEventListeners(){n.onConnectionStatus(n=>{this.onConnectionStatusChangeCallback&&this.onConnectionStatusChangeCallback(n)}),n.onServerResponse(n=>{this.onResponseCallback&&this.onResponseCallback(n)}),n.onError(n=>{this.onErrorCallback&&this.onErrorCallback(n)})}connect(e="wss://localhost:4000",t){const o="string"==typeof t&&""!==t,s=o?{Authorization:`Bearer ${t}`}:void 0,r=o?{token:t}:void 0;n.connect(e,s,r)}disconnect(){n.disconnect()}sendUserInteraction(e,t){n.sendUserInteraction(e,t)}gatherClientInfo(){n.gatherClientInfo().then(n=>{this.onClientInfoCallback&&this.onClientInfoCallback(n)})}onConnectionStatusChange(n){return this.onConnectionStatusChangeCallback=n,()=>{this.onConnectionStatusChangeCallback=void 0}}onResponse(n){return this.onResponseCallback=n,()=>{this.onResponseCallback=void 0}}onError(n){return this.onErrorCallback=n,()=>{this.onErrorCallback=void 0}}}class i{config;client;constructor(n){this.config=n,this.client=e(n)}async getSitemap(){const{data:n,error:e,response:o}=await this.client.get({url:"/sitemap.xml",headers:{Accept:"application/xml"},parseAs:"text"});if(void 0===n){const n=o?.status;throw t.error(void 0===n?"sitemap: no response received":`sitemap: API Error ${n}`,e),Object.assign(new Error(void 0===n?"sitemap request failed":`sitemap request failed with status ${n}`),{status:n,error:e})}return n}}const c="https://api.callimacus.ai";function l(n){const e=n??c;if(!function(n){try{return Boolean(new URL(n))}catch{return!1}}(e))throw new Error(`[thamyr] \`endpoint\` must be an absolute URL such as ${c}, got ${JSON.stringify(n)}. Omit it to use the default.`);return e}class h extends o{config;websocketManager;sitemap;constructor(n){const t=l(n.endpoint),{clientId:o}=n;if(!o)throw new Error("[thamyr] `clientId` is required. Pass your Callimacus Client ID (`cal-pk-…`).");super({client:e({accessToken:o,endpoint:t,withCredentials:!0})}),this.config=n,this.sitemap=new i({accessToken:o,endpoint:t}),this.websocketManager=new a({url:t,autoConnect:!0,token:o,uiObserver:n.uiObserver})}sendAudio(n,e){const t=new File([n],"recording.webm",{type:n.type});this.sendUserInteraction(s.CREATE_ROUND,{inputEvent:{type:r.question,data:{value:e??"",file:t}}})}sendUserInteraction(n,e){this.websocketManager.sendUserInteraction(n,e)}onResponse(n){this.websocketManager.onResponse(n)}onError(n){this.websocketManager.onError(n)}}export{i as SitemapAPI,h as Thamyr,a as WebsocketManager};
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../src/components/callimacus/manager.ts","../../../src/service/sitemap-api.ts","../../../src/service/thamyr.ts"],"sourcesContent":[null,null,null],"names":["WebsocketManager","onConnectionStatusChangeCallback","onResponseCallback","onErrorCallback","onClientInfoCallback","constructor","options","autoConnect","url","token","callbacks","uiObserver","this","onConnectionStatusChange","onResponse","onError","onClientInfo","undefined","callimacusService","configureUiObserver","setupEventListeners","connect","onConnectionStatus","isConnected","onServerResponse","response","error","hasToken","headers","Authorization","auth","disconnect","sendUserInteraction","type","payload","gatherClientInfo","then","clientInfo","callback","SitemapAPI","config","client","createContractClient","getSitemap","data","get","Accept","parseAs","status","logger","Object","assign","Error","DEFAULT_ENDPOINT","resolveEndpoint","endpoint","resolved","value","Boolean","URL","isAbsoluteUrl","JSON","stringify","Thamyr","CallimacusApi","websocketManager","sitemap","clientId","super","accessToken","withCredentials","sendAudio","audio","query","file","File","UserInteractionType","CREATE_ROUND","inputEvent","SLInputEventType","question"],"mappings":";;;;;;;+MA+FaA,EAEJC,iCACAC,mBACAC,gBACSC,qBAMjB,WAAAC,CAAYC,EAAoC,IAC/C,MAAMC,YACLA,GAAc,EAAIC,IAClBA,EAAM,uBAAsBC,MAC5BA,EAAKC,UACLA,EAASC,WACTA,GACGL,EAGJM,KAAKX,iCAAmCS,GAAWG,yBACnDD,KAAKV,mBAAqBQ,GAAWI,WACrCF,KAAKT,gBAAkBO,GAAWK,QAClCH,KAAKR,qBAAuBM,GAAWM,kBAEpBC,IAAfN,GACHO,EAAkBC,oBAAoBR,GAIvCC,KAAKQ,sBAEDb,GACHK,KAAKS,QAAQb,EAAKC,EAEpB,CAKQ,mBAAAW,GACPF,EAAkBI,mBAAmBC,IAChCX,KAAKX,kCACRW,KAAKX,iCAAiCsB,KAIxCL,EAAkBM,iBAAiBC,IAC9Bb,KAAKV,oBACRU,KAAKV,mBAAmBuB,KAI1BP,EAAkBH,QAASW,IACtBd,KAAKT,iBACRS,KAAKT,gBAAgBuB,IAGxB,CAQO,OAAAL,CAAQb,EAAM,uBAAwBC,GAG5C,MAAMkB,EAA4B,iBAAVlB,GAAgC,KAAVA,EAExCmB,EAAUD,EAAW,CAACE,cAAe,UAAUpB,UAAWQ,EAC1Da,EAAOH,EAAW,CAAClB,cAASQ,EAClCC,EAAkBG,QAAQb,EAAKoB,EAASE,EACzC,CAKO,UAAAC,GACNb,EAA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