@storvia/sdk 0.1.1 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +4 -3
- package/dist/index.d.mts +13 -2
- package/dist/index.esm.js +4 -3
- package/dist/index.umd.js +5 -4
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);for(let
|
|
1
|
+
"use strict";var k=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var B=(d,e)=>{for(var t in e)k(d,t,{get:e[t],enumerable:!0})},A=(d,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of H(e))!O.call(d,i)&&i!==t&&k(d,i,{get:()=>e[i],enumerable:!(n=L(e,i))||n.enumerable});return d};var D=d=>A(k({},"__esModule",{value:!0}),d);var K={};B(K,{StorviaError:()=>c,StorviaSDK:()=>E,createStorviaSDK:()=>$});module.exports=D(K);var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var S=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let a="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${a} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${a} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({})),m=new c(r.code||"INTERNAL_ERROR",r.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,m),m}let a=s.body?.getReader();if(!a)throw new c("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,l="",h="";for(;;){let{done:r,value:m}=await a.read();if(r)break;let I=o.decode(m,{stream:!0}).split(`
|
|
2
|
+
`);for(let P of I){if(!P.startsWith("data: "))continue;let _=P.slice(6);if(_==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:h.length}),i(l);return}try{let g=JSON.parse(_);g.type==="done"&&g.id?l=g.id:g.content&&(h+=g.content,n(g.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new c(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var U=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],M=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],j=`
|
|
3
3
|
:host {
|
|
4
4
|
position: fixed;
|
|
5
5
|
bottom: 20px;
|
|
@@ -427,4 +427,5 @@
|
|
|
427
427
|
to { transform: rotate(360deg); }
|
|
428
428
|
}
|
|
429
429
|
.spin { animation: spin 0.8s linear infinite; }
|
|
430
|
-
`,D='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',j='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',F='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',v=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,s=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=s;try{let i=localStorage.getItem("storvia_display_mode");(i==="phone"||i==="desktop")&&(this.displayMode=i)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=U;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let s=document.createElement("button");s.className="fab",s.innerHTML=D,s.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("div");i.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=i,n.appendChild(s),n.appendChild(i);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let d=document.createElement("div");d.className="panel-title",d.textContent="\u6E38\u620F\u8BBE\u7F6E";let p=document.createElement("button");p.className="close-btn",p.innerHTML="\u2715",p.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(d),o.appendChild(p),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let h=document.createElement("button");h.className="save-btn",h.textContent="\u4FDD\u5B58",this.saveBtn=h,h.addEventListener("click",()=>this.handleSave()),m.appendChild(h),r.appendChild(m),a.appendChild(r),s.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",u=>{this.host.contains(u.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(s=>{let i=document.createElement("button");i.className=`model-option${s.id===this.selectedModelId?" active":""}`,i.innerHTML=`<span class="dot"></span><span>${s.name}</span>`,i.addEventListener("click",()=>{this.selectedModelId=s.id,this.callbacks.onModelChange(s.id);try{localStorage.setItem("storvia_model_id",s.id)}catch{}this.updateModelActive()}),n.appendChild(i)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let s=document.createElement("span");s.className="value",s.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=s,t.appendChild(n),t.appendChild(s),e.appendChild(t);let i=document.createElement("div");i.className="section-desc",i.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(i);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let p=parseFloat(o.value);this.settings.temperature=p,this.tempValueEl&&(this.tempValueEl.textContent=p.toFixed(1))}),a.appendChild(o);let d=document.createElement("div");return d.className="slider-labels",d.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(d),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],N.forEach(s=>{let i=document.createElement("button");i.className=`segment-btn${s.value===this.settings.reply_length?" active":""}`,i.textContent=s.label,i.addEventListener("click",()=>{this.settings.reply_length=s.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",N[o].value===s.value)})}),this.segmentBtns.push(i),n.appendChild(i)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let s=document.createElement("select");s.className="select",this.langSelect=s,A.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),s.appendChild(o)}),s.addEventListener("change",()=>{this.settings.reply_language=s.value});let i=document.createElement("span");return i.className="select-arrow",i.textContent="\u25BE",n.appendChild(s),n.appendChild(i),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let s=document.createElement("span");s.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=s,t.appendChild(n),t.appendChild(s),e.appendChild(t);let i=document.createElement("div");i.className="section-desc",i.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(i);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let s=document.createElement("div");s.className="segment",this.displayModeBtns=[];let i=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return i.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((d,p)=>{d.classList.toggle("active",i[p].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),s.appendChild(o)}),e.appendChild(s),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let s=document.createElement("div");s.className="sync-desc",s.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(s);let i=document.createElement("button");return i.className="sync-btn",this.syncBtn=i,this.renderSyncBtn(),i.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(i),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:j,loading:z,success:G,error:F},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var f=class{constructor(e,t,n,s,i=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=s;this.isPreview=i;this.previewConfig=a}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,s=>{n+=s},()=>{}),{id:"",content:n}}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new R(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(s=>s.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(s=>s.from===e&&s.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let s=this.mem.find(i=>i.from===e&&i.to===t);s?Object.assign(s,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(s=>s.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`)}};var C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var I=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var V="/functions/v1/world-engine/v1";function W(){return window.__STORVIA__||{}}function J(l=5e3){let e=W();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let s=setTimeout(()=>{window.removeEventListener("message",i),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},l);function i(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(s),window.removeEventListener("message",i);let d=window;d.__STORVIA__=o,t(o)}}window.addEventListener("message",i)})}var k=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){let e=await J(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${V}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new c("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=e.models||[];this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new v({onModelChange:E=>{this.modelId=E},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,h=()=>this.conversationId,u=()=>this.modelId;this.chat=new f(this.http,m,h,u,!0,this.previewConfig),this.characters=new b(this.http,h,!0),this.relationships=new w(this.http,h,!0),this.inventory=new y(this.http,h,!0),this.world=new C(this.http,h,!0),this.player=new x(this.http,h,!0),this.custom=new I(this.http,h,!0),this.initialized=!0,this.listenForPreviewMessages();return}let n=await this.authenticate();this.conversationId=n.conversationId;let s=n.models||[],i=this.getSavedModelId();this.modelId=i&&s.some(r=>r.id===i)?i:s[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new v({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(s,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,d=()=>this.conversationId,p=()=>this.modelId;this.chat=new f(this.http,o,d,p),this.characters=new b(this.http,d),this.relationships=new w(this.http,d),this.inventory=new y(this.http,d),this.world=new C(this.http,d),this.player=new x(this.http,d),this.custom=new I(this.http,d),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}};0&&(module.exports={StorviaError,StorviaSDK});
|
|
430
|
+
`,z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',F='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',V='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',W='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=j;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=z,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let l=document.createElement("div");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(l),o.appendChild(h),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),r.appendChild(m),a.appendChild(r),i.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),a.appendChild(o);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(l),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],M.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",M[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,U.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((l,h)=>{l.classList.toggle("active",s[h].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:G,loading:F,success:V,error:W},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=a}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
+
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new R(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var N="/functions/v1/world-engine/v1",J="https://api.storvia.ai";function Y(){return window.__STORVIA__||{}}function Z(d=5e3){let e=Y();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},d);function s(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var E=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Z(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${N}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new c("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=await this.fetchModels();this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new u({onModelChange:P=>{this.modelId=P},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new w(this.http,p,!0),this.inventory=new b(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(r=>r.id===s)?s:i[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,l,h),this.characters=new f(this.http,l),this.relationships=new w(this.http,l),this.inventory=new b(this.http,l),this.world=new y(this.http,l),this.player=new C(this.http,l),this.custom=new x(this.http,l),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${J}${N}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new S(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=e.modelId||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new w(this.http,i,!0),this.inventory=new b(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function $(d){let e=new E;return d?.dev?await e.initDev(d.dev):await e.init(),e}0&&(module.exports={StorviaError,StorviaSDK,createStorviaSDK});
|
package/dist/index.d.mts
CHANGED
|
@@ -2,7 +2,8 @@ declare class HttpClient {
|
|
|
2
2
|
private baseUrl;
|
|
3
3
|
private token;
|
|
4
4
|
private debug;
|
|
5
|
-
|
|
5
|
+
private devApiKey;
|
|
6
|
+
constructor(baseUrl: string, token: string, debug?: boolean, devApiKey?: string);
|
|
6
7
|
setToken(token: string): void;
|
|
7
8
|
setDebug(enabled: boolean): void;
|
|
8
9
|
private buildHeaders;
|
|
@@ -197,6 +198,11 @@ declare class CustomModule {
|
|
|
197
198
|
deleteGroupField(groupKey: string, fieldKey: string): Promise<void>;
|
|
198
199
|
}
|
|
199
200
|
|
|
201
|
+
interface DevConfig {
|
|
202
|
+
apiKey: string;
|
|
203
|
+
gameId: string;
|
|
204
|
+
modelId?: string;
|
|
205
|
+
}
|
|
200
206
|
declare class StorviaSDK {
|
|
201
207
|
private http;
|
|
202
208
|
private settingsSheet;
|
|
@@ -222,13 +228,18 @@ declare class StorviaSDK {
|
|
|
222
228
|
private saveSettings;
|
|
223
229
|
/** 同步最新游戏设定到当前存档 */
|
|
224
230
|
syncSettings(): Promise<void>;
|
|
231
|
+
private fetchModels;
|
|
225
232
|
private authenticate;
|
|
226
233
|
private getSavedModelId;
|
|
234
|
+
initDev(devConfig: DevConfig): Promise<void>;
|
|
227
235
|
}
|
|
236
|
+
declare function createStorviaSDK(options?: {
|
|
237
|
+
dev?: DevConfig;
|
|
238
|
+
}): Promise<StorviaSDK>;
|
|
228
239
|
|
|
229
240
|
declare class StorviaError extends Error {
|
|
230
241
|
code: StorviaErrorCode;
|
|
231
242
|
constructor(code: StorviaErrorCode, message: string);
|
|
232
243
|
}
|
|
233
244
|
|
|
234
|
-
export { type CharacterDetail, type CharacterPersona, type ChatGenerateOptions, type ChatResponse, type ChatSaveOptions, type ChatSendOptions, type InventoryItemData, type PlayerPersona, type Relationship, StorviaError, type StorviaErrorCode, StorviaSDK };
|
|
245
|
+
export { type CharacterDetail, type CharacterPersona, type ChatGenerateOptions, type ChatResponse, type ChatSaveOptions, type ChatSendOptions, type InventoryItemData, type PlayerPersona, type Relationship, StorviaError, type StorviaErrorCode, StorviaSDK, createStorviaSDK };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);for(let E of
|
|
1
|
+
var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var S=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let a="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${a} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${a} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({})),m=new c(r.code||"INTERNAL_ERROR",r.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,m),m}let a=s.body?.getReader();if(!a)throw new c("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,d="",h="";for(;;){let{done:r,value:m}=await a.read();if(r)break;let I=o.decode(m,{stream:!0}).split(`
|
|
2
|
+
`);for(let E of I){if(!E.startsWith("data: "))continue;let T=E.slice(6);if(T==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:d,contentLength:h.length}),i(d);return}try{let g=JSON.parse(T);g.type==="done"&&g.id?d=g.id:g.content&&(h+=g.content,n(g.content))}catch{}}}d&&i(d)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new c(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var N=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],_=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],$=`
|
|
3
3
|
:host {
|
|
4
4
|
position: fixed;
|
|
5
5
|
bottom: 20px;
|
|
@@ -427,4 +427,5 @@ var l=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
|
|
|
427
427
|
to { transform: rotate(360deg); }
|
|
428
428
|
}
|
|
429
429
|
.spin { animation: spin 0.8s linear infinite; }
|
|
430
|
-
`,$='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',L='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',H='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',O='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',B='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',v=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,s=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=s;try{let i=localStorage.getItem("storvia_display_mode");(i==="phone"||i==="desktop")&&(this.displayMode=i)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=M;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let s=document.createElement("button");s.className="fab",s.innerHTML=$,s.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("div");i.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=i,n.appendChild(s),n.appendChild(i);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let d=document.createElement("div");d.className="panel-title",d.textContent="\u6E38\u620F\u8BBE\u7F6E";let p=document.createElement("button");p.className="close-btn",p.innerHTML="\u2715",p.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(d),o.appendChild(p),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let h=document.createElement("button");h.className="save-btn",h.textContent="\u4FDD\u5B58",this.saveBtn=h,h.addEventListener("click",()=>this.handleSave()),m.appendChild(h),r.appendChild(m),a.appendChild(r),s.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",u=>{this.host.contains(u.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(s=>{let i=document.createElement("button");i.className=`model-option${s.id===this.selectedModelId?" active":""}`,i.innerHTML=`<span class="dot"></span><span>${s.name}</span>`,i.addEventListener("click",()=>{this.selectedModelId=s.id,this.callbacks.onModelChange(s.id);try{localStorage.setItem("storvia_model_id",s.id)}catch{}this.updateModelActive()}),n.appendChild(i)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let s=document.createElement("span");s.className="value",s.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=s,t.appendChild(n),t.appendChild(s),e.appendChild(t);let i=document.createElement("div");i.className="section-desc",i.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(i);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let p=parseFloat(o.value);this.settings.temperature=p,this.tempValueEl&&(this.tempValueEl.textContent=p.toFixed(1))}),a.appendChild(o);let d=document.createElement("div");return d.className="slider-labels",d.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(d),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],_.forEach(s=>{let i=document.createElement("button");i.className=`segment-btn${s.value===this.settings.reply_length?" active":""}`,i.textContent=s.label,i.addEventListener("click",()=>{this.settings.reply_length=s.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",_[o].value===s.value)})}),this.segmentBtns.push(i),n.appendChild(i)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let s=document.createElement("select");s.className="select",this.langSelect=s,N.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),s.appendChild(o)}),s.addEventListener("change",()=>{this.settings.reply_language=s.value});let i=document.createElement("span");return i.className="select-arrow",i.textContent="\u25BE",n.appendChild(s),n.appendChild(i),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let s=document.createElement("span");s.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=s,t.appendChild(n),t.appendChild(s),e.appendChild(t);let i=document.createElement("div");i.className="section-desc",i.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(i);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let s=document.createElement("div");s.className="segment",this.displayModeBtns=[];let i=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return i.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((d,p)=>{d.classList.toggle("active",i[p].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),s.appendChild(o)}),e.appendChild(s),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let s=document.createElement("div");s.className="sync-desc",s.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(s);let i=document.createElement("button");return i.className="sync-btn",this.syncBtn=i,this.renderSyncBtn(),i.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(i),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:L,loading:H,success:O,error:B},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var f=class{constructor(e,t,n,s,i=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=s;this.isPreview=i;this.previewConfig=a}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,s=>{n+=s},()=>{}),{id:"",content:n}}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new k(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(s=>s.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(s=>s.from===e&&s.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let s=this.mem.find(i=>i.from===e&&i.to===t);s?Object.assign(s,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(s=>s.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`)}};var C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var P=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new P(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var I=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var A="/functions/v1/world-engine/v1";function U(){return window.__STORVIA__||{}}function D(c=5e3){let e=U();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let s=setTimeout(()=>{window.removeEventListener("message",i),n(new l("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},c);function i(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(s),window.removeEventListener("message",i);let d=window;d.__STORVIA__=o,t(o)}}window.addEventListener("message",i)})}var R=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){let e=await D(),t=e.apiBase;if(!t)throw new l("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${A}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new l("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new l("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=e.models||[];this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new v({onModelChange:E=>{this.modelId=E},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,h=()=>this.conversationId,u=()=>this.modelId;this.chat=new f(this.http,m,h,u,!0,this.previewConfig),this.characters=new b(this.http,h,!0),this.relationships=new w(this.http,h,!0),this.inventory=new y(this.http,h,!0),this.world=new C(this.http,h,!0),this.player=new x(this.http,h,!0),this.custom=new I(this.http,h,!0),this.initialized=!0,this.listenForPreviewMessages();return}let n=await this.authenticate();this.conversationId=n.conversationId;let s=n.models||[],i=this.getSavedModelId();this.modelId=i&&s.some(r=>r.id===i)?i:s[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new v({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(s,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,d=()=>this.conversationId,p=()=>this.modelId;this.chat=new f(this.http,o,d,p),this.characters=new b(this.http,d),this.relationships=new w(this.http,d),this.inventory=new y(this.http,d),this.world=new C(this.http,d),this.player=new x(this.http,d),this.custom=new I(this.http,d),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new l("UNAUTHORIZED","User not authenticated"):e.status===404?new l("GAME_NOT_FOUND","Game not found or not published"):new l("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}};export{l as StorviaError,R as StorviaSDK};
|
|
430
|
+
`,L='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',H='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',O='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',B='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',A='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=$;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=L,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let d=document.createElement("div");d.className="panel-title",d.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(d),o.appendChild(h),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),r.appendChild(m),a.appendChild(r),i.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),a.appendChild(o);let d=document.createElement("div");return d.className="slider-labels",d.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(d),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],_.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",_[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,N.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((d,h)=>{d.classList.toggle("active",s[h].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:H,loading:O,success:B,error:A},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=a}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
+
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new k(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new R(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var M="/functions/v1/world-engine/v1",D="https://api.storvia.ai";function U(){return window.__STORVIA__||{}}function j(l=5e3){let e=U();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},l);function s(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let d=window;d.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var P=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await j(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${M}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new c("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=await this.fetchModels();this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new u({onModelChange:E=>{this.modelId=E},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new w(this.http,p,!0),this.inventory=new b(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(r=>r.id===s)?s:i[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,d=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,d,h),this.characters=new f(this.http,d),this.relationships=new w(this.http,d),this.inventory=new b(this.http,d),this.world=new y(this.http,d),this.player=new C(this.http,d),this.custom=new x(this.http,d),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${D}${M}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new S(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=e.modelId||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new w(this.http,i,!0),this.inventory=new b(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function z(l){let e=new P;return l?.dev?await e.initDev(l.dev):await e.init(),e}export{c as StorviaError,P as StorviaSDK,z as createStorviaSDK};
|
package/dist/index.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var StorviaSDK=(()=>{var
|
|
2
|
-
`);for(let
|
|
1
|
+
"use strict";var StorviaSDK=(()=>{var k=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var B=(d,e)=>{for(var t in e)k(d,t,{get:e[t],enumerable:!0})},A=(d,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of H(e))!O.call(d,i)&&i!==t&&k(d,i,{get:()=>e[i],enumerable:!(n=L(e,i))||n.enumerable});return d};var D=d=>A(k({},"__esModule",{value:!0}),d);var K={};B(K,{StorviaError:()=>c,StorviaSDK:()=>E,createStorviaSDK:()=>$});var c=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var S=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let a="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${a} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${a} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({})),m=new c(r.code||"INTERNAL_ERROR",r.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,m),m}let a=s.body?.getReader();if(!a)throw new c("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,l="",h="";for(;;){let{done:r,value:m}=await a.read();if(r)break;let I=o.decode(m,{stream:!0}).split(`
|
|
2
|
+
`);for(let P of I){if(!P.startsWith("data: "))continue;let _=P.slice(6);if(_==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:h.length}),i(l);return}try{let g=JSON.parse(_);g.type==="done"&&g.id?l=g.id:g.content&&(h+=g.content,n(g.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new c(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var U=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],M=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],j=`
|
|
3
3
|
:host {
|
|
4
4
|
position: fixed;
|
|
5
5
|
bottom: 20px;
|
|
@@ -427,5 +427,6 @@
|
|
|
427
427
|
to { transform: rotate(360deg); }
|
|
428
428
|
}
|
|
429
429
|
.spin { animation: spin 0.8s linear infinite; }
|
|
430
|
-
`,D='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',j='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',F='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',v=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,s=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=s;try{let i=localStorage.getItem("storvia_display_mode");(i==="phone"||i==="desktop")&&(this.displayMode=i)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=U;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let s=document.createElement("button");s.className="fab",s.innerHTML=D,s.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("div");i.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=i,n.appendChild(s),n.appendChild(i);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let d=document.createElement("div");d.className="panel-title",d.textContent="\u6E38\u620F\u8BBE\u7F6E";let p=document.createElement("button");p.className="close-btn",p.innerHTML="\u2715",p.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(d),o.appendChild(p),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let h=document.createElement("button");h.className="save-btn",h.textContent="\u4FDD\u5B58",this.saveBtn=h,h.addEventListener("click",()=>this.handleSave()),m.appendChild(h),r.appendChild(m),a.appendChild(r),s.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",u=>{this.host.contains(u.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(s=>{let i=document.createElement("button");i.className=`model-option${s.id===this.selectedModelId?" active":""}`,i.innerHTML=`<span class="dot"></span><span>${s.name}</span>`,i.addEventListener("click",()=>{this.selectedModelId=s.id,this.callbacks.onModelChange(s.id);try{localStorage.setItem("storvia_model_id",s.id)}catch{}this.updateModelActive()}),n.appendChild(i)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let s=document.createElement("span");s.className="value",s.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=s,t.appendChild(n),t.appendChild(s),e.appendChild(t);let i=document.createElement("div");i.className="section-desc",i.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(i);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let p=parseFloat(o.value);this.settings.temperature=p,this.tempValueEl&&(this.tempValueEl.textContent=p.toFixed(1))}),a.appendChild(o);let d=document.createElement("div");return d.className="slider-labels",d.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(d),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],N.forEach(s=>{let i=document.createElement("button");i.className=`segment-btn${s.value===this.settings.reply_length?" active":""}`,i.textContent=s.label,i.addEventListener("click",()=>{this.settings.reply_length=s.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",N[o].value===s.value)})}),this.segmentBtns.push(i),n.appendChild(i)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let s=document.createElement("select");s.className="select",this.langSelect=s,A.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),s.appendChild(o)}),s.addEventListener("change",()=>{this.settings.reply_language=s.value});let i=document.createElement("span");return i.className="select-arrow",i.textContent="\u25BE",n.appendChild(s),n.appendChild(i),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let s=document.createElement("span");s.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=s,t.appendChild(n),t.appendChild(s),e.appendChild(t);let i=document.createElement("div");i.className="section-desc",i.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(i);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let s=document.createElement("div");s.className="segment",this.displayModeBtns=[];let i=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return i.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((d,p)=>{d.classList.toggle("active",i[p].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),s.appendChild(o)}),e.appendChild(s),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let s=document.createElement("div");s.className="sync-desc",s.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(s);let i=document.createElement("button");return i.className="sync-btn",this.syncBtn=i,this.renderSyncBtn(),i.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(i),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:j,loading:z,success:G,error:F},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var f=class{constructor(e,t,n,s,i=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=s;this.isPreview=i;this.previewConfig=a}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,s=>{n+=s},()=>{}),{id:"",content:n}}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new R(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(s=>s.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(s=>s.from===e&&s.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let s=this.mem.find(i=>i.from===e&&i.to===t);s?Object.assign(s,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(s=>s.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`)}};var C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var I=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var V="/functions/v1/world-engine/v1";function W(){return window.__STORVIA__||{}}function J(l=5e3){let e=W();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let s=setTimeout(()=>{window.removeEventListener("message",i),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},l);function i(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(s),window.removeEventListener("message",i);let d=window;d.__STORVIA__=o,t(o)}}window.addEventListener("message",i)})}var k=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){let e=await J(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${V}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new c("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=e.models||[];this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new v({onModelChange:E=>{this.modelId=E},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,h=()=>this.conversationId,u=()=>this.modelId;this.chat=new f(this.http,m,h,u,!0,this.previewConfig),this.characters=new b(this.http,h,!0),this.relationships=new w(this.http,h,!0),this.inventory=new y(this.http,h,!0),this.world=new C(this.http,h,!0),this.player=new x(this.http,h,!0),this.custom=new I(this.http,h,!0),this.initialized=!0,this.listenForPreviewMessages();return}let n=await this.authenticate();this.conversationId=n.conversationId;let s=n.models||[],i=this.getSavedModelId();this.modelId=i&&s.some(r=>r.id===i)?i:s[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new v({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(s,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,d=()=>this.conversationId,p=()=>this.modelId;this.chat=new f(this.http,o,d,p),this.characters=new b(this.http,d),this.relationships=new w(this.http,d),this.inventory=new y(this.http,d),this.world=new C(this.http,d),this.player=new x(this.http,d),this.custom=new I(this.http,d),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}};return B(Y);})();
|
|
431
|
-
if(typeof window!=="undefined"){window.StorviaSDK=StorviaSDK.StorviaSDK;}
|
|
430
|
+
`,z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>',F='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',V='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',W='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',u=class{constructor(e){this.selectedModelId="";this.models=[];this.modelPanel=null;this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.displayMode="phone";this.displayModeBtns=[];this.tempValueEl=null;this.tempSlider=null;this.segmentBtns=[];this.langSelect=null;this.noteInput=null;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.panel=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i;try{let s=localStorage.getItem("storvia_display_mode");(s==="phone"||s==="desktop")&&(this.displayMode=s)}catch{}document.body.appendChild(this.host),this.render()}unmount(){this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=j;let t=document.createElement("div"),n=document.createElement("div");n.className="fab-wrap";let i=document.createElement("button");i.className="fab",i.innerHTML=z,i.title="\u6E38\u620F\u8BBE\u7F6E";let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,n.appendChild(i),n.appendChild(s);let a=document.createElement("div");a.className="panel",this.panel=a;let o=document.createElement("div");o.className="panel-header";let l=document.createElement("div");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let h=document.createElement("button");h.className="close-btn",h.innerHTML="\u2715",h.addEventListener("click",()=>a.classList.remove("open")),o.appendChild(l),o.appendChild(h),a.appendChild(o);let r=document.createElement("div");r.className="panel-body",this.models.length>0&&(r.appendChild(this.buildModelSection()),r.appendChild(this.makeDivider())),r.appendChild(this.buildTemperatureSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLengthSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildReplyLanguageSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildNoteSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildDisplayModeSection()),r.appendChild(this.makeDivider()),r.appendChild(this.buildSyncSection());let m=document.createElement("div");m.className="save-row";let p=document.createElement("button");p.className="save-btn",p.textContent="\u4FDD\u5B58",this.saveBtn=p,p.addEventListener("click",()=>this.handleSave()),m.appendChild(p),r.appendChild(m),a.appendChild(r),i.addEventListener("click",()=>a.classList.toggle("open")),document.addEventListener("click",I=>{this.host.contains(I.target)||a.classList.remove("open")}),t.appendChild(a),t.appendChild(n),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(t)}buildModelSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="AI \u6A21\u578B",e.appendChild(t);let n=document.createElement("div");return n.className="model-list",this.modelPanel=n,this.models.forEach(i=>{let s=document.createElement("button");s.className=`model-option${i.id===this.selectedModelId?" active":""}`,s.innerHTML=`<span class="dot"></span><span>${i.name}</span>`,s.addEventListener("click",()=>{this.selectedModelId=i.id,this.callbacks.onModelChange(i.id);try{localStorage.setItem("storvia_model_id",i.id)}catch{}this.updateModelActive()}),n.appendChild(s)}),e.appendChild(n),e}buildTemperatureSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u66F4\u4F4E\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u3001\u7406\u667A\uFF1B\u66F4\u9AD8\u7684\u6E29\u5EA6\u4F1A\u8BA9 AI \u7684\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027\u548C\u968F\u673A\u6027",e.appendChild(s);let a=document.createElement("div");a.className="slider-wrap";let o=document.createElement("input");o.type="range",o.className="slider",o.min="0",o.max="2",o.step="0.1",o.value=String(this.settings.temperature),this.tempSlider=o,o.addEventListener("input",()=>{let h=parseFloat(o.value);this.settings.temperature=h,this.tempValueEl&&(this.tempValueEl.textContent=h.toFixed(1))}),a.appendChild(o);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",a.appendChild(l),e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment",this.segmentBtns=[],M.forEach(i=>{let s=document.createElement("button");s.className=`segment-btn${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((a,o)=>{a.classList.toggle("active",M[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="select-wrap";let i=document.createElement("select");i.className="select",this.langSelect=i,U.forEach(a=>{let o=document.createElement("option");o.value=a.value,o.textContent=a.label,a.value===this.settings.reply_language&&(o.selected=!0),i.appendChild(o)}),i.addEventListener("change",()=>{this.settings.reply_language=i.value});let s=document.createElement("span");return s.className="select-arrow",s.textContent="\u25BE",n.appendChild(i),n.appendChild(s),e.appendChild(n),e}buildNoteSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("div");s.className="section-desc",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let a=document.createElement("div");a.className="note-wrap";let o=document.createElement("textarea");return o.className="note-input",o.placeholder="\u5907\u6CE8",o.maxLength=50,o.value=this.settings.player_note,this.noteInput=o,o.addEventListener("input",()=>{this.settings.player_note=o.value,this.noteCounter&&(this.noteCounter.textContent=`${o.value.length}/50`)}),a.appendChild(o),e.appendChild(a),e}buildDisplayModeSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u663E\u793A\u6A21\u5F0F",e.appendChild(t);let n=document.createElement("div");n.className="section-desc",n.textContent="\u7535\u8111\u6A21\u5F0F\u4F1A\u81EA\u52A8\u6A2A\u5C4F\u663E\u793A",e.appendChild(n);let i=document.createElement("div");i.className="segment",this.displayModeBtns=[];let s=[{value:"phone",label:"\u624B\u673A"},{value:"desktop",label:"\u7535\u8111"}];return s.forEach(a=>{let o=document.createElement("button");o.className=`segment-btn${a.value===this.displayMode?" active":""}`,o.textContent=a.label,o.addEventListener("click",()=>{this.displayMode=a.value;try{localStorage.setItem("storvia_display_mode",a.value)}catch{}this.displayModeBtns.forEach((l,h)=>{l.classList.toggle("active",s[h].value===a.value)});try{window.parent.postMessage({type:"storvia-orientation",mode:a.value==="desktop"?"landscape":"portrait"},"*")}catch{}}),this.displayModeBtns.push(o),i.appendChild(o)}),e.appendChild(i),e}buildSyncSection(){let e=document.createElement("div");e.className="section";let t=document.createElement("div");t.className="section-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("div");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("div");i.className="sync-desc",i.textContent="\u5982\u679C\u6E38\u620F\u4F5C\u8005\u66F4\u65B0\u4E86\u5185\u5BB9\uFF0C\u70B9\u51FB\u6B64\u6309\u94AE\u53EF\u5C06\u6700\u65B0\u7684\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="sync-btn",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}makeDivider(){let e=document.createElement("div");return e.className="divider",e}updateModelActive(){this.modelPanel&&this.modelPanel.querySelectorAll(".model-option").forEach((e,t)=>{e.classList.toggle("active",this.models[t].id===this.selectedModelId)})}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:G,loading:F,success:V,error:W},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`sync-btn${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.textContent="\u4FDD\u5B58\u4E2D...";try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn.textContent="\u5DF2\u4FDD\u5B58",this.saveBtn.classList.add("saved"),setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.classList.remove("saved"),this.saveBtn.disabled=!1)},2e3)}catch{this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3)}}}};var v=class{constructor(e,t,n,i,s=!1,a){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=a}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,context:(e.context||"")+`
|
|
431
|
+
[\u6307\u4EE4] \u8BF7\u76F4\u63A5\u751F\u6210\u56DE\u590D\uFF0C\u65E0\u9700\u7528\u6237\u8F93\u5165`,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,context:e.context,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,context:e.context,prompt_config:this.previewConfig||{},history_messages:[]};if(e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var R=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},f=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new R(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}};var w=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var b=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(e){if(this.isPreview)return e?this.mem.filter(n=>n.group===e):[...this.mem];let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/inventory`,t)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`)}};var y=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var T=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new T(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t],Object.keys(n).length===0&&delete this.mem[e]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var N="/functions/v1/world-engine/v1",J="https://api.storvia.ai";function Y(){return window.__STORVIA__||{}}function Z(d=5e3){let e=Y();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new c("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},d);function s(a){let o=null;if(a.data?.type==="storvia-init"&&a.data.apiBase?o={apiBase:a.data.apiBase,gameId:a.data.gameId,accessToken:a.data.accessToken}:a.data?.type==="storvia-preview-init"&&a.data.config&&(o=a.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var E=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await Z(),t=e.apiBase;if(!t)throw new c("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${N}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new c("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new c("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new S(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let r=await this.fetchModels();this.modelId=e.selectedModelId||r[0]?.id||"",this.settingsSheet=new u({onModelChange:P=>{this.modelId=P},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),r.length>0&&this.settingsSheet.mount(r,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let m=()=>this.gameId,p=()=>this.conversationId,I=()=>this.modelId;this.chat=new v(this.http,m,p,I,!0,this.previewConfig),this.characters=new f(this.http,p,!0),this.relationships=new w(this.http,p,!0),this.inventory=new b(this.http,p,!0),this.world=new y(this.http,p,!0),this.player=new C(this.http,p,!0),this.custom=new x(this.http,p,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(r=>r.id===s)?s:i[0]?.id||"";let a=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new u({onModelChange:r=>{this.modelId=r},onSettingsChange:r=>this.saveSettings(r),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,a,n.hasWorldUpdate??!1);let o=()=>this.gameId,l=()=>this.conversationId,h=()=>this.modelId;this.chat=new v(this.http,o,l,h),this.characters=new f(this.http,l),this.relationships=new w(this.http,l),this.inventory=new b(this.http,l),this.world=new y(this.http,l),this.player=new C(this.http,l),this.custom=new x(this.http,l),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new c("UNAUTHORIZED","User not authenticated"):e.status===404?new c("GAME_NOT_FOUND","Game not found or not published"):new c("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${J}${N}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new S(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=e.modelId||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new u({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new v(this.http,n,i,s,!0,void 0),this.characters=new f(this.http,i,!0),this.relationships=new w(this.http,i,!0),this.inventory=new b(this.http,i,!0),this.world=new y(this.http,i,!0),this.player=new C(this.http,i,!0),this.custom=new x(this.http,i,!0),this.initialized=!0}};async function $(d){let e=new E;return d?.dev?await e.initDev(d.dev):await e.init(),e}return D(K);})();
|
|
432
|
+
if(typeof window!=="undefined"){window.createStorviaSDK=StorviaSDK.createStorviaSDK;}
|