@runtypelabs/persona-proxy 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,621 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ COMPONENT_FLOW: () => COMPONENT_FLOW,
24
+ CONVERSATIONAL_FLOW: () => CONVERSATIONAL_FLOW,
25
+ FORM_DIRECTIVE_FLOW: () => FORM_DIRECTIVE_FLOW,
26
+ SHOPPING_ASSISTANT_FLOW: () => SHOPPING_ASSISTANT_FLOW,
27
+ SHOPPING_ASSISTANT_METADATA_FLOW: () => SHOPPING_ASSISTANT_METADATA_FLOW,
28
+ createChatProxyApp: () => createChatProxyApp,
29
+ createCheckoutSession: () => createCheckoutSession,
30
+ createVercelHandler: () => createVercelHandler,
31
+ default: () => index_default
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+ var import_hono = require("hono");
35
+ var import_vercel = require("hono/vercel");
36
+
37
+ // src/flows/conversational.ts
38
+ var CONVERSATIONAL_FLOW = {
39
+ name: "Streaming Prompt Flow",
40
+ description: "Streaming chat generated by the widget",
41
+ steps: [
42
+ {
43
+ id: "widget_prompt",
44
+ name: "Prompt",
45
+ type: "prompt",
46
+ enabled: true,
47
+ config: {
48
+ model: "meta/llama3.1-8b-instruct-free",
49
+ response_format: "markdown",
50
+ output_variable: "prompt_result",
51
+ user_prompt: "{{user_message}}",
52
+ system_prompt: "you are a helpful assistant, chatting with a user",
53
+ previous_messages: "{{messages}}"
54
+ }
55
+ }
56
+ ]
57
+ };
58
+
59
+ // src/flows/scheduling.ts
60
+ var FORM_DIRECTIVE_FLOW = {
61
+ name: "Dynamic Form Flow",
62
+ description: "Returns dynamic forms as component directives",
63
+ steps: [
64
+ {
65
+ id: "form_prompt",
66
+ name: "Form Prompt",
67
+ type: "prompt",
68
+ enabled: true,
69
+ config: {
70
+ model: "qwen/qwen3-8b",
71
+ reasoning: false,
72
+ responseFormat: "JSON",
73
+ outputVariable: "prompt_result",
74
+ userPrompt: "{{user_message}}",
75
+ systemPrompt: `You are a helpful assistant that can have conversations and collect user information via forms.
76
+
77
+ RESPONSE FORMAT:
78
+ Always respond with valid JSON. Choose the appropriate format:
79
+
80
+ 1. For CONVERSATIONAL responses or text answers:
81
+ {"text": "Your response here"}
82
+
83
+ 2. When the user wants to SCHEDULE, BOOK, SIGN UP, or provide DETAILS (show a form):
84
+ {"component": "DynamicForm", "props": {"title": "Form Title", "description": "Optional description", "fields": [...], "submit_text": "Submit"}}
85
+
86
+ 3. For BOTH explanation AND form:
87
+ {"text": "Your explanation", "component": "DynamicForm", "props": {...}}
88
+
89
+ FORM FIELD FORMAT:
90
+ Each field in the "fields" array should have:
91
+ - label (required): Display name for the field
92
+ - name (optional): Field identifier (defaults to lowercase label with underscores)
93
+ - type (optional): "text", "email", "tel", "date", "time", "textarea", "number" (defaults to "text")
94
+ - placeholder (optional): Placeholder text
95
+ - required (optional): true/false
96
+
97
+ EXAMPLES:
98
+
99
+ User: "Schedule a demo for me"
100
+ Response: {"text": "I'd be happy to help you schedule a demo! Please fill out the form below:", "component": "DynamicForm", "props": {"title": "Schedule a Demo", "description": "Share your details and we'll follow up with a confirmation.", "fields": [{"label": "Full Name", "type": "text", "required": true}, {"label": "Email", "type": "email", "required": true}, {"label": "Company", "type": "text"}, {"label": "Preferred Date", "type": "date", "required": true}, {"label": "Notes", "type": "textarea", "placeholder": "Any specific topics you'd like to cover?"}], "submit_text": "Request Demo"}}
101
+
102
+ User: "What is AI?"
103
+ Response: {"text": "AI (Artificial Intelligence) refers to computer systems designed to perform tasks that typically require human intelligence, such as learning, reasoning, problem-solving, and understanding language."}
104
+
105
+ User: "Collect my contact details"
106
+ Response: {"component": "DynamicForm", "props": {"title": "Contact Details", "fields": [{"label": "Name", "type": "text", "required": true}, {"label": "Email", "type": "email", "required": true}, {"label": "Phone", "type": "tel"}], "submit_text": "Save Details"}}
107
+
108
+ IMPORTANT:
109
+ - Use {"text": "..."} for questions, explanations, and general conversation
110
+ - Show a DynamicForm when user wants to provide information, schedule, book, or sign up
111
+ - Create contextually appropriate form fields based on what the user is trying to do
112
+ - Keep forms focused with only the relevant fields needed`,
113
+ previousMessages: "{{messages}}"
114
+ }
115
+ }
116
+ ]
117
+ };
118
+
119
+ // src/flows/shopping-assistant.ts
120
+ var SHOPPING_ASSISTANT_FLOW = {
121
+ name: "Shopping Assistant Flow",
122
+ description: "Returns JSON actions for page interaction",
123
+ steps: [
124
+ {
125
+ id: "action_prompt",
126
+ name: "Action Prompt",
127
+ type: "prompt",
128
+ enabled: true,
129
+ config: {
130
+ model: "qwen/qwen3-8b",
131
+ reasoning: false,
132
+ responseFormat: "JSON",
133
+ outputVariable: "prompt_result",
134
+ userPrompt: "{{user_message}}",
135
+ systemPrompt: `You are a helpful shopping assistant that can interact with web pages.
136
+ You will receive information about the current page's elements (class names and text content)
137
+ and user messages. You must respond with JSON in one of these formats:
138
+
139
+ 1. Simple message:
140
+ {
141
+ "action": "message",
142
+ "text": "Your response text here"
143
+ }
144
+
145
+ 2. Navigate then show message (for navigation to another page):
146
+ {
147
+ "action": "nav_then_click",
148
+ "page": "http://site.com/page-url",
149
+ "on_load_text": "Message to show after navigation"
150
+ }
151
+
152
+ 3. Show message and click an element:
153
+ {
154
+ "action": "message_and_click",
155
+ "element": ".className-of-element",
156
+ "text": "Your message text"
157
+ }
158
+
159
+ 4. Create Stripe checkout:
160
+ {
161
+ "action": "checkout",
162
+ "text": "Your message text",
163
+ "items": [
164
+ {"name": "Product Name", "price": 2999, "quantity": 1}
165
+ ]
166
+ }
167
+
168
+ Guidelines:
169
+ - Use "message" for simple conversational responses
170
+ - Use "nav_then_click" when you need to navigate to a different page (like a product detail page)
171
+ - Use "message_and_click" when you want to click a button or element on the current page
172
+ - Use "checkout" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)
173
+ - When selecting elements, use the class names provided in the page context
174
+ - Always respond with valid JSON only, no additional text
175
+ - For product searches, format results as markdown links: [Product Name](url)
176
+ - Be helpful and conversational in your messages
177
+ - Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)
178
+
179
+ Example conversation flow:
180
+ - User: "I am looking for a black shirt in medium"
181
+ - You: {"action": "message", "text": "Here are the products I found:\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\n\\nWould you like me to navigate to the first result and add it to your cart?"}
182
+
183
+ - User: "No, I would like to add another shirt to the cart"
184
+ - You: {"action": "message_and_click", "element": ".AddToCartButton-blue-shirt-large", "text": "I've added the Blue Shirt - Large to your cart. Ready to checkout?"}
185
+
186
+ - User: "yes"
187
+ - You: {"action": "checkout", "text": "Perfect! I'll set up the checkout for you.", "items": [{"name": "Black Shirt - Medium", "price": 2999, "quantity": 1}]}`,
188
+ previousMessages: "{{messages}}"
189
+ }
190
+ }
191
+ ]
192
+ };
193
+ var SHOPPING_ASSISTANT_METADATA_FLOW = {
194
+ name: "Metadata-Based Shopping Assistant",
195
+ description: "Uses DOM context from record metadata for page interaction",
196
+ steps: [
197
+ {
198
+ id: "metadata_action_prompt",
199
+ name: "Metadata Action Prompt",
200
+ type: "prompt",
201
+ enabled: true,
202
+ config: {
203
+ model: "qwen/qwen3-8b",
204
+ reasoning: false,
205
+ responseFormat: "JSON",
206
+ outputVariable: "prompt_result",
207
+ userPrompt: "{{user_message}}",
208
+ systemPrompt: `You are a helpful shopping assistant that can interact with web pages.
209
+
210
+ IMPORTANT: You have access to the current page's DOM elements through the record metadata, which includes:
211
+ - dom_elements: Array of page elements with className, innerText, and tagName
212
+ - dom_body: Complete HTML body of the page (if provided)
213
+ - page_url: Current page URL
214
+ - page_title: Page title
215
+
216
+ The dom_elements array provides information about clickable elements and their text content.
217
+ Use this metadata to understand what's available on the page and help users interact with it.
218
+
219
+ You must respond with JSON in one of these formats:
220
+
221
+ 1. Simple message:
222
+ {
223
+ "action": "message",
224
+ "text": "Your response text here"
225
+ }
226
+
227
+ 2. Navigate then show message (for navigation to another page):
228
+ {
229
+ "action": "nav_then_click",
230
+ "page": "http://site.com/page-url",
231
+ "on_load_text": "Message to show after navigation"
232
+ }
233
+
234
+ 3. Show message and click an element:
235
+ {
236
+ "action": "message_and_click",
237
+ "element": ".className-of-element",
238
+ "text": "Your message text"
239
+ }
240
+
241
+ 4. Create Stripe checkout:
242
+ {
243
+ "action": "checkout",
244
+ "text": "Your message text",
245
+ "items": [
246
+ {"name": "Product Name", "price": 2999, "quantity": 1}
247
+ ]
248
+ }
249
+
250
+ Guidelines:
251
+ - Use "message" for simple conversational responses
252
+ - Use "nav_then_click" when you need to navigate to a different page (like a product detail page)
253
+ - Use "message_and_click" when you want to click a button or element on the current page
254
+ - Use "checkout" when the user wants to proceed to checkout/payment. Include items array with name (string), price (number in cents), and quantity (number)
255
+ - When selecting elements, use the class names from the dom_elements in the metadata
256
+ - Always respond with valid JSON only, no additional text
257
+ - For product searches, format results as markdown links: [Product Name](url)
258
+ - Be helpful and conversational in your messages
259
+ - Product prices: Black Shirt - Medium: $29.99 (2999 cents), Blue Shirt - Large: $34.99 (3499 cents), Red T-Shirt - Small: $19.99 (1999 cents), Jeans - Medium: $49.99 (4999 cents)
260
+
261
+ Example conversation flow:
262
+ - User: "I am looking for a black shirt in medium"
263
+ - You: {"action": "message", "text": "Here are the products I found:\\n1. [Black Shirt - Medium](/products.html?product=black-shirt-medium) - $29.99\\n2. [Blue Shirt - Large](/products.html?product=blue-shirt-large) - $34.99\\n3. [Red T-Shirt - Small](/products.html?product=red-tshirt-small) - $19.99\\n4. [Jeans - Medium](/products.html?product=jeans-medium) - $49.99\\n\\nWould you like me to navigate to the first result and add it to your cart?"}
264
+
265
+ - User: "No, I would like to add another shirt to the cart"
266
+ - You: {"action": "message_and_click", "element": ".AddToCartButton-blue-shirt-large", "text": "I've added the Blue Shirt - Large to your cart. Ready to checkout?"}
267
+
268
+ - User: "yes"
269
+ - You: {"action": "checkout", "text": "Perfect! I'll set up the checkout for you.", "items": [{"name": "Black Shirt - Medium", "price": 2999, "quantity": 1}]}`,
270
+ previousMessages: "{{messages}}"
271
+ }
272
+ }
273
+ ]
274
+ };
275
+
276
+ // src/flows/components.ts
277
+ var COMPONENT_FLOW = {
278
+ name: "Component Flow",
279
+ description: "Flow configured for custom component rendering",
280
+ steps: [
281
+ {
282
+ id: "component_prompt",
283
+ name: "Component Prompt",
284
+ type: "prompt",
285
+ enabled: true,
286
+ config: {
287
+ model: "qwen/qwen3-8b",
288
+ reasoning: false,
289
+ responseFormat: "JSON",
290
+ outputVariable: "prompt_result",
291
+ userPrompt: "{{user_message}}",
292
+ systemPrompt: `You are a helpful assistant that can both have conversations and render custom UI components.
293
+
294
+ RESPONSE FORMAT:
295
+ Always respond with valid JSON. Choose the appropriate format based on the user's request:
296
+
297
+ 1. For CONVERSATIONAL questions or text responses:
298
+ {"text": "Your response here"}
299
+
300
+ 2. For VISUAL DISPLAYS or when the user asks to SHOW/DISPLAY something:
301
+ {"component": "ComponentName", "props": {...}}
302
+
303
+ 3. For BOTH explanation AND visual:
304
+ {"text": "Your explanation here", "component": "ComponentName", "props": {...}}
305
+
306
+ Available components for visual displays:
307
+ - ProductCard: Display product information. Props: title (string), price (number), description (string, optional), image (string, optional)
308
+ - SimpleChart: Display a bar chart. Props: title (string), data (array of numbers), labels (array of strings, optional)
309
+ - StatusBadge: Display a status badge. Props: status (string: "success", "error", "warning", "info", "pending"), message (string)
310
+ - InfoCard: Display an information card. Props: title (string), content (string), icon (string, optional)
311
+
312
+ Examples:
313
+ - User asks "What is the capital of France?": {"text": "The capital of France is Paris."}
314
+ - User asks "What does that chart show?": {"text": "The chart shows sales data increasing from 100 to 200 over three months."}
315
+ - User asks "Show me a product card": {"component": "ProductCard", "props": {"title": "Laptop", "price": 999, "description": "A great laptop"}}
316
+ - User asks "Display a chart": {"component": "SimpleChart", "props": {"title": "Sales", "data": [100, 150, 200], "labels": ["Jan", "Feb", "Mar"]}}
317
+ - User asks "Show me a chart and explain it": {"text": "Here's the sales data for Q1:", "component": "SimpleChart", "props": {"title": "Q1 Sales", "data": [100, 150, 200], "labels": ["Jan", "Feb", "Mar"]}}
318
+
319
+ IMPORTANT:
320
+ - Use {"text": "..."} for questions, explanations, discussions, and general chat
321
+ - Use {"component": "...", "props": {...}} ONLY when the user explicitly wants to SEE/VIEW/DISPLAY visual content
322
+ - You can combine both: {"text": "...", "component": "...", "props": {...}} when you want to explain something AND show a visual
323
+ - Never force a component when the user just wants information`,
324
+ previousMessages: "{{messages}}"
325
+ }
326
+ }
327
+ ]
328
+ };
329
+
330
+ // src/utils/stripe.ts
331
+ async function createCheckoutSession(options) {
332
+ const { secretKey, items, successUrl, cancelUrl } = options;
333
+ try {
334
+ if (!items || !Array.isArray(items) || items.length === 0) {
335
+ return {
336
+ success: false,
337
+ error: "Items array is required"
338
+ };
339
+ }
340
+ for (const item of items) {
341
+ if (!item.name || typeof item.price !== "number" || typeof item.quantity !== "number") {
342
+ return {
343
+ success: false,
344
+ error: "Each item must have name (string), price (number in cents), and quantity (number)"
345
+ };
346
+ }
347
+ }
348
+ const lineItems = items.map((item) => ({
349
+ price_data: {
350
+ currency: "usd",
351
+ product_data: {
352
+ name: item.name
353
+ },
354
+ unit_amount: item.price
355
+ },
356
+ quantity: item.quantity
357
+ }));
358
+ const params = new URLSearchParams({
359
+ "payment_method_types[0]": "card",
360
+ "mode": "payment",
361
+ "success_url": successUrl,
362
+ "cancel_url": cancelUrl
363
+ });
364
+ lineItems.forEach((item, index) => {
365
+ params.append(`line_items[${index}][price_data][currency]`, item.price_data.currency);
366
+ params.append(`line_items[${index}][price_data][product_data][name]`, item.price_data.product_data.name);
367
+ params.append(`line_items[${index}][price_data][unit_amount]`, item.price_data.unit_amount.toString());
368
+ params.append(`line_items[${index}][quantity]`, item.quantity.toString());
369
+ });
370
+ const stripeResponse = await fetch("https://api.stripe.com/v1/checkout/sessions", {
371
+ method: "POST",
372
+ headers: {
373
+ "Authorization": `Bearer ${secretKey}`,
374
+ "Content-Type": "application/x-www-form-urlencoded"
375
+ },
376
+ body: params
377
+ });
378
+ if (!stripeResponse.ok) {
379
+ const errorData = await stripeResponse.text();
380
+ console.error("Stripe API error:", errorData);
381
+ return {
382
+ success: false,
383
+ error: "Failed to create checkout session"
384
+ };
385
+ }
386
+ const session = await stripeResponse.json();
387
+ return {
388
+ success: true,
389
+ checkoutUrl: session.url,
390
+ sessionId: session.id
391
+ };
392
+ } catch (error) {
393
+ console.error("Stripe checkout error:", error);
394
+ return {
395
+ success: false,
396
+ error: error instanceof Error ? error.message : "Failed to create checkout session"
397
+ };
398
+ }
399
+ }
400
+
401
+ // src/index.ts
402
+ var DEFAULT_ENDPOINT = "https://api.travrse.ai/v1/dispatch";
403
+ var DEFAULT_PATH = "/api/chat/dispatch";
404
+ var DEFAULT_FLOW = {
405
+ name: "Streaming Prompt Flow",
406
+ description: "Streaming chat generated by the widget",
407
+ steps: [
408
+ {
409
+ id: "widget_prompt",
410
+ name: "Prompt",
411
+ type: "prompt",
412
+ enabled: true,
413
+ config: {
414
+ model: "gemini-2.5-flash",
415
+ // model: "gpt-4o",
416
+ response_format: "markdown",
417
+ output_variable: "prompt_result",
418
+ user_prompt: "{{user_message}}",
419
+ system_prompt: "you are a helpful assistant, chatting with a user",
420
+ // tools: {
421
+ // tool_ids: [
422
+ // "builtin:dalle"
423
+ // ]
424
+ // },
425
+ previous_messages: "{{messages}}"
426
+ }
427
+ }
428
+ ]
429
+ };
430
+ var withCors = (allowedOrigins) => async (c, next) => {
431
+ var _a;
432
+ const origin = c.req.header("origin");
433
+ const isDevelopment = process.env.NODE_ENV === "development" || !process.env.NODE_ENV;
434
+ let corsOrigin;
435
+ if (!allowedOrigins || allowedOrigins.length === 0) {
436
+ corsOrigin = origin || "*";
437
+ } else if (allowedOrigins.includes(origin || "")) {
438
+ corsOrigin = origin || "*";
439
+ } else if (isDevelopment && origin) {
440
+ corsOrigin = origin;
441
+ } else {
442
+ if (c.req.method === "OPTIONS") {
443
+ return c.json({ error: "CORS policy violation: origin not allowed" }, 403);
444
+ }
445
+ await next();
446
+ return;
447
+ }
448
+ const headers = {
449
+ "Access-Control-Allow-Origin": corsOrigin,
450
+ "Access-Control-Allow-Headers": (_a = c.req.header("access-control-request-headers")) != null ? _a : "Content-Type, Authorization",
451
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
452
+ Vary: "Origin"
453
+ };
454
+ if (c.req.method === "OPTIONS") {
455
+ return new Response(null, { status: 204, headers });
456
+ }
457
+ await next();
458
+ Object.entries(headers).forEach(
459
+ ([key, value]) => c.header(key, value, { append: false })
460
+ );
461
+ };
462
+ var createChatProxyApp = (options = {}) => {
463
+ var _a, _b, _c;
464
+ const app = new import_hono.Hono();
465
+ const path = (_a = options.path) != null ? _a : DEFAULT_PATH;
466
+ const feedbackPath = (_b = options.feedbackPath) != null ? _b : "/api/feedback";
467
+ const upstream = (_c = options.upstreamUrl) != null ? _c : DEFAULT_ENDPOINT;
468
+ app.use("*", withCors(options.allowedOrigins));
469
+ app.post(feedbackPath, async (c) => {
470
+ var _a2, _b2, _c2;
471
+ let payload;
472
+ try {
473
+ payload = await c.req.json();
474
+ } catch (error) {
475
+ return c.json({ error: "Invalid JSON body" }, 400);
476
+ }
477
+ if (!payload.type || !["upvote", "downvote"].includes(payload.type)) {
478
+ return c.json(
479
+ { error: "Invalid feedback type. Must be 'upvote' or 'downvote'" },
480
+ 400
481
+ );
482
+ }
483
+ if (!payload.messageId) {
484
+ return c.json({ error: "Missing messageId" }, 400);
485
+ }
486
+ payload.timestamp = (_a2 = payload.timestamp) != null ? _a2 : (/* @__PURE__ */ new Date()).toISOString();
487
+ const isDevelopment = process.env.NODE_ENV === "development" || !process.env.NODE_ENV;
488
+ if (isDevelopment) {
489
+ console.log("\n=== Feedback Received ===");
490
+ console.log("Type:", payload.type);
491
+ console.log("Message ID:", payload.messageId);
492
+ console.log(
493
+ "Content Preview:",
494
+ (_c2 = (_b2 = payload.content) == null ? void 0 : _b2.substring(0, 100)) != null ? _c2 : "(none)"
495
+ );
496
+ console.log("Timestamp:", payload.timestamp);
497
+ console.log("=== End Feedback ===\n");
498
+ }
499
+ if (options.onFeedback) {
500
+ try {
501
+ await options.onFeedback(payload);
502
+ } catch (error) {
503
+ console.error("[Feedback] Handler error:", error);
504
+ return c.json({ error: "Feedback handler failed" }, 500);
505
+ }
506
+ }
507
+ return c.json({
508
+ success: true,
509
+ message: "Feedback recorded",
510
+ feedback: {
511
+ type: payload.type,
512
+ messageId: payload.messageId,
513
+ timestamp: payload.timestamp
514
+ }
515
+ });
516
+ });
517
+ app.post(path, async (c) => {
518
+ var _a2, _b2, _c2, _d, _e;
519
+ const apiKey = (_a2 = options.apiKey) != null ? _a2 : process.env.TRAVRSE_API_KEY;
520
+ if (!apiKey) {
521
+ return c.json(
522
+ { error: "Missing API key. Set TRAVRSE_API_KEY." },
523
+ 401
524
+ );
525
+ }
526
+ let clientPayload;
527
+ try {
528
+ clientPayload = await c.req.json();
529
+ } catch (error) {
530
+ return c.json(
531
+ { error: "Invalid JSON body", details: error },
532
+ 400
533
+ );
534
+ }
535
+ const messages = (_b2 = clientPayload.messages) != null ? _b2 : [];
536
+ const sortedMessages = [...messages].sort((a, b) => {
537
+ const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
538
+ const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
539
+ return timeA - timeB;
540
+ });
541
+ const formattedMessages = sortedMessages.map((message) => ({
542
+ role: message.role,
543
+ content: message.content
544
+ }));
545
+ const flowId = (_c2 = clientPayload.flowId) != null ? _c2 : options.flowId;
546
+ const flowConfig = (_d = options.flowConfig) != null ? _d : DEFAULT_FLOW;
547
+ const travrsePayload = {
548
+ record: {
549
+ name: "Streaming Chat Widget",
550
+ type: "standalone",
551
+ metadata: clientPayload.metadata || {}
552
+ },
553
+ messages: formattedMessages,
554
+ options: {
555
+ stream_response: true,
556
+ record_mode: "virtual",
557
+ flow_mode: flowId ? "existing" : "virtual",
558
+ auto_append_metadata: false
559
+ }
560
+ };
561
+ if (flowId) {
562
+ travrsePayload.flow = {
563
+ id: flowId
564
+ };
565
+ } else {
566
+ travrsePayload.flow = flowConfig;
567
+ }
568
+ const isDevelopment = process.env.NODE_ENV === "development" || !process.env.NODE_ENV;
569
+ if (isDevelopment) {
570
+ console.log("\n=== Travrse Proxy Request ===");
571
+ console.log("URL:", upstream);
572
+ console.log("API Key Used:", apiKey ? "Yes" : "No");
573
+ console.log("API Key (first 12 chars):", apiKey ? apiKey.substring(0, 12) : "N/A");
574
+ console.log("Request Payload:", JSON.stringify(travrsePayload, null, 2));
575
+ }
576
+ const response = await fetch(upstream, {
577
+ method: "POST",
578
+ headers: {
579
+ Authorization: `Bearer ${apiKey}`,
580
+ "Content-Type": "application/json"
581
+ },
582
+ body: JSON.stringify(travrsePayload)
583
+ });
584
+ if (isDevelopment) {
585
+ console.log("Response Status:", response.status);
586
+ console.log("Response Status Text:", response.statusText);
587
+ if (!response.ok) {
588
+ const clonedResponse = response.clone();
589
+ try {
590
+ const errorBody = await clonedResponse.text();
591
+ console.log("Error Response Body:", errorBody);
592
+ } catch (e) {
593
+ console.log("Could not read error response body:", e);
594
+ }
595
+ }
596
+ console.log("=== End Travrse Proxy Request ===\n");
597
+ }
598
+ return new Response(response.body, {
599
+ status: response.status,
600
+ headers: {
601
+ "Content-Type": (_e = response.headers.get("content-type")) != null ? _e : "application/json",
602
+ "Cache-Control": "no-store"
603
+ }
604
+ });
605
+ });
606
+ return app;
607
+ };
608
+ var createVercelHandler = (options) => (0, import_vercel.handle)(createChatProxyApp(options));
609
+ var index_default = createChatProxyApp;
610
+ // Annotate the CommonJS export names for ESM import in node:
611
+ 0 && (module.exports = {
612
+ COMPONENT_FLOW,
613
+ CONVERSATIONAL_FLOW,
614
+ FORM_DIRECTIVE_FLOW,
615
+ SHOPPING_ASSISTANT_FLOW,
616
+ SHOPPING_ASSISTANT_METADATA_FLOW,
617
+ createChatProxyApp,
618
+ createCheckoutSession,
619
+ createVercelHandler
620
+ });
621
+ //# sourceMappingURL=index.cjs.map