aitu-app 0.6.13 → 0.6.14

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.
Files changed (154) hide show
  1. package/README.md +3 -3
  2. package/assets/{ChatMessagesArea-Btxhq7Z2.js → ChatMessagesArea-BQ33OSbv.js} +4 -4
  3. package/assets/DialogTaskList-D8vkITTk.js +1 -0
  4. package/assets/KnowledgeBaseContent-iIzzEUb9.js +143 -0
  5. package/assets/{ToolboxDrawer-CFAgOmIa.js → ToolboxDrawer-BUixzCAh.js} +14 -14
  6. package/assets/{ai-analyze-CXbDwr-F.js → ai-analyze-BSLl2uAK.js} +1 -1
  7. package/assets/ai-image-generation-DvTfL5Pf.js +1 -0
  8. package/assets/ai-video-generation-mgvQmDxU.js +5 -0
  9. package/assets/{arc-BVpYfX8u.js → arc-7VZa8sld.js} +1 -1
  10. package/assets/{arc-Vb6QIvRI.js → arc-CPYfXPW2.js} +1 -1
  11. package/assets/{batch-image-generation-rvn9zCP-.js → batch-image-generation-C7g9dTtb.js} +5 -5
  12. package/assets/{blockDiagram-38ab4fdb-CbbmIvT5.js → blockDiagram-38ab4fdb-9wKjan3w.js} +1 -1
  13. package/assets/{blockDiagram-38ab4fdb-CbUExfWH.js → blockDiagram-38ab4fdb-BfYiey8T.js} +1 -1
  14. package/assets/{c4Diagram-3d4e48cf-Db1GHdmL.js → c4Diagram-3d4e48cf-Cl1CeBZ9.js} +1 -1
  15. package/assets/{c4Diagram-3d4e48cf-Dw_8bcgE.js → c4Diagram-3d4e48cf-CvDzfWGg.js} +1 -1
  16. package/assets/channel-Dq0dBTpp.js +1 -0
  17. package/assets/channel-QRfYJ0c8.js +1 -0
  18. package/assets/{classDiagram-70f12bd4-CXXAHxeU.js → classDiagram-70f12bd4-7hx7i_r9.js} +1 -1
  19. package/assets/{classDiagram-70f12bd4-_p3Dnvx6.js → classDiagram-70f12bd4-C4dqbFYb.js} +1 -1
  20. package/assets/{classDiagram-v2-f2320105-B-9myg44.js → classDiagram-v2-f2320105-BE6EhyIR.js} +1 -1
  21. package/assets/{classDiagram-v2-f2320105-ChK1LfBX.js → classDiagram-v2-f2320105-BKvCao98.js} +1 -1
  22. package/assets/{clipper-CJLNPhZM.js → clipper-DMBYubGg.js} +1 -1
  23. package/assets/clone-8iorvsVH.js +1 -0
  24. package/assets/clone-CcaoZaCt.js +1 -0
  25. package/assets/{createText-2e5e7dd3-BCbwgqBS.js → createText-2e5e7dd3-B5bm44t-.js} +1 -1
  26. package/assets/{createText-2e5e7dd3-BGRSuPih.js → createText-2e5e7dd3-ClED10Yd.js} +1 -1
  27. package/assets/{edges-e0da2a9e-BoQQRKl3.js → edges-e0da2a9e-CxYbDWHf.js} +1 -1
  28. package/assets/{edges-e0da2a9e-1EAOsAGW.js → edges-e0da2a9e-D83AKoY_.js} +1 -1
  29. package/assets/{erDiagram-9861fffd-DrPXJadW.js → erDiagram-9861fffd-By6KGQIp.js} +1 -1
  30. package/assets/{erDiagram-9861fffd-DIqIVsjO.js → erDiagram-9861fffd-DklWxrea.js} +1 -1
  31. package/assets/{flowDb-956e92f1-DKdojl1Z.js → flowDb-956e92f1-B5waKznT.js} +1 -1
  32. package/assets/{flowDb-956e92f1-_yAXk9b2.js → flowDb-956e92f1-zlQFiVfE.js} +1 -1
  33. package/assets/{flowDiagram-66a62f08-Cn3BWcxJ.js → flowDiagram-66a62f08-Be1TW-l_.js} +1 -1
  34. package/assets/{flowDiagram-66a62f08-BSNSE1vH.js → flowDiagram-66a62f08-DN-7_2yD.js} +1 -1
  35. package/assets/flowDiagram-v2-96b9c2cf-Brfi4xIj.js +1 -0
  36. package/assets/flowDiagram-v2-96b9c2cf-CPIzTRuX.js +1 -0
  37. package/assets/{flowchart-elk-definition-4a651766-CkhkUOMa.js → flowchart-elk-definition-4a651766-N0AfQRnQ.js} +1 -1
  38. package/assets/{flowchart-elk-definition-4a651766-CtRYHypS.js → flowchart-elk-definition-4a651766-r-PtKbtF.js} +1 -1
  39. package/assets/{ganttDiagram-c361ad54-C-olbHti.js → ganttDiagram-c361ad54-Bht9glx_.js} +1 -1
  40. package/assets/{ganttDiagram-c361ad54-DWZxEumf.js → ganttDiagram-c361ad54-C2_MLBXD.js} +1 -1
  41. package/assets/{gitGraphDiagram-72cf32ee-DFI0WJ7k.js → gitGraphDiagram-72cf32ee-2be20W2P.js} +1 -1
  42. package/assets/{gitGraphDiagram-72cf32ee-Dz3X9B4S.js → gitGraphDiagram-72cf32ee-DbRkmH2_.js} +1 -1
  43. package/assets/{graph-BbAdRpyG.js → graph-B8wbK8JG.js} +1 -1
  44. package/assets/{graph-CG3zmXkL.js → graph-Cz6eZWdE.js} +1 -1
  45. package/assets/{grid-image-CahEQ7p7.js → grid-image-BjBUsyzw.js} +1 -1
  46. package/assets/{has-Cq7YuzG9.js → has-xmSj69Ai.js} +1 -1
  47. package/assets/{hasIn-4hPyOh4r.js → hasIn-BEuiXUL_.js} +1 -1
  48. package/assets/{index-3862675e-D_PJ0qZE.js → index-3862675e-B-TzDFUV.js} +1 -1
  49. package/assets/{index-3862675e-Cy2LJr-t.js → index-3862675e-DUv0NNEX.js} +1 -1
  50. package/assets/{index-pt9oZHeu.js → index-BFKE1SDS.js} +1 -1
  51. package/assets/{index-WyqXHNHN.js → index-BGhQ9HiC.js} +10 -10
  52. package/assets/{index-C1tgh8XV.js → index-BJPn-Z4H.js} +1 -1
  53. package/assets/{index-CqEazMaK.js → index-BJt4za3u.js} +1 -1
  54. package/assets/{index-D9rMZcAy.js → index-BYIrI0Fv.js} +52 -49
  55. package/assets/index-Bf4QGnyR.css +9 -0
  56. package/assets/{index-DHrV9sCt.js → index-Bi-3shgC.js} +1 -1
  57. package/assets/{index-BiCrE7Ci.js → index-Biha89Ph.js} +1 -1
  58. package/assets/{index-BDnSt0a8.js → index-C7Vp0sfc.js} +1 -1
  59. package/assets/{index-DtNyBFxZ.js → index-CM5A34wJ.js} +1 -1
  60. package/assets/{index-XoOCAjmC.js → index-CMqABmj9.js} +1 -1
  61. package/assets/{index-BOZ3fCzl.js → index-CURBM_KW.js} +1 -1
  62. package/assets/{index-B4IEsL3l.js → index-CZI4rQ66.js} +1 -1
  63. package/assets/{index-CYf1zrx4.js → index-Cg0P1L1n.js} +1 -1
  64. package/assets/{index-B9uNbnfa.js → index-Cg4DzaGJ.js} +1 -1
  65. package/assets/{index-BZIcMnMw.js → index-Cr7eFaRi.js} +1 -1
  66. package/assets/{index-7WzIC7_D.js → index-CvvgEQLL.js} +557 -519
  67. package/assets/index-Cz1tSwF3.css +1 -0
  68. package/assets/{index-Cx19IgV-.js → index-D35EPyAQ.js} +5 -5
  69. package/assets/{index-Dv8yvI8G.js → index-D55hpwi0.js} +1 -1
  70. package/assets/{index-CciPE8zM.js → index-D8hBvwzc.js} +1 -1
  71. package/assets/{index-BkRTZMZM.js → index-DCPnuU9X.js} +1 -1
  72. package/assets/{index-Bad6y32x.js → index-DFKy--AY.js} +1 -1
  73. package/assets/{index-Bco0OAak.js → index-DGrNJ_p2.js} +1 -1
  74. package/assets/{index-DUgUd4bR.js → index-DZUnWUAx.js} +1 -1
  75. package/assets/{index-BU3nDlFy.js → index-DergpCoU.js} +1 -1
  76. package/assets/{index-DBCwQvu4.js → index-Dgpls_LJ.js} +1 -1
  77. package/assets/{index-jHCkpoWQ.js → index-Dh9OAfqP.js} +1 -1
  78. package/assets/{index-Dqi7TZna.js → index-DoC8-4hw.js} +2 -2
  79. package/assets/{index-BQS_8NU3.js → index-DoNZZrMr.js} +1 -1
  80. package/assets/{index-Bfs6Q-lQ.js → index-Dwd3fQIs.js} +1 -1
  81. package/assets/{index-BE7n-LiY.js → index-H9okbyq7.js} +1 -1
  82. package/assets/{index-BOHFUhjZ.js → index-iNzLrLfW.js} +1 -1
  83. package/assets/index-pQpy2-r1.js +1 -0
  84. package/assets/{index-ICFaM7Tx.js → index-ukQeGfpm.js} +1 -1
  85. package/assets/{infoDiagram-f8f76790-D8T-erO4.js → infoDiagram-f8f76790-Ds4mXkkB.js} +1 -1
  86. package/assets/{infoDiagram-f8f76790-C0TYyx3w.js → infoDiagram-f8f76790-Xs3wpNj_.js} +1 -1
  87. package/assets/{inspiration-board-CiL8hKbX.js → inspiration-board-aPQmVaUX.js} +1 -1
  88. package/assets/{isEmpty-BoFRUVaJ.js → isEmpty-BQn8FtDD.js} +1 -1
  89. package/assets/{journeyDiagram-49397b02-CkmFUv6i.js → journeyDiagram-49397b02-CMj7sdKi.js} +1 -1
  90. package/assets/{journeyDiagram-49397b02-BHw2LUDu.js → journeyDiagram-49397b02-DAcDgbqb.js} +1 -1
  91. package/assets/{layers-CaY2-pH6.js → layers-D6Y5pCwe.js} +1 -1
  92. package/assets/{layout-CSua1dGC.js → layout-DFY48Wfc.js} +1 -1
  93. package/assets/{layout-D_agYVJ_.js → layout-xjQVmyNt.js} +1 -1
  94. package/assets/{line-CN9rNlXr.js → line-CS-j1kBY.js} +1 -1
  95. package/assets/{line-CxGDlzoc.js → line-CnJU8oQA.js} +1 -1
  96. package/assets/{linear-DKP7SWoM.js → linear-8yUIDV7f.js} +1 -1
  97. package/assets/{linear-CvStv2Ny.js → linear-BNtDceQW.js} +1 -1
  98. package/assets/{mermaid.core-DawxQi4y.js → mermaid.core-Bse-qmGl.js} +5 -5
  99. package/assets/{mindmap-definition-fc14e90a-BWrsnm3I.js → mindmap-definition-fc14e90a-B5pHBBH0.js} +1 -1
  100. package/assets/{mindmap-definition-fc14e90a-Dmo2lz3K.js → mindmap-definition-fc14e90a-BZEj0_V2.js} +1 -1
  101. package/assets/{photo-wall-splitter-B_WR4Rl2.js → photo-wall-splitter-DNhSfZ1J.js} +1 -1
  102. package/assets/pick-Bz9u-Vgl.js +1 -0
  103. package/assets/{pieDiagram-8a3498a8-DhrponMk.js → pieDiagram-8a3498a8-BX6EY38S.js} +1 -1
  104. package/assets/{pieDiagram-8a3498a8-CmbWJAb7.js → pieDiagram-8a3498a8-C2SKAWPu.js} +1 -1
  105. package/assets/{quadrantDiagram-120e2f19-CgIF-y-_.js → quadrantDiagram-120e2f19-C_pOTOg2.js} +1 -1
  106. package/assets/{quadrantDiagram-120e2f19-DOKwrvFF.js → quadrantDiagram-120e2f19-_4F-o39n.js} +1 -1
  107. package/assets/{requirementDiagram-deff3bca-BqbqHjdU.js → requirementDiagram-deff3bca-CZBh345Y.js} +1 -1
  108. package/assets/{requirementDiagram-deff3bca-CIXltTSE.js → requirementDiagram-deff3bca-DUvc5b49.js} +1 -1
  109. package/assets/{sankeyDiagram-04a897e0-DcPermhl.js → sankeyDiagram-04a897e0-DgwQWZaB.js} +1 -1
  110. package/assets/{sankeyDiagram-04a897e0-DGiABLdx.js → sankeyDiagram-04a897e0-HlGDp0fm.js} +1 -1
  111. package/assets/{sequenceDiagram-704730f1-piXYTUjh.js → sequenceDiagram-704730f1-CZleNxPQ.js} +1 -1
  112. package/assets/{sequenceDiagram-704730f1-BUXJ6XVH.js → sequenceDiagram-704730f1-HXnccUr4.js} +1 -1
  113. package/assets/{settings-dialog-A3AH7O45.css → settings-dialog-Bf8ExAlc.css} +1 -1
  114. package/assets/settings-dialog-FIIbAUlz.js +11 -0
  115. package/assets/{shard-sync-service-BCo2qKEA.js → shard-sync-service-BmLCs0-9.js} +1 -1
  116. package/assets/{stateDiagram-587899a1-Dnd2X4K4.js → stateDiagram-587899a1-BgbU_RYJ.js} +1 -1
  117. package/assets/{stateDiagram-587899a1-Cdfs3rRO.js → stateDiagram-587899a1-wcO67Z9P.js} +1 -1
  118. package/assets/{stateDiagram-v2-d93cdb3a-DtC5XSWV.js → stateDiagram-v2-d93cdb3a-CyibEwON.js} +1 -1
  119. package/assets/{stateDiagram-v2-d93cdb3a-lOfkWHnS.js → stateDiagram-v2-d93cdb3a-D6v0mGya.js} +1 -1
  120. package/assets/{styles-6aaf32cf-B_EWv7Bz.js → styles-6aaf32cf-CuwtY8aD.js} +1 -1
  121. package/assets/{styles-6aaf32cf-BTv8Dnxa.js → styles-6aaf32cf-DPVcUAPG.js} +1 -1
  122. package/assets/{styles-9a916d00-C4vTAlbK.js → styles-9a916d00-5sadXKIs.js} +1 -1
  123. package/assets/{styles-9a916d00-BNkP2BU4.js → styles-9a916d00-BlcdlroT.js} +1 -1
  124. package/assets/{styles-c10674c1-BcxLBYaC.js → styles-c10674c1-DMY3sr0M.js} +1 -1
  125. package/assets/{styles-c10674c1-Dp5J5JrP.js → styles-c10674c1-fyvfh0rz.js} +2 -2
  126. package/assets/{svgDrawCommon-08f97a94-CalbTy9V.js → svgDrawCommon-08f97a94-D99zFeK3.js} +1 -1
  127. package/assets/{svgDrawCommon-08f97a94-5_vuhhyn.js → svgDrawCommon-08f97a94-DCKNxHs0.js} +1 -1
  128. package/assets/{timeline-definition-85554ec2-DBiJ4h6g.js → timeline-definition-85554ec2-B-Hua8_V.js} +1 -1
  129. package/assets/{timeline-definition-85554ec2-ByBsrbAq.js → timeline-definition-85554ec2-BJFySUyi.js} +1 -1
  130. package/assets/{ttd-dialog-C9noZsTQ.js → ttd-dialog-D_LEovv1.js} +4 -4
  131. package/assets/{upload-DP5n1PVz.js → upload-DPuHWdr4.js} +1 -1
  132. package/assets/{video-recovery-service-DY01FcHI.js → video-recovery-service-BUo0pCsG.js} +1 -1
  133. package/assets/{xychartDiagram-e933f94c-CJ1NxG0K.js → xychartDiagram-e933f94c-Cf5Uc503.js} +1 -1
  134. package/assets/{xychartDiagram-e933f94c-CEXcS3Lw.js → xychartDiagram-e933f94c-Cu1l8Kcq.js} +1 -1
  135. package/changelog.json +42 -0
  136. package/package.json +1 -1
  137. package/precache-manifest.json +279 -279
  138. package/sw.js +4 -4
  139. package/version.json +29 -3
  140. package/assets/DialogTaskList-0I91BD1p.js +0 -1
  141. package/assets/KnowledgeBaseContent-CSEr1paK.js +0 -153
  142. package/assets/ai-image-generation-CvUX_vnh.js +0 -1
  143. package/assets/ai-video-generation-BgDcotXE.js +0 -5
  144. package/assets/channel-ChluHQU5.js +0 -1
  145. package/assets/channel-DQ0ggWsj.js +0 -1
  146. package/assets/clone-BscGHP5K.js +0 -1
  147. package/assets/clone-CTdvgy2F.js +0 -1
  148. package/assets/flowDiagram-v2-96b9c2cf-BmoA7Lrr.js +0 -1
  149. package/assets/flowDiagram-v2-96b9c2cf-Du5Aycbt.js +0 -1
  150. package/assets/index-C_Ed2LrM.js +0 -1
  151. package/assets/index-V8UiJyjb.css +0 -1
  152. package/assets/index-qP_w2VHW.css +0 -9
  153. package/assets/pick-C1hcXSqm.js +0 -1
  154. package/assets/settings-dialog-D1OnKj0y.js +0 -11
package/sw.js CHANGED
@@ -1,7 +1,7 @@
1
- var sw=(function(E){"use strict";var ue=(n=>(n.IMAGE="image",n.VIDEO="video",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(ue||{});ue.IMAGE+"",ue.VIDEO+"",ue.CHARACTER+"",ue.INSPIRATION_BOARD+"",ue.CHAT+"";function it(n){return n instanceof Error?n.name||"Error":"Unknown error"}const Ie="sw-task-queue",ct=3,L="tasks",H="config",R="workflows",k="chat-workflows",P="pending-tool-requests",_="pending-dom-operations",O="task-step-mappings",G="pending-canvas-operations",os=[L,H,R,k,P,_,O,G];function as(){return new Promise(n=>{const e=indexedDB.open(Ie);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,ct))},e.onerror=()=>{n(ct)}})}function is(n){const e=[];for(const t of os)n.objectStoreNames.contains(t)||e.push(t);return e}function cs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(Ie,s);r.onerror=()=>{console.error("[SWStorage] Failed to repair DB:",r.error),t(r.error)},r.onsuccess=()=>{e(r.result)},r.onupgradeneeded=o=>{const i=o.target.result;lt(i)}})}function lt(n){if(!n.objectStoreNames.contains(L)){const e=n.createObjectStore(L,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("type","type",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(H)||n.createObjectStore(H,{keyPath:"key"}),!n.objectStoreNames.contains(R)){const e=n.createObjectStore(R,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(k)){const e=n.createObjectStore(k,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(P)||n.createObjectStore(P,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(_)){const e=n.createObjectStore(_,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(O)||n.createObjectStore(O,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains(G)||n.createObjectStore(G,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function ls(){const n=await as();return new Promise((e,t)=>{const s=indexedDB.open(Ie,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=is(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),cs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;lt(o)}})}class us{constructor(){this.dbPromise=null,this.pendingTaskSaves=new Map,this.batchSaveTimer=null,this.batchSavePromises=new Map,this.BATCH_SAVE_DELAY=50}async getDB(){return this.dbPromise||(this.dbPromise=ls()),this.dbPromise}async flushPendingTaskSaves(){this.batchSaveTimer&&(clearTimeout(this.batchSaveTimer),this.batchSaveTimer=null);const e=Array.from(this.pendingTaskSaves.values()),t=new Map(this.batchSavePromises);if(this.pendingTaskSaves.clear(),this.batchSavePromises.clear(),e.length!==0)try{const s=await this.getDB();await new Promise((r,o)=>{const i=s.transaction(L,"readwrite"),a=i.objectStore(L);for(const c of e)a.put(c);i.oncomplete=()=>{t.forEach(({resolve:c})=>c()),r()},i.onerror=()=>{const c=i.error;t.forEach(({reject:l})=>l(c)),o(c)}})}catch(s){console.error("[SWStorage] Failed to batch save tasks:",s),t.forEach(({reject:r})=>r(s))}}async saveTask(e){return new Promise((t,s)=>{this.pendingTaskSaves.set(e.id,e),this.batchSavePromises.set(e.id,{resolve:t,reject:s}),this.batchSaveTimer||(this.batchSaveTimer=setTimeout(()=>{this.flushPendingTaskSaves()},this.BATCH_SAVE_DELAY))})}async saveTaskImmediate(e){this.pendingTaskSaves.delete(e.id);const t=this.batchSavePromises.get(e.id);t&&this.batchSavePromises.delete(e.id);try{const s=await this.getDB();await new Promise((r,o)=>{const c=s.transaction(L,"readwrite").objectStore(L).put(e);c.onerror=()=>o(c.error),c.onsuccess=()=>r()}),t&&t.resolve()}catch(s){throw console.error("[SWStorage] Failed to save task:",s),t&&t.reject(s),s}}async getTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(L,"readonly").objectStore(L).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task:",t),null}}async getAllTasks(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(L,"readonly").objectStore(L).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all tasks:",e),[]}}async getTasksByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(L,"readonly").objectStore(L).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get tasks by status:",t),[]}}async getTasksPaginated(e){const{offset:t,limit:s,status:r,type:o,sortOrder:i="desc"}=e;try{const a=await this.getDB();return new Promise((c,l)=>{const f=a.transaction(L,"readonly").objectStore(L).index("createdAt"),m=i==="desc"?"prev":"next",w=f.openCursor(null,m),p=[];let d=0,b=0;w.onerror=()=>l(w.error),w.onsuccess=S=>{const C=S.target.result;if(!C){c({tasks:p,total:b,hasMore:b>t+p.length});return}const T=C.value,K=!r||T.status===r,ee=!o||T.type===o;K&&ee&&(b++,d<t?d++:p.length<s&&p.push(T)),C.continue()}})}catch(a){return console.error("[SWStorage] Failed to get paginated tasks:",a),{tasks:[],total:0,hasMore:!1}}}async deleteTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(L,"readwrite").objectStore(L).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task:",t)}}async getConfig(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(H,"readonly").objectStore(H).get(e);a.onsuccess=()=>{const c=a.result;if(!c){s(null);return}const{key:l,...u}=c;s(u)},a.onerror=()=>r(a.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",it(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const i=s.transaction(H,"readwrite");i.objectStore(H).put({key:e,...t,updatedAt:Date.now()}),i.oncomplete=()=>r(),i.onerror=()=>o(i.error)})}catch(s){throw console.error("[SWStorage] Failed to save config:",it(s)),s}}async loadConfig(){const e=await this.getConfig("gemini"),t=await this.getConfig("video");return{geminiConfig:e,videoConfig:t}}async saveAllConfig(e,t){await this.saveConfig("gemini",e),await this.saveConfig("video",t)}async saveSystemPrompt(e){try{const t=await this.getDB();return new Promise((s,r)=>{const o=t.transaction(H,"readwrite");o.objectStore(H).put({key:"systemPrompt",value:e,updatedAt:Date.now()}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.error("[SWStorage] Failed to save system prompt:",t)}}async getSystemPrompt(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(H,"readonly").objectStore(H).get("systemPrompt");i.onsuccess=()=>{const a=i.result;t((a==null?void 0:a.value)||null)},i.onerror=()=>s(i.error)})}catch(e){return console.error("[SWStorage] Failed to get system prompt:",e),null}}async saveWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(R,"readwrite").objectStore(R).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save workflow:",t)}}async getWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(R,"readonly").objectStore(R).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get workflow:",t),null}}async getAllWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(R,"readonly").objectStore(R).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all workflows:",e),[]}}async getWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(R,"readonly").objectStore(R).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get workflows by status:",t),[]}}async deleteWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(R,"readwrite").objectStore(R).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete workflow:",t)}}async saveChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(k,"readwrite").objectStore(k).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save chat workflow:",t)}}async getChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(k,"readonly").objectStore(k).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get chat workflow:",t),null}}async getAllChatWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(k,"readonly").objectStore(k).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all chat workflows:",e),[]}}async getChatWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(k,"readonly").objectStore(k).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get chat workflows by status:",t),[]}}async deleteChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(k,"readwrite").objectStore(k).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete chat workflow:",t)}}async savePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(P,"readwrite").objectStore(P).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending tool request:",t)}}async getAllPendingToolRequests(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(P,"readonly").objectStore(P).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending tool requests:",e),[]}}async getPendingToolRequestsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(P,"readonly").objectStore(P).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending tool requests by workflow:",t),[]}}async getPendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(P,"readonly").objectStore(P).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending tool request:",t),null}}async deletePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(P,"readwrite").objectStore(P).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending tool request:",t)}}async deletePendingToolRequestsByWorkflow(e){try{const t=await this.getPendingToolRequestsByWorkflow(e);for(const s of t)await this.deletePendingToolRequest(s.requestId)}catch(t){console.error("[SWStorage] Failed to delete pending tool requests by workflow:",t)}}async cleanupStalePendingToolRequests(e=36e5){try{const t=await this.getAllPendingToolRequests(),s=Date.now(),r=t.filter(o=>s-o.createdAt>e);if(r.length===0)return 0;console.log(`[SWStorage] Cleaning up ${r.length} stale pending tool requests`);for(const o of r)await this.deletePendingToolRequest(o.requestId);return r.length}catch(t){return console.error("[SWStorage] Failed to cleanup stale pending tool requests:",t),0}}async savePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(_,"readwrite").objectStore(_).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending DOM operation:",t)}}async getAllPendingDomOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(_,"readonly").objectStore(_).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending DOM operations:",e),[]}}async getPendingDomOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(_,"readonly").objectStore(_).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by workflow:",t),[]}}async getPendingDomOperationsByChatId(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(_,"readonly").objectStore(_).index("chatId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by chat ID:",t),[]}}async getPendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(_,"readonly").objectStore(_).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operation:",t),null}}async deletePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(_,"readwrite").objectStore(_).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending DOM operation:",t)}}async deletePendingDomOperationsByWorkflow(e){try{const t=await this.getPendingDomOperationsByWorkflow(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by workflow:",t)}}async deletePendingDomOperationsByChatId(e){try{const t=await this.getPendingDomOperationsByChatId(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by chat ID:",t)}}async saveTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(O,"readwrite").objectStore(O).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save task-step mapping:",t)}}async getAllTaskStepMappings(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(O,"readonly").objectStore(O).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all task-step mappings:",e),[]}}async getTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(O,"readonly").objectStore(O).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task-step mapping:",t),null}}async getTaskStepMappingsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(O,"readonly").objectStore(O).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get task-step mappings by workflow:",t),[]}}async deleteTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(O,"readwrite").objectStore(O).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task-step mapping:",t)}}async deleteTaskStepMappingsByWorkflow(e){try{const t=await this.getTaskStepMappingsByWorkflow(e);for(const s of t)await this.deleteTaskStepMapping(s.taskId)}catch(t){console.error("[SWStorage] Failed to delete task-step mappings by workflow:",t)}}async savePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(G,"readwrite").objectStore(G).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending canvas operation:",t)}}async getAllPendingCanvasOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(G,"readonly").objectStore(G).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending canvas operations:",e),[]}}async getPendingCanvasOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(G,"readonly").objectStore(G).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending canvas operations by workflow:",t),[]}}async deletePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(G,"readwrite").objectStore(G).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending canvas operation:",t)}}async deletePendingCanvasOperationsByWorkflow(e){try{const t=await this.getPendingCanvasOperationsByWorkflow(e);for(const s of t)await this.deletePendingCanvasOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending canvas operations by workflow:",t)}}}const hs=new us,ds=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function We(n){if(!n)return n;if(typeof n=="string")return n.toLowerCase().startsWith("bearer ")||n.length>30&&/^[a-zA-Z0-9-_]+$/.test(n)&&!n.includes("-")?"[REDACTED]":n;if(Array.isArray(n))return n.map(e=>We(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();ds.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=We(s)}return e}return n}let Se=!1;const gs=500,te=[];let Be=0;function ut(){return Se}const ht=["SW_DEBUG_ENABLE","SW_DEBUG_DISABLE","SW_DEBUG_GET_STATUS","SW_DEBUG_CLEAR_LOGS","SW_DEBUG_CLEAR_CONSOLE_LOGS","SW_DEBUG_GET_CONSOLE_LOGS","SW_DEBUG_EXPORT_LOGS","SW_DEBUG_HEARTBEAT","SW_DEBUG_STATUS","SW_DEBUG_ENABLED","SW_DEBUG_DISABLED","SW_DEBUG_LOG","SW_DEBUG_LOGS","SW_DEBUG_LOGS_CLEARED","SW_CONSOLE_LOG","SW_DEBUG_CONSOLE_LOGS","SW_DEBUG_CONSOLE_LOGS_CLEARED","SW_POSTMESSAGE_LOG","SW_DEBUG_POSTMESSAGE_LOGS","SW_DEBUG_POSTMESSAGE_LOGS_CLEARED","SW_DEBUG_NEW_CRASH_SNAPSHOT","SW_DEBUG_CRASH_SNAPSHOTS","SW_DEBUG_CRASH_SNAPSHOTS_CLEARED","SW_DEBUG_GET_CRASH_SNAPSHOTS","SW_DEBUG_CLEAR_CRASH_SNAPSHOTS","CRASH_SNAPSHOT","debug:log","debug:llmLog","debug:statusChanged","debug:enable","debug:disable","debug:getStatus","debug:getLogs","debug:clearLogs","debug:getConsoleLogs","debug:clearConsoleLogs","debug:getPostMessageLogs","debug:clearPostMessageLogs","debug:getCrashSnapshots","debug:clearCrashSnapshots","debug:getLLMApiLogs","debug:clearLLMApiLogs","debug:getCacheStats","debug:exportLogs","debug:newCrashSnapshot","console:log","console:report","postmessage:log","postmessage:logBatch","crash:snapshot","crash:heartbeat"],me=new Map;function dt(n){const e=Se;Se=n,!n&&e&&(te.length=0,me.clear(),Be=0)}function Ne(){return Se}function fs(n){if(!ut()||n==="unknown"||ht.includes(n))return!1;if(n.startsWith("RPC:")){let e=n.slice(4);if(e.endsWith(":response")?e=e.slice(0,-9):e.endsWith(":error")&&(e=e.slice(0,-6)),ht.includes(e))return!1}return!0}function ps(n){if(!n)return{};let e="other";return n.includes("sw-debug")?e="debug":(n.includes("localhost")||n.includes("127.0.0.1")||!n.includes("chrome-extension")&&!n.includes("moz-extension"))&&(e="main"),{clientType:e,clientUrl:new URL(n).pathname+new URL(n).search}}function qe(n,e,t,s,r){if(r||!fs(n))return"";const o=ps(s);if(o.clientType==="debug")return"";const i=`pm-recv-${Date.now()}-${++Be}`,a={id:i,timestamp:Date.now(),direction:"receive",messageType:n,data:gt(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(ms(a),ws(n)){const c=ys(e);c&&me.set(c,{entry:a,startTime:Date.now()})}return i}function ms(n){te.unshift(n),te.length>gs&&te.pop()}function xe(n,e,t,s){if(!ut())return"";const r=me.get(n);if(r){r.entry.response=gt(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return me.delete(n),o}return""}function Ce(){return[...te]}function bs(){te.length=0,me.clear(),Be=0}function ws(n){return n.startsWith("RPC:")&&!n.endsWith(":response")&&!n.endsWith(":error")?!0:["TASK_SUBMIT","TASK_CANCEL","TASK_RETRY","TASK_DELETE","TASK_GET_","WORKFLOW_SUBMIT","WORKFLOW_CANCEL","WORKFLOW_GET_","CHAT_START","MCP_TOOL_EXECUTE","MAIN_THREAD_TOOL_REQUEST"].some(t=>n.includes(t))}function ys(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function gt(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return We(e)}catch{return"[Non-serializable data]"}}function Ss(){const n={total:te.length,sent:0,received:0,byType:{}};for(const e of te)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const He=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:bs,getAllLogs:Ce,getLogStats:Ss,isPostMessageLoggerDebugMode:Ne,logReceivedMessage:qe,setPostMessageLoggerDebugMode:dt,updateRequestWithResponse:xe},Symbol.toStringTag,{value:"Module"}));function Cs(){return typeof window<"u"?window:typeof self<"u"?self:{}}function Es(n){return JSON.parse(JSON.stringify(n))}function ft(n){const e=Date.now().toString(36);let t;if(typeof crypto<"u"&&crypto.getRandomValues){const s=new Uint32Array(2);crypto.getRandomValues(s),t=s[0].toString(36)+s[1].toString(36)}else t=Math.floor(1e10*Math.random()).toString(36);return`${n}${e}${t}_`}const Ts="postmessage-duplex",Ds="1.2.0",Ee=Cs();var z,se;Ee.__POSTMESSAGE_DUPLEX__||(Ee.__POSTMESSAGE_DUPLEX__={}),Ee.__POSTMESSAGE_DUPLEX__.version=Ds,Ee.__POSTMESSAGE_DUPLEX__.name=Ts,(function(n){n[n.Success=0]="Success",n[n.ReceiverCallbackError=-1]="ReceiverCallbackError",n[n.SendCallbackError=-2]="SendCallbackError",n[n.NoSubscribe=-3]="NoSubscribe",n[n.TimeOut=-99]="TimeOut"})(z||(z={})),(function(n){n.ConnectionDestroyed="CONNECTION_DESTROYED",n.ConnectionTimeout="CONNECTION_TIMEOUT",n.MethodCallTimeout="METHOD_CALL_TIMEOUT",n.MethodNotFound="METHOD_NOT_FOUND",n.TransmissionFailed="TRANSMISSION_FAILED",n.MessageSizeExceeded="MESSAGE_SIZE_EXCEEDED",n.RateLimitExceeded="RATE_LIMIT_EXCEEDED",n.HandlerError="HANDLER_ERROR",n.InvalidMessage="INVALID_MESSAGE",n.OriginMismatch="ORIGIN_MISMATCH",n.HeartbeatFailed="HEARTBEAT_FAILED",n.ReconnectFailed="RECONNECT_FAILED",n.HandshakeFailed="HANDSHAKE_FAILED",n.ServiceWorkerUnavailable="SERVICE_WORKER_UNAVAILABLE"})(se||(se={}));class ne extends Error{constructor(e,t,s){super(e),Object.defineProperty(this,"code",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"details",{enumerable:1,configurable:1,writable:1,value:void 0}),this.name="ChannelError",this.code=t,this.details=s,Error.captureStackTrace&&Error.captureStackTrace(this,ne)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class Ls{constructor(){Object.defineProperty(this,"timeouts",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timer",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"nextDeadline",{enumerable:1,configurable:1,writable:1,value:1/0}),Object.defineProperty(this,"destroyed",{enumerable:1,configurable:1,writable:1,value:0})}add(e,t,s){if(this.destroyed)return;const r=Date.now()+t;this.timeouts.set(e,{deadline:r,callback:s}),r<this.nextDeadline&&this.reschedule(r)}remove(e){return this.timeouts.delete(e)}has(e){return this.timeouts.has(e)}get size(){return this.timeouts.size}reschedule(e){this.timer!==null&&clearTimeout(this.timer),this.nextDeadline=e;const t=Math.max(0,e-Date.now());this.timer=setTimeout(()=>this.processTimeouts(),t)}processTimeouts(){if(this.destroyed)return;const e=Date.now(),t=[];for(const[s,{deadline:r,callback:o}]of this.timeouts)r<=e&&(t.push(o),this.timeouts.delete(s));for(const s of t)try{s()}catch(r){console.error("[TimeoutManager] Callback error:",r)}this.scheduleNext()}scheduleNext(){if(this.timeouts.size===0)return this.nextDeadline=1/0,void(this.timer=null);let e=1/0;for(const{deadline:t}of this.timeouts.values())t<e&&(e=t);e<1/0&&this.reschedule(e)}destroy(){this.destroyed=1,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}}class _s{constructor(e,t=1e3){Object.defineProperty(this,"limit",{enumerable:1,configurable:1,writable:1,value:e}),Object.defineProperty(this,"windowMs",{enumerable:1,configurable:1,writable:1,value:t}),Object.defineProperty(this,"timestamps",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"head",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"tail",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"count",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"enabled",{enumerable:1,configurable:1,writable:1,value:void 0}),this.enabled=e>0,this.timestamps=this.enabled?new Array(e).fill(0):[]}tryAcquire(){if(!this.enabled)return 1;const e=Date.now(),t=e-this.windowMs;for(;this.count>0&&this.timestamps[this.head]<=t;)this.head=(this.head+1)%this.limit,this.count--;return this.count>=this.limit?0:(this.timestamps[this.tail]=e,this.tail=(this.tail+1)%this.limit,this.count++,1)}getCurrentCount(){if(!this.enabled)return 0;const e=Date.now()-this.windowMs;let t=0,s=this.head;for(let r=0;r<this.count;r++)this.timestamps[s]>e&&t++,s=(s+1)%this.limit;return t}getRemainingCapacity(){return this.enabled?Math.max(0,this.limit-this.getCurrentCount()):1/0}getTimeUntilAvailable(){if(!this.enabled||this.count<this.limit)return 0;const e=Date.now()-this.windowMs;let t=this.head;for(;t!==this.tail;){if(this.timestamps[t]>e)return this.timestamps[t]-e;t=(t+1)%this.limit}return 0}isLimited(){return this.enabled?this.getCurrentCount()>=this.limit:0}reset(){this.head=0,this.tail=0,this.count=0,this.enabled&&this.timestamps.fill(0)}getLimit(){return this.limit}getWindowMs(){return this.windowMs}isEnabled(){return this.enabled}}class As{constructor(){Object.defineProperty(this,"eventHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"eventsEnabled",{enumerable:1,configurable:1,writable:1,value:1})}on(e,t){let s=this.eventHandlers.get(e);return s||(s=new Set,this.eventHandlers.set(e,s)),s.add(t),()=>{s==null||s.delete(t),(s==null?void 0:s.size)===0&&this.eventHandlers.delete(e)}}once(e,t){const s=r=>{this.off(e,s),t(r)};return this.on(e,s)}off(e,t){const s=this.eventHandlers.get(e);if(!s)return 0;const r=s.delete(t);return s.size===0&&this.eventHandlers.delete(e),r}offAll(e){e?this.eventHandlers.delete(e):this.eventHandlers.clear()}emit(e,t){if(!this.eventsEnabled)return;const s=this.eventHandlers.get(e);if(s)for(const r of[...s])try{r(t)}catch(o){console.error(`[ChannelEventEmitter] Error in ${e} handler:`,o)}}hasListeners(e){const t=this.eventHandlers.get(e);return t!==void 0&&t.size>0}listenerCount(e){var t;return((t=this.eventHandlers.get(e))==null?void 0:t.size)??0}setEventsEnabled(e){this.eventsEnabled=e}destroyEventEmitter(){this.eventHandlers.clear(),this.eventsEnabled=0}}function pt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const X=n=>({valid:0,error:n});function vs(n){if(!pt(n))return X("Message must be an object");const e=n,t="requestId"in e,s="cmdname"in e,r="msg"in e,o="ret"in e;return t||s||r?t&&typeof e.requestId!="string"?X("requestId must be a string"):s&&typeof e.cmdname!="string"?X("cmdname must be a string"):r&&typeof e.msg!="string"?X("msg must be a string"):!o||typeof(i=e.ret)=="number"&&Object.values(z).includes(i)?"data"in e&&e.data!==void 0&&!pt(e.data)?X("data must be an object"):"_senderKey"in e&&e._senderKey!==void 0&&typeof e._senderKey!="string"?X("_senderKey must be a string"):!("time"in e)||e.time===void 0||typeof e.time=="number"&&Number.isFinite(e.time)?{valid:1,message:e}:X("time must be a finite number"):X("ret must be a valid ReturnCode"):X("Message must have requestId, cmdname, or msg field");var i}function Te(n){return"ret"in n&&typeof n.ret=="number"}function Ms(n){return n.msg==="ready"}function Rs(n){return n._broadcast==1&&typeof n.cmdname=="string"}function ks(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const Ge=[],Y=[];function mt(n){Y.length>=200&&Y.shift(),Y.push(n)}function bt(n,e){for(let t=Y.length-1;t>=0;t--)if(Y[t].requestId===n&&Y[t].status==="pending"){Y[t].status=e,Y[t].duration=Date.now()-Y[t].timestamp;break}}class Ps extends As{constructor(e){if(super(),Object.defineProperty(this,"baseKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"peerKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"reqTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"callbackMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"subscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"broadcastHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timeout",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"isReady",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isDestroyed",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"postTasks",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"bindOnMessage",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"console",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"maxMessageSize",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"timeoutManager",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"rateLimiter",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"strictValidation",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"requestCmdMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"isProcessingBatch",{enumerable:1,configurable:1,writable:1,value:0}),this.timeout=(e==null?void 0:e.timeout)??5e3,this.console=(e==null?void 0:e.log)??(typeof window<"u"?window.console:console),this.maxMessageSize=(e==null?void 0:e.maxMessageSize)??1048576,this.strictValidation=(e==null?void 0:e.strictValidation)??1,this.timeoutManager=new Ls,this.rateLimiter=new _s((e==null?void 0:e.rateLimit)??100,1e3),e==null?void 0:e.subscribeMap)for(const s in e.subscribeMap)this.subscribeMap.set(s,e.subscribeMap[s]);var t;this.bindOnMessage=this.onMessage.bind(this),t=this,Ge.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{mt({direction:"send",cmdname:s,requestId:r,status:"pending",timestamp:Date.now(),dataSummary:""})}),t.on("message:received",({cmdname:s,requestId:r,isResponse:o})=>{const i=s||"",a=r||"";o?bt(a,"ok"):mt({direction:"receive",cmdname:i,requestId:a,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{bt(r,"timeout")}),t.on("error",({context:s})=>{}),t.on("destroy",()=>{})}checkRateLimit(){if(!this.rateLimiter.isEnabled())return 1;if(!this.rateLimiter.tryAcquire()){const e=this.rateLimiter.getCurrentCount(),t=this.rateLimiter.getLimit();return this.log("warn","Rate limit exceeded:",e,"/",t,"messages per second"),this.emit("rate:limited",{currentCount:e,limit:t}),0}return 1}validateMessageSize(e){if(this.maxMessageSize<=0)return;const t=ks(e);if(t>this.maxMessageSize){const s=new ne(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,se.MessageSizeExceeded,{size:t,limit:this.maxMessageSize});throw this.emit("error",{error:s,context:"validateMessageSize"}),s}}init(){this.setupMessageListener(),this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})}log(e,...t){var s,r;(r=(s=this.console)==null?void 0:s[e])==null||r.call(s,`[${this.channelType}]: `,...t)}isFromPeer(e){return this.peerKey?e._senderKey&&e._senderKey!==this.peerKey?(this.log("log","Message from non-paired channel, ignored",e._senderKey,"expected:",this.peerKey),0):Te(e)&&e.requestId&&!e.requestId.startsWith(this.baseKey)?0:1:1}sendMessage(e,t){this.validateMessageSize(e),this.checkRateLimit()?(e.time=Date.now(),e._senderKey=this.baseKey,this.sendRawMessage(e,t)):this.log("warn","Message dropped due to rate limiting")}async onMessage(e){if(this.log("log","onMessage",e.data),!this.isValidSource(e))return;if(this.strictValidation){const o=vs(e.data);if(!o.valid)return this.log("warn","Invalid message structure:",o.error),void this.emit("validation:failed",{reason:o.error,data:e.data})}const t=e.data;if(!t||!this.isFromPeer(t))return;this.emit("message:received",{cmdname:t.cmdname||"",requestId:t.requestId||"",isResponse:Te(t)});const{requestId:s,cmdname:r}=t;this.handleResponseMessage(t,s)||this.handleBroadcastMessage(t,r)||await this.handleSubscriptionMessage(t,s,r)||this.handleReadyMessage(t,s)||this.handleUnhandledMessage(t,s,r)}handleResponseMessage(e,t){const s=t?this.callbackMap.get(t):void 0;return s&&t?(this.timeoutManager.remove(t),this.requestCmdMap.delete(t),s.resolve(e),this.deleteCallback(t),1):0}handleBroadcastMessage(e,t){if(!Rs(e))return 0;const s=t?this.broadcastHandlers.get(t):void 0;if(s)try{s({cmdname:t,data:e.data})}catch(r){const o=r instanceof Error?r.message:String(r);this.emit("error",{error:r instanceof Error?r:new Error(o),context:`broadcast:${t}`})}return 1}async handleSubscriptionMessage(e,t,s){if(!s)return 0;const r=this.subscribeMap.get(s);if(!r)return 0;try{const o=await r(e);this.sendMessage({requestId:t,ret:z.Success,data:o})}catch(o){const i=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:z.ReceiverCallbackError,msg:i||"unknown error"}),this.emit("error",{error:o instanceof Error?o:new Error(i),context:`handler:${s}`})}return 1}handleReadyMessage(e,t){if(!Ms(e))return 0;const{_senderKey:s}=e;return s&&!this.peerKey&&(this.peerKey=s,this.log("log","Point-to-point pairing established","self:",this.baseKey,"peer:",this.peerKey)),this.isReady=1,this.executePosts(),this.emit("ready",{peerKey:this.peerKey}),Te(e)||this.sendMessage({requestId:t,ret:z.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Te(e)&&(this.log("warn","No registered handler for:",s||t),this.sendMessage({requestId:t,ret:z.NoSubscribe}))}postMessage(e,t){try{this.sendMessage(e,t),this.emit("message:sent",{cmdname:e.cmdname||"",requestId:e.requestId||""})}catch(s){this.log("error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"postMessage"})}}publish(e,t,s){if(this.isDestroyed)return Promise.reject(new ne("Cannot publish: channel has been destroyed",se.ConnectionDestroyed,{cmdname:e}));const r=this.baseKey+ ++this.reqTime,o={requestId:r,cmdname:e,data:t};this.requestCmdMap.set(r,e);const i=new Promise((a,c)=>{this.callbackMap.set(r,{resolve:a,reject:c})});return this.log("log","publish",this.isReady,this.postTasks.size),this.isReady?this.doPublish(o,s):this.postTasks.set(r,{data:o,prm:i,options:s}),i}doPublish(e,t){const{requestId:s,cmdname:r}=e,o=(t==null?void 0:t.timeout)??this.timeout;this.timeoutManager.add(s,o,()=>{const i=this.callbackMap.get(s);if(i){const a={req:e,requestId:s,ret:z.TimeOut,time:Date.now(),msg:"timeout"};this.log("error","postmessage timeout",a),this.emit("timeout",{requestId:s,cmdname:r,timeoutMs:o}),i.resolve(a),this.deleteCallback(s),this.requestCmdMap.delete(s)}}),this.postMessage(e,t==null?void 0:t.transferables)}deleteCallback(e){this.callbackMap.delete(e),this.postTasks.delete(e),this.timeoutManager.remove(e)}executePosts(){this.postTasks.size===0||this.isProcessingBatch||(this.isProcessingBatch=1,queueMicrotask(()=>{this.processBatch(),this.isProcessingBatch=0}))}processBatch(){const e=Array.from(this.postTasks.entries());for(const[t,s]of e)this.postTasks.has(t)&&(t.startsWith("_broadcast_")?(this.doBroadcast(s.data,s.options),this.postTasks.delete(t)):this.doPublish(s.data,s.options))}call(e,t,s){return this.publish(e,t,s)}subscribe(e,t){return this.subscribeMap.has(e)&&this.log("warn",`${e} has been subscribed`),this.subscribeMap.set(e,t),this}unSubscribe(e){return this.subscribeMap.delete(e),this}subscribeOnce(e,t){return this.subscribe(e,async s=>(this.unSubscribe(e),t(s)))}broadcast(e,t,s){if(this.isDestroyed)return void this.log("warn","Cannot broadcast: channel has been destroyed");const r={cmdname:e,data:t,time:Date.now(),_broadcast:1};if(this.log("log","broadcast",e,this.isReady),this.isReady)this.doBroadcast(r,s);else{const o=`_broadcast_${Date.now()}_${Math.random()}`;this.postTasks.set(o,{data:r,prm:Promise.resolve({}),options:s})}}doBroadcast(e,t){try{this.sendMessage(e,t==null?void 0:t.transferables),this.emit("broadcast:sent",{cmdname:e.cmdname})}catch(s){this.log("error","broadcast error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"broadcast"})}}onBroadcast(e,t){return this.broadcastHandlers.has(e)&&this.log("warn",`Broadcast handler for ${e} already registered, replacing`),this.broadcastHandlers.set(e,t),this}offBroadcast(e){return this.broadcastHandlers.delete(e),this}getPeerKey(){return this.peerKey}getRateLimitStats(){return{current:this.rateLimiter.getCurrentCount(),limit:this.rateLimiter.getLimit(),remaining:this.rateLimiter.getRemainingCapacity()}}getPendingCount(){return this.callbackMap.size}destroy(){if(this.isDestroyed)return;this.isDestroyed=1,this.emit("destroy",{reason:"explicit"}),(function(t){const s=Ge.findIndex(r=>r.deref()===t);s!==-1&&Ge.splice(s,1)})(this);const e=new ne("Channel has been destroyed",se.ConnectionDestroyed);for(const[t,s]of this.callbackMap)try{s.reject({ret:z.SendCallbackError,msg:e.message})}catch(r){this.log("warn","Error rejecting pending request:",t,r)}this.removeMessageListener(),this.subscribeMap.clear(),this.broadcastHandlers.clear(),this.postTasks.clear(),this.callbackMap.clear(),this.requestCmdMap.clear(),this.timeoutManager.destroy(),this.rateLimiter.reset(),this.destroyEventEmitter(),this.isReady=0,this.peerKey=""}}class ${constructor(){Object.defineProperty(this,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"initialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"options",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"channelFactory",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:e=>{const t=e.source,s=t==null?void 0:t.id;if(!s)return;const r=this.channelsByClientId.get(s);r?r.handleMessage(e):this.unknownClientCallback&&this.unknownClientCallback(s,e)}})}static getInstance(){return $.instance||($.instance=new $),$.instance}static resetInstance(){$.instance&&($.instance.shutdown(),$.instance=null)}setup(e,t){if(this.initialized)return void console.warn("[ServiceWorkerHub] Already initialized");this.options=e,this.channelFactory=t,this.initialized=1,this.registerBuiltInHandlers(),this.setupLifecycleEvents();const s=e.cleanupInterval??3e4;s>0&&(this.cleanupIntervalId=setInterval(()=>this.cleanupInactiveClients(),s))}shutdown(){this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0);for(const e of this.channelsByClientId.values())try{e.destroy()}catch{}this.channelsByClientId.clear(),this.clientMeta.clear(),this.globalSubscribeMap.clear(),this.initialized=0}isInitialized(){return this.initialized}getOptions(){return this.options}enableGlobalRouting(e){this.unknownClientCallback=e??null,this.globalListenerSetup||(self.addEventListener("message",this.globalMessageHandler),this.globalListenerSetup=1)}disableGlobalRouting(){this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0)}isGlobalRoutingEnabled(){return this.globalListenerSetup}registerChannel(e,t){this.channelsByClientId.set(e,t),this.applyGlobalHandlersToChannel(t,e)}unregisterChannel(e){var t,s;this.channelsByClientId.delete(e),this.clientMeta.delete(e),(s=(t=this.options).onClientDisconnect)==null||s.call(t,e)}getChannel(e){return this.channelsByClientId.get(e)}hasChannel(e){return this.channelsByClientId.has(e)}getChannelCount(){return this.channelsByClientId.size}createChannelForClient(e){if(!this.channelFactory)return console.warn("[ServiceWorkerHub] No channel factory configured"),null;const t=this.channelFactory(e);return this.registerChannel(e,t),t}registerClientMeta(e,t){var r,o;const s={clientId:e,appType:t.appType,appName:t.appName,connectedAt:new Date().toISOString()};return this.clientMeta.set(e,s),(o=(r=this.options).onClientConnect)==null||o.call(r,e,s),s}getClientMeta(e){return this.clientMeta.get(e)}getAllClientMeta(){return new Map(this.clientMeta)}getClientsByType(e){const t=[];for(const s of this.clientMeta.values())s.appType===e&&t.push(s);return t}subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerHub] Handler name '${e}' uses reserved prefix '__'.`),this.globalSubscribeMap.set(e,t);for(const[s,r]of this.channelsByClientId)this.applyHandlerToChannel(r,s,e,t)}unsubscribeGlobal(e){this.globalSubscribeMap.delete(e);for(const t of this.channelsByClientId.values())t.unSubscribe(e)}applyGlobalHandlersToChannel(e,t){for(const[s,r]of this.globalSubscribeMap)this.applyHandlerToChannel(e,t,s,r)}applyHandlerToChannel(e,t,s,r){e.subscribe(s,async o=>{const i=this.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:i})})}registerBuiltInHandlers(){this.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>(this.registerClientMeta(t,{appType:e.appType,appName:e.appName}),{success:1,clientId:t,totalClients:this.clientMeta.size})),this.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:this.channelsByClientId.size}))}setupLifecycleEvents(){self.addEventListener("install",e=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await this.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:this.options.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerHub] Error notifying clients:",e)}}async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o,i]of this.channelsByClientId)r.has(o)||(i.destroy(),this.channelsByClientId.delete(o),this.clientMeta.delete(o),(t=(e=this.options).onClientDisconnect)==null||t.call(e,o))}catch(s){console.error("[ServiceWorkerHub] Cleanup error:",s)}}async broadcastToAll(e,t,s){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const r=await self.clients.matchAll();let o=0;for(const i of r){if(s&&i.id===s)continue;const a=this.channelsByClientId.get(i.id);if(a)try{a.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,c)}}return o}catch(r){return console.error("[ServiceWorkerHub] broadcastToAll error:",r),0}}async broadcastToType(e,t,s,r){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const o=await self.clients.matchAll();let i=0;for(const a of o){if(r&&a.id===r)continue;const c=this.clientMeta.get(a.id);if(!c||c.appType!==e)continue;const l=this.channelsByClientId.get(a.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),i++}catch(u){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",a.id,u)}}return i}catch(o){return console.error("[ServiceWorkerHub] broadcastToType error:",o),0}}}Object.defineProperty($,"instance",{enumerable:1,configurable:1,writable:1,value:null});class g extends Ps{static enableGlobalRouting(e){g.useGlobalRouting=1,g.unknownClientCallback=e??null,g.globalListenerSetup||(self.addEventListener("message",g.globalMessageHandler),g.globalListenerSetup=1)}static disableGlobalRouting(){g.useGlobalRouting=0,g.globalListenerSetup&&(self.removeEventListener("message",g.globalMessageHandler),g.globalListenerSetup=0)}static setupHub(e={}){if(g.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");g.hubOptions=e,g.hubInitialized=1,$.getInstance().setup(e,s=>g.createFromWorker(s)),g.enableGlobalRouting((s,r)=>{const o=g.createFromWorker(s);g.setupChannelHandlers(o,s),o.handleMessage(r)}),g.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(g.cleanupIntervalId=setInterval(()=>g.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){g.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>{var r,o;const s={clientId:t,appType:e.appType,appName:e.appName,connectedAt:new Date().toISOString()};return g.clientMeta.set(t,s),(o=(r=g.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:g.clientMeta.size}}),g.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:g.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of g.globalSubscribeMap)e.subscribe(s,async o=>{const i=g.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:i})})}static setupLifecycleEvents(){self.addEventListener("install",()=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await g.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}static async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:g.hubOptions.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerChannel] Error notifying clients:",e)}}static async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o]of g.channelsByClientId)if(!r.has(o)){const i=g.channelsByClientId.get(o);i&&i.destroy(),g.clientMeta.delete(o),(t=(e=g.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!g.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const r=await self.clients.matchAll();let o=0;for(const i of r){if(s&&i.id===s)continue;const a=g.channelsByClientId.get(i.id);if(a)try{a.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,c)}}return o}catch(r){return console.error("[ServiceWorkerChannel] broadcastToAll error:",r),0}}static async broadcastToType(e,t,s,r){if(!g.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const o=await self.clients.matchAll();let i=0;for(const a of o){if(r&&a.id===r)continue;const c=g.clientMeta.get(a.id);if(!c||c.appType!==e)continue;const l=g.channelsByClientId.get(a.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),i++}catch(u){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",a.id,u)}}return i}catch(o){return console.error("[ServiceWorkerChannel] broadcastToType error:",o),0}}static getClientInfo(e){return g.clientMeta.get(e)}static getAllClients(){return new Map(g.clientMeta)}static getClientsByType(e){const t=[];for(const s of g.clientMeta.values())s.appType===e&&t.push(s);return t}static subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerChannel] Handler name '${e}' uses reserved prefix '__'. This may conflict with internal handlers.`),g.globalSubscribeMap.set(e,t);for(const[s,r]of g.channelsByClientId)r.subscribe(e,async o=>{const i=g.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:i})})}static unsubscribeGlobal(e){g.globalSubscribeMap.delete(e);for(const t of g.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&g.useGlobalRouting&&g.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&g.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return g.channelsByClientId.get(e)}static hasChannel(e){return g.channelsByClientId.has(e)}static getChannelCount(){return g.channelsByClientId.size}handleMessage(e){return this.onMessage(e)}constructor(e,t){if(super(t),Object.defineProperty(this,"channelType",{enumerable:1,configurable:1,writable:1,value:"ServiceWorkerChannel"}),Object.defineProperty(this,"isWorkerSide",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"worker",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"clientId",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"swContainer",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"l",{enumerable:1,configurable:1,writable:1,value:"connecting"}),Object.defineProperty(this,"lastSuccessfulMessageTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"heartbeatIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"missedHeartbeatCount",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isReconnecting",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"reconnectAttempt",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"connectionOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"boundControllerChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"boundStateChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),this.isWorkerSide=(t==null?void 0:t.isWorkerSide)??0,this.isWorkerSide){if(typeof e!="string")throw new Error("Service Worker 端必须传入 clientId 字符串");this.clientId=e,this.baseKey=ft("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=ft("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(g.useGlobalRouting)return void(g.globalListenerSetup||(self.addEventListener("message",g.globalMessageHandler),g.globalListenerSetup=1));self.addEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.addEventListener("message",this.bindOnMessage)}removeMessageListener(){var e;if(this.unregisterFromGlobalRouter(),this.isWorkerSide){if(g.useGlobalRouting)return;self.removeEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.removeEventListener("message",this.bindOnMessage)}sendRawMessage(e,t){var s,r;try{const o=Es(e);this.isWorkerSide?this.sendToClient(o,t):t&&t.length>0?(s=this.worker)==null||s.postMessage(o,t):(r=this.worker)==null||r.postMessage(o)}catch(o){this.log("error","sendMessage error",o,e)}}async sendToClient(e,t){const s=this.clientId;if(s)try{const r=await self.clients.get(s);r?t&&t.length>0?r.postMessage(e,t):r.postMessage(e):this.log("warn","Client not found:",s)}catch(r){this.log("error","sendToClient error",r)}else this.log("error","No clientId available")}isValidSource(e){if(this.isWorkerSide){const t=e.source;return(t==null?void 0:t.id)===this.clientId}return 1}log(e,...t){var r,o;const s=this.isWorkerSide?"worker":"page";(o=(r=this.console)==null?void 0:r[e])==null||o.call(r,`[ServiceWorkerChannel](${s}): `,...t)}getClientId(){return this.clientId}isWorkerAvailable(){var e;return this.isWorkerSide||((e=this.worker)==null?void 0:e.state)==="activated"}async refreshWorker(){if(this.isWorkerSide)throw new Error("refreshWorker() can only be called on page side");const e=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;e?(this.worker=e,this.peerKey="",this.isReady=0,this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})):console.warn("[ServiceWorkerChannel] No active Service Worker found during refresh")}get connectionState(){return this.l}get isConnected(){return this.l==="connected"}updateLastMessageTime(){this.lastSuccessfulMessageTime=Date.now()}setConnectionState(e,t){if(this.l===e)return;const s=this.l;switch(this.l=e,this.log("log",`Connection state: ${s} -> ${e}`),e){case"connected":this.missedHeartbeatCount=0,this.reconnectAttempt=0,this.emit("connected",{isReconnect:s==="reconnecting"});break;case"disconnected":this.emit("disconnected",{reason:(t==null?void 0:t.reason)||"error",error:t==null?void 0:t.error});break;case"reconnecting":this.emit("reconnecting",{attempt:(t==null?void 0:t.attempt)||this.reconnectAttempt,maxAttempts:this.connectionOptions.maxReconnectAttempts||5,nextRetryIn:(t==null?void 0:t.nextRetryIn)||0})}}startHeartbeat(){if(this.isWorkerSide)return;const e=this.connectionOptions.heartbeatInterval??3e4;e<=0||(this.stopHeartbeat(),this.heartbeatIntervalId=setInterval(()=>{this.performHeartbeat()},e),this.log("log",`Heartbeat started with interval ${e}ms`))}stopHeartbeat(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)}async performHeartbeat(){const e=this.connectionOptions.heartbeatInterval??3e4;if(this.connectionOptions.smartHeartbeat!=0&&this.lastSuccessfulMessageTime>0&&Date.now()-this.lastSuccessfulMessageTime<e)return this.missedHeartbeatCount=0,void this.emit("heartbeat",{success:1,missedCount:0});const t=this.connectionOptions.heartbeatTimeout??5e3,s=Date.now();try{if((await this.publish("__ping__",{},{timeout:t})).ret===z.Success){const r=Date.now()-s;this.missedHeartbeatCount=0,this.updateLastMessageTime(),this.emit("heartbeat",{success:1,latencyMs:r,missedCount:0}),this.l==="reconnecting"&&this.setConnectionState("connected")}else this.handleHeartbeatFailure()}catch(r){this.handleHeartbeatFailure(r instanceof Error?r:void 0)}}handleHeartbeatFailure(e){this.missedHeartbeatCount++;const t=this.connectionOptions.maxMissedHeartbeats??3;this.emit("heartbeat",{success:0,missedCount:this.missedHeartbeatCount}),this.log("warn",`Heartbeat failed (${this.missedHeartbeatCount}/${t})`),this.missedHeartbeatCount>=t&&(this.log("error","Connection lost: heartbeat threshold exceeded"),this.setConnectionState("disconnected",{reason:"heartbeat_failed",error:e||new ne("Heartbeat detection failed",se.HeartbeatFailed,{missedCount:this.missedHeartbeatCount})}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}async attemptReconnect(){if(this.isReconnecting||this.isDestroyed)return;const e=this.connectionOptions.maxReconnectAttempts??5;if(e<=0)return;this.isReconnecting=1,this.reconnectAttempt=0;const t=this.connectionOptions.reconnectBaseDelay??1e3,s=this.connectionOptions.maxReconnectDelay??3e4;for(;this.reconnectAttempt<e&&!this.isDestroyed;){this.reconnectAttempt++;const r=Math.min(t*Math.pow(2,this.reconnectAttempt-1),s);if(this.setConnectionState("reconnecting",{attempt:this.reconnectAttempt,nextRetryIn:r}),await this.delay(r),this.isDestroyed)break;try{return await this.refreshWorker(),this.isReady||await this.waitForReady(this.connectionOptions.handshakeTimeout??1e4),(this.connectionOptions.appType||this.connectionOptions.appName)&&await this.publish("__register__",{appType:this.connectionOptions.appType,appName:this.connectionOptions.appName}),this.missedHeartbeatCount=0,this.setConnectionState("connected"),this.updateLastMessageTime(),this.isReconnecting=0,void this.log("log","Reconnection successful")}catch(o){this.log("warn",`Reconnection attempt ${this.reconnectAttempt} failed:`,o)}}this.isReconnecting=0,this.emit("reconnect:failed",{attempts:this.reconnectAttempt,lastError:new ne("All reconnection attempts failed",se.ReconnectFailed,{attempts:this.reconnectAttempt})})}waitForReady(e){return new Promise((t,s)=>{if(this.isReady)return void t();const r=setTimeout(()=>{this.off("ready",o),s(new ne("Handshake timeout",se.HandshakeFailed))},e),o=()=>{clearTimeout(r),t()};this.once("ready",o)})}delay(e){return new Promise(t=>setTimeout(t,e))}setupSwLifecycleListeners(){this.isWorkerSide||typeof navigator>"u"||(this.boundControllerChangeHandler=()=>{this.log("log","Service Worker controller changed"),this.handleControllerChange()},navigator.serviceWorker.addEventListener("controllerchange",this.boundControllerChangeHandler),this.worker&&(this.boundStateChangeHandler=()=>{var e;this.handleStateChange((e=this.worker)==null?void 0:e.state)},this.worker.addEventListener("statechange",this.boundStateChangeHandler)))}removeSwLifecycleListeners(){var e;this.boundControllerChangeHandler&&((e=navigator.serviceWorker)==null||e.removeEventListener("controllerchange",this.boundControllerChangeHandler),this.boundControllerChangeHandler=null),this.boundStateChangeHandler&&this.worker&&(this.worker.removeEventListener("statechange",this.boundStateChangeHandler),this.boundStateChangeHandler=null)}handleControllerChange(){this.l==="connected"&&this.setConnectionState("disconnected",{reason:"controller_changed"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect()}handleStateChange(e){this.log("log","Service Worker state changed:",e),e==="redundant"&&(this.l==="connected"&&this.setConnectionState("disconnected",{reason:"sw_terminated"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}static async createFromPage(e){if(!("serviceWorker"in navigator))throw new Error("Service Worker is not supported in this browser");if(e!=null&&e.swUrl)try{const l={};e.swScope&&(l.scope=e.swScope),await navigator.serviceWorker.register(e.swUrl,l)}catch(l){throw console.error("[ServiceWorkerChannel] Failed to register Service Worker:",l),l}const t=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;if(!t)throw new Error("No active Service Worker found");const s=new g(t,e);s.connectionOptions=e||{};const r=(e==null?void 0:e.appType)||(e==null?void 0:e.appName);let o=0,i=0;const a=async()=>{if(!i){i=1;try{await s.publish("__register__",{appType:e==null?void 0:e.appType,appName:e==null?void 0:e.appName}),o=1,s.updateLastMessageTime()}catch(l){console.warn("[ServiceWorkerChannel] Auto-registration failed:",l)}finally{i=0}}},c=()=>{s.setConnectionState("connected"),s.updateLastMessageTime(),s.startHeartbeat(),s.setupSwLifecycleListeners()};return r?s.isReady?(a(),c()):s.once("ready",()=>{a(),c()}):s.isReady?c():s.once("ready",c),(e==null?void 0:e.autoReconnect)!=0&&s.onBroadcast("__sw-activated__",async({data:l})=>{s.emit("sw-activated",{version:l==null?void 0:l.version}),s.setConnectionState("disconnected",{reason:"controller_changed"}),r&&(await s.refreshWorker(),o=0,await a()),s.setConnectionState("connected"),s.updateLastMessageTime()}),s.on("message:received",({isResponse:l})=>{l&&s.updateLastMessageTime()}),s}static createFromWorker(e,t){return new g(e,{...t,isWorkerSide:1})}static createFromEvent(e,t){const s=e.source;if(!(s!=null&&s.id))throw new Error("Invalid message event: no client source");return g.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(g,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(g,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(g,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(g,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(g,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(g,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(g,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(g,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(g,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(g,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:n=>{const e=n.source,t=e==null?void 0:e.id;if(!t)return;const s=g.channelsByClientId.get(t);s?s.handleMessage(n):g.unknownClientCallback&&g.unknownClientCallback(t,n)}});function Os(n,e,t){return Promise.race([n,new Promise(s=>setTimeout(()=>s(t),e))])}const y={THUMBNAIL_GENERATE:"thumbnail:generate",CRASH_SNAPSHOT:"crash:snapshot",CRASH_HEARTBEAT:"crash:heartbeat",CONSOLE_REPORT:"console:report",DEBUG_GET_STATUS:"debug:getStatus",DEBUG_ENABLE:"debug:enable",DEBUG_DISABLE:"debug:disable",DEBUG_GET_LOGS:"debug:getLogs",DEBUG_CLEAR_LOGS:"debug:clearLogs",DEBUG_GET_CONSOLE_LOGS:"debug:getConsoleLogs",DEBUG_CLEAR_CONSOLE_LOGS:"debug:clearConsoleLogs",DEBUG_GET_POSTMESSAGE_LOGS:"debug:getPostMessageLogs",DEBUG_CLEAR_POSTMESSAGE_LOGS:"debug:clearPostMessageLogs",DEBUG_GET_CRASH_SNAPSHOTS:"debug:getCrashSnapshots",DEBUG_CLEAR_CRASH_SNAPSHOTS:"debug:clearCrashSnapshots",DEBUG_GET_LLM_API_LOGS:"debug:getLLMApiLogs",DEBUG_GET_LLM_API_LOG_BY_ID:"debug:getLLMApiLogById",DEBUG_CLEAR_LLM_API_LOGS:"debug:clearLLMApiLogs",DEBUG_DELETE_LLM_API_LOGS:"debug:deleteLLMApiLogs",DEBUG_GET_CACHE_ENTRIES:"debug:getCacheEntries",DEBUG_GET_CACHE_STATS:"debug:getCacheStats",DEBUG_EXPORT_LOGS:"debug:exportLogs",CDN_GET_STATUS:"cdn:getStatus",CDN_RESET_STATUS:"cdn:resetStatus",CDN_HEALTH_CHECK:"cdn:healthCheck",UPGRADE_GET_STATUS:"upgrade:getStatus",UPGRADE_FORCE:"upgrade:force",CACHE_DELETE:"cache:delete",PING:"ping"},I={CACHE_IMAGE_CACHED:"cache:imageCached",CACHE_DELETED:"cache:deleted",CACHE_QUOTA_WARNING:"cache:quotaWarning",SW_NEW_VERSION_READY:"sw:newVersionReady",SW_ACTIVATED:"sw:activated",SW_UPDATED:"sw:updated",CONSOLE_LOG:"console:log",DEBUG_LOG:"debug:log",DEBUG_LLM_LOG:"debug:llmLog",DEBUG_STATUS_CHANGED:"debug:statusChanged",DEBUG_NEW_CRASH_SNAPSHOT:"debug:newCrashSnapshot",POSTMESSAGE_LOG_BATCH:"postmessage:logBatch"},le=class le{constructor(e){this.channels=new Map,this.onDebugClientCountChanged=null,this.postMessageLogBuffer=[],this.postMessageLogTimer=null,this.POSTMESSAGE_LOG_BATCH_INTERVAL=500,this.sw=e,this.channels.clear(),g.enableGlobalRouting((t,s)=>{var o;this.ensureChannel(t);const r=(o=this.channels.get(t))==null?void 0:o.channel;r&&r.handleMessage(s)}),setInterval(()=>{this.cleanupDisconnectedClients().catch(()=>{}),this.cleanupStalePendingRequests().catch(()=>{})},6e4)}async cleanupStalePendingRequests(){try{const e=await hs.cleanupStalePendingToolRequests();e>0&&console.log(`[ChannelManager] Cleaned up ${e} stale pending tool requests`)}catch(e){console.warn("[ChannelManager] Failed to cleanup stale pending requests:",e)}}setDebugClientCountChangedCallback(e){this.onDebugClientCountChanged=e}getDebugClientCount(){let e=0;for(const t of this.channels.values())t.isDebugClient&&e++;return e}async isDebugClient(e){try{const t=await this.sw.clients.get(e);if(t&&t.url)return t.url.includes("sw-debug")}catch{}return!1}static getInstance(e){return le.instance||(le.instance=new le(e)),le.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:g.createFromWorker(e,{timeout:12e4,subscribeMap:this.createSubscribeMap(e),log:{log:()=>{},warn:()=>{},error:()=>{}}}),clientId:e,createdAt:Date.now(),isDebugClient:!1},this.channels.set(e,t),this.checkAndUpdateDebugClient(e)),t.channel}async checkAndUpdateDebugClient(e){var r;const t=await this.isDebugClient(e),s=this.channels.get(e);s&&t&&(s.isDebugClient=!0,(r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}hasAnyClientChannel(){return this.channels.size>0}unwrapRpcData(e){return e&&typeof e=="object"&&"cmdname"in e?e.data:e}broadcastPostMessageLog(e){if(!e)return;const s=Ce().find(r=>r.id===e);s&&this.sendPostMessageLog(s)}wrapRpcHandler(e,t,s){return async r=>{var l;const o=this.unwrapRpcData(r),i=Date.now(),a=r==null?void 0:r.requestId,c=Ne()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=qe(`RPC:${e}`,{params:o,requestId:a},t);this.broadcastPostMessageLog(u)}try{const u=await s(o);try{JSON.stringify(u)}catch(h){throw console.error(`[SW wrapRpcHandler] ${e} result serialization failed:`,h),new Error(`Result serialization failed: ${h}`)}if(c&&a){const h=xe(a,{result:u},Date.now()-i);h&&this.broadcastPostMessageLog(h)}return u}catch(u){if(console.error(`[SW wrapRpcHandler] ${e} error:`,u),c&&a){const h=xe(a,null,Date.now()-i,String(u));h&&this.broadcastPostMessageLog(h)}throw u}}}createSubscribeMap(e){return{[y.THUMBNAIL_GENERATE]:this.wrapRpcHandler(y.THUMBNAIL_GENERATE,e,t=>this.handleThumbnailGenerate(t)),[y.CRASH_SNAPSHOT]:async t=>{const s=this.unwrapRpcData(t);return this.handleCrashSnapshot(s)},[y.CRASH_HEARTBEAT]:async t=>{const s=this.unwrapRpcData(t);return this.handleHeartbeat(s)},[y.CONSOLE_REPORT]:async t=>{const s=this.unwrapRpcData(t);return this.handleConsoleReport(s)},[y.DEBUG_GET_STATUS]:async()=>this.handleDebugGetStatus(),[y.DEBUG_ENABLE]:async()=>this.handleDebugEnable(),[y.DEBUG_DISABLE]:async()=>this.handleDebugDisable(),[y.DEBUG_GET_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLogs(s)},[y.DEBUG_CLEAR_LOGS]:async()=>this.handleDebugClearLogs(),[y.DEBUG_GET_CONSOLE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetConsoleLogs(s)},[y.DEBUG_CLEAR_CONSOLE_LOGS]:async()=>this.handleDebugClearConsoleLogs(),[y.DEBUG_GET_POSTMESSAGE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetPostMessageLogs(s)},[y.DEBUG_CLEAR_POSTMESSAGE_LOGS]:async()=>this.handleDebugClearPostMessageLogs(),[y.DEBUG_GET_CRASH_SNAPSHOTS]:async()=>this.handleDebugGetCrashSnapshots(),[y.DEBUG_CLEAR_CRASH_SNAPSHOTS]:async()=>this.handleDebugClearCrashSnapshots(),[y.DEBUG_GET_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogs(s)},[y.DEBUG_GET_LLM_API_LOG_BY_ID]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogById(s==null?void 0:s.logId)},[y.DEBUG_CLEAR_LLM_API_LOGS]:async()=>this.handleDebugClearLLMApiLogs(),[y.DEBUG_DELETE_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugDeleteLLMApiLogs(s)},[y.DEBUG_GET_CACHE_ENTRIES]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetCacheEntries(s)},[y.DEBUG_GET_CACHE_STATS]:async()=>this.handleDebugGetCacheStats(),[y.DEBUG_EXPORT_LOGS]:async()=>this.handleDebugExportLogs(),[y.CDN_GET_STATUS]:async()=>this.handleCDNGetStatus(),[y.CDN_RESET_STATUS]:async()=>this.handleCDNResetStatus(),[y.CDN_HEALTH_CHECK]:async()=>this.handleCDNHealthCheck(),[y.UPGRADE_GET_STATUS]:async()=>this.handleUpgradeGetStatus(),[y.UPGRADE_FORCE]:async()=>this.handleUpgradeForce(),[y.CACHE_DELETE]:async t=>{const s=this.unwrapRpcData(t);return this.handleCacheDelete(s)},[y.PING]:async()=>this.handlePing()}}async handleThumbnailGenerate(e){try{const{url:t,mediaType:s,blob:r,mimeType:o}=e,{generateThumbnailAsync:i}=await Promise.resolve().then(()=>x),a=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return i(a,t,s),{success:!0}}catch(t){return console.error("[SWChannelManager] Thumbnail generation failed:",t),{success:!1,error:t.message}}}async handleCrashSnapshot(e){try{const{saveCrashSnapshot:t}=await Promise.resolve().then(()=>D);return await t(e.snapshot),{success:!0}}catch(t){return console.error("[SWChannelManager] Crash snapshot save failed:",t),{success:!1,error:t.message}}}async handleHeartbeat(e){return{success:!0}}serializeLogArg(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)}async handleConsoleReport(e){try{const{addConsoleLog:t}=await Promise.resolve().then(()=>D),s=e.logArgs??[],o=(Array.isArray(s)?s.map(i=>this.serializeLogArg(i)):[this.serializeLogArg(s)]).join(" ");return t({logLevel:e.logLevel,logMessage:o||"-"}),{success:!0}}catch(t){return{success:!1,error:t.message}}}async handleDebugGetStatus(){try{const{getDebugStatus:e,getCacheStats:t}=await Promise.resolve().then(()=>D),s=e(),r=await t();return{...s,enabled:s.debugModeEnabled,cacheStats:r}}catch{return{debugModeEnabled:!1}}}async handleDebugEnable(){try{const{enableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>D);await e();const s=t();return this.sendDebugStatusChanged(!0),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugDisable(){try{const{disableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>D);await e();const s=t();return this.sendDebugStatusChanged(!1),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugGetLogs(e){try{const{getDebugLogs:t,getInternalFetchLogs:s}=await Promise.resolve().then(()=>D),{limit:r=100,offset:o=0,filter:i}=e||{},a=s().map(f=>({...f,type:"fetch"})),c=t(),l=new Map;for(const f of c)l.set(f.id,f);for(const f of a)l.set(f.id,f);let u=Array.from(l.values()).sort((f,m)=>m.timestamp-f.timestamp);return i&&(i.type&&(u=u.filter(f=>f.type===i.type)),i.status&&(u=u.filter(f=>f.status===i.status))),{logs:u.slice(o,o+r),total:u.length,offset:o,limit:r}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||100}}}async handleDebugClearLogs(){try{const{clearDebugLogs:e}=await Promise.resolve().then(()=>D);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>D),{limit:s=500,offset:r=0,filter:o}=e||{};let i=await t();if(o&&(o.logLevel&&(i=i.filter(c=>c.logLevel===o.logLevel)),o.search)){const c=o.search.toLowerCase();i=i.filter(l=>{var u,h;return((u=l.logMessage)==null?void 0:u.toLowerCase().includes(c))||((h=l.logStack)==null?void 0:h.toLowerCase().includes(c))})}return{logs:i.slice(r,r+s),total:i.length,offset:r,limit:s}}catch(t){return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||500,error:String(t)}}}async handleDebugClearConsoleLogs(){try{const{clearConsoleLogs:e,clearAllConsoleLogs:t}=await Promise.resolve().then(()=>D);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>He),{limit:r=200,offset:o=0,filter:i}=e||{};let a=t();if(i&&(i.direction&&(a=a.filter(l=>l.direction===i.direction)),i.messageType)){const l=i.messageType.toLowerCase();a=a.filter(u=>{var h;return(h=u.messageType)==null?void 0:h.toLowerCase().includes(l)})}return{logs:a.slice(o,o+r),total:a.length,offset:o,limit:r,stats:s()}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||200}}}async handleDebugClearPostMessageLogs(){try{const{clearLogs:e}=await Promise.resolve().then(()=>He);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>D),t=await e();return{snapshots:t,total:t.length}}catch(e){return{snapshots:[],total:0,error:String(e)}}}async handleDebugClearCrashSnapshots(){try{const{clearCrashSnapshots:e}=await Promise.resolve().then(()=>D);return await e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetLLMApiLogs(e){try{const t=typeof(e==null?void 0:e.page)=="number"?e.page:Number(e==null?void 0:e.page)||1,s=typeof(e==null?void 0:e.pageSize)=="number"?e.pageSize:Number(e==null?void 0:e.pageSize)||20,r={taskType:typeof(e==null?void 0:e.taskType)=="string"?e.taskType:void 0,status:typeof(e==null?void 0:e.status)=="string"?e.status:void 0},{getLLMApiLogsPaginated:o}=await Promise.resolve().then(()=>ce);return await o(t,s,r)}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogs error:",t),{logs:[],total:0,page:1,pageSize:20,totalPages:0,error:String(t)}}}async handleDebugGetLLMApiLogById(e){try{if(!e)return{log:null,error:"Missing logId"};const{getLLMApiLogById:t}=await Promise.resolve().then(()=>ce);return{log:await t(e)}}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogById error:",t),{log:null,error:String(t)}}}async handleDebugClearLLMApiLogs(){try{const{clearAllLLMApiLogs:e}=await Promise.resolve().then(()=>ce);return await e(),{success:!0}}catch{return{success:!1}}}async handleDebugDeleteLLMApiLogs(e){try{if(!(e!=null&&e.logIds)||e.logIds.length===0)return{success:!1,deletedCount:0};const{deleteLLMApiLogs:t}=await Promise.resolve().then(()=>ce);return{success:!0,deletedCount:await t(e.logIds)}}catch{return{success:!1,deletedCount:0}}}async handleDebugGetCacheEntries(e){try{const{IMAGE_CACHE_NAME:t}=await Promise.resolve().then(()=>D),{cacheName:s=t,limit:r=50,offset:o=0}=e||{},i=await caches.open(s),a=await i.keys(),c=[];for(let l=o;l<Math.min(o+r,a.length);l++){const u=a[l],h=await i.match(u);if(h){const f=h.headers.get("sw-cache-date"),m=h.headers.get("sw-image-size")||h.headers.get("content-length");c.push({url:u.url,cacheDate:f?parseInt(f):void 0,size:m?parseInt(m):void 0})}}return{cacheName:s,entries:c,total:a.length,offset:o,limit:r}}catch(t){return{cacheName:(e==null?void 0:e.cacheName)||"",entries:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||50,error:String(t)}}}async handleDebugGetCacheStats(){try{const e=await caches.keys(),t=[];let s=0,r=0;for(const o of e){const i=await caches.open(o),a=await i.keys();let c=0;for(const l of a){const u=await i.match(l);if(u){const h=u.headers.get("content-length");h&&(c+=parseInt(h))}}t.push({name:o,count:a.length,size:c}),s+=a.length,r+=c}return{stats:{caches:t,totalCount:s,totalSize:r}}}catch(e){return{stats:{caches:[],totalCount:0,totalSize:0},error:String(e)}}}async handleDebugExportLogs(){try{const{getDebugStatus:e,getDebugLogs:t,loadConsoleLogsFromDB:s,APP_VERSION:r}=await Promise.resolve().then(()=>D),{getAllLogs:o}=await Promise.resolve().then(()=>He),i=await s(),a=o(),c=t();return{exportTime:new Date().toISOString(),swVersion:r,status:e(),fetchLogs:c,consoleLogs:i,postmessageLogs:a}}catch{return{exportTime:new Date().toISOString(),swVersion:"unknown",status:{},fetchLogs:[],consoleLogs:[],postmessageLogs:[]}}}async handleCDNGetStatus(){try{const{getCDNStatusReport:e}=await Promise.resolve().then(()=>D);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>D);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>D),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>D);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>D);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>D);return await t(e.url),this.sendCacheDeleted(e.url),{success:!0}}catch(t){return{success:!1,error:String(t)}}}async handlePing(){return{success:!0}}broadcastToAll(e,t){this.channels.forEach(s=>{s.channel.broadcast(e,t)})}broadcastToOthers(e,t,s){this.channels.forEach(r=>{r.clientId!==s&&r.channel.broadcast(e,t)})}publishToClient(e,t,s){const r=this.channels.get(e);r&&r.channel.broadcast(t,s)}sendCacheImageCached(e,t,s){this.broadcastToAll(I.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheDeleted(e){this.broadcastToAll(I.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(I.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(I.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(I.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(I.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(I.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(I.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(I.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(I.DEBUG_LLM_LOG,{log:e})}sendPostMessageLog(e){this.postMessageLogBuffer.push(e),this.postMessageLogTimer||(this.postMessageLogTimer=setTimeout(()=>{this.flushPostMessageLogs()},this.POSTMESSAGE_LOG_BATCH_INTERVAL))}flushPostMessageLogs(){if(this.postMessageLogTimer=null,this.postMessageLogBuffer.length===0)return;const e=this.postMessageLogBuffer;this.postMessageLogBuffer=[],this.broadcastToAll(I.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(I.DEBUG_NEW_CRASH_SNAPSHOT,{snapshot:e})}async requestVideoThumbnail(e,t=3e4){const s=Array.from(this.channels.values())[0];if(!s)return console.warn("[ChannelManager] No client channel available for video thumbnail request"),null;try{const r=await Os(s.channel.call("thumbnail:generate",{url:e}),t,"Video thumbnail generation timeout");if(!r||r.ret!==0)return console.warn("[ChannelManager] Video thumbnail generation failed:",r==null?void 0:r.msg),null;const o=r.data;return o!=null&&o.error?(console.warn("[ChannelManager] Video thumbnail generation error:",o.error),null):(o==null?void 0:o.thumbnailUrl)||null}catch(r){return console.warn("[ChannelManager] Video thumbnail request failed:",r),null}}getConnectedClients(){return Array.from(this.channels.keys())}getConnectedClientCount(){return this.channels.size}async cleanupDisconnectedClients(){var r;const e=await this.sw.clients.matchAll({type:"window"}),t=new Set(e.map(o=>o.id));let s=!1;for(const[o,i]of this.channels)t.has(o)||(i.isDebugClient&&(s=!0),this.channels.delete(o));s&&((r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}};le.instance=null;let De=le,Le=null;function wt(n){return Le||(Le=De.getInstance(n)),Le}function W(){return Le}const Is=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:y,SWChannelManager:De,SW_EVENTS:I,getChannelManager:W,initChannelManager:wt},Symbol.toStringTag,{value:"Module"}));function _e(n){dt(n)}const Ws=[];let yt=!1;function be(n){yt=n}function Ue(){return yt}function je(){return[...Ws]}const Bs=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:je,isDebugFetchEnabled:Ue,setDebugFetchEnabled:be},Symbol.toStringTag,{value:"Module"})),Ns=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),Fe={degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500},ze=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1},{name:"unpkg",urlTemplate:"https://unpkg.com/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:2}],he=new Map;function St(){ze.forEach(n=>{he.has(n.name)||he.set(n.name,{name:n.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}St();function Ct(n){const e=he.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now())}function ae(n){const e=he.get(n);e&&(e.failCount++,e.lastCheckTime=Date.now(),e.failCount>=Fe.failThreshold&&(e.isHealthy=!1,console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${e.failCount} failures`)))}function qs(n){const e=he.get(n);return e?e.isHealthy?!0:Date.now()-e.lastCheckTime>Fe.degradeTimeout?(console.log(`[CDN Fallback] Trying to recover ${n}...`),!0):!1:!1}function xs(){return ze.filter(n=>n.enabled&&qs(n.name)).sort((n,e)=>n.priority-e.priority)}function Et(n){const e=/^\/?(aitu-app@[\d.]+\/)/;return n.replace(e,"/")}function Tt(n,e,t){const s=Et(t);return n.urlTemplate.replace("{version}",e).replace("{path}",s.startsWith("/")?s.slice(1):s)}async function $e(n,e=Fe.fetchTimeout){const t=new AbortController,s=setTimeout(()=>t.abort(),e);try{return await fetch(n,{signal:t.signal,cache:"no-store"})}finally{clearTimeout(s)}}async function Dt(n,e,t){var r;if(Ns)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;const s=xs();for(const o of s){const i=Tt(o,e,n);try{console.log(`[CDN Fallback] Trying ${o.name}: ${i}`);const a=await $e(i);if(a.ok){const c=a.headers.get("Content-Type")||"";if(!(c.includes("javascript")||c.includes("css")||c.includes("json")||c.includes("font")||c.includes("image")||c.includes("woff")||c.includes("application/octet-stream"))){console.warn(`[CDN Fallback] ${o.name} invalid Content-Type: ${c}`),ae(o.name);continue}const u=parseInt(a.headers.get("Content-Length")||"0",10),h=c.includes("javascript")||c.includes("css")||c.includes("json");if(h&&u>0&&u<50){console.warn(`[CDN Fallback] ${o.name} response too small: ${u} bytes`),ae(o.name);continue}const f=a.clone();try{const m=(r=f.body)==null?void 0:r.getReader();if(m){const{value:w}=await m.read();if(m.cancel(),w){const p=new TextDecoder().decode(w.slice(0,200)),d=p.includes("<!DOCTYPE")||p.includes("<html")||p.includes("<HTML")||p.includes("Not Found")||p.includes("404");if(h&&d){console.warn(`[CDN Fallback] ${o.name} returned HTML instead of ${c}`),ae(o.name);continue}}}}catch{}return Ct(o.name),console.log(`[CDN Fallback] Success from ${o.name}`),{response:a,source:o.name}}else console.warn(`[CDN Fallback] ${o.name} returned ${a.status}`),ae(o.name)}catch(a){console.warn(`[CDN Fallback] ${o.name} failed:`,a),ae(o.name)}}try{const o=Et(n),i=`${t}/${o.startsWith("/")?o.slice(1):o}`;console.log(`[CDN Fallback] Trying local server: ${i}`);const a=await $e(i);if(a.ok)return console.log("[CDN Fallback] Success from local server"),{response:a,source:"local"}}catch(o){console.warn("[CDN Fallback] Local server failed:",o)}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function Lt(n){const e=new Map;for(const t of ze){if(!t.enabled)continue;const s=Tt(t,n,t.healthCheckPath);try{const o=(await $e(s,5e3)).ok;e.set(t.name,o),o?Ct(t.name):ae(t.name)}catch{e.set(t.name,!1),ae(t.name)}}return e}function _t(){return Array.from(he.entries()).map(([n,e])=>({name:n,status:e}))}function At(){St(),console.log("[CDN Fallback] All CDN status reset")}const Q=self;wt(Q).setDebugClientCountChangedCallback(en);const J={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function Ae(n){var t;const e=((t=n[0])==null?void 0:t.toString())||"";return!!(e.includes("[ServiceWorkerChannel]")||e.includes("[BaseChannel]")||e.includes("Invalid message structure")||e.includes("broadcast:")||e.includes("publish:")||e.includes("subscribe:")||e.includes("[Main]")||e.includes("[SW Console Capture]")||e.includes("[SWChannelManager]")&&(e.includes("broadcast")||e.includes("sendConsoleLog")))}function Hs(){console.log=(...n)=>{J.log(...n),Ue()&&!Ae(n)&&ve("log",n)},console.info=(...n)=>{J.info(...n),Ue()&&!Ae(n)&&ve("info",n)},console.warn=(...n)=>{J.warn(...n),Ae(n)||ve("warn",n)},console.error=(...n)=>{J.error(...n),Ae(n)||ve("error",n)}}function Gs(n){let e;const t=[];for(const r of n)try{const o=r;if(r instanceof Error||r&&typeof r=="object"&&typeof o.message=="string")e=o.stack||e,t.push(`${o.name||"Error"}: ${o.message||""}`);else if(typeof r=="object"&&r!==null){const i=JSON.stringify(r);t.push(i==="{}"?String(r):i)}else t.push(String(r))}catch{t.push(String(r))}return{message:t.join(" ")||"(empty)",stack:e}}function ve(n,e){try{const{message:t,stack:s}=Gs(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Ve=="function"&&Ve({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){J.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Ve=null;Hs(),Promise.resolve().then(()=>ce).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=W();t&&t.sendDebugLLMLog(e)})});const U="0.6.13",Ke=`drawnix-v${U}`,A="drawnix-images",we=`drawnix-static-v${U}`,Me="drawnix-fonts",Us="/__aitu_cache__/",js="/asset-library/",vt=location.hostname==="localhost"||location.hostname==="127.0.0.1",Fs=[{hostname:"google.datas.systems",pathPattern:"response_images",fallbackDomain:"cdn.i666.fun"},{hostname:"googlecdn2.datas.systems",pathPattern:"response_images",fallbackDomain:"googlecdn2.i666.fun"},{hostname:"filesystem.i666.fun",pathPattern:"response_images",fallbackDomain:"filesystem.i666.fun"}],zs=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,$s=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,q=new Map,ie=new Map,Mt=30*1e3,ye=new Map,B=new Map,Vs=300*1e3,Rt=10,de=new Set,ge=new Set,Ks=3600*1e3,Xe=new Map;function kt(n){ge.add(n),Xe.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function Xs(n){if(!ge.has(n))return!1;const e=Xe.get(n);return e&&Date.now()-e>Ks?(ge.delete(n),Xe.delete(n),!1):!0}const V=[],Pt=7,j=[],Ys=500;let v=!1;function N(n){if(!v)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return j.unshift(t),j.length>Ys&&j.pop(),Ot(t),e}function M(n,e){if(!v||!n)return;const t=j.find(s=>s.id===n);t&&(Object.assign(t,e),Ot(t))}function Ot(n){const e=W();e&&e.sendDebugLog(n)}function Re(){return new Promise((n,e)=>{const t=indexedDB.open("ConsoleLogDB",1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains("logs")){const o=r.createObjectStore("logs",{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("logLevel","logLevel",{unique:!1})}}})}async function Qs(n){try{const e=await Re(),t=e.transaction(["logs"],"readwrite");return t.objectStore("logs").add(n),new Promise((r,o)=>{t.oncomplete=()=>{e.close(),r()},t.onerror=()=>{e.close(),o(t.error)}})}catch(e){console.warn("Service Worker: 无法保存控制台日志:",e)}}async function It(){try{await Wt();const n=await Re(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Pt*24*60*60*1e3;return new Promise((o,i)=>{const a=s.openCursor(null,"prev"),c=[];a.onsuccess=()=>{const l=a.result;if(l){const u=l.value;u.timestamp>=r&&c.push(u),l.continue()}else n.close(),o(c)},a.onerror=()=>{n.close(),i(a.error)}})}catch(n){return console.warn("Service Worker: 无法加载控制台日志:",n),[]}}async function Wt(){try{const n=await Re(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Pt*24*60*60*1e3,o=IDBKeyRange.upperBound(r);return new Promise((i,a)=>{const c=s.openCursor(o);let l=0;c.onsuccess=()=>{const u=c.result;u?(u.delete(),l++,u.continue()):(n.close(),l>0,i(l))},c.onerror=()=>{n.close(),a(c.error)}})}catch(n){return console.warn("Service Worker: 无法清理过期日志:",n),0}}async function Bt(){try{const n=await Re(),e=n.transaction(["logs"],"readwrite");return e.objectStore("logs").clear(),new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("Service Worker: 无法清空控制台日志:",n)}}const Nt=500;function Ye(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(v||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};Qs(r),V.unshift(r),V.length>Nt&&(V.length=Nt),v&&Js(r)}Ve=Ye;function Js(n){const e=W();e&&e.sendConsoleLog(n)}function Zs(){let n=0;return B.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function qt(){return{version:U,cacheNames:[Ke,A,we,Me],pendingImageRequests:q.size,pendingVideoRequests:ye.size,videoBlobCacheSize:B.size,videoBlobCacheTotalBytes:Zs(),completedImageRequestsSize:ie.size,failedDomainsCount:de.size,failedDomains:Array.from(de),corsFailedDomainsCount:ge.size,corsFailedDomains:Array.from(ge),debugLogsCount:j.length,consoleLogsCount:V.length,debugModeEnabled:v,memoryStats:{pendingRequestsMapSize:q.size,completedRequestsMapSize:ie.size,videoBlobCacheMapSize:B.size,failedDomainsSetSize:de.size,corsFailedDomainsSetSize:ge.size,debugLogsArraySize:j.length,consoleLogsArraySize:V.length}}}function Qe(){return j}function xt(){j.length=0}function Ht(){V.length=0}function Je(){v||(v=!0,be(!0),_e(!0),J.log("Service Worker: Debug mode enabled (debug page connected)"))}function Ze(){v&&(v=!1,be(!1),_e(!1),V.length=0,j.length=0,J.log("Service Worker: Debug mode disabled (no debug pages)"))}function en(n){n>0?Je():Ze()}function Gt(n){for(const e of Fs)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function tn(n,e){return zs.test(n.pathname)||e.destination==="image"||Gt(n)!==null}function sn(n,e){return $s.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function nn(n,e){return n.hostname==="fonts.googleapis.com"||n.hostname==="fonts.gstatic.com"?!0:/\.(woff|woff2|ttf|otf|eot)$/i.test(n.pathname)||e.destination==="font"}async function rn(){try{const n=indexedDB.open("ServiceWorkerDB",1);return new Promise((e,t)=>{n.onerror=()=>t(n.error),n.onsuccess=()=>{const s=n.result;if(s.objectStoreNames.contains("failedDomains")){const i=s.transaction(["failedDomains"],"readonly").objectStore("failedDomains").getAll();i.onsuccess=()=>{i.result.forEach(c=>de.add(c.domain)),e()},i.onerror=()=>t(i.error)}else e()},n.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains("failedDomains")||r.createObjectStore("failedDomains",{keyPath:"domain"})}})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function on(n){try{const e=indexedDB.open("ServiceWorkerDB",1);return new Promise((t,s)=>{e.onerror=()=>s(e.error),e.onsuccess=()=>{const o=e.result.transaction(["failedDomains"],"readwrite");o.objectStore("failedDomains").put({domain:n,timestamp:Date.now()}),o.oncomplete=()=>{t()},o.onerror=()=>s(o.error)},e.onupgradeneeded=r=>{const o=r.target.result;o.objectStoreNames.contains("failedDomains")||o.createObjectStore("failedDomains",{keyPath:"domain"})}})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function an(n){try{const e=await n.keys();if(e.length<=10)return;const t=[];for(const i of e)try{const a=await n.match(i);if(a){const c=a.headers.get("sw-cache-date"),l=a.headers.get("sw-image-size");t.push({request:i,cacheDate:c?parseInt(c):0,imageSize:l?parseInt(l):0})}}catch(a){console.warn("Service Worker: Error reading cache entry:",a)}t.sort((i,a)=>i.cacheDate-a.cacheDate);const s=Math.max(1,Math.floor(t.length*.25));let r=0,o=0;for(let i=0;i<s&&i<t.length;i++)try{await n.delete(t[i].request),r++,o+=t[i].imageSize}catch(a){console.warn("Service Worker: Error deleting cache entry:",a)}}catch(e){console.warn("Service Worker: Cache cleanup failed:",e)}}async function cn(){try{const n=await fetch("./precache-manifest.json",{cache:"reload"});return n.ok?(await n.json()).files:null}catch{return null}}async function ln(n,e,t){try{const s=await n.match(e);if(s&&s.headers.get("x-sw-revision")===t)return{url:e,success:!0,skipped:!0};const r=e.endsWith(".html")||e==="/";let o=null,i="server";if(!r){const a=await Dt(e.startsWith("/")?e.slice(1):e,U,location.origin);a&&a.response.ok&&(o=a.response,i=a.source)}if(o||(o=await fetch(e,{cache:"reload"}),i="server"),o.ok){const a=new Headers(o.headers);a.set("x-sw-revision",t),a.set("x-sw-cached-at",new Date().toISOString()),a.set("x-sw-source",i);const c=new Response(await o.blob(),{status:o.status,statusText:o.statusText,headers:a}),l=new URL(e,self.location.origin).href;return await n.put(l,c),{url:e,success:!0,source:i}}return{url:e,success:!1,status:o.status}}catch(s){return{url:e,success:!1,error:String(s)}}}async function un(n,e){const s=[];for(let r=0;r<e.length;r+=6){const o=e.slice(r,r+6),i=await Promise.allSettled(o.map(({url:a,revision:c})=>ln(n,a,c)));for(const a of i)a.status==="fulfilled"?s.push({success:a.value.success,source:a.value.source}):s.push({success:!1})}s.filter(r=>r.success).length,s.filter(r=>r.success&&r.source&&r.source!=="server").length,s.filter(r=>r.success&&r.source==="server").length}Q.addEventListener("install",n=>{Q.skipWaiting(),n.waitUntil((async()=>{await rn();try{const e=await cn();if(e&&e.length>0){const t=await caches.open(we);await un(t,e)}}catch(e){console.warn("Service Worker: Precache failed:",e)}})())}),Q.addEventListener("activate",n=>{n.waitUntil((async()=>{await Q.clients.claim();const e=W();e&&e.sendSWActivated(U)})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(o=>o.startsWith("drawnix-images-v")&&o!==A);if(t.length>0){const o=await caches.open(A);for(const i of t)try{const a=await caches.open(i),c=await a.keys();for(const l of c){const u=await a.match(l);u&&await o.put(l,u)}await caches.delete(i)}catch(a){console.warn(`Failed to migrate cache ${i}:`,a)}}const s=e.filter(o=>o.startsWith("drawnix-static-v")&&o!==we),r=e.filter(o=>o.startsWith("drawnix-v")&&o!==Ke&&o!==A&&!o.startsWith("drawnix-static-v"));(s.length>0||r.length>0)&&setTimeout(async()=>{for(const o of[...s,...r])try{await caches.delete(o)}catch(i){console.warn("Failed to delete old cache:",o,i)}},3e4),Wt().catch(o=>{console.warn("Failed to cleanup expired console logs:",o)})}))});function hn(n){if(v){const e=W();e&&e.sendPostMessageLog(n)}}Q.addEventListener("message",n=>{var i,a,c,l,u,h,f,m,w,p;const e=((i=n.data)==null?void 0:i.type)||((a=n.data)==null?void 0:a.cmdname)||((l=(c=n.data)==null?void 0:c.req)==null?void 0:l.cmdname)||"unknown",t=((u=n.source)==null?void 0:u.id)||"",s=((h=n.source)==null?void 0:h.url)||"",r=((f=n.data)==null?void 0:f.cmdname)||((m=n.data)==null?void 0:m.requestId)&&((w=n.data)==null?void 0:w.ret)!==void 0;let o="";if(Ne()&&!r&&(o=qe(e,n.data,t,s,(p=n.data)==null?void 0:p.__internal__),o&&v)){const b=Ce().find(S=>S.id===o);b&&hn(b)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:d,mediaType:b,blob:S,mimeType:C}=n.data;if(d&&b&&S){const T=new Blob([S],{type:C||(b==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:K}=await Promise.resolve().then(()=>x);K(T,d,b)})()}return}if(n.data&&n.data.type==="SKIP_WAITING"){Q.skipWaiting();const d=W();d&&d.sendSWUpdated(U)}else if(n.data&&n.data.type==="FORCE_UPGRADE"){Q.skipWaiting();const d=W();d&&d.sendSWUpdated(U)}else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:d}=n.data;d&&tt(d).then(()=>{const b=W();b&&b.sendCacheDeleted(d)}).catch(b=>{console.error("Service Worker: Failed to delete cache:",b)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:d}=n.data;d&&Array.isArray(d)&&mn(d).then(()=>{}).catch(b=>{console.error("Service Worker: Failed to batch delete caches:",b)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")bn().then(()=>{}).catch(d=>{console.error("Service Worker: Failed to clear all cache:",d)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){v=!0,be(!0),_e(!0),J.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const d=W();d&&d.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){v=!1,be(!1),_e(!1),V.length=0,j.length=0,J.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const d=W();d&&d.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:d}=await Promise.resolve().then(()=>ce),b=await d(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:b})}catch(d){console.error("[SW] Failed to get LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:d}=await Promise.resolve().then(()=>ce);await d();const b=n.source;b&&b.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(d){console.error("[SW] Failed to clear LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const d=n.source;d&&d.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:v,swVersion:U,logs:j.slice(-100),consoleLogs:V.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:d}=await Promise.resolve().then(()=>Bs),b=Qe(),S=d(),C=n.source;C&&C.postMessage({type:"SW_DEBUG_LOGS",logs:[...b,...S.map(T=>({...T,type:"fetch"}))]})}catch(d){console.error("[SW] Failed to get fetch logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const d=n.source;d&&d.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:V})}catch(d){console.error("[SW] Failed to get console logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const d=Ce(),b=n.source;b&&b.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:d})}catch(d){console.error("[SW] Failed to get postmessage logs:",d)}})();return}});const dn="MemorySnapshotDB",re="snapshots",Ut=50;async function et(){return new Promise((n,e)=>{const t=indexedDB.open(dn,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(re)){const o=r.createObjectStore(re,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function jt(n){try{const e=await et(),t=e.transaction(re,"readwrite"),s=t.objectStore(re);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>Ut){const a=s.index("timestamp").openCursor();let c=0;const l=o-Ut;a.onsuccess=u=>{const h=u.target.result;h&&c<l&&(s.delete(h.value.id),c++,h.continue())}}},await new Promise((o,i)=>{t.oncomplete=()=>{e.close(),o()},t.onerror=()=>{e.close(),i(t.error)}})}catch(e){console.warn("[SW] Failed to save crash snapshot:",e)}}async function Ft(){try{const n=await et(),s=n.transaction(re,"readonly").objectStore(re).index("timestamp");return new Promise((r,o)=>{const i=s.getAll();i.onsuccess=()=>{n.close();const a=i.result.sort((c,l)=>l.timestamp-c.timestamp);r(a)},i.onerror=()=>{n.close(),o(i.error)}})}catch(n){return console.warn("[SW] Failed to get crash snapshots:",n),[]}}async function zt(){try{const n=await et(),e=n.transaction(re,"readwrite");e.objectStore(re).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("[SW] Failed to clear crash snapshots:",n)}}const gn=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function fn(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function pn(n){return new Promise(e=>{try{const t=indexedDB.open(n);t.onerror=()=>e({count:0,totalSize:0}),t.onsuccess=()=>{const s=t.result,r=Array.from(s.objectStoreNames);if(r.length===0){s.close(),e({count:0,totalSize:0});return}let o=0,i=0,a=0,c=0;const l=10;try{const u=s.transaction(r,"readonly");for(const h of r){const f=u.objectStore(h),m=f.count();m.onsuccess=()=>{const w=m.result;if(o+=w,w>0){const p=f.openCursor();let d=0;p.onsuccess=b=>{const S=b.target.result;if(S&&d<l)i+=fn(S.value),a++,d++,S.continue();else if(c++,c===r.length){s.close();const C=a>0?i/a:0,T=Math.round(C*o);e({count:o,totalSize:T})}},p.onerror=()=>{if(c++,c===r.length){s.close();const b=a>0?i/a:0,S=Math.round(b*o);e({count:o,totalSize:S})}}}else c++,c===r.length&&(s.close(),e({count:o,totalSize:0}))},m.onerror=()=>{if(c++,c===r.length){s.close();const w=a>0?i/a:0,p=Math.round(w*o);e({count:o,totalSize:p})}}}}catch{s.close(),e({count:0,totalSize:0})}},t.onupgradeneeded=s=>{s.target.result.close();try{indexedDB.deleteDatabase(n)}catch{}e({count:0,totalSize:0})}}catch{e({count:0,totalSize:0})}})}async function $t(){const n={},e=[Ke,A,we,Me];for(const t of e)try{const s=await caches.open(t),r=await s.keys();let o=0;const i=Math.min(r.length,100);let a=0;for(let c=0;c<i;c++){const l=await s.match(r[c]);if(l){const u=l.headers.get("sw-image-size")||l.headers.get("content-length");u&&(a+=parseInt(u))}}i>0&&r.length>i?o=Math.round(a/i*r.length):o=a,n[t]={count:r.length,totalSize:o,type:"cache"}}catch{n[t]={count:0,totalSize:0,type:"cache"}}for(const t of gn)try{const s=await pn(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function tt(n){try{await(await caches.open(A)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function mn(n){try{const e=await caches.open(A);let t=0;for(const s of n)try{await e.delete(s),t++}catch(r){console.warn("Service Worker: Failed to delete cache in batch:",s,r)}}catch(e){throw console.error("Service Worker: Failed to batch delete caches:",e),e}}async function bn(){try{const n=await caches.open(A),e=await n.keys();for(const t of e)await n.delete(t)}catch(n){throw console.error("Service Worker: Failed to clear image cache:",n),n}}async function Vt(n,e,t){try{const s=W();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}async function wn(){try{if(navigator.storage&&navigator.storage.estimate){const n=await navigator.storage.estimate(),e=n.usage||0,t=n.quota||0,s=t>0?e/t*100:0;if(s>90){console.warn("Service Worker: Storage quota warning:",{usage:e,quota:t,percentage:s});const r=W();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const Z=new Map,Kt=300*1e3,Xt=500;function yn(n){const e=n.match(/\/(\d{4})\/(\d{2})\/(\d{2})\//),t=n.match(/\/(\d{4})(\d{2})(\d{2})\//);let s=null;if(e?s=new Date(parseInt(e[1]),parseInt(e[2])-1,parseInt(e[3])):t&&(s=new Date(parseInt(t[1]),parseInt(t[2])-1,parseInt(t[3]))),!s)return!1;const r=new Date;return!(s.getFullYear()===r.getFullYear()&&s.getMonth()===r.getMonth()&&s.getDate()===r.getDate())}function Sn(n){const e=Z.get(n);return e?Date.now()-e>Kt?(Z.delete(n),!1):!0:!1}function Yt(n){if(yn(n)){if(Z.size>=Xt){const e=Date.now();for(const[t,s]of Z)e-s>Kt&&Z.delete(t);if(Z.size>=Xt){const t=Array.from(Z.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)Z.delete(r)}}Z.set(n,Date.now())}}Q.addEventListener("fetch",n=>{const e=new URL(n.request.url),t=Date.now();if(e.protocol!=="http:"&&e.protocol!=="https:"){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"other",details:`Skipped: non-http protocol (${e.protocol})`,status:0,duration:0});return}if(e.pathname.startsWith(Us)){const s=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(En(n.request).then(r=>(M(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw M(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(js)){const s=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Tn(n.request).then(r=>(M(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw M(s,{error:String(r),duration:Date.now()-t}),r}));return}if(!(e.hostname.endsWith(".posthog.com")||e.hostname.endsWith(".sentry.io")||e.hostname.endsWith(".ingest.sentry.io"))){if(e.hostname==="cdn.i666.fun"){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: cdn.i666.fun (fallback domain)",status:0,duration:0});return}if(e.hostname.endsWith(".volces.com")||e.hostname.endsWith(".volccdn.com")){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Volcengine domain (no CORS)",status:0,duration:0});return}if(e.hostname.endsWith(".aliyuncs.com")){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Aliyun OSS domain (no CORS)",status:0,duration:0});return}if(Xs(e.hostname)){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:`Passthrough: ${e.hostname} (CORS failed domain, auto-detected)`,status:0,duration:0});return}if(e.hostname!=="api.github.com"){if(sn(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"video",headers:r?{range:r}:void 0,details:r?`Video Range request: ${r}`:"Video request"});n.respondWith(Dn(n.request).then(i=>(M(o,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-s,responseHeaders:{"content-type":i.headers.get("content-type")||"","content-length":i.headers.get("content-length")||"","content-range":i.headers.get("content-range")||""}}),i)).catch(i=>{throw M(o,{error:String(i),duration:Date.now()-s}),i}));return}if(nn(e,n.request)){const s=Date.now(),r=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(Cn(n.request).then(o=>(M(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date")}),o)).catch(o=>{throw M(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&tn(e,n.request)){if(Sn(n.request.url)){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"Skipped: recently failed URL (cached 404)",status:404,duration:0}),n.respondWith(new Response("",{status:404,statusText:"Not Found (cached)"}));return}const s=Date.now(),r=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(vn(n.request).then(o=>(o.status===404&&Yt(n.request.url),M(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date"),size:parseInt(o.headers.get("content-length")||"0")}),o)).catch(o=>{throw Yt(n.request.url),M(r,{error:String(o),duration:Date.now()-s}),o}));return}if(n.request.method==="GET"){const s=n.request.mode==="navigate",r=n.request.destination!=="";if(s||r){const o=Date.now(),i=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(Ln(n.request).then(a=>(M(i,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-o}),a)).catch(a=>{throw M(i,{error:String(a),duration:Date.now()-o}),a}));return}}if(v){const s=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"xhr",details:`XHR/API request (${n.request.method})`});n.respondWith((async()=>{try{const r=n.request.clone();let o;const i={};if(n.request.headers.forEach((h,f)=>{i[f]=h}),["POST","PUT","PATCH"].includes(n.request.method))try{const h=n.request.headers.get("content-type")||"";h.includes("application/json")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):h.includes("application/x-www-form-urlencoded")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):o=`[${h||"binary data"}]`}catch{o="[unable to read body]"}M(s,{headers:i,details:o?`XHR/API request (${n.request.method})
1
+ var sw=(function(E){"use strict";var ae=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(ae||{});ae.IMAGE+"",ae.VIDEO+"",ae.AUDIO+"",ae.CHARACTER+"",ae.INSPIRATION_BOARD+"",ae.CHAT+"";function lt(n){return n instanceof Error?n.name||"Error":"Unknown error"}const Be="sw-task-queue",ut=3,L="tasks",G="config",M="workflows",k="chat-workflows",P="pending-tool-requests",_="pending-dom-operations",O="task-step-mappings",U="pending-canvas-operations",is=[L,G,M,k,P,_,O,U];function cs(){return new Promise(n=>{const e=indexedDB.open(Be);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,ut))},e.onerror=()=>{n(ut)}})}function ls(n){const e=[];for(const t of is)n.objectStoreNames.contains(t)||e.push(t);return e}function us(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(Be,s);r.onerror=()=>{console.error("[SWStorage] Failed to repair DB:",r.error),t(r.error)},r.onsuccess=()=>{e(r.result)},r.onupgradeneeded=o=>{const i=o.target.result;ht(i)}})}function ht(n){if(!n.objectStoreNames.contains(L)){const e=n.createObjectStore(L,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("type","type",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(G)||n.createObjectStore(G,{keyPath:"key"}),!n.objectStoreNames.contains(M)){const e=n.createObjectStore(M,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(k)){const e=n.createObjectStore(k,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(P)||n.createObjectStore(P,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(_)){const e=n.createObjectStore(_,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(O)||n.createObjectStore(O,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains(U)||n.createObjectStore(U,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function hs(){const n=await cs();return new Promise((e,t)=>{const s=indexedDB.open(Be,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=ls(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),us(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;ht(o)}})}class ds{constructor(){this.dbPromise=null,this.pendingTaskSaves=new Map,this.batchSaveTimer=null,this.batchSavePromises=new Map,this.BATCH_SAVE_DELAY=50}async getDB(){return this.dbPromise||(this.dbPromise=hs()),this.dbPromise}async flushPendingTaskSaves(){this.batchSaveTimer&&(clearTimeout(this.batchSaveTimer),this.batchSaveTimer=null);const e=Array.from(this.pendingTaskSaves.values()),t=new Map(this.batchSavePromises);if(this.pendingTaskSaves.clear(),this.batchSavePromises.clear(),e.length!==0)try{const s=await this.getDB();await new Promise((r,o)=>{const i=s.transaction(L,"readwrite"),a=i.objectStore(L);for(const c of e)a.put(c);i.oncomplete=()=>{t.forEach(({resolve:c})=>c()),r()},i.onerror=()=>{const c=i.error;t.forEach(({reject:l})=>l(c)),o(c)}})}catch(s){console.error("[SWStorage] Failed to batch save tasks:",s),t.forEach(({reject:r})=>r(s))}}async saveTask(e){return new Promise((t,s)=>{this.pendingTaskSaves.set(e.id,e),this.batchSavePromises.set(e.id,{resolve:t,reject:s}),this.batchSaveTimer||(this.batchSaveTimer=setTimeout(()=>{this.flushPendingTaskSaves()},this.BATCH_SAVE_DELAY))})}async saveTaskImmediate(e){this.pendingTaskSaves.delete(e.id);const t=this.batchSavePromises.get(e.id);t&&this.batchSavePromises.delete(e.id);try{const s=await this.getDB();await new Promise((r,o)=>{const c=s.transaction(L,"readwrite").objectStore(L).put(e);c.onerror=()=>o(c.error),c.onsuccess=()=>r()}),t&&t.resolve()}catch(s){throw console.error("[SWStorage] Failed to save task:",s),t&&t.reject(s),s}}async getTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(L,"readonly").objectStore(L).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task:",t),null}}async getAllTasks(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(L,"readonly").objectStore(L).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all tasks:",e),[]}}async getTasksByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(L,"readonly").objectStore(L).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get tasks by status:",t),[]}}async getTasksPaginated(e){const{offset:t,limit:s,status:r,type:o,sortOrder:i="desc"}=e;try{const a=await this.getDB();return new Promise((c,l)=>{const f=a.transaction(L,"readonly").objectStore(L).index("createdAt"),m=i==="desc"?"prev":"next",b=f.openCursor(null,m),p=[];let d=0,w=0;b.onerror=()=>l(b.error),b.onsuccess=y=>{const C=y.target.result;if(!C){c({tasks:p,total:w,hasMore:w>t+p.length});return}const T=C.value,q=!r||T.status===r,ee=!o||T.type===o;q&&ee&&(w++,d<t?d++:p.length<s&&p.push(T)),C.continue()}})}catch(a){return console.error("[SWStorage] Failed to get paginated tasks:",a),{tasks:[],total:0,hasMore:!1}}}async deleteTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(L,"readwrite").objectStore(L).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task:",t)}}async getConfig(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(G,"readonly").objectStore(G).get(e);a.onsuccess=()=>{const c=a.result;if(!c){s(null);return}const{key:l,...u}=c;s(u)},a.onerror=()=>r(a.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",lt(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const i=s.transaction(G,"readwrite");i.objectStore(G).put({key:e,...t,updatedAt:Date.now()}),i.oncomplete=()=>r(),i.onerror=()=>o(i.error)})}catch(s){throw console.error("[SWStorage] Failed to save config:",lt(s)),s}}async loadConfig(){const e=await this.getConfig("gemini"),t=await this.getConfig("video");return{geminiConfig:e,videoConfig:t}}async saveAllConfig(e,t){await this.saveConfig("gemini",e),await this.saveConfig("video",t)}async saveSystemPrompt(e){try{const t=await this.getDB();return new Promise((s,r)=>{const o=t.transaction(G,"readwrite");o.objectStore(G).put({key:"systemPrompt",value:e,updatedAt:Date.now()}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.error("[SWStorage] Failed to save system prompt:",t)}}async getSystemPrompt(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(G,"readonly").objectStore(G).get("systemPrompt");i.onsuccess=()=>{const a=i.result;t((a==null?void 0:a.value)||null)},i.onerror=()=>s(i.error)})}catch(e){return console.error("[SWStorage] Failed to get system prompt:",e),null}}async saveWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(M,"readwrite").objectStore(M).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save workflow:",t)}}async getWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(M,"readonly").objectStore(M).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get workflow:",t),null}}async getAllWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(M,"readonly").objectStore(M).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all workflows:",e),[]}}async getWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(M,"readonly").objectStore(M).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get workflows by status:",t),[]}}async deleteWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(M,"readwrite").objectStore(M).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete workflow:",t)}}async saveChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(k,"readwrite").objectStore(k).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save chat workflow:",t)}}async getChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(k,"readonly").objectStore(k).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get chat workflow:",t),null}}async getAllChatWorkflows(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(k,"readonly").objectStore(k).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all chat workflows:",e),[]}}async getChatWorkflowsByStatus(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(k,"readonly").objectStore(k).index("status").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get chat workflows by status:",t),[]}}async deleteChatWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(k,"readwrite").objectStore(k).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete chat workflow:",t)}}async savePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(P,"readwrite").objectStore(P).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending tool request:",t)}}async getAllPendingToolRequests(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(P,"readonly").objectStore(P).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending tool requests:",e),[]}}async getPendingToolRequestsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(P,"readonly").objectStore(P).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending tool requests by workflow:",t),[]}}async getPendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(P,"readonly").objectStore(P).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending tool request:",t),null}}async deletePendingToolRequest(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(P,"readwrite").objectStore(P).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending tool request:",t)}}async deletePendingToolRequestsByWorkflow(e){try{const t=await this.getPendingToolRequestsByWorkflow(e);for(const s of t)await this.deletePendingToolRequest(s.requestId)}catch(t){console.error("[SWStorage] Failed to delete pending tool requests by workflow:",t)}}async cleanupStalePendingToolRequests(e=36e5){try{const t=await this.getAllPendingToolRequests(),s=Date.now(),r=t.filter(o=>s-o.createdAt>e);if(r.length===0)return 0;console.log(`[SWStorage] Cleaning up ${r.length} stale pending tool requests`);for(const o of r)await this.deletePendingToolRequest(o.requestId);return r.length}catch(t){return console.error("[SWStorage] Failed to cleanup stale pending tool requests:",t),0}}async savePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(_,"readwrite").objectStore(_).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending DOM operation:",t)}}async getAllPendingDomOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(_,"readonly").objectStore(_).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending DOM operations:",e),[]}}async getPendingDomOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(_,"readonly").objectStore(_).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by workflow:",t),[]}}async getPendingDomOperationsByChatId(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(_,"readonly").objectStore(_).index("chatId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by chat ID:",t),[]}}async getPendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(_,"readonly").objectStore(_).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operation:",t),null}}async deletePendingDomOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(_,"readwrite").objectStore(_).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending DOM operation:",t)}}async deletePendingDomOperationsByWorkflow(e){try{const t=await this.getPendingDomOperationsByWorkflow(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by workflow:",t)}}async deletePendingDomOperationsByChatId(e){try{const t=await this.getPendingDomOperationsByChatId(e);for(const s of t)await this.deletePendingDomOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending DOM operations by chat ID:",t)}}async saveTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(O,"readwrite").objectStore(O).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save task-step mapping:",t)}}async getAllTaskStepMappings(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(O,"readonly").objectStore(O).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all task-step mappings:",e),[]}}async getTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(O,"readonly").objectStore(O).get(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s(a.result||null)})}catch(t){return console.error("[SWStorage] Failed to get task-step mapping:",t),null}}async getTaskStepMappingsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(O,"readonly").objectStore(O).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get task-step mappings by workflow:",t),[]}}async deleteTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(O,"readwrite").objectStore(O).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete task-step mapping:",t)}}async deleteTaskStepMappingsByWorkflow(e){try{const t=await this.getTaskStepMappingsByWorkflow(e);for(const s of t)await this.deleteTaskStepMapping(s.taskId)}catch(t){console.error("[SWStorage] Failed to delete task-step mappings by workflow:",t)}}async savePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(U,"readwrite").objectStore(U).put(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to save pending canvas operation:",t)}}async getAllPendingCanvasOperations(){try{const e=await this.getDB();return new Promise((t,s)=>{const i=e.transaction(U,"readonly").objectStore(U).getAll();i.onerror=()=>s(i.error),i.onsuccess=()=>t(i.result||[])})}catch(e){return console.error("[SWStorage] Failed to get all pending canvas operations:",e),[]}}async getPendingCanvasOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(U,"readonly").objectStore(U).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending canvas operations by workflow:",t),[]}}async deletePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const a=t.transaction(U,"readwrite").objectStore(U).delete(e);a.onerror=()=>r(a.error),a.onsuccess=()=>s()})}catch(t){console.error("[SWStorage] Failed to delete pending canvas operation:",t)}}async deletePendingCanvasOperationsByWorkflow(e){try{const t=await this.getPendingCanvasOperationsByWorkflow(e);for(const s of t)await this.deletePendingCanvasOperation(s.id)}catch(t){console.error("[SWStorage] Failed to delete pending canvas operations by workflow:",t)}}}const gs=new ds,fs=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function Ne(n){if(!n)return n;if(typeof n=="string")return n.toLowerCase().startsWith("bearer ")||n.length>30&&/^[a-zA-Z0-9-_]+$/.test(n)&&!n.includes("-")?"[REDACTED]":n;if(Array.isArray(n))return n.map(e=>Ne(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();fs.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Ne(s)}return e}return n}let Ee=!1;const ps=500,te=[];let qe=0;function dt(){return Ee}const gt=["SW_DEBUG_ENABLE","SW_DEBUG_DISABLE","SW_DEBUG_GET_STATUS","SW_DEBUG_CLEAR_LOGS","SW_DEBUG_CLEAR_CONSOLE_LOGS","SW_DEBUG_GET_CONSOLE_LOGS","SW_DEBUG_EXPORT_LOGS","SW_DEBUG_HEARTBEAT","SW_DEBUG_STATUS","SW_DEBUG_ENABLED","SW_DEBUG_DISABLED","SW_DEBUG_LOG","SW_DEBUG_LOGS","SW_DEBUG_LOGS_CLEARED","SW_CONSOLE_LOG","SW_DEBUG_CONSOLE_LOGS","SW_DEBUG_CONSOLE_LOGS_CLEARED","SW_POSTMESSAGE_LOG","SW_DEBUG_POSTMESSAGE_LOGS","SW_DEBUG_POSTMESSAGE_LOGS_CLEARED","SW_DEBUG_NEW_CRASH_SNAPSHOT","SW_DEBUG_CRASH_SNAPSHOTS","SW_DEBUG_CRASH_SNAPSHOTS_CLEARED","SW_DEBUG_GET_CRASH_SNAPSHOTS","SW_DEBUG_CLEAR_CRASH_SNAPSHOTS","CRASH_SNAPSHOT","debug:log","debug:llmLog","debug:statusChanged","debug:enable","debug:disable","debug:getStatus","debug:getLogs","debug:clearLogs","debug:getConsoleLogs","debug:clearConsoleLogs","debug:getPostMessageLogs","debug:clearPostMessageLogs","debug:getCrashSnapshots","debug:clearCrashSnapshots","debug:getLLMApiLogs","debug:clearLLMApiLogs","debug:getCacheStats","debug:exportLogs","debug:newCrashSnapshot","console:log","console:report","postmessage:log","postmessage:logBatch","crash:snapshot","crash:heartbeat"],we=new Map;function ft(n){const e=Ee;Ee=n,!n&&e&&(te.length=0,we.clear(),qe=0)}function He(){return Ee}function ms(n){if(!dt()||n==="unknown"||gt.includes(n))return!1;if(n.startsWith("RPC:")){let e=n.slice(4);if(e.endsWith(":response")?e=e.slice(0,-9):e.endsWith(":error")&&(e=e.slice(0,-6)),gt.includes(e))return!1}return!0}function bs(n){if(!n)return{};let e="other";return n.includes("sw-debug")?e="debug":(n.includes("localhost")||n.includes("127.0.0.1")||!n.includes("chrome-extension")&&!n.includes("moz-extension"))&&(e="main"),{clientType:e,clientUrl:new URL(n).pathname+new URL(n).search}}function xe(n,e,t,s,r){if(r||!ms(n))return"";const o=bs(s);if(o.clientType==="debug")return"";const i=`pm-recv-${Date.now()}-${++qe}`,a={id:i,timestamp:Date.now(),direction:"receive",messageType:n,data:pt(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(ws(a),Ss(n)){const c=Cs(e);c&&we.set(c,{entry:a,startTime:Date.now()})}return i}function ws(n){te.unshift(n),te.length>ps&&te.pop()}function Ge(n,e,t,s){if(!dt())return"";const r=we.get(n);if(r){r.entry.response=pt(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return we.delete(n),o}return""}function Te(){return[...te]}function ys(){te.length=0,we.clear(),qe=0}function Ss(n){return n.startsWith("RPC:")&&!n.endsWith(":response")&&!n.endsWith(":error")?!0:["TASK_SUBMIT","TASK_CANCEL","TASK_RETRY","TASK_DELETE","TASK_GET_","WORKFLOW_SUBMIT","WORKFLOW_CANCEL","WORKFLOW_GET_","CHAT_START","MCP_TOOL_EXECUTE","MAIN_THREAD_TOOL_REQUEST"].some(t=>n.includes(t))}function Cs(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function pt(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return Ne(e)}catch{return"[Non-serializable data]"}}function Es(){const n={total:te.length,sent:0,received:0,byType:{}};for(const e of te)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const Ue=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:ys,getAllLogs:Te,getLogStats:Es,isPostMessageLoggerDebugMode:He,logReceivedMessage:xe,setPostMessageLoggerDebugMode:ft,updateRequestWithResponse:Ge},Symbol.toStringTag,{value:"Module"}));function Ts(){return typeof window<"u"?window:typeof self<"u"?self:{}}function Ds(n){return JSON.parse(JSON.stringify(n))}function mt(n){const e=Date.now().toString(36);let t;if(typeof crypto<"u"&&crypto.getRandomValues){const s=new Uint32Array(2);crypto.getRandomValues(s),t=s[0].toString(36)+s[1].toString(36)}else t=Math.floor(1e10*Math.random()).toString(36);return`${n}${e}${t}_`}const Ls="postmessage-duplex",_s="1.2.0",De=Ts();var $,se;De.__POSTMESSAGE_DUPLEX__||(De.__POSTMESSAGE_DUPLEX__={}),De.__POSTMESSAGE_DUPLEX__.version=_s,De.__POSTMESSAGE_DUPLEX__.name=Ls,(function(n){n[n.Success=0]="Success",n[n.ReceiverCallbackError=-1]="ReceiverCallbackError",n[n.SendCallbackError=-2]="SendCallbackError",n[n.NoSubscribe=-3]="NoSubscribe",n[n.TimeOut=-99]="TimeOut"})($||($={})),(function(n){n.ConnectionDestroyed="CONNECTION_DESTROYED",n.ConnectionTimeout="CONNECTION_TIMEOUT",n.MethodCallTimeout="METHOD_CALL_TIMEOUT",n.MethodNotFound="METHOD_NOT_FOUND",n.TransmissionFailed="TRANSMISSION_FAILED",n.MessageSizeExceeded="MESSAGE_SIZE_EXCEEDED",n.RateLimitExceeded="RATE_LIMIT_EXCEEDED",n.HandlerError="HANDLER_ERROR",n.InvalidMessage="INVALID_MESSAGE",n.OriginMismatch="ORIGIN_MISMATCH",n.HeartbeatFailed="HEARTBEAT_FAILED",n.ReconnectFailed="RECONNECT_FAILED",n.HandshakeFailed="HANDSHAKE_FAILED",n.ServiceWorkerUnavailable="SERVICE_WORKER_UNAVAILABLE"})(se||(se={}));class ne extends Error{constructor(e,t,s){super(e),Object.defineProperty(this,"code",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"details",{enumerable:1,configurable:1,writable:1,value:void 0}),this.name="ChannelError",this.code=t,this.details=s,Error.captureStackTrace&&Error.captureStackTrace(this,ne)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class As{constructor(){Object.defineProperty(this,"timeouts",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timer",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"nextDeadline",{enumerable:1,configurable:1,writable:1,value:1/0}),Object.defineProperty(this,"destroyed",{enumerable:1,configurable:1,writable:1,value:0})}add(e,t,s){if(this.destroyed)return;const r=Date.now()+t;this.timeouts.set(e,{deadline:r,callback:s}),r<this.nextDeadline&&this.reschedule(r)}remove(e){return this.timeouts.delete(e)}has(e){return this.timeouts.has(e)}get size(){return this.timeouts.size}reschedule(e){this.timer!==null&&clearTimeout(this.timer),this.nextDeadline=e;const t=Math.max(0,e-Date.now());this.timer=setTimeout(()=>this.processTimeouts(),t)}processTimeouts(){if(this.destroyed)return;const e=Date.now(),t=[];for(const[s,{deadline:r,callback:o}]of this.timeouts)r<=e&&(t.push(o),this.timeouts.delete(s));for(const s of t)try{s()}catch(r){console.error("[TimeoutManager] Callback error:",r)}this.scheduleNext()}scheduleNext(){if(this.timeouts.size===0)return this.nextDeadline=1/0,void(this.timer=null);let e=1/0;for(const{deadline:t}of this.timeouts.values())t<e&&(e=t);e<1/0&&this.reschedule(e)}destroy(){this.destroyed=1,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}}class vs{constructor(e,t=1e3){Object.defineProperty(this,"limit",{enumerable:1,configurable:1,writable:1,value:e}),Object.defineProperty(this,"windowMs",{enumerable:1,configurable:1,writable:1,value:t}),Object.defineProperty(this,"timestamps",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"head",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"tail",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"count",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"enabled",{enumerable:1,configurable:1,writable:1,value:void 0}),this.enabled=e>0,this.timestamps=this.enabled?new Array(e).fill(0):[]}tryAcquire(){if(!this.enabled)return 1;const e=Date.now(),t=e-this.windowMs;for(;this.count>0&&this.timestamps[this.head]<=t;)this.head=(this.head+1)%this.limit,this.count--;return this.count>=this.limit?0:(this.timestamps[this.tail]=e,this.tail=(this.tail+1)%this.limit,this.count++,1)}getCurrentCount(){if(!this.enabled)return 0;const e=Date.now()-this.windowMs;let t=0,s=this.head;for(let r=0;r<this.count;r++)this.timestamps[s]>e&&t++,s=(s+1)%this.limit;return t}getRemainingCapacity(){return this.enabled?Math.max(0,this.limit-this.getCurrentCount()):1/0}getTimeUntilAvailable(){if(!this.enabled||this.count<this.limit)return 0;const e=Date.now()-this.windowMs;let t=this.head;for(;t!==this.tail;){if(this.timestamps[t]>e)return this.timestamps[t]-e;t=(t+1)%this.limit}return 0}isLimited(){return this.enabled?this.getCurrentCount()>=this.limit:0}reset(){this.head=0,this.tail=0,this.count=0,this.enabled&&this.timestamps.fill(0)}getLimit(){return this.limit}getWindowMs(){return this.windowMs}isEnabled(){return this.enabled}}class Rs{constructor(){Object.defineProperty(this,"eventHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"eventsEnabled",{enumerable:1,configurable:1,writable:1,value:1})}on(e,t){let s=this.eventHandlers.get(e);return s||(s=new Set,this.eventHandlers.set(e,s)),s.add(t),()=>{s==null||s.delete(t),(s==null?void 0:s.size)===0&&this.eventHandlers.delete(e)}}once(e,t){const s=r=>{this.off(e,s),t(r)};return this.on(e,s)}off(e,t){const s=this.eventHandlers.get(e);if(!s)return 0;const r=s.delete(t);return s.size===0&&this.eventHandlers.delete(e),r}offAll(e){e?this.eventHandlers.delete(e):this.eventHandlers.clear()}emit(e,t){if(!this.eventsEnabled)return;const s=this.eventHandlers.get(e);if(s)for(const r of[...s])try{r(t)}catch(o){console.error(`[ChannelEventEmitter] Error in ${e} handler:`,o)}}hasListeners(e){const t=this.eventHandlers.get(e);return t!==void 0&&t.size>0}listenerCount(e){var t;return((t=this.eventHandlers.get(e))==null?void 0:t.size)??0}setEventsEnabled(e){this.eventsEnabled=e}destroyEventEmitter(){this.eventHandlers.clear(),this.eventsEnabled=0}}function bt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const X=n=>({valid:0,error:n});function Ms(n){if(!bt(n))return X("Message must be an object");const e=n,t="requestId"in e,s="cmdname"in e,r="msg"in e,o="ret"in e;return t||s||r?t&&typeof e.requestId!="string"?X("requestId must be a string"):s&&typeof e.cmdname!="string"?X("cmdname must be a string"):r&&typeof e.msg!="string"?X("msg must be a string"):!o||typeof(i=e.ret)=="number"&&Object.values($).includes(i)?"data"in e&&e.data!==void 0&&!bt(e.data)?X("data must be an object"):"_senderKey"in e&&e._senderKey!==void 0&&typeof e._senderKey!="string"?X("_senderKey must be a string"):!("time"in e)||e.time===void 0||typeof e.time=="number"&&Number.isFinite(e.time)?{valid:1,message:e}:X("time must be a finite number"):X("ret must be a valid ReturnCode"):X("Message must have requestId, cmdname, or msg field");var i}function Le(n){return"ret"in n&&typeof n.ret=="number"}function ks(n){return n.msg==="ready"}function Ps(n){return n._broadcast==1&&typeof n.cmdname=="string"}function Os(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const je=[],Y=[];function wt(n){Y.length>=200&&Y.shift(),Y.push(n)}function yt(n,e){for(let t=Y.length-1;t>=0;t--)if(Y[t].requestId===n&&Y[t].status==="pending"){Y[t].status=e,Y[t].duration=Date.now()-Y[t].timestamp;break}}class Is extends Rs{constructor(e){if(super(),Object.defineProperty(this,"baseKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"peerKey",{enumerable:1,configurable:1,writable:1,value:""}),Object.defineProperty(this,"reqTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"callbackMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"subscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"broadcastHandlers",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timeout",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"isReady",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isDestroyed",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"postTasks",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"bindOnMessage",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"console",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"maxMessageSize",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"timeoutManager",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"rateLimiter",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"strictValidation",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"requestCmdMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"isProcessingBatch",{enumerable:1,configurable:1,writable:1,value:0}),this.timeout=(e==null?void 0:e.timeout)??5e3,this.console=(e==null?void 0:e.log)??(typeof window<"u"?window.console:console),this.maxMessageSize=(e==null?void 0:e.maxMessageSize)??1048576,this.strictValidation=(e==null?void 0:e.strictValidation)??1,this.timeoutManager=new As,this.rateLimiter=new vs((e==null?void 0:e.rateLimit)??100,1e3),e==null?void 0:e.subscribeMap)for(const s in e.subscribeMap)this.subscribeMap.set(s,e.subscribeMap[s]);var t;this.bindOnMessage=this.onMessage.bind(this),t=this,je.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{wt({direction:"send",cmdname:s,requestId:r,status:"pending",timestamp:Date.now(),dataSummary:""})}),t.on("message:received",({cmdname:s,requestId:r,isResponse:o})=>{const i=s||"",a=r||"";o?yt(a,"ok"):wt({direction:"receive",cmdname:i,requestId:a,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{yt(r,"timeout")}),t.on("error",({context:s})=>{}),t.on("destroy",()=>{})}checkRateLimit(){if(!this.rateLimiter.isEnabled())return 1;if(!this.rateLimiter.tryAcquire()){const e=this.rateLimiter.getCurrentCount(),t=this.rateLimiter.getLimit();return this.log("warn","Rate limit exceeded:",e,"/",t,"messages per second"),this.emit("rate:limited",{currentCount:e,limit:t}),0}return 1}validateMessageSize(e){if(this.maxMessageSize<=0)return;const t=Os(e);if(t>this.maxMessageSize){const s=new ne(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,se.MessageSizeExceeded,{size:t,limit:this.maxMessageSize});throw this.emit("error",{error:s,context:"validateMessageSize"}),s}}init(){this.setupMessageListener(),this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})}log(e,...t){var s,r;(r=(s=this.console)==null?void 0:s[e])==null||r.call(s,`[${this.channelType}]: `,...t)}isFromPeer(e){return this.peerKey?e._senderKey&&e._senderKey!==this.peerKey?(this.log("log","Message from non-paired channel, ignored",e._senderKey,"expected:",this.peerKey),0):Le(e)&&e.requestId&&!e.requestId.startsWith(this.baseKey)?0:1:1}sendMessage(e,t){this.validateMessageSize(e),this.checkRateLimit()?(e.time=Date.now(),e._senderKey=this.baseKey,this.sendRawMessage(e,t)):this.log("warn","Message dropped due to rate limiting")}async onMessage(e){if(this.log("log","onMessage",e.data),!this.isValidSource(e))return;if(this.strictValidation){const o=Ms(e.data);if(!o.valid)return this.log("warn","Invalid message structure:",o.error),void this.emit("validation:failed",{reason:o.error,data:e.data})}const t=e.data;if(!t||!this.isFromPeer(t))return;this.emit("message:received",{cmdname:t.cmdname||"",requestId:t.requestId||"",isResponse:Le(t)});const{requestId:s,cmdname:r}=t;this.handleResponseMessage(t,s)||this.handleBroadcastMessage(t,r)||await this.handleSubscriptionMessage(t,s,r)||this.handleReadyMessage(t,s)||this.handleUnhandledMessage(t,s,r)}handleResponseMessage(e,t){const s=t?this.callbackMap.get(t):void 0;return s&&t?(this.timeoutManager.remove(t),this.requestCmdMap.delete(t),s.resolve(e),this.deleteCallback(t),1):0}handleBroadcastMessage(e,t){if(!Ps(e))return 0;const s=t?this.broadcastHandlers.get(t):void 0;if(s)try{s({cmdname:t,data:e.data})}catch(r){const o=r instanceof Error?r.message:String(r);this.emit("error",{error:r instanceof Error?r:new Error(o),context:`broadcast:${t}`})}return 1}async handleSubscriptionMessage(e,t,s){if(!s)return 0;const r=this.subscribeMap.get(s);if(!r)return 0;try{const o=await r(e);this.sendMessage({requestId:t,ret:$.Success,data:o})}catch(o){const i=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:$.ReceiverCallbackError,msg:i||"unknown error"}),this.emit("error",{error:o instanceof Error?o:new Error(i),context:`handler:${s}`})}return 1}handleReadyMessage(e,t){if(!ks(e))return 0;const{_senderKey:s}=e;return s&&!this.peerKey&&(this.peerKey=s,this.log("log","Point-to-point pairing established","self:",this.baseKey,"peer:",this.peerKey)),this.isReady=1,this.executePosts(),this.emit("ready",{peerKey:this.peerKey}),Le(e)||this.sendMessage({requestId:t,ret:$.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Le(e)&&(this.log("warn","No registered handler for:",s||t),this.sendMessage({requestId:t,ret:$.NoSubscribe}))}postMessage(e,t){try{this.sendMessage(e,t),this.emit("message:sent",{cmdname:e.cmdname||"",requestId:e.requestId||""})}catch(s){this.log("error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"postMessage"})}}publish(e,t,s){if(this.isDestroyed)return Promise.reject(new ne("Cannot publish: channel has been destroyed",se.ConnectionDestroyed,{cmdname:e}));const r=this.baseKey+ ++this.reqTime,o={requestId:r,cmdname:e,data:t};this.requestCmdMap.set(r,e);const i=new Promise((a,c)=>{this.callbackMap.set(r,{resolve:a,reject:c})});return this.log("log","publish",this.isReady,this.postTasks.size),this.isReady?this.doPublish(o,s):this.postTasks.set(r,{data:o,prm:i,options:s}),i}doPublish(e,t){const{requestId:s,cmdname:r}=e,o=(t==null?void 0:t.timeout)??this.timeout;this.timeoutManager.add(s,o,()=>{const i=this.callbackMap.get(s);if(i){const a={req:e,requestId:s,ret:$.TimeOut,time:Date.now(),msg:"timeout"};this.log("error","postmessage timeout",a),this.emit("timeout",{requestId:s,cmdname:r,timeoutMs:o}),i.resolve(a),this.deleteCallback(s),this.requestCmdMap.delete(s)}}),this.postMessage(e,t==null?void 0:t.transferables)}deleteCallback(e){this.callbackMap.delete(e),this.postTasks.delete(e),this.timeoutManager.remove(e)}executePosts(){this.postTasks.size===0||this.isProcessingBatch||(this.isProcessingBatch=1,queueMicrotask(()=>{this.processBatch(),this.isProcessingBatch=0}))}processBatch(){const e=Array.from(this.postTasks.entries());for(const[t,s]of e)this.postTasks.has(t)&&(t.startsWith("_broadcast_")?(this.doBroadcast(s.data,s.options),this.postTasks.delete(t)):this.doPublish(s.data,s.options))}call(e,t,s){return this.publish(e,t,s)}subscribe(e,t){return this.subscribeMap.has(e)&&this.log("warn",`${e} has been subscribed`),this.subscribeMap.set(e,t),this}unSubscribe(e){return this.subscribeMap.delete(e),this}subscribeOnce(e,t){return this.subscribe(e,async s=>(this.unSubscribe(e),t(s)))}broadcast(e,t,s){if(this.isDestroyed)return void this.log("warn","Cannot broadcast: channel has been destroyed");const r={cmdname:e,data:t,time:Date.now(),_broadcast:1};if(this.log("log","broadcast",e,this.isReady),this.isReady)this.doBroadcast(r,s);else{const o=`_broadcast_${Date.now()}_${Math.random()}`;this.postTasks.set(o,{data:r,prm:Promise.resolve({}),options:s})}}doBroadcast(e,t){try{this.sendMessage(e,t==null?void 0:t.transferables),this.emit("broadcast:sent",{cmdname:e.cmdname})}catch(s){this.log("error","broadcast error",s,e),this.emit("error",{error:s instanceof Error?s:new Error(String(s)),context:"broadcast"})}}onBroadcast(e,t){return this.broadcastHandlers.has(e)&&this.log("warn",`Broadcast handler for ${e} already registered, replacing`),this.broadcastHandlers.set(e,t),this}offBroadcast(e){return this.broadcastHandlers.delete(e),this}getPeerKey(){return this.peerKey}getRateLimitStats(){return{current:this.rateLimiter.getCurrentCount(),limit:this.rateLimiter.getLimit(),remaining:this.rateLimiter.getRemainingCapacity()}}getPendingCount(){return this.callbackMap.size}destroy(){if(this.isDestroyed)return;this.isDestroyed=1,this.emit("destroy",{reason:"explicit"}),(function(t){const s=je.findIndex(r=>r.deref()===t);s!==-1&&je.splice(s,1)})(this);const e=new ne("Channel has been destroyed",se.ConnectionDestroyed);for(const[t,s]of this.callbackMap)try{s.reject({ret:$.SendCallbackError,msg:e.message})}catch(r){this.log("warn","Error rejecting pending request:",t,r)}this.removeMessageListener(),this.subscribeMap.clear(),this.broadcastHandlers.clear(),this.postTasks.clear(),this.callbackMap.clear(),this.requestCmdMap.clear(),this.timeoutManager.destroy(),this.rateLimiter.reset(),this.destroyEventEmitter(),this.isReady=0,this.peerKey=""}}class V{constructor(){Object.defineProperty(this,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"initialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"options",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"channelFactory",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:e=>{const t=e.source,s=t==null?void 0:t.id;if(!s)return;const r=this.channelsByClientId.get(s);r?r.handleMessage(e):this.unknownClientCallback&&this.unknownClientCallback(s,e)}})}static getInstance(){return V.instance||(V.instance=new V),V.instance}static resetInstance(){V.instance&&(V.instance.shutdown(),V.instance=null)}setup(e,t){if(this.initialized)return void console.warn("[ServiceWorkerHub] Already initialized");this.options=e,this.channelFactory=t,this.initialized=1,this.registerBuiltInHandlers(),this.setupLifecycleEvents();const s=e.cleanupInterval??3e4;s>0&&(this.cleanupIntervalId=setInterval(()=>this.cleanupInactiveClients(),s))}shutdown(){this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0);for(const e of this.channelsByClientId.values())try{e.destroy()}catch{}this.channelsByClientId.clear(),this.clientMeta.clear(),this.globalSubscribeMap.clear(),this.initialized=0}isInitialized(){return this.initialized}getOptions(){return this.options}enableGlobalRouting(e){this.unknownClientCallback=e??null,this.globalListenerSetup||(self.addEventListener("message",this.globalMessageHandler),this.globalListenerSetup=1)}disableGlobalRouting(){this.globalListenerSetup&&(self.removeEventListener("message",this.globalMessageHandler),this.globalListenerSetup=0)}isGlobalRoutingEnabled(){return this.globalListenerSetup}registerChannel(e,t){this.channelsByClientId.set(e,t),this.applyGlobalHandlersToChannel(t,e)}unregisterChannel(e){var t,s;this.channelsByClientId.delete(e),this.clientMeta.delete(e),(s=(t=this.options).onClientDisconnect)==null||s.call(t,e)}getChannel(e){return this.channelsByClientId.get(e)}hasChannel(e){return this.channelsByClientId.has(e)}getChannelCount(){return this.channelsByClientId.size}createChannelForClient(e){if(!this.channelFactory)return console.warn("[ServiceWorkerHub] No channel factory configured"),null;const t=this.channelFactory(e);return this.registerChannel(e,t),t}registerClientMeta(e,t){var r,o;const s={clientId:e,appType:t.appType,appName:t.appName,connectedAt:new Date().toISOString()};return this.clientMeta.set(e,s),(o=(r=this.options).onClientConnect)==null||o.call(r,e,s),s}getClientMeta(e){return this.clientMeta.get(e)}getAllClientMeta(){return new Map(this.clientMeta)}getClientsByType(e){const t=[];for(const s of this.clientMeta.values())s.appType===e&&t.push(s);return t}subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerHub] Handler name '${e}' uses reserved prefix '__'.`),this.globalSubscribeMap.set(e,t);for(const[s,r]of this.channelsByClientId)this.applyHandlerToChannel(r,s,e,t)}unsubscribeGlobal(e){this.globalSubscribeMap.delete(e);for(const t of this.channelsByClientId.values())t.unSubscribe(e)}applyGlobalHandlersToChannel(e,t){for(const[s,r]of this.globalSubscribeMap)this.applyHandlerToChannel(e,t,s,r)}applyHandlerToChannel(e,t,s,r){e.subscribe(s,async o=>{const i=this.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:i})})}registerBuiltInHandlers(){this.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>(this.registerClientMeta(t,{appType:e.appType,appName:e.appName}),{success:1,clientId:t,totalClients:this.clientMeta.size})),this.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:this.channelsByClientId.size}))}setupLifecycleEvents(){self.addEventListener("install",e=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await this.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:this.options.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerHub] Error notifying clients:",e)}}async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o,i]of this.channelsByClientId)r.has(o)||(i.destroy(),this.channelsByClientId.delete(o),this.clientMeta.delete(o),(t=(e=this.options).onClientDisconnect)==null||t.call(e,o))}catch(s){console.error("[ServiceWorkerHub] Cleanup error:",s)}}async broadcastToAll(e,t,s){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const r=await self.clients.matchAll();let o=0;for(const i of r){if(s&&i.id===s)continue;const a=this.channelsByClientId.get(i.id);if(a)try{a.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,c)}}return o}catch(r){return console.error("[ServiceWorkerHub] broadcastToAll error:",r),0}}async broadcastToType(e,t,s,r){if(!this.initialized)return console.warn("[ServiceWorkerHub] Not initialized"),0;try{const o=await self.clients.matchAll();let i=0;for(const a of o){if(r&&a.id===r)continue;const c=this.clientMeta.get(a.id);if(!c||c.appType!==e)continue;const l=this.channelsByClientId.get(a.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),i++}catch(u){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",a.id,u)}}return i}catch(o){return console.error("[ServiceWorkerHub] broadcastToType error:",o),0}}}Object.defineProperty(V,"instance",{enumerable:1,configurable:1,writable:1,value:null});class g extends Is{static enableGlobalRouting(e){g.useGlobalRouting=1,g.unknownClientCallback=e??null,g.globalListenerSetup||(self.addEventListener("message",g.globalMessageHandler),g.globalListenerSetup=1)}static disableGlobalRouting(){g.useGlobalRouting=0,g.globalListenerSetup&&(self.removeEventListener("message",g.globalMessageHandler),g.globalListenerSetup=0)}static setupHub(e={}){if(g.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");g.hubOptions=e,g.hubInitialized=1,V.getInstance().setup(e,s=>g.createFromWorker(s)),g.enableGlobalRouting((s,r)=>{const o=g.createFromWorker(s);g.setupChannelHandlers(o,s),o.handleMessage(r)}),g.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(g.cleanupIntervalId=setInterval(()=>g.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){g.globalSubscribeMap.set("__register__",({data:e,clientId:t})=>{var r,o;const s={clientId:t,appType:e.appType,appName:e.appName,connectedAt:new Date().toISOString()};return g.clientMeta.set(t,s),(o=(r=g.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:g.clientMeta.size}}),g.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:g.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of g.globalSubscribeMap)e.subscribe(s,async o=>{const i=g.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:i})})}static setupLifecycleEvents(){self.addEventListener("install",()=>{typeof self.skipWaiting=="function"&&self.skipWaiting()}),self.addEventListener("activate",e=>{const t=(async()=>{var s;typeof((s=self.clients)==null?void 0:s.claim)=="function"&&await self.clients.claim(),await g.notifyAllClientsSwActivated()})();typeof e.waitUntil=="function"&&e.waitUntil(t)})}static async notifyAllClientsSwActivated(){try{const e=await self.clients.matchAll();for(const t of e)t.postMessage({cmdname:"__sw-activated__",data:{version:g.hubOptions.version},_broadcast:1})}catch(e){console.error("[ServiceWorkerChannel] Error notifying clients:",e)}}static async cleanupInactiveClients(){var e,t;try{const s=await self.clients.matchAll(),r=new Set(s.map(o=>o.id));for(const[o]of g.channelsByClientId)if(!r.has(o)){const i=g.channelsByClientId.get(o);i&&i.destroy(),g.clientMeta.delete(o),(t=(e=g.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!g.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const r=await self.clients.matchAll();let o=0;for(const i of r){if(s&&i.id===s)continue;const a=g.channelsByClientId.get(i.id);if(a)try{a.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,c)}}return o}catch(r){return console.error("[ServiceWorkerChannel] broadcastToAll error:",r),0}}static async broadcastToType(e,t,s,r){if(!g.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const o=await self.clients.matchAll();let i=0;for(const a of o){if(r&&a.id===r)continue;const c=g.clientMeta.get(a.id);if(!c||c.appType!==e)continue;const l=g.channelsByClientId.get(a.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),i++}catch(u){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",a.id,u)}}return i}catch(o){return console.error("[ServiceWorkerChannel] broadcastToType error:",o),0}}static getClientInfo(e){return g.clientMeta.get(e)}static getAllClients(){return new Map(g.clientMeta)}static getClientsByType(e){const t=[];for(const s of g.clientMeta.values())s.appType===e&&t.push(s);return t}static subscribeGlobal(e,t){e.startsWith("__")&&console.warn(`[ServiceWorkerChannel] Handler name '${e}' uses reserved prefix '__'. This may conflict with internal handlers.`),g.globalSubscribeMap.set(e,t);for(const[s,r]of g.channelsByClientId)r.subscribe(e,async o=>{const i=g.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:i})})}static unsubscribeGlobal(e){g.globalSubscribeMap.delete(e);for(const t of g.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&g.useGlobalRouting&&g.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&g.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return g.channelsByClientId.get(e)}static hasChannel(e){return g.channelsByClientId.has(e)}static getChannelCount(){return g.channelsByClientId.size}handleMessage(e){return this.onMessage(e)}constructor(e,t){if(super(t),Object.defineProperty(this,"channelType",{enumerable:1,configurable:1,writable:1,value:"ServiceWorkerChannel"}),Object.defineProperty(this,"isWorkerSide",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"worker",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"clientId",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"swContainer",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"l",{enumerable:1,configurable:1,writable:1,value:"connecting"}),Object.defineProperty(this,"lastSuccessfulMessageTime",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"heartbeatIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"missedHeartbeatCount",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"isReconnecting",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"reconnectAttempt",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"connectionOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(this,"boundControllerChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"boundStateChangeHandler",{enumerable:1,configurable:1,writable:1,value:null}),this.isWorkerSide=(t==null?void 0:t.isWorkerSide)??0,this.isWorkerSide){if(typeof e!="string")throw new Error("Service Worker 端必须传入 clientId 字符串");this.clientId=e,this.baseKey=mt("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=mt("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(g.useGlobalRouting)return void(g.globalListenerSetup||(self.addEventListener("message",g.globalMessageHandler),g.globalListenerSetup=1));self.addEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.addEventListener("message",this.bindOnMessage)}removeMessageListener(){var e;if(this.unregisterFromGlobalRouter(),this.isWorkerSide){if(g.useGlobalRouting)return;self.removeEventListener("message",this.bindOnMessage)}else(e=this.swContainer)==null||e.removeEventListener("message",this.bindOnMessage)}sendRawMessage(e,t){var s,r;try{const o=Ds(e);this.isWorkerSide?this.sendToClient(o,t):t&&t.length>0?(s=this.worker)==null||s.postMessage(o,t):(r=this.worker)==null||r.postMessage(o)}catch(o){this.log("error","sendMessage error",o,e)}}async sendToClient(e,t){const s=this.clientId;if(s)try{const r=await self.clients.get(s);r?t&&t.length>0?r.postMessage(e,t):r.postMessage(e):this.log("warn","Client not found:",s)}catch(r){this.log("error","sendToClient error",r)}else this.log("error","No clientId available")}isValidSource(e){if(this.isWorkerSide){const t=e.source;return(t==null?void 0:t.id)===this.clientId}return 1}log(e,...t){var r,o;const s=this.isWorkerSide?"worker":"page";(o=(r=this.console)==null?void 0:r[e])==null||o.call(r,`[ServiceWorkerChannel](${s}): `,...t)}getClientId(){return this.clientId}isWorkerAvailable(){var e;return this.isWorkerSide||((e=this.worker)==null?void 0:e.state)==="activated"}async refreshWorker(){if(this.isWorkerSide)throw new Error("refreshWorker() can only be called on page side");const e=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;e?(this.worker=e,this.peerKey="",this.isReady=0,this.sendMessage({requestId:this.baseKey+this.reqTime,msg:"ready",_senderKey:this.baseKey})):console.warn("[ServiceWorkerChannel] No active Service Worker found during refresh")}get connectionState(){return this.l}get isConnected(){return this.l==="connected"}updateLastMessageTime(){this.lastSuccessfulMessageTime=Date.now()}setConnectionState(e,t){if(this.l===e)return;const s=this.l;switch(this.l=e,this.log("log",`Connection state: ${s} -> ${e}`),e){case"connected":this.missedHeartbeatCount=0,this.reconnectAttempt=0,this.emit("connected",{isReconnect:s==="reconnecting"});break;case"disconnected":this.emit("disconnected",{reason:(t==null?void 0:t.reason)||"error",error:t==null?void 0:t.error});break;case"reconnecting":this.emit("reconnecting",{attempt:(t==null?void 0:t.attempt)||this.reconnectAttempt,maxAttempts:this.connectionOptions.maxReconnectAttempts||5,nextRetryIn:(t==null?void 0:t.nextRetryIn)||0})}}startHeartbeat(){if(this.isWorkerSide)return;const e=this.connectionOptions.heartbeatInterval??3e4;e<=0||(this.stopHeartbeat(),this.heartbeatIntervalId=setInterval(()=>{this.performHeartbeat()},e),this.log("log",`Heartbeat started with interval ${e}ms`))}stopHeartbeat(){this.heartbeatIntervalId&&(clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)}async performHeartbeat(){const e=this.connectionOptions.heartbeatInterval??3e4;if(this.connectionOptions.smartHeartbeat!=0&&this.lastSuccessfulMessageTime>0&&Date.now()-this.lastSuccessfulMessageTime<e)return this.missedHeartbeatCount=0,void this.emit("heartbeat",{success:1,missedCount:0});const t=this.connectionOptions.heartbeatTimeout??5e3,s=Date.now();try{if((await this.publish("__ping__",{},{timeout:t})).ret===$.Success){const r=Date.now()-s;this.missedHeartbeatCount=0,this.updateLastMessageTime(),this.emit("heartbeat",{success:1,latencyMs:r,missedCount:0}),this.l==="reconnecting"&&this.setConnectionState("connected")}else this.handleHeartbeatFailure()}catch(r){this.handleHeartbeatFailure(r instanceof Error?r:void 0)}}handleHeartbeatFailure(e){this.missedHeartbeatCount++;const t=this.connectionOptions.maxMissedHeartbeats??3;this.emit("heartbeat",{success:0,missedCount:this.missedHeartbeatCount}),this.log("warn",`Heartbeat failed (${this.missedHeartbeatCount}/${t})`),this.missedHeartbeatCount>=t&&(this.log("error","Connection lost: heartbeat threshold exceeded"),this.setConnectionState("disconnected",{reason:"heartbeat_failed",error:e||new ne("Heartbeat detection failed",se.HeartbeatFailed,{missedCount:this.missedHeartbeatCount})}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}async attemptReconnect(){if(this.isReconnecting||this.isDestroyed)return;const e=this.connectionOptions.maxReconnectAttempts??5;if(e<=0)return;this.isReconnecting=1,this.reconnectAttempt=0;const t=this.connectionOptions.reconnectBaseDelay??1e3,s=this.connectionOptions.maxReconnectDelay??3e4;for(;this.reconnectAttempt<e&&!this.isDestroyed;){this.reconnectAttempt++;const r=Math.min(t*Math.pow(2,this.reconnectAttempt-1),s);if(this.setConnectionState("reconnecting",{attempt:this.reconnectAttempt,nextRetryIn:r}),await this.delay(r),this.isDestroyed)break;try{return await this.refreshWorker(),this.isReady||await this.waitForReady(this.connectionOptions.handshakeTimeout??1e4),(this.connectionOptions.appType||this.connectionOptions.appName)&&await this.publish("__register__",{appType:this.connectionOptions.appType,appName:this.connectionOptions.appName}),this.missedHeartbeatCount=0,this.setConnectionState("connected"),this.updateLastMessageTime(),this.isReconnecting=0,void this.log("log","Reconnection successful")}catch(o){this.log("warn",`Reconnection attempt ${this.reconnectAttempt} failed:`,o)}}this.isReconnecting=0,this.emit("reconnect:failed",{attempts:this.reconnectAttempt,lastError:new ne("All reconnection attempts failed",se.ReconnectFailed,{attempts:this.reconnectAttempt})})}waitForReady(e){return new Promise((t,s)=>{if(this.isReady)return void t();const r=setTimeout(()=>{this.off("ready",o),s(new ne("Handshake timeout",se.HandshakeFailed))},e),o=()=>{clearTimeout(r),t()};this.once("ready",o)})}delay(e){return new Promise(t=>setTimeout(t,e))}setupSwLifecycleListeners(){this.isWorkerSide||typeof navigator>"u"||(this.boundControllerChangeHandler=()=>{this.log("log","Service Worker controller changed"),this.handleControllerChange()},navigator.serviceWorker.addEventListener("controllerchange",this.boundControllerChangeHandler),this.worker&&(this.boundStateChangeHandler=()=>{var e;this.handleStateChange((e=this.worker)==null?void 0:e.state)},this.worker.addEventListener("statechange",this.boundStateChangeHandler)))}removeSwLifecycleListeners(){var e;this.boundControllerChangeHandler&&((e=navigator.serviceWorker)==null||e.removeEventListener("controllerchange",this.boundControllerChangeHandler),this.boundControllerChangeHandler=null),this.boundStateChangeHandler&&this.worker&&(this.worker.removeEventListener("statechange",this.boundStateChangeHandler),this.boundStateChangeHandler=null)}handleControllerChange(){this.l==="connected"&&this.setConnectionState("disconnected",{reason:"controller_changed"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect()}handleStateChange(e){this.log("log","Service Worker state changed:",e),e==="redundant"&&(this.l==="connected"&&this.setConnectionState("disconnected",{reason:"sw_terminated"}),this.connectionOptions.autoReconnect!=0&&this.attemptReconnect())}static async createFromPage(e){if(!("serviceWorker"in navigator))throw new Error("Service Worker is not supported in this browser");if(e!=null&&e.swUrl)try{const l={};e.swScope&&(l.scope=e.swScope),await navigator.serviceWorker.register(e.swUrl,l)}catch(l){throw console.error("[ServiceWorkerChannel] Failed to register Service Worker:",l),l}const t=(await navigator.serviceWorker.ready).active||navigator.serviceWorker.controller;if(!t)throw new Error("No active Service Worker found");const s=new g(t,e);s.connectionOptions=e||{};const r=(e==null?void 0:e.appType)||(e==null?void 0:e.appName);let o=0,i=0;const a=async()=>{if(!i){i=1;try{await s.publish("__register__",{appType:e==null?void 0:e.appType,appName:e==null?void 0:e.appName}),o=1,s.updateLastMessageTime()}catch(l){console.warn("[ServiceWorkerChannel] Auto-registration failed:",l)}finally{i=0}}},c=()=>{s.setConnectionState("connected"),s.updateLastMessageTime(),s.startHeartbeat(),s.setupSwLifecycleListeners()};return r?s.isReady?(a(),c()):s.once("ready",()=>{a(),c()}):s.isReady?c():s.once("ready",c),(e==null?void 0:e.autoReconnect)!=0&&s.onBroadcast("__sw-activated__",async({data:l})=>{s.emit("sw-activated",{version:l==null?void 0:l.version}),s.setConnectionState("disconnected",{reason:"controller_changed"}),r&&(await s.refreshWorker(),o=0,await a()),s.setConnectionState("connected"),s.updateLastMessageTime()}),s.on("message:received",({isResponse:l})=>{l&&s.updateLastMessageTime()}),s}static createFromWorker(e,t){return new g(e,{...t,isWorkerSide:1})}static createFromEvent(e,t){const s=e.source;if(!(s!=null&&s.id))throw new Error("Invalid message event: no client source");return g.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(g,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(g,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(g,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(g,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(g,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(g,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(g,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(g,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(g,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(g,"globalMessageHandler",{enumerable:1,configurable:1,writable:1,value:n=>{const e=n.source,t=e==null?void 0:e.id;if(!t)return;const s=g.channelsByClientId.get(t);s?s.handleMessage(n):g.unknownClientCallback&&g.unknownClientCallback(t,n)}});function Ws(n,e,t){return Promise.race([n,new Promise(s=>setTimeout(()=>s(t),e))])}const S={THUMBNAIL_GENERATE:"thumbnail:generate",CRASH_SNAPSHOT:"crash:snapshot",CRASH_HEARTBEAT:"crash:heartbeat",CONSOLE_REPORT:"console:report",DEBUG_GET_STATUS:"debug:getStatus",DEBUG_ENABLE:"debug:enable",DEBUG_DISABLE:"debug:disable",DEBUG_GET_LOGS:"debug:getLogs",DEBUG_CLEAR_LOGS:"debug:clearLogs",DEBUG_GET_CONSOLE_LOGS:"debug:getConsoleLogs",DEBUG_CLEAR_CONSOLE_LOGS:"debug:clearConsoleLogs",DEBUG_GET_POSTMESSAGE_LOGS:"debug:getPostMessageLogs",DEBUG_CLEAR_POSTMESSAGE_LOGS:"debug:clearPostMessageLogs",DEBUG_GET_CRASH_SNAPSHOTS:"debug:getCrashSnapshots",DEBUG_CLEAR_CRASH_SNAPSHOTS:"debug:clearCrashSnapshots",DEBUG_GET_LLM_API_LOGS:"debug:getLLMApiLogs",DEBUG_GET_LLM_API_LOG_BY_ID:"debug:getLLMApiLogById",DEBUG_CLEAR_LLM_API_LOGS:"debug:clearLLMApiLogs",DEBUG_DELETE_LLM_API_LOGS:"debug:deleteLLMApiLogs",DEBUG_GET_CACHE_ENTRIES:"debug:getCacheEntries",DEBUG_GET_CACHE_STATS:"debug:getCacheStats",DEBUG_EXPORT_LOGS:"debug:exportLogs",CDN_GET_STATUS:"cdn:getStatus",CDN_RESET_STATUS:"cdn:resetStatus",CDN_HEALTH_CHECK:"cdn:healthCheck",UPGRADE_GET_STATUS:"upgrade:getStatus",UPGRADE_FORCE:"upgrade:force",CACHE_DELETE:"cache:delete",PING:"ping"},I={CACHE_IMAGE_CACHED:"cache:imageCached",CACHE_DELETED:"cache:deleted",CACHE_QUOTA_WARNING:"cache:quotaWarning",SW_NEW_VERSION_READY:"sw:newVersionReady",SW_ACTIVATED:"sw:activated",SW_UPDATED:"sw:updated",CONSOLE_LOG:"console:log",DEBUG_LOG:"debug:log",DEBUG_LLM_LOG:"debug:llmLog",DEBUG_STATUS_CHANGED:"debug:statusChanged",DEBUG_NEW_CRASH_SNAPSHOT:"debug:newCrashSnapshot",POSTMESSAGE_LOG_BATCH:"postmessage:logBatch"},he=class he{constructor(e){this.channels=new Map,this.onDebugClientCountChanged=null,this.postMessageLogBuffer=[],this.postMessageLogTimer=null,this.POSTMESSAGE_LOG_BATCH_INTERVAL=500,this.sw=e,this.channels.clear(),g.enableGlobalRouting((t,s)=>{var o;this.ensureChannel(t);const r=(o=this.channels.get(t))==null?void 0:o.channel;r&&r.handleMessage(s)}),setInterval(()=>{this.cleanupDisconnectedClients().catch(()=>{}),this.cleanupStalePendingRequests().catch(()=>{})},6e4)}async cleanupStalePendingRequests(){try{const e=await gs.cleanupStalePendingToolRequests();e>0&&console.log(`[ChannelManager] Cleaned up ${e} stale pending tool requests`)}catch(e){console.warn("[ChannelManager] Failed to cleanup stale pending requests:",e)}}setDebugClientCountChangedCallback(e){this.onDebugClientCountChanged=e}getDebugClientCount(){let e=0;for(const t of this.channels.values())t.isDebugClient&&e++;return e}async isDebugClient(e){try{const t=await this.sw.clients.get(e);if(t&&t.url)return t.url.includes("sw-debug")}catch{}return!1}static getInstance(e){return he.instance||(he.instance=new he(e)),he.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:g.createFromWorker(e,{timeout:12e4,subscribeMap:this.createSubscribeMap(e),log:{log:()=>{},warn:()=>{},error:()=>{}}}),clientId:e,createdAt:Date.now(),isDebugClient:!1},this.channels.set(e,t),this.checkAndUpdateDebugClient(e)),t.channel}async checkAndUpdateDebugClient(e){var r;const t=await this.isDebugClient(e),s=this.channels.get(e);s&&t&&(s.isDebugClient=!0,(r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}hasAnyClientChannel(){return this.channels.size>0}unwrapRpcData(e){return e&&typeof e=="object"&&"cmdname"in e?e.data:e}broadcastPostMessageLog(e){if(!e)return;const s=Te().find(r=>r.id===e);s&&this.sendPostMessageLog(s)}wrapRpcHandler(e,t,s){return async r=>{var l;const o=this.unwrapRpcData(r),i=Date.now(),a=r==null?void 0:r.requestId,c=He()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=xe(`RPC:${e}`,{params:o,requestId:a},t);this.broadcastPostMessageLog(u)}try{const u=await s(o);try{JSON.stringify(u)}catch(h){throw console.error(`[SW wrapRpcHandler] ${e} result serialization failed:`,h),new Error(`Result serialization failed: ${h}`)}if(c&&a){const h=Ge(a,{result:u},Date.now()-i);h&&this.broadcastPostMessageLog(h)}return u}catch(u){if(console.error(`[SW wrapRpcHandler] ${e} error:`,u),c&&a){const h=Ge(a,null,Date.now()-i,String(u));h&&this.broadcastPostMessageLog(h)}throw u}}}createSubscribeMap(e){return{[S.THUMBNAIL_GENERATE]:this.wrapRpcHandler(S.THUMBNAIL_GENERATE,e,t=>this.handleThumbnailGenerate(t)),[S.CRASH_SNAPSHOT]:async t=>{const s=this.unwrapRpcData(t);return this.handleCrashSnapshot(s)},[S.CRASH_HEARTBEAT]:async t=>{const s=this.unwrapRpcData(t);return this.handleHeartbeat(s)},[S.CONSOLE_REPORT]:async t=>{const s=this.unwrapRpcData(t);return this.handleConsoleReport(s)},[S.DEBUG_GET_STATUS]:async()=>this.handleDebugGetStatus(),[S.DEBUG_ENABLE]:async()=>this.handleDebugEnable(),[S.DEBUG_DISABLE]:async()=>this.handleDebugDisable(),[S.DEBUG_GET_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLogs(s)},[S.DEBUG_CLEAR_LOGS]:async()=>this.handleDebugClearLogs(),[S.DEBUG_GET_CONSOLE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetConsoleLogs(s)},[S.DEBUG_CLEAR_CONSOLE_LOGS]:async()=>this.handleDebugClearConsoleLogs(),[S.DEBUG_GET_POSTMESSAGE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetPostMessageLogs(s)},[S.DEBUG_CLEAR_POSTMESSAGE_LOGS]:async()=>this.handleDebugClearPostMessageLogs(),[S.DEBUG_GET_CRASH_SNAPSHOTS]:async()=>this.handleDebugGetCrashSnapshots(),[S.DEBUG_CLEAR_CRASH_SNAPSHOTS]:async()=>this.handleDebugClearCrashSnapshots(),[S.DEBUG_GET_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogs(s)},[S.DEBUG_GET_LLM_API_LOG_BY_ID]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogById(s==null?void 0:s.logId)},[S.DEBUG_CLEAR_LLM_API_LOGS]:async()=>this.handleDebugClearLLMApiLogs(),[S.DEBUG_DELETE_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugDeleteLLMApiLogs(s)},[S.DEBUG_GET_CACHE_ENTRIES]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetCacheEntries(s)},[S.DEBUG_GET_CACHE_STATS]:async()=>this.handleDebugGetCacheStats(),[S.DEBUG_EXPORT_LOGS]:async()=>this.handleDebugExportLogs(),[S.CDN_GET_STATUS]:async()=>this.handleCDNGetStatus(),[S.CDN_RESET_STATUS]:async()=>this.handleCDNResetStatus(),[S.CDN_HEALTH_CHECK]:async()=>this.handleCDNHealthCheck(),[S.UPGRADE_GET_STATUS]:async()=>this.handleUpgradeGetStatus(),[S.UPGRADE_FORCE]:async()=>this.handleUpgradeForce(),[S.CACHE_DELETE]:async t=>{const s=this.unwrapRpcData(t);return this.handleCacheDelete(s)},[S.PING]:async()=>this.handlePing()}}async handleThumbnailGenerate(e){try{const{url:t,mediaType:s,blob:r,mimeType:o}=e,{generateThumbnailAsync:i}=await Promise.resolve().then(()=>x),a=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return i(a,t,s),{success:!0}}catch(t){return console.error("[SWChannelManager] Thumbnail generation failed:",t),{success:!1,error:t.message}}}async handleCrashSnapshot(e){try{const{saveCrashSnapshot:t}=await Promise.resolve().then(()=>D);return await t(e.snapshot),{success:!0}}catch(t){return console.error("[SWChannelManager] Crash snapshot save failed:",t),{success:!1,error:t.message}}}async handleHeartbeat(e){return{success:!0}}serializeLogArg(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)}async handleConsoleReport(e){try{const{addConsoleLog:t}=await Promise.resolve().then(()=>D),s=e.logArgs??[],o=(Array.isArray(s)?s.map(i=>this.serializeLogArg(i)):[this.serializeLogArg(s)]).join(" ");return t({logLevel:e.logLevel,logMessage:o||"-"}),{success:!0}}catch(t){return{success:!1,error:t.message}}}async handleDebugGetStatus(){try{const{getDebugStatus:e,getCacheStats:t}=await Promise.resolve().then(()=>D),s=e(),r=await t();return{...s,enabled:s.debugModeEnabled,cacheStats:r}}catch{return{debugModeEnabled:!1}}}async handleDebugEnable(){try{const{enableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>D);await e();const s=t();return this.sendDebugStatusChanged(!0),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugDisable(){try{const{disableDebugMode:e,getDebugStatus:t}=await Promise.resolve().then(()=>D);await e();const s=t();return this.sendDebugStatusChanged(!1),{success:!0,status:s}}catch{return{success:!1}}}async handleDebugGetLogs(e){try{const{getDebugLogs:t,getInternalFetchLogs:s}=await Promise.resolve().then(()=>D),{limit:r=100,offset:o=0,filter:i}=e||{},a=s().map(f=>({...f,type:"fetch"})),c=t(),l=new Map;for(const f of c)l.set(f.id,f);for(const f of a)l.set(f.id,f);let u=Array.from(l.values()).sort((f,m)=>m.timestamp-f.timestamp);return i&&(i.type&&(u=u.filter(f=>f.type===i.type)),i.status&&(u=u.filter(f=>f.status===i.status))),{logs:u.slice(o,o+r),total:u.length,offset:o,limit:r}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||100}}}async handleDebugClearLogs(){try{const{clearDebugLogs:e}=await Promise.resolve().then(()=>D);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>D),{limit:s=500,offset:r=0,filter:o}=e||{};let i=await t();if(o&&(o.logLevel&&(i=i.filter(c=>c.logLevel===o.logLevel)),o.search)){const c=o.search.toLowerCase();i=i.filter(l=>{var u,h;return((u=l.logMessage)==null?void 0:u.toLowerCase().includes(c))||((h=l.logStack)==null?void 0:h.toLowerCase().includes(c))})}return{logs:i.slice(r,r+s),total:i.length,offset:r,limit:s}}catch(t){return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||500,error:String(t)}}}async handleDebugClearConsoleLogs(){try{const{clearConsoleLogs:e,clearAllConsoleLogs:t}=await Promise.resolve().then(()=>D);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>Ue),{limit:r=200,offset:o=0,filter:i}=e||{};let a=t();if(i&&(i.direction&&(a=a.filter(l=>l.direction===i.direction)),i.messageType)){const l=i.messageType.toLowerCase();a=a.filter(u=>{var h;return(h=u.messageType)==null?void 0:h.toLowerCase().includes(l)})}return{logs:a.slice(o,o+r),total:a.length,offset:o,limit:r,stats:s()}}catch{return{logs:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||200}}}async handleDebugClearPostMessageLogs(){try{const{clearLogs:e}=await Promise.resolve().then(()=>Ue);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>D),t=await e();return{snapshots:t,total:t.length}}catch(e){return{snapshots:[],total:0,error:String(e)}}}async handleDebugClearCrashSnapshots(){try{const{clearCrashSnapshots:e}=await Promise.resolve().then(()=>D);return await e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetLLMApiLogs(e){try{const t=typeof(e==null?void 0:e.page)=="number"?e.page:Number(e==null?void 0:e.page)||1,s=typeof(e==null?void 0:e.pageSize)=="number"?e.pageSize:Number(e==null?void 0:e.pageSize)||20,r={taskType:typeof(e==null?void 0:e.taskType)=="string"?e.taskType:void 0,status:typeof(e==null?void 0:e.status)=="string"?e.status:void 0},{getLLMApiLogsPaginated:o}=await Promise.resolve().then(()=>ue);return await o(t,s,r)}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogs error:",t),{logs:[],total:0,page:1,pageSize:20,totalPages:0,error:String(t)}}}async handleDebugGetLLMApiLogById(e){try{if(!e)return{log:null,error:"Missing logId"};const{getLLMApiLogById:t}=await Promise.resolve().then(()=>ue);return{log:await t(e)}}catch(t){return console.error("[SWChannelManager] handleDebugGetLLMApiLogById error:",t),{log:null,error:String(t)}}}async handleDebugClearLLMApiLogs(){try{const{clearAllLLMApiLogs:e}=await Promise.resolve().then(()=>ue);return await e(),{success:!0}}catch{return{success:!1}}}async handleDebugDeleteLLMApiLogs(e){try{if(!(e!=null&&e.logIds)||e.logIds.length===0)return{success:!1,deletedCount:0};const{deleteLLMApiLogs:t}=await Promise.resolve().then(()=>ue);return{success:!0,deletedCount:await t(e.logIds)}}catch{return{success:!1,deletedCount:0}}}async handleDebugGetCacheEntries(e){try{const{IMAGE_CACHE_NAME:t}=await Promise.resolve().then(()=>D),{cacheName:s=t,limit:r=50,offset:o=0}=e||{},i=await caches.open(s),a=await i.keys(),c=[];for(let l=o;l<Math.min(o+r,a.length);l++){const u=a[l],h=await i.match(u);if(h){const f=h.headers.get("sw-cache-date"),m=h.headers.get("sw-cache-created-at")||f,b=h.headers.get("sw-image-size")||h.headers.get("content-length");c.push({url:u.url,cacheDate:f?parseInt(f):void 0,cacheCreatedAt:m?parseInt(m):void 0,size:b?parseInt(b):void 0})}}return{cacheName:s,entries:c,total:a.length,offset:o,limit:r}}catch(t){return{cacheName:(e==null?void 0:e.cacheName)||"",entries:[],total:0,offset:(e==null?void 0:e.offset)||0,limit:(e==null?void 0:e.limit)||50,error:String(t)}}}async handleDebugGetCacheStats(){try{const e=await caches.keys(),t=[];let s=0,r=0;for(const o of e){const i=await caches.open(o),a=await i.keys();let c=0;for(const l of a){const u=await i.match(l);if(u){const h=u.headers.get("content-length");h&&(c+=parseInt(h))}}t.push({name:o,count:a.length,size:c}),s+=a.length,r+=c}return{stats:{caches:t,totalCount:s,totalSize:r}}}catch(e){return{stats:{caches:[],totalCount:0,totalSize:0},error:String(e)}}}async handleDebugExportLogs(){try{const{getDebugStatus:e,getDebugLogs:t,loadConsoleLogsFromDB:s,APP_VERSION:r}=await Promise.resolve().then(()=>D),{getAllLogs:o}=await Promise.resolve().then(()=>Ue),i=await s(),a=o(),c=t();return{exportTime:new Date().toISOString(),swVersion:r,status:e(),fetchLogs:c,consoleLogs:i,postmessageLogs:a}}catch{return{exportTime:new Date().toISOString(),swVersion:"unknown",status:{},fetchLogs:[],consoleLogs:[],postmessageLogs:[]}}}async handleCDNGetStatus(){try{const{getCDNStatusReport:e}=await Promise.resolve().then(()=>D);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>D);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>D),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>D);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>D);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>D);return await t(e.url),this.sendCacheDeleted(e.url),{success:!0}}catch(t){return{success:!1,error:String(t)}}}async handlePing(){return{success:!0}}broadcastToAll(e,t){this.channels.forEach(s=>{s.channel.broadcast(e,t)})}broadcastToOthers(e,t,s){this.channels.forEach(r=>{r.clientId!==s&&r.channel.broadcast(e,t)})}publishToClient(e,t,s){const r=this.channels.get(e);r&&r.channel.broadcast(t,s)}sendCacheImageCached(e,t,s){this.broadcastToAll(I.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheDeleted(e){this.broadcastToAll(I.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(I.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(I.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(I.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(I.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(I.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(I.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(I.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(I.DEBUG_LLM_LOG,{log:e})}sendPostMessageLog(e){this.postMessageLogBuffer.push(e),this.postMessageLogTimer||(this.postMessageLogTimer=setTimeout(()=>{this.flushPostMessageLogs()},this.POSTMESSAGE_LOG_BATCH_INTERVAL))}flushPostMessageLogs(){if(this.postMessageLogTimer=null,this.postMessageLogBuffer.length===0)return;const e=this.postMessageLogBuffer;this.postMessageLogBuffer=[],this.broadcastToAll(I.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(I.DEBUG_NEW_CRASH_SNAPSHOT,{snapshot:e})}async requestVideoThumbnail(e,t=3e4){const s=Array.from(this.channels.values())[0];if(!s)return console.warn("[ChannelManager] No client channel available for video thumbnail request"),null;try{const r=await Ws(s.channel.call("thumbnail:generate",{url:e}),t,"Video thumbnail generation timeout");if(!r||r.ret!==0)return console.warn("[ChannelManager] Video thumbnail generation failed:",r==null?void 0:r.msg),null;const o=r.data;return o!=null&&o.error?(console.warn("[ChannelManager] Video thumbnail generation error:",o.error),null):(o==null?void 0:o.thumbnailUrl)||null}catch(r){return console.warn("[ChannelManager] Video thumbnail request failed:",r),null}}getConnectedClients(){return Array.from(this.channels.keys())}getConnectedClientCount(){return this.channels.size}async cleanupDisconnectedClients(){var r;const e=await this.sw.clients.matchAll({type:"window"}),t=new Set(e.map(o=>o.id));let s=!1;for(const[o,i]of this.channels)t.has(o)||(i.isDebugClient&&(s=!0),this.channels.delete(o));s&&((r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}};he.instance=null;let _e=he,Ae=null;function St(n){return Ae||(Ae=_e.getInstance(n)),Ae}function W(){return Ae}const Bs=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:S,SWChannelManager:_e,SW_EVENTS:I,getChannelManager:W,initChannelManager:St},Symbol.toStringTag,{value:"Module"}));function ve(n){ft(n)}const Ns=[];let Ct=!1;function ye(n){Ct=n}function Fe(){return Ct}function ze(){return[...Ns]}const qs=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:ze,isDebugFetchEnabled:Fe,setDebugFetchEnabled:ye},Symbol.toStringTag,{value:"Module"})),Hs=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),$e={degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500},Ve=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1},{name:"unpkg",urlTemplate:"https://unpkg.com/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:2}],de=new Map;function Et(){Ve.forEach(n=>{de.has(n.name)||de.set(n.name,{name:n.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}Et();function Tt(n){const e=de.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now())}function ie(n){const e=de.get(n);e&&(e.failCount++,e.lastCheckTime=Date.now(),e.failCount>=$e.failThreshold&&(e.isHealthy=!1,console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${e.failCount} failures`)))}function xs(n){const e=de.get(n);return e?e.isHealthy?!0:Date.now()-e.lastCheckTime>$e.degradeTimeout?(console.log(`[CDN Fallback] Trying to recover ${n}...`),!0):!1:!1}function Gs(){return Ve.filter(n=>n.enabled&&xs(n.name)).sort((n,e)=>n.priority-e.priority)}function Dt(n){const e=/^\/?(aitu-app@[\d.]+\/)/;return n.replace(e,"/")}function Lt(n,e,t){const s=Dt(t);return n.urlTemplate.replace("{version}",e).replace("{path}",s.startsWith("/")?s.slice(1):s)}async function Ke(n,e=$e.fetchTimeout){const t=new AbortController,s=setTimeout(()=>t.abort(),e);try{return await fetch(n,{signal:t.signal,cache:"no-store"})}finally{clearTimeout(s)}}async function _t(n,e,t){var r;if(Hs)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;const s=Gs();for(const o of s){const i=Lt(o,e,n);try{console.log(`[CDN Fallback] Trying ${o.name}: ${i}`);const a=await Ke(i);if(a.ok){const c=a.headers.get("Content-Type")||"";if(!(c.includes("javascript")||c.includes("css")||c.includes("json")||c.includes("font")||c.includes("image")||c.includes("woff")||c.includes("application/octet-stream"))){console.warn(`[CDN Fallback] ${o.name} invalid Content-Type: ${c}`),ie(o.name);continue}const u=parseInt(a.headers.get("Content-Length")||"0",10),h=c.includes("javascript")||c.includes("css")||c.includes("json");if(h&&u>0&&u<50){console.warn(`[CDN Fallback] ${o.name} response too small: ${u} bytes`),ie(o.name);continue}const f=a.clone();try{const m=(r=f.body)==null?void 0:r.getReader();if(m){const{value:b}=await m.read();if(m.cancel(),b){const p=new TextDecoder().decode(b.slice(0,200)),d=p.includes("<!DOCTYPE")||p.includes("<html")||p.includes("<HTML")||p.includes("Not Found")||p.includes("404");if(h&&d){console.warn(`[CDN Fallback] ${o.name} returned HTML instead of ${c}`),ie(o.name);continue}}}}catch{}return Tt(o.name),console.log(`[CDN Fallback] Success from ${o.name}`),{response:a,source:o.name}}else console.warn(`[CDN Fallback] ${o.name} returned ${a.status}`),ie(o.name)}catch(a){console.warn(`[CDN Fallback] ${o.name} failed:`,a),ie(o.name)}}try{const o=Dt(n),i=`${t}/${o.startsWith("/")?o.slice(1):o}`;console.log(`[CDN Fallback] Trying local server: ${i}`);const a=await Ke(i);if(a.ok)return console.log("[CDN Fallback] Success from local server"),{response:a,source:"local"}}catch(o){console.warn("[CDN Fallback] Local server failed:",o)}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function At(n){const e=new Map;for(const t of Ve){if(!t.enabled)continue;const s=Lt(t,n,t.healthCheckPath);try{const o=(await Ke(s,5e3)).ok;e.set(t.name,o),o?Tt(t.name):ie(t.name)}catch{e.set(t.name,!1),ie(t.name)}}return e}function vt(){return Array.from(de.entries()).map(([n,e])=>({name:n,status:e}))}function Rt(){Et(),console.log("[CDN Fallback] All CDN status reset")}const Q=self;St(Q).setDebugClientCountChangedCallback(sn);const J={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function Re(n){var t;const e=((t=n[0])==null?void 0:t.toString())||"";return!!(e.includes("[ServiceWorkerChannel]")||e.includes("[BaseChannel]")||e.includes("Invalid message structure")||e.includes("broadcast:")||e.includes("publish:")||e.includes("subscribe:")||e.includes("[Main]")||e.includes("[SW Console Capture]")||e.includes("[SWChannelManager]")&&(e.includes("broadcast")||e.includes("sendConsoleLog")))}function Us(){console.log=(...n)=>{J.log(...n),Fe()&&!Re(n)&&Me("log",n)},console.info=(...n)=>{J.info(...n),Fe()&&!Re(n)&&Me("info",n)},console.warn=(...n)=>{J.warn(...n),Re(n)||Me("warn",n)},console.error=(...n)=>{J.error(...n),Re(n)||Me("error",n)}}function js(n){let e;const t=[];for(const r of n)try{const o=r;if(r instanceof Error||r&&typeof r=="object"&&typeof o.message=="string")e=o.stack||e,t.push(`${o.name||"Error"}: ${o.message||""}`);else if(typeof r=="object"&&r!==null){const i=JSON.stringify(r);t.push(i==="{}"?String(r):i)}else t.push(String(r))}catch{t.push(String(r))}return{message:t.join(" ")||"(empty)",stack:e}}function Me(n,e){try{const{message:t,stack:s}=js(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Xe=="function"&&Xe({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){J.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Xe=null;Us(),Promise.resolve().then(()=>ue).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=W();t&&t.sendDebugLLMLog(e)})});const j="0.6.14",Ye=`drawnix-v${j}`,A="drawnix-images",Se=`drawnix-static-v${j}`,ke="drawnix-fonts",ce="sw-cache-date",ge="sw-cache-created-at",Fs="/__aitu_cache__/",zs="/asset-library/",Mt=location.hostname==="localhost"||location.hostname==="127.0.0.1",$s=[{hostname:"google.datas.systems",pathPattern:"response_images",fallbackDomain:"cdn.i666.fun"},{hostname:"googlecdn2.datas.systems",pathPattern:"response_images",fallbackDomain:"googlecdn2.i666.fun"},{hostname:"filesystem.i666.fun",pathPattern:"response_images",fallbackDomain:"filesystem.i666.fun"}],Vs=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Ks=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,H=new Map,le=new Map,kt=30*1e3,Ce=new Map,B=new Map,Xs=300*1e3,Pt=10,fe=new Set,pe=new Set,Ys=3600*1e3,Qe=new Map;function Ot(n){pe.add(n),Qe.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function Qs(n){if(!pe.has(n))return!1;const e=Qe.get(n);return e&&Date.now()-e>Ys?(pe.delete(n),Qe.delete(n),!1):!0}const K=[],It=7,F=[],Js=500;let v=!1;function N(n){if(!v)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return F.unshift(t),F.length>Js&&F.pop(),Wt(t),e}function R(n,e){if(!v||!n)return;const t=F.find(s=>s.id===n);t&&(Object.assign(t,e),Wt(t))}function Wt(n){const e=W();e&&e.sendDebugLog(n)}function Pe(){return new Promise((n,e)=>{const t=indexedDB.open("ConsoleLogDB",1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains("logs")){const o=r.createObjectStore("logs",{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("logLevel","logLevel",{unique:!1})}}})}async function Zs(n){try{const e=await Pe(),t=e.transaction(["logs"],"readwrite");return t.objectStore("logs").add(n),new Promise((r,o)=>{t.oncomplete=()=>{e.close(),r()},t.onerror=()=>{e.close(),o(t.error)}})}catch(e){console.warn("Service Worker: 无法保存控制台日志:",e)}}async function Bt(){try{await Nt();const n=await Pe(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-It*24*60*60*1e3;return new Promise((o,i)=>{const a=s.openCursor(null,"prev"),c=[];a.onsuccess=()=>{const l=a.result;if(l){const u=l.value;u.timestamp>=r&&c.push(u),l.continue()}else n.close(),o(c)},a.onerror=()=>{n.close(),i(a.error)}})}catch(n){return console.warn("Service Worker: 无法加载控制台日志:",n),[]}}async function Nt(){try{const n=await Pe(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-It*24*60*60*1e3,o=IDBKeyRange.upperBound(r);return new Promise((i,a)=>{const c=s.openCursor(o);let l=0;c.onsuccess=()=>{const u=c.result;u?(u.delete(),l++,u.continue()):(n.close(),l>0,i(l))},c.onerror=()=>{n.close(),a(c.error)}})}catch(n){return console.warn("Service Worker: 无法清理过期日志:",n),0}}async function qt(){try{const n=await Pe(),e=n.transaction(["logs"],"readwrite");return e.objectStore("logs").clear(),new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("Service Worker: 无法清空控制台日志:",n)}}const Ht=500;function Je(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(v||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};Zs(r),K.unshift(r),K.length>Ht&&(K.length=Ht),v&&en(r)}Xe=Je;function en(n){const e=W();e&&e.sendConsoleLog(n)}function tn(){let n=0;return B.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function xt(){return{version:j,cacheNames:[Ye,A,Se,ke],pendingImageRequests:H.size,pendingVideoRequests:Ce.size,videoBlobCacheSize:B.size,videoBlobCacheTotalBytes:tn(),completedImageRequestsSize:le.size,failedDomainsCount:fe.size,failedDomains:Array.from(fe),corsFailedDomainsCount:pe.size,corsFailedDomains:Array.from(pe),debugLogsCount:F.length,consoleLogsCount:K.length,debugModeEnabled:v,memoryStats:{pendingRequestsMapSize:H.size,completedRequestsMapSize:le.size,videoBlobCacheMapSize:B.size,failedDomainsSetSize:fe.size,corsFailedDomainsSetSize:pe.size,debugLogsArraySize:F.length,consoleLogsArraySize:K.length}}}function Ze(){return F}function Gt(){F.length=0}function Ut(){K.length=0}function et(){v||(v=!0,ye(!0),ve(!0),J.log("Service Worker: Debug mode enabled (debug page connected)"))}function tt(){v&&(v=!1,ye(!1),ve(!1),K.length=0,F.length=0,J.log("Service Worker: Debug mode disabled (no debug pages)"))}function sn(n){n>0?et():tt()}function jt(n){for(const e of $s)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function nn(n,e){return Vs.test(n.pathname)||e.destination==="image"||jt(n)!==null}function rn(n,e){return Ks.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function on(n,e){return n.hostname==="fonts.googleapis.com"||n.hostname==="fonts.gstatic.com"?!0:/\.(woff|woff2|ttf|otf|eot)$/i.test(n.pathname)||e.destination==="font"}async function an(){try{const n=indexedDB.open("ServiceWorkerDB",1);return new Promise((e,t)=>{n.onerror=()=>t(n.error),n.onsuccess=()=>{const s=n.result;if(s.objectStoreNames.contains("failedDomains")){const i=s.transaction(["failedDomains"],"readonly").objectStore("failedDomains").getAll();i.onsuccess=()=>{i.result.forEach(c=>fe.add(c.domain)),e()},i.onerror=()=>t(i.error)}else e()},n.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains("failedDomains")||r.createObjectStore("failedDomains",{keyPath:"domain"})}})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function cn(n){try{const e=indexedDB.open("ServiceWorkerDB",1);return new Promise((t,s)=>{e.onerror=()=>s(e.error),e.onsuccess=()=>{const o=e.result.transaction(["failedDomains"],"readwrite");o.objectStore("failedDomains").put({domain:n,timestamp:Date.now()}),o.oncomplete=()=>{t()},o.onerror=()=>s(o.error)},e.onupgradeneeded=r=>{const o=r.target.result;o.objectStoreNames.contains("failedDomains")||o.createObjectStore("failedDomains",{keyPath:"domain"})}})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function ln(n){try{const e=await n.keys();if(e.length<=10)return;const t=[];for(const i of e)try{const a=await n.match(i);if(a){const c=a.headers.get(ce),l=a.headers.get("sw-image-size");t.push({request:i,cacheDate:c?parseInt(c):0,imageSize:l?parseInt(l):0})}}catch(a){console.warn("Service Worker: Error reading cache entry:",a)}t.sort((i,a)=>i.cacheDate-a.cacheDate);const s=Math.max(1,Math.floor(t.length*.25));let r=0,o=0;for(let i=0;i<s&&i<t.length;i++)try{await n.delete(t[i].request),r++,o+=t[i].imageSize}catch(a){console.warn("Service Worker: Error deleting cache entry:",a)}}catch(e){console.warn("Service Worker: Cache cleanup failed:",e)}}async function un(){try{const n=await fetch("./precache-manifest.json",{cache:"reload"});return n.ok?(await n.json()).files:null}catch{return null}}async function hn(n,e,t){try{const s=await n.match(e);if(s&&s.headers.get("x-sw-revision")===t)return{url:e,success:!0,skipped:!0};const r=e.endsWith(".html")||e==="/";let o=null,i="server";if(!r){const a=await _t(e.startsWith("/")?e.slice(1):e,j,location.origin);a&&a.response.ok&&(o=a.response,i=a.source)}if(o||(o=await fetch(e,{cache:"reload"}),i="server"),o.ok){const a=new Headers(o.headers);a.set("x-sw-revision",t),a.set("x-sw-cached-at",new Date().toISOString()),a.set("x-sw-source",i);const c=new Response(await o.blob(),{status:o.status,statusText:o.statusText,headers:a}),l=new URL(e,self.location.origin).href;return await n.put(l,c),{url:e,success:!0,source:i}}return{url:e,success:!1,status:o.status}}catch(s){return{url:e,success:!1,error:String(s)}}}async function dn(n,e){const s=[];for(let r=0;r<e.length;r+=6){const o=e.slice(r,r+6),i=await Promise.allSettled(o.map(({url:a,revision:c})=>hn(n,a,c)));for(const a of i)a.status==="fulfilled"?s.push({success:a.value.success,source:a.value.source}):s.push({success:!1})}s.filter(r=>r.success).length,s.filter(r=>r.success&&r.source&&r.source!=="server").length,s.filter(r=>r.success&&r.source==="server").length}Q.addEventListener("install",n=>{Q.skipWaiting(),n.waitUntil((async()=>{await an();try{const e=await un();if(e&&e.length>0){const t=await caches.open(Se);await dn(t,e)}}catch(e){console.warn("Service Worker: Precache failed:",e)}})())}),Q.addEventListener("activate",n=>{n.waitUntil((async()=>{await Q.clients.claim();const e=W();e&&e.sendSWActivated(j)})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(o=>o.startsWith("drawnix-images-v")&&o!==A);if(t.length>0){const o=await caches.open(A);for(const i of t)try{const a=await caches.open(i),c=await a.keys();for(const l of c){const u=await a.match(l);u&&await o.put(l,u)}await caches.delete(i)}catch(a){console.warn(`Failed to migrate cache ${i}:`,a)}}const s=e.filter(o=>o.startsWith("drawnix-static-v")&&o!==Se),r=e.filter(o=>o.startsWith("drawnix-v")&&o!==Ye&&o!==A&&!o.startsWith("drawnix-static-v"));(s.length>0||r.length>0)&&setTimeout(async()=>{for(const o of[...s,...r])try{await caches.delete(o)}catch(i){console.warn("Failed to delete old cache:",o,i)}},3e4),Nt().catch(o=>{console.warn("Failed to cleanup expired console logs:",o)})}))});function gn(n){if(v){const e=W();e&&e.sendPostMessageLog(n)}}Q.addEventListener("message",n=>{var i,a,c,l,u,h,f,m,b,p;const e=((i=n.data)==null?void 0:i.type)||((a=n.data)==null?void 0:a.cmdname)||((l=(c=n.data)==null?void 0:c.req)==null?void 0:l.cmdname)||"unknown",t=((u=n.source)==null?void 0:u.id)||"",s=((h=n.source)==null?void 0:h.url)||"",r=((f=n.data)==null?void 0:f.cmdname)||((m=n.data)==null?void 0:m.requestId)&&((b=n.data)==null?void 0:b.ret)!==void 0;let o="";if(He()&&!r&&(o=xe(e,n.data,t,s,(p=n.data)==null?void 0:p.__internal__),o&&v)){const w=Te().find(y=>y.id===o);w&&gn(w)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:d,mediaType:w,blob:y,mimeType:C}=n.data;if(d&&w&&y){const T=new Blob([y],{type:C||(w==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:q}=await Promise.resolve().then(()=>x);q(T,d,w)})()}return}if(n.data&&n.data.type==="SKIP_WAITING"){Q.skipWaiting();const d=W();d&&d.sendSWUpdated(j)}else if(n.data&&n.data.type==="FORCE_UPGRADE"){Q.skipWaiting();const d=W();d&&d.sendSWUpdated(j)}else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:d}=n.data;d&&nt(d).then(()=>{const w=W();w&&w.sendCacheDeleted(d)}).catch(w=>{console.error("Service Worker: Failed to delete cache:",w)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:d}=n.data;d&&Array.isArray(d)&&wn(d).then(()=>{}).catch(w=>{console.error("Service Worker: Failed to batch delete caches:",w)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")yn().then(()=>{}).catch(d=>{console.error("Service Worker: Failed to clear all cache:",d)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){v=!0,ye(!0),ve(!0),J.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const d=W();d&&d.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){v=!1,ye(!1),ve(!1),K.length=0,F.length=0,J.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const d=W();d&&d.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:d}=await Promise.resolve().then(()=>ue),w=await d(),y=n.source;y&&y.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:w})}catch(d){console.error("[SW] Failed to get LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:d}=await Promise.resolve().then(()=>ue);await d();const w=n.source;w&&w.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(d){console.error("[SW] Failed to clear LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const d=n.source;d&&d.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:v,swVersion:j,logs:F.slice(-100),consoleLogs:K.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:d}=await Promise.resolve().then(()=>qs),w=Ze(),y=d(),C=n.source;C&&C.postMessage({type:"SW_DEBUG_LOGS",logs:[...w,...y.map(T=>({...T,type:"fetch"}))]})}catch(d){console.error("[SW] Failed to get fetch logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const d=n.source;d&&d.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:K})}catch(d){console.error("[SW] Failed to get console logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const d=Te(),w=n.source;w&&w.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:d})}catch(d){console.error("[SW] Failed to get postmessage logs:",d)}})();return}});const fn="MemorySnapshotDB",re="snapshots",Ft=50;async function st(){return new Promise((n,e)=>{const t=indexedDB.open(fn,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(re)){const o=r.createObjectStore(re,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function zt(n){try{const e=await st(),t=e.transaction(re,"readwrite"),s=t.objectStore(re);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>Ft){const a=s.index("timestamp").openCursor();let c=0;const l=o-Ft;a.onsuccess=u=>{const h=u.target.result;h&&c<l&&(s.delete(h.value.id),c++,h.continue())}}},await new Promise((o,i)=>{t.oncomplete=()=>{e.close(),o()},t.onerror=()=>{e.close(),i(t.error)}})}catch(e){console.warn("[SW] Failed to save crash snapshot:",e)}}async function $t(){try{const n=await st(),s=n.transaction(re,"readonly").objectStore(re).index("timestamp");return new Promise((r,o)=>{const i=s.getAll();i.onsuccess=()=>{n.close();const a=i.result.sort((c,l)=>l.timestamp-c.timestamp);r(a)},i.onerror=()=>{n.close(),o(i.error)}})}catch(n){return console.warn("[SW] Failed to get crash snapshots:",n),[]}}async function Vt(){try{const n=await st(),e=n.transaction(re,"readwrite");e.objectStore(re).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("[SW] Failed to clear crash snapshots:",n)}}const pn=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function mn(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function bn(n){return new Promise(e=>{try{const t=indexedDB.open(n);t.onerror=()=>e({count:0,totalSize:0}),t.onsuccess=()=>{const s=t.result,r=Array.from(s.objectStoreNames);if(r.length===0){s.close(),e({count:0,totalSize:0});return}let o=0,i=0,a=0,c=0;const l=10;try{const u=s.transaction(r,"readonly");for(const h of r){const f=u.objectStore(h),m=f.count();m.onsuccess=()=>{const b=m.result;if(o+=b,b>0){const p=f.openCursor();let d=0;p.onsuccess=w=>{const y=w.target.result;if(y&&d<l)i+=mn(y.value),a++,d++,y.continue();else if(c++,c===r.length){s.close();const C=a>0?i/a:0,T=Math.round(C*o);e({count:o,totalSize:T})}},p.onerror=()=>{if(c++,c===r.length){s.close();const w=a>0?i/a:0,y=Math.round(w*o);e({count:o,totalSize:y})}}}else c++,c===r.length&&(s.close(),e({count:o,totalSize:0}))},m.onerror=()=>{if(c++,c===r.length){s.close();const b=a>0?i/a:0,p=Math.round(b*o);e({count:o,totalSize:p})}}}}catch{s.close(),e({count:0,totalSize:0})}},t.onupgradeneeded=s=>{s.target.result.close();try{indexedDB.deleteDatabase(n)}catch{}e({count:0,totalSize:0})}}catch{e({count:0,totalSize:0})}})}async function Kt(){const n={},e=[Ye,A,Se,ke];for(const t of e)try{const s=await caches.open(t),r=await s.keys();let o=0;const i=Math.min(r.length,100);let a=0;for(let c=0;c<i;c++){const l=await s.match(r[c]);if(l){const u=l.headers.get("sw-image-size")||l.headers.get("content-length");u&&(a+=parseInt(u))}}i>0&&r.length>i?o=Math.round(a/i*r.length):o=a,n[t]={count:r.length,totalSize:o,type:"cache"}}catch{n[t]={count:0,totalSize:0,type:"cache"}}for(const t of pn)try{const s=await bn(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function nt(n){try{await(await caches.open(A)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function wn(n){try{const e=await caches.open(A);let t=0;for(const s of n)try{await e.delete(s),t++}catch(r){console.warn("Service Worker: Failed to delete cache in batch:",s,r)}}catch(e){throw console.error("Service Worker: Failed to batch delete caches:",e),e}}async function yn(){try{const n=await caches.open(A),e=await n.keys();for(const t of e)await n.delete(t)}catch(n){throw console.error("Service Worker: Failed to clear image cache:",n),n}}async function Xt(n,e,t){try{const s=W();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}async function Sn(){try{if(navigator.storage&&navigator.storage.estimate){const n=await navigator.storage.estimate(),e=n.usage||0,t=n.quota||0,s=t>0?e/t*100:0;if(s>90){console.warn("Service Worker: Storage quota warning:",{usage:e,quota:t,percentage:s});const r=W();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const Z=new Map,Yt=300*1e3,Qt=500;function Cn(n){const e=n.match(/\/(\d{4})\/(\d{2})\/(\d{2})\//),t=n.match(/\/(\d{4})(\d{2})(\d{2})\//);let s=null;if(e?s=new Date(parseInt(e[1]),parseInt(e[2])-1,parseInt(e[3])):t&&(s=new Date(parseInt(t[1]),parseInt(t[2])-1,parseInt(t[3]))),!s)return!1;const r=new Date;return!(s.getFullYear()===r.getFullYear()&&s.getMonth()===r.getMonth()&&s.getDate()===r.getDate())}function En(n){const e=Z.get(n);return e?Date.now()-e>Yt?(Z.delete(n),!1):!0:!1}function Jt(n){if(Cn(n)){if(Z.size>=Qt){const e=Date.now();for(const[t,s]of Z)e-s>Yt&&Z.delete(t);if(Z.size>=Qt){const t=Array.from(Z.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)Z.delete(r)}}Z.set(n,Date.now())}}Q.addEventListener("fetch",n=>{const e=new URL(n.request.url),t=Date.now();if(e.protocol!=="http:"&&e.protocol!=="https:"){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"other",details:`Skipped: non-http protocol (${e.protocol})`,status:0,duration:0});return}if(e.pathname.startsWith(Fs)){const s=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(Dn(n.request).then(r=>(R(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw R(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(zs)){const s=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Ln(n.request).then(r=>(R(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw R(s,{error:String(r),duration:Date.now()-t}),r}));return}if(!(e.hostname.endsWith(".posthog.com")||e.hostname.endsWith(".sentry.io")||e.hostname.endsWith(".ingest.sentry.io"))){if(e.hostname==="cdn.i666.fun"){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: cdn.i666.fun (fallback domain)",status:0,duration:0});return}if(e.hostname.endsWith(".volces.com")||e.hostname.endsWith(".volccdn.com")){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Volcengine domain (no CORS)",status:0,duration:0});return}if(e.hostname.endsWith(".aliyuncs.com")){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:"Passthrough: Aliyun OSS domain (no CORS)",status:0,duration:0});return}if(Qs(e.hostname)){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"passthrough",details:`Passthrough: ${e.hostname} (CORS failed domain, auto-detected)`,status:0,duration:0});return}if(e.hostname!=="api.github.com"){if(rn(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"video",headers:r?{range:r}:void 0,details:r?`Video Range request: ${r}`:"Video request"});n.respondWith(_n(n.request).then(i=>(R(o,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-s,responseHeaders:{"content-type":i.headers.get("content-type")||"","content-length":i.headers.get("content-length")||"","content-range":i.headers.get("content-range")||""}}),i)).catch(i=>{throw R(o,{error:String(i),duration:Date.now()-s}),i}));return}if(on(e,n.request)){const s=Date.now(),r=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(Tn(n.request).then(o=>(R(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date")}),o)).catch(o=>{throw R(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&nn(e,n.request)){if(En(n.request.url)){N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"Skipped: recently failed URL (cached 404)",status:404,duration:0}),n.respondWith(new Response("",{status:404,statusText:"Not Found (cached)"}));return}const s=Date.now(),r=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(Mn(n.request).then(o=>(o.status===404&&Jt(n.request.url),R(r,{status:o.status,statusText:o.statusText,responseType:o.type,duration:Date.now()-s,cached:o.headers.has("sw-cache-date"),size:parseInt(o.headers.get("content-length")||"0")}),o)).catch(o=>{throw Jt(n.request.url),R(r,{error:String(o),duration:Date.now()-s}),o}));return}if(n.request.method==="GET"){const s=n.request.mode==="navigate",r=n.request.destination!=="";if(s||r){const o=Date.now(),i=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(An(n.request).then(a=>(R(i,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-o}),a)).catch(a=>{throw R(i,{error:String(a),duration:Date.now()-o}),a}));return}}if(v){const s=N({type:"fetch",url:n.request.url,method:n.request.method,requestType:"xhr",details:`XHR/API request (${n.request.method})`});n.respondWith((async()=>{try{const r=n.request.clone();let o;const i={};if(n.request.headers.forEach((h,f)=>{i[f]=h}),["POST","PUT","PATCH"].includes(n.request.method))try{const h=n.request.headers.get("content-type")||"";h.includes("application/json")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):h.includes("application/x-www-form-urlencoded")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):o=`[${h||"binary data"}]`}catch{o="[unable to read body]"}R(s,{headers:i,details:o?`XHR/API request (${n.request.method})
2
2
 
3
3
  Request Body:
4
- ${o}`:`XHR/API request (${n.request.method})`});const a=await fetch(n.request),c=a.clone();let l;const u={};a.headers.forEach((h,f)=>{u[f]=h});try{const h=a.headers.get("content-type")||"";h.includes("application/json")||h.includes("text/")?(l=await c.text(),l.length>5e3&&(l=l.substring(0,5e3)+"... (truncated)")):l=`[${h||"binary data"}] (${a.headers.get("content-length")||"unknown"} bytes)`}catch{l="[unable to read response body]"}return M(s,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-t,responseHeaders:u,size:parseInt(a.headers.get("content-length")||"0"),details:o?`XHR/API request (${n.request.method})
4
+ ${o}`:`XHR/API request (${n.request.method})`});const a=await fetch(n.request),c=a.clone();let l;const u={};a.headers.forEach((h,f)=>{u[f]=h});try{const h=a.headers.get("content-type")||"";h.includes("application/json")||h.includes("text/")?(l=await c.text(),l.length>5e3&&(l=l.substring(0,5e3)+"... (truncated)")):l=`[${h||"binary data"}] (${a.headers.get("content-length")||"unknown"} bytes)`}catch{l="[unable to read response body]"}return R(s,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-t,responseHeaders:u,size:parseInt(a.headers.get("content-length")||"0"),details:o?`XHR/API request (${n.request.method})
5
5
 
6
6
  Request Body:
7
7
  ${o}
@@ -10,7 +10,7 @@ Response Body:
10
10
  ${l}`:`XHR/API request (${n.request.method})
11
11
 
12
12
  Response Body:
13
- ${l}`}),a}catch(r){throw M(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function Cn(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(Me),s=await t.match(n);if(s)return s;const r=await fetch(n);if(r&&r.status===200){const o=r.clone(),i=new Headers(o.headers);i.set("sw-cache-date",Date.now().toString());const a=new Response(o.body,{status:o.status,statusText:o.statusText,headers:i});t.put(n,a).catch(c=>{console.warn(`Service Worker [Font-${e}]: 缓存字体失败:`,c)})}return r}catch(t){console.error(`Service Worker [Font-${e}]: 字体请求失败:`,t);const r=await(await caches.open(Me)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function st(n,e={}){return fetch(n,e)}async function En(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname.includes("/video/")||/\.(mp4|webm|ogg|mov)$/i.test(t.pathname),o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),a=t.searchParams.has("thumbnail")&&!o&&!i;if(a){const c=t.searchParams.get("thumbnail")||"small",l=new URL(t.toString());l.searchParams.delete("thumbnail"),l.searchParams.delete("bypass_sw"),l.searchParams.delete("direct_fetch"),l.searchParams.delete("_retry");const{findThumbnailWithFallback:u,createThumbnailResponse:h}=await Promise.resolve().then(()=>x),f=await u(l.toString(),c,[t.pathname]);if(f){const m=await f.response.blob();return h(m)}}try{const c=await caches.open(A);let l=await c.match(n.url);if(l||(l=await c.match(t.pathname)),l){const u=await l.blob();if(a&&!r){const{generateThumbnailAsync:h}=await Promise.resolve().then(()=>x);h(u,t.pathname,"image")}return r?fe(u,s,e):new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":u.type||"image/png","Content-Length":u.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error("Service Worker: Media not found in cache:",{fullUrl:n.url,pathname:t.pathname}),new Response("Media not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error("Service Worker: Error handling cache URL request:",c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Tn(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname,o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),a=t.searchParams.has("thumbnail")&&!o&&!i;if(a){const c=t.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:l,createThumbnailResponse:u}=await Promise.resolve().then(()=>x),h=await l(r,c,[r]);if(h){const f=await h.response.blob();return u(f)}}try{const l=await(await caches.open(A)).match(r);if(l){const u=await l.blob(),h=t.pathname.match(/\.(mp4|webm|ogg|mov)$/i);if(a&&!h){const{generateThumbnailAsync:f}=await Promise.resolve().then(()=>x);f(u,r,"image")}return h&&s?fe(u,s,e):new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":u.type||"application/octet-stream","Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error(`Service Worker [Asset-${e}]: Asset not found in cache:`,r),new Response("Asset not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error(`Service Worker [Asset-${e}]: Error handling asset library request:`,c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const ke=Symbol("VIDEO_LOAD_ERROR");async function Dn(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10);try{const s=n.headers.get("range"),r=e.searchParams.has("bypass_sw")||e.searchParams.has("direct_fetch"),o=e.searchParams.has("_retry"),i=e.searchParams.has("thumbnail")&&!r&&!o,a=new URL(e);["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","rand","bypass_sw","direct_fetch","thumbnail"].forEach(m=>a.searchParams.delete(m));const l=a.toString();if(i){const m=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:w,createThumbnailResponse:p}=await Promise.resolve().then(()=>x),d=await w(l,m);if(d){const S=await d.response.blob();return p(S)}const b=new Uint8Array([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,137,0,0,0,10,73,68,65,84,120,156,99,0,1,0,0,5,0,1,13,10,45,180,0,0,0,0,73,69,78,68,174,66,96,130]);return new Response(b,{status:200,headers:{"Content-Type":"image/png","Cache-Control":"no-cache"}})}const u=ye.get(l);if(u){u.count=(u.count||1)+1;const m=await u.promise;if(m===ke)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(m===null){const w={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,w)}return fe(m,s,t)}if(B.has(l)){const m=B.get(l);if(m)return m.timestamp=Date.now(),fe(m.blob,s,t)}try{const w=await(await caches.open(A)).match(l);if(w){const p=await w.blob();return p.size/(1024*1024)<50&&B.set(l,{blob:p,timestamp:Date.now()}),fe(p,s,t)}}catch{}const h=(async()=>{try{const m={method:"GET",mode:"cors",credentials:"omit",cache:"default"},w=new URL(a),p=await fetch(w,m);if(!p.ok)return ke;if(p.status===206)return null;const d=await p.blob();if(d.size/(1024*1024)<50){B.set(l,{blob:d,timestamp:Date.now()});try{const S=await caches.open(A),C=new Response(d,{headers:{"Content-Type":d.type||"video/mp4","Content-Length":d.size.toString(),"sw-cache-date":Date.now().toString(),"sw-video-size":d.size.toString()}});await S.put(l,C);const{generateThumbnailAsync:T}=await Promise.resolve().then(()=>x);T(d,l,"video")}catch{}}return d}catch{return ke}})();ye.set(l,{promise:h,timestamp:Date.now(),count:1,requestId:t}),h.finally(()=>{ye.get(l)&&ye.delete(l)});const f=await h;if(f===ke)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(f===null){const m={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,m)}return fe(f,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function fe(n,e,t){const s=n.size;if(!e)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":"video/mp4","Content-Length":s.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}});const r=e.match(/bytes=(\d+)-(\d*)/);if(!r)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});const o=parseInt(r[1],10),i=r[2]?parseInt(r[2],10):s-1,a=n.slice(o,i+1),c=i-o+1;return new Response(a,{status:206,statusText:"Partial Content",headers:{"Content-Type":"video/mp4","Content-Range":`bytes ${o}-${i}/${s}`,"Content-Length":c.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}})}async function Ln(n){const e=new URL(n.url),t=n.mode==="navigate"||e.pathname.endsWith(".html"),s=await caches.open(we);if(vt)try{const a=await st(n);if(a&&a.status===200&&n.url.startsWith("http"))return s.put(n,a.clone()),a;if(!a.ok){let c=await s.match(n);return!c&&t&&(c=await s.match("/"),c||(c=await s.match("/index.html"))),c||a}return a}catch{let c=await s.match(n);return!c&&t&&(c=await s.match("/"),c||(c=await s.match("/index.html"))),c||(t?Qt():new Response("Resource unavailable",{status:503}))}if(t)try{const a=await st(n,{cache:"reload"});if(a&&a.status===200&&n.url.startsWith("http"))return s.put(n,a.clone()),a;if(!a.ok){let c=await s.match(n);if(c||(c=await s.match("/")),c||(c=await s.match("/index.html")),!c){const l=await caches.keys();for(const u of l)if(u.startsWith("drawnix-static-v"))try{const h=await caches.open(u);if(c=await h.match(n)||await h.match("/")||await h.match("/index.html"),c)break}catch{}}return c||a}return a}catch{let c=await s.match(n);if(c||(c=await s.match("/")),c||(c=await s.match("/index.html")),!c){const l=await caches.keys();for(const u of l)if(u.startsWith("drawnix-static-v"))try{const h=await caches.open(u);if(c=await h.match(n)||await h.match("/")||await h.match("/index.html"),c)break}catch{}}return c||Qt()}const r=await s.match(n);if(r)return r;const o=e.pathname;if(!vt&&(o.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|woff|woff2|ttf|eot|json|ico)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font"))try{const a=await Dt(o,U,location.origin);if(a&&a.response.ok){const c=a.response.clone();return s.put(n,c),a.response}}catch(a){console.warn("[SW CDN] CDN sources failed, trying local server:",a)}try{const a=await st(n),c=a.headers.get("Content-Type");if(a.status===200&&(c==null?void 0:c.includes("text/html"))&&(e.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|json|woff|woff2|ttf)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font")){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const u=await caches.keys();for(const h of u)if(h.startsWith("drawnix-static-v"))try{const m=await(await caches.open(h)).match(n);if(m)return m}catch{}return new Response("Resource not found",{status:404,statusText:"Not Found"})}if(a&&a.status===200&&n.url.startsWith("http")&&s.put(n,a.clone()),a.status>=400){const u=await caches.keys();for(const h of u)if(h.startsWith("drawnix-static-v"))try{const m=await(await caches.open(h)).match(n);if(m)return m}catch{}}return a}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const c=await caches.keys();for(const l of c)if(l.startsWith("drawnix-static-v"))try{const h=await(await caches.open(l)).match(n);if(h)return h}catch{}return new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}function Qt(){return new Response(`<!DOCTYPE html>
13
+ ${l}`}),a}catch(r){throw R(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function Tn(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(ke),s=await t.match(n);if(s)return s;const r=await fetch(n);if(r&&r.status===200){const o=r.clone(),i=new Headers(o.headers),a=Date.now().toString();i.set(ce,a),i.set(ge,a);const c=new Response(o.body,{status:o.status,statusText:o.statusText,headers:i});t.put(n,c).catch(l=>{console.warn(`Service Worker [Font-${e}]: 缓存字体失败:`,l)})}return r}catch(t){console.error(`Service Worker [Font-${e}]: 字体请求失败:`,t);const r=await(await caches.open(ke)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function rt(n,e={}){return fetch(n,e)}async function Dn(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname.includes("/video/")||/\.(mp4|webm|ogg|mov)$/i.test(t.pathname),o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),a=t.searchParams.has("thumbnail")&&!o&&!i;if(a){const c=t.searchParams.get("thumbnail")||"small",l=new URL(t.toString());l.searchParams.delete("thumbnail"),l.searchParams.delete("bypass_sw"),l.searchParams.delete("direct_fetch"),l.searchParams.delete("_retry");const{findThumbnailWithFallback:u,createThumbnailResponse:h}=await Promise.resolve().then(()=>x),f=await u(l.toString(),c,[t.pathname]);if(f){const m=await f.response.blob();return h(m)}}try{const c=await caches.open(A);let l=await c.match(n.url);if(l||(l=await c.match(t.pathname)),l){const u=await l.blob();if(a&&!r){const{generateThumbnailAsync:h}=await Promise.resolve().then(()=>x);h(u,t.pathname,"image")}return r?me(u,s,e):new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":u.type||"image/png","Content-Length":u.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error("Service Worker: Media not found in cache:",{fullUrl:n.url,pathname:t.pathname}),new Response("Media not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error("Service Worker: Error handling cache URL request:",c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Ln(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname,o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),a=t.searchParams.has("thumbnail")&&!o&&!i;if(a){const c=t.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:l,createThumbnailResponse:u}=await Promise.resolve().then(()=>x),h=await l(r,c,[r]);if(h){const f=await h.response.blob();return u(f)}}try{const l=await(await caches.open(A)).match(r);if(l){const u=await l.blob(),h=t.pathname.match(/\.(mp4|webm|ogg|mov)$/i);if(a&&!h){const{generateThumbnailAsync:f}=await Promise.resolve().then(()=>x);f(u,r,"image")}return h&&s?me(u,s,e):new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":u.type||"application/octet-stream","Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error(`Service Worker [Asset-${e}]: Asset not found in cache:`,r),new Response("Asset not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error(`Service Worker [Asset-${e}]: Error handling asset library request:`,c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const Oe=Symbol("VIDEO_LOAD_ERROR");async function _n(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10);try{const s=n.headers.get("range"),r=e.searchParams.has("bypass_sw")||e.searchParams.has("direct_fetch"),o=e.searchParams.has("_retry"),i=e.searchParams.has("thumbnail")&&!r&&!o,a=new URL(e);["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","rand","bypass_sw","direct_fetch","thumbnail"].forEach(m=>a.searchParams.delete(m));const l=a.toString();if(i){const m=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:b,createThumbnailResponse:p}=await Promise.resolve().then(()=>x),d=await b(l,m);if(d){const y=await d.response.blob();return p(y)}const w=new Uint8Array([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,137,0,0,0,10,73,68,65,84,120,156,99,0,1,0,0,5,0,1,13,10,45,180,0,0,0,0,73,69,78,68,174,66,96,130]);return new Response(w,{status:200,headers:{"Content-Type":"image/png","Cache-Control":"no-cache"}})}const u=Ce.get(l);if(u){u.count=(u.count||1)+1;const m=await u.promise;if(m===Oe)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(m===null){const b={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,b)}return me(m,s,t)}if(B.has(l)){const m=B.get(l);if(m)return m.timestamp=Date.now(),me(m.blob,s,t)}try{const b=await(await caches.open(A)).match(l);if(b){const p=await b.blob();return p.size/(1024*1024)<50&&B.set(l,{blob:p,timestamp:Date.now()}),me(p,s,t)}}catch{}const h=(async()=>{try{const m={method:"GET",mode:"cors",credentials:"omit",cache:"default"},b=new URL(a),p=await fetch(b,m);if(!p.ok)return Oe;if(p.status===206)return null;const d=await p.blob();if(d.size/(1024*1024)<50){B.set(l,{blob:d,timestamp:Date.now()});try{const y=await caches.open(A),C=new Response(d,{headers:{"Content-Type":d.type||"video/mp4","Content-Length":d.size.toString(),[ce]:Date.now().toString(),[ge]:Date.now().toString(),"sw-video-size":d.size.toString()}});await y.put(l,C);const{generateThumbnailAsync:T}=await Promise.resolve().then(()=>x);T(d,l,"video")}catch{}}return d}catch{return Oe}})();Ce.set(l,{promise:h,timestamp:Date.now(),count:1,requestId:t}),h.finally(()=>{Ce.get(l)&&Ce.delete(l)});const f=await h;if(f===Oe)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(f===null){const m={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,m)}return me(f,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function me(n,e,t){const s=n.size;if(!e)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":"video/mp4","Content-Length":s.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}});const r=e.match(/bytes=(\d+)-(\d*)/);if(!r)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":"video/mp4","Accept-Ranges":"bytes"}});const o=parseInt(r[1],10),i=r[2]?parseInt(r[2],10):s-1,a=n.slice(o,i+1),c=i-o+1;return new Response(a,{status:206,statusText:"Partial Content",headers:{"Content-Type":"video/mp4","Content-Range":`bytes ${o}-${i}/${s}`,"Content-Length":c.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}})}async function An(n){const e=new URL(n.url),t=n.mode==="navigate"||e.pathname.endsWith(".html"),s=await caches.open(Se);if(Mt)try{const a=await rt(n);if(a&&a.status===200&&n.url.startsWith("http"))return s.put(n,a.clone()),a;if(!a.ok){let c=await s.match(n);return!c&&t&&(c=await s.match("/"),c||(c=await s.match("/index.html"))),c||a}return a}catch{let c=await s.match(n);return!c&&t&&(c=await s.match("/"),c||(c=await s.match("/index.html"))),c||(t?Zt():new Response("Resource unavailable",{status:503}))}if(t)try{const a=await rt(n,{cache:"reload"});if(a&&a.status===200&&n.url.startsWith("http"))return s.put(n,a.clone()),a;if(!a.ok){let c=await s.match(n);if(c||(c=await s.match("/")),c||(c=await s.match("/index.html")),!c){const l=await caches.keys();for(const u of l)if(u.startsWith("drawnix-static-v"))try{const h=await caches.open(u);if(c=await h.match(n)||await h.match("/")||await h.match("/index.html"),c)break}catch{}}return c||a}return a}catch{let c=await s.match(n);if(c||(c=await s.match("/")),c||(c=await s.match("/index.html")),!c){const l=await caches.keys();for(const u of l)if(u.startsWith("drawnix-static-v"))try{const h=await caches.open(u);if(c=await h.match(n)||await h.match("/")||await h.match("/index.html"),c)break}catch{}}return c||Zt()}const r=await s.match(n);if(r)return r;const o=e.pathname;if(!Mt&&(o.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|woff|woff2|ttf|eot|json|ico)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font"))try{const a=await _t(o,j,location.origin);if(a&&a.response.ok){const c=a.response.clone();return s.put(n,c),a.response}}catch(a){console.warn("[SW CDN] CDN sources failed, trying local server:",a)}try{const a=await rt(n),c=a.headers.get("Content-Type");if(a.status===200&&(c==null?void 0:c.includes("text/html"))&&(e.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|json|woff|woff2|ttf)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font")){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const u=await caches.keys();for(const h of u)if(h.startsWith("drawnix-static-v"))try{const m=await(await caches.open(h)).match(n);if(m)return m}catch{}return new Response("Resource not found",{status:404,statusText:"Not Found"})}if(a&&a.status===200&&n.url.startsWith("http")&&s.put(n,a.clone()),a.status>=400){const u=await caches.keys();for(const h of u)if(h.startsWith("drawnix-static-v"))try{const m=await(await caches.open(h)).match(n);if(m)return m}catch{}}return a}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const c=await caches.keys();for(const l of c)if(l.startsWith("drawnix-static-v"))try{const h=await(await caches.open(l)).match(n);if(h)return h}catch{}return new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}function Zt(){return new Response(`<!DOCTYPE html>
14
14
  <html lang="zh-CN">
15
15
  <head>
16
16
  <meta charset="UTF-8">
@@ -51,4 +51,4 @@ ${l}`}),a}catch(r){throw M(s,{error:String(r),duration:Date.now()-t}),r}})());re
51
51
  <p>请检查您的网络连接,或稍后再试。</p>
52
52
  <button onclick="location.reload()">重试</button>
53
53
  </body>
54
- </html>`,{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}const nt=15e3,Jt=3e4;function Zt(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function _n(){const n=Date.now(),e=[];if(B.forEach((t,s)=>{n-t.timestamp>Vs&&e.push(s)}),e.length>0&&e.forEach(t=>B.delete(t)),B.size>Rt){const t=Array.from(B.entries()).sort((o,i)=>o[1].timestamp-i[1].timestamp),s=B.size-Rt,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>B.delete(o))}}function An(){const n=Date.now(),e=[];q.forEach((s,r)=>{n-s.timestamp>Jt&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>q.delete(s)));const t=[];ie.forEach((s,r)=>{n-s.timestamp>Mt&&t.push(r)}),t.length>0&&t.forEach(s=>ie.delete(s)),_n()}async function vn(n){try{const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),r=t.searchParams.has("_retry"),o=t.searchParams.has("thumbnail")&&!s&&!r,i=o&&t.searchParams.get("thumbnail")||"small";["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","rand","_force","bypass_sw","direct_fetch","thumbnail"].forEach(f=>t.searchParams.delete(f));const c=new Request(t.toString(),{method:n.method,headers:n.headers,mode:n.mode,credentials:n.credentials}),l=t.toString();if(o){const{findThumbnailWithFallback:f,createThumbnailResponse:m}=await Promise.resolve().then(()=>x),w=await f(l,i,[c.url]);if(w){const p=await w.response.blob();return m(p)}}const u=ie.get(l);if(u){if(Date.now()-u.timestamp<Mt)return u.response.clone();ie.delete(l)}if(q.has(l)){const f=q.get(l);if(f){const m=Date.now()-f.timestamp;if(m>Jt)console.warn(`Service Worker [${e}]: 发现过期的 pending 请求 (${m}ms),清理并重新发起:`,l),q.delete(l);else{f.count=(f.count||1)+1,f.duplicateRequestIds=f.duplicateRequestIds||[],f.duplicateRequestIds.push(e);try{const w=await Zt(f.promise,nt,"Image request timeout");return w&&w.clone?w.clone():w}catch(w){if(w.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),q.delete(l),es(n.url,e);throw w}}}}An();const h=Mn(c,n.url,l,e,s,o?i:void 0);q.set(l,{promise:h,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),h.then(f=>{f&&f.ok&&ie.set(l,{response:f.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{q.get(l)&&q.delete(l)});try{return await Zt(h,nt,"Image request timeout")}catch(f){if(f.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${nt}ms),清理并返回超时响应让前端直接加载:`,n.url),q.delete(l),es(n.url,e);throw f}}catch(e){throw e}}function es(n,e){return new Response("Image request timeout - use direct load",{status:504,statusText:"Gateway Timeout",headers:{"Content-Type":"text/plain","X-SW-Timeout":"true","X-SW-Original-URL":n,"Access-Control-Allow-Origin":"*"}})}async function Mn(n,e,t,s,r=!1,o){try{const i=await caches.open(A);if(!r){let p=await i.match(n);if(p||(p=await i.match(n.url)),p||(p=await i.match(t)),p){const b=await p.clone().blob();if(b.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await i.delete(n);else{if(o){const{generateThumbnailAsync:C}=await Promise.resolve().then(()=>x);C(b,n.url,"image")}if(p.headers.get("sw-cache-date")){const C=Date.now(),T=new Response(b,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),"sw-cache-date":C.toString()}});return n.url.startsWith("http")&&await i.put(n,T.clone()),T}else{const C=new Response(b,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),"sw-cache-date":Date.now().toString()}});return n.url.startsWith("http")&&await i.put(n,C.clone()),C}}}}const a=new URL(e),c=Gt(a);let l=null,u=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),de.has(c.hostname)&&(u=!0));let h;const f=[{method:"GET",mode:"cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"},{method:"GET",cache:"no-cache"},{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"}];let m;u?m=[l]:(m=[e],l&&m.push(l));let w=null;for(let p=0;p<m.length;p++){const d=m[p],b=p>0;for(const S of f)try{let C,T=!1;for(let K=0;K<=2;K++)try{if(h=await fetch(d,S),h&&(h.status!==0||h.type==="opaque"))break}catch(ee){C=ee;const pe=ee.message||"";if(pe.includes("CORS")||pe.includes("cross-origin")||pe.includes("Access-Control-Allow-Origin")||pe.includes("Failed to fetch")||pe.includes("NetworkError")||pe.includes("TypeError")){T=!0;break}K<2&&await new Promise($n=>setTimeout($n,Math.pow(2,K)*1e3))}if(T){const K=new URL(d).hostname;kt(K);try{const ee=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(ee.type==="opaque")return ee}catch(ee){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,ee)}return new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(h&&(h.status!==0||h.type==="opaque"))break;C&&(w=C)}catch(C){w=C;continue}if(h&&(h.status!==0||h.type==="opaque"))break;c&&c.fallbackDomain&&p===0&&!u&&(de.add(c.hostname),on(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!h||h.status===0&&h.type!=="opaque"){let p="All fetch attempts failed";return c&&c.fallbackDomain&&(u?p=`备用域名${c.fallbackDomain}也失败了`:p=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${p}`,w),new Response("Image load failed after all attempts",{status:404,statusText:"Image Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*"}})}if(h.type==="opaque"){const p=new URL(e).hostname;return kt(p),h}if(h.ok){const d=await h.clone().blob(),b=d.size/(1024*1024),S=new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":h.headers.get("Content-Type")||"image/png","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*","Cache-Control":"max-age=3153600000","sw-cache-date":Date.now().toString(),"sw-image-size":d.size.toString()}});try{if(n.url.startsWith("http")){await i.put(n,S.clone()),await Vt(e,d.size,d.type),await wn();const{generateThumbnailAsync:C}=await Promise.resolve().then(()=>x);C(d,n.url,"image")}}catch(C){console.warn(`Service Worker: Failed to cache normal response (${b.toFixed(2)}MB, 可能超出存储限制):`,C),await an(i);try{if(n.url.startsWith("http")){await i.put(n,S.clone()),await Vt(e,d.size,d.type);const{generateThumbnailAsync:T}=await Promise.resolve().then(()=>x);T(d,n.url,"image")}}catch(T){console.error("Service Worker: Still failed to cache after cleanup:",T)}}return S}throw new Error(`HTTP ${h.status}: ${h.statusText}`)}catch(i){const a=new URL(e);return i.message.includes("SSL_PROTOCOL_ERROR")||i.message.includes("ERR_SSL_PROTOCOL_ERROR")||i.message.includes("net::ERR_CERT")||i.message.includes("ERR_INSECURE_RESPONSE")?(console.warn("Service Worker: 检测到SSL/证书错误,尝试跳过Service Worker处理"),fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit"}).catch(()=>new Response("SSL Error - Image not accessible",{status:404,statusText:"SSL Protocol Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}))):a.pathname.match(/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i)||a.searchParams.has("_t")||a.searchParams.has("cache_buster")||a.searchParams.has("timestamp")?new Response("Image not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}):new Response(`Network Error: ${i.message}`,{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})}}const D=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:U,IMAGE_CACHE_NAME:A,addConsoleLog:Ye,clearAllConsoleLogs:Bt,clearConsoleLogs:Ht,clearCrashSnapshots:zt,clearDebugLogs:xt,deleteCacheByUrl:tt,disableDebugMode:Ze,enableDebugMode:Je,getCDNStatusReport:_t,getCacheStats:$t,getCrashSnapshots:Ft,getDebugLogs:Qe,getDebugStatus:qt,getInternalFetchLogs:je,loadConsoleLogsFromDB:It,performHealthCheck:Lt,resetCDNStatus:At,saveCrashSnapshot:jt},Symbol.toStringTag,{value:"Module"})),Pe="drawnix-images-thumb",ts=128,rt=400,Rn=.8;function kn(n,e,t){const s=n/e;let r=t,o=t;return s>1?o=t/s:r=t*s,{width:Math.round(r),height:Math.round(o)}}function ot(n,e){try{let t;try{t=new URL(n)}catch{t=new URL(n,self.location.origin)}return t.searchParams.delete("thumbnail"),t.searchParams.set("_thumb",e),t.toString()}catch{const t=n.includes("?")?"&":"?";return`${n.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/,"")}${t}_thumb=${e}`}}async function ss(n,e,t=["small","large"]){try{for(const s of t)await Pn(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Pn(n,e,t){try{const s=t==="large"?rt:ts,r=ot(e,t),o=await caches.open(Pe);let i=await o.match(r);if(!i){const d=new Request(r,{method:"GET"});i=await o.match(d)}if(!i)try{const d=new URL(r);i=await o.match(d.pathname)}catch{}if(i||n.size===0)return;const a=(n.type||"").toLowerCase();if(!a.startsWith("image/")&&a!=="")return;let c;try{c=await createImageBitmap(n)}catch(d){if(d instanceof Error&&d.name==="InvalidStateError")return;throw d}const{width:l,height:u}=kn(c.width,c.height,s),h=new OffscreenCanvas(l,u),f=h.getContext("2d");if(!f){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{f.drawImage(c,0,0,l,u)}finally{c.close()}const m=await h.convertToBlob({type:"image/jpeg",quality:Rn}),w=()=>new Response(m,{headers:{"Content-Type":"image/jpeg","Content-Length":m.size.toString()}}),p=new Request(r,{method:"GET"});await o.put(p,w()),await o.put(r,w());try{const d=new URL(r);(d.pathname.startsWith("/__aitu_cache__/")||d.pathname.startsWith("/asset-library/"))&&await o.put(r,w())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function ns(n,e,t=["small","large"]){try{for(const s of t)await On(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function On(n,e,t){try{const s=ot(e,t),r=await caches.open(Pe);let o=await r.match(s);if(!o){const u=new Request(s,{method:"GET"});o=await r.match(u)}if(!o)try{const u=new URL(s);o=await r.match(u.pathname)}catch{}if(o)return;const a=await In(e,n,t==="large"?rt:ts);if(!a){console.warn(`[ThumbnailUtils] Failed to generate ${t} video thumbnail from main thread`);return}const c=()=>new Response(a,{headers:{"Content-Type":"image/jpeg","Content-Length":a.size.toString()}}),l=new Request(s,{method:"GET"});await r.put(l,c()),await r.put(s,c());try{const u=new URL(s);(u.pathname.startsWith("/__aitu_cache__/")||u.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function In(n,e,t=rt){const{getChannelManager:s}=await Promise.resolve().then(()=>Is),r=s();if(!r||r.getConnectedClientCount()===0)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const o=await r.requestVideoThumbnail(n,3e4);if(!o)return null;try{return await(await fetch(o)).blob()}catch(i){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",i),null}}async function at(n,e,t){try{const s=await caches.open(Pe),r=ot(n,e);let o=await s.match(r);if(!o){const i=new Request(r,{method:"GET"});o=await s.match(i)}if(!o&&t)for(const i of t){const a=await s.match(i);if(a){o=a;break}}return o||null}catch(s){return console.warn("[ThumbnailUtils] Error finding thumbnail:",s),null}}async function Wn(n,e,t){let s=await at(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await at(n,r,t),s?{response:s,size:r}:null}function Bn(n){return new Response(n,{status:200,headers:{"Content-Type":"image/jpeg","Content-Length":n.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}function Nn(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await ss(n,e,s):await ns(n,e,s)}catch(r){console.warn(`[ThumbnailUtils] Failed to generate ${t} thumbnail:`,r)}})()}const x=Object.freeze(Object.defineProperty({__proto__:null,IMAGE_CACHE_NAME_THUMB:Pe,createThumbnailResponse:Bn,findThumbnail:at,findThumbnailWithFallback:Wn,generateImageThumbnail:ss,generateThumbnailAsync:Nn,generateVideoThumbnail:ns},Symbol.toStringTag,{value:"Module"})),oe=[],qn="llm-api-logs",xn=4,F="logs";function Oe(){return new Promise((n,e)=>{const t=indexedDB.open(qn,xn);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result,o=s.oldVersion;let i;if(!r.objectStoreNames.contains(F))i=r.createObjectStore(F,{keyPath:"id"}),i.createIndex("timestamp","timestamp",{unique:!1}),i.createIndex("taskType","taskType",{unique:!1}),i.createIndex("status","status",{unique:!1}),i.createIndex("taskId","taskId",{unique:!1});else{const a=s.target.transaction;a&&(i=a.objectStore(F),o<4&&!i.indexNames.contains("taskId")&&(i.createIndex("taskId","taskId",{unique:!1}),console.log("[LLMApiLogger] Created taskId index during upgrade to v4")))}}})}async function rs(){try{const n=await Oe(),s=n.transaction(F,"readonly").objectStore(F).index("timestamp");return new Promise((r,o)=>{const i=s.getAll();i.onsuccess=()=>{n.close();const a=i.result.reverse();r(a)},i.onerror=()=>{n.close(),o(i.error)}})}catch(n){return console.warn("[LLMApiLogger] Failed to get logs from DB:",n),oe}}function Hn(n){return{id:n.id,timestamp:n.timestamp,endpoint:n.endpoint,model:n.model,taskType:n.taskType,taskId:n.taskId,prompt:n.prompt?n.prompt.length>200?n.prompt.substring(0,200)+"...":n.prompt:void 0,status:n.status,httpStatus:n.httpStatus,duration:n.duration,errorMessage:n.errorMessage,hasReferenceImages:n.hasReferenceImages,referenceImageCount:n.referenceImageCount,resultType:n.resultType,resultCount:n.resultCount,resultUrl:n.resultUrl}}async function Gn(n=1,e=20,t){let s=await rs();t!=null&&t.taskType&&(s=s.filter(c=>c.taskType===t.taskType)),t!=null&&t.status&&(s=s.filter(c=>c.status===t.status));const r=s.length,o=Math.ceil(r/e),i=(n-1)*e;return{logs:s.slice(i,i+e).map(Hn),total:r,page:n,pageSize:e,totalPages:o}}async function Un(n){const e=oe.find(t=>t.id===n);if(e)return e;try{const t=await Oe(),r=t.transaction(F,"readonly").objectStore(F);return new Promise((o,i)=>{const a=r.get(n);a.onsuccess=()=>{t.close(),o(a.result||null)},a.onerror=()=>{t.close(),i(a.error)}})}catch(t){return console.warn("[LLMApiLogger] Failed to get log by id:",t),null}}async function jn(){oe.length=0;try{const n=await Oe(),e=n.transaction(F,"readwrite");e.objectStore(F).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("[LLMApiLogger] Failed to clear logs from DB:",n)}}async function Fn(n){if(!n||n.length===0)return 0;const e=new Set(n),t=oe.length;for(let r=oe.length-1;r>=0;r--)e.has(oe[r].id)&&oe.splice(r,1);const s=t-oe.length;try{const r=await Oe(),o=r.transaction(F,"readwrite"),i=o.objectStore(F);for(const a of n)i.delete(a);await new Promise((a,c)=>{o.oncomplete=()=>{r.close(),a()},o.onerror=()=>{r.close(),c(o.error)}})}catch(r){console.warn("[LLMApiLogger] Failed to delete logs from DB:",r)}return s}function zn(n){}const ce=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:jn,deleteLLMApiLogs:Fn,getAllLLMApiLogs:rs,getLLMApiLogById:Un,getLLMApiLogsPaginated:Gn,setLLMApiLogBroadcast:zn},Symbol.toStringTag,{value:"Module"}));return E.APP_VERSION=U,E.IMAGE_CACHE_NAME=A,E.addConsoleLog=Ye,E.clearAllConsoleLogs=Bt,E.clearConsoleLogs=Ht,E.clearCrashSnapshots=zt,E.clearDebugLogs=xt,E.deleteCacheByUrl=tt,E.disableDebugMode=Ze,E.enableDebugMode=Je,E.getCDNStatusReport=_t,E.getCacheStats=$t,E.getCrashSnapshots=Ft,E.getDebugLogs=Qe,E.getDebugStatus=qt,E.getInternalFetchLogs=je,E.loadConsoleLogsFromDB=It,E.performHealthCheck=Lt,E.resetCDNStatus=At,E.saveCrashSnapshot=jt,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"}),E})({});
54
+ </html>`,{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}const ot=15e3,es=3e4;function ts(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function vn(){const n=Date.now(),e=[];if(B.forEach((t,s)=>{n-t.timestamp>Xs&&e.push(s)}),e.length>0&&e.forEach(t=>B.delete(t)),B.size>Pt){const t=Array.from(B.entries()).sort((o,i)=>o[1].timestamp-i[1].timestamp),s=B.size-Pt,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>B.delete(o))}}function Rn(){const n=Date.now(),e=[];H.forEach((s,r)=>{n-s.timestamp>es&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>H.delete(s)));const t=[];le.forEach((s,r)=>{n-s.timestamp>kt&&t.push(r)}),t.length>0&&t.forEach(s=>le.delete(s)),vn()}async function Mn(n){try{const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),r=t.searchParams.has("_retry"),o=t.searchParams.has("thumbnail")&&!s&&!r,i=o&&t.searchParams.get("thumbnail")||"small";["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","rand","_force","bypass_sw","direct_fetch","thumbnail"].forEach(f=>t.searchParams.delete(f));const c=new Request(t.toString(),{method:n.method,headers:n.headers,mode:n.mode,credentials:n.credentials}),l=t.toString();if(o){const{findThumbnailWithFallback:f,createThumbnailResponse:m}=await Promise.resolve().then(()=>x),b=await f(l,i,[c.url]);if(b){const p=await b.response.blob();return m(p)}}const u=le.get(l);if(u){if(Date.now()-u.timestamp<kt)return u.response.clone();le.delete(l)}if(H.has(l)){const f=H.get(l);if(f){const m=Date.now()-f.timestamp;if(m>es)console.warn(`Service Worker [${e}]: 发现过期的 pending 请求 (${m}ms),清理并重新发起:`,l),H.delete(l);else{f.count=(f.count||1)+1,f.duplicateRequestIds=f.duplicateRequestIds||[],f.duplicateRequestIds.push(e);try{const b=await ts(f.promise,ot,"Image request timeout");return b&&b.clone?b.clone():b}catch(b){if(b.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),H.delete(l),ss(n.url,e);throw b}}}}Rn();const h=kn(c,n.url,l,e,s,o?i:void 0);H.set(l,{promise:h,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),h.then(f=>{f&&f.ok&&le.set(l,{response:f.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{H.get(l)&&H.delete(l)});try{return await ts(h,ot,"Image request timeout")}catch(f){if(f.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${ot}ms),清理并返回超时响应让前端直接加载:`,n.url),H.delete(l),ss(n.url,e);throw f}}catch(e){throw e}}function ss(n,e){return new Response("Image request timeout - use direct load",{status:504,statusText:"Gateway Timeout",headers:{"Content-Type":"text/plain","X-SW-Timeout":"true","X-SW-Original-URL":n,"Access-Control-Allow-Origin":"*"}})}async function kn(n,e,t,s,r=!1,o){try{const i=await caches.open(A);if(!r){let p=await i.match(n);if(p||(p=await i.match(n.url)),p||(p=await i.match(t)),p){const w=await p.clone().blob();if(w.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await i.delete(n);else{if(o){const{generateThumbnailAsync:C}=await Promise.resolve().then(()=>x);C(w,n.url,"image")}const y=p.headers.get(ce);if(y){const C=Date.now(),T=p.headers.get(ge)||y,q=new Response(w,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),[ce]:C.toString(),[ge]:T}});return n.url.startsWith("http")&&await i.put(n,q.clone()),q}else{const C=new Response(w,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),[ce]:Date.now().toString(),[ge]:Date.now().toString()}});return n.url.startsWith("http")&&await i.put(n,C.clone()),C}}}}const a=new URL(e),c=jt(a);let l=null,u=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),fe.has(c.hostname)&&(u=!0));let h;const f=[{method:"GET",mode:"cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"},{method:"GET",cache:"no-cache"},{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"}];let m;u?m=[l]:(m=[e],l&&m.push(l));let b=null;for(let p=0;p<m.length;p++){const d=m[p],w=p>0;for(const y of f)try{let C,T=!1;for(let q=0;q<=2;q++)try{if(h=await fetch(d,y),h&&(h.status!==0||h.type==="opaque"))break}catch(ee){C=ee;const be=ee.message||"";if(be.includes("CORS")||be.includes("cross-origin")||be.includes("Access-Control-Allow-Origin")||be.includes("Failed to fetch")||be.includes("NetworkError")||be.includes("TypeError")){T=!0;break}q<2&&await new Promise(Kn=>setTimeout(Kn,Math.pow(2,q)*1e3))}if(T){const q=new URL(d).hostname;Ot(q);try{const ee=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(ee.type==="opaque")return ee}catch(ee){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,ee)}return new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(h&&(h.status!==0||h.type==="opaque"))break;C&&(b=C)}catch(C){b=C;continue}if(h&&(h.status!==0||h.type==="opaque"))break;c&&c.fallbackDomain&&p===0&&!u&&(fe.add(c.hostname),cn(c.hostname).catch(y=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",y)}))}if(!h||h.status===0&&h.type!=="opaque"){let p="All fetch attempts failed";return c&&c.fallbackDomain&&(u?p=`备用域名${c.fallbackDomain}也失败了`:p=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${p}`,b),new Response("Image load failed after all attempts",{status:404,statusText:"Image Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*"}})}if(h.type==="opaque"){const p=new URL(e).hostname;return Ot(p),h}if(h.ok){const d=await h.clone().blob(),w=d.size/(1024*1024),y=new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":h.headers.get("Content-Type")||"image/png","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*","Cache-Control":"max-age=3153600000",[ce]:Date.now().toString(),[ge]:Date.now().toString(),"sw-image-size":d.size.toString()}});try{if(n.url.startsWith("http")){await i.put(n,y.clone()),await Xt(e,d.size,d.type),await Sn();const{generateThumbnailAsync:C}=await Promise.resolve().then(()=>x);C(d,n.url,"image")}}catch(C){console.warn(`Service Worker: Failed to cache normal response (${w.toFixed(2)}MB, 可能超出存储限制):`,C),await ln(i);try{if(n.url.startsWith("http")){await i.put(n,y.clone()),await Xt(e,d.size,d.type);const{generateThumbnailAsync:T}=await Promise.resolve().then(()=>x);T(d,n.url,"image")}}catch(T){console.error("Service Worker: Still failed to cache after cleanup:",T)}}return y}throw new Error(`HTTP ${h.status}: ${h.statusText}`)}catch(i){const a=new URL(e);return i.message.includes("SSL_PROTOCOL_ERROR")||i.message.includes("ERR_SSL_PROTOCOL_ERROR")||i.message.includes("net::ERR_CERT")||i.message.includes("ERR_INSECURE_RESPONSE")?(console.warn("Service Worker: 检测到SSL/证书错误,尝试跳过Service Worker处理"),fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit"}).catch(()=>new Response("SSL Error - Image not accessible",{status:404,statusText:"SSL Protocol Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}))):a.pathname.match(/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i)||a.searchParams.has("_t")||a.searchParams.has("cache_buster")||a.searchParams.has("timestamp")?new Response("Image not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}):new Response(`Network Error: ${i.message}`,{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})}}const D=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:j,IMAGE_CACHE_NAME:A,addConsoleLog:Je,clearAllConsoleLogs:qt,clearConsoleLogs:Ut,clearCrashSnapshots:Vt,clearDebugLogs:Gt,deleteCacheByUrl:nt,disableDebugMode:tt,enableDebugMode:et,getCDNStatusReport:vt,getCacheStats:Kt,getCrashSnapshots:$t,getDebugLogs:Ze,getDebugStatus:xt,getInternalFetchLogs:ze,loadConsoleLogsFromDB:Bt,performHealthCheck:At,resetCDNStatus:Rt,saveCrashSnapshot:zt},Symbol.toStringTag,{value:"Module"})),Ie="drawnix-images-thumb",ns=128,at=400,Pn=.8;function On(n,e,t){const s=n/e;let r=t,o=t;return s>1?o=t/s:r=t*s,{width:Math.round(r),height:Math.round(o)}}function it(n,e){try{let t;try{t=new URL(n)}catch{t=new URL(n,self.location.origin)}return t.searchParams.delete("thumbnail"),t.searchParams.set("_thumb",e),t.toString()}catch{const t=n.includes("?")?"&":"?";return`${n.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/,"")}${t}_thumb=${e}`}}async function rs(n,e,t=["small","large"]){try{for(const s of t)await In(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function In(n,e,t){try{const s=t==="large"?at:ns,r=it(e,t),o=await caches.open(Ie);let i=await o.match(r);if(!i){const d=new Request(r,{method:"GET"});i=await o.match(d)}if(!i)try{const d=new URL(r);i=await o.match(d.pathname)}catch{}if(i||n.size===0)return;const a=(n.type||"").toLowerCase();if(!a.startsWith("image/")&&a!=="")return;let c;try{c=await createImageBitmap(n)}catch(d){if(d instanceof Error&&d.name==="InvalidStateError")return;throw d}const{width:l,height:u}=On(c.width,c.height,s),h=new OffscreenCanvas(l,u),f=h.getContext("2d");if(!f){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{f.drawImage(c,0,0,l,u)}finally{c.close()}const m=await h.convertToBlob({type:"image/jpeg",quality:Pn}),b=()=>new Response(m,{headers:{"Content-Type":"image/jpeg","Content-Length":m.size.toString()}}),p=new Request(r,{method:"GET"});await o.put(p,b()),await o.put(r,b());try{const d=new URL(r);(d.pathname.startsWith("/__aitu_cache__/")||d.pathname.startsWith("/asset-library/"))&&await o.put(r,b())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function os(n,e,t=["small","large"]){try{for(const s of t)await Wn(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function Wn(n,e,t){try{const s=it(e,t),r=await caches.open(Ie);let o=await r.match(s);if(!o){const u=new Request(s,{method:"GET"});o=await r.match(u)}if(!o)try{const u=new URL(s);o=await r.match(u.pathname)}catch{}if(o)return;const a=await Bn(e,n,t==="large"?at:ns);if(!a){console.warn(`[ThumbnailUtils] Failed to generate ${t} video thumbnail from main thread`);return}const c=()=>new Response(a,{headers:{"Content-Type":"image/jpeg","Content-Length":a.size.toString()}}),l=new Request(s,{method:"GET"});await r.put(l,c()),await r.put(s,c());try{const u=new URL(s);(u.pathname.startsWith("/__aitu_cache__/")||u.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function Bn(n,e,t=at){const{getChannelManager:s}=await Promise.resolve().then(()=>Bs),r=s();if(!r||r.getConnectedClientCount()===0)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const o=await r.requestVideoThumbnail(n,3e4);if(!o)return null;try{return await(await fetch(o)).blob()}catch(i){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",i),null}}async function ct(n,e,t){try{const s=await caches.open(Ie),r=it(n,e);let o=await s.match(r);if(!o){const i=new Request(r,{method:"GET"});o=await s.match(i)}if(!o&&t)for(const i of t){const a=await s.match(i);if(a){o=a;break}}return o||null}catch(s){return console.warn("[ThumbnailUtils] Error finding thumbnail:",s),null}}async function Nn(n,e,t){let s=await ct(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await ct(n,r,t),s?{response:s,size:r}:null}function qn(n){return new Response(n,{status:200,headers:{"Content-Type":"image/jpeg","Content-Length":n.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}function Hn(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await rs(n,e,s):await os(n,e,s)}catch(r){console.warn(`[ThumbnailUtils] Failed to generate ${t} thumbnail:`,r)}})()}const x=Object.freeze(Object.defineProperty({__proto__:null,IMAGE_CACHE_NAME_THUMB:Ie,createThumbnailResponse:qn,findThumbnail:ct,findThumbnailWithFallback:Nn,generateImageThumbnail:rs,generateThumbnailAsync:Hn,generateVideoThumbnail:os},Symbol.toStringTag,{value:"Module"})),oe=[],xn="llm-api-logs",Gn=4,z="logs";function We(){return new Promise((n,e)=>{const t=indexedDB.open(xn,Gn);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result,o=s.oldVersion;let i;if(!r.objectStoreNames.contains(z))i=r.createObjectStore(z,{keyPath:"id"}),i.createIndex("timestamp","timestamp",{unique:!1}),i.createIndex("taskType","taskType",{unique:!1}),i.createIndex("status","status",{unique:!1}),i.createIndex("taskId","taskId",{unique:!1});else{const a=s.target.transaction;a&&(i=a.objectStore(z),o<4&&!i.indexNames.contains("taskId")&&(i.createIndex("taskId","taskId",{unique:!1}),console.log("[LLMApiLogger] Created taskId index during upgrade to v4")))}}})}async function as(){try{const n=await We(),s=n.transaction(z,"readonly").objectStore(z).index("timestamp");return new Promise((r,o)=>{const i=s.getAll();i.onsuccess=()=>{n.close();const a=i.result.reverse();r(a)},i.onerror=()=>{n.close(),o(i.error)}})}catch(n){return console.warn("[LLMApiLogger] Failed to get logs from DB:",n),oe}}function Un(n){return{id:n.id,timestamp:n.timestamp,endpoint:n.endpoint,model:n.model,taskType:n.taskType,taskId:n.taskId,prompt:n.prompt?n.prompt.length>200?n.prompt.substring(0,200)+"...":n.prompt:void 0,status:n.status,httpStatus:n.httpStatus,duration:n.duration,errorMessage:n.errorMessage,hasReferenceImages:n.hasReferenceImages,referenceImageCount:n.referenceImageCount,resultType:n.resultType,resultCount:n.resultCount,resultUrl:n.resultUrl}}async function jn(n=1,e=20,t){let s=await as();t!=null&&t.taskType&&(s=s.filter(c=>c.taskType===t.taskType)),t!=null&&t.status&&(s=s.filter(c=>c.status===t.status));const r=s.length,o=Math.ceil(r/e),i=(n-1)*e;return{logs:s.slice(i,i+e).map(Un),total:r,page:n,pageSize:e,totalPages:o}}async function Fn(n){const e=oe.find(t=>t.id===n);if(e)return e;try{const t=await We(),r=t.transaction(z,"readonly").objectStore(z);return new Promise((o,i)=>{const a=r.get(n);a.onsuccess=()=>{t.close(),o(a.result||null)},a.onerror=()=>{t.close(),i(a.error)}})}catch(t){return console.warn("[LLMApiLogger] Failed to get log by id:",t),null}}async function zn(){oe.length=0;try{const n=await We(),e=n.transaction(z,"readwrite");e.objectStore(z).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{n.close(),s()},e.onerror=()=>{n.close(),r(e.error)}})}catch(n){console.warn("[LLMApiLogger] Failed to clear logs from DB:",n)}}async function $n(n){if(!n||n.length===0)return 0;const e=new Set(n),t=oe.length;for(let r=oe.length-1;r>=0;r--)e.has(oe[r].id)&&oe.splice(r,1);const s=t-oe.length;try{const r=await We(),o=r.transaction(z,"readwrite"),i=o.objectStore(z);for(const a of n)i.delete(a);await new Promise((a,c)=>{o.oncomplete=()=>{r.close(),a()},o.onerror=()=>{r.close(),c(o.error)}})}catch(r){console.warn("[LLMApiLogger] Failed to delete logs from DB:",r)}return s}function Vn(n){}const ue=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:zn,deleteLLMApiLogs:$n,getAllLLMApiLogs:as,getLLMApiLogById:Fn,getLLMApiLogsPaginated:jn,setLLMApiLogBroadcast:Vn},Symbol.toStringTag,{value:"Module"}));return E.APP_VERSION=j,E.IMAGE_CACHE_NAME=A,E.addConsoleLog=Je,E.clearAllConsoleLogs=qt,E.clearConsoleLogs=Ut,E.clearCrashSnapshots=Vt,E.clearDebugLogs=Gt,E.deleteCacheByUrl=nt,E.disableDebugMode=tt,E.enableDebugMode=et,E.getCDNStatusReport=vt,E.getCacheStats=Kt,E.getCrashSnapshots=$t,E.getDebugLogs=Ze,E.getDebugStatus=xt,E.getInternalFetchLogs=ze,E.loadConsoleLogsFromDB=Bt,E.performHealthCheck=At,E.resetCDNStatus=Rt,E.saveCrashSnapshot=zt,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"}),E})({});