Delete monetano.js
Browse files- monetano.js +0 -1452
monetano.js
DELETED
@@ -1,1452 +0,0 @@
|
|
1 |
-
"use strict";
|
2 |
-
(() => {
|
3 |
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
4 |
-
var __esm = (fn, res) => function __init() {
|
5 |
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
6 |
-
};
|
7 |
-
var __commonJS = (cb, mod) => function __require() {
|
8 |
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
9 |
-
};
|
10 |
-
|
11 |
-
// src/utils.ts
|
12 |
-
var getBidForUnit, renderAd, getAdsForUnit, serverAuction, markImpressionAsViewed, markImpressionAsRendered, markImpressionAsErrored, markImpressionAsClicked, intialiseMonetanoObject;
|
13 |
-
var init_utils = __esm({
|
14 |
-
"src/utils.ts"() {
|
15 |
-
"use strict";
|
16 |
-
getBidForUnit = async (adUnit, messages, bidder, params, timeout) => {
|
17 |
-
const bidPromise = bidder.getBid(messages, adUnit, adUnit.params, params);
|
18 |
-
const timeoutPromise = new Promise(
|
19 |
-
(resolve) => setTimeout(
|
20 |
-
() => resolve({
|
21 |
-
errorReason: "Bid timeout",
|
22 |
-
bidder: bidder.name,
|
23 |
-
outcome: "failed",
|
24 |
-
advertiserToken: bidder.advertiserToken
|
25 |
-
}),
|
26 |
-
timeout
|
27 |
-
)
|
28 |
-
);
|
29 |
-
const bid = await Promise.race([bidPromise, timeoutPromise]).catch(
|
30 |
-
(error) => {
|
31 |
-
return {
|
32 |
-
errorReason: error.message,
|
33 |
-
bidder: bidder.name,
|
34 |
-
outcome: "failed",
|
35 |
-
advertiserToken: bidder.advertiserToken
|
36 |
-
};
|
37 |
-
}
|
38 |
-
);
|
39 |
-
return bid;
|
40 |
-
};
|
41 |
-
renderAd = async (monetano, impressionId, adUnit, winningBid, options) => {
|
42 |
-
try {
|
43 |
-
console.log("[renderAd] (adUnit.code)", adUnit.code);
|
44 |
-
const adUnitDiv = document.getElementById(adUnit.code);
|
45 |
-
const innerElement = document.createElement("div");
|
46 |
-
innerElement.classList.add("monetano-ad-container");
|
47 |
-
adUnitDiv?.replaceChildren(innerElement);
|
48 |
-
if (!adUnitDiv) {
|
49 |
-
monetano.log.error("Ad unit not found", { adUnit });
|
50 |
-
return;
|
51 |
-
}
|
52 |
-
adUnitDiv.addEventListener("click", () => {
|
53 |
-
options.onClick?.();
|
54 |
-
markImpressionAsClicked(monetano, impressionId).catch((error) => {
|
55 |
-
monetano.log.error("Failed to mark impression as clicked", { error });
|
56 |
-
});
|
57 |
-
});
|
58 |
-
const bidder = monetano._bidders.find((b) => b.name === winningBid.bidder);
|
59 |
-
await bidder?.renderAd(winningBid, innerElement);
|
60 |
-
if (!innerElement.textContent) {
|
61 |
-
markImpressionAsErrored(monetano, impressionId, "No content rendered").catch(
|
62 |
-
(error) => {
|
63 |
-
monetano.log.error("Failed to mark impression as errored", { error });
|
64 |
-
}
|
65 |
-
);
|
66 |
-
return;
|
67 |
-
}
|
68 |
-
options.onRender?.();
|
69 |
-
markImpressionAsRendered(monetano, impressionId, innerElement.textContent).catch((error) => {
|
70 |
-
monetano.log.error("Failed to mark impression as rendered", { error });
|
71 |
-
});
|
72 |
-
if (typeof window.IntersectionObserver === "undefined") {
|
73 |
-
options.onView?.();
|
74 |
-
markImpressionAsViewed(monetano, impressionId).catch((error) => {
|
75 |
-
monetano.log.error("Failed to mark impression as viewed", { error });
|
76 |
-
});
|
77 |
-
}
|
78 |
-
const observer = new window.IntersectionObserver((entries, observer2) => {
|
79 |
-
entries.forEach((entry) => {
|
80 |
-
if (entry.isIntersecting && innerElement.innerHTML.length > 0) {
|
81 |
-
options.onView?.();
|
82 |
-
markImpressionAsViewed(monetano, impressionId).catch((error) => {
|
83 |
-
monetano.log.error("Failed to mark impression as viewed", {
|
84 |
-
error
|
85 |
-
});
|
86 |
-
});
|
87 |
-
observer2.unobserve(entry.target);
|
88 |
-
}
|
89 |
-
});
|
90 |
-
});
|
91 |
-
observer.observe(innerElement);
|
92 |
-
} catch (error) {
|
93 |
-
markImpressionAsErrored(monetano, impressionId, error.message).catch(
|
94 |
-
(error2) => {
|
95 |
-
monetano.log.error("Failed to mark impression as errored", { error: error2 });
|
96 |
-
}
|
97 |
-
);
|
98 |
-
}
|
99 |
-
};
|
100 |
-
getAdsForUnit = async (monetano, adUnit, messages, params, options, timeout) => {
|
101 |
-
const bidderNames = adUnit.bidders;
|
102 |
-
const bidders = bidderNames.map((bidder) => monetano._bidders.find((b) => b.name === bidder)).filter((b) => b !== void 0);
|
103 |
-
const bids = await Promise.all(
|
104 |
-
bidders.map(async (bidder) => {
|
105 |
-
const bid = await getBidForUnit(
|
106 |
-
adUnit,
|
107 |
-
messages,
|
108 |
-
bidder,
|
109 |
-
params,
|
110 |
-
timeout
|
111 |
-
);
|
112 |
-
return bid;
|
113 |
-
})
|
114 |
-
);
|
115 |
-
const adjustedBids = options.onBids ? options.onBids(bids) : bids;
|
116 |
-
const { impressionId, winner } = await serverAuction(
|
117 |
-
monetano,
|
118 |
-
adUnit,
|
119 |
-
messages,
|
120 |
-
adjustedBids
|
121 |
-
);
|
122 |
-
if (winner) {
|
123 |
-
options.onWinner?.(winner);
|
124 |
-
await renderAd(monetano, impressionId, adUnit, winner, options);
|
125 |
-
}
|
126 |
-
};
|
127 |
-
serverAuction = async (monetano, adUnit, messages, bids) => {
|
128 |
-
const url = monetano.settings.url;
|
129 |
-
const response = await fetch(`${url}/impression`, {
|
130 |
-
method: "POST",
|
131 |
-
body: JSON.stringify({
|
132 |
-
adUnit,
|
133 |
-
messages,
|
134 |
-
bids,
|
135 |
-
publisherToken: monetano.settings.publisherToken
|
136 |
-
})
|
137 |
-
});
|
138 |
-
const data = await response.json();
|
139 |
-
return data;
|
140 |
-
};
|
141 |
-
markImpressionAsViewed = async (monetano, id) => {
|
142 |
-
const url = monetano.settings.url;
|
143 |
-
const response = await fetch(`${url}/impression/${id}/view`, {
|
144 |
-
method: "POST"
|
145 |
-
});
|
146 |
-
if (!response.ok) {
|
147 |
-
throw new Error("Failed to mark impression as viewed", {
|
148 |
-
cause: response.status
|
149 |
-
});
|
150 |
-
}
|
151 |
-
};
|
152 |
-
markImpressionAsRendered = async (monetano, id, content) => {
|
153 |
-
const url = monetano.settings.url;
|
154 |
-
const response = await fetch(`${url}/impression/${id}/render`, {
|
155 |
-
method: "POST",
|
156 |
-
body: JSON.stringify({ content })
|
157 |
-
});
|
158 |
-
if (!response.ok) {
|
159 |
-
throw new Error("Failed to mark impression as rendered", {
|
160 |
-
cause: response.status
|
161 |
-
});
|
162 |
-
}
|
163 |
-
};
|
164 |
-
markImpressionAsErrored = async (monetano, id, errorReason) => {
|
165 |
-
const url = monetano.settings.url;
|
166 |
-
const response = await fetch(`${url}/impression/${id}/error`, {
|
167 |
-
method: "POST",
|
168 |
-
body: JSON.stringify({ errorReason })
|
169 |
-
});
|
170 |
-
};
|
171 |
-
markImpressionAsClicked = async (monetano, id) => {
|
172 |
-
const url = monetano.settings.url;
|
173 |
-
const response = await fetch(`${url}/impression/${id}/click`, {
|
174 |
-
method: "POST"
|
175 |
-
});
|
176 |
-
if (!response.ok) {
|
177 |
-
throw new Error("Failed to mark impression as clicked", {
|
178 |
-
cause: response.status
|
179 |
-
});
|
180 |
-
}
|
181 |
-
};
|
182 |
-
intialiseMonetanoObject = (monetano) => {
|
183 |
-
const allBidderNames = new Set(
|
184 |
-
monetano.settings.adUnits.flatMap((adUnit) => adUnit.bidders)
|
185 |
-
);
|
186 |
-
for (const bidderName of allBidderNames) {
|
187 |
-
const bidderFactory = monetano._publisherBidderFactories[bidderName];
|
188 |
-
if (!bidderFactory) {
|
189 |
-
throw new Error(`Bidder ${bidderName} not included in bundle.`);
|
190 |
-
}
|
191 |
-
const bidder = bidderFactory();
|
192 |
-
monetano._bidders.push(bidder);
|
193 |
-
}
|
194 |
-
};
|
195 |
-
}
|
196 |
-
});
|
197 |
-
|
198 |
-
// src/log.ts
|
199 |
-
var Logger, log, log_default;
|
200 |
-
var init_log = __esm({
|
201 |
-
"src/log.ts"() {
|
202 |
-
"use strict";
|
203 |
-
Logger = class {
|
204 |
-
localLevel = "log";
|
205 |
-
remoteLevel = "error";
|
206 |
-
remoteConfig = null;
|
207 |
-
levels = {
|
208 |
-
debug: 0,
|
209 |
-
info: 1,
|
210 |
-
log: 2,
|
211 |
-
warn: 3,
|
212 |
-
error: 4,
|
213 |
-
silent: 5
|
214 |
-
};
|
215 |
-
setLocalLevel(level) {
|
216 |
-
this.localLevel = level;
|
217 |
-
}
|
218 |
-
setRemoteLevel(level) {
|
219 |
-
this.remoteLevel = level;
|
220 |
-
}
|
221 |
-
configureRemote(url, params) {
|
222 |
-
this.remoteConfig = { url, params };
|
223 |
-
}
|
224 |
-
shouldLog(level, targetLevel) {
|
225 |
-
if (targetLevel === "silent") {
|
226 |
-
return false;
|
227 |
-
}
|
228 |
-
return this.levels[level] >= this.levels[targetLevel];
|
229 |
-
}
|
230 |
-
logToConsole(level, ...args) {
|
231 |
-
if (this.shouldLog(level, this.localLevel)) {
|
232 |
-
if (level === "silent") {
|
233 |
-
return;
|
234 |
-
}
|
235 |
-
console[level](...args);
|
236 |
-
}
|
237 |
-
}
|
238 |
-
logToRemote(level, ...args) {
|
239 |
-
if (this.remoteConfig && this.shouldLog(level, this.remoteLevel)) {
|
240 |
-
fetch(`${this.remoteConfig.url}/log`, {
|
241 |
-
method: "POST",
|
242 |
-
body: JSON.stringify({
|
243 |
-
...this.remoteConfig.params,
|
244 |
-
level,
|
245 |
-
message: args,
|
246 |
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
247 |
-
})
|
248 |
-
}).catch((e) => {
|
249 |
-
});
|
250 |
-
}
|
251 |
-
}
|
252 |
-
debug(...args) {
|
253 |
-
this.logToConsole("debug", ...args);
|
254 |
-
this.logToRemote("debug", ...args);
|
255 |
-
}
|
256 |
-
info(...args) {
|
257 |
-
this.logToConsole("info", ...args);
|
258 |
-
this.logToRemote("info", ...args);
|
259 |
-
}
|
260 |
-
log(...args) {
|
261 |
-
this.logToConsole("log", ...args);
|
262 |
-
this.logToRemote("log", ...args);
|
263 |
-
}
|
264 |
-
warn(...args) {
|
265 |
-
this.logToConsole("warn", ...args);
|
266 |
-
this.logToRemote("warn", ...args);
|
267 |
-
}
|
268 |
-
error(...args) {
|
269 |
-
this.logToConsole("error", ...args);
|
270 |
-
this.logToRemote("error", ...args);
|
271 |
-
}
|
272 |
-
};
|
273 |
-
log = new Logger();
|
274 |
-
log_default = log;
|
275 |
-
}
|
276 |
-
});
|
277 |
-
|
278 |
-
// src/monetano.ts
|
279 |
-
var createMonetano;
|
280 |
-
var init_monetano = __esm({
|
281 |
-
"src/monetano.ts"() {
|
282 |
-
"use strict";
|
283 |
-
init_utils();
|
284 |
-
init_log();
|
285 |
-
createMonetano = (queue, settings, publisherBidderFactories) => {
|
286 |
-
log_default.configureRemote(settings.url, {
|
287 |
-
publisherToken: settings.publisherToken
|
288 |
-
});
|
289 |
-
log_default.setLocalLevel(settings.localLogLevel || "log");
|
290 |
-
log_default.setRemoteLevel(settings.remoteLogLevel || "debug");
|
291 |
-
const monetano = {
|
292 |
-
que: queue,
|
293 |
-
settings,
|
294 |
-
log: log_default,
|
295 |
-
getAds: async (messages, params, options) => {
|
296 |
-
const adUnits = monetano.settings.adUnits;
|
297 |
-
try {
|
298 |
-
await Promise.all(
|
299 |
-
adUnits.map(async (adUnit) => {
|
300 |
-
const bids = await getAdsForUnit(
|
301 |
-
monetano,
|
302 |
-
adUnit,
|
303 |
-
messages,
|
304 |
-
params,
|
305 |
-
options,
|
306 |
-
settings.timeout
|
307 |
-
);
|
308 |
-
return bids;
|
309 |
-
})
|
310 |
-
);
|
311 |
-
} catch (error) {
|
312 |
-
options?.onError?.(error);
|
313 |
-
}
|
314 |
-
},
|
315 |
-
_bidders: [],
|
316 |
-
_publisherBidderFactories: publisherBidderFactories
|
317 |
-
};
|
318 |
-
const originalPush = monetano.que.push;
|
319 |
-
monetano.que.push = (fn) => {
|
320 |
-
originalPush.call(monetano.que, fn);
|
321 |
-
fn();
|
322 |
-
return monetano.que.length;
|
323 |
-
};
|
324 |
-
intialiseMonetanoObject(monetano);
|
325 |
-
return monetano;
|
326 |
-
};
|
327 |
-
}
|
328 |
-
});
|
329 |
-
|
330 |
-
// src/bidders/koah-bidder.ts
|
331 |
-
var KoahBidder, koah_bidder_default;
|
332 |
-
var init_koah_bidder = __esm({
|
333 |
-
"src/bidders/koah-bidder.ts"() {
|
334 |
-
"use strict";
|
335 |
-
KoahBidder = class {
|
336 |
-
name;
|
337 |
-
params;
|
338 |
-
advertiserToken;
|
339 |
-
renderStart = null;
|
340 |
-
messages;
|
341 |
-
constructor(params) {
|
342 |
-
this.messages = [];
|
343 |
-
this.name = params.bidderName;
|
344 |
-
this.params = params;
|
345 |
-
this.advertiserToken = params.advertiserToken;
|
346 |
-
const script = document.createElement("script");
|
347 |
-
script.src = `https://app.koah.ai/js?token=${this.params.koahPublisherId}`;
|
348 |
-
script.type = "module";
|
349 |
-
document.head.appendChild(script);
|
350 |
-
}
|
351 |
-
async getBid(messages, adUnit, params, getAdsParams) {
|
352 |
-
this.messages = messages;
|
353 |
-
const country = await fetch(this.params.countryEndpoint).then((res) => {
|
354 |
-
if (!res.ok) {
|
355 |
-
throw new Error(`Failed to fetch country: ${res.statusText}`);
|
356 |
-
} else {
|
357 |
-
return res.json();
|
358 |
-
}
|
359 |
-
});
|
360 |
-
country.countryCode = "US";
|
361 |
-
console.log("[DEV / KoahBidder] OVERRIDING countryCode", "US");
|
362 |
-
if (country.countryCode === "US") {
|
363 |
-
return {
|
364 |
-
advertiserToken: this.params.advertiserToken,
|
365 |
-
bidder: this.name,
|
366 |
-
price: 1,
|
367 |
-
outcome: "successful"
|
368 |
-
};
|
369 |
-
} else {
|
370 |
-
return {
|
371 |
-
advertiserToken: this.params.advertiserToken,
|
372 |
-
bidder: this.name,
|
373 |
-
price: 0,
|
374 |
-
outcome: "successful"
|
375 |
-
};
|
376 |
-
}
|
377 |
-
}
|
378 |
-
async renderAd(bid, element) {
|
379 |
-
const existingAds = document.querySelectorAll(".koah-ad");
|
380 |
-
existingAds.forEach((ad) => ad.remove());
|
381 |
-
element.classList.add("koah-ad");
|
382 |
-
const userMessage = this.messages.reverse().find(
|
383 |
-
(message) => message.role === "user"
|
384 |
-
);
|
385 |
-
const assistantMessage = this.messages.reverse().find(
|
386 |
-
(message) => message.role === "assistant"
|
387 |
-
);
|
388 |
-
if (userMessage && assistantMessage) {
|
389 |
-
const koah = window.koah;
|
390 |
-
if (koah) {
|
391 |
-
await koah.process(userMessage.content, assistantMessage.content, "suffix");
|
392 |
-
}
|
393 |
-
}
|
394 |
-
}
|
395 |
-
};
|
396 |
-
koah_bidder_default = KoahBidder;
|
397 |
-
}
|
398 |
-
});
|
399 |
-
|
400 |
-
// ../sdk-js/dist/index.mjs
|
401 |
-
function concatChunks(chunks, totalLength) {
|
402 |
-
const concatenatedChunks = new Uint8Array(totalLength);
|
403 |
-
let offset = 0;
|
404 |
-
for (const chunk of chunks) {
|
405 |
-
concatenatedChunks.set(chunk, offset);
|
406 |
-
offset += chunk.length;
|
407 |
-
}
|
408 |
-
chunks.length = 0;
|
409 |
-
return concatenatedChunks;
|
410 |
-
}
|
411 |
-
async function* readDataStream(reader, {
|
412 |
-
isAborted
|
413 |
-
} = {}) {
|
414 |
-
const decoder = new TextDecoder();
|
415 |
-
const chunks = [];
|
416 |
-
let totalLength = 0;
|
417 |
-
while (true) {
|
418 |
-
const { value } = await reader.read();
|
419 |
-
if (value) {
|
420 |
-
chunks.push(value);
|
421 |
-
totalLength += value.length;
|
422 |
-
if (value[value.length - 1] !== NEWLINE) {
|
423 |
-
continue;
|
424 |
-
}
|
425 |
-
}
|
426 |
-
if (chunks.length === 0) {
|
427 |
-
break;
|
428 |
-
}
|
429 |
-
const concatenatedChunks = concatChunks(chunks, totalLength);
|
430 |
-
totalLength = 0;
|
431 |
-
const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
|
432 |
-
for (const streamPart of streamParts2) {
|
433 |
-
yield streamPart;
|
434 |
-
}
|
435 |
-
if (isAborted?.()) {
|
436 |
-
reader.cancel();
|
437 |
-
break;
|
438 |
-
}
|
439 |
-
}
|
440 |
-
}
|
441 |
-
var version, UNRETRIABLE_ERRORS, fetchWithTimeout, fetchRetry, HTML_EM_CLASS, HTML_A_CLASS, convertThemedText, convertMarkdownLinks, DATE_REGEX, validateFetchAdSettings, textStreamPart, functionCallStreamPart, dataStreamPart, errorStreamPart, assistantMessageStreamPart, assistantControlDataStreamPart, dataMessageStreamPart, toolCallStreamPart, messageAnnotationsStreamPart, streamParts, streamPartsByCode, StreamStringPrefixes, validCodes, parseStreamPart, NEWLINE, Logger2, log2, DEFAULT_SERVER_URL, CONTAINER_CSS_CLASS, KontextKey, markAdAsViewed, fixUrl, fetchAd;
|
442 |
-
var init_dist = __esm({
|
443 |
-
"../sdk-js/dist/index.mjs"() {
|
444 |
-
"use strict";
|
445 |
-
version = "0.0.8";
|
446 |
-
UNRETRIABLE_ERRORS = [403, 429, 404];
|
447 |
-
fetchWithTimeout = async (input, init) => {
|
448 |
-
const { timeout = 16e3, ...rest } = init || {};
|
449 |
-
const controller = new AbortController();
|
450 |
-
const id = setTimeout(() => controller.abort(), timeout);
|
451 |
-
try {
|
452 |
-
const response = await fetch(input, {
|
453 |
-
...rest,
|
454 |
-
signal: controller.signal
|
455 |
-
});
|
456 |
-
return response;
|
457 |
-
} catch (err) {
|
458 |
-
if (controller.signal.aborted) {
|
459 |
-
throw new Error(`Fetch aborted after ${timeout}ms`);
|
460 |
-
}
|
461 |
-
throw err;
|
462 |
-
} finally {
|
463 |
-
clearTimeout(id);
|
464 |
-
}
|
465 |
-
};
|
466 |
-
fetchRetry = async (input, init, singleRequestTimeout, maxRetries, onRetry) => {
|
467 |
-
let retries = 0;
|
468 |
-
let response;
|
469 |
-
let lastError = null;
|
470 |
-
while (retries < maxRetries) {
|
471 |
-
try {
|
472 |
-
const requestInit = { ...init, timeout: singleRequestTimeout };
|
473 |
-
response = await fetchWithTimeout(input, requestInit);
|
474 |
-
if (UNRETRIABLE_ERRORS.includes(response.status)) {
|
475 |
-
throw new Error(`Unretriable error: ${response.statusText}`);
|
476 |
-
}
|
477 |
-
if (response.ok) {
|
478 |
-
return response;
|
479 |
-
} else {
|
480 |
-
if (response.status === 400) {
|
481 |
-
const body = await response.json();
|
482 |
-
throw new Error(`Validation error: ${JSON.stringify(body)}`);
|
483 |
-
}
|
484 |
-
throw new Error(`Failed with status ${response.status}`);
|
485 |
-
}
|
486 |
-
} catch (error) {
|
487 |
-
console.debug(`Retrying ${input} ${retries} times, error: ${error}`);
|
488 |
-
retries++;
|
489 |
-
lastError = error;
|
490 |
-
onRetry?.(error, retries);
|
491 |
-
}
|
492 |
-
}
|
493 |
-
throw lastError || new Error("Failed to fetch after multiple retries");
|
494 |
-
};
|
495 |
-
HTML_EM_CLASS = "kontext-em";
|
496 |
-
HTML_A_CLASS = "kontext-a";
|
497 |
-
convertThemedText = (text) => {
|
498 |
-
const regex = /\*(.*?)\*/gs;
|
499 |
-
return text.replace(
|
500 |
-
regex,
|
501 |
-
(match, themedText) => `<em class='${HTML_EM_CLASS}'>${themedText}</em>`
|
502 |
-
);
|
503 |
-
};
|
504 |
-
convertMarkdownLinks = (text) => {
|
505 |
-
const regex = /\[([^\]]+)\]\(([^)]+)\)/gs;
|
506 |
-
return text.replace(
|
507 |
-
regex,
|
508 |
-
(match, linkText, linkUrl) => `<a class='${HTML_A_CLASS}' href='${linkUrl}' target='_blank'>${linkText}</a>`
|
509 |
-
);
|
510 |
-
};
|
511 |
-
DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
512 |
-
validateFetchAdSettings = (settings) => {
|
513 |
-
if (!settings.serverUrl) {
|
514 |
-
throw new Error("Server URL is required.");
|
515 |
-
}
|
516 |
-
if (!settings.publisherToken) {
|
517 |
-
throw new Error("Publisher token is required.");
|
518 |
-
}
|
519 |
-
if (!settings.conversationId) {
|
520 |
-
throw new Error("Conversation ID is required.");
|
521 |
-
}
|
522 |
-
if (typeof settings.conversationId !== "string") {
|
523 |
-
throw new Error("Conversation ID must be a string.");
|
524 |
-
}
|
525 |
-
if (!settings.userId) {
|
526 |
-
throw new Error("User ID is required.");
|
527 |
-
}
|
528 |
-
if (typeof settings.userId !== "string") {
|
529 |
-
throw new Error("User ID must be a string.");
|
530 |
-
}
|
531 |
-
if (!settings.code) {
|
532 |
-
throw new Error("Placement code is required.");
|
533 |
-
}
|
534 |
-
if (!settings.messages || !Array.isArray(settings.messages) || settings.messages.length === 0) {
|
535 |
-
throw new Error("Messages are required.");
|
536 |
-
}
|
537 |
-
settings.messages.forEach((message) => {
|
538 |
-
if (!message.id) {
|
539 |
-
throw new Error("Message ID is required.");
|
540 |
-
}
|
541 |
-
if (typeof message.id !== "string") {
|
542 |
-
throw new Error("Message ID must be a string.");
|
543 |
-
}
|
544 |
-
if (!message.content) {
|
545 |
-
throw new Error("Message content is required.");
|
546 |
-
}
|
547 |
-
if (!message.createdAt) {
|
548 |
-
throw new Error("Message createdAt is required.");
|
549 |
-
}
|
550 |
-
if (typeof message.createdAt !== "string" && !(message.createdAt instanceof Date)) {
|
551 |
-
throw new Error("Message createdAt must be string or Date object.");
|
552 |
-
}
|
553 |
-
if (typeof message.createdAt === "string" && !DATE_REGEX.test(message.createdAt)) {
|
554 |
-
throw new Error(
|
555 |
-
"Message createdAt must be a valid ISO 8601 date string."
|
556 |
-
);
|
557 |
-
}
|
558 |
-
if (message.createdAt instanceof Date && isNaN(message.createdAt.getTime())) {
|
559 |
-
throw new Error("Message createdAt must be a valid Date object.");
|
560 |
-
}
|
561 |
-
if (!message.role) {
|
562 |
-
throw new Error("Message role is required.");
|
563 |
-
}
|
564 |
-
if (message.role !== "assistant" && message.role !== "user") {
|
565 |
-
throw new Error('Message role must be either "assistant" or "user".');
|
566 |
-
}
|
567 |
-
});
|
568 |
-
};
|
569 |
-
textStreamPart = {
|
570 |
-
code: "0",
|
571 |
-
name: "text",
|
572 |
-
parse: (value) => {
|
573 |
-
if (typeof value !== "string") {
|
574 |
-
throw new Error('"text" parts expect a string value.');
|
575 |
-
}
|
576 |
-
return { type: "text", value };
|
577 |
-
}
|
578 |
-
};
|
579 |
-
functionCallStreamPart = {
|
580 |
-
code: "1",
|
581 |
-
name: "function_call",
|
582 |
-
parse: (value) => {
|
583 |
-
if (value == null || typeof value !== "object" || !("function_call" in value) || typeof value.function_call !== "object" || value.function_call == null || !("name" in value.function_call) || !("arguments" in value.function_call) || typeof value.function_call.name !== "string" || typeof value.function_call.arguments !== "string") {
|
584 |
-
throw new Error(
|
585 |
-
'"function_call" parts expect an object with a "function_call" property.'
|
586 |
-
);
|
587 |
-
}
|
588 |
-
return {
|
589 |
-
type: "function_call",
|
590 |
-
value
|
591 |
-
};
|
592 |
-
}
|
593 |
-
};
|
594 |
-
dataStreamPart = {
|
595 |
-
code: "2",
|
596 |
-
name: "data",
|
597 |
-
parse: (value) => {
|
598 |
-
if (!Array.isArray(value)) {
|
599 |
-
throw new Error('"data" parts expect an array value.');
|
600 |
-
}
|
601 |
-
return { type: "data", value };
|
602 |
-
}
|
603 |
-
};
|
604 |
-
errorStreamPart = {
|
605 |
-
code: "3",
|
606 |
-
name: "error",
|
607 |
-
parse: (value) => {
|
608 |
-
if (typeof value !== "string") {
|
609 |
-
throw new Error('"error" parts expect a string value.');
|
610 |
-
}
|
611 |
-
return { type: "error", value };
|
612 |
-
}
|
613 |
-
};
|
614 |
-
assistantMessageStreamPart = {
|
615 |
-
code: "4",
|
616 |
-
name: "assistant_message",
|
617 |
-
parse: (value) => {
|
618 |
-
if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
|
619 |
-
(item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
|
620 |
-
)) {
|
621 |
-
throw new Error(
|
622 |
-
'"assistant_message" parts expect an object with an "id", "role", and "content" property.'
|
623 |
-
);
|
624 |
-
}
|
625 |
-
return {
|
626 |
-
type: "assistant_message",
|
627 |
-
value
|
628 |
-
};
|
629 |
-
}
|
630 |
-
};
|
631 |
-
assistantControlDataStreamPart = {
|
632 |
-
code: "5",
|
633 |
-
name: "assistant_control_data",
|
634 |
-
parse: (value) => {
|
635 |
-
if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
|
636 |
-
throw new Error(
|
637 |
-
'"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
|
638 |
-
);
|
639 |
-
}
|
640 |
-
return {
|
641 |
-
type: "assistant_control_data",
|
642 |
-
value: {
|
643 |
-
threadId: value.threadId,
|
644 |
-
messageId: value.messageId
|
645 |
-
}
|
646 |
-
};
|
647 |
-
}
|
648 |
-
};
|
649 |
-
dataMessageStreamPart = {
|
650 |
-
code: "6",
|
651 |
-
name: "data_message",
|
652 |
-
parse: (value) => {
|
653 |
-
if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
|
654 |
-
throw new Error(
|
655 |
-
'"data_message" parts expect an object with a "role" and "data" property.'
|
656 |
-
);
|
657 |
-
}
|
658 |
-
return {
|
659 |
-
type: "data_message",
|
660 |
-
value
|
661 |
-
};
|
662 |
-
}
|
663 |
-
};
|
664 |
-
toolCallStreamPart = {
|
665 |
-
code: "7",
|
666 |
-
name: "tool_calls",
|
667 |
-
parse: (value) => {
|
668 |
-
if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some((tc) => {
|
669 |
-
tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string";
|
670 |
-
})) {
|
671 |
-
throw new Error(
|
672 |
-
'"tool_calls" parts expect an object with a ToolCallPayload.'
|
673 |
-
);
|
674 |
-
}
|
675 |
-
return {
|
676 |
-
type: "tool_calls",
|
677 |
-
value
|
678 |
-
};
|
679 |
-
}
|
680 |
-
};
|
681 |
-
messageAnnotationsStreamPart = {
|
682 |
-
code: "8",
|
683 |
-
name: "message_annotations",
|
684 |
-
parse: (value) => {
|
685 |
-
if (!Array.isArray(value)) {
|
686 |
-
throw new Error('"message_annotations" parts expect an array value.');
|
687 |
-
}
|
688 |
-
return { type: "message_annotations", value };
|
689 |
-
}
|
690 |
-
};
|
691 |
-
streamParts = [
|
692 |
-
textStreamPart,
|
693 |
-
functionCallStreamPart,
|
694 |
-
dataStreamPart,
|
695 |
-
errorStreamPart,
|
696 |
-
assistantMessageStreamPart,
|
697 |
-
assistantControlDataStreamPart,
|
698 |
-
dataMessageStreamPart,
|
699 |
-
toolCallStreamPart,
|
700 |
-
messageAnnotationsStreamPart
|
701 |
-
];
|
702 |
-
streamPartsByCode = {
|
703 |
-
[textStreamPart.code]: textStreamPart,
|
704 |
-
[functionCallStreamPart.code]: functionCallStreamPart,
|
705 |
-
[dataStreamPart.code]: dataStreamPart,
|
706 |
-
[errorStreamPart.code]: errorStreamPart,
|
707 |
-
[assistantMessageStreamPart.code]: assistantMessageStreamPart,
|
708 |
-
[assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
|
709 |
-
[dataMessageStreamPart.code]: dataMessageStreamPart,
|
710 |
-
[toolCallStreamPart.code]: toolCallStreamPart,
|
711 |
-
[messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart
|
712 |
-
};
|
713 |
-
StreamStringPrefixes = {
|
714 |
-
[textStreamPart.name]: textStreamPart.code,
|
715 |
-
[functionCallStreamPart.name]: functionCallStreamPart.code,
|
716 |
-
[dataStreamPart.name]: dataStreamPart.code,
|
717 |
-
[errorStreamPart.name]: errorStreamPart.code,
|
718 |
-
[assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
|
719 |
-
[assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
|
720 |
-
[dataMessageStreamPart.name]: dataMessageStreamPart.code,
|
721 |
-
[toolCallStreamPart.name]: toolCallStreamPart.code,
|
722 |
-
[messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code
|
723 |
-
};
|
724 |
-
validCodes = streamParts.map((part) => part.code);
|
725 |
-
parseStreamPart = (line) => {
|
726 |
-
const firstSeparatorIndex = line.indexOf(":");
|
727 |
-
if (firstSeparatorIndex === -1) {
|
728 |
-
throw new Error("Failed to parse stream string. No separator found.");
|
729 |
-
}
|
730 |
-
const prefix = line.slice(0, firstSeparatorIndex);
|
731 |
-
if (!validCodes.includes(prefix)) {
|
732 |
-
throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
|
733 |
-
}
|
734 |
-
const code = prefix;
|
735 |
-
const textValue = line.slice(firstSeparatorIndex + 1);
|
736 |
-
const any = JSON.parse(textValue);
|
737 |
-
return streamPartsByCode[code].parse(any);
|
738 |
-
};
|
739 |
-
NEWLINE = "\n".charCodeAt(0);
|
740 |
-
Logger2 = class {
|
741 |
-
localLevel = "log";
|
742 |
-
remoteLevel = "error";
|
743 |
-
remoteConfig = null;
|
744 |
-
levels = {
|
745 |
-
debug: 0,
|
746 |
-
info: 1,
|
747 |
-
log: 2,
|
748 |
-
warn: 3,
|
749 |
-
error: 4,
|
750 |
-
silent: 5
|
751 |
-
};
|
752 |
-
getLocalLevel() {
|
753 |
-
return this.localLevel;
|
754 |
-
}
|
755 |
-
setLocalLevel(level) {
|
756 |
-
this.localLevel = level;
|
757 |
-
}
|
758 |
-
getRemoteLevel() {
|
759 |
-
return this.remoteLevel;
|
760 |
-
}
|
761 |
-
setRemoteLevel(level) {
|
762 |
-
this.remoteLevel = level;
|
763 |
-
}
|
764 |
-
configureRemote(url, params) {
|
765 |
-
this.remoteConfig = { url, params };
|
766 |
-
}
|
767 |
-
shouldLog(level, targetLevel) {
|
768 |
-
if (targetLevel === "silent") {
|
769 |
-
return false;
|
770 |
-
}
|
771 |
-
return this.levels[level] >= this.levels[targetLevel];
|
772 |
-
}
|
773 |
-
logToConsole(level, ...args) {
|
774 |
-
if (this.shouldLog(level, this.localLevel)) {
|
775 |
-
if (level === "silent") {
|
776 |
-
return;
|
777 |
-
}
|
778 |
-
console[level](...args);
|
779 |
-
}
|
780 |
-
}
|
781 |
-
logToRemote(level, ...args) {
|
782 |
-
if (this.remoteConfig && this.shouldLog(level, this.remoteLevel)) {
|
783 |
-
fetch(`${this.remoteConfig.url}/log`, {
|
784 |
-
method: "POST",
|
785 |
-
body: JSON.stringify({
|
786 |
-
...this.remoteConfig.params,
|
787 |
-
level,
|
788 |
-
message: args,
|
789 |
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
790 |
-
})
|
791 |
-
}).catch((e) => {
|
792 |
-
});
|
793 |
-
}
|
794 |
-
}
|
795 |
-
debug(...args) {
|
796 |
-
this.logToConsole("debug", ...args);
|
797 |
-
this.logToRemote("debug", ...args);
|
798 |
-
}
|
799 |
-
info(...args) {
|
800 |
-
this.logToConsole("info", ...args);
|
801 |
-
this.logToRemote("info", ...args);
|
802 |
-
}
|
803 |
-
log(...args) {
|
804 |
-
this.logToConsole("log", ...args);
|
805 |
-
this.logToRemote("log", ...args);
|
806 |
-
}
|
807 |
-
warn(...args) {
|
808 |
-
this.logToConsole("warn", ...args);
|
809 |
-
this.logToRemote("warn", ...args);
|
810 |
-
}
|
811 |
-
error(...args) {
|
812 |
-
this.logToConsole("error", ...args);
|
813 |
-
this.logToRemote("error", ...args);
|
814 |
-
}
|
815 |
-
};
|
816 |
-
log2 = new Logger2();
|
817 |
-
DEFAULT_SERVER_URL = "https://server.megabrain.co";
|
818 |
-
CONTAINER_CSS_CLASS = "kontext-ad";
|
819 |
-
KontextKey = Symbol("Kontext");
|
820 |
-
if (!globalThis[KontextKey]) {
|
821 |
-
globalThis[KontextKey] = {};
|
822 |
-
}
|
823 |
-
markAdAsViewed = async (impressionId, serverUrl = DEFAULT_SERVER_URL) => {
|
824 |
-
try {
|
825 |
-
const response = await fetch(
|
826 |
-
`${serverUrl}/impression/${impressionId}/view`,
|
827 |
-
{
|
828 |
-
method: "POST"
|
829 |
-
}
|
830 |
-
);
|
831 |
-
if (!response.ok) {
|
832 |
-
throw new Error("Error sending view request");
|
833 |
-
}
|
834 |
-
log2.debug("[Kontext] ad marked as viewed", impressionId);
|
835 |
-
return true;
|
836 |
-
} catch (e) {
|
837 |
-
log2.error("[Kontext] Error sending view request", e, {
|
838 |
-
impressionId,
|
839 |
-
serverUrl
|
840 |
-
});
|
841 |
-
}
|
842 |
-
};
|
843 |
-
fixUrl = (adserverUrl, content) => {
|
844 |
-
if (content) {
|
845 |
-
content = content.replace("/impression/", `${adserverUrl}/impression/`);
|
846 |
-
content = content.replace("/ad/", `${adserverUrl}/impression/`);
|
847 |
-
}
|
848 |
-
return content;
|
849 |
-
};
|
850 |
-
fetchAd = async (params, callbacks) => {
|
851 |
-
const settings = {
|
852 |
-
...params,
|
853 |
-
serverUrl: params.serverUrl ?? DEFAULT_SERVER_URL
|
854 |
-
};
|
855 |
-
let sessionId = globalThis[KontextKey].sessionId ?? void 0;
|
856 |
-
const sdkVersion = `sdk-js-${version}`;
|
857 |
-
try {
|
858 |
-
log2.setLocalLevel(params.logLevel || "silent");
|
859 |
-
validateFetchAdSettings(settings);
|
860 |
-
if (callbacks?.onStart) {
|
861 |
-
callbacks.onStart();
|
862 |
-
}
|
863 |
-
log2.debug("Fetching ad", settings);
|
864 |
-
const urlPreload = `${settings.serverUrl}/preload`;
|
865 |
-
const responsePreload = await fetchRetry(
|
866 |
-
urlPreload,
|
867 |
-
{
|
868 |
-
method: "POST",
|
869 |
-
headers: {
|
870 |
-
"Content-Type": "application/json"
|
871 |
-
},
|
872 |
-
body: JSON.stringify({
|
873 |
-
publisherToken: settings.publisherToken,
|
874 |
-
code: settings.code,
|
875 |
-
conversationId: settings.conversationId,
|
876 |
-
userId: settings.userId,
|
877 |
-
messages: settings.messages,
|
878 |
-
params: settings.params,
|
879 |
-
bidRequest: !!callbacks?.onBid,
|
880 |
-
sessionId,
|
881 |
-
sdkVersion
|
882 |
-
})
|
883 |
-
},
|
884 |
-
1e4,
|
885 |
-
1
|
886 |
-
);
|
887 |
-
if (!responsePreload.ok) {
|
888 |
-
throw new Error(`Error fetching ad ${responsePreload.status}`);
|
889 |
-
}
|
890 |
-
if (responsePreload.status === 204) {
|
891 |
-
if (callbacks?.onComplete) {
|
892 |
-
callbacks.onComplete("", {});
|
893 |
-
if (callbacks.onBid) {
|
894 |
-
callbacks.onBid(null);
|
895 |
-
}
|
896 |
-
return {
|
897 |
-
content: "",
|
898 |
-
metadata: {}
|
899 |
-
};
|
900 |
-
}
|
901 |
-
}
|
902 |
-
const remoteLogLevel = responsePreload.headers.get(
|
903 |
-
"X-Kontext-RemoteLogLevel"
|
904 |
-
);
|
905 |
-
if (remoteLogLevel) {
|
906 |
-
log2.setRemoteLevel(remoteLogLevel);
|
907 |
-
}
|
908 |
-
const preloaded = await responsePreload.json();
|
909 |
-
if (preloaded.sessionId) {
|
910 |
-
sessionId = preloaded.sessionId;
|
911 |
-
globalThis[KontextKey].sessionId = preloaded.sessionId;
|
912 |
-
}
|
913 |
-
if (preloaded.errCode) {
|
914 |
-
log2.info("[Kontext] Preload result: ", preloaded.errCode);
|
915 |
-
if (callbacks?.onBid) {
|
916 |
-
callbacks.onBid(null);
|
917 |
-
}
|
918 |
-
if (callbacks?.onComplete) {
|
919 |
-
callbacks.onComplete("", {});
|
920 |
-
}
|
921 |
-
return {
|
922 |
-
content: "",
|
923 |
-
metadata: {}
|
924 |
-
};
|
925 |
-
}
|
926 |
-
let bidId = void 0;
|
927 |
-
if (callbacks?.onBid) {
|
928 |
-
bidId = preloaded.bidId;
|
929 |
-
const shouldRenderAd = await callbacks.onBid(preloaded.bid);
|
930 |
-
if (!shouldRenderAd) {
|
931 |
-
if (callbacks?.onComplete) {
|
932 |
-
callbacks.onComplete("", {});
|
933 |
-
}
|
934 |
-
return {
|
935 |
-
content: "",
|
936 |
-
metadata: {}
|
937 |
-
};
|
938 |
-
}
|
939 |
-
}
|
940 |
-
const urlStream = `${settings.serverUrl}/stream`;
|
941 |
-
const response = await fetchRetry(
|
942 |
-
urlStream,
|
943 |
-
{
|
944 |
-
method: "POST",
|
945 |
-
headers: {
|
946 |
-
"Content-Type": "application/json"
|
947 |
-
},
|
948 |
-
body: JSON.stringify({
|
949 |
-
publisherToken: settings.publisherToken,
|
950 |
-
code: settings.code,
|
951 |
-
conversationId: settings.conversationId,
|
952 |
-
userId: settings.userId,
|
953 |
-
messages: settings.messages,
|
954 |
-
params: settings.params,
|
955 |
-
bidId,
|
956 |
-
sessionId,
|
957 |
-
sdkVersion
|
958 |
-
})
|
959 |
-
},
|
960 |
-
6e4,
|
961 |
-
1
|
962 |
-
);
|
963 |
-
if (response.status === 204) {
|
964 |
-
if (callbacks?.onComplete) {
|
965 |
-
callbacks.onComplete("", {});
|
966 |
-
}
|
967 |
-
return {
|
968 |
-
content: "",
|
969 |
-
metadata: {}
|
970 |
-
};
|
971 |
-
}
|
972 |
-
const reader = response.body?.getReader();
|
973 |
-
if (!reader) {
|
974 |
-
throw new Error("Reader not found");
|
975 |
-
}
|
976 |
-
let data = "";
|
977 |
-
let metadata = {};
|
978 |
-
let container = null;
|
979 |
-
if (params.element) {
|
980 |
-
while (params.element.firstChild) {
|
981 |
-
params.element.removeChild(params.element.firstChild);
|
982 |
-
}
|
983 |
-
container = document.createElement("a");
|
984 |
-
container.className = CONTAINER_CSS_CLASS;
|
985 |
-
container.target = "_blank";
|
986 |
-
container.rel = "noopener noreferrer";
|
987 |
-
container.style.display = "block";
|
988 |
-
container.style.textDecoration = "none";
|
989 |
-
container.style.color = "inherit";
|
990 |
-
params.element.appendChild(container);
|
991 |
-
}
|
992 |
-
log2.log("[Kontext] Streaming ad started");
|
993 |
-
for await (const { type, value } of readDataStream(reader)) {
|
994 |
-
switch (type) {
|
995 |
-
case "text": {
|
996 |
-
if (callbacks?.onToken) {
|
997 |
-
callbacks.onToken(value);
|
998 |
-
}
|
999 |
-
data += value;
|
1000 |
-
if (container) {
|
1001 |
-
container.innerHTML = fixUrl(
|
1002 |
-
settings.serverUrl,
|
1003 |
-
convertMarkdownLinks(convertThemedText(data))
|
1004 |
-
);
|
1005 |
-
}
|
1006 |
-
break;
|
1007 |
-
}
|
1008 |
-
case "data": {
|
1009 |
-
let val = value;
|
1010 |
-
if (Array.isArray(val)) {
|
1011 |
-
val = val[0];
|
1012 |
-
}
|
1013 |
-
metadata = {
|
1014 |
-
...metadata,
|
1015 |
-
...val
|
1016 |
-
};
|
1017 |
-
break;
|
1018 |
-
}
|
1019 |
-
case "error": {
|
1020 |
-
throw new Error(`Error streaming ad ${value}`);
|
1021 |
-
}
|
1022 |
-
}
|
1023 |
-
}
|
1024 |
-
const content = metadata.content ?? data;
|
1025 |
-
if (container) {
|
1026 |
-
container.addEventListener("click", () => {
|
1027 |
-
if (params?.onAdClick) {
|
1028 |
-
params.onAdClick({
|
1029 |
-
id: metadata.impressionId,
|
1030 |
-
content: fixUrl(settings.serverUrl, content)
|
1031 |
-
});
|
1032 |
-
}
|
1033 |
-
});
|
1034 |
-
}
|
1035 |
-
if (container && metadata.product) {
|
1036 |
-
container.href = fixUrl(
|
1037 |
-
settings.serverUrl,
|
1038 |
-
`/impression/${metadata.impressionId}/redirect`
|
1039 |
-
);
|
1040 |
-
container.innerHTML = fixUrl(
|
1041 |
-
settings.serverUrl,
|
1042 |
-
convertMarkdownLinks(convertThemedText(content))
|
1043 |
-
).replace(
|
1044 |
-
new RegExp(`/(ad|impression)/${metadata.product.id}/redirect`, "g"),
|
1045 |
-
`/impression/${metadata.impressionId}/redirect`
|
1046 |
-
);
|
1047 |
-
}
|
1048 |
-
log2.log("[Kontext] Streaming ad completed");
|
1049 |
-
log2.debug("Streaming ad metadata", {
|
1050 |
-
...metadata,
|
1051 |
-
containerHtml: container?.innerHTML
|
1052 |
-
});
|
1053 |
-
const res = {
|
1054 |
-
content,
|
1055 |
-
metadata: {
|
1056 |
-
sessionId,
|
1057 |
-
impressionId: metadata.impressionId,
|
1058 |
-
productUrl: metadata.product?.url ?? null
|
1059 |
-
}
|
1060 |
-
};
|
1061 |
-
if (callbacks?.onComplete) {
|
1062 |
-
callbacks.onComplete(res.content, res.metadata);
|
1063 |
-
}
|
1064 |
-
if (container && metadata.impressionId) {
|
1065 |
-
if (typeof window.IntersectionObserver === "undefined") {
|
1066 |
-
markAdAsViewed(metadata.impressionId, settings.serverUrl);
|
1067 |
-
params.onAdView?.({
|
1068 |
-
id: metadata.impressionId,
|
1069 |
-
content
|
1070 |
-
});
|
1071 |
-
return res;
|
1072 |
-
}
|
1073 |
-
const observer = new window.IntersectionObserver((entries, observer2) => {
|
1074 |
-
entries.forEach((entry) => {
|
1075 |
-
if (entry.isIntersecting) {
|
1076 |
-
markAdAsViewed(metadata.impressionId, settings.serverUrl);
|
1077 |
-
params.onAdView?.({
|
1078 |
-
id: metadata.impressionId,
|
1079 |
-
content
|
1080 |
-
});
|
1081 |
-
observer2.unobserve(entry.target);
|
1082 |
-
}
|
1083 |
-
});
|
1084 |
-
});
|
1085 |
-
observer.observe(container);
|
1086 |
-
}
|
1087 |
-
return res;
|
1088 |
-
} catch (error) {
|
1089 |
-
log2.error("[Kontext] Error fetching ad", error, {
|
1090 |
-
...settings,
|
1091 |
-
sessionId,
|
1092 |
-
sdkVersion
|
1093 |
-
});
|
1094 |
-
if (callbacks?.onError) {
|
1095 |
-
callbacks.onError(error);
|
1096 |
-
} else {
|
1097 |
-
throw error;
|
1098 |
-
}
|
1099 |
-
}
|
1100 |
-
};
|
1101 |
-
}
|
1102 |
-
});
|
1103 |
-
|
1104 |
-
// src/bidders/kontext-bidder.ts
|
1105 |
-
var KontextBidder, kontext_bidder_default;
|
1106 |
-
var init_kontext_bidder = __esm({
|
1107 |
-
"src/bidders/kontext-bidder.ts"() {
|
1108 |
-
"use strict";
|
1109 |
-
init_dist();
|
1110 |
-
KontextBidder = class {
|
1111 |
-
name;
|
1112 |
-
params;
|
1113 |
-
advertiserToken;
|
1114 |
-
renderStart = null;
|
1115 |
-
renderDone = null;
|
1116 |
-
div;
|
1117 |
-
constructor(params) {
|
1118 |
-
this.name = params.bidderName;
|
1119 |
-
this.params = params;
|
1120 |
-
this.advertiserToken = params.advertiserToken;
|
1121 |
-
this.div = document.createElement("div");
|
1122 |
-
}
|
1123 |
-
async getBid(messages, adUnit, params, getAdsParams) {
|
1124 |
-
const fetchAdParams = {
|
1125 |
-
publisherToken: this.params.kontextPublisherToken,
|
1126 |
-
userId: getAdsParams.userId,
|
1127 |
-
conversationId: getAdsParams.conversationId,
|
1128 |
-
code: adUnit.params.placementCode,
|
1129 |
-
element: this.div,
|
1130 |
-
messages: messages.map((message, index) => ({
|
1131 |
-
id: getAdsParams.conversationId + "-" + index,
|
1132 |
-
content: message.content,
|
1133 |
-
createdAt: /* @__PURE__ */ new Date(),
|
1134 |
-
role: message.role
|
1135 |
-
}))
|
1136 |
-
};
|
1137 |
-
let renderDoneResolve;
|
1138 |
-
this.renderDone = new Promise((resolve) => {
|
1139 |
-
renderDoneResolve = resolve;
|
1140 |
-
});
|
1141 |
-
const bid = await new Promise((resolve) => {
|
1142 |
-
fetchAd(fetchAdParams, {
|
1143 |
-
onBid: async (bid2) => {
|
1144 |
-
resolve(bid2);
|
1145 |
-
await new Promise((resolve2) => {
|
1146 |
-
this.renderStart = resolve2;
|
1147 |
-
});
|
1148 |
-
return true;
|
1149 |
-
},
|
1150 |
-
onComplete: () => {
|
1151 |
-
console.log("Kontext ad complete");
|
1152 |
-
renderDoneResolve();
|
1153 |
-
}
|
1154 |
-
});
|
1155 |
-
});
|
1156 |
-
if (bid === null || bid === void 0) {
|
1157 |
-
throw new Error("No bid returned from Kontext");
|
1158 |
-
}
|
1159 |
-
return {
|
1160 |
-
advertiserToken: this.params.advertiserToken,
|
1161 |
-
bidder: this.name,
|
1162 |
-
price: bid,
|
1163 |
-
outcome: "successful"
|
1164 |
-
};
|
1165 |
-
}
|
1166 |
-
async renderAd(bid, element) {
|
1167 |
-
if (this.renderStart) {
|
1168 |
-
this.renderStart();
|
1169 |
-
element.appendChild(this.div);
|
1170 |
-
}
|
1171 |
-
await this.renderDone;
|
1172 |
-
}
|
1173 |
-
};
|
1174 |
-
kontext_bidder_default = KontextBidder;
|
1175 |
-
}
|
1176 |
-
});
|
1177 |
-
|
1178 |
-
// src/bidders/ahilab-bidder.ts
|
1179 |
-
function formatMarkdown(markdown) {
|
1180 |
-
return markdown.replace(
|
1181 |
-
/\[([^\]]+)\]\(([^)]+)\)/g,
|
1182 |
-
'<a class="ahilab-a" href="$2" target="_blank" rel="noopener noreferrer">$1</a>'
|
1183 |
-
);
|
1184 |
-
}
|
1185 |
-
var AhilabBidder, ahilab_bidder_default;
|
1186 |
-
var init_ahilab_bidder = __esm({
|
1187 |
-
"src/bidders/ahilab-bidder.ts"() {
|
1188 |
-
"use strict";
|
1189 |
-
AhilabBidder = class {
|
1190 |
-
name;
|
1191 |
-
params;
|
1192 |
-
messages = [];
|
1193 |
-
advertiserToken;
|
1194 |
-
renderStart = null;
|
1195 |
-
renderDone = null;
|
1196 |
-
div;
|
1197 |
-
country = null;
|
1198 |
-
constructor(params) {
|
1199 |
-
this.name = params.bidderName;
|
1200 |
-
this.params = params;
|
1201 |
-
this.advertiserToken = params.advertiserToken;
|
1202 |
-
this.div = document.createElement("div");
|
1203 |
-
}
|
1204 |
-
async getBid(messages, adUnit, params, getAdsParams) {
|
1205 |
-
this.messages = messages;
|
1206 |
-
const country = await fetch(this.params.countryEndpoint).then((res) => {
|
1207 |
-
if (!res.ok) {
|
1208 |
-
throw new Error(`Failed to fetch country: ${res.statusText}`);
|
1209 |
-
} else {
|
1210 |
-
return res.json();
|
1211 |
-
}
|
1212 |
-
});
|
1213 |
-
this.country = country.countryCode;
|
1214 |
-
this.country = "US";
|
1215 |
-
console.log("[DEV / Ahilab Bidder] OVERRIDING countryCode", "US");
|
1216 |
-
if (this.country === "US") {
|
1217 |
-
return {
|
1218 |
-
advertiserToken: this.params.advertiserToken,
|
1219 |
-
bidder: this.name,
|
1220 |
-
price: 1,
|
1221 |
-
// return 1 if countryCode exists, 0 if not
|
1222 |
-
outcome: "successful"
|
1223 |
-
};
|
1224 |
-
} else {
|
1225 |
-
return {
|
1226 |
-
advertiserToken: this.params.advertiserToken,
|
1227 |
-
bidder: this.name,
|
1228 |
-
price: 0,
|
1229 |
-
outcome: "successful"
|
1230 |
-
};
|
1231 |
-
}
|
1232 |
-
}
|
1233 |
-
async renderAd(bid, element) {
|
1234 |
-
const userMessage = this.messages.slice().reverse().find(
|
1235 |
-
(msg) => msg.role === "user"
|
1236 |
-
);
|
1237 |
-
if (!userMessage) {
|
1238 |
-
console.warn("AhilabBidder: No user message found");
|
1239 |
-
return;
|
1240 |
-
}
|
1241 |
-
try {
|
1242 |
-
const res = await fetch("https://connect.ahilab.co/prompt_matching", {
|
1243 |
-
method: "POST",
|
1244 |
-
headers: {
|
1245 |
-
Authorization: "Bearer 4u4IfD26lCeJHmR_4gZTsQ",
|
1246 |
-
"Content-Type": "application/json"
|
1247 |
-
},
|
1248 |
-
body: JSON.stringify({
|
1249 |
-
query: userMessage.content,
|
1250 |
-
country: "US"
|
1251 |
-
// or pass real countryCode if available
|
1252 |
-
})
|
1253 |
-
});
|
1254 |
-
const markdownText = await res.text();
|
1255 |
-
const htmlInner = formatMarkdown(markdownText);
|
1256 |
-
const htmlString = `<div class="ahilab-ad-container">${htmlInner}</div>`.trim();
|
1257 |
-
element.innerHTML = htmlString;
|
1258 |
-
} catch (err) {
|
1259 |
-
console.error("Ahilab renderAd error:", err);
|
1260 |
-
}
|
1261 |
-
}
|
1262 |
-
};
|
1263 |
-
ahilab_bidder_default = AhilabBidder;
|
1264 |
-
}
|
1265 |
-
});
|
1266 |
-
|
1267 |
-
// publishers/deepai-prod-v2.ts
|
1268 |
-
var require_deepai_prod_v2 = __commonJS({
|
1269 |
-
"publishers/deepai-prod-v2.ts"() {
|
1270 |
-
init_monetano();
|
1271 |
-
init_utils();
|
1272 |
-
init_koah_bidder();
|
1273 |
-
init_kontext_bidder();
|
1274 |
-
init_ahilab_bidder();
|
1275 |
-
var renderKoahAd = (bid, adContainer, bidder) => {
|
1276 |
-
bidder.renderAd = async (bid2, element) => {
|
1277 |
-
element.classList.add("koah-ad");
|
1278 |
-
const userMessage = bidder.messages.reverse().find(
|
1279 |
-
(message) => message.role === "user"
|
1280 |
-
);
|
1281 |
-
const assistantMessage = bidder.messages.reverse().find(
|
1282 |
-
(message) => message.role === "assistant"
|
1283 |
-
);
|
1284 |
-
if (userMessage && assistantMessage) {
|
1285 |
-
const koah = window.koah;
|
1286 |
-
if (koah) {
|
1287 |
-
await koah.process(userMessage.content, assistantMessage.content, "suffix");
|
1288 |
-
}
|
1289 |
-
}
|
1290 |
-
};
|
1291 |
-
bidder.renderAd(bid, adContainer).then(() => {
|
1292 |
-
console.log("Koah ad rendered successfully");
|
1293 |
-
}).catch((error) => {
|
1294 |
-
console.error("Error rendering Koah ad", error);
|
1295 |
-
});
|
1296 |
-
};
|
1297 |
-
var renderKontextAd = (bid, adContainer, bidder) => {
|
1298 |
-
bidder.renderAd(bid, adContainer).then(() => {
|
1299 |
-
console.log("Kontext ad rendered successfully");
|
1300 |
-
}).catch((error) => {
|
1301 |
-
console.error("Error rendering Kontext ad", error);
|
1302 |
-
});
|
1303 |
-
};
|
1304 |
-
var renderAhilabAd = (bid, adContainer, bidder) => {
|
1305 |
-
bidder.renderAd(bid, adContainer).then(() => {
|
1306 |
-
console.log("Ahilab ad rendered successfully");
|
1307 |
-
}).catch((error) => {
|
1308 |
-
console.error("Error rendering Ahilab ad", error);
|
1309 |
-
});
|
1310 |
-
};
|
1311 |
-
if (typeof window !== "undefined") {
|
1312 |
-
const queue = window.monetano?.que || [];
|
1313 |
-
const monetano = createMonetano(
|
1314 |
-
queue,
|
1315 |
-
{
|
1316 |
-
publisherToken: "deepai-prod-v2",
|
1317 |
-
adUnits: [
|
1318 |
-
{
|
1319 |
-
code: "monetano-infeed-ad-below",
|
1320 |
-
params: {
|
1321 |
-
placementCode: "inlineAd"
|
1322 |
-
},
|
1323 |
-
bidders: ["koah-bidder", "kontext-bidder", "ahilab-bidder"],
|
1324 |
-
floorPrice: 1
|
1325 |
-
}
|
1326 |
-
],
|
1327 |
-
timeout: 2e3,
|
1328 |
-
url: "http://localhost:3008"
|
1329 |
-
},
|
1330 |
-
{
|
1331 |
-
"koah-bidder": () => new koah_bidder_default({
|
1332 |
-
koahPublisherId: "8a686266-fd49-462b-8480-f7326a2566f7",
|
1333 |
-
bidderName: "koah-bidder",
|
1334 |
-
advertiserToken: "adv-koah",
|
1335 |
-
countryEndpoint: "http://localhost:3008/country"
|
1336 |
-
}),
|
1337 |
-
"kontext-bidder": () => new kontext_bidder_default({
|
1338 |
-
bidderName: "kontext-bidder",
|
1339 |
-
kontextPublisherToken: "deepai-yjdgkyt51l",
|
1340 |
-
advertiserToken: "kontext"
|
1341 |
-
}),
|
1342 |
-
"ahilab-bidder": () => new ahilab_bidder_default({
|
1343 |
-
bidderName: "ahilab-bidder",
|
1344 |
-
advertiserToken: "ahilab-bidder",
|
1345 |
-
countryEndpoint: "http://localhost:3008/country"
|
1346 |
-
})
|
1347 |
-
}
|
1348 |
-
);
|
1349 |
-
window.monetano = monetano;
|
1350 |
-
window.monetano.getAds = async (messages, params, options = {}) => {
|
1351 |
-
console.log(`--- getAds (${(/* @__PURE__ */ new Date()).toISOString()}) ---`);
|
1352 |
-
const adUnit = monetano.settings.adUnits[0];
|
1353 |
-
if (!adUnit) return;
|
1354 |
-
console.log("adUnit: ", adUnit);
|
1355 |
-
const allAdSlots = document.querySelectorAll(`.${adUnit?.code}`);
|
1356 |
-
console.log("allAdSlots (total): ", allAdSlots.length);
|
1357 |
-
const adSlot = allAdSlots[allAdSlots.length - 1];
|
1358 |
-
const bidderNames = adUnit?.bidders;
|
1359 |
-
const bidders = bidderNames.map((bidder) => monetano._bidders.find((b) => b.name === bidder)).filter((b) => b !== void 0);
|
1360 |
-
const bids = await Promise.all(
|
1361 |
-
bidders.map(async (bidder) => {
|
1362 |
-
const bid = await getBidForUnit(
|
1363 |
-
adUnit,
|
1364 |
-
messages,
|
1365 |
-
bidder,
|
1366 |
-
params,
|
1367 |
-
monetano.settings.timeout
|
1368 |
-
);
|
1369 |
-
return bid;
|
1370 |
-
})
|
1371 |
-
);
|
1372 |
-
const adjustedBids = options.onBids ? options.onBids(bids) : bids;
|
1373 |
-
const { impressionId, winner } = await serverAuction(
|
1374 |
-
// winner = WinningBid
|
1375 |
-
monetano,
|
1376 |
-
adUnit,
|
1377 |
-
messages,
|
1378 |
-
adjustedBids
|
1379 |
-
);
|
1380 |
-
const winningBid = winner;
|
1381 |
-
console.log("[getAds] winningBid: ", winningBid);
|
1382 |
-
if (winningBid) {
|
1383 |
-
options.onWinner?.(winner);
|
1384 |
-
if (winner.bidder === "koah-bidder") {
|
1385 |
-
const koahBidder = monetano._bidders.find((b) => b.name === "koah-bidder");
|
1386 |
-
renderKoahAd(winner, adSlot, koahBidder);
|
1387 |
-
options.onRender?.();
|
1388 |
-
return;
|
1389 |
-
}
|
1390 |
-
if (winner.bidder === "kontext-bidder") {
|
1391 |
-
const kontextBidder = monetano._bidders.find((b) => b.name === "kontext-bidder");
|
1392 |
-
renderKontextAd(winner, adSlot, kontextBidder);
|
1393 |
-
options.onRender?.();
|
1394 |
-
return;
|
1395 |
-
}
|
1396 |
-
if (winner.bidder === "ahilab-bidder") {
|
1397 |
-
const ahilabBidder = monetano._bidders.find((b) => b.name === "ahilab-bidder");
|
1398 |
-
renderAhilabAd(winner, adSlot, ahilabBidder);
|
1399 |
-
options.onRender?.();
|
1400 |
-
return;
|
1401 |
-
}
|
1402 |
-
}
|
1403 |
-
};
|
1404 |
-
const getAds1 = async (messages, params, options = {}) => {
|
1405 |
-
console.log(`--- getAds (${(/* @__PURE__ */ new Date()).toISOString()}) ---`);
|
1406 |
-
console.log("[getAds] (messages)", messages);
|
1407 |
-
console.log("[getAds] (params)", params);
|
1408 |
-
console.log("[getAds] (options)", options);
|
1409 |
-
if (!monetano.settings.adUnits[0]?.code) {
|
1410 |
-
console.error("[getAds] No ad unit code found in monetano settings");
|
1411 |
-
return;
|
1412 |
-
}
|
1413 |
-
const adUnit = monetano.settings.adUnits[0];
|
1414 |
-
console.log("[getAds] Ad unit (css class): ", adUnit);
|
1415 |
-
const adContainers = document.querySelectorAll(`.${adUnit.code}`);
|
1416 |
-
console.log("[getAds] adContainers: ", adContainers);
|
1417 |
-
console.log("[getAds] total adContainers: ", adContainers.length);
|
1418 |
-
let newAdContainer = adContainers[adContainers.length - 1];
|
1419 |
-
if (!newAdContainer) {
|
1420 |
-
console.error("No ad container found");
|
1421 |
-
return;
|
1422 |
-
}
|
1423 |
-
const newDiv = document.createElement("div");
|
1424 |
-
const newDivId = `monetano-ad-${Date.now()}`;
|
1425 |
-
newDiv.id = newDivId;
|
1426 |
-
newAdContainer.appendChild(newDiv);
|
1427 |
-
let renderAdUnit = { ...adUnit };
|
1428 |
-
renderAdUnit.code = newDivId;
|
1429 |
-
try {
|
1430 |
-
await Promise.all(
|
1431 |
-
[renderAdUnit].map(async (_adUnit) => {
|
1432 |
-
const bids = await getAdsForUnit(
|
1433 |
-
monetano,
|
1434 |
-
_adUnit,
|
1435 |
-
messages,
|
1436 |
-
params,
|
1437 |
-
options,
|
1438 |
-
monetano.settings.timeout
|
1439 |
-
);
|
1440 |
-
return bids;
|
1441 |
-
})
|
1442 |
-
);
|
1443 |
-
} catch (error) {
|
1444 |
-
console.error("[getAds] Error fetching bids", error);
|
1445 |
-
}
|
1446 |
-
};
|
1447 |
-
monetano.que.forEach((fn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