PageSourceSearch

https://ai-prime-strategy.gmo/wp-content/plugins/gmo-ai-rag-chat/m…/magatama-chat.bundle.js?ver=1790243387

js ai-prime-strategy.gmo collected 2026-10-04 16:26:23 UTC 64,510 bytes, 1 lines download raw bytes

1!function(){var e;function t(e){const t=e.link;e.link=function(e){let n=e.href;const a=e.text,o=/^(https?:\/\/[^\s]+)/,i=o.test(a),s=o.test(e.href);i&&(!s||e.href.length<a.length)&&(n=a);const r=n.match(/^(https?:\/\/[^\s\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF]+)/);return r&&r[0]&&(n=r[0]),n=n.replace(/[.,))]+$/,""),t.call(this,{...e,href:n}).replace(/^<a /,'<a target="_blank" rel="noopener noreferrer" ')}}function n(e){if("string"!=typeof e)return"";let t=e.trim().replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"");try{const e=new URL(t,window.location.href);return e.hash="",e.search="",e.pathname.length>1&&(e.pathname=e.pathname.replace(/\/+$/,"")),e.toString()}catch(e){return t=t.split("#")[0].split("?")[0],t=t.replace(/\/+$/,""),t}}function a(e){try{if("string"!=typeof e)return e;if(!e.includes(".s3.amazonaws.com/")||!e.includes("index/"))return e;const t=e.includes("chatbot_id=")&&e.includes("/index/"),n=/\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/index\//.test(e);if(!t&&!n)return e;const a=new URL(e).pathname.replace(/^\/+/,""),o=a.indexOf("index/");if(-1===o)return e;let i=a.substring(o+6);i.includes(".json")&&(i=i.split(".json")[0]),i=decodeURIComponent(i);let s=i.replace(/-/g,"+").replace(/_/g,"/");for(;s.length%4!=0;)s+="=";const r=atob(s),c=Uint8Array.from(r,e=>e.charCodeAt(0)),l=new TextDecoder("utf-8").decode(c);return l.startsWith("http://")||l.startsWith("https://")?l:e}catch(t){return console.warn("convertS3UrlToDocumentUrl failed:",t),e}}function o(e){return e?e.replace(/https:\/\/[^\s<>"')]+/g,e=>a(e)):e}function i(){return{chatBody:document.querySelector("#magatama-chat-body"),chatWindow:document.querySelector("#magatama-chat-window"),clearButton:document.querySelector("#chat-clear-btn"),closeButton:document.querySelector("#chat-close-btn"),fontDecreaseBtn:document.querySelector("#chat-font-decrease-btn"),fontIncreaseBtn:document.querySelector("#chat-font-increase-btn"),inputField:document.querySelector("#magatama-chat-input"),launcher:document.querySelector("#magatama-chat-launcher"),maximizeButton:document.querySelector("#chat-maximize-btn"),minimizeButton:document.querySelector("#chat-minimize-btn"),sendButton:document.querySelector("#chat-send-btn")}}function s({convertS3UrlToDocumentUrl:e=a,normalizeReferenceUrl:t=n}={}){return{appendReferencesToMessage:function(n,a){if(!a||0===a.length||!n)return;const o=new Set,i=document.createElement("ul");if(a.forEach(n=>{if(!n||!n.fileUri)return;const a=function(e){if("string"!=typeof e)return"";try{const t=new URL(e.trim(),window.location.href);return"http:"===t.protocol||"https:"===t.protocol?t.toString():""}catch(e){return""}}(e(n.fileUri)||n.fileUri);if(!a)return;const s=t(a);if(!s||o.has(s))return;o.add(s);const r=document.createElement("li"),c=document.createElement("a");c.href=a,c.target="_blank",c.rel="noopener noreferrer",c.textContent=a,r.appendChild(c),i.appendChild(r)}),i.children.length>0){const e=document.createElement("div");e.className="references";const t=document.createElement("h5");t.textContent="参考資料:",e.appendChild(t),e.appendChild(i),n.appendChild(e)}}}}async function r(e){if(navigator.clipboard&&"function"==typeof navigator.clipboard.writeText)return void await navigator.clipboard.writeText(e);const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{if(!document.execCommand("copy"))throw new Error("execCommand copy failed")}finally{t.remove()}}function c(){const e=new Date;return`${e.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"})} ${e.toLocaleTimeString("ja-JP",{hour:"2-digit",minute:"2-digit"})}`}function l(e){e.preventDefault(),e.stopPropagation()}function d({addMessageToUI:e,chatBody:t,chatSettings:n,getSessionId:a,getState:o,logFinalAnswerToServer:i,saveCoreState:s,scrollToBottom:
1d}){t.addEventListener("click",async t=>{const u=t.target.closest(".copy-user-message-btn");if(u)return l(t),void await async function(e){const t=e.closest(".chat-message");if(!t)return;const n=t.querySelector(".message-content"),a=n?n.innerText.trim():"",o=e.parentElement.querySelector(".user-copy-feedback");try{await r(a),o&&(o.textContent="コピーしました",e.disabled=!0,setTimeout(()=>{o.textContent="",e.disabled=!1},2e3))}catch(e){console.error("ユーザーメッセージのコピーに失敗しました: ",e),o&&(o.textContent="コピー失敗",setTimeout(()=>{o.textContent=""},2e3))}}(u);const m=t.target.closest(".feedback-btn");if(m)return l(t),void await async function(e,t){const n=e.dataset.rating,a=e.parentElement;if(!a.querySelector(".selected")){a.querySelectorAll(".feedback-btn").forEach(e=>e.classList.add("disabled")),e.classList.add("selected");try{const o=t.getSessionId(),i=await async function(e,{getSessionId:t,logFinalAnswerToServer:n}){const a=e.parentElement.closest(".chat-message");let o=parseInt(a?.dataset?.logId||"0",10)||0;if(!o){const e=((a?.querySelector(".message-content"))?.innerText||"").trim();if(e){const i=await n(t(),e,[]);i&&(o=i,a.dataset.logId=String(i))}}if(!o)throw new Error("log_id could not be resolved");return o}(e,t);await async function({chatSettings:e,logId:t,rating:n,sessionId:a}){const o=e.ajax_url||`${window.location.origin}/wp-admin/admin-ajax.php`,i=await window.MagatamaNonceManager.getNonce(),s=`${o}?action=magatama_feedback_submit&log_id=${encodeURIComponent(t)}&session_id=${encodeURIComponent(a)}&rating=${encodeURIComponent(n)}&nonce=${encodeURIComponent(i||"")}`,r=await fetch(s,{method:"GET",credentials:"include"});if(!r.ok)throw new Error(`feedback submit failed: HTTP ${r.status}`);const c=await r.json();if(!c.success&&"success"!==c.data?.status)throw new Error("feedback submit returned non-success payload")}({chatSettings:t.chatSettings,logId:i,rating:n,sessionId:o}),a.querySelector(".feedback-thanks").textContent="ありがとうございます","bad"===n&&function({addMessageToUI:e,chatSettings:t,getState:n,saveCoreState:a,scrollToBottom:o}){const i=n();if(!t.contact_form_url){const t={sender:"bot",text:"ご期待に沿えず申し訳ございません。貴重なご意見として今後のサービス改善に役立てさせていただきます。恐れ入りますが、現在個別のお問い合わせには対応しておりませんこと、何卒ご了承ください。",timestamp:c()};return e(t),i.history.push(t),a(),void o()}const s={sender:"bot",text:`ご不便おかけし申し訳ありません。担当者が対応いたします。<br><a href="${t.contact_form_url}" target="_blank" rel="noopener noreferrer" class="feedback-action-btn primary">お問い合わせフォームへ</a><p class="feedback-description">下のボタンから会話ログをコピーし、お問い合わせフォームの所定の欄に貼り付けていただくと、よりスムーズにご案内が可能です。</p><button class="feedback-action-btn copy-log-btn">会話ログをコピーする</button>`,timestamp:c()};e(s),i.history.push(s),a(),o()}(t)}catch(e){console.error("Feedback submission failed:",e),a.querySelector(".feedback-thanks").textContent="エラー",a.querySelectorAll(".feedback-btn").forEach(e=>{e.classList.remove("disabled","selected")})}}}(m,{addMessageToUI:e,chatSettings:n,getSessionId:a,getState:o,logFinalAnswerToServer:i,saveCoreState:s,scrollToBottom:
1d});const g=t.target.closest(".copy-log-btn");if(g)return l(t),void await async function(e,{getState:t}){e.disabled=!0,e.textContent="コピー中...";const n=`【チャット履歴】\n--------------------------------\n${t().history.slice(0,-1).slice(-6).map(e=>{return`[${"bot"===e.sender?"チャットボット":"あなた"} - ${e.timestamp}]\n${t=e.text,(new DOMParser).parseFromString(t||"","text/html").body.textContent.trim()}\n`;var t}).join("\n")}--------------------------------\n【お問い合わせ内容】\n`;try{await r(n),e.textContent="コピーしました!"}catch(t){console.error("クリップボードへのコピーに失敗しました: ",t),e.textContent="コピー失敗",e.disabled=!1}}(g,{getState:o});const h=t.target.closest(".copy-message-btn");return h?(l(t),void await async function(e,{getState:t}){const n=e.closest(".chat-message");if(!n)return;const a=n.dataset.logId;if(!a)return void console.error("Copy failed: logId not found on message element.");const o=t().history.find(e=>String(e.logId)===String(a));let i;if(o&&void 0!==o.text)i=o.text;else{console.warn("Could not find message in history by logId. Falling back to plain text.");const e=n.querySelector(".message-content");i=e?e.innerText.trim():""}const s=e.parentElement.querySelector(".feedback-thanks");try{if(await r(i),s){const t=s.textContent;s.textContent="コピーしました",e.disabled=!0,setTimeout(()=>{s.textContent=t,e.disabled=!1},2e3)}}catch(e){if(console.error("メッセージのコピーに失敗しました: ",e),s){const e=s.textContent;s.textContent="コピー失敗",setTimeout(()=>{s.textContent=e},2e3)}}}(h,{getState:o})):void 0})}(e=window).MagatamaNonceManager=function(){let t=e.magatamaChatSettings?.nonce||null,n=0;async function a(){try{const a=e.magatamaChatSettings?.ajax_url||window.ajaxurl;if(!a)throw new Error("[MAGATAMA] ajax_url is not defined. Ensure it is set via magatama_chat_enqueue_assets().");const o=await(await fetch(`${a}?action=magatama_refresh_nonce`,{method:"GET",credentials:"same-origin"})).text();let i;try{i=JSON.parse(o)}catch{throw console.error("[MAGATAMA] Ajax returned non-JSON response:",o.substring(0,200)),new Error("Invalid JSON from admin-ajax.php")}i?.success&&i?.data?.new_nonce?(t=i.data.new_nonce,n=0,i.data.new_rest_nonce&&e.magatamaChatSettings&&(e.magatamaChatSettings.rest_nonce=i.data.new_rest_nonce),console.info("[MAGATAMA] Nonce refreshed:",t)):console.warn("[MAGATAMA] Nonce refresh failed:",i)}catch(e){console.error("[MAGATAMA] Nonce refresh error",e)}}return{getNonce:async function(){return t||await a(),n++,n>=5&&await a(),t},refreshNonce:a}}(),window.applyCustomLinkParser=t,window.magatamaChatReferences={convertS3UrlToDocumentUrl:a,normalizeReferenceUrl:n,replaceS3UrlsInText:o},window.magatamaChatMessageReferences={createChatMessageReferenceAppender:s},window.magatamaChatDomElements={getChatDomElements:i};var u="magatamaChatFontSize";function m(e,t){let n=(parseFloat(getComputedStyle(e).getPropertyValue("--chat-font-size"))||14)+t;n=Math.max(12,Math.min(20,n)),e.style.setProperty("--chat-font-size",`${n}px`),localStorage.setItem(u,n)}function g(e){return"magatama-chat-state-preview"===e.state_key}var h=!1;try{sessionStorage.removeItem("magatama_launcher_closed")}catch{}function f(){return h}function p(e){h=Boolean(e)}function y(e){return e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||22===e.code)}function w(e){const t=document.documentElement.clientWidth,n=document.documentElement.clientHeight,a=window.getComputedStyle(e);return{clientWidth:t,clientHeight:n,minWidth:parseInt(a.minWidth,10),minHeight:parseInt(a.minHeight,10)}}function S({VIEW:e,addMessageToUI:t,chatBody:n,chatSettings:a,chatWindow:o,getInitialMessageText:i,getState:s,isMobileView:r,saveCoreState:l,setState:d,setView:m}){let g=!1;
1function h(){g||(s().history.forEach(e=>t(e)),g=!0)}return{loadStateAndApply:function(){!function(e){const t=localStorage.getItem(u);t&&e.style.setProperty("--chat-font-size",`${parseFloat(t)}px`)}(o);const t="magatama-chat-state-preview"===a.state_key,f=localStorage.getItem(a.state_key);d(f&&!t?function(e,t){return function(e){return!0===e.save_window_state||1===e.save_window_state||"1"===e.save_window_state}(t)?e:{...e,isOpen:!1,minimized:!1}}(function(e){const t=JSON.parse(e);return{...t,history:Array.isArray(t.history)?t.history:[],minimized:Boolean(t.minimized),isOpen:Boolean(t.isOpen),sessionId:"string"==typeof t.sessionId?t.sessionId:null,threadId:"string"==typeof t.threadId?t.threadId:t.threadId??void 0,initialMessageText:"string"==typeof t.initialMessageText?t.initialMessageText:void 0}}(f),a):{history:[],minimized:!1,isOpen:!1,sessionId:null});const p=s();g=!1,n.innerHTML="";const y=i();if(1===p.history.length&&"bot"===p.history[0].sender&&p.history[0].text!==y&&(p.history[0].text=y,p.history[0].timestamp=c()),p.history.forEac
1h(e=>{e&&"bot"===e.sender&&!0!==e.allowFeedback&&(e.logId||e.threadId||e.md5||e.duration||e.usage)&&(e.allowFeedback=!0)}),0===p.history.length){const e={sender:"bot",text:y,timestamp:c()};p.history.push(e),l()}p.isOpen?(h(),r()?m(p.minimized?e.MINIMIZED:e.FULLSCREEN):p.minimized?m(e.MINIMIZED):m(e.NORMAL)):m(e.ICON)},renderHistoryIfNeeded:h}}function b({replaceS3UrlsInText:e}){const n=new marked.Renderer;return t(n),{renderToHtml:function(t){const a=e(t||""),o=marked.parse(a,{renderer:n});return DOMPurify.sanitize(o,{ADD_ATTR:["target"]})}}}var v='<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>',T='<span class="dashicons dashicons-admin-page" aria-hidden="true"></span>';function I(){return`\n<button class="feedback-btn" data-rating="good" title="役に立った">👍</button>\n<button class="feedback-btn" data-rating="bad" title="役に立たない">👎</button>\n<button class="copy-message-btn" title="回答をコピーする" style="background:none;border:none;cursor:pointer;padding:4px;vertical-align:middle;">${T}</button>\n<span class="feedback-thanks"></span>`}function M(e,t,n,a){return!e&&(o=function(e,t,n){return`プレビューエラー (コード${e}):\n\n${t}\n${n}`}(t,n,a),window.location.href.includes("main_color=")&&window.alert(o),!0);var o}function C({chatSettings:e}){const t=function(e){const t=e.chat_title||"GMO AI RAGチャット";return`\n\n<div id="magatama-chat-launcher" role="button" aria-label="チャットを開く">\n\n\x3c!-- アイコンをタブセッション中だけ非表示にする × ボタン(クリックは stopPropagation で本体と分離) --\x3e\n<button type="button" class="magatama-launcher-close-btn" aria-label="チャットアイコンを非表示にする" title="閉じる">${v}</button>\n\n\x3c!-- 「画像+テキスト」用のコンテナ --\x3e\n<div class="magatama-icon-image-text-wrapper" style="display: none; text-align: center;">\n\n  \x3c!-- ▼▼▼ テキストを囲む「吹き出し」を追加 ▼▼▼ --\x3e\n  <div class="magatama-icon-text-bubble">\n    <span class="magatama-icon-text"></span>\n  </div>\n\n  <img class="magatama-icon-image" src="" alt="チャットアイコン">\n</div>\n\n\x3c!-- 「画像のみ」用のコンテナ --\x3e\n<div class="magatama-icon-image-only" style="display: none;"></div>\n\n</div>\n\n<div id="magatama-chat-window" class="hidden" role="dialog" aria-labelledby="chat-header-title">\n<div class="chat-header">\n  <span id="chat-header-title">${t}</span>\n  <div class="hd_div">\n    <button id="chat-font-decrease-btn" class="font-size-btn" aria-label="文字を小さく" title="文字を小さく">A-</button>\n    <button id="chat-font-increase-btn" class="font-size-btn" aria-label="文字を大きく" title="文字を大きく">A+</button>\n    <button id="chat-clear-btn" aria-label="チャット履歴を削除" title="チャット履歴を削除"><span class="dashicons dashicons-trash" aria-hidden="true"></span></button>\n    <button id="chat-minimize-btn" aria-label="最小化する" title="最小化する"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M20 11v2H4v-2h16z"></path></svg></button>\n    <button id="chat-maximize-btn" aria-label="最大化する" title="最大化する"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M4 4h16v16H4V4zm2 2v12h12V6H6z"></path></svg></button>\n    <button id="chat-close-btn" aria-label="閉じる" title="閉じる">${v}</button>\n  </div>\n</div>\n<div class="chat-body" id="magatama-chat-body" aria-live="polite"></div>\n<div class="chat-input">\n  <textarea id="magatama-chat-input" placeholder="メッセージを入力..." rows="1" aria-label="メッセージ入力欄"></textarea>\n  <button id="chat-send-btn" class="chat-btn" aria-label="送信">\n    <span class="dashicons dashicons-arrow-up-alt" title="質問する"></span>\n  </button>\n</div>\n<div class="resizer top left"></div>\n<div class="resizer top"></div>\n<div class="resizer top right"></div>\n<div class="resizer right"></div>\n<div class="resizer bottom right"></div>\n<div class="resizer bottom"></div>\n<div class="resizer bottom left"></div>\n<div class="resizer left"></div>\n</div>`}(e);document.body.insertAdjacentHTML("beforeend",t);const n=i();return function({launcher:e}){return M(e,3,"アイコン要素(magatama-chat-launcher)の生成に失敗しました。","createLauncherHtml関数を確認してください。")}({launcher:n.launcher})?null:function(e){return Object.values(e).every(e=>null!==e)}(n)?(function({launcher:e,settings:t,fallbackIconUrl:n,fallbackIconHoverUrl:a}){if(!e||!t)return;const o=function(e){const t=Array.from(document.getElementsByTagName("script")).find(e=>(e.src||"").includes("magatama-chat/dist/magatama-chat.bundle.js"));if(!t)return{fallbackIconHoverUrl:"",fallbackIconUrl:e.icon_url};const n=t.src.split("/");n.pop(),"dist"===n[n.length-1]&&n.pop();const a=n.join("/");return{fallbackIconHoverUrl:`${a}/assets/images/chat-icon2.png`,fallbackIconUrl:`${a}/assets/images/chat-icon.png`}}
1(t),i=n||o.fallbackIconUrl,s=a||o.fallbackIconHoverUrl,r=t.icon_type||"image_text",c=t.icon_layout||"horizontal",l=t.icon_size||"m",d=t.icon_text||"",u=!!t.icon_image_url,m=t.icon_image_url||t.icon_url||i;let g=t.icon_image_url_hover||"";g||(g=u?m:s||m);const h=e.querySelector(".magatama-icon-image-only"),p=e.querySelector(".magatama-icon-image-text-wrapper"),y=e.querySelector(".magatama-icon-image"),w=e.querySelector(".magatama-icon-text");h.style.display="none",p.style.display="none",e.onmouseenter=null,e.onmouseleave=null,e.style.display=f()?"none":"block",e.classList.remove("layout-horizontal","layout-vertical","size-s","position-right_bottom","position-left_bottom","magatama-custom-icon","is-reversed"),e.classList.add(`layout-${c}`),e.classList.add(`position-${t.launcher_position||"right_bottom"}`),"s"===l&&e.classList.add("size-s"),t.launcher_extra_classes&&t.launcher_extra_classes.split(/\s+/).filter(Boolean).forEach(t=>e.classList.add(t)),"image_only"===r?(h.style.display="block",m&&(h.style.backgroundImage=`url('${m}')`,e.onmouseenter=()=>{h.style.backgroundImage=`url('${g||m}')`},e.onmouseleave=()=>{h.style.backgroundImage=`url('${m}')`})):(p.style.display="flex",y&&m&&(y.src=m,e.onmouseenter=()=>{y.src=g||m},e.onmouseleave=()=>{y.src=m}),w&&(w.textContent=d)),(m||d)&&e.classList.add("magatama-custom-icon")}({launcher:n.launcher,settings:e}),n):(M(!1,3,"チャット UI 要素の生成に失敗しました。","createChatShellHtml 関数を確認してください。"),null)}var k={ICON:"icon",MINIMIZED:"minimized",NORMAL:"normal",FULLSCREEN:"fullscreen"};function x(e){let t="message",n="";for(const a of e.split("\n"))a.startsWith("event:")?t=a.substring(6).trim():a.startsWith("data:")&&(n=a.substring(5).trim());return{eventData:n,eventType:t}}function A(e){return"object"==typeof e&&null!==e}function E(e,t){return{fullResponseText:e,references:t.references,logId:t.logId,threadId:t.threadId,duration:t.duration,contentMd5:t.contentMd5,usage:t.usage}}function _(e,t){e.receivedAnyChunk||(e.receivedAnyChunk=!0,clearTimeout(t))}function L({addMessageToUI:e,appendAIErrorBubble:t,appendReferencesToMessage:n,
1chatBody:i,getSessionId:s,getState:r,lockChatForLimitExceeded:l,logFinalAnswerToServer:d,notifyTokenLimitReached:u,restoreFailedUserMessage:m,saveCoreState:g,scrollController:h}){return{handleStreamingResponse:async(f,p)=>{if(!f.body)throw new Error("[MAGATAMA] Streaming response body is not available.");const y=f.body.getReader(),w={buffer:"",accumulatedText:"",streamStartTs:Date.now(),firstChunkTs:null,lastChunkTs:null,receivedAnyChunk:!1,finalAnswer:"",completionReceived:!1,references:[],logId:null,threadId:null,duration:null,contentMd5:null,usage:null,logSaved:!1,hasSseError:!1,sseErrorMessage:""},S=function({addMessageToUI:e,chatBody:t,getAccumulatedText:n,getState:a,scrollController:i}){const s=function({chatBody:e}){let t=!1;function n(){const t=e.querySelector(".thinking-initial"),n=e.querySelector(".thinking-preparing");t&&(t.style.display="none"),n&&(n.style.display="")}return{hideThinkingIndicator:function(){const e=document.querySelector(".thinking");e&&(e.style.display="none")},showThinkingIndicator:function(){const e=document.querySelector(".thinking");e&&(e.style.display="")},switchToPreparing:n,switchToPreparingOnFirstChunk:function(){t||(t=!0,n(),console.log("[MAGATAMA] Switched to preparing on first chunk"))},updateThinkingText:function(n){if(t)return;const a=e.querySelector(".thinking-initial");a&&n&&(a.textContent=n)}}}({chatBody:t}),r=function({getState:e}){let t=null;return{createAssistantEntry:function({allowFeedback:n=!1}={}){return t={sender:"bot",text:"",timestamp:c()},n&&(t.allowFeedback=!0),e().history.push(t),t},removeAssistantEntry:function(){if(!t)return;const n=e().history,a=n.indexOf(t);-1!==a&&n.splice(a,1),t=null},setLogId:function(e){t&&(t.logId=e)},syncAssistantEntry:function({contentMd5:e,duration:n,finalText:a,logId:o,references:i,threadId:s,usage:r}){t&&(t.text=a,t.logId=o,t.references=i,t.threadId=s,t.md5=e,t.usage=r,t.duration=n,t.allowFeedback=!0)}}}({getState:a});let l=null,d=null;const u=function({chatBody:e,getAccumulatedText:t,getMessageContentDiv:n,requestFollowScroll:a}){const i=b({replaceS3UrlsInText:o});let s=null,r=null,c=null;function l(){e.scrollTo({top:e.scrollHeight,behavior:"smooth"})}function d(){null!==s&&(cancelAnimationFrame(s),s=null)}function u({scroll:e=!0}={}){d();const o=n(),s=t();o&&s&&(o===r&&s===c||(o.innerHTML=i.renderToHtml(s),r=o,c=s),e&&(a?a():l()))}return{cancelScheduledRender:d,renderMessageImmediate:u,scheduleRender:function(e=!1){e?u():null===s&&(s=requestAnimationFrame(()=>{s=null,u()}))},smoothScroll:l}}({chatBody:t,getAccumulatedText:n,getMessageContentDiv:()=>d,requestFollowScroll:i?()=>i.requestFollowScroll():void 0});return{appendFeedbackControls:function(){if(l&&!l.querySelector(".feedback-buttons")){const e=document.createElement("div");e.className="feedback-buttons",e.innerHTML=I(),l.appendChild(e)}},ensureMessageContainer:function(){if(l&&d)return"existing";const t="bot-msg-"+Date.now();e({id:t,sender:"bot",text:"",timestamp:c()});const n=document.getElementById(t),a=n?.querySelector(".message-content")||null;return n&&a?(l=n,d=a,r.createAssistantEntry(),s.switchToPreparingOnFirstChunk(),i?.noteStreamStart(l),"created"):(n?.remove(),null)},getMessageContentDiv:()=>d,hideThinkingIndicator:s.hideThinkingIndicator,removeBotMessageContainer:function(){u.cancelScheduledRender(),l?.remove(),l=null,d=null,r.removeAssistantEntry()},renderMessageImmediate:u.renderMessageImmediate,scheduleRender:u.scheduleRender,setLogId:function(e){l&&(l.dataset.logId=String(e)),r.setLogId(e)},showThinkingIndicator:s.showThinkingIndicator,syncAssistantEntry:function({contentMd5:e,duration:t,finalText:n,logId:a,references:o,threadId:i,usage:s}){r.syncAssistantEntry({contentMd5:e,duration:t,finalText:n,logId:a,references:o,threadId:i,usage:s})},updateThinkingText:s.updateThinkingText}}({addMessageToUI:e,chatBody:i,getAccumulatedText:()=>w.accumulatedText,getState:r,scrollController:h}),v=function({appendAIErrorBubble:e,hasReceivedAnyChunk:t,hideThinkingIndicator:n,reader:a,restoreFailedUserMessage:o}){return setTimeout(()=>{if(!t()){console.warn("[MAGATAMA] SSE timeout (no chunks received)"),n(),e("サーバーの応答がタイムアウトしました。もう一度お試しください。"),o();try{a.cancel()}catch(e){console.warn("reader.cancel() failed:",e)}}},6e4)}({appendAIErrorBubble:t,hasReceivedAnyChunk:()=>w.receivedAnyChunk,hideThinkingIndicator:S.hideThinkingIndicator,reader:y,restoreFailedUserMessage:m}),T=function({addMessageToUI:e,getSessionId:t,getState:n,lockChatForLimitExceeded:o,logFinalAnswerToServer:i,notifyTokenLimitReached:s,saveCoreState:r,streamDom:l,sseTimeoutTimer:d}){return async function({eventData:u,eventType:m,streamState:g}){console.log("[MAGATAMA][RAG raw event]",{eventType:m,eventData:u}),"error"===m&&(g.hasSseError=!0,g.sseErrorMessage="サービスからエラーが返されました。");let h=!1;try{const e="message"===m&&"[DONE]"===u,n=e||"done"===m&&""===u?{}:JSON.parse(u);switch(h=!0,e?"done":m){case"status":"string"==typeof n.label&&""!==n.label?l.updateThinkingText(n.label):"thinking"===n.status&&l.updateThinkingText("回答を生成しています"),"received"===n.status?console.log("Message received"):"thinking"===n.status?l.showThinkingIndicator():"done"===n.status&&(g.completionReceived=!0,l.hideThinkingIndicator());break;case"tools-call":l.updateThinkingText("関連文書を検索しています");break;case"done":if(g.completionReceived=!0,g.hasSseError)break;n&&n.log_id&&(g.logId=n.log_id,g.logSaved=!0,l.setLogId(g.logId)),l.hideThinkingIndicator();break;case"message":!function({parsedData:e,sseTimeoutTimer:t,streamDom:n,streamState:a}){if(a.hasSseError)return;if(_(a,t),!e.content)return;a.accumulatedText+=e.content;const o=n.ensureMessageContainer();if(null===o)throw new Error("回答の表示欄を作成できませんでした。");n.scheduleRender("created"===o)}({parsedData:n,sseTimeoutTimer:d,streamDom:l,streamState:g});break;case"complete-response":await async function({getSessionId:e,logFinalAnswerToServer:t,parsedData:n,saveCoreState:a,sseTimeoutTimer:o,streamDom:i,streamState:s}){if(!s.hasSseError){if(!n||"object"!=typeof n||"string"!=typeof n.content)return s.hasSseError=!0,void(s.sseErrorMessage="回答の完了情報を読み取れませんでした。");if(s.completionReceived=!0,_(s,o),console.log("Complete response:",n),s.threadId=n.threadId||null,s.duration=n.duration||null,s.contentMd5=n.contentMd5||null,s.finalAnswer=n.content,s.accumulatedText=n.content,n.content.trim()){if(_(s,o),null===i.ensureMessageContainer())throw new Error("回答の表示欄を作成できませんでした。");i.renderMessageImmediate()}if(!s.logSaved&&s.accumulatedText.trim())try{s.logId=await t(e(),s.finalAnswer,s.references),s.logSaved=!0,i.setLogId(s.logId),console.log("[MAGATAMA] Log saved at complete-response:",s.logId),a()}catch(e){console.warn("[MAGATAMA] logFinalAnswerToServer failed:",e)}}}({getSessionId:t,logFinalAnswerToServer:i,parsedData:n,saveCoreState:r,sseTimeoutTimer:d,streamDom:l,streamState:g});break;case"tools-result":{const e=function(e){if("vector_search"!==e.tool?.name)return null;const t=e.tool.content;if(A(t)&&"string"==typeof t.fileUri)return[t];if("string"==typeof t){const e=/https:\/\/[^\s<>"')]+/g,n=[];let o;for(;null!==(o=e.exec(t));){const e=o[0];
1n.push({fileUri:e,displayUrl:a(e)})}return n}return A(t)?[t]:[]}(n);null!==e&&(g.references=e);break}case"usage-info":g.usage=n.usage||null,console.log("Token usage:",g.usage);break;case"error":if(console.error("SSE error event received:",n),!n||"object"!=typeof n)break;"RATE_LIMIT_EXCEEDED"===n.error_code&&(o(),s(n.magatama_error)),g.sseErrorMessage=function(e){const t=e.message||e.error||"サービスに接続できませんでした。",n=[];return e.error_detail&&n.push(e.error_detail),n.length>0?`${t}\n詳細: ${n.join(" / ")}`:t}(n)}}catch(t){if(console.error("Streaming event handling error:",t,"Original:",u),"error"===m||"complete-response"===m&&!h)return g.hasSseError=!0,void(g.sseErrorMessage="error"===m?"サービスからエラーが返されました。":"回答の完了情報を読み取れませんでした。");const a={id:"bot-error-"+Date.now(),sender:"bot",text:`[CLIENT ERROR]\n${t instanceof Error?t.message:String(t)}`,timestamp:c()};e(a),n().history.push(a),r()}}}({addMessageToUI:e,getSessionId:s,getState:r,lockChatForLimitExceeded:l,logFinalAnswerToServer:d,notifyTokenLimitReached:u,saveCoreState:g,streamDom:S,sseTimeoutTimer:v}),{handleStreamCompletion:M}=function({appendAIErrorBubble:e,appendReferencesToMessage:t,getSessionId:n,logFinalAnswerToServer:a,saveCoreState:o}){return{handleStreamCompletion:async function({reader:i,streamDom:s,streamState:r,sseTimeoutTimer:c,thinkingElements:l}){const d=!r.finalAnswer.trim()&&!r.accumulatedText.trim();if(function({contentEmpty:e,hasSseError:t,receivedAnyChunk:n}){return t||!n||e}({contentEmpty:d,hasSseError:r.hasSseError,receivedAnyChunk:r.receivedAnyChunk})){s.hideThinkingIndicator(),l&&l.thinkingPreparing&&(l.thinkingPreparing.style.display="none"),s.removeBotMessageContainer(),e(function({contentEmpty:e,hasSseError:t,receivedAnyChunk:n,sseErrorMessage:a}){const o=!(!a||!a.trim());return n&&!t&&e?"AIからの回答が空でした。\nしばらく時間をおいてから再度お試しください。\n\n改善しない場合は、サイト運営者にお問い合わせください。":o?`問題が発生し回答を生成できませんでした。\n\n詳細: ${a}`:"この質問に対する回答を生成できませんでした。\n質問内容を変えて再度お試しください。\n\n同じ状態が何度も続く場合は、サイト運営者にお問い合わせください。"}({contentEmpty:d,hasSseError:r.hasSseError,receivedAnyChunk:r.receivedAnyChunk,sseErrorMessage:r.sseErrorMessage}));try{i.cancel()}catch(e){}return clearTimeout(c),{fullResponseText:"",references:[],logId:null,threadId:null,duration:null,contentMd5:null,usage:null}}if(!r.completionReceived)throw s.hideThinkingIndicator(),s.removeBotMessageContainer(),clearTimeout(c),Object.assign(new Error("回答の終端イベントを受信する前に接続が終了しました。"),{isStreamInterrupted:!0});const u=r.finalAnswer&&""!==r.finalAnswer.trim()?r.finalAnswer:r.accumulatedText;if(!s.getMessageContentDiv())return console.error("[MAGATAMA] messageContentDiv is null at final render"),clearTimeout(c),E(u,r);if(r.accumulatedText=u,s.renderMessageImmediate(),t(s.getMessageContentDiv(),r.references),!r.logSaved&&u)try{const e=await a(n(),u,r.references);r.logId=e,s.setLogId(r.logId),console.log("[MAGATAMA] Log saved (fallback):",e)}catch(e){console.warn("[MAGATAMA] Fallback log save failed:",e)}return s.syncAssistantEntry({contentMd5:r.contentMd5,duration:r.duration,finalText:u,logId:r.logId,references:r.references,threadId:r.threadId,usage:r.usage}),o(),s.appendFeedbackControls(),clearTimeout(c),E(u,r)}}}({appendAIErrorBubble:t,appendReferencesToMessage:n,getSessionId:s,logFinalAnswerToServer:d,saveCoreState:g});try{await async function({handleStreamEvent:e,reader:t,streamDom:n,streamState:a}){const o=new TextDecoder("utf-8");for(;;){const{done:n,value:i}=await t.read();if(n){if(a.lastChunkTs){const e=new Date(a.lastChunkTs).toISOString(),t=a.lastChunkTs-a.streamStartTs,n=a.firstChunkTs?a.lastChunkTs-a.firstChunkTs:null;console.log("[MAGATAMA][SSE] last chunk received",{time:e,msSinceStart:t,msSinceFirstChunk:n})}break}if(!a.firstChunkTs){a.firstChunkTs=Date.now();const e=new Date(a.firstChunkTs).toISOString();console.log("[MAGATAMA][SSE] first chunk received",{time:e,msSinceStart:a.firstChunkTs-a.streamStartTs})}a.lastChunkTs=Date.now(),a.buffer+=o.decode(i,{stream:!0});const s=a.buffer.split(/\r?\n\r?\n/);a.buffer=s.pop()||"";for(const t of s){const{eventData:n,eventType:o}=x(t);(n||["done","error","complete-response"].includes(o))&&await e({eventData:n,eventType:o,streamState:a})}}}({handleStreamEvent:T,reader:y,streamDom:S,streamState:w})}catch(e){throw clearTimeout(v),e&&"object"==typeof e&&(e.isStreamInterrupted=!0),e}return M({reader:y,streamDom:S,streamState:w,sseTimeoutTimer:v,thinkingElements:p})}}}function B(e){e?.thinkingInitial?.remove(),e?.thinkingPreparing?.remove()}function F({addMessageToUI:e,attachFeedbackToLatestBotMessage:t,buildChatSendErrorMessage:n,buildHeaders:a,chatBody:o,chatSettings:i,getSessionId:s,getState:r,handleStreamingResponse:l,inputField:d,markIdle:u,markSending:m,saveCoreState:g,scrollC
1ontroller:h,scrollToBottom:f,setCurrentFetchController:p,throwChatResponseError:y}){function w(){return!h||h.isFollowing()&&!h.isClampStopped()}async function S(e,t){const n=await async function({chatSettings:e,getSessionId:t,messageText:n,state:a}){const o=function(e){return e.threadId||(e.threadId="10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(Number(e)^crypto.getRandomValues(new Uint8Array(1))[0]&15>>Number(e)/4).toString(16))),e.threadId}(a),i=await window.MagatamaNonceManager.getNonce();return{message:n,context_url:window.location.href,context_title:document.title,context_key:e.context_key,context_label:e.context_label,session_id:t(),is_logged_in_user:window.magatamaChatSettings?.is_logged_in_user||"0",mgs_member_label:(window.magatamaChatSettings?.mgs_member_label||["all"]).join(","),thread_id:o,nonce:i}}({chatSettings:i,getSessionId:s,messageText:e,state:r()}),o=await async function(e,t){let n=`${e.api_url}/${t}`;try{const t=e.api_url.replace(/\/message\/?$/,"");try{const a=await fetch(t,{method:"GET",credentials:"include"});401===a.status?(console.warn("[MAGATAMA] BasicAuth detected, switching to admin-ajax route."),n=`${e.ajax_url}?action=magatama_chat_message`):404===a.status&&console.info("[MAGATAMA] REST route not found, keep default route (local dev).")}catch(e){console.warn("[MAGATAMA] REST availability check skipped:",e)}}catch(e){console.warn("[MAGATAMA] REST check skipped:",e)}return n}(i,n.thread_id);let c={"Content-Type":"application/json"};try{c=await a()}catch(e){console.warn("[MAGATAMA] Nonce header skipped (local environment):",e)}return await fetch(o,{method:"POST",headers:c,body:JSON.stringify(n),credentials:"include",signal:t.signal})}return{sendMessage:async function(a){const i={sender:"user",text:a,timestamp:c()};e(i),r().history.push(i),d.value="",d.style.height="auto",h?.noteUserSend(),f(),m();const s=new AbortController;p(s);const b=setTimeout(()=>{s.abort()},18e5),v=function(e){const t=document.createElement("div");t.className="chat-message bot thinking",t.innerHTML='<div class="thinking thinking-initial">考え中</div>',e.appendChild(t);const n=document.createElement("div");return n.className="chat-message bot thinking",n.innerHTML='<div class="thinking thinking-preparing" style="display:none;">回答を準備中</div>',e.appendChild(n),{thinkingInitial:t,thinkingPreparing:n}}(o);f();try{let n,o=await S(a,s);if(401!==o.status&&403!==o.status||(console.warn(`[MAGATAMA] HTTP ${o.status} - refreshing nonce and retrying once.`),await window.MagatamaNonceManager.refreshNonce(),o=await S(a,s)),o.ok||(B(v),await y(o)),function(e){const t=e.headers.get("content-type");return Boolean(t&&(t.includes("text/event-stream")||t.includes("application/octet-stream")))}(o)){if(n=await l(o,v),B(v),!n.fullResponseText)return;if(w()&&f(),!t(n.logId)){B(v),n=await async function(e){const t=(await e.json()).data;let n=null,a=null,o=null,i=null;return(t||t.answer)&&(t.threadId&&(n=t.threadId),t.duration&&(a=t.duration),t.contentMd5&&(o=t.contentMd5),t.usage&&(i=t.usage)),{fullResponseText:"",references:[],logId:null,threadId:n,duration:a,contentMd5:o,usage:i}}(o);const t={sender:"bot",text:n.fullResponseText,timestamp:c(),logId:n.logId,references:n.references};e(t),r().history.push(t)}}}catch(t){if(B(v),"AbortError"!==t.name){console.error("Bot応答エラー:",t);const a={sender:"bot",text:n(t),timestamp:c()};e(a),r().history.push(a),g(),w()&&f()}}finally{clearTimeout(b),u(),p(null),g(),h?.noteStreamEnd(),w()&&f()}}}}function R({chatSettings:e,getCurrentFetchController:t,getSessionId:n,getWpHeaders:a,inputField:o,maxMessageLength:i,sendMessage:s}){return async function(){const r=t();if(r){r.abort();try{await async function({chatSettings:e,getSessionId:t,getWpHeaders:n}){const a="function"==typeof n?await n():{},o=await window.MagatamaNonceManager.getNonce();await fetch(e.interrupt_url,{method:"POST",headers:a,body:JSON.stringify({session_id:t(),nonce:o})})}({chatSettings:e,getSessionId:n,getWpHeaders:a})}catch(e){console.error("Failed to send interruption signal:",e)}return}const c=o.value.trim();""!==c&&(Array.from(c).length>i?alert(`メッセージは${i}文字以内で入力してください。`):s(c))}}function z(e){const{appState:t,chatSettings:n,elements:a,maxMessageLength:o,messageRenderer:i,scrollController:s,scrollToBottom:r,sendUi:l,statePersistence:d}=e,{chatBody:u,inputField:m,sendButton:g}=a,{getCurrentFetchController:h,getSessionId:f,getState:p,setCurrentFetchController:y}=t,{markIdle:w,markSending:S}
1=l,{addMessageToUI:b,appendReferencesToMessage:v,attachFeedbackToLatestBotMessage:T}=i,{saveCoreState:I}=d,{buildHeaders:M,getWpHeaders:C,logFinalAnswerToServer:k}=function({chatSettings:e}){function t(){return{"Content-Type":"application/json","X-WP-Nonce":window.magatamaChatSettings?.rest_nonce||""}}return{buildHeaders:async function(e={}){const t=window.magatamaChatSettings?.rest_nonce;return await window.MagatamaNonceManager.getNonce(),{"Content-Type":"application/json","X-WP-Nonce":t,...e}},getWpHeaders:t,logFinalAnswerToServer:async(n,a,o=[])=>{const i=e.api_url.replace("/message","/log-update"),s={session_id:n,answer:a,references:o,nonce:await window.MagatamaNonceManager.getNonce()};try{const e=await t(),n=await fetch(i,{method:"POST",headers:e,body:JSON.stringify(s)});if(!n.ok)return console.error("最終回答のロギングに失敗しました。HTTP Status:",n.status),null;const a=await n.json(),o=a?.log_id??a?.data?.log_id??a?.data?.id??null;return null!=o?o:(console.warn("[MAGATAMA] log_id not found in response:",a),null)}catch(e){return console.error("最終回答ロギングAPIへの通信も失敗しました:",e),null}}}}({chatSettings:n}),{appendAIErrorBubble:x,buildChatSendErrorMessage:A,lockChatForLimitExceeded:E,notifyTokenLimitReached:_,restoreFailedUserMessage:B,throwChatResponseError:z}=function({addMessageToUI:e,chatSettings:t,getState:n,inputField:a,saveCoreState:o,sendButton:i}){return{appendAIErrorBubble:function(t){if(!document.getElementById("magatama-chat-body"))return;const a={id:"bot-error-"+Date.now(),sender:"bot",text:t,timestamp:c()};e(a),n().history.push(a),o()},buildChatSendErrorMessage:function(e){if(!navigator.onLine)return"ネットワーク接続のエラーが発生しました。\n以下をご確認の上、再度お試しください。\n\n・Wi-Fi やインターネット接続が正常か確認してください\n・VPN をご利用の場合は接続状態を確認してください\n・ページを再読み込みしてから再度お試しください";if(e&&e.isStreamInterrupted)return"回答の受信が途中で切断されました。\nお手数ですが、もう一度お試しください。\n\n同じ状態が何度も続く場合は、サイト運営者にお問い合わせください。";const t=String(e&&e.message||"").toLowerCase();return e instanceof TypeError&&(t.includes("failed to fetch")||t.includes("networkerror")||t.includes("network error")||t.includes("load failed")||t.includes("net::err_"))?"ネットワーク接続のエラーが発生しました。\n以下をご確認の上、再度お試しください。\n\n・Wi-Fi やインターネット接続が正常か確認してください\n・VPN をご利用の場合は接続状態を確認してください\n・ページを再読み込みしてから再度お試しください":e&&e.isServerProvidedMessage?e.message:`申し訳ありません、エラーが発生しました。画面をリロードして再度お試しください。: ${e.message}`},lockChatForLimitExceeded:function(){a&&(a.disabled=!0,a.placeholder="無料版シリアルの利用上限に達しました"),i&&(i.disabled=!0)},notifyTokenLimitReached:function e(n){const a=e;if(a._sent)return;a._sent=!0;const o=t.ajax_url||window.location.origin+"/wp-admin/admin-ajax.php",i=t.nonce||"";fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({action:"magatama_set_token_limit_reached",nonce:i,magatama_error:JSON.stringify(n||{})})}).catch(function(e){console.warn("[MAGATAMA] notifyTokenLimitReached failed:",e)})},restoreFailedUserMessage:function(){const e=document.getElementById("magatama-chat-input");e&&window.lastUserMessage&&(e.value=window.lastUserMessage)},throwChatResponseError:async function(e){if(404===e.status)throw new Error("ページが見つかりませんでした。しばらくしてから再度お試しください。");let t,n="";try{n=await e.text()}catch(e){console.error("[MAGATAMA] Failed to read error body:",e)}try{t=JSON.parse(n)}catch{t=null}if(!t||"object"!=typeof t)throw console.error("[MAGATAMA ERROR BODY]",n),new Error(`HTTP ${e.status}`);const a=t.message||`サーバーエラー: ${e.status}`,o=new Error(a);throw o.isServerProvidedMessage=Boolean(t.message),o}}}({addMessageToUI:b,chatSettings:n,getState:p,inputField:m,saveCoreState:I,sendButton:g}),{handleStreamingResponse:W}=L({addMessageToUI:b,appendAIErrorBubble:x,appendReferencesToMessage:v,chatBody:u,getSessionId:f,getState:p,lockChatForLimitExceeded:E,logFinalAnswerToServer:k,notifyTokenLimitReached:_,restoreFailedUserMessage:B,saveCoreState:I,scrollController:s}),{sendMessage:N}=F({addMessageToUI:b,attachFeedbackToLatestBotMessage:T,buildChatSendErrorMessage:A,buildHeaders:M,chatBody:u,chatSettings:n,getSessionId:f,getState:p,handleStreamingResponse:W,inputField:m,markIdle:w,markSending:S,saveCoreState:I,scrollController:s,scrollToBottom:r,setCurrentFetchController:y,throwChatResponseError:z});return{handleSendButtonClick:R({chatSettings:n,getCurrentFetchController:h,getSessionId:f,getWpHeaders:C,inputField:m,maxMessageLength:o,sendMessage:N}),logFinalAnswerToServer:k}}document.addEventListener("DOMContentLoaded",function(){if(e=window.location.pathname,/(^|\/)wp-admin(?:\/|$)/.test(e))return;var e;if(document.getElementById("magatama-chat-launcher"))return;
1const t=function(){if(M(void 0!==window.magatamaChatSettings,1,"PHPから設定値(magatamaChatSettings)が渡されませんでした。","プラグインのメインファイルにある magatama_chat_enqueue_assets 関数を確認してください。"))return null;if(M("undefined"!=typeof DOMPurify&&"function"==typeof DOMPurify.sanitize,58,"Markdown 表示に必要な DOMPurify が読み込まれませんでした。","同梱ライブラリの読み込み設定を確認してください。"))return null;if(M("undefined"!=typeof marked&&"function"==typeof marked.Renderer&&"function"==typeof marked.parse,59,"Markdown 表示に必要な marked が読み込まれませんでした。","同梱ライブラリの読み込み設定を確認してください。"))return null;const e=function(e={},t=window.location.origin){return{api_url:`${t}/wp-json/magatama-chat/v1/message`,feedback_submit_url:"/wp-json/magatama-chat/v1/feedback-submit",interrupt_url:"/wp-json/magatama-chat/v1/interrupt",icon_url:"./assets/images/chat-icon.png",icon_image_url:"",icon_image_url_hover:"",icon_text:"",icon_type:"image_text",icon_layout:"horizontal",icon_size:"m",launcher_extra_classes:"",launcher_position:"right_bottom",maximized_top_offset:0,state_key:"magatamaChatState",size_key:"magatamaChatSize",position_key:"magatamaChatPosition",is_logged_in_user:!1,contact_form_url:"",...e}}(window.magatamaChatSettings||{});return g(t=e)||!t.contract_expired||localStorage.getItem(t.state_key)?(function(e,t=document.documentElement,n=window.location.search){const a=g(e)?new URLSearchParams(n).get("chat_theme"):"";"dark"===String(a||e.theme||"light").toLowerCase()?t.classList.add("dark-mode"):t.classList.remove("dark-mode")}(e),{chatSettings:e,getInitialMessageText:()=>function(e){return e.initial_message_text||"こんにちは。ご質問があればどうぞ。"}(e),maxMessageLength:1e4}):null;var t}();t&&function(e){const t=function(e){const{chatSettings:t,getInitialMessageText:n,maxMessageLength:a}=e,o=C({chatSettings:t});if(!o)return null;const{chatBody:i,chatWindow:r,clearButton:c,inputField:l,launcher:d,maximizeButton:u,minimizeButton:m,sendButton:g}=o,h=function({chatWindow:e,maximizeButton:t,minimizeButton:n}){function a(e,t){e.setAttribute("aria-label",t),e.title=t}return{updateButtonVisibility:function(){if(!e)return;const o=window.innerWidth<768,i=e.classList.contains("is-maximized"),s=e.classList.contains("is-minimized")||e.classList.contains("minimized");if(a(t,i&&!o?"元のサイズに戻す":"最大化する"),a(n,s?"元のサイズに戻す":"最小化する"),o)return t.style.display=s?"inline-flex":"none",void(n.style.display="inline-flex");t.style.display="inline-flex",n.style.display="inline-flex"}}}({chatWindow:r,maximizeButton:u,minimizeButton:m}),w=function({chatSettings:e}){return{clearStoredWindowRect:function(){localStorage.removeItem(e.position_key),localStorage.removeItem(e.size_key)},createPcWindowStateSaver:function({chatWindow:t,isMobileView:n}){return function({includeSize:a}){if(!e.save_window_state||n())return;if(t.classList.contains("is-maximized"))return;const o=t.getBoundingClientRect(),i=t.style.top||o.top+"px",s=t.style.left||o.left+"px";if(!a)return r={top:i,left:s},void localStorage.setItem(e.position_key,JSON.stringify(r));var r;!function(t){localStorage.setItem(e.position_key,JSON.stringify({top:t.top,left:t.left})),localStorage.setItem(e.size_key,JSON.stringify({width:t.width,height:t.height}))}({top:i,left:s,width:t.style.width||o.width+"px",height:t.style.height||o.height+"px"})}},getStoredPosition:function(){try{return JSON.parse(localStorage.getItem(e.position_key)||"null")}catch{return null}},getStoredSize:function(){try{return JSON.parse(localStorage.getItem(e.size_key)||"null")}catch{return null}}}}({chatSettings:t}),v=function(){let e={history:[],minimized:!1,isOpen:!1,sessionId:null},t=null;return{getCurrentFetchController:()=>t,getSessionId:()=>function(e){if(e.sessionId)return e.sessionId;const t=1===performance.navigation.type;let n=sessionStorage.getItem("magatama_session_id");return n&&!t||(n=Date.now().toString(36)+Math.random().toString(36).substring(2),sessionStorage.setItem("magatama_session_id",n)),e.sessionId=n,n}(e),getState:()=>e,setCurrentFetchController:e=>{t=e},setState:t=>{e=t}}}(),M=function({chatBody:e,chatWindow:t}){let n=!0,a=!1,o=null,i=null;function s(){return e.scrollHeight-e.scrollTop-e.clientHeight<=30}function r(){const c=i||(i=document.createElement("button"),i.type="button",i.className="
1chat-jump-latest-btn hidden",i.setAttribute("aria-label","最新のメッセージへ移動"),i.textContent="↓ 最新へ",i.addEventListener("click",()=>{n=!0,a=!1,o=null,e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),r()}),t.appendChild(i),i),l=!s();if(l){const e=t.querySelector(".chat-input"),n=e?e.offsetHeight:60;c.style.bottom=`${n+12}px`}c.classList.toggle("hidden",!l)}return e.addEventListener("wheel",e=>{e.deltaY<0&&(n=!1,r())},{passive:!0}),e.addEventListener("touchmove",()=>{n=!1,r()},{passive:!0}),e.addEventListener("scroll",()=>{s()&&(n=!0),r()},{passive:!0}),{isClampStopped:function(){return a},isFollowing:function(){return n},noteStreamEnd:function(){o=null,r()},noteStreamStart:function(e){o=e},noteUserSend:function(){n=!0,a=!1},requestFollowScroll:function(){if(!n)return void r();const t=e.scrollHeight-e.clientHeight;let i=t;if(a=!1,o&&o.isConnected){const n=o.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-8;i=Math.min(t,Math.max(0,n)),a=n<t,a&&e.scrollTop>i+1&&s()&&(a=!1)}i>e.scrollTop+1?e.scrollTo({top:i,behavior:"smooth"}):r()}}}({chatBody:i,chatWindow:r}),x=function({clearButton:e,inputField:t,sendButton:n}){return{markIdle:function(){n.innerHTML='<span class="dashicons dashicons-arrow-up-alt" title="質問する"></span>',n.setAttribute("aria-label","送信"),n.classList.remove("magatama-stop-button"),t.disabled=!1,t.focus(),e.disabled=!1,e.classList.remove("disabled")},markSending:function(){n.innerHTML='<span class="magatama-send-spinner" aria-hidden="true"></span><span title="応答を停止">■</span>',n.setAttribute("aria-label","応答を停止"),n.classList.add("magatama-stop-button"),t.disabled=!0,e.disabled=!0,e.classList.add("disabled")}}}({clearButton:c,inputField:l,sendButton:g}),A=function({chatSettings:e,chatWindow:t}){return{adjustWindowPosition:function(){if("1"===t.dataset.isDefaultPosition||window.innerWidth<768||t.classList.contains("is-maximized")||"1"===t.dataset.dragging)return;const e=t.getBoundingClientRect();let n=parseFloat(t.style.top||e.top),a=parseFloat(t.style.left||e.left);n<0&&(n=0),n+e.height>window.innerHeight&&(n=window.innerHeight-e.height),a<0&&(a=0),a+e.width>window.innerWidth&&(a=window.innerWidth-e.width),(t.style.top||t.style.left)&&(t.style.top=n+"px",t.style.left=a+"px")},resetWindowToDefaultPosition:function(){t.style.top="auto",t.style.left="auto",t.style.right="",t.style.bottom="",t.style.transform="none";const n=e.launcher_position||"right_bottom";t.style.bottom="20px",n.includes("left")?(t.style.left="20px",t.style.right="auto"):(t.style.right="20px",t.style.left="auto"),t.dataset.isDefaultPosition="1"},resetWindowToDefaults:function(){t.style.width="",t.style.height="",t.style.top="",t.style.left="",t.style.right="",t.style.bottom="",t.style.transform=""}}}({chatSettings:t,chatWindow:r}),{appendReferencesToMessage:E}=s(),_=function({appendReferencesToMessage:e,chatBody:t}){const n=b({replaceS3UrlsInText:e=>e});return{addMessageToUI:a=>{const o=document.createElement("div");o.className=`chat-message ${a.sender}`,a.id&&(o.id=a.id),a.logId&&(o.dataset.logId=a.logId);const i=document.createElement("div");if(i.className="message-content","bot"===a.sender?i.innerHTML=n.renderToHtml(a.text||""):i.textContent=a.text,o.appendChild(i),"bot"===a.sender&&e(i,a.references),"user"===a.sender){const e=document.createElement("div");e.className="user-copy-container",e.innerHTML=`\n<button class="copy-user-message-btn" title="送信メッセージをコピーする" style="background: none; border: none; cursor: pointer; padding: 4px; vertical-align: middle;">${T}</button>\n<span class="user-copy-feedback"></span>`,o.appendChild(e)}if("bot"===a.sender&&(a.logId||!0===a.allowFeedback)){const e=document.createElement("div");e.className="feedback-buttons",e.innerHTML=I(),o.appendChild(e)}const s=document.createElement("span");s.className="chat-timestamp",s.textContent=a.timestamp,o.appendChild(s),t.appendChild(o)},appendReferencesToMessage:e,attachFeedbackToLatestBotMessage:e=>{const n=t.querySelectorAll(".chat-message.bot"),a=n[n.length-1],o=a?a.querySelector(".message-content"):null;if(!a||!o)return!1;if(e&&(a.dataset.logId=e),!a.querySelector(".feedback-buttons")){const e=document.createElement("div");e.className="feedback-buttons",e.innerHTML=I(),a.appendChild(e)}return!0}}}({appendReferencesToMessage:E,chatBody:i}),L=function({addMessageToUI:e,chatBody:t,chatSettings:n,getInitialMessageText:a,getState:o}){const i=()=>
1{if(!t||t.querySelector(".magatama-auto-trim-notice"))return;const e=document.createElement("div");e.className="magatama-auto-trim-notice",e.setAttribute("role","status"),e.textContent="容量の上限により、古いチャット履歴が自動削除されました。",t.insertBefore(e,t.firstChild)};return{saveCoreState:()=>{const s=o(),r=()=>JSON.stringify({history:s.history,minimized:s.minimized,isOpen:s.isOpen,sessionId:s.sessionId,initialMessageText:a()});try{return void localStorage.setItem(n.state_key,r())}catch(e){if(!y(e))return void console.warn("[MAGATAMA] Failed to save chat state:",e)}let c=!1;for(;s.history.length>3;){s.history.splice(1,2),c=!0;try{localStorage.setItem(n.state_key,r());break}catch(e){if(!y(e)){console.warn("[MAGATAMA] Failed to save chat state after trim:",e);break}}}c&&((s.isOpen||t.querySelector(".chat-message"))&&(t.innerHTML="",s.history.forEach(t=>e(t))),i(),console.info("[MAGATAMA] Chat history auto-trimmed due to storage quota."))},showAutoTrimNotice:i}}({addMessageToUI:_.addMessageToUI,chatBody:i,chatSettings:t,getInitialMessageText:n,getState:v.getState}),B=function({chatSettings:e,chatWindow:t,getState:n,getStoredPosition:a,getStoredSize:o,launcher:i,resetWindowToDefaultPosition:s,saveCoreState:r,updateButtonVisibility:c}){const l=()=>window.innerWidth<768,{applyPosition:d}=function({chatWindow:e,getStoredPosition:t,getStoredSize:n,isMobileView:a,resetWindowToDefaultPosition:o}){return{applyPosition:function({applySize:i}){if(a())return;const s=t(),r=i?n():null;s&&"string"==typeof s.top&&"string"==typeof s.left&&!Number.isNaN(parseFloat(s.top))&&!Number.isNaN(parseFloat(s.left))&&parseFloat(s.top)>=0&&parseFloat(s.left)>=0&&parseFloat(s.top)<window.innerHeight?(e.style.top=s.top,e.style.left=s.left,e.style.right="auto",e.style.bottom="auto",e.style.transform="none",delete e.dataset.isDefaultPosition,i&&r&&!e.classList.contains("is-minimized")&&(e.style.width=r.width||"",e.style.height=r.height||"")):o()}}}({chatWindow:t,getStoredPosition:a,getStoredSize:o,isMobileView:l,resetWindowToDefaultPosition:s}),u=()=>{const n=(()=>{const t=Number.parseInt(e?.maximized_top_offset,10);return!Number.isFinite(t)||t<0?0:Math.min(t,300)})();t.style.top=`${n}px`,t.style.left="0",t.style.right="auto",t.style.bottom="auto",t.style.transform="none",t.style.position="fixed",t.style.width="100vw",t.style.height=n>0?`calc(100vh - ${n}px)`:"100vh"};return{VIEW:k,getCurrentView:()=>t.classList.contains("hidden")?k.ICON:t.classList.contains("is-maximized")?k.FULLSCREEN:t.classList.contains("is-minimized")||t.classList.contains("minimized")?k.MINIMIZED:k.NORMAL,isMobileView:l,setView:e=>{(e=>{const a=n(),o=t.classList.contains("is-maximized");t.classList.remove("closing","is-maximized","is-minimized","minimized"),o&&e!==k.FULLSCREEN&&(t.style.width="",t.style.height="",t.style.top="",t.style.left="",t.style.right="",t.style.bottom="",t.style.transform="",t.style.position=""),e===k.ICON?(t.classList.add("hidden"),!0===a.isOpen?(p(!1),i.style.display="block"):i.style.display=f()?"none":"block",a.isOpen=!1):(t.classList.remove("hidden"),i.style.display="none",a.isOpen=!0,l()?e===k.MINIMIZED?(t.classList.add("minimized"),a.minimized=!0):(t.classList.add("is-maximized"),u(),t.classList.remove("minimized"),a.minimized=!1):e===k.MINIMIZED?(t.classList.add("is-minimized"),a.minimized=!0):e===k.FULLSCREEN?(t.classList.add("is-maximized"),u()):e===k.NORMAL&&(t.classList.remove("hidden"),t.classList.remove("is-maximized","is-minimized","minimized"),a.minimized=!1,t.style.width="",t.style.height=""))})(e),l()||e===k.FULLSCREEN||e===k.ICON||d({applySize:e===k.NORMAL}),r(),c()}}}({chatSettings:t,chatWindow:r,getState:v.getState,getStoredPosition:w.getStoredPosition,getStoredSize:w.getStoredSize,launcher:d,resetWindowToDefaultPosition:A.resetWindowToDefaultPosition,saveCoreState:L.saveCoreState,updateButtonVisibility:h.updateButtonVisibility});return{appState:v,chatSettings:t,elements:o,maxMessageLength:a,messageRenderer:_,savePcWindowState:w.createPcWindowStateSaver({chatWindow:r,isMobileView:B.isMobileView}),scrollController:M,scrollToBottom:()=>function(e){setTimeout(()=>{e&&(e.scrollTop=e.scrollHeight)},50)}(i),sendUi:x,stateLoader:S({VIEW:B.VIEW,addMessageToUI:_.addMessageToUI,chatBody:i,chatSettings:t,chatWindow:r,getInitialMessageText:n,getState:v.getState,isMobileView:B.isMobileView,saveCoreState:L.saveCoreState,setState:v.setState,setView:B.setVie
1w}),statePersistence:L,windowControls:h,windowPosition:A,windowStorage:w,windowView:B}}(e);t&&function({foundation:e,messageServices:t}){const{appState:n,chatSettings:a,elements:o,messageRenderer:i,savePcWindowState:s,scrollToBottom:r,stateLoader:l,statePersistence:h,windowControls:f,windowPosition:y,windowStorage:S,windowView:b}=e,{chatBody:v,chatWindow:T,clearButton:I,closeButton:M,fontDecreaseBtn:C,fontIncreaseBtn:k,inputField:x,launcher:A,maximizeButton:E,minimizeButton:_,sendButton:L}=o,{getSessionId:B,getState:F,setState:R}=n,{adjustWindowPosition:z,resetWindowToDefaultPosition:W,resetWindowToDefaults:N}=y,{addMessageToUI:D}=i,{saveCoreState:U}=h,{VIEW:P,getCurrentView:O,isMobileView:H,setView:$}=b,{updateButtonVisibility:V}=f,{clearStoredWindowRect:q}=S,{loadStateAndApply:j,renderHistoryIfNeeded:G}=l,{handleSendButtonClick:J,logFinalAnswerToServer:X}=t;d({addMessageToUI:D,chatBody:v,chatSettings:a,getSessionId:B,getState:F,logFinalAnswerToServer:X,saveCoreState:U,scrollToBottom:r}),function({chatWindow:e,fontDecreaseBtn:t,fontIncreaseBtn:n}){e&&t&&n&&(t.addEventListener("click",()=>m(e,-1)),n.addEventListener("click",()=>m(e,1)))}({chatWindow:T,fontDecreaseBtn:C,fontIncreaseBtn:k}),function({VIEW:e,addMessageToUI:t,chatSettings:n,chatWindow:a,clearButton:o,clearStoredWindowRect:i,closeButton:s,getCurrentView:r,getState:l,isMobileView:d,launcher:m,loadStateAndApply:h,renderHistoryIfNeeded:f,maximizeButton:y,minimizeButton:w,resetWindowToDefaultPosition:S,resetWindowToDefaults:b,saveCoreState:v,savePcWindowState:T,scrollToBottom:I,setState:M,setView:C,updateButtonVisibility:k}){function x(e){f(),C(e)}m.addEventListener("click",()=>{x(d()?e.FULLSCREEN:e.NORMAL)});const A=m.querySelector(".magatama-launcher-close-btn");A&&A.addEventListener("click",e=>{e.stopPropagation(),g(n)?function(){if(document.querySelector(".magatama-preview-close-note"))return;const e=document.createElement("div");e.className="magatama-preview-close-note",e.setAttribute("role","status"),document.body.appendChild(e),setTimeout(()=>{e.textContent="プレビューでは非表示は保存されません。ページを再読み込みするとアイコンが再表示されます。"},50),setTimeout(()=>{e.remove()},6e3)}():p(!0),m.style.display="none"});let E=!1;s.addEventListener("click",()=>{const o=()=>function({VIEW:e,chatWindow:t,clearStoredWindowRect:n,resetWindowToDefaults:a,setView:o}){const i=t.style.transition;t.style.transition="none",t.classList.remove("closing"),n(),o(e.ICON),a(),delete t.dataset.isDefaultPosition,window.requestAnimationFrame(()=>{t.style.transition=i})}({VIEW:e,chatWindow:a,clearStoredWindowRect:i,resetWindowToDefaults:b,setView:C});if(E)return;const s=String(n.closing_message_text||"").trim();if(!s)return void o();const r=l().history,d=r[r.length-1];if(d&&"bot"===d.sender&&d.text===s)return void o();const u={sender:"bot",text:s,timestamp:c()};t(u),r.push(u),v(),I(),E=!0,setTimeout(()=>{E=!1,o()},2e3)}),w.addEventListener("click",()=>{if(d())return void x(r()===e.MINIMIZED?e.FULLSCREEN:e.MINIMIZED);const t=r()===e.MINIMIZED?e.NORMAL:e.MINIMIZED;t===e.MINIMIZED&&n.save_window_state&&T({includeSize:!1}),x(t)}),y.addEventListener("click",()=>{if(!d())return r()===e.FULLSCREEN?(x(e.NORMAL),a.style.width="",a.style.height="",a.style.top="",a.style.left="",a.style.right="",a.style.bottom="",a.style.transform="",void S()):void x(e.FULLSCREEN);x(e.FULLSCREEN)}),o.addEventListener("click",()=>{window.confirm("チャット履歴をすべて削除しますか?")&&function({chatSettings:e,chatWindow:t,loadStateAndApply:n,resetWindowToDefaultPosition:a,setState:o,updateButtonVisibility:i}){localStorage.removeItem(e.state_key),localStorage.removeItem(e.size_key),localStorage.removeItem(e.position_key),localStorage.removeItem(u),o({history:[],minimized:!1,isOpen:!1,sessionId:null}),sessionStorage.removeItem("magatama_session_id"),t.classList.remove("is-maximized","is-minimized","minimized"),t.style.cssText="",t.style.setProperty("--chat-font-size","14px"),o({history:[],minimized:!1,isOpen:!1,sessionId:null}),n(),window.innerWidth>=768&&a(),i()}({chatSettings:n,chatWindow:a,loadStateAndApply:h,resetWindowToDefaultPosition:S,setState:M,updateButtonVisibility:k})})}({VIEW:P,addMessageToUI:D,chatSettings:a,chatWindow:T,clearButton:I,clearStoredWindowRect:q,closeButton:M,getCurrentView:O,getState:F,isMobileView:H,launcher:A,loadStateAndApply:j,renderHistoryIfNeeded:G,maximizeButton:E,minimizeButton:_,resetWindowToDefaultPosition:W,resetWindowToDefaults:N,saveCoreState:U,savePcWindowState:s,scrollToBottom:r,setState:R,setVie
1w:$,updateButtonVisibility:V}),function({handleSendButtonClick:e,inputField:t,sendButton:n}){let a=!1,o=0;n.addEventListener("click",e),t.addEventListener("compositionstart",()=>{a=!0}),t.addEventListener("compositionend",()=>{a=!1,o=Date.now()}),t.addEventListener("keydown",t=>{(function(e,t){return t||e.isComposing||229===e.keyCode||229===e.which||"Process"===e.key})(t,a)||Date.now()-o<50||"Enter"!==t.key||t.shiftKey||(t.preventDefault(),e())}),t.addEventListener("input",()=>{t.style.height="auto",t.style.height=t.scrollHeight+"px"})}({handleSendButtonClick:J,inputField:x,sendButton:L}),function({adjustWindowPosition:e,chatWindow:t,savePcWindowState:n,updateButtonVisibility:a}){if(!t||window.innerWidth<768)return;const o=t.querySelector(".chat-header");if(!o)return;let i,s,r,c,l,d,u,m,g=!1,h=!1,f=null,p=null,y=null,S={};function b(){if(null!==p&&(window.cancelAnimationFrame(p),p=null),y){const e=y.clientX-i,n=y.clientY-s;let a=r.left+e,o=r.top+n;a=Math.max(0,Math.min(a,l.width-c.width)),o=Math.max(0,Math.min(o,l.height-c.height)),t.style.left=a+"px",t.style.top=o+"px",y=null}!function({chatWindow:e,changes:t}){for(const[n,a]of Object.entries(t))e.style[n]=a+"px"}({chatWindow:t,changes:S}),S={}}function v(){null===p&&(p=window.requestAnimationFrame(()=>{p=null,b()}))}function T(e){g&&(e.clientX===u&&e.clientY===m||(u=e.clientX,m=e.clientY,y=e,v()))}function I(e){g&&(T(e),b(),g=!1,t.classList.remove("is-interactive"),document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",I),n({includeSize:!0}))}function M(e){if(!h)return;if(e.clientX===u&&e.clientY===m)return;u=e.clientX,m=e.clientY;const t=function({currentResizer:e,event:t,initialRect:n,startX:a,startY:o,limits:i}){const s={};if(!e)return s;const{clientWidth:r,clientHeight:c,minWidth:l,minHeight:d}=i;if(e.classList.contains("right")){const e=n.width+(t.clientX-a);e>=l&&n.left+e<=r&&(s.width=e)}if(e.classList.contains("bottom")){const e=n.height+(t.clientY-o);e>=d&&n.top+e<=c&&(s.height=e)}if(e.classList.contains("left")){const e=n.width-(t.clientX-a),o=n.left+(t.clientX-a);e>=l&&o>=0&&(s.width=e,s.left=o)}if(e.classList.contains("top")){const e=n.height-(t.clientY-o),a=n.top+(t.clientY-o);e>=d&&a>=0&&(s.height=e,s.top=a)}return s}({currentResizer:f,event:e,initialRect:r,startX:i,startY:s,limits:d});Object.assign(S,t),Object.keys(t).length>0&&v()}function C(e){h&&(M(e),b(),h=!1,t.classList.remove("is-interactive"),f=null,document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",C),n({includeSize:!0}))}o.addEventListener("mousedown",function(e){if(e.target.closest("button")||t.classList.contains("is-maximized"))return;e.preventDefault(),delete t.dataset.isDefaultPosition;const n=t.getBoundingClientRect();t.style.top=n.top+"px",t.style.left=n.left+"px",t.style.bottom="auto",t.style.right="auto",t.style.transform="none",t.classList.add("is-interactive"),g=!0,i=e.clientX,s=e.clientY,u=i,m=s,r=n,c={width:t.offsetWidth,height:t.offsetHeight},l={width:window.innerWidth,height:window.innerHeight},document.addEventListener("mousemove",T),document.addEventListener("mouseup",I)}),t.addEventListener("mousedown",function(e){if(!e.target.classList.contains("resizer")||t.classList.contains("is-maximized"))return;e.preventDefault();const n=t.getBoundingClientRect();d=w(t),t.style.top=n.top+"px",t.style.left=n.left+"px",t.style.bottom="auto",t.style.right="auto",t.style.transform="none",t.classList.add("is-interactive"),h=!0,f=e.target,i=e.clientX,s=e.clientY,u=i,m=s,r=n,document.addEventListener("mousemove",M),document.addEventListener("mouseup",C)}),window.addEventListener("resize",()=>{g&&(l={width:window.innerWidth,height:window.innerHeight}),h&&(d=w(t)),window.innerWidth>=768&&e(),a()})}({adjustWindowPosition:z,chatWindow:T,savePcWindowState:s,updateButtonVisibility:V}),j(),function({addMessageToUI:e,chatSettings:t,getState:n,saveCoreState:a,scrollToBottom:o}){if(!t.updateMessage)return;const i={sender:"bot",text:t.updateMessage,timestamp:c()};n().isOpen&&e(i),n().history.push(i),a(),n().isOpen&&o()}({addMessageToUI:D,chatSettings:a,getState:F,saveCoreState:U,scrollToBottom:r}),function({adjustWindowPosition:e,chatWindow:t,getState:n,scrollToBottom:a}){setTimeout(()=>{window.innerWidth>=768&&e(),n().isOpen&&!t.classList.contains("is-minimized")&&a()},100)}({adjustWindowPosition:z,chatWindow:T,getState:F,scrollToBottom:r})}({foundation:t,messageServices:z(t)})}(t)})}();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.