aitu-app 0.6.21 → 0.6.22

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 (144) hide show
  1. package/README.md +3 -3
  2. package/assets/{ChatMessagesArea-Bc7FkjZo.js → ChatMessagesArea-63H9tZtG.js} +3 -3
  3. package/assets/{KnowledgeBaseContent-BLIcG9KK.js → KnowledgeBaseContent-5j70f-FP.js} +4 -4
  4. package/assets/{ModelBenchmarkWorkbench-CGztJD2j.js → ModelBenchmarkWorkbench-OdGWsh0T.js} +1 -1
  5. package/assets/{ResizableDivider-DfqWs8LM.js → ResizableDivider-DUn2YRJi.js} +1 -1
  6. package/assets/{ToolboxDrawer-B9g_w8pc.js → ToolboxDrawer-DDAFUdNA.js} +1 -1
  7. package/assets/{VideoAnalyzer-KdlQiqKF.js → VideoAnalyzer-C7mAfG_a.js} +1 -1
  8. package/assets/{ai-analyze-D51W4jnj.js → ai-analyze-CJsLcVP0.js} +1 -1
  9. package/assets/{arc-DVIrWwbE.js → arc-BwiBrwsC.js} +1 -1
  10. package/assets/{arc-BqtXmYwJ.js → arc-bU0RTLO_.js} +1 -1
  11. package/assets/{batch-image-generation-DEC8rrCP.js → batch-image-generation-se7md6Xz.js} +1 -1
  12. package/assets/{blockDiagram-38ab4fdb-BgPS1CyJ.js → blockDiagram-38ab4fdb-C-J430-U.js} +1 -1
  13. package/assets/{blockDiagram-38ab4fdb-CMoyjTgm.js → blockDiagram-38ab4fdb-CRlC08-f.js} +1 -1
  14. package/assets/{c4Diagram-3d4e48cf-wjCA-CL-.js → c4Diagram-3d4e48cf-CZXHUfLE.js} +1 -1
  15. package/assets/{c4Diagram-3d4e48cf-CIeKmCwa.js → c4Diagram-3d4e48cf-CjnnPMdb.js} +1 -1
  16. package/assets/channel-C0300EYS.js +1 -0
  17. package/assets/channel-CFKYr4PJ.js +1 -0
  18. package/assets/{classDiagram-70f12bd4-vizVZzUd.js → classDiagram-70f12bd4-CHHFCLtW.js} +1 -1
  19. package/assets/{classDiagram-70f12bd4-DfTNrA1t.js → classDiagram-70f12bd4-Cka5pz9E.js} +1 -1
  20. package/assets/{classDiagram-v2-f2320105-LutY6jPP.js → classDiagram-v2-f2320105-BoY5QpGK.js} +1 -1
  21. package/assets/{classDiagram-v2-f2320105-DO7izSAk.js → classDiagram-v2-f2320105-DhMOYQPM.js} +1 -1
  22. package/assets/{clipper-D3zP18nj.js → clipper-ZDte_DyN.js} +1 -1
  23. package/assets/clone-B4wQMor7.js +1 -0
  24. package/assets/clone-DTNvy75S.js +1 -0
  25. package/assets/{createText-2e5e7dd3-CtWg9f_f.js → createText-2e5e7dd3-CouAisK8.js} +1 -1
  26. package/assets/{createText-2e5e7dd3-iSllMU05.js → createText-2e5e7dd3-DQiR2iFi.js} +1 -1
  27. package/assets/{edges-e0da2a9e-B8N3S4AD.js → edges-e0da2a9e-D5w5n92i.js} +1 -1
  28. package/assets/{edges-e0da2a9e-B9APkBSa.js → edges-e0da2a9e-dJImi3XC.js} +1 -1
  29. package/assets/{erDiagram-9861fffd-Dnp1WpmL.js → erDiagram-9861fffd-9WI5iVS2.js} +1 -1
  30. package/assets/{erDiagram-9861fffd-B1x-ZWfU.js → erDiagram-9861fffd-IyJNqdw_.js} +1 -1
  31. package/assets/{flowDb-956e92f1-BT8eaBZE.js → flowDb-956e92f1-DltT8K-M.js} +1 -1
  32. package/assets/{flowDb-956e92f1-5caTHN1T.js → flowDb-956e92f1-FUMkFpNV.js} +1 -1
  33. package/assets/{flowDiagram-66a62f08-B5xcjVie.js → flowDiagram-66a62f08-Dbc4Nx93.js} +1 -1
  34. package/assets/{flowDiagram-66a62f08-Cx_V_MoA.js → flowDiagram-66a62f08-nXDkz0Ug.js} +1 -1
  35. package/assets/flowDiagram-v2-96b9c2cf-BVOhfZw2.js +1 -0
  36. package/assets/flowDiagram-v2-96b9c2cf-j5LlfdZR.js +1 -0
  37. package/assets/{flowchart-elk-definition-4a651766-Cjgywupa.js → flowchart-elk-definition-4a651766-B6rzHwEw.js} +1 -1
  38. package/assets/{flowchart-elk-definition-4a651766-CwIA9l-O.js → flowchart-elk-definition-4a651766-gZ7Jh0C4.js} +1 -1
  39. package/assets/{ganttDiagram-c361ad54-6zSjhOJy.js → ganttDiagram-c361ad54-B9Sd11GI.js} +1 -1
  40. package/assets/{ganttDiagram-c361ad54-oySKvDa4.js → ganttDiagram-c361ad54-CItnWrDi.js} +1 -1
  41. package/assets/{gitGraphDiagram-72cf32ee-BK7TWB1s.js → gitGraphDiagram-72cf32ee-CYyEomwm.js} +1 -1
  42. package/assets/{gitGraphDiagram-72cf32ee-BnNAY3pp.js → gitGraphDiagram-72cf32ee-Dd5nG_11.js} +1 -1
  43. package/assets/{graph-B_MH2EY9.js → graph-BHlg4sFb.js} +1 -1
  44. package/assets/{graph-BPS27gwv.js → graph-Cy6oe2k_.js} +1 -1
  45. package/assets/{grid-image-DLa8OQhL.js → grid-image-C-msrN1B.js} +1 -1
  46. package/assets/{has-D0S1Zmzg.js → has-CWNO02CD.js} +1 -1
  47. package/assets/{hasIn-De9yBkgj.js → hasIn-Bs6kQ8q7.js} +1 -1
  48. package/assets/{index-3862675e-FzFTrzJW.js → index-3862675e-BKpqGoRu.js} +1 -1
  49. package/assets/{index-3862675e-D6LCgHcS.js → index-3862675e-DsPsD_QS.js} +1 -1
  50. package/assets/{index-T5OF1JP4.js → index-B-A2026m.js} +1 -1
  51. package/assets/{index-Bjr6SLmW.js → index-BC5aP94k.js} +1 -1
  52. package/assets/{index-Cb_6lq4r.js → index-BEFGFeiI.js} +1 -1
  53. package/assets/{index-Dgs_9LtJ.js → index-BTRvm9gy.js} +1 -1
  54. package/assets/{index-B8Cp8ZAq.js → index-B_ECxmtW.js} +1 -1
  55. package/assets/{index-CGUpUzSI.js → index-BcM3gyCR.js} +1 -1
  56. package/assets/{index-Ia_xKhIZ.js → index-BdH171U0.js} +5 -5
  57. package/assets/{index-sARZWo5n.js → index-Br38Ej3g.js} +1 -1
  58. package/assets/{index-CU-f8hlX.js → index-C-wf0YcU.js} +1 -1
  59. package/assets/{index-Ctlb8bi0.js → index-C1X4nHa1.js} +1 -1
  60. package/assets/{index-Br6iEGLw.js → index-CCzr4Dqs.js} +1 -1
  61. package/assets/{index-DYQtOpt_.js → index-CMfdA3Eb.js} +1 -1
  62. package/assets/{index-B1Qj7KmK.js → index-CRvF4JAy.js} +1 -1
  63. package/assets/{index-GP_0iNEx.js → index-CUYzOOe1.js} +1 -1
  64. package/assets/{index-rrHZbeHC.js → index-CnVvluBH.js} +1 -1
  65. package/assets/{index-Ddc6oDDk.js → index-D4JTX52h.js} +1 -1
  66. package/assets/{index-BdrYk4gf.js → index-DB9eHDVM.js} +1 -1
  67. package/assets/{index-DFgRlr0t.js → index-DGVrURNm.js} +1 -1
  68. package/assets/{index-CG_qIHbM.js → index-Dczi3BkD.js} +1 -1
  69. package/assets/{index-CSxjkKUk.js → index-DtJW2qel.js} +1 -1
  70. package/assets/{index-6opHRfWl.js → index-DysS6hq1.js} +1 -1
  71. package/assets/{index-C6mW2Bug.js → index-KJVd0B2z.js} +1 -1
  72. package/assets/{index-BIv91qW9.js → index-T9dstNa6.js} +16 -16
  73. package/assets/{index-B3GMIqjJ.js → index-TQu9hYF9.js} +1 -1
  74. package/assets/{index-CAghokCh.js → index-Y5c26X-0.js} +1 -1
  75. package/assets/{index-BR5Ge2w3.js → index-YBixVTkA.js} +1 -1
  76. package/assets/{index-CqeciDtE.js → index-ZRpcXeUi.js} +1 -1
  77. package/assets/{index-DUFh_idy.js → index-byQfZx9Y.js} +1 -1
  78. package/assets/{index-DJhDtQwz.js → index-hmLPqXUT.js} +1 -1
  79. package/assets/{index-BUde8Mm7.js → index-iDwZIVzi.js} +1 -1
  80. package/assets/{index-B_TY0tLT.js → index-sRNe5iWo.js} +1 -1
  81. package/assets/{index-CoNiRHcD.js → index-w0J-N3Bz.js} +1 -1
  82. package/assets/{index-CIsTR1zp.js → index-xSQSiTqU.js} +1 -1
  83. package/assets/{infoDiagram-f8f76790-C5lK_OdP.js → infoDiagram-f8f76790-D3aFK43x.js} +1 -1
  84. package/assets/{infoDiagram-f8f76790-DqxLIqvx.js → infoDiagram-f8f76790-plyhvVln.js} +1 -1
  85. package/assets/{inspiration-board-DELLwhlH.js → inspiration-board-WeHubIbH.js} +1 -1
  86. package/assets/{isEmpty-DF_ugZHw.js → isEmpty-DZgnI1Gi.js} +1 -1
  87. package/assets/{journeyDiagram-49397b02-f6bVwxyz.js → journeyDiagram-49397b02-BUEu9YZl.js} +1 -1
  88. package/assets/{journeyDiagram-49397b02-BJ9tbMfk.js → journeyDiagram-49397b02-CJLyWjZc.js} +1 -1
  89. package/assets/{layers-DAOrLzwi.js → layers-BZ-h9vGA.js} +1 -1
  90. package/assets/{layout-yMh6DKYs.js → layout-CB3iLEN-.js} +1 -1
  91. package/assets/{layout-fmUyEip8.js → layout-CfIv6ys6.js} +1 -1
  92. package/assets/{line-DANa88VO.js → line-Cl2IINpY.js} +1 -1
  93. package/assets/{line-DXiCFjwk.js → line-DEMH00tR.js} +1 -1
  94. package/assets/{linear-5iY8Cy-H.js → linear-CAlPBLIZ.js} +1 -1
  95. package/assets/{linear-ctDXkzM_.js → linear-CYligRij.js} +1 -1
  96. package/assets/{mermaid.core-Dgk12NKe.js → mermaid.core-HRa8_3iy.js} +5 -5
  97. package/assets/{mindmap-definition-fc14e90a-C7BlMhzr.js → mindmap-definition-fc14e90a-BE_BelNq.js} +1 -1
  98. package/assets/{mindmap-definition-fc14e90a-DLlf6Rx9.js → mindmap-definition-fc14e90a-BjEfE1ER.js} +1 -1
  99. package/assets/{model-benchmark-launcher-fleyPbmY.js → model-benchmark-launcher-DGhnqUWi.js} +1 -1
  100. package/assets/{photo-wall-splitter-xpPO2k5T.js → photo-wall-splitter-CEBkekUS.js} +1 -1
  101. package/assets/{pick-VCZntyna.js → pick-BDzXufGU.js} +1 -1
  102. package/assets/{pieDiagram-8a3498a8-BBnaNSJ-.js → pieDiagram-8a3498a8-BOz79K-l.js} +1 -1
  103. package/assets/{pieDiagram-8a3498a8-BvSfbq65.js → pieDiagram-8a3498a8-BXg1_0zb.js} +1 -1
  104. package/assets/{quadrantDiagram-120e2f19-Bnh-DNQv.js → quadrantDiagram-120e2f19-BNSax4Yv.js} +1 -1
  105. package/assets/{quadrantDiagram-120e2f19-Cm8pCCM5.js → quadrantDiagram-120e2f19-BW0c6246.js} +1 -1
  106. package/assets/{requirementDiagram-deff3bca-CDm-DECv.js → requirementDiagram-deff3bca-BdKQCBBh.js} +1 -1
  107. package/assets/{requirementDiagram-deff3bca-DMRUc1cx.js → requirementDiagram-deff3bca-DLC9wibM.js} +1 -1
  108. package/assets/{sankeyDiagram-04a897e0-CXC5R9JG.js → sankeyDiagram-04a897e0-gzh6unx3.js} +1 -1
  109. package/assets/{sankeyDiagram-04a897e0-BMtXJIXg.js → sankeyDiagram-04a897e0-mnwYvtIk.js} +1 -1
  110. package/assets/{sequenceDiagram-704730f1-D42qglAv.js → sequenceDiagram-704730f1-9WzL_6Og.js} +1 -1
  111. package/assets/{sequenceDiagram-704730f1-CNMmBUQx.js → sequenceDiagram-704730f1-CPrfOGmY.js} +1 -1
  112. package/assets/{settings-dialog-2ODvctTh.js → settings-dialog-DKi0S3Fj.js} +1 -1
  113. package/assets/{shard-sync-service-D3USLllH.js → shard-sync-service-DMBoL8-S.js} +1 -1
  114. package/assets/{stateDiagram-587899a1-DqPLyMub.js → stateDiagram-587899a1-D0lAIKBU.js} +1 -1
  115. package/assets/{stateDiagram-587899a1-DsEPR5ou.js → stateDiagram-587899a1-DHfaNuxL.js} +1 -1
  116. package/assets/{stateDiagram-v2-d93cdb3a-DrlPKA21.js → stateDiagram-v2-d93cdb3a-BW2UOJGd.js} +1 -1
  117. package/assets/{stateDiagram-v2-d93cdb3a-Bf_7sDs_.js → stateDiagram-v2-d93cdb3a-BkSMcdnU.js} +1 -1
  118. package/assets/{styles-6aaf32cf-YHAPMNO9.js → styles-6aaf32cf-BzV4m8wn.js} +1 -1
  119. package/assets/{styles-6aaf32cf-Bj2sDHb0.js → styles-6aaf32cf-DbLx1dQP.js} +1 -1
  120. package/assets/{styles-9a916d00-7jELss6_.js → styles-9a916d00-BWvAJ5en.js} +1 -1
  121. package/assets/{styles-9a916d00-CZUDnhpb.js → styles-9a916d00-DfAvsjKD.js} +1 -1
  122. package/assets/{styles-c10674c1-DC9073pI.js → styles-c10674c1-CeFiajQK.js} +1 -1
  123. package/assets/{styles-c10674c1-DLuj745u.js → styles-c10674c1-DOM3WQ5r.js} +1 -1
  124. package/assets/{svgDrawCommon-08f97a94-CrWF0HaY.js → svgDrawCommon-08f97a94-BVgqbMeh.js} +1 -1
  125. package/assets/{svgDrawCommon-08f97a94-D2AO9i1k.js → svgDrawCommon-08f97a94-BlKKsIl4.js} +1 -1
  126. package/assets/{timeline-definition-85554ec2-leTEuD1Q.js → timeline-definition-85554ec2-9aW1_D2N.js} +1 -1
  127. package/assets/{timeline-definition-85554ec2-7KS0GPh6.js → timeline-definition-85554ec2-DzpdYs0t.js} +1 -1
  128. package/assets/ttd-dialog-DEnnfHyO.js +115 -0
  129. package/assets/{upload-CQNwOcX2.js → upload-DNNZ8L4F.js} +1 -1
  130. package/assets/{video-recovery-service-BQIopXWm.js → video-recovery-service-CbVWiAGn.js} +1 -1
  131. package/assets/{xychartDiagram-e933f94c-BCEY4mIx.js → xychartDiagram-e933f94c-DNl2ns7z.js} +1 -1
  132. package/assets/{xychartDiagram-e933f94c-B_6b1Ojq.js → xychartDiagram-e933f94c-d54TQLOU.js} +1 -1
  133. package/changelog.json +13 -0
  134. package/package.json +1 -1
  135. package/precache-manifest.json +277 -277
  136. package/sw.js +1 -1
  137. package/version.json +3 -7
  138. package/assets/channel-Ckduo0Rh.js +0 -1
  139. package/assets/channel-DXN87Isu.js +0 -1
  140. package/assets/clone-CuD87pDT.js +0 -1
  141. package/assets/clone-DOLqw3Mb.js +0 -1
  142. package/assets/flowDiagram-v2-96b9c2cf-BaJg3X7e.js +0 -1
  143. package/assets/flowDiagram-v2-96b9c2cf-bslUZjmZ.js +0 -1
  144. package/assets/ttd-dialog-DZzhIaYG.js +0 -115
package/sw.js CHANGED
@@ -1,4 +1,4 @@
1
- var sw=(function(E){"use strict";var ie=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(ie||{});ie.IMAGE+"",ie.VIDEO+"",ie.AUDIO+"",ie.CHARACTER+"",ie.INSPIRATION_BOARD+"",ie.CHAT+"";function dt(n){return n instanceof Error?n.name||"Error":"Unknown error"}const xe="sw-task-queue",gt=3,T="tasks",G="config",O="workflows",P="chat-workflows",v="pending-tool-requests",R="pending-dom-operations",I="task-step-mappings",U="pending-canvas-operations",ds=[T,G,O,P,v,R,I,U];function gs(){return new Promise(n=>{const e=indexedDB.open(xe);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,gt))},e.onerror=()=>{n(gt)}})}function fs(n){const e=[];for(const t of ds)n.objectStoreNames.contains(t)||e.push(t);return e}function ps(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(xe,s);r.onerror=()=>{console.error("[SWStorage] Failed to repair DB:",r.error),t(r.error)},r.onsuccess=()=>{e(r.result)},r.onupgradeneeded=o=>{const a=o.target.result;ft(a)}})}function ft(n){if(!n.objectStoreNames.contains(T)){const e=n.createObjectStore(T,{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(O)){const e=n.createObjectStore(O,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(P)){const e=n.createObjectStore(P,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(v)||n.createObjectStore(v,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(R)){const e=n.createObjectStore(R,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(I)||n.createObjectStore(I,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains(U)||n.createObjectStore(U,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function ms(){const n=await gs();return new Promise((e,t)=>{const s=indexedDB.open(xe,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=fs(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),ps(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;ft(o)}})}class bs{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=ms()),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 a=s.transaction(T,"readwrite"),i=a.objectStore(T);for(const c of e)i.put(c);a.oncomplete=()=>{t.forEach(({resolve:c})=>c()),r()},a.onerror=()=>{const c=a.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(T,"readwrite").objectStore(T).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 i=t.transaction(T,"readonly").objectStore(T).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 a=e.transaction(T,"readonly").objectStore(T).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(T,"readonly").objectStore(T).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:a="desc"}=e;try{const i=await this.getDB();return new Promise((c,l)=>{const d=i.transaction(T,"readonly").objectStore(T).index("createdAt"),m=a==="desc"?"prev":"next",b=d.openCursor(null,m),p=[];let g=0,w=0;b.onerror=()=>l(b.error),b.onsuccess=S=>{const C=S.target.result;if(!C){c({tasks:p,total:w,hasMore:w>t+p.length});return}const L=C.value,N=!r||L.status===r,te=!o||L.type===o;N&&te&&(w++,g<t?g++:p.length<s&&p.push(L)),C.continue()}})}catch(i){return console.error("[SWStorage] Failed to get paginated tasks:",i),{tasks:[],total:0,hasMore:!1}}}async deleteTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(T,"readwrite").objectStore(T).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(G,"readonly").objectStore(G).get(e);i.onsuccess=()=>{const c=i.result;if(!c){s(null);return}const{key:l,...u}=c;s(u)},i.onerror=()=>r(i.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",dt(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const a=s.transaction(G,"readwrite");a.objectStore(G).put({key:e,...t,updatedAt:Date.now()}),a.oncomplete=()=>r(),a.onerror=()=>o(a.error)})}catch(s){throw console.error("[SWStorage] Failed to save config:",dt(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 a=e.transaction(G,"readonly").objectStore(G).get("systemPrompt");a.onsuccess=()=>{const i=a.result;t((i==null?void 0:i.value)||null)},a.onerror=()=>s(a.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 i=t.transaction(O,"readwrite").objectStore(O).put(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(O,"readonly").objectStore(O).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 a=e.transaction(O,"readonly").objectStore(O).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(O,"readonly").objectStore(O).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 i=t.transaction(O,"readwrite").objectStore(O).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(P,"readwrite").objectStore(P).put(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(P,"readonly").objectStore(P).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 a=e.transaction(P,"readonly").objectStore(P).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(P,"readonly").objectStore(P).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 i=t.transaction(P,"readwrite").objectStore(P).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(v,"readwrite").objectStore(v).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(v,"readonly").objectStore(v).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(v,"readonly").objectStore(v).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 i=t.transaction(v,"readonly").objectStore(v).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 i=t.transaction(v,"readwrite").objectStore(v).delete(e);i.onerror=()=>r(i.error),i.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.getDB(),s=Date.now()-e;return new Promise((r,o)=>{const a=t.transaction(v,"readwrite"),c=a.objectStore(v).openCursor();let l=0;c.onsuccess=()=>{const u=c.result;u&&(u.value.createdAt<s&&(u.delete(),l++),u.continue())},a.oncomplete=()=>{l>0&&console.log(`[SWStorage] Cleaned up ${l} stale pending tool requests`),r(l)},a.onerror=()=>o(a.error)})}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 i=t.transaction(R,"readwrite").objectStore(R).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(R,"readonly").objectStore(R).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(R,"readonly").objectStore(R).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(R,"readonly").objectStore(R).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 i=t.transaction(R,"readonly").objectStore(R).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 i=t.transaction(R,"readwrite").objectStore(R).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(I,"readwrite").objectStore(I).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(I,"readonly").objectStore(I).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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 i=t.transaction(I,"readonly").objectStore(I).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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(I,"readonly").objectStore(I).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 i=t.transaction(I,"readwrite").objectStore(I).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(U,"readwrite").objectStore(U).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(U,"readonly").objectStore(U).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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 i=t.transaction(U,"readwrite").objectStore(U).delete(e);i.onerror=()=>r(i.error),i.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)}}async archiveOldTasks(e=100){try{const t=await this.getDB(),s=await new Promise((c,l)=>{const d=t.transaction(T,"readonly").objectStore(T).index("createdAt"),m=[],b=d.openCursor(null,"next");b.onsuccess=()=>{const p=b.result;if(!p){c(m);return}const g=p.value;g.archived||m.push(g),p.continue()},b.onerror=()=>l(b.error)}),r=s.length-e;if(r<=0)return 0;const o=["completed","failed","cancelled"],a=s.filter(c=>o.includes(c.status)).slice(0,r);if(a.length===0)return 0;const i=Date.now();return new Promise((c,l)=>{const u=t.transaction(T,"readwrite"),h=u.objectStore(T);for(const d of a)d.archived=!0,d.updatedAt=i,h.put(d);u.oncomplete=()=>{console.log(`[SWStorage] Archived ${a.length} old tasks`),c(a.length)},u.onerror=()=>l(u.error)})}catch(t){return console.error("[SWStorage] Failed to archive old tasks:",t),0}}}const pt=new bs,ws=["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();ws.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Ne(s)}return e}return n}let Te=!1;const ys=500,se=[];let qe=0;function mt(){return Te}const bt=["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 wt(n){const e=Te;Te=n,!n&&e&&(se.length=0,we.clear(),qe=0)}function He(){return Te}function Ss(n){if(!mt()||n==="unknown"||bt.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)),bt.includes(e))return!1}return!0}function Cs(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 Ge(n,e,t,s,r){if(r||!Ss(n))return"";const o=Cs(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++qe}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:yt(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Es(i),Ds(n)){const c=Ls(e);c&&we.set(c,{entry:i,startTime:Date.now()})}return a}function Es(n){se.unshift(n),se.length>ys&&se.pop()}function Ue(n,e,t,s){if(!mt())return"";const r=we.get(n);if(r){r.entry.response=yt(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return we.delete(n),o}return""}function De(){return[...se]}function Ts(){se.length=0,we.clear(),qe=0}function Ds(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 Ls(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function yt(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return Ne(e)}catch{return"[Non-serializable data]"}}function _s(){const n={total:se.length,sent:0,received:0,byType:{}};for(const e of se)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const je=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Ts,getAllLogs:De,getLogStats:_s,isPostMessageLoggerDebugMode:He,logReceivedMessage:Ge,setPostMessageLoggerDebugMode:wt,updateRequestWithResponse:Ue},Symbol.toStringTag,{value:"Module"}));function As(){return typeof window<"u"?window:typeof self<"u"?self:{}}function vs(n){return JSON.parse(JSON.stringify(n))}function St(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 Rs="postmessage-duplex",Ms="1.2.0",Le=As();var $,ne;Le.__POSTMESSAGE_DUPLEX__||(Le.__POSTMESSAGE_DUPLEX__={}),Le.__POSTMESSAGE_DUPLEX__.version=Ms,Le.__POSTMESSAGE_DUPLEX__.name=Rs,(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"})(ne||(ne={}));class re 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,re)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class ks{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 Os{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 Ps{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 Ct(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const X=n=>({valid:0,error:n});function Is(n){if(!Ct(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(a=e.ret)=="number"&&Object.values($).includes(a)?"data"in e&&e.data!==void 0&&!Ct(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 a}function _e(n){return"ret"in n&&typeof n.ret=="number"}function Ws(n){return n.msg==="ready"}function Bs(n){return n._broadcast==1&&typeof n.cmdname=="string"}function xs(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const Fe=[],Y=[];function Et(n){Y.length>=200&&Y.shift(),Y.push(n)}function Tt(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 Ns extends Ps{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 ks,this.rateLimiter=new Os((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,Fe.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{Et({direction:"send",cmdname:s,requestId:r,status:"pending",timestamp:Date.now(),dataSummary:""})}),t.on("message:received",({cmdname:s,requestId:r,isResponse:o})=>{const a=s||"",i=r||"";o?Tt(i,"ok"):Et({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{Tt(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=xs(e);if(t>this.maxMessageSize){const s=new re(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ne.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):_e(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=Is(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:_e(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(!Bs(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 a=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:$.ReceiverCallbackError,msg:a||"unknown error"}),this.emit("error",{error:o instanceof Error?o:new Error(a),context:`handler:${s}`})}return 1}handleReadyMessage(e,t){if(!Ws(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}),_e(e)||this.sendMessage({requestId:t,ret:$.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!_e(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 re("Cannot publish: channel has been destroyed",ne.ConnectionDestroyed,{cmdname:e}));const r=this.baseKey+ ++this.reqTime,o={requestId:r,cmdname:e,data:t};this.requestCmdMap.set(r,e);const a=new Promise((i,c)=>{this.callbackMap.set(r,{resolve:i,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:a,options:s}),a}doPublish(e,t){const{requestId:s,cmdname:r}=e,o=(t==null?void 0:t.timeout)??this.timeout;this.timeoutManager.add(s,o,()=>{const a=this.callbackMap.get(s);if(a){const i={req:e,requestId:s,ret:$.TimeOut,time:Date.now(),msg:"timeout"};this.log("error","postmessage timeout",i),this.emit("timeout",{requestId:s,cmdname:r,timeoutMs:o}),a.resolve(i),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=Fe.findIndex(r=>r.deref()===t);s!==-1&&Fe.splice(s,1)})(this);const e=new re("Channel has been destroyed",ne.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 a=this.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}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,a]of this.channelsByClientId)r.has(o)||(a.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 a of r){if(s&&a.id===s)continue;const i=this.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",a.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 a=0;for(const i of o){if(r&&i.id===r)continue;const c=this.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=this.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(u){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,u)}}return a}catch(o){return console.error("[ServiceWorkerHub] broadcastToType error:",o),0}}}Object.defineProperty(V,"instance",{enumerable:1,configurable:1,writable:1,value:null});class f extends Ns{static enableGlobalRouting(e){f.useGlobalRouting=1,f.unknownClientCallback=e??null,f.globalListenerSetup||(self.addEventListener("message",f.globalMessageHandler),f.globalListenerSetup=1)}static disableGlobalRouting(){f.useGlobalRouting=0,f.globalListenerSetup&&(self.removeEventListener("message",f.globalMessageHandler),f.globalListenerSetup=0)}static setupHub(e={}){if(f.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");f.hubOptions=e,f.hubInitialized=1,V.getInstance().setup(e,s=>f.createFromWorker(s)),f.enableGlobalRouting((s,r)=>{const o=f.createFromWorker(s);f.setupChannelHandlers(o,s),o.handleMessage(r)}),f.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(f.cleanupIntervalId=setInterval(()=>f.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){f.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 f.clientMeta.set(t,s),(o=(r=f.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:f.clientMeta.size}}),f.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:f.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of f.globalSubscribeMap)e.subscribe(s,async o=>{const a=f.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}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 f.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:f.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 f.channelsByClientId)if(!r.has(o)){const a=f.channelsByClientId.get(o);a&&a.destroy(),f.clientMeta.delete(o),(t=(e=f.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!f.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const r=await self.clients.matchAll();let o=0;for(const a of r){if(s&&a.id===s)continue;const i=f.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",a.id,c)}}return o}catch(r){return console.error("[ServiceWorkerChannel] broadcastToAll error:",r),0}}static async broadcastToType(e,t,s,r){if(!f.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const o=await self.clients.matchAll();let a=0;for(const i of o){if(r&&i.id===r)continue;const c=f.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=f.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(u){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,u)}}return a}catch(o){return console.error("[ServiceWorkerChannel] broadcastToType error:",o),0}}static getClientInfo(e){return f.clientMeta.get(e)}static getAllClients(){return new Map(f.clientMeta)}static getClientsByType(e){const t=[];for(const s of f.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.`),f.globalSubscribeMap.set(e,t);for(const[s,r]of f.channelsByClientId)r.subscribe(e,async o=>{const a=f.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){f.globalSubscribeMap.delete(e);for(const t of f.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&f.useGlobalRouting&&f.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&f.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return f.channelsByClientId.get(e)}static hasChannel(e){return f.channelsByClientId.has(e)}static getChannelCount(){return f.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=St("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=St("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(f.useGlobalRouting)return void(f.globalListenerSetup||(self.addEventListener("message",f.globalMessageHandler),f.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(f.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=vs(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 re("Heartbeat detection failed",ne.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 re("All reconnection attempts failed",ne.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 re("Handshake timeout",ne.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 f(t,e);s.connectionOptions=e||{};const r=(e==null?void 0:e.appType)||(e==null?void 0:e.appName);let o=0,a=0;const i=async()=>{if(!a){a=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{a=0}}},c=()=>{s.setConnectionState("connected"),s.updateLastMessageTime(),s.startHeartbeat(),s.setupSwLifecycleListeners()};return r?s.isReady?(i(),c()):s.once("ready",()=>{i(),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 i()),s.setConnectionState("connected"),s.updateLastMessageTime()}),s.on("message:received",({isResponse:l})=>{l&&s.updateLastMessageTime()}),s}static createFromWorker(e,t){return new f(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 f.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(f,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(f,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(f,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(f,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(f,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(f,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(f,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(f,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(f,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(f,"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=f.channelsByClientId.get(t);s?s.handleMessage(n):f.unknownClientCallback&&f.unknownClientCallback(t,n)}});function qs(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"},W={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"},de=class de{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(),f.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 pt.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 de.instance||(de.instance=new de(e)),de.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:f.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=De().find(r=>r.id===e);s&&this.sendPostMessageLog(s)}wrapRpcHandler(e,t,s){return async r=>{var l;const o=this.unwrapRpcData(r),a=Date.now(),i=r==null?void 0:r.requestId,c=He()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=Ge(`RPC:${e}`,{params:o,requestId:i},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&&i){const h=Ue(i,{result:u},Date.now()-a);h&&this.broadcastPostMessageLog(h)}return u}catch(u){if(console.error(`[SW wrapRpcHandler] ${e} error:`,u),c&&i){const h=Ue(i,null,Date.now()-a,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:a}=await Promise.resolve().then(()=>H),i=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return a(i,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(a=>this.serializeLogArg(a)):[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:a}=e||{},i=s().map(d=>({...d,type:"fetch"})),c=t(),l=new Map;for(const d of c)l.set(d.id,d);for(const d of i)l.set(d.id,d);let u=Array.from(l.values()).sort((d,m)=>m.timestamp-d.timestamp);return a&&(a.type&&(u=u.filter(d=>d.type===a.type)),a.status&&(u=u.filter(d=>d.status===a.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 a=await t();if(o&&(o.logLevel&&(a=a.filter(c=>c.logLevel===o.logLevel)),o.search)){const c=o.search.toLowerCase();a=a.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:a.slice(r,r+s),total:a.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(()=>je),{limit:r=200,offset:o=0,filter:a}=e||{};let i=t();if(a&&(a.direction&&(i=i.filter(l=>l.direction===a.direction)),a.messageType)){const l=a.messageType.toLowerCase();i=i.filter(u=>{var h;return(h=u.messageType)==null?void 0:h.toLowerCase().includes(l)})}return{logs:i.slice(o,o+r),total:i.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(()=>je);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(()=>he);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(()=>he);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(()=>he);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(()=>he);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||{},a=await caches.open(s),i=await a.keys(),c=[];for(let l=o;l<Math.min(o+r,i.length);l++){const u=i[l],h=await a.match(u);if(h){const d=h.headers.get("sw-cache-date"),m=h.headers.get("sw-cache-created-at")||d,b=h.headers.get("sw-image-size")||h.headers.get("content-length");c.push({url:u.url,cacheDate:d?parseInt(d):void 0,cacheCreatedAt:m?parseInt(m):void 0,size:b?parseInt(b):void 0})}}return{cacheName:s,entries:c,total:i.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 a=await caches.open(o),i=await a.keys();let c=0;for(const l of i){const u=await a.match(l);if(u){const h=u.headers.get("content-length");h&&(c+=parseInt(h))}}t.push({name:o,count:i.length,size:c}),s+=i.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(()=>je),a=await s(),i=o(),c=t();return{exportTime:new Date().toISOString(),swVersion:r,status:e(),fetchLogs:c,consoleLogs:a,postmessageLogs:i}}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(W.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheDeleted(e){this.broadcastToAll(W.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(W.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(W.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(W.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(W.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(W.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(W.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(W.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(W.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(W.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(W.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 qs(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,a]of this.channels)t.has(o)||(a.isDebugClient&&(s=!0),this.channels.delete(o));s&&((r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}};de.instance=null;let Ae=de,ve=null;function Dt(n){return ve||(ve=Ae.getInstance(n)),ve}function B(){return ve}const Hs=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:y,SWChannelManager:Ae,SW_EVENTS:W,getChannelManager:B,initChannelManager:Dt},Symbol.toStringTag,{value:"Module"}));function Re(n){wt(n)}const Gs=[];let Lt=!1;function ye(n){Lt=n}function ze(){return Lt}function $e(){return[...Gs]}const Us=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:$e,isDebugFetchEnabled:ze,setDebugFetchEnabled:ye},Symbol.toStringTag,{value:"Module"})),js=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),Ve={degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500},Ke=[{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}],ge=new Map;function _t(){Ke.forEach(n=>{ge.has(n.name)||ge.set(n.name,{name:n.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}_t();function At(n){const e=ge.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now())}function ce(n){const e=ge.get(n);e&&(e.failCount++,e.lastCheckTime=Date.now(),e.failCount>=Ve.failThreshold&&(e.isHealthy=!1,console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${e.failCount} failures`)))}function Fs(n){const e=ge.get(n);return e?e.isHealthy?!0:Date.now()-e.lastCheckTime>Ve.degradeTimeout?(console.log(`[CDN Fallback] Trying to recover ${n}...`),!0):!1:!1}function zs(){return Ke.filter(n=>n.enabled&&Fs(n.name)).sort((n,e)=>n.priority-e.priority)}function vt(n){const e=/^\/?(aitu-app@[\d.]+\/)/;return n.replace(e,"/")}function Rt(n,e,t){const s=vt(t);return n.urlTemplate.replace("{version}",e).replace("{path}",s.startsWith("/")?s.slice(1):s)}async function Xe(n,e=Ve.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 Mt(n,e,t){var r;if(js)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;const s=zs();for(const o of s){const a=Rt(o,e,n);try{console.log(`[CDN Fallback] Trying ${o.name}: ${a}`);const i=await Xe(a);if(i.ok){const c=i.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}`),ce(o.name);continue}const u=parseInt(i.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`),ce(o.name);continue}const d=i.clone();try{const m=(r=d.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)),g=p.includes("<!DOCTYPE")||p.includes("<html")||p.includes("<HTML")||p.includes("Not Found")||p.includes("404");if(h&&g){console.warn(`[CDN Fallback] ${o.name} returned HTML instead of ${c}`),ce(o.name);continue}}}}catch{}return At(o.name),console.log(`[CDN Fallback] Success from ${o.name}`),{response:i,source:o.name}}else console.warn(`[CDN Fallback] ${o.name} returned ${i.status}`),ce(o.name)}catch(i){console.warn(`[CDN Fallback] ${o.name} failed:`,i),ce(o.name)}}try{const o=vt(n),a=`${t}/${o.startsWith("/")?o.slice(1):o}`;console.log(`[CDN Fallback] Trying local server: ${a}`);const i=await Xe(a);if(i.ok)return console.log("[CDN Fallback] Success from local server"),{response:i,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 kt(n){const e=new Map;for(const t of Ke){if(!t.enabled)continue;const s=Rt(t,n,t.healthCheckPath);try{const o=(await Xe(s,5e3)).ok;e.set(t.name,o),o?At(t.name):ce(t.name)}catch{e.set(t.name,!1),ce(t.name)}}return e}function Ot(){return Array.from(ge.entries()).map(([n,e])=>({name:n,status:e}))}function Pt(){_t(),console.log("[CDN Fallback] All CDN status reset")}const Q=self;Dt(Q).setDebugClientCountChangedCallback(ln);const J={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function Me(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 $s(){console.log=(...n)=>{J.log(...n),ze()&&!Me(n)&&ke("log",n)},console.info=(...n)=>{J.info(...n),ze()&&!Me(n)&&ke("info",n)},console.warn=(...n)=>{J.warn(...n),Me(n)||ke("warn",n)},console.error=(...n)=>{J.error(...n),Me(n)||ke("error",n)}}function Vs(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 a=JSON.stringify(r);t.push(a==="{}"?String(r):a)}else t.push(String(r))}catch{t.push(String(r))}return{message:t.join(" ")||"(empty)",stack:e}}function ke(n,e){try{const{message:t,stack:s}=Vs(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Ye=="function"&&Ye({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){J.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Ye=null;$s(),Promise.resolve().then(()=>he).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=B();t&&t.sendDebugLLMLog(e)})});const j="0.6.21",Qe=`drawnix-v${j}`,_="drawnix-images",Se=`drawnix-static-v${j}`,Oe="drawnix-fonts",Z="sw-cache-date",le="sw-cache-created-at",Ks="/__aitu_cache__/",Xs="/__aitu_generated__/audio/",Ys="/asset-library/",It=location.hostname==="localhost"||location.hostname==="127.0.0.1",Qs=[{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"}],Js=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Zs=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Je=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,en=new Set(["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","rand","_force","bypass_sw","direct_fetch","thumbnail","expires","signature","sig","token","policy","x-amz-algorithm","x-amz-credential","x-amz-date","x-amz-expires","x-amz-security-token","x-amz-signature","x-amz-signedheaders","x-goog-algorithm","x-goog-credential","x-goog-date","x-goog-expires","x-goog-signature","x-goog-signedheaders","ossaccesskeyid","x-oss-security-token","x-oss-signature-version","x-oss-credential","x-oss-date","x-oss-expires","x-oss-signature"]);function Ze(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)en.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const q=new Map,ue=new Map,Wt=30*1e3,Ce=new Map,x=new Map,tn=300*1e3,Bt=10,fe=new Set,pe=new Set,sn=3600*1e3,et=new Map;function xt(n){pe.add(n),et.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function nn(n){if(!pe.has(n))return!1;const e=et.get(n);return e&&Date.now()-e>sn?(pe.delete(n),et.delete(n),!1):!0}const K=[],Nt=7,F=[],rn=500;let M=!1;function k(n){if(!M)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return F.unshift(t),F.length>rn&&F.pop(),qt(t),e}function A(n,e){if(!M||!n)return;const t=F.find(s=>s.id===n);t&&(Object.assign(t,e),qt(t))}function qt(n){const e=B();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 on(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 Ht(){try{await Gt();const n=await Pe(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Nt*24*60*60*1e3;return new Promise((o,a)=>{const i=s.openCursor(null,"prev"),c=[];i.onsuccess=()=>{const l=i.result;if(l){const u=l.value;u.timestamp>=r&&c.push(u),l.continue()}else n.close(),o(c)},i.onerror=()=>{n.close(),a(i.error)}})}catch(n){return console.warn("Service Worker: 无法加载控制台日志:",n),[]}}async function Gt(){try{const n=await Pe(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Nt*24*60*60*1e3,o=IDBKeyRange.upperBound(r);return new Promise((a,i)=>{const c=s.openCursor(o);let l=0;c.onsuccess=()=>{const u=c.result;u?(u.delete(),l++,u.continue()):(n.close(),l>0,a(l))},c.onerror=()=>{n.close(),i(c.error)}})}catch(n){return console.warn("Service Worker: 无法清理过期日志:",n),0}}async function Ut(){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 jt=500;function tt(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(M||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};on(r),K.unshift(r),K.length>jt&&(K.length=jt),M&&an(r)}Ye=tt;function an(n){const e=B();e&&e.sendConsoleLog(n)}function cn(){let n=0;return x.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function Ft(){return{version:j,cacheNames:[Qe,_,Se,Oe],pendingImageRequests:q.size,pendingVideoRequests:Ce.size,videoBlobCacheSize:x.size,videoBlobCacheTotalBytes:cn(),completedImageRequestsSize:ue.size,failedDomainsCount:fe.size,failedDomains:Array.from(fe),corsFailedDomainsCount:pe.size,corsFailedDomains:Array.from(pe),debugLogsCount:F.length,consoleLogsCount:K.length,debugModeEnabled:M,memoryStats:{pendingRequestsMapSize:q.size,completedRequestsMapSize:ue.size,videoBlobCacheMapSize:x.size,failedDomainsSetSize:fe.size,corsFailedDomainsSetSize:pe.size,debugLogsArraySize:F.length,consoleLogsArraySize:K.length}}}function st(){return F}function zt(){F.length=0}function $t(){K.length=0}function nt(){M||(M=!0,ye(!0),Re(!0),J.log("Service Worker: Debug mode enabled (debug page connected)"))}function rt(){M&&(M=!1,ye(!1),Re(!1),K.length=0,F.length=0,J.log("Service Worker: Debug mode disabled (no debug pages)"))}function ln(n){n>0?nt():rt()}function Vt(n){for(const e of Qs)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function un(n,e){return Js.test(n.pathname)||e.destination==="image"||Vt(n)!==null}function hn(n,e){return Zs.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function dn(n,e){return Je.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function gn(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"}function fn(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}async function pn(){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 a=s.transaction(["failedDomains"],"readonly").objectStore("failedDomains").getAll();a.onsuccess=()=>{a.result.forEach(c=>fe.add(c.domain)),e()},a.onerror=()=>t(a.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 mn(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 bn(n){try{const e=await n.keys();if(e.length<=10)return;const t=[];for(const a of e)try{const i=await n.match(a);if(i){const c=i.headers.get(Z),l=i.headers.get("sw-image-size");t.push({request:a,cacheDate:c?parseInt(c):0,imageSize:l?parseInt(l):0})}}catch(i){console.warn("Service Worker: Error reading cache entry:",i)}t.sort((a,i)=>a.cacheDate-i.cacheDate);const s=Math.max(1,Math.floor(t.length*.25));let r=0,o=0;for(let a=0;a<s&&a<t.length;a++)try{await n.delete(t[a].request),r++,o+=t[a].imageSize}catch(i){console.warn("Service Worker: Error deleting cache entry:",i)}}catch(e){console.warn("Service Worker: Cache cleanup failed:",e)}}async function wn(){try{const n=await fetch("./precache-manifest.json",{cache:"reload"});return n.ok?(await n.json()).files:null}catch{return null}}async function yn(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,a="server";if(!r){const i=await Mt(e.startsWith("/")?e.slice(1):e,j,location.origin);i&&i.response.ok&&(o=i.response,a=i.source)}if(o||(o=await fetch(e,{cache:"reload"}),a="server"),o.ok){const i=new Headers(o.headers);i.set("x-sw-revision",t),i.set("x-sw-cached-at",new Date().toISOString()),i.set("x-sw-source",a);const c=new Response(await o.blob(),{status:o.status,statusText:o.statusText,headers:i}),l=new URL(e,self.location.origin).href;return await n.put(l,c),{url:e,success:!0,source:a}}return{url:e,success:!1,status:o.status}}catch(s){return{url:e,success:!1,error:String(s)}}}async function Sn(n,e){const s=[];for(let r=0;r<e.length;r+=6){const o=e.slice(r,r+6),a=await Promise.allSettled(o.map(({url:i,revision:c})=>yn(n,i,c)));for(const i of a)i.status==="fulfilled"?s.push({success:i.value.success,source:i.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 pn();try{const e=await wn();if(e&&e.length>0){const t=await caches.open(Se);await Sn(t,e)}}catch(e){console.warn("Service Worker: Precache failed:",e)}})())}),Q.addEventListener("activate",n=>{n.waitUntil((async()=>{await Q.clients.claim();const e=B();e&&e.sendSWActivated(j)})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(o=>o.startsWith("drawnix-images-v")&&o!==_);if(t.length>0){const o=await caches.open(_);for(const a of t)try{const i=await caches.open(a),c=await i.keys();for(const l of c){const u=await i.match(l);u&&await o.put(l,u)}await caches.delete(a)}catch(i){console.warn(`Failed to migrate cache ${a}:`,i)}}const s=e.filter(o=>o.startsWith("drawnix-static-v")&&o!==Se),r=e.filter(o=>o.startsWith("drawnix-v")&&o!==Qe&&o!==_&&!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(a){console.warn("Failed to delete old cache:",o,a)}},3e4),Gt().catch(o=>{console.warn("Failed to cleanup expired console logs:",o)}),pt.archiveOldTasks(100).catch(o=>{console.warn("Failed to archive old tasks:",o)})}))});function Cn(n){if(M){const e=B();e&&e.sendPostMessageLog(n)}}Q.addEventListener("message",n=>{var a,i,c,l,u,h,d,m,b,p;const e=((a=n.data)==null?void 0:a.type)||((i=n.data)==null?void 0:i.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=((d=n.data)==null?void 0:d.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=Ge(e,n.data,t,s,(p=n.data)==null?void 0:p.__internal__),o&&M)){const w=De().find(S=>S.id===o);w&&Cn(w)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:g,mediaType:w,blob:S,mimeType:C}=n.data;if(g&&w&&S){const L=new Blob([S],{type:C||(w==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:N}=await Promise.resolve().then(()=>H);N(L,g,w)})()}return}if(n.data&&n.data.type==="SKIP_WAITING"){Q.skipWaiting();const g=B();g&&g.sendSWUpdated(j)}else if(n.data&&n.data.type==="FORCE_UPGRADE"){Q.skipWaiting();const g=B();g&&g.sendSWUpdated(j)}else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:g}=n.data;g&&at(g).then(()=>{const w=B();w&&w.sendCacheDeleted(g)}).catch(w=>{console.error("Service Worker: Failed to delete cache:",w)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:g}=n.data;g&&Array.isArray(g)&&_n(g).then(()=>{}).catch(w=>{console.error("Service Worker: Failed to batch delete caches:",w)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")An().then(()=>{}).catch(g=>{console.error("Service Worker: Failed to clear all cache:",g)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){M=!0,ye(!0),Re(!0),J.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const g=B();g&&g.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){M=!1,ye(!1),Re(!1),K.length=0,F.length=0,J.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const g=B();g&&g.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:g}=await Promise.resolve().then(()=>he),w=await g(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:w})}catch(g){console.error("[SW] Failed to get LLM API logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:g}=await Promise.resolve().then(()=>he);await g();const w=n.source;w&&w.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(g){console.error("[SW] Failed to clear LLM API logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const g=n.source;g&&g.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:M,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:g}=await Promise.resolve().then(()=>Us),w=st(),S=g(),C=n.source;C&&C.postMessage({type:"SW_DEBUG_LOGS",logs:[...w,...S.map(L=>({...L,type:"fetch"}))]})}catch(g){console.error("[SW] Failed to get fetch logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const g=n.source;g&&g.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:K})}catch(g){console.error("[SW] Failed to get console logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const g=De(),w=n.source;w&&w.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:g})}catch(g){console.error("[SW] Failed to get postmessage logs:",g)}})();return}});const En="MemorySnapshotDB",oe="snapshots",Kt=50;async function ot(){return new Promise((n,e)=>{const t=indexedDB.open(En,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(oe)){const o=r.createObjectStore(oe,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function Xt(n){try{const e=await ot(),t=e.transaction(oe,"readwrite"),s=t.objectStore(oe);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>Kt){const i=s.index("timestamp").openCursor();let c=0;const l=o-Kt;i.onsuccess=u=>{const h=u.target.result;h&&c<l&&(s.delete(h.value.id),c++,h.continue())}}},await new Promise((o,a)=>{t.oncomplete=()=>{e.close(),o()},t.onerror=()=>{e.close(),a(t.error)}})}catch(e){console.warn("[SW] Failed to save crash snapshot:",e)}}async function Yt(){try{const n=await ot(),s=n.transaction(oe,"readonly").objectStore(oe).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{n.close();const i=a.result.sort((c,l)=>l.timestamp-c.timestamp);r(i)},a.onerror=()=>{n.close(),o(a.error)}})}catch(n){return console.warn("[SW] Failed to get crash snapshots:",n),[]}}async function Qt(){try{const n=await ot(),e=n.transaction(oe,"readwrite");e.objectStore(oe).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 Tn=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Dn(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Ln(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,a=0,i=0,c=0;const l=10;try{const u=s.transaction(r,"readonly");for(const h of r){const d=u.objectStore(h),m=d.count();m.onsuccess=()=>{const b=m.result;if(o+=b,b>0){const p=d.openCursor();let g=0;p.onsuccess=w=>{const S=w.target.result;if(S&&g<l)a+=Dn(S.value),i++,g++,S.continue();else if(c++,c===r.length){s.close();const C=i>0?a/i:0,L=Math.round(C*o);e({count:o,totalSize:L})}},p.onerror=()=>{if(c++,c===r.length){s.close();const w=i>0?a/i:0,S=Math.round(w*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 b=i>0?a/i: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 Jt(){const n={},e=[Qe,_,Se,Oe];for(const t of e)try{const s=await caches.open(t),r=await s.keys();let o=0;const a=Math.min(r.length,100);let i=0;for(let c=0;c<a;c++){const l=await s.match(r[c]);if(l){const u=l.headers.get("sw-image-size")||l.headers.get("content-length");u&&(i+=parseInt(u))}}a>0&&r.length>a?o=Math.round(i/a*r.length):o=i,n[t]={count:r.length,totalSize:o,type:"cache"}}catch{n[t]={count:0,totalSize:0,type:"cache"}}for(const t of Tn)try{const s=await Ln(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function at(n){try{await(await caches.open(_)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function _n(n){try{const e=await caches.open(_);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 An(){try{const n=await caches.open(_),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 Zt(n,e,t){try{const s=B();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}async function vn(){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=B();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const ee=new Map,es=300*1e3,ts=500;function Rn(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 Mn(n){const e=ee.get(n);return e?Date.now()-e>es?(ee.delete(n),!1):!0:!1}function ss(n){if(Rn(n)){if(ee.size>=ts){const e=Date.now();for(const[t,s]of ee)e-s>es&&ee.delete(t);if(ee.size>=ts){const t=Array.from(ee.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)ee.delete(r)}}ee.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:"){k({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(Ks)||e.pathname.startsWith(Xs)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(On(n.request).then(r=>(A(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw A(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(Ys)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Pn(n.request).then(r=>(A(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw A(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"){k({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")){k({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")){k({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(nn(e.hostname)){k({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(e.origin!==location.origin&&dn(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"audio",headers:r?{range:r}:void 0,details:r?`Audio Range request: ${r}`:"External audio request"});n.respondWith(In(n.request).then(a=>(A(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,cached:a.headers.has(Z),responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw A(o,{error:String(a),duration:Date.now()-s}),a}));return}if(hn(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=k({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(Wn(n.request).then(a=>(A(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw A(o,{error:String(a),duration:Date.now()-s}),a}));return}if(gn(e,n.request)){const s=Date.now(),r=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(kn(n.request).then(o=>(A(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 A(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&un(e,n.request)){if(Mn(n.request.url)){k({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=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(qn(n.request).then(o=>(o.status===404&&ss(n.request.url),A(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 ss(n.request.url),A(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(),a=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(Bn(n.request).then(i=>(A(a,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-o}),i)).catch(i=>{throw A(a,{error:String(i),duration:Date.now()-o}),i}));return}}if(M){if(fn(e)){k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"xhr",details:`Skipped SW debug interception for generateContent request (${n.request.method})`,duration:0});return}const s=k({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 a={};if(n.request.headers.forEach((h,d)=>{a[d]=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]"}A(s,{headers:a,details:o?`XHR/API request (${n.request.method})
1
+ var sw=(function(E){"use strict";var ie=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(ie||{});ie.IMAGE+"",ie.VIDEO+"",ie.AUDIO+"",ie.CHARACTER+"",ie.INSPIRATION_BOARD+"",ie.CHAT+"";function dt(n){return n instanceof Error?n.name||"Error":"Unknown error"}const xe="sw-task-queue",gt=3,T="tasks",G="config",O="workflows",P="chat-workflows",v="pending-tool-requests",R="pending-dom-operations",I="task-step-mappings",U="pending-canvas-operations",ds=[T,G,O,P,v,R,I,U];function gs(){return new Promise(n=>{const e=indexedDB.open(xe);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,gt))},e.onerror=()=>{n(gt)}})}function fs(n){const e=[];for(const t of ds)n.objectStoreNames.contains(t)||e.push(t);return e}function ps(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(xe,s);r.onerror=()=>{console.error("[SWStorage] Failed to repair DB:",r.error),t(r.error)},r.onsuccess=()=>{e(r.result)},r.onupgradeneeded=o=>{const a=o.target.result;ft(a)}})}function ft(n){if(!n.objectStoreNames.contains(T)){const e=n.createObjectStore(T,{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(O)){const e=n.createObjectStore(O,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(P)){const e=n.createObjectStore(P,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(v)||n.createObjectStore(v,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(R)){const e=n.createObjectStore(R,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(I)||n.createObjectStore(I,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains(U)||n.createObjectStore(U,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function ms(){const n=await gs();return new Promise((e,t)=>{const s=indexedDB.open(xe,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=fs(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),ps(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;ft(o)}})}class bs{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=ms()),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 a=s.transaction(T,"readwrite"),i=a.objectStore(T);for(const c of e)i.put(c);a.oncomplete=()=>{t.forEach(({resolve:c})=>c()),r()},a.onerror=()=>{const c=a.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(T,"readwrite").objectStore(T).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 i=t.transaction(T,"readonly").objectStore(T).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 a=e.transaction(T,"readonly").objectStore(T).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(T,"readonly").objectStore(T).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:a="desc"}=e;try{const i=await this.getDB();return new Promise((c,l)=>{const d=i.transaction(T,"readonly").objectStore(T).index("createdAt"),m=a==="desc"?"prev":"next",b=d.openCursor(null,m),p=[];let g=0,w=0;b.onerror=()=>l(b.error),b.onsuccess=S=>{const C=S.target.result;if(!C){c({tasks:p,total:w,hasMore:w>t+p.length});return}const L=C.value,N=!r||L.status===r,te=!o||L.type===o;N&&te&&(w++,g<t?g++:p.length<s&&p.push(L)),C.continue()}})}catch(i){return console.error("[SWStorage] Failed to get paginated tasks:",i),{tasks:[],total:0,hasMore:!1}}}async deleteTask(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(T,"readwrite").objectStore(T).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(G,"readonly").objectStore(G).get(e);i.onsuccess=()=>{const c=i.result;if(!c){s(null);return}const{key:l,...u}=c;s(u)},i.onerror=()=>r(i.error)})}catch(t){return console.error("[SWStorage] Failed to get config:",dt(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const a=s.transaction(G,"readwrite");a.objectStore(G).put({key:e,...t,updatedAt:Date.now()}),a.oncomplete=()=>r(),a.onerror=()=>o(a.error)})}catch(s){throw console.error("[SWStorage] Failed to save config:",dt(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 a=e.transaction(G,"readonly").objectStore(G).get("systemPrompt");a.onsuccess=()=>{const i=a.result;t((i==null?void 0:i.value)||null)},a.onerror=()=>s(a.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 i=t.transaction(O,"readwrite").objectStore(O).put(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(O,"readonly").objectStore(O).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 a=e.transaction(O,"readonly").objectStore(O).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(O,"readonly").objectStore(O).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 i=t.transaction(O,"readwrite").objectStore(O).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(P,"readwrite").objectStore(P).put(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(P,"readonly").objectStore(P).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 a=e.transaction(P,"readonly").objectStore(P).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(P,"readonly").objectStore(P).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 i=t.transaction(P,"readwrite").objectStore(P).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(v,"readwrite").objectStore(v).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(v,"readonly").objectStore(v).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(v,"readonly").objectStore(v).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 i=t.transaction(v,"readonly").objectStore(v).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 i=t.transaction(v,"readwrite").objectStore(v).delete(e);i.onerror=()=>r(i.error),i.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.getDB(),s=Date.now()-e;return new Promise((r,o)=>{const a=t.transaction(v,"readwrite"),c=a.objectStore(v).openCursor();let l=0;c.onsuccess=()=>{const u=c.result;u&&(u.value.createdAt<s&&(u.delete(),l++),u.continue())},a.oncomplete=()=>{l>0&&console.log(`[SWStorage] Cleaned up ${l} stale pending tool requests`),r(l)},a.onerror=()=>o(a.error)})}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 i=t.transaction(R,"readwrite").objectStore(R).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(R,"readonly").objectStore(R).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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(R,"readonly").objectStore(R).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(R,"readonly").objectStore(R).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 i=t.transaction(R,"readonly").objectStore(R).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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 i=t.transaction(R,"readwrite").objectStore(R).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(I,"readwrite").objectStore(I).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(I,"readonly").objectStore(I).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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 i=t.transaction(I,"readonly").objectStore(I).get(e);i.onerror=()=>r(i.error),i.onsuccess=()=>s(i.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(I,"readonly").objectStore(I).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 i=t.transaction(I,"readwrite").objectStore(I).delete(e);i.onerror=()=>r(i.error),i.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 i=t.transaction(U,"readwrite").objectStore(U).put(e);i.onerror=()=>r(i.error),i.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 a=e.transaction(U,"readonly").objectStore(U).getAll();a.onerror=()=>s(a.error),a.onsuccess=()=>t(a.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 i=t.transaction(U,"readwrite").objectStore(U).delete(e);i.onerror=()=>r(i.error),i.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)}}async archiveOldTasks(e=100){try{const t=await this.getDB(),s=await new Promise((c,l)=>{const d=t.transaction(T,"readonly").objectStore(T).index("createdAt"),m=[],b=d.openCursor(null,"next");b.onsuccess=()=>{const p=b.result;if(!p){c(m);return}const g=p.value;g.archived||m.push(g),p.continue()},b.onerror=()=>l(b.error)}),r=s.length-e;if(r<=0)return 0;const o=["completed","failed","cancelled"],a=s.filter(c=>o.includes(c.status)).slice(0,r);if(a.length===0)return 0;const i=Date.now();return new Promise((c,l)=>{const u=t.transaction(T,"readwrite"),h=u.objectStore(T);for(const d of a)d.archived=!0,d.updatedAt=i,h.put(d);u.oncomplete=()=>{console.log(`[SWStorage] Archived ${a.length} old tasks`),c(a.length)},u.onerror=()=>l(u.error)})}catch(t){return console.error("[SWStorage] Failed to archive old tasks:",t),0}}}const pt=new bs,ws=["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();ws.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Ne(s)}return e}return n}let Te=!1;const ys=500,se=[];let qe=0;function mt(){return Te}const bt=["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 wt(n){const e=Te;Te=n,!n&&e&&(se.length=0,we.clear(),qe=0)}function He(){return Te}function Ss(n){if(!mt()||n==="unknown"||bt.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)),bt.includes(e))return!1}return!0}function Cs(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 Ge(n,e,t,s,r){if(r||!Ss(n))return"";const o=Cs(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++qe}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:yt(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Es(i),Ds(n)){const c=Ls(e);c&&we.set(c,{entry:i,startTime:Date.now()})}return a}function Es(n){se.unshift(n),se.length>ys&&se.pop()}function Ue(n,e,t,s){if(!mt())return"";const r=we.get(n);if(r){r.entry.response=yt(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return we.delete(n),o}return""}function De(){return[...se]}function Ts(){se.length=0,we.clear(),qe=0}function Ds(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 Ls(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function yt(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return Ne(e)}catch{return"[Non-serializable data]"}}function _s(){const n={total:se.length,sent:0,received:0,byType:{}};for(const e of se)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const je=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Ts,getAllLogs:De,getLogStats:_s,isPostMessageLoggerDebugMode:He,logReceivedMessage:Ge,setPostMessageLoggerDebugMode:wt,updateRequestWithResponse:Ue},Symbol.toStringTag,{value:"Module"}));function As(){return typeof window<"u"?window:typeof self<"u"?self:{}}function vs(n){return JSON.parse(JSON.stringify(n))}function St(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 Rs="postmessage-duplex",Ms="1.2.0",Le=As();var $,ne;Le.__POSTMESSAGE_DUPLEX__||(Le.__POSTMESSAGE_DUPLEX__={}),Le.__POSTMESSAGE_DUPLEX__.version=Ms,Le.__POSTMESSAGE_DUPLEX__.name=Rs,(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"})(ne||(ne={}));class re 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,re)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class ks{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 Os{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 Ps{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 Ct(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const X=n=>({valid:0,error:n});function Is(n){if(!Ct(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(a=e.ret)=="number"&&Object.values($).includes(a)?"data"in e&&e.data!==void 0&&!Ct(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 a}function _e(n){return"ret"in n&&typeof n.ret=="number"}function Ws(n){return n.msg==="ready"}function Bs(n){return n._broadcast==1&&typeof n.cmdname=="string"}function xs(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const Fe=[],Y=[];function Et(n){Y.length>=200&&Y.shift(),Y.push(n)}function Tt(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 Ns extends Ps{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 ks,this.rateLimiter=new Os((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,Fe.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{Et({direction:"send",cmdname:s,requestId:r,status:"pending",timestamp:Date.now(),dataSummary:""})}),t.on("message:received",({cmdname:s,requestId:r,isResponse:o})=>{const a=s||"",i=r||"";o?Tt(i,"ok"):Et({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{Tt(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=xs(e);if(t>this.maxMessageSize){const s=new re(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ne.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):_e(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=Is(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:_e(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(!Bs(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 a=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:$.ReceiverCallbackError,msg:a||"unknown error"}),this.emit("error",{error:o instanceof Error?o:new Error(a),context:`handler:${s}`})}return 1}handleReadyMessage(e,t){if(!Ws(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}),_e(e)||this.sendMessage({requestId:t,ret:$.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!_e(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 re("Cannot publish: channel has been destroyed",ne.ConnectionDestroyed,{cmdname:e}));const r=this.baseKey+ ++this.reqTime,o={requestId:r,cmdname:e,data:t};this.requestCmdMap.set(r,e);const a=new Promise((i,c)=>{this.callbackMap.set(r,{resolve:i,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:a,options:s}),a}doPublish(e,t){const{requestId:s,cmdname:r}=e,o=(t==null?void 0:t.timeout)??this.timeout;this.timeoutManager.add(s,o,()=>{const a=this.callbackMap.get(s);if(a){const i={req:e,requestId:s,ret:$.TimeOut,time:Date.now(),msg:"timeout"};this.log("error","postmessage timeout",i),this.emit("timeout",{requestId:s,cmdname:r,timeoutMs:o}),a.resolve(i),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=Fe.findIndex(r=>r.deref()===t);s!==-1&&Fe.splice(s,1)})(this);const e=new re("Channel has been destroyed",ne.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 a=this.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}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,a]of this.channelsByClientId)r.has(o)||(a.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 a of r){if(s&&a.id===s)continue;const i=this.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",a.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 a=0;for(const i of o){if(r&&i.id===r)continue;const c=this.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=this.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(u){console.warn("[ServiceWorkerHub] Failed to broadcast to client:",i.id,u)}}return a}catch(o){return console.error("[ServiceWorkerHub] broadcastToType error:",o),0}}}Object.defineProperty(V,"instance",{enumerable:1,configurable:1,writable:1,value:null});class f extends Ns{static enableGlobalRouting(e){f.useGlobalRouting=1,f.unknownClientCallback=e??null,f.globalListenerSetup||(self.addEventListener("message",f.globalMessageHandler),f.globalListenerSetup=1)}static disableGlobalRouting(){f.useGlobalRouting=0,f.globalListenerSetup&&(self.removeEventListener("message",f.globalMessageHandler),f.globalListenerSetup=0)}static setupHub(e={}){if(f.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");f.hubOptions=e,f.hubInitialized=1,V.getInstance().setup(e,s=>f.createFromWorker(s)),f.enableGlobalRouting((s,r)=>{const o=f.createFromWorker(s);f.setupChannelHandlers(o,s),o.handleMessage(r)}),f.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(f.cleanupIntervalId=setInterval(()=>f.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){f.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 f.clientMeta.set(t,s),(o=(r=f.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:f.clientMeta.size}}),f.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:f.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of f.globalSubscribeMap)e.subscribe(s,async o=>{const a=f.clientMeta.get(t);return r({data:o.data||{},clientId:t,clientMeta:a})})}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 f.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:f.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 f.channelsByClientId)if(!r.has(o)){const a=f.channelsByClientId.get(o);a&&a.destroy(),f.clientMeta.delete(o),(t=(e=f.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!f.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const r=await self.clients.matchAll();let o=0;for(const a of r){if(s&&a.id===s)continue;const i=f.channelsByClientId.get(a.id);if(i)try{i.broadcast(e,{...t,t:1,i:Date.now()}),o++}catch(c){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",a.id,c)}}return o}catch(r){return console.error("[ServiceWorkerChannel] broadcastToAll error:",r),0}}static async broadcastToType(e,t,s,r){if(!f.hubInitialized)return console.warn("[ServiceWorkerChannel] Hub not initialized. Call setupHub() first."),0;try{const o=await self.clients.matchAll();let a=0;for(const i of o){if(r&&i.id===r)continue;const c=f.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=f.channelsByClientId.get(i.id);if(l)try{l.broadcast(t,{...s,t:1,o:e,i:Date.now()}),a++}catch(u){console.warn("[ServiceWorkerChannel] Failed to broadcast to client:",i.id,u)}}return a}catch(o){return console.error("[ServiceWorkerChannel] broadcastToType error:",o),0}}static getClientInfo(e){return f.clientMeta.get(e)}static getAllClients(){return new Map(f.clientMeta)}static getClientsByType(e){const t=[];for(const s of f.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.`),f.globalSubscribeMap.set(e,t);for(const[s,r]of f.channelsByClientId)r.subscribe(e,async o=>{const a=f.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){f.globalSubscribeMap.delete(e);for(const t of f.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&f.useGlobalRouting&&f.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&f.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return f.channelsByClientId.get(e)}static hasChannel(e){return f.channelsByClientId.has(e)}static getChannelCount(){return f.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=St("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=St("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(f.useGlobalRouting)return void(f.globalListenerSetup||(self.addEventListener("message",f.globalMessageHandler),f.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(f.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=vs(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 re("Heartbeat detection failed",ne.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 re("All reconnection attempts failed",ne.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 re("Handshake timeout",ne.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 f(t,e);s.connectionOptions=e||{};const r=(e==null?void 0:e.appType)||(e==null?void 0:e.appName);let o=0,a=0;const i=async()=>{if(!a){a=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{a=0}}},c=()=>{s.setConnectionState("connected"),s.updateLastMessageTime(),s.startHeartbeat(),s.setupSwLifecycleListeners()};return r?s.isReady?(i(),c()):s.once("ready",()=>{i(),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 i()),s.setConnectionState("connected"),s.updateLastMessageTime()}),s.on("message:received",({isResponse:l})=>{l&&s.updateLastMessageTime()}),s}static createFromWorker(e,t){return new f(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 f.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(f,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(f,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(f,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(f,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(f,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(f,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(f,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(f,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(f,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(f,"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=f.channelsByClientId.get(t);s?s.handleMessage(n):f.unknownClientCallback&&f.unknownClientCallback(t,n)}});function qs(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"},W={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"},de=class de{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(),f.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 pt.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 de.instance||(de.instance=new de(e)),de.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:f.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=De().find(r=>r.id===e);s&&this.sendPostMessageLog(s)}wrapRpcHandler(e,t,s){return async r=>{var l;const o=this.unwrapRpcData(r),a=Date.now(),i=r==null?void 0:r.requestId,c=He()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=Ge(`RPC:${e}`,{params:o,requestId:i},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&&i){const h=Ue(i,{result:u},Date.now()-a);h&&this.broadcastPostMessageLog(h)}return u}catch(u){if(console.error(`[SW wrapRpcHandler] ${e} error:`,u),c&&i){const h=Ue(i,null,Date.now()-a,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:a}=await Promise.resolve().then(()=>H),i=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return a(i,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(a=>this.serializeLogArg(a)):[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:a}=e||{},i=s().map(d=>({...d,type:"fetch"})),c=t(),l=new Map;for(const d of c)l.set(d.id,d);for(const d of i)l.set(d.id,d);let u=Array.from(l.values()).sort((d,m)=>m.timestamp-d.timestamp);return a&&(a.type&&(u=u.filter(d=>d.type===a.type)),a.status&&(u=u.filter(d=>d.status===a.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 a=await t();if(o&&(o.logLevel&&(a=a.filter(c=>c.logLevel===o.logLevel)),o.search)){const c=o.search.toLowerCase();a=a.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:a.slice(r,r+s),total:a.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(()=>je),{limit:r=200,offset:o=0,filter:a}=e||{};let i=t();if(a&&(a.direction&&(i=i.filter(l=>l.direction===a.direction)),a.messageType)){const l=a.messageType.toLowerCase();i=i.filter(u=>{var h;return(h=u.messageType)==null?void 0:h.toLowerCase().includes(l)})}return{logs:i.slice(o,o+r),total:i.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(()=>je);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(()=>he);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(()=>he);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(()=>he);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(()=>he);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||{},a=await caches.open(s),i=await a.keys(),c=[];for(let l=o;l<Math.min(o+r,i.length);l++){const u=i[l],h=await a.match(u);if(h){const d=h.headers.get("sw-cache-date"),m=h.headers.get("sw-cache-created-at")||d,b=h.headers.get("sw-image-size")||h.headers.get("content-length");c.push({url:u.url,cacheDate:d?parseInt(d):void 0,cacheCreatedAt:m?parseInt(m):void 0,size:b?parseInt(b):void 0})}}return{cacheName:s,entries:c,total:i.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 a=await caches.open(o),i=await a.keys();let c=0;for(const l of i){const u=await a.match(l);if(u){const h=u.headers.get("content-length");h&&(c+=parseInt(h))}}t.push({name:o,count:i.length,size:c}),s+=i.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(()=>je),a=await s(),i=o(),c=t();return{exportTime:new Date().toISOString(),swVersion:r,status:e(),fetchLogs:c,consoleLogs:a,postmessageLogs:i}}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(W.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheDeleted(e){this.broadcastToAll(W.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(W.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(W.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(W.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(W.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(W.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(W.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(W.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(W.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(W.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(W.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 qs(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,a]of this.channels)t.has(o)||(a.isDebugClient&&(s=!0),this.channels.delete(o));s&&((r=this.onDebugClientCountChanged)==null||r.call(this,this.getDebugClientCount()))}};de.instance=null;let Ae=de,ve=null;function Dt(n){return ve||(ve=Ae.getInstance(n)),ve}function B(){return ve}const Hs=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:y,SWChannelManager:Ae,SW_EVENTS:W,getChannelManager:B,initChannelManager:Dt},Symbol.toStringTag,{value:"Module"}));function Re(n){wt(n)}const Gs=[];let Lt=!1;function ye(n){Lt=n}function ze(){return Lt}function $e(){return[...Gs]}const Us=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:$e,isDebugFetchEnabled:ze,setDebugFetchEnabled:ye},Symbol.toStringTag,{value:"Module"})),js=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),Ve={degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500},Ke=[{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}],ge=new Map;function _t(){Ke.forEach(n=>{ge.has(n.name)||ge.set(n.name,{name:n.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}_t();function At(n){const e=ge.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now())}function ce(n){const e=ge.get(n);e&&(e.failCount++,e.lastCheckTime=Date.now(),e.failCount>=Ve.failThreshold&&(e.isHealthy=!1,console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${e.failCount} failures`)))}function Fs(n){const e=ge.get(n);return e?e.isHealthy?!0:Date.now()-e.lastCheckTime>Ve.degradeTimeout?(console.log(`[CDN Fallback] Trying to recover ${n}...`),!0):!1:!1}function zs(){return Ke.filter(n=>n.enabled&&Fs(n.name)).sort((n,e)=>n.priority-e.priority)}function vt(n){const e=/^\/?(aitu-app@[\d.]+\/)/;return n.replace(e,"/")}function Rt(n,e,t){const s=vt(t);return n.urlTemplate.replace("{version}",e).replace("{path}",s.startsWith("/")?s.slice(1):s)}async function Xe(n,e=Ve.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 Mt(n,e,t){var r;if(js)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;const s=zs();for(const o of s){const a=Rt(o,e,n);try{console.log(`[CDN Fallback] Trying ${o.name}: ${a}`);const i=await Xe(a);if(i.ok){const c=i.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}`),ce(o.name);continue}const u=parseInt(i.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`),ce(o.name);continue}const d=i.clone();try{const m=(r=d.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)),g=p.includes("<!DOCTYPE")||p.includes("<html")||p.includes("<HTML")||p.includes("Not Found")||p.includes("404");if(h&&g){console.warn(`[CDN Fallback] ${o.name} returned HTML instead of ${c}`),ce(o.name);continue}}}}catch{}return At(o.name),console.log(`[CDN Fallback] Success from ${o.name}`),{response:i,source:o.name}}else console.warn(`[CDN Fallback] ${o.name} returned ${i.status}`),ce(o.name)}catch(i){console.warn(`[CDN Fallback] ${o.name} failed:`,i),ce(o.name)}}try{const o=vt(n),a=`${t}/${o.startsWith("/")?o.slice(1):o}`;console.log(`[CDN Fallback] Trying local server: ${a}`);const i=await Xe(a);if(i.ok)return console.log("[CDN Fallback] Success from local server"),{response:i,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 kt(n){const e=new Map;for(const t of Ke){if(!t.enabled)continue;const s=Rt(t,n,t.healthCheckPath);try{const o=(await Xe(s,5e3)).ok;e.set(t.name,o),o?At(t.name):ce(t.name)}catch{e.set(t.name,!1),ce(t.name)}}return e}function Ot(){return Array.from(ge.entries()).map(([n,e])=>({name:n,status:e}))}function Pt(){_t(),console.log("[CDN Fallback] All CDN status reset")}const Q=self;Dt(Q).setDebugClientCountChangedCallback(ln);const J={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function Me(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 $s(){console.log=(...n)=>{J.log(...n),ze()&&!Me(n)&&ke("log",n)},console.info=(...n)=>{J.info(...n),ze()&&!Me(n)&&ke("info",n)},console.warn=(...n)=>{J.warn(...n),Me(n)||ke("warn",n)},console.error=(...n)=>{J.error(...n),Me(n)||ke("error",n)}}function Vs(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 a=JSON.stringify(r);t.push(a==="{}"?String(r):a)}else t.push(String(r))}catch{t.push(String(r))}return{message:t.join(" ")||"(empty)",stack:e}}function ke(n,e){try{const{message:t,stack:s}=Vs(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Ye=="function"&&Ye({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){J.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Ye=null;$s(),Promise.resolve().then(()=>he).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=B();t&&t.sendDebugLLMLog(e)})});const j="0.6.22",Qe=`drawnix-v${j}`,_="drawnix-images",Se=`drawnix-static-v${j}`,Oe="drawnix-fonts",Z="sw-cache-date",le="sw-cache-created-at",Ks="/__aitu_cache__/",Xs="/__aitu_generated__/audio/",Ys="/asset-library/",It=location.hostname==="localhost"||location.hostname==="127.0.0.1",Qs=[{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"}],Js=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Zs=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Je=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,en=new Set(["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","rand","_force","bypass_sw","direct_fetch","thumbnail","expires","signature","sig","token","policy","x-amz-algorithm","x-amz-credential","x-amz-date","x-amz-expires","x-amz-security-token","x-amz-signature","x-amz-signedheaders","x-goog-algorithm","x-goog-credential","x-goog-date","x-goog-expires","x-goog-signature","x-goog-signedheaders","ossaccesskeyid","x-oss-security-token","x-oss-signature-version","x-oss-credential","x-oss-date","x-oss-expires","x-oss-signature"]);function Ze(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)en.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const q=new Map,ue=new Map,Wt=30*1e3,Ce=new Map,x=new Map,tn=300*1e3,Bt=10,fe=new Set,pe=new Set,sn=3600*1e3,et=new Map;function xt(n){pe.add(n),et.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function nn(n){if(!pe.has(n))return!1;const e=et.get(n);return e&&Date.now()-e>sn?(pe.delete(n),et.delete(n),!1):!0}const K=[],Nt=7,F=[],rn=500;let M=!1;function k(n){if(!M)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return F.unshift(t),F.length>rn&&F.pop(),qt(t),e}function A(n,e){if(!M||!n)return;const t=F.find(s=>s.id===n);t&&(Object.assign(t,e),qt(t))}function qt(n){const e=B();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 on(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 Ht(){try{await Gt();const n=await Pe(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Nt*24*60*60*1e3;return new Promise((o,a)=>{const i=s.openCursor(null,"prev"),c=[];i.onsuccess=()=>{const l=i.result;if(l){const u=l.value;u.timestamp>=r&&c.push(u),l.continue()}else n.close(),o(c)},i.onerror=()=>{n.close(),a(i.error)}})}catch(n){return console.warn("Service Worker: 无法加载控制台日志:",n),[]}}async function Gt(){try{const n=await Pe(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Nt*24*60*60*1e3,o=IDBKeyRange.upperBound(r);return new Promise((a,i)=>{const c=s.openCursor(o);let l=0;c.onsuccess=()=>{const u=c.result;u?(u.delete(),l++,u.continue()):(n.close(),l>0,a(l))},c.onerror=()=>{n.close(),i(c.error)}})}catch(n){return console.warn("Service Worker: 无法清理过期日志:",n),0}}async function Ut(){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 jt=500;function tt(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(M||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};on(r),K.unshift(r),K.length>jt&&(K.length=jt),M&&an(r)}Ye=tt;function an(n){const e=B();e&&e.sendConsoleLog(n)}function cn(){let n=0;return x.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function Ft(){return{version:j,cacheNames:[Qe,_,Se,Oe],pendingImageRequests:q.size,pendingVideoRequests:Ce.size,videoBlobCacheSize:x.size,videoBlobCacheTotalBytes:cn(),completedImageRequestsSize:ue.size,failedDomainsCount:fe.size,failedDomains:Array.from(fe),corsFailedDomainsCount:pe.size,corsFailedDomains:Array.from(pe),debugLogsCount:F.length,consoleLogsCount:K.length,debugModeEnabled:M,memoryStats:{pendingRequestsMapSize:q.size,completedRequestsMapSize:ue.size,videoBlobCacheMapSize:x.size,failedDomainsSetSize:fe.size,corsFailedDomainsSetSize:pe.size,debugLogsArraySize:F.length,consoleLogsArraySize:K.length}}}function st(){return F}function zt(){F.length=0}function $t(){K.length=0}function nt(){M||(M=!0,ye(!0),Re(!0),J.log("Service Worker: Debug mode enabled (debug page connected)"))}function rt(){M&&(M=!1,ye(!1),Re(!1),K.length=0,F.length=0,J.log("Service Worker: Debug mode disabled (no debug pages)"))}function ln(n){n>0?nt():rt()}function Vt(n){for(const e of Qs)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function un(n,e){return Js.test(n.pathname)||e.destination==="image"||Vt(n)!==null}function hn(n,e){return Zs.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function dn(n,e){return Je.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function gn(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"}function fn(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}async function pn(){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 a=s.transaction(["failedDomains"],"readonly").objectStore("failedDomains").getAll();a.onsuccess=()=>{a.result.forEach(c=>fe.add(c.domain)),e()},a.onerror=()=>t(a.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 mn(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 bn(n){try{const e=await n.keys();if(e.length<=10)return;const t=[];for(const a of e)try{const i=await n.match(a);if(i){const c=i.headers.get(Z),l=i.headers.get("sw-image-size");t.push({request:a,cacheDate:c?parseInt(c):0,imageSize:l?parseInt(l):0})}}catch(i){console.warn("Service Worker: Error reading cache entry:",i)}t.sort((a,i)=>a.cacheDate-i.cacheDate);const s=Math.max(1,Math.floor(t.length*.25));let r=0,o=0;for(let a=0;a<s&&a<t.length;a++)try{await n.delete(t[a].request),r++,o+=t[a].imageSize}catch(i){console.warn("Service Worker: Error deleting cache entry:",i)}}catch(e){console.warn("Service Worker: Cache cleanup failed:",e)}}async function wn(){try{const n=await fetch("./precache-manifest.json",{cache:"reload"});return n.ok?(await n.json()).files:null}catch{return null}}async function yn(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,a="server";if(!r){const i=await Mt(e.startsWith("/")?e.slice(1):e,j,location.origin);i&&i.response.ok&&(o=i.response,a=i.source)}if(o||(o=await fetch(e,{cache:"reload"}),a="server"),o.ok){const i=new Headers(o.headers);i.set("x-sw-revision",t),i.set("x-sw-cached-at",new Date().toISOString()),i.set("x-sw-source",a);const c=new Response(await o.blob(),{status:o.status,statusText:o.statusText,headers:i}),l=new URL(e,self.location.origin).href;return await n.put(l,c),{url:e,success:!0,source:a}}return{url:e,success:!1,status:o.status}}catch(s){return{url:e,success:!1,error:String(s)}}}async function Sn(n,e){const s=[];for(let r=0;r<e.length;r+=6){const o=e.slice(r,r+6),a=await Promise.allSettled(o.map(({url:i,revision:c})=>yn(n,i,c)));for(const i of a)i.status==="fulfilled"?s.push({success:i.value.success,source:i.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 pn();try{const e=await wn();if(e&&e.length>0){const t=await caches.open(Se);await Sn(t,e)}}catch(e){console.warn("Service Worker: Precache failed:",e)}})())}),Q.addEventListener("activate",n=>{n.waitUntil((async()=>{await Q.clients.claim();const e=B();e&&e.sendSWActivated(j)})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(o=>o.startsWith("drawnix-images-v")&&o!==_);if(t.length>0){const o=await caches.open(_);for(const a of t)try{const i=await caches.open(a),c=await i.keys();for(const l of c){const u=await i.match(l);u&&await o.put(l,u)}await caches.delete(a)}catch(i){console.warn(`Failed to migrate cache ${a}:`,i)}}const s=e.filter(o=>o.startsWith("drawnix-static-v")&&o!==Se),r=e.filter(o=>o.startsWith("drawnix-v")&&o!==Qe&&o!==_&&!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(a){console.warn("Failed to delete old cache:",o,a)}},3e4),Gt().catch(o=>{console.warn("Failed to cleanup expired console logs:",o)}),pt.archiveOldTasks(100).catch(o=>{console.warn("Failed to archive old tasks:",o)})}))});function Cn(n){if(M){const e=B();e&&e.sendPostMessageLog(n)}}Q.addEventListener("message",n=>{var a,i,c,l,u,h,d,m,b,p;const e=((a=n.data)==null?void 0:a.type)||((i=n.data)==null?void 0:i.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=((d=n.data)==null?void 0:d.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=Ge(e,n.data,t,s,(p=n.data)==null?void 0:p.__internal__),o&&M)){const w=De().find(S=>S.id===o);w&&Cn(w)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:g,mediaType:w,blob:S,mimeType:C}=n.data;if(g&&w&&S){const L=new Blob([S],{type:C||(w==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:N}=await Promise.resolve().then(()=>H);N(L,g,w)})()}return}if(n.data&&n.data.type==="SKIP_WAITING"){Q.skipWaiting();const g=B();g&&g.sendSWUpdated(j)}else if(n.data&&n.data.type==="FORCE_UPGRADE"){Q.skipWaiting();const g=B();g&&g.sendSWUpdated(j)}else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:g}=n.data;g&&at(g).then(()=>{const w=B();w&&w.sendCacheDeleted(g)}).catch(w=>{console.error("Service Worker: Failed to delete cache:",w)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:g}=n.data;g&&Array.isArray(g)&&_n(g).then(()=>{}).catch(w=>{console.error("Service Worker: Failed to batch delete caches:",w)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")An().then(()=>{}).catch(g=>{console.error("Service Worker: Failed to clear all cache:",g)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){M=!0,ye(!0),Re(!0),J.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const g=B();g&&g.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){M=!1,ye(!1),Re(!1),K.length=0,F.length=0,J.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const g=B();g&&g.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:g}=await Promise.resolve().then(()=>he),w=await g(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:w})}catch(g){console.error("[SW] Failed to get LLM API logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:g}=await Promise.resolve().then(()=>he);await g();const w=n.source;w&&w.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(g){console.error("[SW] Failed to clear LLM API logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const g=n.source;g&&g.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:M,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:g}=await Promise.resolve().then(()=>Us),w=st(),S=g(),C=n.source;C&&C.postMessage({type:"SW_DEBUG_LOGS",logs:[...w,...S.map(L=>({...L,type:"fetch"}))]})}catch(g){console.error("[SW] Failed to get fetch logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const g=n.source;g&&g.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:K})}catch(g){console.error("[SW] Failed to get console logs:",g)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const g=De(),w=n.source;w&&w.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:g})}catch(g){console.error("[SW] Failed to get postmessage logs:",g)}})();return}});const En="MemorySnapshotDB",oe="snapshots",Kt=50;async function ot(){return new Promise((n,e)=>{const t=indexedDB.open(En,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(oe)){const o=r.createObjectStore(oe,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function Xt(n){try{const e=await ot(),t=e.transaction(oe,"readwrite"),s=t.objectStore(oe);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>Kt){const i=s.index("timestamp").openCursor();let c=0;const l=o-Kt;i.onsuccess=u=>{const h=u.target.result;h&&c<l&&(s.delete(h.value.id),c++,h.continue())}}},await new Promise((o,a)=>{t.oncomplete=()=>{e.close(),o()},t.onerror=()=>{e.close(),a(t.error)}})}catch(e){console.warn("[SW] Failed to save crash snapshot:",e)}}async function Yt(){try{const n=await ot(),s=n.transaction(oe,"readonly").objectStore(oe).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{n.close();const i=a.result.sort((c,l)=>l.timestamp-c.timestamp);r(i)},a.onerror=()=>{n.close(),o(a.error)}})}catch(n){return console.warn("[SW] Failed to get crash snapshots:",n),[]}}async function Qt(){try{const n=await ot(),e=n.transaction(oe,"readwrite");e.objectStore(oe).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 Tn=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Dn(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Ln(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,a=0,i=0,c=0;const l=10;try{const u=s.transaction(r,"readonly");for(const h of r){const d=u.objectStore(h),m=d.count();m.onsuccess=()=>{const b=m.result;if(o+=b,b>0){const p=d.openCursor();let g=0;p.onsuccess=w=>{const S=w.target.result;if(S&&g<l)a+=Dn(S.value),i++,g++,S.continue();else if(c++,c===r.length){s.close();const C=i>0?a/i:0,L=Math.round(C*o);e({count:o,totalSize:L})}},p.onerror=()=>{if(c++,c===r.length){s.close();const w=i>0?a/i:0,S=Math.round(w*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 b=i>0?a/i: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 Jt(){const n={},e=[Qe,_,Se,Oe];for(const t of e)try{const s=await caches.open(t),r=await s.keys();let o=0;const a=Math.min(r.length,100);let i=0;for(let c=0;c<a;c++){const l=await s.match(r[c]);if(l){const u=l.headers.get("sw-image-size")||l.headers.get("content-length");u&&(i+=parseInt(u))}}a>0&&r.length>a?o=Math.round(i/a*r.length):o=i,n[t]={count:r.length,totalSize:o,type:"cache"}}catch{n[t]={count:0,totalSize:0,type:"cache"}}for(const t of Tn)try{const s=await Ln(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function at(n){try{await(await caches.open(_)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function _n(n){try{const e=await caches.open(_);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 An(){try{const n=await caches.open(_),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 Zt(n,e,t){try{const s=B();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}async function vn(){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=B();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const ee=new Map,es=300*1e3,ts=500;function Rn(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 Mn(n){const e=ee.get(n);return e?Date.now()-e>es?(ee.delete(n),!1):!0:!1}function ss(n){if(Rn(n)){if(ee.size>=ts){const e=Date.now();for(const[t,s]of ee)e-s>es&&ee.delete(t);if(ee.size>=ts){const t=Array.from(ee.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)ee.delete(r)}}ee.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:"){k({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(Ks)||e.pathname.startsWith(Xs)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(On(n.request).then(r=>(A(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw A(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(Ys)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Pn(n.request).then(r=>(A(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw A(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"){k({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")){k({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")){k({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(nn(e.hostname)){k({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(e.origin!==location.origin&&dn(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"audio",headers:r?{range:r}:void 0,details:r?`Audio Range request: ${r}`:"External audio request"});n.respondWith(In(n.request).then(a=>(A(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,cached:a.headers.has(Z),responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw A(o,{error:String(a),duration:Date.now()-s}),a}));return}if(hn(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=k({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(Wn(n.request).then(a=>(A(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,responseHeaders:{"content-type":a.headers.get("content-type")||"","content-length":a.headers.get("content-length")||"","content-range":a.headers.get("content-range")||""}}),a)).catch(a=>{throw A(o,{error:String(a),duration:Date.now()-s}),a}));return}if(gn(e,n.request)){const s=Date.now(),r=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(kn(n.request).then(o=>(A(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 A(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&un(e,n.request)){if(Mn(n.request.url)){k({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=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(qn(n.request).then(o=>(o.status===404&&ss(n.request.url),A(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 ss(n.request.url),A(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(),a=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(Bn(n.request).then(i=>(A(a,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-o}),i)).catch(i=>{throw A(a,{error:String(i),duration:Date.now()-o}),i}));return}}if(M){if(fn(e)){k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"xhr",details:`Skipped SW debug interception for generateContent request (${n.request.method})`,duration:0});return}const s=k({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 a={};if(n.request.headers.forEach((h,d)=>{a[d]=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]"}A(s,{headers:a,details:o?`XHR/API request (${n.request.method})
2
2
 
3
3
  Request Body:
4
4
  ${o}`:`XHR/API request (${n.request.method})`});const i=await fetch(n.request),c=i.clone();let l;const u={};i.headers.forEach((h,d)=>{u[d]=h});try{const h=i.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"}] (${i.headers.get("content-length")||"unknown"} bytes)`}catch{l="[unable to read response body]"}return A(s,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-t,responseHeaders:u,size:parseInt(i.headers.get("content-length")||"0"),details:o?`XHR/API request (${n.request.method})