@storvia/sdk 0.6.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +7 -803
- package/dist/index.d.mts +100 -24
- package/dist/index.esm.js +9 -805
- package/dist/index.umd.js +7 -803
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var
|
|
2
|
-
#${
|
|
1
|
+
var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var j=1;function Q(o){if(!o||typeof o!="object")return!1;let e=o;return typeof e.protocol=="number"&&typeof e.type=="string"&&"payload"in e}function E(o,e,t){return{protocol:1,type:o,payload:e,...t?.id?{id:t.id}:{},...t?.ackId?{ackId:t.ackId}:{}}}var _=class{constructor(e){this.handlers=new Map;this.pendingAcks=new Map;this.listener=null;this.incoming=e.incoming,this.getOutgoing=e.outgoing,this.verifySource=e.verifySource??(()=>!0),this.validate=e.validate,this.debug=!!e.debug,this.getTransferables=e.transfer??(()=>{}),this.customSend=e.customSend,this.attach()}attach(){this.listener=e=>{if((this.incoming instanceof Window||this.incoming===window)&&!this.verifySource(e))return;let t=e.data;if(!Q(t))return;if(t.protocol!==1){this.debug&&console.warn("[StorviaBus] protocol mismatch",{expected:1,got:t.protocol,type:t.type});return}if(this.validate&&!this.validate(t)){this.debug&&console.warn("[StorviaBus] validation failed",t);return}if(t.ackId){let r=this.pendingAcks.get(t.ackId);if(r){this.pendingAcks.delete(t.ackId),r(t);return}}let n=this.handlers.get(t.type);if(!n||n.size===0){this.debug&&console.debug("[StorviaBus] no handler for",t.type);return}n.forEach(r=>{try{r(t)}catch(i){console.error(`[StorviaBus] handler '${t.type}' threw:`,i)}})},this.incoming.addEventListener("message",this.listener),this.incoming instanceof MessagePort&&this.incoming.start()}on(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n));let r=t;return n.add(r),()=>n.delete(r)}send(e){let t=e.protocol?e:E(e.type,e.payload,{id:e.id,ackId:e.ackId});if(this.customSend){try{this.customSend(t)}catch(i){console.error("[StorviaBus] customSend failed:",i,{type:e.type})}return}let n=this.getOutgoing();if(!n){this.debug&&console.warn("[StorviaBus] outgoing target unavailable, drop:",e.type);return}let r=this.getTransferables(t);try{n instanceof MessagePort?n.postMessage(t,r??[]):n.postMessage(t,"*",r??[])}catch(i){console.error("[StorviaBus] postMessage failed:",i,{type:e.type})}}request(e,t=1e4){return new Promise((n,r)=>{let i=e.id??Ee(),s=E(e.type,e.payload,{id:i}),c=setTimeout(()=>{this.pendingAcks.delete(i),r(new Error(`[StorviaBus] request '${e.type}' timed out after ${t}ms`))},t);this.pendingAcks.set(i,d=>{clearTimeout(c),n(d)}),this.send(s)})}destroy(){if(this.listener&&(this.incoming.removeEventListener("message",this.listener),this.listener=null),this.incoming instanceof MessagePort)try{this.incoming.close()}catch{}this.handlers.clear(),this.pendingAcks.clear()}};function Ee(){return`bus-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var oe=null;function pe(o){oe=o}var J="storvia-sdk-toast-style",X="storvia-sdk-toast-stack",ue=`
|
|
2
|
+
#${X} {
|
|
3
3
|
position: fixed;
|
|
4
4
|
top: max(20px, env(safe-area-inset-top, 0px) + 20px);
|
|
5
5
|
right: max(20px, env(safe-area-inset-right, 0px) + 20px);
|
|
@@ -12,7 +12,7 @@ var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
@media (max-width: 768px) {
|
|
15
|
-
#${
|
|
15
|
+
#${X} {
|
|
16
16
|
top: max(10px, env(safe-area-inset-top, 0px) + 10px);
|
|
17
17
|
left: 10px;
|
|
18
18
|
right: 10px;
|
|
@@ -219,10 +219,10 @@ var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
|
|
|
219
219
|
.storvia-sheet-msg { font-size: 13px; margin-bottom: 22px; }
|
|
220
220
|
.storvia-sheet-btn { height: 40px; font-size: 13px; }
|
|
221
221
|
}
|
|
222
|
-
`,
|
|
223
|
-
<span class="storvia-toast-icon">${
|
|
222
|
+
`,Se={success:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',error:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>',warning:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',info:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'},ie={UNAUTHORIZED:"\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55",INSUFFICIENT_CREDITS:"\u82B1\u56ED\u5E01\u4E0D\u8DB3\uFF0C\u8BF7\u5145\u503C\u540E\u518D\u7EE7\u7EED\u6E38\u620F",VIOLATION_WORD_DETECTED:"\u5185\u5BB9\u542B\u6709\u8FDD\u7981\u8BCD\uFF0C\u8BF7\u4FEE\u6539\u540E\u91CD\u8BD5",CONTENT_FILTERED:"\u5185\u5BB9\u88AB\u5B89\u5168\u7B56\u7565\u62E6\u622A\uFF0C\u8BF7\u8C03\u6574\u540E\u91CD\u8BD5",MODEL_REFUSAL:"\u6A21\u578B\u62D2\u7EDD\u54CD\u5E94\uFF0C\u6362\u4E2A\u8BF4\u6CD5\u8BD5\u8BD5",STREAM_INTERRUPTED:"\u56DE\u590D\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",RATE_LIMITED:"\u64CD\u4F5C\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",MODEL_NOT_FOUND:"\u6240\u9009\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u6A21\u578B",GAME_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u6E38\u620F",INVALID_REQUEST:"\u8BF7\u6C42\u65E0\u6548\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",INTERNAL_ERROR:"\u670D\u52A1\u51FA\u4E86\u70B9\u5C0F\u95EE\u9898\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",NOT_INITIALIZED:"SDK \u5C1A\u672A\u521D\u59CB\u5316",NOT_SUPPORTED_IN_PREVIEW:"\u5F53\u524D\u63A5\u53E3\u5728\u9884\u89C8\u6A21\u5F0F\u4E0B\u4E0D\u53EF\u7528",NETWORK_ERROR:"\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5",REQUEST_TIMEOUT:"\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",MODEL_LOADING_TIMEOUT:"\u6A21\u578B\u54CD\u5E94\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",STREAM_INACTIVITY:"\u8FDE\u63A5\u5DF2\u4E2D\u65AD\uFF0C\u8BF7\u91CD\u8BD5",DAISY_CARD_REQUIRED:"\u56DE\u6EAF\u6D88\u606F\u9700\u8981\u6709\u6548\u7684\u96CF\u83CA\u5361\u8BA2\u9605",MESSAGE_NOT_FOUND:"\u6D88\u606F\u4E0D\u5B58\u5728\u6216\u65E0\u6743\u64CD\u4F5C",MESSAGE_TOO_OLD:"\u4EC5\u53EF\u56DE\u6EAF 30 \u5929\u5185\u7684\u6D88\u606F",NO_MESSAGES_TO_DELETE:"\u8BE5\u6D88\u606F\u4E4B\u540E\u6CA1\u6709\u53EF\u56DE\u6EAF\u7684\u6D88\u606F",GENERATION_TIMEOUT:"\u751F\u6210\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5",REPETITION_LOOP:"\u56DE\u590D\u51FA\u73B0\u91CD\u590D\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6362\u4E2A\u8BF4\u6CD5",SAVE_FAILED:"\u6D88\u606F\u4FDD\u5B58\u5931\u8D25\uFF0C\u672C\u6B21\u4E0D\u6263\u8D39\uFF0C\u8BF7\u91CD\u8BD5",FINALIZE_FAILED:"\u56DE\u590D\u5904\u7406\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5",CONVERSATION_NOT_FOUND:"\u672A\u627E\u5230\u5BF9\u5E94\u4F1A\u8BDD",EMPTY_MESSAGE:"\u6D88\u606F\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A",CONTINUE_MODEL_NOT_AVAILABLE:"\u7EED\u5199\u6A21\u578B\u5F53\u524D\u4E0D\u53EF\u7528",CONTINUE_PROMPT_MISSING:"\u7EED\u5199\u914D\u7F6E\u7F3A\u5931"},me=!0;function be(o){me=o}function Pe(){if(typeof document>"u")return null;let o=document.getElementById(X);if(!o){if(!document.getElementById(J)){let e=document.createElement("style");e.id=J,e.textContent=ue,document.head.appendChild(e)}o=document.createElement("div"),o.id=X,document.body.appendChild(o)}return o}function ge(o,e="info",t=3500,n){if(!me)return;let r=Pe();if(!r)return;let i=t<=0,s=document.createElement("div");s.className=`storvia-toast ${e}`,s.innerHTML=`
|
|
223
|
+
<span class="storvia-toast-icon">${Se[e]}</span>
|
|
224
224
|
<span class="storvia-toast-msg"></span>
|
|
225
|
-
`;let
|
|
225
|
+
`;let c=s.querySelector(".storvia-toast-msg");c&&(c.textContent=o);let d=()=>{s.isConnected&&(s.classList.add("leaving"),s.classList.remove("show"),setTimeout(()=>s.remove(),320))};if(n){let a=document.createElement("button");a.type="button",a.className="storvia-toast-action",a.textContent=n.label,a.addEventListener("click",()=>{try{n.onClick()}catch(h){console.error("[Storvia toast] action error:",h)}d()}),s.appendChild(a)}if(i){let a=document.createElement("button");a.type="button",a.className="storvia-toast-close",a.setAttribute("aria-label","\u5173\u95ED"),a.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',a.addEventListener("click",d),s.appendChild(a)}r.appendChild(s),requestAnimationFrame(()=>s.classList.add("show")),i||setTimeout(d,t)}function S(o,e){if(o==="INSUFFICIENT_CREDITS"){he({title:"\u82B1\u56ED\u5E01\u4E0D\u8DB3",msg:e||ie.INSUFFICIENT_CREDITS,primaryLabel:"\u53BB\u5145\u503C"});return}if(o==="DAISY_CARD_REQUIRED"){he({title:"\u9700\u8981\u96CF\u83CA\u5361",msg:e||ie.DAISY_CARD_REQUIRED,primaryLabel:"\u53BB\u5F00\u901A"});return}let t=ie[o]||e||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";ge(t,o==="RATE_LIMITED"?"warning":"error")}var Z=null;function he(o){if(typeof document>"u"||Z)return;if(!document.getElementById(J)){let s=document.createElement("style");s.id=J,s.textContent=ue,document.head.appendChild(s)}let e=document.createElement("div");e.className="storvia-sheet-backdrop",e.innerHTML=`
|
|
226
226
|
<div class="storvia-sheet" role="dialog" aria-modal="true" aria-labelledby="storvia-sheet-title">
|
|
227
227
|
<div class="storvia-sheet-icon">
|
|
228
228
|
<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>
|
|
@@ -234,802 +234,6 @@ var u=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
|
|
|
234
234
|
<button type="button" class="storvia-sheet-btn storvia-sheet-btn-primary" data-role="navigate"></button>
|
|
235
235
|
</div>
|
|
236
236
|
</div>
|
|
237
|
-
`;let t=e.querySelector(".storvia-sheet-title");t&&(t.textContent=o.title);let n=e.querySelector(".storvia-sheet-msg");n&&(n.textContent=o.msg);let
|
|
238
|
-
`);for(let
|
|
239
|
-
:host {
|
|
240
|
-
position: fixed;
|
|
241
|
-
z-index: 2147483647;
|
|
242
|
-
font-family: "PingFang SC", -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/* \u2500\u2500 FAB \u2500\u2500 */
|
|
246
|
-
.fab-wrap {
|
|
247
|
-
position: relative;
|
|
248
|
-
display: inline-block;
|
|
249
|
-
touch-action: none;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
.fab {
|
|
253
|
-
width: 48px;
|
|
254
|
-
height: 48px;
|
|
255
|
-
border-radius: 50%;
|
|
256
|
-
background: rgba(255, 255, 255, 0.1);
|
|
257
|
-
backdrop-filter: blur(10px);
|
|
258
|
-
-webkit-backdrop-filter: blur(10px);
|
|
259
|
-
border: none;
|
|
260
|
-
cursor: grab;
|
|
261
|
-
display: flex;
|
|
262
|
-
align-items: center;
|
|
263
|
-
justify-content: center;
|
|
264
|
-
overflow: hidden;
|
|
265
|
-
user-select: none;
|
|
266
|
-
-webkit-user-select: none;
|
|
267
|
-
transition: transform 0.2s, background 0.15s;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
.fab:hover {
|
|
271
|
-
transform: scale(1.06);
|
|
272
|
-
background: rgba(255, 255, 255, 0.15);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
.fab.dragging {
|
|
276
|
-
cursor: grabbing;
|
|
277
|
-
transition: none;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
.fab img {
|
|
281
|
-
width: 32px;
|
|
282
|
-
height: 32px;
|
|
283
|
-
pointer-events: none;
|
|
284
|
-
display: block;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
.fab-dot {
|
|
288
|
-
position: absolute;
|
|
289
|
-
top: 2px;
|
|
290
|
-
right: 2px;
|
|
291
|
-
width: 10px;
|
|
292
|
-
height: 10px;
|
|
293
|
-
border-radius: 50%;
|
|
294
|
-
background: #f87171;
|
|
295
|
-
border: 2px solid #1e1e1e;
|
|
296
|
-
display: none;
|
|
297
|
-
pointer-events: none;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
.fab-dot.visible {
|
|
301
|
-
display: block;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/* \u2500\u2500 Panel \u2500\u2500 */
|
|
305
|
-
.panel {
|
|
306
|
-
position: absolute;
|
|
307
|
-
width: 380px;
|
|
308
|
-
max-height: 80vh;
|
|
309
|
-
background: #1e1e1e;
|
|
310
|
-
border-radius: 12px;
|
|
311
|
-
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
|
312
|
-
display: none;
|
|
313
|
-
flex-direction: column;
|
|
314
|
-
overflow: hidden;
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
.panel.open {
|
|
318
|
-
display: flex;
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
/* Header */
|
|
322
|
-
.panel-header {
|
|
323
|
-
flex-shrink: 0;
|
|
324
|
-
display: flex;
|
|
325
|
-
align-items: center;
|
|
326
|
-
justify-content: space-between;
|
|
327
|
-
padding: 16px;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
.panel-title {
|
|
331
|
-
font-size: 16px;
|
|
332
|
-
font-weight: 600;
|
|
333
|
-
color: #fff;
|
|
334
|
-
margin: 0;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
.close-btn {
|
|
338
|
-
width: 32px;
|
|
339
|
-
height: 32px;
|
|
340
|
-
border: none;
|
|
341
|
-
background: transparent;
|
|
342
|
-
color: rgba(255, 255, 255, 0.7);
|
|
343
|
-
cursor: pointer;
|
|
344
|
-
border-radius: 8px;
|
|
345
|
-
display: flex;
|
|
346
|
-
align-items: center;
|
|
347
|
-
justify-content: center;
|
|
348
|
-
transition: background 0.15s, color 0.15s;
|
|
349
|
-
padding: 0;
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
.close-btn:hover {
|
|
353
|
-
background: rgba(130, 70, 255, 0.1);
|
|
354
|
-
color: #fff;
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
.close-btn svg {
|
|
358
|
-
width: 20px;
|
|
359
|
-
height: 20px;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
/* Tabs (segment-control \u6837\u5F0F) */
|
|
363
|
-
.tabs {
|
|
364
|
-
flex-shrink: 0;
|
|
365
|
-
margin: 0 16px 12px;
|
|
366
|
-
display: flex;
|
|
367
|
-
background: #2a2a2a;
|
|
368
|
-
border-radius: 12px;
|
|
369
|
-
padding: 3px;
|
|
370
|
-
gap: 2px;
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
.tab-btn {
|
|
374
|
-
flex: 1;
|
|
375
|
-
padding: 8px 16px;
|
|
376
|
-
background: transparent;
|
|
377
|
-
border: none;
|
|
378
|
-
border-radius: 8px;
|
|
379
|
-
font-size: 13px;
|
|
380
|
-
color: rgba(255, 255, 255, 0.7);
|
|
381
|
-
cursor: pointer;
|
|
382
|
-
transition: all 0.15s;
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
.tab-btn:hover {
|
|
386
|
-
color: #fff;
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
.tab-btn.active {
|
|
390
|
-
background: #8246FF;
|
|
391
|
-
color: #fff;
|
|
392
|
-
font-weight: 500;
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
/* Body */
|
|
396
|
-
.panel-body {
|
|
397
|
-
flex: 1;
|
|
398
|
-
overflow-y: auto;
|
|
399
|
-
overscroll-behavior: contain;
|
|
400
|
-
-webkit-overflow-scrolling: touch;
|
|
401
|
-
padding: 0 16px 16px;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
.panel-body::-webkit-scrollbar {
|
|
405
|
-
width: 6px;
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
.panel-body::-webkit-scrollbar-thumb {
|
|
409
|
-
background: rgba(255, 255, 255, 0.12);
|
|
410
|
-
border-radius: 3px;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
/* \u2500\u2500 Models \u2500\u2500 */
|
|
414
|
-
.category-tabs {
|
|
415
|
-
display: flex;
|
|
416
|
-
flex-wrap: wrap;
|
|
417
|
-
gap: 8px;
|
|
418
|
-
margin-bottom: 16px;
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
.category-tab {
|
|
422
|
-
display: inline-flex;
|
|
423
|
-
align-items: center;
|
|
424
|
-
justify-content: center;
|
|
425
|
-
padding: 6px 14px;
|
|
426
|
-
background: rgba(255, 255, 255, 0.1);
|
|
427
|
-
border: none;
|
|
428
|
-
border-radius: 16px;
|
|
429
|
-
color: rgba(255, 255, 255, 0.7);
|
|
430
|
-
font-size: 12px;
|
|
431
|
-
font-weight: 500;
|
|
432
|
-
cursor: pointer;
|
|
433
|
-
transition: all 0.15s;
|
|
434
|
-
white-space: nowrap;
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
.category-tab:hover {
|
|
438
|
-
background: rgba(255, 255, 255, 0.15);
|
|
439
|
-
color: #fff;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
.category-tab.active {
|
|
443
|
-
background: rgba(130, 70, 255, 0.3);
|
|
444
|
-
color: #fff;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
.models-grid {
|
|
448
|
-
display: grid;
|
|
449
|
-
grid-template-columns: repeat(2, 1fr);
|
|
450
|
-
gap: 12px;
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
.model-card {
|
|
454
|
-
display: flex;
|
|
455
|
-
align-items: center;
|
|
456
|
-
gap: 8px;
|
|
457
|
-
padding: 10px 12px;
|
|
458
|
-
border-radius: 8px;
|
|
459
|
-
cursor: pointer;
|
|
460
|
-
background: #2a2a2a;
|
|
461
|
-
border: none;
|
|
462
|
-
color: #fff;
|
|
463
|
-
transition: background 0.15s;
|
|
464
|
-
overflow: hidden;
|
|
465
|
-
text-align: left;
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
.model-card:hover {
|
|
469
|
-
background: rgba(130, 70, 255, 0.05);
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
.model-card:active {
|
|
473
|
-
background: rgba(130, 70, 255, 0.2);
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
.model-card.selected {
|
|
477
|
-
background: rgba(130, 70, 255, 0.1);
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
.model-card.disabled {
|
|
481
|
-
opacity: 0.7;
|
|
482
|
-
cursor: not-allowed;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
.status-dot {
|
|
486
|
-
width: 8px;
|
|
487
|
-
height: 8px;
|
|
488
|
-
border-radius: 50%;
|
|
489
|
-
flex-shrink: 0;
|
|
490
|
-
pointer-events: none;
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
.model-name {
|
|
494
|
-
flex: 1;
|
|
495
|
-
min-width: 0;
|
|
496
|
-
font-size: 13px;
|
|
497
|
-
font-weight: 500;
|
|
498
|
-
color: #fff;
|
|
499
|
-
white-space: nowrap;
|
|
500
|
-
overflow: hidden;
|
|
501
|
-
text-overflow: ellipsis;
|
|
502
|
-
pointer-events: none;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
/* Model detail */
|
|
506
|
-
.model-detail {
|
|
507
|
-
margin-top: 20px;
|
|
508
|
-
padding: 16px;
|
|
509
|
-
background: #2a2a2a;
|
|
510
|
-
border-radius: 8px;
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
.detail-header {
|
|
514
|
-
display: flex;
|
|
515
|
-
align-items: center;
|
|
516
|
-
justify-content: space-between;
|
|
517
|
-
margin-bottom: 12px;
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
.detail-title {
|
|
521
|
-
font-size: 14px;
|
|
522
|
-
font-weight: 600;
|
|
523
|
-
color: #fff;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
.detail-status {
|
|
527
|
-
font-size: 12px;
|
|
528
|
-
font-weight: 500;
|
|
529
|
-
padding: 2px 8px;
|
|
530
|
-
border-radius: 6px;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
.detail-status.excellent { background: rgba(16, 185, 129, 0.1); color: #10b981; }
|
|
534
|
-
.detail-status.good { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }
|
|
535
|
-
.detail-status.normal { background: rgba(234, 179, 8, 0.1); color: #eab308; }
|
|
536
|
-
.detail-status.crowded { background: rgba(249, 115, 22, 0.1); color: #f97316; }
|
|
537
|
-
.detail-status.inactive { background: rgba(107, 114, 128, 0.1); color: #6b7280; }
|
|
538
|
-
|
|
539
|
-
.detail-credits {
|
|
540
|
-
display: flex;
|
|
541
|
-
align-items: center;
|
|
542
|
-
gap: 4px;
|
|
543
|
-
margin-bottom: 12px;
|
|
544
|
-
font-size: 13px;
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
.credits-label {
|
|
548
|
-
color: rgba(255, 255, 255, 0.7);
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
.credits-value {
|
|
552
|
-
font-weight: 600;
|
|
553
|
-
color: #fff;
|
|
554
|
-
margin-left: 4px;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
.credits-icon {
|
|
558
|
-
width: 16px;
|
|
559
|
-
height: 16px;
|
|
560
|
-
margin-left: 2px;
|
|
561
|
-
display: inline-block;
|
|
562
|
-
vertical-align: middle;
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
.credits-unit {
|
|
566
|
-
font-size: 12px;
|
|
567
|
-
color: rgba(255, 255, 255, 0.7);
|
|
568
|
-
margin-left: 2px;
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
.detail-description {
|
|
572
|
-
font-size: 13px;
|
|
573
|
-
color: rgba(255, 255, 255, 0.7);
|
|
574
|
-
line-height: 1.5;
|
|
575
|
-
white-space: pre-wrap;
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
/* \u2500\u2500 Settings form \u2500\u2500 */
|
|
579
|
-
.form-stack {
|
|
580
|
-
display: flex;
|
|
581
|
-
flex-direction: column;
|
|
582
|
-
gap: 20px;
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
.form-group {
|
|
586
|
-
display: flex;
|
|
587
|
-
flex-direction: column;
|
|
588
|
-
gap: 12px;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
.form-label {
|
|
592
|
-
font-size: 13px;
|
|
593
|
-
font-weight: 500;
|
|
594
|
-
color: #fff;
|
|
595
|
-
display: flex;
|
|
596
|
-
justify-content: space-between;
|
|
597
|
-
align-items: center;
|
|
598
|
-
margin: 0;
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
.temperature-value {
|
|
602
|
-
font-weight: 600;
|
|
603
|
-
color: #8246FF;
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
.form-hint {
|
|
607
|
-
font-size: 12px;
|
|
608
|
-
color: rgba(255, 255, 255, 0.7);
|
|
609
|
-
margin: -8px 0 0;
|
|
610
|
-
line-height: 1.5;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
/* Slider */
|
|
614
|
-
.slider {
|
|
615
|
-
-webkit-appearance: none;
|
|
616
|
-
appearance: none;
|
|
617
|
-
width: 100%;
|
|
618
|
-
height: 8px;
|
|
619
|
-
background: rgba(255, 255, 255, 0.08);
|
|
620
|
-
border-radius: 8px;
|
|
621
|
-
outline: none;
|
|
622
|
-
cursor: pointer;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
.slider::-webkit-slider-thumb {
|
|
626
|
-
-webkit-appearance: none;
|
|
627
|
-
appearance: none;
|
|
628
|
-
width: 24px;
|
|
629
|
-
height: 24px;
|
|
630
|
-
background: #8246FF;
|
|
631
|
-
border-radius: 50%;
|
|
632
|
-
cursor: pointer;
|
|
633
|
-
border: none;
|
|
634
|
-
transition: transform 0.15s, box-shadow 0.15s;
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
.slider::-webkit-slider-thumb:hover {
|
|
638
|
-
transform: scale(1.1);
|
|
639
|
-
box-shadow: 0 0 0 4px rgba(130, 70, 255, 0.2);
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
.slider::-moz-range-thumb {
|
|
643
|
-
width: 24px;
|
|
644
|
-
height: 24px;
|
|
645
|
-
background: #8246FF;
|
|
646
|
-
border-radius: 50%;
|
|
647
|
-
border: none;
|
|
648
|
-
cursor: pointer;
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
.slider-labels {
|
|
652
|
-
display: flex;
|
|
653
|
-
justify-content: space-between;
|
|
654
|
-
font-size: 12px;
|
|
655
|
-
color: rgba(255, 255, 255, 0.6);
|
|
656
|
-
margin-top: 4px;
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
/* Segment-control (\u56DE\u590D\u957F\u5EA6) */
|
|
660
|
-
.segment-control {
|
|
661
|
-
display: flex;
|
|
662
|
-
background: #2a2a2a;
|
|
663
|
-
border-radius: 12px;
|
|
664
|
-
padding: 3px;
|
|
665
|
-
gap: 2px;
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
.segment-button {
|
|
669
|
-
flex: 1;
|
|
670
|
-
padding: 8px 16px;
|
|
671
|
-
background: transparent;
|
|
672
|
-
border: none;
|
|
673
|
-
border-radius: 8px;
|
|
674
|
-
font-size: 13px;
|
|
675
|
-
color: rgba(255, 255, 255, 0.7);
|
|
676
|
-
cursor: pointer;
|
|
677
|
-
transition: all 0.15s;
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
.segment-button:hover {
|
|
681
|
-
color: #fff;
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
.segment-button.active {
|
|
685
|
-
background: #8246FF;
|
|
686
|
-
color: #fff;
|
|
687
|
-
font-weight: 500;
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
/* Custom Select */
|
|
691
|
-
.custom-select {
|
|
692
|
-
position: relative;
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
.select-trigger {
|
|
696
|
-
width: 100%;
|
|
697
|
-
padding: 12px 16px;
|
|
698
|
-
background: #2a2a2a;
|
|
699
|
-
border: none;
|
|
700
|
-
border-radius: 8px;
|
|
701
|
-
font-size: 13px;
|
|
702
|
-
color: #fff;
|
|
703
|
-
cursor: pointer;
|
|
704
|
-
display: flex;
|
|
705
|
-
justify-content: space-between;
|
|
706
|
-
align-items: center;
|
|
707
|
-
text-align: left;
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
.select-arrow {
|
|
711
|
-
color: rgba(255, 255, 255, 0.6);
|
|
712
|
-
font-size: 11px;
|
|
713
|
-
margin-left: 8px;
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
.select-dropdown {
|
|
717
|
-
position: absolute;
|
|
718
|
-
top: calc(100% + 4px);
|
|
719
|
-
left: 0;
|
|
720
|
-
right: 0;
|
|
721
|
-
background: #2a2a2a;
|
|
722
|
-
border-radius: 8px;
|
|
723
|
-
overflow: hidden;
|
|
724
|
-
z-index: 10;
|
|
725
|
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
|
726
|
-
display: none;
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
.select-dropdown.open {
|
|
730
|
-
display: block;
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
.select-option {
|
|
734
|
-
width: 100%;
|
|
735
|
-
padding: 12px 16px;
|
|
736
|
-
background: transparent;
|
|
737
|
-
border: none;
|
|
738
|
-
font-size: 13px;
|
|
739
|
-
color: #fff;
|
|
740
|
-
cursor: pointer;
|
|
741
|
-
display: flex;
|
|
742
|
-
justify-content: space-between;
|
|
743
|
-
align-items: center;
|
|
744
|
-
text-align: left;
|
|
745
|
-
transition: background 0.15s;
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
.select-option:hover {
|
|
749
|
-
background: rgba(255, 255, 255, 0.05);
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
.select-option.active {
|
|
753
|
-
color: #8246FF;
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
.select-option .check {
|
|
757
|
-
width: 16px;
|
|
758
|
-
height: 16px;
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
/* Note input */
|
|
762
|
-
.player-note-input {
|
|
763
|
-
width: 100%;
|
|
764
|
-
padding: 12px;
|
|
765
|
-
background: rgba(255, 255, 255, 0.08);
|
|
766
|
-
border: none;
|
|
767
|
-
border-radius: 8px;
|
|
768
|
-
color: #fff;
|
|
769
|
-
font-size: 13px;
|
|
770
|
-
line-height: 1.5;
|
|
771
|
-
resize: none;
|
|
772
|
-
box-sizing: border-box;
|
|
773
|
-
font-family: inherit;
|
|
774
|
-
outline: none;
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
.player-note-input::placeholder {
|
|
778
|
-
color: rgba(255, 255, 255, 0.4);
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
.char-count {
|
|
782
|
-
font-size: 12px;
|
|
783
|
-
font-weight: normal;
|
|
784
|
-
color: rgba(255, 255, 255, 0.6);
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
/* Sync section label dot */
|
|
788
|
-
.sync-label-wrap {
|
|
789
|
-
display: flex;
|
|
790
|
-
align-items: center;
|
|
791
|
-
gap: 6px;
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
.sync-label-dot {
|
|
795
|
-
width: 8px;
|
|
796
|
-
height: 8px;
|
|
797
|
-
border-radius: 50%;
|
|
798
|
-
background: #f87171;
|
|
799
|
-
display: none;
|
|
800
|
-
flex-shrink: 0;
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
.sync-label-dot.visible {
|
|
804
|
-
display: block;
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
/* Sync hint */
|
|
808
|
-
.sync-hint {
|
|
809
|
-
font-size: 12px;
|
|
810
|
-
color: #f59e0b;
|
|
811
|
-
margin: -8px 0 0;
|
|
812
|
-
line-height: 1.4;
|
|
813
|
-
display: none;
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
.sync-hint.visible {
|
|
817
|
-
display: block;
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
/* Buttons */
|
|
821
|
-
.btn {
|
|
822
|
-
padding: 8px 16px;
|
|
823
|
-
border-radius: 8px;
|
|
824
|
-
border: none;
|
|
825
|
-
font-size: 13px;
|
|
826
|
-
font-weight: 500;
|
|
827
|
-
cursor: pointer;
|
|
828
|
-
transition: all 0.15s;
|
|
829
|
-
display: flex;
|
|
830
|
-
align-items: center;
|
|
831
|
-
gap: 8px;
|
|
832
|
-
justify-content: center;
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
.btn:disabled {
|
|
836
|
-
opacity: 0.5;
|
|
837
|
-
cursor: not-allowed;
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
.btn-sync {
|
|
841
|
-
width: 100%;
|
|
842
|
-
background: rgba(255, 255, 255, 0.08);
|
|
843
|
-
color: #fff;
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
.btn-sync:hover:not(:disabled) {
|
|
847
|
-
background: rgba(255, 255, 255, 0.12);
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
.btn-sync svg {
|
|
851
|
-
width: 16px;
|
|
852
|
-
height: 16px;
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
.btn-sync.success { color: #4ade80; }
|
|
856
|
-
.btn-sync.error { color: #f87171; }
|
|
857
|
-
|
|
858
|
-
/* Footer */
|
|
859
|
-
.panel-footer {
|
|
860
|
-
flex-shrink: 0;
|
|
861
|
-
padding: 16px;
|
|
862
|
-
display: flex;
|
|
863
|
-
justify-content: flex-end;
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
.btn-save {
|
|
867
|
-
background: #8246FF;
|
|
868
|
-
color: #fff;
|
|
869
|
-
padding: 8px 24px;
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
.btn-save:hover:not(:disabled) {
|
|
873
|
-
opacity: 0.9;
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
.spinner {
|
|
877
|
-
display: inline-block;
|
|
878
|
-
width: 12px;
|
|
879
|
-
height: 12px;
|
|
880
|
-
border: 1.5px solid rgba(255, 255, 255, 0.35);
|
|
881
|
-
border-top-color: #fff;
|
|
882
|
-
border-radius: 50%;
|
|
883
|
-
animation: spin 0.6s linear infinite;
|
|
884
|
-
flex-shrink: 0;
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
@keyframes spin {
|
|
888
|
-
to { transform: rotate(360deg); }
|
|
889
|
-
}
|
|
890
|
-
.spin { animation: spin 0.8s linear infinite; }
|
|
891
|
-
|
|
892
|
-
/* \u2500\u2500 Confirm Dialog \u2500\u2500 */
|
|
893
|
-
.confirm-overlay {
|
|
894
|
-
position: fixed;
|
|
895
|
-
inset: 0;
|
|
896
|
-
background: rgba(0, 0, 0, 0.7);
|
|
897
|
-
backdrop-filter: blur(4px);
|
|
898
|
-
-webkit-backdrop-filter: blur(4px);
|
|
899
|
-
display: flex;
|
|
900
|
-
align-items: center;
|
|
901
|
-
justify-content: center;
|
|
902
|
-
z-index: 2147483647;
|
|
903
|
-
opacity: 0;
|
|
904
|
-
transition: opacity 0.2s;
|
|
905
|
-
pointer-events: none;
|
|
906
|
-
padding: 16px;
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
.confirm-overlay.visible {
|
|
910
|
-
opacity: 1;
|
|
911
|
-
pointer-events: auto;
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
.confirm-dialog {
|
|
915
|
-
background: #1e1e1e;
|
|
916
|
-
border-radius: 16px;
|
|
917
|
-
padding: 24px;
|
|
918
|
-
max-width: 360px;
|
|
919
|
-
width: 100%;
|
|
920
|
-
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
|
921
|
-
transform: scale(0.95);
|
|
922
|
-
transition: transform 0.2s;
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
.confirm-overlay.visible .confirm-dialog {
|
|
926
|
-
transform: scale(1);
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
.confirm-title {
|
|
930
|
-
font-size: 16px;
|
|
931
|
-
font-weight: 600;
|
|
932
|
-
color: #fff;
|
|
933
|
-
margin: 0 0 12px;
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
.confirm-message {
|
|
937
|
-
font-size: 14px;
|
|
938
|
-
color: rgba(255, 255, 255, 0.75);
|
|
939
|
-
line-height: 1.5;
|
|
940
|
-
margin: 0 0 20px;
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
.confirm-message:has(.spinner) {
|
|
944
|
-
display: flex;
|
|
945
|
-
align-items: center;
|
|
946
|
-
gap: 8px;
|
|
947
|
-
line-height: 1;
|
|
948
|
-
}
|
|
949
|
-
.confirm-message:has(.spinner) > span:last-child {
|
|
950
|
-
line-height: 1;
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
.confirm-actions {
|
|
954
|
-
display: flex;
|
|
955
|
-
gap: 8px;
|
|
956
|
-
justify-content: flex-end;
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
.btn-confirm-cancel {
|
|
960
|
-
background: rgba(255, 255, 255, 0.08);
|
|
961
|
-
color: #fff;
|
|
962
|
-
padding: 8px 16px;
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
.btn-confirm-cancel:hover {
|
|
966
|
-
background: rgba(255, 255, 255, 0.12);
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
.btn-confirm-ok {
|
|
970
|
-
background: #8246FF;
|
|
971
|
-
color: #fff;
|
|
972
|
-
padding: 8px 16px;
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
.btn-confirm-ok:hover {
|
|
976
|
-
opacity: 0.9;
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
/* \u2500\u2500 Mobile: \u5E95\u90E8\u5F39\u51FA sheet \u2500\u2500 */
|
|
980
|
-
@media (max-width: 768px) {
|
|
981
|
-
.panel {
|
|
982
|
-
position: fixed !important;
|
|
983
|
-
left: 0 !important;
|
|
984
|
-
right: 0 !important;
|
|
985
|
-
bottom: 0 !important;
|
|
986
|
-
top: auto !important;
|
|
987
|
-
width: 100% !important;
|
|
988
|
-
max-height: 85vh;
|
|
989
|
-
border-radius: 16px 16px 0 0;
|
|
990
|
-
box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.5);
|
|
991
|
-
transform: translateY(100%);
|
|
992
|
-
transition: transform 0.3s cubic-bezier(0.32, 0.72, 0, 1), visibility 0s linear 0.3s;
|
|
993
|
-
display: flex;
|
|
994
|
-
visibility: hidden;
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
.panel.open {
|
|
998
|
-
transform: translateY(0);
|
|
999
|
-
visibility: visible;
|
|
1000
|
-
transition: transform 0.3s cubic-bezier(0.32, 0.72, 0, 1), visibility 0s linear 0s;
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
.panel::before {
|
|
1004
|
-
content: '';
|
|
1005
|
-
position: absolute;
|
|
1006
|
-
top: 8px;
|
|
1007
|
-
left: 50%;
|
|
1008
|
-
transform: translateX(-50%);
|
|
1009
|
-
width: 36px;
|
|
1010
|
-
height: 4px;
|
|
1011
|
-
border-radius: 2px;
|
|
1012
|
-
background: rgba(255, 255, 255, 0.2);
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
.panel-header {
|
|
1016
|
-
padding-top: 24px;
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
.panel-footer {
|
|
1020
|
-
padding-bottom: calc(16px + env(safe-area-inset-bottom, 0px));
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
`,Ne='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',Le='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"/></svg>',Ae='<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>',$e='<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>',Ue='<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>',ye='<svg class="check" viewBox="0 0 24 24" fill="none" stroke="#8246FF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',I=48,k=16,Be=5,D=class{constructor(e){this.selectedModelId="";this.pendingModelId="";this.fabWrap=null;this.models=[];this.settings={temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.activeTab="model";this.selectedCategory=null;this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.syncDot=null;this.fabX=0;this.fabY=0;this.fab=null;this.panel=null;this.modelTabBtn=null;this.settingsTabBtn=null;this.modelBody=null;this.settingsBody=null;this.footer=null;this.modelGrid=null;this.modelDetail=null;this.tempValueEl=null;this.segmentBtns=[];this.langDropdown=null;this.langOptions=[];this.langArrow=null;this.langDropdownOpen=!1;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.dragStartX=0;this.dragStartY=0;this.dragOffsetX=0;this.dragOffsetY=0;this.dragMoved=!1;this.dragging=!1;this.updateDialogOpen=!1;this.handlePointerDown=e=>{this.fab&&(e.preventDefault(),this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOffsetX=e.clientX-this.fabX,this.dragOffsetY=e.clientY-this.fabY,this.dragMoved=!1,this.dragging=!0,this.fab.setPointerCapture(e.pointerId),this.fab.addEventListener("pointermove",this.handlePointerMove),this.fab.addEventListener("pointerup",this.handlePointerUp),this.fab.addEventListener("pointercancel",this.handlePointerUp))};this.handlePointerMove=e=>{if(!this.dragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;!this.dragMoved&&Math.hypot(t,n)>Be&&(this.dragMoved=!0,this.fab?.classList.add("dragging"),this.closePanel()),this.dragMoved&&(this.fabX=e.clientX-this.dragOffsetX,this.fabY=e.clientY-this.dragOffsetY,this.applyHostPosition())};this.handlePointerUp=e=>{if(!this.fab)return;this.fab.removeEventListener("pointermove",this.handlePointerMove),this.fab.removeEventListener("pointerup",this.handlePointerUp),this.fab.removeEventListener("pointercancel",this.handlePointerUp);try{this.fab.releasePointerCapture(e.pointerId)}catch{}if(this.dragging=!1,!this.dragMoved){this.togglePanel();return}this.fab.classList.remove("dragging");let n=this.fabX+I/2<window.innerWidth/2;this.fabX=n?k:window.innerWidth-I-k,this.fabY=Math.max(k,Math.min(window.innerHeight-I-k,this.fabY)),this.fab&&(this.fab.style.transition="left 0.25s cubic-bezier(0.32, 0.72, 0, 1), top 0.25s cubic-bezier(0.32, 0.72, 0, 1), transform 0.2s, box-shadow 0.2s"),this.applyHostPosition(),setTimeout(()=>{this.fab&&(this.fab.style.transition="")},260)};this.handleResize=()=>{this.fabX=Math.max(k,Math.min(window.innerWidth-I-k,this.fabX)),this.fabY=Math.max(k,Math.min(window.innerHeight-I-k,this.fabY)),this.applyHostPosition()};this.handleDocClick=e=>{this.host.contains(e.target)||(this.closePanel(),this.closeLangDropdown())};this.savedBodyOverflow=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.pendingModelId=t,this.settings={...n},this.hasWorldUpdate=i,this.fabX=window.innerWidth-I-k,this.fabY=window.innerHeight-I-k,document.body.appendChild(this.host),this.render(),this.applyHostPosition(),window.addEventListener("resize",this.handleResize),document.addEventListener("click",this.handleDocClick),i&&setTimeout(()=>this.showUpdateDialog("prompt"),600)}unmount(){window.removeEventListener("resize",this.handleResize),document.removeEventListener("click",this.handleDocClick),this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=De;let t=document.createElement("div");t.className="fab-wrap",this.fabWrap=t;let n=document.createElement("div");n.className="fab",n.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("img");i.src=_e,i.alt="Storvia",n.appendChild(i),this.fab=n;let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,t.appendChild(n),t.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let l=document.createElement("div");l.className="panel-header";let d=document.createElement("h2");d.className="panel-title",d.textContent="\u6E38\u620F\u8BBE\u7F6E";let a=document.createElement("button");a.className="close-btn",a.innerHTML=Ne,a.addEventListener("click",()=>this.closePanel()),l.appendChild(d),l.appendChild(a),r.appendChild(l);let c=document.createElement("div");c.className="tabs",this.modelTabBtn=this.createTabBtn("model","\u6A21\u578B\u9009\u62E9"),this.settingsTabBtn=this.createTabBtn("settings","\u6E38\u620F\u8BBE\u7F6E"),this.models.length===0&&(this.activeTab="settings",this.modelTabBtn.style.display="none"),c.appendChild(this.modelTabBtn),c.appendChild(this.settingsTabBtn),r.appendChild(c);let p=document.createElement("div");p.className="panel-body",this.modelBody=this.buildModelTab(),this.settingsBody=this.buildSettingsTab(),p.appendChild(this.modelBody),p.appendChild(this.settingsBody),r.appendChild(p);let y=document.createElement("div");y.className="panel-footer";let m=document.createElement("button");m.className="btn btn-save",m.textContent="\u4FDD\u5B58",this.saveBtn=m,m.addEventListener("click",()=>this.handleSave()),y.appendChild(m),this.footer=y,r.appendChild(y),n.addEventListener("pointerdown",this.handlePointerDown);let h=document.createElement("div");h.appendChild(r),h.appendChild(t),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(h),this.applyTab()}createTabBtn(e,t){let n=document.createElement("button");return n.className=`tab-btn${this.activeTab===e?" active":""}`,n.textContent=t,n.addEventListener("click",()=>{this.activeTab=e,this.applyTab()}),n}applyTab(){this.modelTabBtn&&this.modelTabBtn.classList.toggle("active",this.activeTab==="model"),this.settingsTabBtn&&this.settingsTabBtn.classList.toggle("active",this.activeTab==="settings"),this.modelBody&&(this.modelBody.style.display=this.activeTab==="model"?"block":"none"),this.settingsBody&&(this.settingsBody.style.display=this.activeTab==="settings"?"block":"none"),this.footer&&(this.footer.style.display="flex")}buildModelTab(){let e=document.createElement("div"),t=this.getCategories();if(t.length>0){let s=document.createElement("div");s.className="category-tabs";let r=(l,d)=>{let a=document.createElement("button");return a.className=`category-tab${this.selectedCategory===d?" active":""}`,a.textContent=l,a.addEventListener("click",()=>{this.selectedCategory=d,s.querySelectorAll(".category-tab").forEach(c=>c.classList.remove("active")),a.classList.add("active"),this.renderModelGrid()}),a};s.appendChild(r("\u5168\u90E8",null)),t.forEach(l=>s.appendChild(r(l,l))),e.appendChild(s)}let n=document.createElement("div");n.className="models-grid",this.modelGrid=n,e.appendChild(n);let i=document.createElement("div");return i.className="model-detail",i.style.display="none",this.modelDetail=i,e.appendChild(i),this.renderModelGrid(),this.renderModelDetail(),e}getCategories(){let e=new Set;return this.models.forEach(t=>{t.category&&e.add(t.category)}),Array.from(e)}getFilteredModels(){return this.selectedCategory?this.models.filter(e=>e.category===this.selectedCategory):this.models}renderModelGrid(){this.modelGrid&&(this.modelGrid.innerHTML="",this.getFilteredModels().forEach(e=>{let t=document.createElement("button"),n=e.is_active!==!1;t.className=`model-card${e.id===this.pendingModelId?" selected":""}${n?"":" disabled"}`;let i=this.getStatusDotColor(e);t.innerHTML=`<span class="status-dot" style="background:${i}"></span><span class="model-name">${this.escapeHtml(e.name)}</span>`,t.addEventListener("click",()=>this.handleSelectModel(e)),this.modelGrid.appendChild(t)}))}handleSelectModel(e){this.pendingModelId=e.id;let t=this.getFilteredModels();this.modelGrid&&this.modelGrid.querySelectorAll(".model-card").forEach((n,i)=>{n.classList.toggle("selected",t[i].id===this.pendingModelId)}),this.renderModelDetail()}renderModelDetail(){if(!this.modelDetail)return;let e=this.models.find(l=>l.id===this.pendingModelId);if(!e){this.modelDetail.style.display="none";return}this.modelDetail.style.display="block";let t=this.getStatusClass(e),n=this.getStatusText(e),i=this.getCreditsValue(e),s=this.getCreditsUnit(e),r=e.description||"";this.modelDetail.innerHTML=`
|
|
1024
|
-
<div class="detail-header">
|
|
1025
|
-
<span class="detail-title">${this.escapeHtml(e.name)}</span>
|
|
1026
|
-
<span class="detail-status ${t}">${n}</span>
|
|
1027
|
-
</div>
|
|
1028
|
-
${i!==null?`<div class="detail-credits">
|
|
1029
|
-
<span class="credits-label">\u6D88\u8017</span>
|
|
1030
|
-
<span class="credits-value">${i}</span>
|
|
1031
|
-
<img class="credits-icon" src="${Oe}" alt="credits" />
|
|
1032
|
-
<span class="credits-unit">${s}</span>
|
|
1033
|
-
</div>`:""}
|
|
1034
|
-
${r?`<div class="detail-description">${this.escapeHtml(r)}</div>`:""}
|
|
1035
|
-
`}getStatusDotColor(e){if(e.is_active===!1)return"#6b7280";let t=e.success_rate??100;return t>=90?"#10b981":t>=80?"#3b82f6":t>=60?"#eab308":"#f97316"}getStatusClass(e){if(e.is_active===!1)return"inactive";let t=e.success_rate??100;return t>=90?"excellent":t>=80?"good":t>=60?"normal":"crowded"}getStatusText(e){if(e.is_active===!1)return"\u505C\u7528";let t=e.success_rate??100;return t>=90?"\u6D41\u7545":t>=80?"\u826F\u597D":t>=60?"\u4E00\u822C":"\u62E5\u6324"}getCreditsValue(e){let t=e.credits_config;return t?.billing_mode==="per_10k"&&typeof t.per_10k_tokens=="number"?String(t.per_10k_tokens):t?.billing_mode==="flat"&&typeof t.flat=="number"?String(t.flat):null}getCreditsUnit(e){return e.credits_config?.billing_mode==="per_10k"?"/ 10000 token":"/ 1 \u6B21"}buildSettingsTab(){let e=document.createElement("div"),t=document.createElement("div");return t.className="form-stack",t.appendChild(this.buildTemperatureSection()),t.appendChild(this.buildReplyLengthSection()),t.appendChild(this.buildReplyLanguageSection()),t.appendChild(this.buildNoteSection()),t.appendChild(this.buildSyncSection()),e.appendChild(t),e}buildTemperatureSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="temperature-value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u66F4\u4F4E\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u7406\u667A\uFF0C\u66F4\u9AD8\u8BA9\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027",e.appendChild(s);let r=document.createElement("input");r.type="range",r.className="slider",r.min="0",r.max="1",r.step="0.1",r.value=String(this.settings.temperature),r.addEventListener("input",()=>{let d=parseFloat(r.value);this.settings.temperature=d,this.tempValueEl&&(this.tempValueEl.textContent=d.toFixed(1))}),e.appendChild(r);let l=document.createElement("div");return l.className="slider-labels",l.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",e.appendChild(l),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment-control",this.segmentBtns=[],ve.forEach(i=>{let s=document.createElement("button");s.className=`segment-button${i.value===this.settings.replyLength?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.replyLength=i.value,this.segmentBtns.forEach((r,l)=>{r.classList.toggle("active",ve[l].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="custom-select";let i=document.createElement("button");i.className="select-trigger";let s=document.createElement("span");s.textContent=Y.find(d=>d.value===this.settings.replyLanguage)?.label||"";let r=document.createElement("span");r.className="select-arrow",r.textContent="\u25BE",this.langArrow=r,i.appendChild(s),i.appendChild(r),i.addEventListener("click",d=>{d.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let l=document.createElement("div");return l.className="select-dropdown",this.langDropdown=l,this.langOptions=[],Y.forEach(d=>{let a=document.createElement("button");a.className=`select-option${d.value===this.settings.replyLanguage?" active":""}`,a.innerHTML=`<span>${d.label}</span>${d.value===this.settings.replyLanguage?ye:""}`,a.addEventListener("click",()=>{this.settings.replyLanguage=d.value,s.textContent=d.label,this.langOptions.forEach((c,p)=>{c.classList.toggle("active",Y[p].value===d.value),c.innerHTML=`<span>${Y[p].label}</span>${Y[p].value===d.value?ye:""}`}),this.closeLangDropdown()}),this.langOptions.push(a),l.appendChild(a)}),n.appendChild(l),e.appendChild(n),e}toggleLangDropdown(){this.langDropdownOpen?this.closeLangDropdown():this.openLangDropdown()}openLangDropdown(){this.langDropdownOpen=!0,this.langDropdown?.classList.add("open"),this.langArrow&&(this.langArrow.textContent="\u25B4")}closeLangDropdown(){this.langDropdownOpen=!1,this.langDropdown?.classList.remove("open"),this.langArrow&&(this.langArrow.textContent="\u25BE")}buildNoteSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.className="char-count",i.textContent=`${this.settings.playerNote.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",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 r=document.createElement("textarea");return r.className="player-note-input",r.placeholder="\u5907\u6CE8",r.maxLength=50,r.rows=2,r.value=this.settings.playerNote,r.addEventListener("input",()=>{this.settings.playerNote=r.value,this.noteCounter&&(this.noteCounter.textContent=`${r.value.length}/50`)}),e.appendChild(r),e}buildSyncSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label sync-label-wrap";let n=document.createElement("span");n.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A";let i=document.createElement("span");i.className=`sync-label-dot${this.hasWorldUpdate?" visible":""}`,this.syncDot=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,s.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=s,e.appendChild(s);let r=document.createElement("p");r.className="form-hint",r.textContent="\u5C06\u6700\u65B0\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(r);let l=document.createElement("button");return l.className="btn btn-sync",this.syncBtn=l,this.renderSyncBtn(),l.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.syncDot&&this.syncDot.classList.remove("visible"),this.syncHint&&(this.syncHint.textContent="\u2705 \u540C\u6B65\u6210\u529F\uFF0C\u8BF7\u9000\u51FA\u6E38\u620F\u540E\u91CD\u65B0\u6253\u5F00\uFF0C\u6700\u65B0\u8BBE\u5B9A\u5373\u53EF\u751F\u6548",this.syncHint.classList.add("visible")),setTimeout(()=>this.setSyncState("idle"),3e3),this.showUpdateDialog("success")}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(l),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:Le,loading:Ae,success:$e,error:Ue},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`btn btn-sync${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}showUpdateDialog(e="prompt"){if(this.updateDialogOpen)return;this.updateDialogOpen=!0;let t=document.createElement("div");t.className="confirm-overlay";let n=document.createElement("div");n.className="confirm-dialog";let i=document.createElement("h3");i.className="confirm-title";let s=document.createElement("p");s.className="confirm-message";let r=document.createElement("div");r.className="confirm-actions",n.appendChild(i),n.appendChild(s),n.appendChild(r),t.appendChild(n),this.shadowRoot.appendChild(t);let l=()=>{this.updateDialogOpen=!1,t.classList.remove("visible"),setTimeout(()=>t.remove(),200)},d=(c,p,y)=>{let m=document.createElement("button");return m.className=`btn ${p}`,m.textContent=c,m.addEventListener("click",y),m},a=c=>{r.innerHTML="",c==="prompt"?(i.textContent="\u68C0\u6D4B\u5230\u65B0\u7248\u672C",s.textContent="\u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u662F\u5426\u7ACB\u5373\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A\uFF1F",r.appendChild(d("\u7A0D\u540E","btn-confirm-cancel",l)),r.appendChild(d("\u7ACB\u5373\u66F4\u65B0","btn-confirm-ok",async()=>{a("syncing");try{await this.callbacks.onSync(),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncDot&&this.syncDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),this.setSyncState("success"),setTimeout(()=>this.setSyncState("idle"),3e3),a("success")}catch{a("error")}}))):c==="syncing"?(i.textContent="\u6B63\u5728\u540C\u6B65",s.innerHTML='<span class="spinner"></span><span>\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A\u4E2D\uFF0C\u8BF7\u7A0D\u5019...</span>'):c==="success"?(i.textContent="\u540C\u6B65\u6210\u529F",s.textContent="\u9700\u8981\u91CD\u65B0\u542F\u52A8\u6E38\u620F\u624D\u80FD\u5E94\u7528\u6700\u65B0\u8BBE\u5B9A\u3002",r.appendChild(d("\u91CD\u65B0\u542F\u52A8","btn-confirm-ok",()=>{l();try{window.parent.postMessage({type:"storvia-exit"},"*")}catch{}}))):(i.textContent="\u540C\u6B65\u5931\u8D25",s.textContent="\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF0C\u6216\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u3002",r.appendChild(d("\u5173\u95ED","btn-confirm-cancel",l)))};t.addEventListener("click",c=>{c.target===t&&e==="prompt"&&l()}),a(e),requestAnimationFrame(()=>t.classList.add("visible"))}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.innerHTML='<span class="spinner"></span>\u4FDD\u5B58\u4E2D...';try{if(this.pendingModelId&&this.pendingModelId!==this.selectedModelId){let e=this.models.find(t=>t.id===this.pendingModelId);if(e&&e.is_active!==!1){this.selectedModelId=this.pendingModelId,this.callbacks.onModelChange(this.pendingModelId);try{localStorage.setItem(oe,this.pendingModelId)}catch{}}else this.pendingModelId=this.selectedModelId}await this.callbacks.onSettingsChange({temperature:this.settings.temperature,replyLength:this.settings.replyLength,replyLanguage:this.settings.replyLanguage,playerNote:this.settings.playerNote}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1),this.closePanel()}catch{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3))}}}escapeHtml(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}applyHostPosition(){this.host.style.left=`${this.fabX}px`,this.host.style.top=`${this.fabY}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.applyPanelPosition()}isMobile(){return window.innerWidth<=768}applyPanelPosition(){if(!this.panel)return;if(this.isMobile()){this.panel.style.left="",this.panel.style.right="",this.panel.style.top="",this.panel.style.bottom="";return}let e=this.fabX+I/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${I-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${I+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${I+8}px`,this.panel.style.bottom="auto")}togglePanel(){this.panel&&(this.panel.classList.contains("open")?this.closePanel():(this.applyPanelPosition(),this.panel.classList.add("open"),requestAnimationFrame(()=>{this.panel?.classList.contains("open")&&(this.fab&&(this.fab.style.visibility="hidden"),this.fabDot&&(this.fabDot.style.visibility="hidden"),this.fabWrap&&(this.fabWrap.style.pointerEvents="none"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){if(this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.fabWrap&&(this.fabWrap.style.pointerEvents=""),this.unlockBodyScroll(),this.pendingModelId!==this.selectedModelId){if(this.pendingModelId=this.selectedModelId,this.modelGrid){let e=this.getFilteredModels();this.modelGrid.querySelectorAll(".model-card").forEach((t,n)=>{t.classList.toggle("selected",e[n].id===this.pendingModelId)})}this.renderModelDetail()}}lockBodyScroll(){this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow||"",document.body.style.overflow="hidden")}unlockBodyScroll(){this.savedBodyOverflow!==null&&(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)}};var N=class{constructor(e,t,n,i,s=!1,r,l,d){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r,this.getSettings=l,this.getModelName=d}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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,scene_key:e.sceneKey,extract:e.extract,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),ee(e.onState),e.onThinking,e.onCreatedCharacters);return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone,onState:e.onState,onThinking:e.onThinking,onCreatedCharacters:e.onCreatedCharacters});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.sceneKey,extract:e.extract,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),ee(e.onState),e.onThinking,e.onCreatedCharacters);return}return this.http.post("/generate",t,this.reqMeta())}async retry(e={}){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.retry() is not available in preview mode. Publish the game and test on the Storvia platform.");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.sceneKey,extract:e.extract,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),ee(e.onState),e.onThinking,e.onCreatedCharacters);return}return this.http.post("/retry",t,this.reqMeta())}async messages(e){if(this.isPreview)return{data:[],hasMore:!1,nextCursor:null};let t={conversation_id:this.getConversationId(),order:e.order,limit:String(e.limit??20)};e.topic&&(t.topic=e.topic),e.cursor&&(t.cursor_uuid=e.cursor.uuid,t.cursor_created_at=e.cursor.createdAt);let n=await this.http.get("/messages",t);return{data:n.messages.map(i=>({uuid:i.uuid,role:i.role,content:i.content,topic:i.topic,status:i.status,model:i.model,createdAt:i.created_at})),hasMore:n.has_more,nextCursor:n.next_cursor?{uuid:n.next_cursor.cursor_uuid,createdAt:n.next_cursor.cursor_created_at}:null}}async edit(e){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.edit() is not available in preview mode. Publish the game and test on the Storvia platform.");let t=await this.http.patch(`/messages/${encodeURIComponent(e.uuid)}`,{content:e.content});return{uuid:t.uuid,role:t.role,content:t.content,updatedAt:t.updated_at}}async delete(e){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.delete() is not available in preview mode. Publish the game and test on the Storvia platform.");return{uuid:(await this.http.delete(`/messages/${encodeURIComponent(e.uuid)}`)).uuid}}async rollback(e){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.rollback() is not available in preview mode. Publish the game and test on the Storvia platform.");let t=await this.http.post(`/messages/${encodeURIComponent(e.uuid)}/rollback`,{});return{deletedCount:t.deleted_count,deletedUuids:t.deleted_uuids,restoredGameState:t.restored_game_state}}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.getSettings?.();if(n&&(typeof n.temperature=="number"&&(t.temperature=n.temperature),n.replyLength&&(t.reply_length=n.replyLength),n.replyLanguage&&(t.reply_language=n.replyLanguage)),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),ee(e.onState),e.onThinking,e.onCreatedCharacters);return}let i="",s=null,r=null,l=[];await this.http.stream("/preview",t,a=>{i+=a},()=>{},this.reqMeta(),(a,c)=>{s=a,r=c,e.onState&&e.onState(s,r)},void 0,a=>{l=a,e.onCreatedCharacters&&e.onCreatedCharacters(a)});let d={id:"",content:i};return s&&(d.delta=s,r&&(d.full=r)),l.length&&(d.createdNames=l),d}};function ee(o){if(o)return(e,t)=>o(e,t)}var ae=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(e,t){if(this.isPreview){let i=this.mem[e]||{};return t?{...i[t]||{}}:{...i}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let i=this.mem[e]||(this.mem[e]={});i[t]={...i[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},L=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(be)),this.state=new ae(e,t,n,s)}setInitial(e,t){this.mem=e?e.map(be):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(we):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?we(t):{name:e}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push({...e,isPreset:!1});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,description:t?.description,...t?.introduction!==void 0?{introduction:t.introduction}:{},...t?.visibleAtStart!==void 0?{visibleAtStart:t.visibleAtStart}:{},userDescription:t?.userDescription,...t?.gender?{gender:t.gender}:{},...t?.isPreset!==void 0?{isPreset:t.isPreset}:{},state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};function be(o){return{name:o.name,description:o.description,avatar:o.avatar,...o.introduction!==void 0?{introduction:o.introduction}:{},...o.visibleAtStart!==void 0?{visibleAtStart:o.visibleAtStart}:{},...o.gender?{gender:o.gender}:{},...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}function we(o){return{name:o.name,avatar:o.avatar,description:o.description,...o.introduction!==void 0?{introduction:o.introduction}:{},...o.visibleAtStart!==void 0?{visibleAtStart:o.visibleAtStart}:{},...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.gender?{gender:o.gender}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}var A=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(s=>({...s})))}setInitial(e){this.mem=e?e.map(t=>({...t})):[]}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)}`)}};function Ce(o){let e={count:o.count};return o.desc!==void 0&&(e.desc=o.desc),o.icon_url!==void 0&&(e.iconUrl=o.icon_url),e}function le(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o)){let i={};for(let[s,r]of Object.entries(n))i[s]=Ce(r);e[t]=i}return e}function He(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o))e[t]=Ce(n);return e}var $=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=le(i))}setInitial(e){this.mem=e?le(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let n={};for(let[i,s]of Object.entries(this.mem))n[i]={...s};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return He(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return le(t)}async add(e){let{group:t,name:n,count:i=1,desc:s,iconUrl:r}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let d={count:i};s!==void 0&&(d.desc=s),r!==void 0&&(d.iconUrl=r),this.mem[t][n]=d;return}let l={group:t,name:n,count:i};s!==void 0&&(l.desc=s),r!==void 0&&(l.icon_url=r),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,l)}async update(e){let{group:t,name:n,count:i,desc:s,iconUrl:r}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let a=d[n];i!==void 0&&(a.count=i),s!==void 0&&(a.desc=s),r!==void 0&&(a.iconUrl=r);return}let l={};i!==void 0&&(l.count=i),s!==void 0&&(l.desc=s),r!==void 0&&(l.icon_url=r),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,l)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:i,newName:s}=e;if(this.isPreview){let r=this.mem[t];if(!r||!(i in r))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let l=s||i;if(t===n&&l===i)return;if(l in this.mem[n])throw new Error(`Item "${l}" already exists in target group`);this.mem[n][l]=r[i],delete r[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:s})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let s=this.mem[e];if(s&&Object.keys(s).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let i=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${i}`)}};var U=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}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 de=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}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})}},B=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new de(e,t,n,s)}setInitial(e,t){this.memPersona=e?{...e}:{name:""},this.state.setInitial(t)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};function H(o,e){if(!e)return o;let t=o.includes("?")?"&":"?";return`${o}${t}game_id=${encodeURIComponent(e)}`}var F=class{constructor(e,t,n,i=!1,s,r){this.http=e;this.getConversationId=t;this.getGameId=n;this.isPreview=i;this.mem={};this.memInject={};s&&(this.mem=xe(s)),r&&(this.memInject={...r})}setInitial(e,t){this.mem=e?xe(e):{},this.memInject=t?{...t}:{}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(H(`/conversations/${this.getConversationId()}/custom`,this.getGameId()));return e!==void 0?t[e]:t}async set(e,t){if(this.isPreview){for(let[i,s]of Object.entries(e))typeof s=="object"&&s!==null&&typeof this.mem[i]=="object"&&this.mem[i]!==null?this.mem[i]={...this.mem[i],...s}:this.mem[i]=s,t?.inject!==void 0&&(this.memInject[i]=t.inject);return}let n=t?.inject!==void 0?{data:e,inject:t.inject}:e;await this.http.patch(H(`/conversations/${this.getConversationId()}/custom`,this.getGameId()),n)}async setInject(e,t){if(this.isPreview){this.memInject[e]=t;return}await this.http.patch(H(`/conversations/${this.getConversationId()}/custom/inject/${encodeURIComponent(e)}`,this.getGameId()),{inject:t})}getInject(){return{...this.memInject}}async delete(e){if(this.isPreview){delete this.mem[e],delete this.memInject[e];return}await this.http.delete(H(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`,this.getGameId()))}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(H(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,this.getGameId()),{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]}return}await this.http.delete(H(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,this.getGameId()))}};function xe(o){let e={};for(let[t,n]of Object.entries(o))typeof n=="object"&&n!==null&&!Array.isArray(n)?e[t]={...n}:e[t]=n;return e}function Se(o,e){if(!e)return o;let t=o.includes("?")?"&":"?";return`${o}${t}game_id=${encodeURIComponent(e)}`}var G=class{constructor(e,t,n,i=!1,s){this.http=e;this.getConversationId=t;this.getGameId=n;this.isPreview=i;this.mem={};s&&(this.mem={...s})}setInitial(e){this.mem=e?{...e}:{}}async get(){return this.isPreview?{...this.mem}:await this.http.get(Se(`/conversations/${this.getConversationId()}/save`,this.getGameId()))}async set(e){if(this.isPreview){this.mem={...e};return}await this.http.put(Se(`/conversations/${this.getConversationId()}/save`,this.getGameId()),e)}};var q=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n}async get(){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.state.get() is not available in preview mode. Publish the game and test on the Storvia platform. (Use per-module get() like storvia.world.get() if you need to inspect state during preview.)");return this.http.get(`/conversations/${this.getConversationId()}/state`)}};var V=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=null}async get(){return this.isPreview?this.mem?{...this.mem}:null:(await this.http.get(`/conversations/${this.getConversationId()}/summary`)).ai_summary}async update(e){let t=(e??"").trim();if(this.isPreview){let i={content:t,updated_at:new Date().toISOString()};return this.mem=i,{...i}}return(await this.http.patch(`/conversations/${this.getConversationId()}/summary`,{content:t})).ai_summary}};var Ie="/functions/v1/world-engine/v1",Fe="https://api.storvia.ai";function Ge(){return window.__STORVIA__||{}}function Ve(o,e=3e4){let t=Ge();return t.apiBase?Promise.resolve(t):new Promise((n,i)=>{let s=setTimeout(()=>{r(),l(),i(new u("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},e),r=o.on("init",a=>{a.payload?.apiBase&&d({apiBase:a.payload.apiBase,gameId:a.payload.gameId,conversationId:a.payload.conversationId,accessToken:a.payload.accessToken,debug:a.payload.debug})}),l=o.on("preview-init",a=>{a.payload?.apiBase&&d(a.payload)});function d(a){clearTimeout(s),r(),l();let c=window;c.__STORVIA__=a,n(a)}o.send(E("ready",{}))})}var te=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=window.flutter_inappwebview,t=typeof e?.callHandler=="function";this.bus=new O({incoming:window,outgoing:()=>t?null:window.parent,verifySource:t?h=>h.source===null||h.source===window:h=>h.source===window.parent,customSend:t?h=>e.callHandler("storviaBus",h):void 0}),ue(h=>this.bus.send(h));let n=await Ve(this.bus),i=n.apiBase;if(!i)throw new u("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${i}${Ie}`,this.isPreview=!!n.preview,this.previewConfig=n.previewConfig,!n.gameId)throw new u("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=n.gameId,!n.accessToken)throw new u("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=n.accessToken,this.http=new W(this.baseUrl,this.accessToken,!!n.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[h,g]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=h;let x=this.getSavedModelId();this.modelId=n.selectedModelId||(x&&h.some(R=>R.id===x)?x:"")||h[0]?.id||"",this.settingsSheet=new D({onModelChange:R=>this.handleLocalModelChange(R),onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),h.length>0&&this.settingsSheet.mount(h,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let w=()=>this.gameId,f=()=>this.conversationId,_=()=>this.modelId,S=()=>this.models.find(R=>R.id===this.modelId)?.name;this.chat=new N(this.http,w,f,_,!0,this.previewConfig,()=>this.settingsSheet?.getSettings()??null,S),this.characters=new L(this.http,f,!0,g?.characters,g?.characterStates),this.relationships=new A(this.http,f,!0,g?.relationships),this.inventory=new $(this.http,f,!0,g?.inventory),this.world=new U(this.http,f,!0,g?.world),this.player=new B(this.http,f,!0,g?.player,g?.playerState),this.custom=new F(this.http,f,w,!0,g?.custom,g?.custom_inject),this.save=new G(this.http,f,w,!0,g?.save_data),this.state=new q(this.http,f,!0),this.memory=new V(this.http,f,!0),this.initialized=!0,this.listenForPreviewMessages(),this.listenForTokenUpdate();return}this.conversationId=n.conversationId??"";let[s,r]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=s.conversationId,this.models=r;let l=this.getSavedModelId();this.modelId=l&&r.some(h=>h.id===l)?l:r[0]?.id||"";let d=s.settings,a=d?{temperature:d.temperature??1,replyLength:d.reply_length??"medium",replyLanguage:d.reply_language??"zh-CN",playerNote:d.player_note??""}:{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""};this.settingsSheet=new D({onModelChange:h=>this.handleLocalModelChange(h),onSettingsChange:h=>this.saveSettings(h),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(r,this.modelId,a,s.hasWorldUpdate??!1);let c=()=>this.gameId,p=()=>this.conversationId,y=()=>this.modelId,m=()=>this.models.find(h=>h.id===this.modelId)?.name;this.chat=new N(this.http,c,p,y,!1,void 0,void 0,m),this.characters=new L(this.http,p),this.relationships=new A(this.http,p),this.inventory=new $(this.http,p),this.world=new U(this.http,p),this.player=new B(this.http,p),this.custom=new F(this.http,p,c),this.save=new G(this.http,p,c),this.state=new q(this.http,p),this.memory=new V(this.http,p),this.listenForTokenUpdate(),this.initialized=!0}listenForTokenUpdate(){this.bus.on("token-update",e=>{let t=e.payload?.accessToken;typeof t!="string"||!t||(this.accessToken=t,this.http?.setToken(t))})}handleLocalModelChange(e){this.modelId=e,this.bus&&e&&this.bus.send(E("model-change",{modelId:e}))}listenForPreviewMessages(){this.bus.on("set-model",e=>{this.modelId=e.payload.modelId||""}),this.bus.on("config-update",e=>{this.previewConfig=e.payload.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig),this.refreshPreviewSnapshot().catch(t=>{console.warn("[Storvia SDK] refreshPreviewSnapshot failed:",t)})})}async fetchPreviewSnapshot(){try{let e={game_id:this.gameId};return this.previewConfig&&("game_config"in this.previewConfig&&(e.game_config=this.previewConfig.game_config),"game_state"in this.previewConfig&&(e.game_state_override=this.previewConfig.game_state)),await this.http.post("/preview/initial-snapshot",e)}catch(e){return console.warn("[Storvia SDK] fetchPreviewSnapshot failed:",e),null}}async refreshPreviewSnapshot(){let e=await this.fetchPreviewSnapshot();e&&(this.characters?.setInitial(e.characters,e.characterStates),this.player?.setInitial(e.player,e.playerState),this.inventory?.setInitial(e.inventory),this.relationships?.setInitial(e.relationships),this.world?.setInitial(e.world),this.custom?.setInitial(e.custom,e.custom_inject),this.save?.setInitial(e.save_data))}async saveSettings(e){let t={conversation_id:this.conversationId};e.temperature!==void 0&&(t.temperature=e.temperature),e.replyLength!==void 0&&(t.reply_length=e.replyLength),e.replyLanguage!==void 0&&(t.reply_language=e.replyLanguage),e.playerNote!==void 0&&(t.player_note=e.playerNote),await this.http.patch("/settings",t)}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={game_id:this.gameId};this.conversationId&&(e.conversation_id=this.conversationId);let t=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify(e)});if(!t.ok)throw t.status===401?new u("UNAUTHORIZED","User not authenticated"):t.status===404?new u("GAME_NOT_FOUND","Game not found or not published"):new u("INTERNAL_ERROR",`Auth failed: HTTP ${t.status}`);let n=await t.json();return n.data??n}getSavedModelId(){try{return localStorage.getItem(oe)||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${Fe}${Ie}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new W(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let i=this.getSavedModelId();this.modelId=(i&&t.some(a=>a.id===i)?i:"")||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new D({onModelChange:a=>this.handleLocalModelChange(a),onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,replyLength:"medium",replyLanguage:"zh-CN",playerNote:""},!1);let s=()=>this.gameId,r=()=>this.conversationId,l=()=>this.modelId,d=()=>this.models.find(a=>a.id===this.modelId)?.name;this.chat=new N(this.http,s,r,l,!0,void 0,()=>this.settingsSheet?.getSettings()??null,d),this.characters=new L(this.http,r,!0,n?.characters,n?.characterStates),this.relationships=new A(this.http,r,!0,n?.relationships),this.inventory=new $(this.http,r,!0,n?.inventory),this.world=new U(this.http,r,!0,n?.world),this.player=new B(this.http,r,!0,n?.player,n?.playerState),this.custom=new F(this.http,r,s,!0,n?.custom),this.save=new G(this.http,r,s,!0,n?.save_data),this.memory=new V(this.http,r,!0),this.initialized=!0}async getAssets(e,t){let n={asset_type:e};return t&&(n.category=t),(await this.http.get("/assets",n)).map(s=>({id:s.id,name:s.name,url:s.url,assetType:s.asset_type,category:s.category}))}};async function je(o){let e=new te;return o?.dev?await e.initDev(o.dev):await e.init(),e}function Ee(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function ze(o){return Ee(o)?o.value:o}export{z as PROTOCOL_VERSION,O as StorviaBus,u as StorviaError,te as StorviaSDK,je as createStorviaSDK,E as envelope,ze as extractFieldValue,X as isProtocolEnvelope,Ee as isRichFieldValue,Pe as setToastEnabled,fe as showToast};
|
|
237
|
+
`;let t=e.querySelector(".storvia-sheet-title");t&&(t.textContent=o.title);let n=e.querySelector(".storvia-sheet-msg");n&&(n.textContent=o.msg);let r=e.querySelector('[data-role="navigate"]');r&&(r.textContent=o.primaryLabel);let i=()=>{e.isConnected&&(e.classList.add("leaving"),e.classList.remove("show"),setTimeout(()=>{e.remove(),Z===e&&(Z=null)},240))};e.querySelector('[data-role="cancel"]')?.addEventListener("click",i),e.addEventListener("click",s=>{s.target===e&&i()}),r?.addEventListener("click",()=>{if(oe)try{oe(E("navigate",{target:"wallet"})),console.log("[Storvia] navigate \u2192 wallet\uFF1A\u5DF2\u901A\u8FC7 bus \u901A\u77E5\u5BBF\u4E3B\u8DF3\u8F6C\u94B1\u5305\u9875")}catch(s){console.error("[Storvia] navigate \u2192 wallet \u901A\u8FC7 bus \u53D1\u9001\u5931\u8D25:",s)}else console.warn("[Storvia] navigate \u2192 wallet\uFF1A\u5F53\u524D\u672A\u68C0\u6D4B\u5230\u5BBF\u4E3B\uFF08dev \u6A21\u5F0F\uFF09\uFF0C\u6309\u94AE\u5DF2\u70B9\u4F46\u65E0\u4EBA\u63A5\u6536\u3002\u751F\u4EA7\u73AF\u5883\u4F1A\u81EA\u52A8\u8DF3\u5230\u4E3B\u7AD9 /wallet \u6216 App \u94B1\u5305\u9875\u3002");i()}),document.body.appendChild(e),Z=e,requestAnimationFrame(()=>e.classList.add("show"))}var f=class f{constructor(e,t,n=!1,r=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=r}setToken(e){this.token=e}setDebug(e){this.debug=e}maybeShowNetworkToast(e){e instanceof u||S("NETWORK_ERROR")}wrapAbortError(e){if(e instanceof DOMException&&e.name==="AbortError"){let t=new u("REQUEST_TIMEOUT","Request timed out");return S("REQUEST_TIMEOUT"),t}return e}createTimeoutController(){let e=new AbortController,t=setTimeout(()=>e.abort(),f.REQUEST_TIMEOUT);return{controller:e,clear:()=>clearTimeout(t)}}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){if(!this.debug)return;let{method:t,path:n,body:r,status:i,rawResponse:s,parsedData:c,error:d,durationMs:a,modelName:h}=e,l="%c[Storvia SDK]",m="color: #6366f1; font-weight: bold",p=a!==void 0?` (${a}ms)`:"",g=i!==void 0?` [${i}]`:"",b=h?` [model: ${h}]`:"";d?(console.groupCollapsed(`${l} %c${t} ${n}${g}${b}${p} %c\u2717`,m,"color: #e0e0e0","color: #ef4444"),r!==void 0&&console.log("Request:",r),s!==void 0&&console.log("Response (raw):",s),console.error("Error:",d),console.groupEnd()):(console.groupCollapsed(`${l} %c${t} ${n}${g}${b}${p} %c\u2713`,m,"color: #e0e0e0","color: #22c55e"),r!==void 0&&console.log("Request:",r),s!==void 0&&console.log("Response (raw):",s),c!==void 0&&c!==s&&console.log("Response (data):",c),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([a,h])=>n.searchParams.set(a,h));let r=Date.now(),i,s,{controller:c,clear:d}=this.createTimeoutController();try{let a=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders(),signal:c.signal});d(),i=a.status;let{raw:h,data:l}=await this.handleResponseWithRaw(a);return s=h,this.log({method:"GET",path:e,body:t,status:i,rawResponse:s,parsedData:l,durationMs:Date.now()-r}),l}catch(a){d();let h=this.wrapAbortError(a);throw this.log({method:"GET",path:e,body:t,status:i,rawResponse:s,error:h,durationMs:Date.now()-r}),h===a&&this.maybeShowNetworkToast(a),h}}async post(e,t,n){let r=Date.now(),i,s,{controller:c,clear:d}=this.createTimeoutController();try{let a=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0,signal:c.signal});d(),i=a.status;let{raw:h,data:l}=await this.handleResponseWithRaw(a);return s=h,this.log({method:"POST",path:e,body:t,status:i,rawResponse:s,parsedData:l,durationMs:Date.now()-r,modelName:n?.modelName}),l}catch(a){d();let h=this.wrapAbortError(a);throw this.log({method:"POST",path:e,body:t,status:i,rawResponse:s,error:h,durationMs:Date.now()-r,modelName:n?.modelName}),h===a&&this.maybeShowNetworkToast(a),h}}async patch(e,t){let n=Date.now(),r,i,{controller:s,clear:c}=this.createTimeoutController();try{let d=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0,signal:s.signal});c(),r=d.status;let{raw:a,data:h}=await this.handleResponseWithRaw(d);return i=a,this.log({method:"PATCH",path:e,body:t,status:r,rawResponse:i,parsedData:h,durationMs:Date.now()-n}),h}catch(d){c();let a=this.wrapAbortError(d);throw this.log({method:"PATCH",path:e,body:t,status:r,rawResponse:i,error:a,durationMs:Date.now()-n}),a===d&&this.maybeShowNetworkToast(d),a}}async put(e,t){let n=Date.now(),r,i,{controller:s,clear:c}=this.createTimeoutController();try{let d=await fetch(`${this.baseUrl}${e}`,{method:"PUT",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0,signal:s.signal});c(),r=d.status;let{raw:a,data:h}=await this.handleResponseWithRaw(d);return i=a,this.log({method:"PUT",path:e,body:t,status:r,rawResponse:i,parsedData:h,durationMs:Date.now()-n}),h}catch(d){c();let a=this.wrapAbortError(d);throw this.log({method:"PUT",path:e,body:t,status:r,rawResponse:i,error:a,durationMs:Date.now()-n}),a===d&&this.maybeShowNetworkToast(d),a}}async delete(e){let t=Date.now(),n,r,{controller:i,clear:s}=this.createTimeoutController();try{let c=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders(),signal:i.signal});s(),n=c.status;let{raw:d,data:a}=await this.handleResponseWithRaw(c);return r=d,this.log({method:"DELETE",path:e,status:n,rawResponse:r,parsedData:a,durationMs:Date.now()-t}),a}catch(c){s();let d=this.wrapAbortError(c);throw this.log({method:"DELETE",path:e,status:n,rawResponse:r,error:d,durationMs:Date.now()-t}),d===c&&this.maybeShowNetworkToast(c),d}}async stream(e,t,n,r,i,s,c,d,a,h){let l=Date.now(),m=i?.modelName?` [model: ${i.modelName}]`:"",p=[],g=w=>{this.debug&&p.push({t:Date.now()-l,event:w})},b=new AbortController,C=null,I=null,P=null,R=null,k=()=>{C!==null&&(clearTimeout(C),C=null),I!==null&&(clearTimeout(I),I=null),P!==null&&(clearTimeout(P),P=null)},K=w=>{R=w,k(),b.abort()};C=setTimeout(()=>K("REQUEST_TIMEOUT"),f.REQUEST_TIMEOUT);let T;try{T=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t),signal:b.signal})}catch(w){if(k(),R){let y=new u(R,"Request timed out");throw S(R),this.log({method:"STREAM",path:e,body:t,error:y,durationMs:Date.now()-l,modelName:i?.modelName}),y}throw this.maybeShowNetworkToast(w),w}if(C!==null&&(clearTimeout(C),C=null),!T.ok){k();let w=await T.text().catch(()=>""),y={};try{y=JSON.parse(w)}catch{}let ne=y.code||"INTERNAL_ERROR",z=new u(ne,y.message||`HTTP ${T.status}`);throw S(ne,y.message),this.log({method:"STREAM",path:e,body:t,status:T.status,rawResponse:w,error:z,durationMs:Date.now()-l,modelName:i?.modelName}),z}let ce=T.body?.getReader();if(!ce)throw k(),new u("INTERNAL_ERROR","No response body for stream");I=setTimeout(()=>K("MODEL_LOADING_TIMEOUT"),f.MODEL_LOADING_TIMEOUT);let Te=new TextDecoder,V="",x="",le=!1,te,q;try{for(;;){let{done:w,value:y}=await ce.read();if(w)break;let z=Te.decode(y,{stream:!0}).split(`
|
|
238
|
+
`);for(let Y of z){if(Y.startsWith("id: ")){q=Y.slice(4);continue}if(!Y.startsWith("data: "))continue;let re=Y.slice(6);if(re==="[DONE]"){g("[DONE]"),k(),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${T.status}]${m} (${Date.now()-l}ms) %c\u2713`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #22c55e"),console.log("Request:",t),console.log(`Accumulated content (${x.length} chars):`,x),console.log("Message ID:",V),console.log(`SSE events (${p.length}):`,p),console.groupEnd()),r(V);return}try{let v=JSON.parse(re);g(v),v.type==="done"&&v.id?V=v.id:v.type==="state"?(s&&s(v.delta,v.full??null),d&&Array.isArray(v.createdNames)&&v.createdNames.length&&d(v.createdNames)):v.type==="thinking"?c&&(v.status==="start"||v.status==="end")&&c(v.status):v.content&&(le?(P!==null&&clearTimeout(P),P=setTimeout(()=>K("STREAM_INACTIVITY"),f.STREAM_INACTIVITY_TIMEOUT)):(le=!0,I!==null&&(clearTimeout(I),I=null),P=setTimeout(()=>K("STREAM_INACTIVITY"),f.STREAM_INACTIVITY_TIMEOUT)),x+=v.content,n(v.content))}catch{g({raw:re})}q!==void 0&&(te=q,q=void 0)}}}catch(w){if(k(),R){let y=new u(R,R==="MODEL_LOADING_TIMEOUT"?"Model loading timed out":"Stream inactivity timed out");throw S(R),this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${T.status}]${m} (${Date.now()-l}ms) %c\u2717 ${R}`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${x.length} chars):`,x),console.log(`SSE events (${p.length}):`,p),console.error("Timeout:",y),console.groupEnd()),y}if(this.debug&&(console.groupCollapsed(`%c[Storvia SDK] %cSTREAM ${e} [${T.status}]${m} (${Date.now()-l}ms) %c\u2717`,"color: #6366f1; font-weight: bold","color: #e0e0e0","color: #ef4444"),console.log("Request:",t),console.log(`Accumulated content (${x.length} chars):`,x),console.log(`SSE events (${p.length}):`,p),console.error("Stream error:",w),console.groupEnd()),a){await this.resumeLoop(a,te,{onChunk:n,onDone:r,onState:s,onThinking:c,onCreatedCharacters:d,onReconnect:h});return}throw w}if(k(),V){r(V);return}a&&await this.resumeLoop(a,te,{onChunk:n,onDone:r,onState:s,onThinking:c,onCreatedCharacters:d,onReconnect:h})}async resumeLoop(e,t,n){let r=t;for(let s=1;s<=f.RECONNECT_MAX_ATTEMPTS;s++){let c=Math.min(f.RECONNECT_BACKOFF_CAP,1e3*2**(s-1));await new Promise(h=>setTimeout(h,c)),n.onReconnect?.({attempt:s});let d={messageId:"",lastId:r},a;try{a=await this.pumpGetStream(e.conversationId,e.topic,r,d,n)}catch{continue}if(r=d.lastId??r,a==="done"){n.onDone(d.messageId);return}if(a==="inactive"){d.messageId&&n.onDone(d.messageId);return}}let i=new u("STREAM_INTERRUPTED","Stream reconnection failed after maximum attempts");throw S("STREAM_INTERRUPTED"),i}async resumeStream(e,t,n){let r={messageId:""},i;try{i=await this.pumpGetStream(e,t,void 0,r,n)}catch{await this.resumeLoop({conversationId:e,topic:t},r.lastId,n);return}if(i==="done"){n.onDone(r.messageId);return}if(i==="inactive"){r.messageId&&n.onDone(r.messageId);return}await this.resumeLoop({conversationId:e,topic:t},r.lastId,n)}async pumpGetStream(e,t,n,r,i){let s=new URL(`${this.baseUrl}/conversations/${encodeURIComponent(e)}/stream`);n&&s.searchParams.set("from",n),t&&s.searchParams.set("topic",t);let c=new AbortController,d=setTimeout(()=>c.abort(),f.REQUEST_TIMEOUT),a;try{a=await fetch(s.toString(),{method:"GET",headers:this.buildHeaders(),signal:c.signal})}finally{clearTimeout(d)}if(!a.ok)throw new u("STREAM_INTERRUPTED",`Resume HTTP ${a.status}`);if(!(a.headers.get("content-type")||"").includes("text/event-stream"))return"inactive";let l=a.body?.getReader();return l?await this.pumpReader(l,r,i):"inactive"}async pumpReader(e,t,n){let r=new TextDecoder,i,s=null,c=()=>{s&&clearTimeout(s),s=setTimeout(()=>{e.cancel().catch(()=>{})},f.STREAM_INACTIVITY_TIMEOUT)};c();try{for(;;){let{done:d,value:a}=await e.read();if(d)break;c();let h=r.decode(a,{stream:!0});for(let l of h.split(`
|
|
239
|
+
`)){if(l.startsWith("id: ")){i=l.slice(4);continue}if(!l.startsWith("data: "))continue;let m=l.slice(6);if(m==="[DONE]")return s&&clearTimeout(s),"done";try{let p=JSON.parse(m);p.type==="done"&&p.id?t.messageId=p.id:p.type==="state"?(n.onState?.(p.delta,p.full??null),Array.isArray(p.createdNames)&&p.createdNames.length&&n.onCreatedCharacters?.(p.createdNames)):p.type==="thinking"?(p.status==="start"||p.status==="end")&&n.onThinking?.(p.status):p.content&&n.onChunk(p.content)}catch{}i!==void 0&&(t.lastId=i,i=void 0)}}}catch{}finally{s&&clearTimeout(s)}return"eof"}async handleResponseWithRaw(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{n=t}if(!e.ok){let r=n&&typeof n=="object"?n:{},i={401:"UNAUTHORIZED",402:"INSUFFICIENT_CREDITS",429:"RATE_LIMITED"},s=r.code||i[e.status]||"INTERNAL_ERROR",c=new u(s,r.message||`HTTP ${e.status}`);throw S(s,r.message),c}return n&&typeof n=="object"&&"data"in n?{raw:n,data:n.data}:{raw:n,data:n}}};f.REQUEST_TIMEOUT=6e4,f.MODEL_LOADING_TIMEOUT=18e4,f.STREAM_INACTIVITY_TIMEOUT=6e4,f.RECONNECT_MAX_ATTEMPTS=10,f.RECONNECT_BACKOFF_CAP=15e3;var B=f;var O=class{constructor(e,t,n,r,i=!1,s,c){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=r;this.isPreview=i;this.previewConfig=s,this.getModelName=c}reqMeta(){let e=this.getModelName?.();return e?{modelName:e}:void 0}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,scene_key:e.sceneKey,extract:e.extract,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),H(e.onState),e.onThinking,e.onCreatedCharacters,{conversationId:this.getConversationId(),topic:e.topic},e.onReconnecting);return}return this.http.post("/chat",t,this.reqMeta())}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,sceneKey:e.sceneKey,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone,onState:e.onState,onThinking:e.onThinking,onCreatedCharacters:e.onCreatedCharacters});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.sceneKey,extract:e.extract,stream:e.stream??!1};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),H(e.onState),e.onThinking,e.onCreatedCharacters,{conversationId:this.getConversationId(),topic:e.topic},e.onReconnecting);return}return this.http.post("/generate",t,this.reqMeta())}async retry(e={}){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.retry() is not available in preview mode. Publish the game and test on the Storvia platform.");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.sceneKey,extract:e.extract,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),H(e.onState),e.onThinking,e.onCreatedCharacters,{conversationId:this.getConversationId(),topic:e.topic},e.onReconnecting);return}return this.http.post("/retry",t,this.reqMeta())}async messages(e){if(this.isPreview)return{data:[],hasMore:!1,nextCursor:null};let t={conversation_id:this.getConversationId(),order:e.order,limit:String(e.limit??20)};e.topic&&(t.topic=e.topic),e.cursor&&(t.cursor_uuid=e.cursor.uuid,t.cursor_created_at=e.cursor.createdAt);let n=await this.http.get("/messages",t);return{data:n.messages.map(r=>({uuid:r.uuid,role:r.role,content:r.content,topic:r.topic,status:r.status,model:r.model,createdAt:r.created_at})),hasMore:n.has_more,nextCursor:n.next_cursor?{uuid:n.next_cursor.cursor_uuid,createdAt:n.next_cursor.cursor_created_at}:null}}async edit(e){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.edit() is not available in preview mode. Publish the game and test on the Storvia platform.");let t=await this.http.patch(`/messages/${encodeURIComponent(e.uuid)}`,{content:e.content});return{uuid:t.uuid,role:t.role,content:t.content,updatedAt:t.updated_at}}async delete(e){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.delete() is not available in preview mode. Publish the game and test on the Storvia platform.");return{uuid:(await this.http.delete(`/messages/${encodeURIComponent(e.uuid)}`)).uuid}}async rollback(e){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.chat.rollback() is not available in preview mode. Publish the game and test on the Storvia platform.");let t=await this.http.post(`/messages/${encodeURIComponent(e.uuid)}/rollback`,{});return{deletedCount:t.deleted_count,deletedUuids:t.deleted_uuids,restoredGameState:t.restored_game_state}}async active(e={}){if(this.isPreview)return{active:!1};let t={};return e.topic&&(t.topic=e.topic),this.http.get(`/conversations/${encodeURIComponent(this.getConversationId())}/active`,t)}async resume(e={}){this.isPreview||await this.http.resumeStream(this.getConversationId(),e.topic,{onChunk:e.onChunk??(()=>{}),onDone:e.onDone??(()=>{}),onState:H(e.onState),onThinking:e.onThinking,onCreatedCharacters:e.onCreatedCharacters,onReconnect:e.onReconnecting})}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.sceneKey,history_messages:[]};this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId();let n=this.previewConfig;if(n?.reply_length&&(t.reply_length=n.reply_length),n?.reply_language&&(t.reply_language=n.reply_language),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}),this.reqMeta(),H(e.onState),e.onThinking,e.onCreatedCharacters);return}let r="",i=null,s=null,c=[];await this.http.stream("/preview",t,a=>{r+=a},()=>{},this.reqMeta(),(a,h)=>{i=a,s=h,e.onState&&e.onState(i,s)},void 0,a=>{c=a,e.onCreatedCharacters&&e.onCreatedCharacters(a)});let d={id:"",content:r};return i&&(d.delta=i,s&&(d.full=s)),c.length&&(d.createdNames=c),d}};function H(o){if(o)return(e,t)=>o(e,t)}var se=class{constructor(e,t,n=!1,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};r&&(this.mem={...r})}setInitial(e){this.mem=e?{...e}:{}}async get(e,t){if(this.isPreview){let r=this.mem[e]||{};return t?{...r[t]||{}}:{...r}}let n=t?{group:t}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,n)}async update(e,t,n){if(this.isPreview){let r=this.mem[e]||(this.mem[e]={});r[t]={...r[t]||{},...n};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{group:t,values:n})}},A=class{constructor(e,t,n=!1,r,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];r&&(this.mem=r.map(ve)),this.state=new se(e,t,n,i)}setInitial(e,t){this.mem=e?e.map(ve):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(fe):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?fe(t):{name:e}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push({...e,isPreset:!1});return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(r=>r.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,description:t?.description,...t?.introduction!==void 0?{introduction:t.introduction}:{},...t?.visibleAtStart!==void 0?{visibleAtStart:t.visibleAtStart}:{},userDescription:t?.userDescription,...t?.gender?{gender:t.gender}:{},...t?.isPreset!==void 0?{isPreset:t.isPreset}:{},state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};function ve(o){return{name:o.name,description:o.description,avatar:o.avatar,...o.introduction!==void 0?{introduction:o.introduction}:{},...o.visibleAtStart!==void 0?{visibleAtStart:o.visibleAtStart}:{},...o.gender?{gender:o.gender}:{},...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}function fe(o){return{name:o.name,avatar:o.avatar,description:o.description,...o.introduction!==void 0?{introduction:o.introduction}:{},...o.visibleAtStart!==void 0?{visibleAtStart:o.visibleAtStart}:{},...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.gender?{gender:o.gender}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}var M=class{constructor(e,t,n=!1,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];r&&(this.mem=r.map(i=>({...i})))}setInitial(e){this.mem=e?e.map(t=>({...t})):[]}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(r=>r.from===e&&r.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 r=this.mem.find(i=>i.from===e&&i.to===t);r?Object.assign(r,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)}`)}};function we(o){let e={count:o.count};return o.desc!==void 0&&(e.desc=o.desc),o.icon_url!==void 0&&(e.iconUrl=o.icon_url),e}function ae(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o)){let r={};for(let[i,s]of Object.entries(n))r[i]=we(s);e[t]=r}return e}function ke(o){let e={};if(!o)return e;for(let[t,n]of Object.entries(o))e[t]=we(n);return e}var D=class{constructor(e,t,n=!1,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};r&&(this.mem=ae(r))}setInitial(e){this.mem=e?ae(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let n={};for(let[r,i]of Object.entries(this.mem))n[r]={...i};return n}if(e!==void 0){let n=await this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`);return ke(n)}let t=await this.http.get(`/conversations/${this.getConversationId()}/inventory`);return ae(t)}async add(e){let{group:t,name:n,count:r=1,desc:i,iconUrl:s}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let d={count:r};i!==void 0&&(d.desc=i),s!==void 0&&(d.iconUrl=s),this.mem[t][n]=d;return}let c={group:t,name:n,count:r};i!==void 0&&(c.desc=i),s!==void 0&&(c.icon_url=s),await this.http.post(`/conversations/${this.getConversationId()}/inventory`,c)}async update(e){let{group:t,name:n,count:r,desc:i,iconUrl:s}=e;if(this.isPreview){let d=this.mem[t];if(!d||!(n in d))throw new Error(`Item "${t}/${n}" not found`);let a=d[n];r!==void 0&&(a.count=r),i!==void 0&&(a.desc=i),s!==void 0&&(a.iconUrl=s);return}let c={};r!==void 0&&(c.count=r),i!==void 0&&(c.desc=i),s!==void 0&&(c.icon_url=s),await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,c)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:r,newName:i}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(r in s))throw new Error(`Source item "${t}/${r}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let c=i||r;if(t===n&&c===r)return;if(c in this.mem[n])throw new Error(`Item "${c}" already exists in target group`);this.mem[n][c]=s[r],delete s[r];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:r,newName:i})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let i=this.mem[e];if(i&&Object.keys(i).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let r=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${r}`)}};var N=class{constructor(e,t,n=!1,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};r&&(this.mem={...r})}setInitial(e){this.mem=e?{...e}:{}}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 de=class{constructor(e,t,n=!1,r){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};r&&(this.mem={...r})}setInitial(e){this.mem=e?{...e}:{}}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})}},U=class{constructor(e,t,n=!1,r,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};r&&(this.memPersona={...r}),this.state=new de(e,t,n,i)}setInitial(e,t){this.memPersona=e?{...e}:{name:""},this.state.setInitial(t)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};function $(o,e){if(!e)return o;let t=o.includes("?")?"&":"?";return`${o}${t}game_id=${encodeURIComponent(e)}`}var L=class{constructor(e,t,n,r=!1,i,s){this.http=e;this.getConversationId=t;this.getGameId=n;this.isPreview=r;this.mem={};this.memInject={};i&&(this.mem=ye(i)),s&&(this.memInject={...s})}setInitial(e,t){this.mem=e?ye(e):{},this.memInject=t?{...t}:{}}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`,this.getGameId()));return e!==void 0?t[e]:t}async set(e,t){if(this.isPreview){for(let[r,i]of Object.entries(e))typeof i=="object"&&i!==null&&typeof this.mem[r]=="object"&&this.mem[r]!==null?this.mem[r]={...this.mem[r],...i}:this.mem[r]=i,t?.inject!==void 0&&(this.memInject[r]=t.inject);return}let n=t?.inject!==void 0?{data:e,inject:t.inject}:e;await this.http.patch($(`/conversations/${this.getConversationId()}/custom`,this.getGameId()),n)}async setInject(e,t){if(this.isPreview){this.memInject[e]=t;return}await this.http.patch($(`/conversations/${this.getConversationId()}/custom/inject/${encodeURIComponent(e)}`,this.getGameId()),{inject:t})}getInject(){return{...this.memInject}}async delete(e){if(this.isPreview){delete this.mem[e],delete this.memInject[e];return}await this.http.delete($(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`,this.getGameId()))}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)}`,this.getGameId()),{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]}return}await this.http.delete($(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,this.getGameId()))}};function ye(o){let e={};for(let[t,n]of Object.entries(o))typeof n=="object"&&n!==null&&!Array.isArray(n)?e[t]={...n}:e[t]=n;return e}function Ie(o,e){if(!e)return o;let t=o.includes("?")?"&":"?";return`${o}${t}game_id=${encodeURIComponent(e)}`}var F=class{constructor(e,t,n,r=!1,i){this.http=e;this.getConversationId=t;this.getGameId=n;this.isPreview=r;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(){return this.isPreview?{...this.mem}:await this.http.get(Ie(`/conversations/${this.getConversationId()}/save`,this.getGameId()))}async set(e){if(this.isPreview){this.mem={...e};return}await this.http.put(Ie(`/conversations/${this.getConversationId()}/save`,this.getGameId()),e)}};var W=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n}async get(){if(this.isPreview)throw new u("NOT_SUPPORTED_IN_PREVIEW","storvia.state.get() is not available in preview mode. Publish the game and test on the Storvia platform. (Use per-module get() like storvia.world.get() if you need to inspect state during preview.)");return this.http.get(`/conversations/${this.getConversationId()}/state`)}};var G=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=null}async get(){return this.isPreview?this.mem?{...this.mem}:null:(await this.http.get(`/conversations/${this.getConversationId()}/summary`)).ai_summary}async update(e){let t=(e??"").trim();if(this.isPreview){let r={content:t,updated_at:new Date().toISOString()};return this.mem=r,{...r}}return(await this.http.patch(`/conversations/${this.getConversationId()}/summary`,{content:t})).ai_summary}};var Ce="/functions/v1/world-engine/v1",xe="https://api.storvia.ai";function _e(){return window.__STORVIA__||{}}function Oe(o,e=3e4){let t=_e();return t.apiBase?Promise.resolve(t):new Promise((n,r)=>{let i=setTimeout(()=>{s(),c(),r(new u("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},e),s=o.on("init",a=>{a.payload?.apiBase&&d({apiBase:a.payload.apiBase,gameId:a.payload.gameId,conversationId:a.payload.conversationId,accessToken:a.payload.accessToken,selectedModelId:a.payload.selectedModelId,debug:a.payload.debug})}),c=o.on("preview-init",a=>{a.payload?.apiBase&&d(a.payload)});function d(a){clearTimeout(i),s(),c();let h=window;h.__STORVIA__=a,n(a)}o.send(E("ready",{}))})}var ee=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.models=[];this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=window.flutter_inappwebview,t=typeof e?.callHandler=="function";this.bus=new _({incoming:window,outgoing:()=>t?null:window.parent,verifySource:t?l=>l.source===null||l.source===window:l=>l.source===window.parent,customSend:t?l=>e.callHandler("storviaBus",l):void 0}),pe(l=>this.bus.send(l));let n=await Oe(this.bus),r=n.apiBase;if(!r)throw new u("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${r}${Ce}`,this.isPreview=!!n.preview,this.previewConfig=n.previewConfig,!n.gameId)throw new u("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=n.gameId,!n.accessToken)throw new u("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=n.accessToken,this.http=new B(this.baseUrl,this.accessToken,!!n.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[l,m]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=l,this.modelId=(n.selectedModelId&&l.some(I=>I.id===n.selectedModelId)?n.selectedModelId:"")||l[0]?.id||"";let p=()=>this.gameId,g=()=>this.conversationId,b=()=>this.modelId,C=()=>this.models.find(I=>I.id===this.modelId)?.name;this.chat=new O(this.http,p,g,b,!0,this.previewConfig,C),this.characters=new A(this.http,g,!0,m?.characters,m?.characterStates),this.relationships=new M(this.http,g,!0,m?.relationships),this.inventory=new D(this.http,g,!0,m?.inventory),this.world=new N(this.http,g,!0,m?.world),this.player=new U(this.http,g,!0,m?.player,m?.playerState),this.custom=new L(this.http,g,p,!0,m?.custom,m?.custom_inject),this.save=new F(this.http,g,p,!0,m?.save_data),this.state=new W(this.http,g,!0),this.memory=new G(this.http,g,!0),this.initialized=!0,this.listenForPreviewMessages(),this.listenForTokenUpdate();return}this.conversationId=n.conversationId??"";let[i,s]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=i.conversationId,this.models=s,this.modelId=(n.selectedModelId&&s.some(l=>l.id===n.selectedModelId)?n.selectedModelId:"")||s[0]?.id||"";let c=()=>this.gameId,d=()=>this.conversationId,a=()=>this.modelId,h=()=>this.models.find(l=>l.id===this.modelId)?.name;this.chat=new O(this.http,c,d,a,!1,void 0,h),this.characters=new A(this.http,d),this.relationships=new M(this.http,d),this.inventory=new D(this.http,d),this.world=new N(this.http,d),this.player=new U(this.http,d),this.custom=new L(this.http,d,c),this.save=new F(this.http,d,c),this.state=new W(this.http,d),this.memory=new G(this.http,d),this.listenForTokenUpdate(),this.listenForModelChange(),this.initialized=!0}listenForModelChange(){this.bus.on("set-model",e=>{let t=e.payload?.modelId||"";t&&(this.modelId=t)})}listenForTokenUpdate(){this.bus.on("token-update",e=>{let t=e.payload?.accessToken;typeof t!="string"||!t||(this.accessToken=t,this.http?.setToken(t))})}listenForPreviewMessages(){this.bus.on("set-model",e=>{this.modelId=e.payload.modelId||""}),this.bus.on("config-update",e=>{this.previewConfig=e.payload.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig),this.refreshPreviewSnapshot().catch(t=>{console.warn("[Storvia SDK] refreshPreviewSnapshot failed:",t)})})}async fetchPreviewSnapshot(){try{let e={game_id:this.gameId};return this.previewConfig&&("game_config"in this.previewConfig&&(e.game_config=this.previewConfig.game_config),"game_state"in this.previewConfig&&(e.game_state_override=this.previewConfig.game_state)),await this.http.post("/preview/initial-snapshot",e)}catch(e){return console.warn("[Storvia SDK] fetchPreviewSnapshot failed:",e),null}}async refreshPreviewSnapshot(){let e=await this.fetchPreviewSnapshot();e&&(this.characters?.setInitial(e.characters,e.characterStates),this.player?.setInitial(e.player,e.playerState),this.inventory?.setInitial(e.inventory),this.relationships?.setInitial(e.relationships),this.world?.setInitial(e.world),this.custom?.setInitial(e.custom,e.custom_inject),this.save?.setInitial(e.save_data))}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e={game_id:this.gameId};this.conversationId&&(e.conversation_id=this.conversationId);let t=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify(e)});if(!t.ok)throw t.status===401?new u("UNAUTHORIZED","User not authenticated"):t.status===404?new u("GAME_NOT_FOUND","Game not found or not published"):new u("INTERNAL_ERROR",`Auth failed: HTTP ${t.status}`);let n=await t.json();return n.data??n}async initDev(e){if(this.initialized)return;this.baseUrl=`${xe}${Ce}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new B(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.models=t;let r=e.model?t.find(a=>a.name===e.model)?.id??"":"";this.modelId=r||t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000";let i=()=>this.gameId,s=()=>this.conversationId,c=()=>this.modelId,d=()=>this.models.find(a=>a.id===this.modelId)?.name;this.chat=new O(this.http,i,s,c,!0,void 0,d),this.characters=new A(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new M(this.http,s,!0,n?.relationships),this.inventory=new D(this.http,s,!0,n?.inventory),this.world=new N(this.http,s,!0,n?.world),this.player=new U(this.http,s,!0,n?.player,n?.playerState),this.custom=new L(this.http,s,i,!0,n?.custom),this.save=new F(this.http,s,i,!0,n?.save_data),this.memory=new G(this.http,s,!0),this.initialized=!0}async getAssets(e,t){let n={asset_type:e};return t&&(n.category=t),(await this.http.get("/assets",n)).map(i=>({id:i.id,name:i.name,url:i.url,assetType:i.asset_type,category:i.category}))}};async function Ae(o){let e=new ee;return o?.dev?await e.initDev(o.dev):await e.init(),e}function Re(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function Me(o){return Re(o)?o.value:o}export{j as PROTOCOL_VERSION,_ as StorviaBus,u as StorviaError,ee as StorviaSDK,Ae as createStorviaSDK,E as envelope,Me as extractFieldValue,Q as isProtocolEnvelope,Re as isRichFieldValue,be as setToastEnabled,ge as showToast};
|