-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
123 lines (115 loc) · 3.15 KB
/
logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const weavelApiKey = document.currentScript.getAttribute("api-key");
const LOCAL_STORAGE_PREFIX = "@weavel/";
const generateUUID = () => {
const s4 = () =>
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
};
const getStorageItem = (key) =>
localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${key}`);
function setStorageItem(key, value) {
localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${key}`, value);
}
function createTrace() {
const traceUUID = generateUUID();
setStorageItem("traceUUID", traceUUID);
setStorageItem("loggedMessages", 0);
return traceUUID;
}
function logMessage({
userId,
traceUUID,
traceDataId,
role,
content,
timestamp,
}) {
if (!weavelApiKey) {
console.error("Weavel API key is not set.");
return;
}
fetch("https://api.weavel.ai/capture/trace_data", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${weavelApiKey}`,
},
body: JSON.stringify({
user_id: userId,
trace_id: traceUUID,
trace_data_id: traceDataId,
role,
content,
timestamp,
}),
});
}
function parseMessages(messages) {
let content = "";
messages.forEach((message, i) => {
switch (message.type) {
case "text":
message.text.forEach((text) => {
text.children.forEach((child) => {
content += child.text;
});
content += "\n";
});
break;
case "image":
content += "Image\n";
content += `URL: ${message.url}\n`;
break;
default:
content += message.type;
Object.keys(message).forEach((key) => {
if (key === "type") return;
content += `${key}: ${message[key]}\n`;
});
break;
}
if (i < messages.length - 1) content += "\n";
});
return content;
}
window.addEventListener("message", (event) => {
try {
if (typeof event.data !== "string") return;
const data = JSON.parse(event.data);
if ("type" in data) {
const eventName = data.type.split("voiceflow:")[1];
if (eventName === "interact") {
let traceUUID = getStorageItem("traceUUID");
if (data.payload.action.type === "launch") {
traceUUID = createTrace();
}
const userId = data.payload.session.userID;
const allMessages = data.payload.session.turns;
const messagesToLog = allMessages.slice(
getStorageItem("loggedMessages") || 0
);
messagesToLog.forEach((msg) => {
let content;
if (msg.message) {
content = msg.message;
} else if (msg.messages) {
content = parseMessages(msg.messages);
}
logMessage({
userId,
traceUUID,
traceDataId: msg.id,
role: msg.type,
content,
timestamp: new Date(msg.timestamp).toISOString(),
});
});
setStorageItem("loggedMessages", allMessages.length);
}
}
} catch (error) {
console.log("Error parsing message", error, event.data);
}
});