aitu-app 0.6.76 → 0.6.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/assets/CanvasAudioPlayer-DutgwdiU.js +2 -0
- package/assets/ChatDrawer-E6Fog16I.js +11 -0
- package/assets/{ChatMessagesArea-CZkiRzmW.js → ChatMessagesArea-Bgwiz_XP.js} +3 -3
- package/assets/DeferredAIInputBar-CPkD8Cv9.js +8 -0
- package/assets/DeferredAIInputBar-szBPHiNW.css +1 -0
- package/assets/DrawnixDeferredFeatures-Cul76-88.js +2 -0
- package/assets/{KnowledgeBaseContent-Dan2DUqY.js → KnowledgeBaseContent-DcX5Jofx.js} +6 -6
- package/assets/{MVCreator-Dzjl2fXA.js → MVCreator-DllHozYg.js} +8 -8
- package/assets/{ModelBenchmarkWorkbench-oy2wue1u.js → ModelBenchmarkWorkbench-Dv9SNYTi.js} +2 -2
- package/assets/MusicAnalyzer-CHcQ5t4P.js +1 -0
- package/assets/{MusicAnalyzer-BO44f-db.js → MusicAnalyzer-DDeT6g3c.js} +2 -2
- package/assets/ResizableDivider-CaG9JQbJ.js +1 -0
- package/assets/TaskQueuePanel-BNhNzGp5.js +1 -0
- package/assets/{VideoAnalyzer-iiJpoWb6.js → VideoAnalyzer-BSLz1FaI.js} +2 -2
- package/assets/ai-generation-preferences-service-BF7QkuJp.js +1 -0
- package/assets/arc-BU2KKCa_.js +1 -0
- package/assets/arc-DmGoDCEL.js +1 -0
- package/assets/{batch-image-generation-B2R0hJW_.js → batch-image-generation-Bg68r_Ql.js} +5 -5
- package/assets/{blockDiagram-38ab4fdb-BmWPnNuS.js → blockDiagram-38ab4fdb-BCGEnMME.js} +1 -1
- package/assets/{blockDiagram-38ab4fdb-trArAOFP.js → blockDiagram-38ab4fdb-CsZR5uC5.js} +1 -1
- package/assets/board-utils-CpAtoKn2.js +1 -0
- package/assets/{browser-Dya3c6_X.js → browser-DpICcNby.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-Cvj3RMOv.js → c4Diagram-3d4e48cf-9fuiuFdV.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-CqJrO4Za.js → c4Diagram-3d4e48cf-WM4wd_GR.js} +1 -1
- package/assets/{canvas-insertion-Dq3gR9Nw.js → canvas-insertion-CdUQF7IV.js} +3 -3
- package/assets/channel-CZjE-WNp.js +1 -0
- package/assets/channel-SXZD6bG3.js +1 -0
- package/assets/classDiagram-70f12bd4-CBVHTwQu.js +2 -0
- package/assets/{classDiagram-70f12bd4-DvrRZ41d.js → classDiagram-70f12bd4-DcYDedz1.js} +2 -2
- package/assets/classDiagram-v2-f2320105-CsxWGkSy.js +2 -0
- package/assets/classDiagram-v2-f2320105-jpCwaHEd.js +2 -0
- package/assets/{clipper-B4i11tN1.js → clipper-jvd5rF5a.js} +1 -1
- package/assets/clone-C4mvvMDb.js +1 -0
- package/assets/{createText-2e5e7dd3-D7dXlVes.js → createText-2e5e7dd3-CkXS3l7I.js} +2 -2
- package/assets/{createText-2e5e7dd3-B8gnT5hD.js → createText-2e5e7dd3-x5lOIwut.js} +1 -1
- package/assets/edges-e0da2a9e-CbrF4nbD.js +4 -0
- package/assets/{edges-e0da2a9e-CyRAzEMi.js → edges-e0da2a9e-Ch6PBwWs.js} +2 -2
- package/assets/{erDiagram-9861fffd-D8yYsjoN.js → erDiagram-9861fffd-Bq07elcI.js} +3 -3
- package/assets/{erDiagram-9861fffd-BHbAa_Ka.js → erDiagram-9861fffd-DSlNVuAZ.js} +4 -4
- package/assets/{flowDb-956e92f1-DAqb8wjP.js → flowDb-956e92f1-BqPCJlZp.js} +3 -3
- package/assets/{flowDb-956e92f1-f30uG4pp.js → flowDb-956e92f1-Ti5YC4Vv.js} +3 -3
- package/assets/{flowDiagram-66a62f08-C4Gz9mOM.js → flowDiagram-66a62f08-CPDuG3rY.js} +3 -3
- package/assets/{flowDiagram-66a62f08-CBXypoEi.js → flowDiagram-66a62f08-D3GSABFi.js} +1 -1
- package/assets/flowDiagram-v2-96b9c2cf-BCcJ-cre.js +1 -0
- package/assets/flowDiagram-v2-96b9c2cf-DCVaFEgV.js +1 -0
- package/assets/{flowchart-elk-definition-4a651766-CSm5diF6.js → flowchart-elk-definition-4a651766-BH09NeLA.js} +1 -1
- package/assets/{flowchart-elk-definition-4a651766-BHB7pRxm.js → flowchart-elk-definition-4a651766-BLaLPCDV.js} +1 -1
- package/assets/{ganttDiagram-c361ad54-CU9a9DsJ.js → ganttDiagram-c361ad54-DL9ZeaEc.js} +4 -4
- package/assets/ganttDiagram-c361ad54-Sp9M1KHP.js +257 -0
- package/assets/{gitGraphDiagram-72cf32ee-B2zj8Xnu.js → gitGraphDiagram-72cf32ee-BSf1fsDV.js} +1 -1
- package/assets/{gitGraphDiagram-72cf32ee-BWOgrFeh.js → gitGraphDiagram-72cf32ee-BWwmRKo-.js} +1 -1
- package/assets/{graph-Bnmq4jgf.js → graph--nPw8zXQ.js} +1 -1
- package/assets/graph-g-2U7grQ.js +1 -0
- package/assets/{index-3862675e-CQLKy6RO.js → index-3862675e-BXwbZ2pz.js} +1 -1
- package/assets/{index-3862675e-BSxxidV_.js → index-3862675e-D6Zy95zZ.js} +1 -1
- package/assets/index-3eqA7Bag.js +1 -0
- package/assets/{index-D1ORCZqJ.js → index-7Q-aiwln.js} +2 -2
- package/assets/index-B2dttXd7.js +1 -0
- package/assets/index-B7V7-Vxz.js +1 -0
- package/assets/index-BHPTfCZM.js +1 -0
- package/assets/{index-vvV37Q1S.js → index-BP77pG9S.js} +4 -4
- package/assets/index-BPR_DyGD.js +1 -0
- package/assets/index-BWrcsh8u.js +1 -0
- package/assets/{index-D4qm_1m5.js → index-BXzGHPXz.js} +1 -1
- package/assets/index-BaCHOxhI.js +1 -0
- package/assets/{index-BoglETHF.js → index-Bq8mPedC.js} +2 -2
- package/assets/index-BqHZCcen.js +2 -0
- package/assets/index-Bti3m-iW.js +1 -0
- package/assets/{index-sPNG1_UN.js → index-BwSnJN93.js} +5 -5
- package/assets/{index-D5qxbeGT.js → index-C3qD42ws.js} +1 -1
- package/assets/{index-VzDb_AHs.js → index-C5eu4uSl.js} +5 -5
- package/assets/index-CLJUfzvO.js +1 -0
- package/assets/index-CfgvFFx3.js +271 -0
- package/assets/index-CmyOpFTN.js +1 -0
- package/assets/index-D4pIkh3S.js +1 -0
- package/assets/index-D7b5fX1d.js +1 -0
- package/assets/index-DH12_HTj.js +13 -0
- package/assets/index-DI0OV6F8.js +7 -0
- package/assets/index-DIiIUyb-.js +1 -0
- package/assets/index-DcZrElEK.js +2 -0
- package/assets/index-DllL1sx1.js +1 -0
- package/assets/index-DqMndQiP.js +1 -0
- package/assets/index-Dz8sghkK.js +1 -0
- package/assets/index-QkP3EC02.js +1 -0
- package/assets/index-TkfyNewx.js +1 -0
- package/assets/index-ZrVeQUWo.js +1 -0
- package/assets/index-eZfwJ9bV.js +3 -0
- package/assets/{index-VarwiJlL.js → index-gQ7LgvSv.js} +1 -1
- package/assets/{infoDiagram-f8f76790-d-BYTW2w.js → infoDiagram-f8f76790-DpFqCCNv.js} +3 -3
- package/assets/{infoDiagram-f8f76790-BMsVq8O_.js → infoDiagram-f8f76790-G2JpJJP7.js} +3 -3
- package/assets/{journeyDiagram-49397b02-DCtCkoaC.js → journeyDiagram-49397b02-BdESGMrv.js} +1 -1
- package/assets/{journeyDiagram-49397b02-CBqb8-ml.js → journeyDiagram-49397b02-DLLTobRM.js} +1 -1
- package/assets/{layout-DKqEkE_W.js → layout-CVkuImk4.js} +1 -1
- package/assets/layout-WSR0vNPO.js +1 -0
- package/assets/line-D3bnG227.js +1 -0
- package/assets/line-DQuMJveY.js +1 -0
- package/assets/{linear-C6OQYT56.js → linear-CciP-97N.js} +1 -1
- package/assets/linear-Z6vFvuwc.js +1 -0
- package/assets/{main-i0s2IJTn.css → main-8DNjLY6L.css} +1 -1
- package/assets/main-BFEkxCOK.js +56 -0
- package/assets/{mermaid.core-CI-VJEiw.js → mermaid.core-CwZQb0ud.js} +5 -5
- package/assets/{mindmap-definition-fc14e90a-k_RSypuP.js → mindmap-definition-fc14e90a-BnJ8OOTI.js} +1 -1
- package/assets/{mindmap-definition-fc14e90a-DrtlQLES.js → mindmap-definition-fc14e90a-CxQMydCW.js} +1 -1
- package/assets/model-benchmark-launcher-Ct3lYXVq.js +1 -0
- package/assets/photo-wall-splitter-BZ88W5Zy.js +1 -0
- package/assets/{pieDiagram-8a3498a8-CdknGxKY.js → pieDiagram-8a3498a8-BSDdkTeu.js} +5 -5
- package/assets/{pieDiagram-8a3498a8-Bpr5V3o5.js → pieDiagram-8a3498a8-D6VtAoja.js} +4 -4
- package/assets/ppt-generation-FzjP_rp0.js +48 -0
- package/assets/{quadrantDiagram-120e2f19-Dx3qoKDx.js → quadrantDiagram-120e2f19-BbFV0VXY.js} +3 -3
- package/assets/{quadrantDiagram-120e2f19-pVIXp9i6.js → quadrantDiagram-120e2f19-C8k2xuBd.js} +3 -3
- package/assets/{requirementDiagram-deff3bca-hM4oekUG.js → requirementDiagram-deff3bca-C3xMdzJV.js} +1 -1
- package/assets/{requirementDiagram-deff3bca-DD6NY75P.js → requirementDiagram-deff3bca-CpjqKjYZ.js} +1 -1
- package/assets/{sankeyDiagram-04a897e0-BsvEG71N.js → sankeyDiagram-04a897e0-BBJJgsFv.js} +5 -5
- package/assets/{sankeyDiagram-04a897e0-C9uf1jU5.js → sankeyDiagram-04a897e0-Bjvig9bW.js} +4 -4
- package/assets/{sequenceDiagram-704730f1-CNEBmz1G.js → sequenceDiagram-704730f1-DX1MmBN_.js} +4 -4
- package/assets/{sequenceDiagram-704730f1-Bpg54z74.js → sequenceDiagram-704730f1-PFC_9IFI.js} +4 -4
- package/assets/settings-dialog-CQM4v791.js +1 -0
- package/assets/{skill-dsl-parser-DS3VOBFI.js → skill-dsl-parser-syNWYxFu.js} +10 -10
- package/assets/{stateDiagram-587899a1-BN2ZP-3x.js → stateDiagram-587899a1-Dc3mI_B_.js} +1 -1
- package/assets/stateDiagram-587899a1-SFMUVAam.js +1 -0
- package/assets/{stateDiagram-v2-d93cdb3a-BtV1Ziy9.js → stateDiagram-v2-d93cdb3a-DmnBjHpC.js} +1 -1
- package/assets/{stateDiagram-v2-d93cdb3a-BLwIM8s1.js → stateDiagram-v2-d93cdb3a-P4Yt2p_j.js} +1 -1
- package/assets/{styles-6aaf32cf-aFVlX_lA.js → styles-6aaf32cf-C3jnr3hV.js} +1 -1
- package/assets/{styles-6aaf32cf-CGp3i5qu.js → styles-6aaf32cf-b6AdP7fu.js} +1 -1
- package/assets/{styles-9a916d00-BK7pejCH.js → styles-9a916d00-BUiD9iBe.js} +4 -4
- package/assets/{styles-9a916d00-CSwFWVnr.js → styles-9a916d00-ii0XTdIm.js} +1 -1
- package/assets/styles-c10674c1-Bt89Yy8Q.js +116 -0
- package/assets/styles-c10674c1-DbTSpy3W.js +116 -0
- package/assets/{svgDrawCommon-08f97a94-Cr4rWU-W.js → svgDrawCommon-08f97a94-BK6lD4D6.js} +1 -1
- package/assets/{svgDrawCommon-08f97a94-DypvMDvH.js → svgDrawCommon-08f97a94-D4gIV05W.js} +1 -1
- package/assets/{timeline-definition-85554ec2-D3-lXEL5.js → timeline-definition-85554ec2-Bl2y548G.js} +1 -1
- package/assets/{timeline-definition-85554ec2-DIwHE15c.js → timeline-definition-85554ec2-CWKg_JxG.js} +3 -3
- package/assets/{tool-windows-B-a9r3G3.css → tool-windows-CUNbW1Tz.css} +1 -1
- package/assets/tool-windows-DOIu9TAD.js +2975 -0
- package/assets/ttd-dialog-DI4kQSg8.js +99 -0
- package/assets/{useCharacters-DsZ779l-.js → useCharacters-Chv4Ky7x.js} +3 -3
- package/assets/useWorkflowSubmission-BizuDmuw.js +70 -0
- package/assets/video-analyze-6v3Y-rUE.js +1 -0
- package/assets/{video-generation-C7qCz-ZF.js → video-generation-DnmTlWnm.js} +2 -2
- package/assets/video-recovery-service-BeRoh0s2.js +1 -0
- package/assets/workflow-generation-utils-me381Cax.js +3 -0
- package/assets/workflow-submission-service-YOpo7g37.js +4 -0
- package/assets/{xychartDiagram-e933f94c-B17Evxfw.js → xychartDiagram-e933f94c-CJX9_9WF.js} +4 -4
- package/assets/{xychartDiagram-e933f94c-Dln5PJtU.js → xychartDiagram-e933f94c-Cep8CQEH.js} +3 -3
- package/changelog.json +50 -0
- package/idle-prefetch-manifest.json +300 -316
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +8 -8
- package/sw.js +5 -5
- package/version.json +19 -3
- package/assets/CanvasAudioPlayer-DwM6PU4W.js +0 -2
- package/assets/ChatDrawer-BQTaa6r6.js +0 -11
- package/assets/DeferredAIInputBar-BmPgFhXr.css +0 -1
- package/assets/DeferredAIInputBar-ObyfJQ0O.js +0 -7
- package/assets/DrawnixDeferredFeatures-CFHVLxc5.js +0 -2
- package/assets/ModelDropdown-CQTTHEI7.css +0 -1
- package/assets/ModelDropdown-DjvIvi8O.js +0 -1
- package/assets/MusicAnalyzer-BU5l2wPR.js +0 -1
- package/assets/ResizableDivider-CBgTphcS.js +0 -1
- package/assets/TaskQueuePanel-CTDuSScf.js +0 -1
- package/assets/ai-generation-preferences-service-CqwXb9Cs.js +0 -5
- package/assets/arc-BBE0LXa1.js +0 -1
- package/assets/arc-h476db6P.js +0 -1
- package/assets/channel-DMTz1UNN.js +0 -1
- package/assets/channel-DQOY3XLe.js +0 -1
- package/assets/classDiagram-70f12bd4-5ACx619h.js +0 -2
- package/assets/classDiagram-v2-f2320105-4zQ4jrwi.js +0 -2
- package/assets/classDiagram-v2-f2320105-CB4rof84.js +0 -2
- package/assets/clone-fuaXEdc-.js +0 -1
- package/assets/edges-e0da2a9e-DZalSm7f.js +0 -4
- package/assets/flowDiagram-v2-96b9c2cf-C-DFFh54.js +0 -1
- package/assets/flowDiagram-v2-96b9c2cf-CWjydvHB.js +0 -1
- package/assets/ganttDiagram-c361ad54-DDnbMkWm.js +0 -257
- package/assets/graph-BsYIlc-B.js +0 -1
- package/assets/index-B10kMZoq.js +0 -1
- package/assets/index-B2_XRj3U.js +0 -1
- package/assets/index-B4lLv-Sz.js +0 -1
- package/assets/index-BFZNUUCR.js +0 -1
- package/assets/index-BTSYG2Vy.js +0 -1
- package/assets/index-BY5Kvjqg.js +0 -1
- package/assets/index-Blf7J5yW.js +0 -1
- package/assets/index-BoQA7VaE.js +0 -3
- package/assets/index-BzqQ69oU.js +0 -1
- package/assets/index-CD2D1BYc.js +0 -2
- package/assets/index-CLRs5cWt.js +0 -1
- package/assets/index-CLU4LJjR.js +0 -1
- package/assets/index-CPDfMZkS.js +0 -1
- package/assets/index-CPfhqyDz.js +0 -316
- package/assets/index-CU4ySaQE.js +0 -1
- package/assets/index-CsCwwmYY.js +0 -1
- package/assets/index-Cyz_w8KS.js +0 -7
- package/assets/index-D489cJtb.js +0 -1
- package/assets/index-D6DebbcI.js +0 -1
- package/assets/index-DDtPG6Km.js +0 -1
- package/assets/index-DKhTnUBU.js +0 -1
- package/assets/index-DMIwLDS8.js +0 -13
- package/assets/index-DgsUJgRJ.js +0 -1
- package/assets/index-oT8mbA3U.js +0 -2
- package/assets/layout-B1ePJO5V.js +0 -1
- package/assets/line-C_jmJ6v1.js +0 -1
- package/assets/line-DfhCgsyz.js +0 -1
- package/assets/linear-ChY5Iu43.js +0 -1
- package/assets/main-LCg1nQGB.js +0 -69
- package/assets/model-benchmark-launcher-B2MsZXmV.js +0 -1
- package/assets/model-benchmark-service-CkIRp-Sq.js +0 -1
- package/assets/model-selection-BvdXmVGX.js +0 -1
- package/assets/photo-wall-splitter-CVrfkWnh.js +0 -1
- package/assets/prompt-optimize-dialog-DLdL2_a1.css +0 -1
- package/assets/settings-dialog-CAhU3cfG.js +0 -1
- package/assets/stateDiagram-587899a1-CMylUAYu.js +0 -1
- package/assets/styles-c10674c1-KfJINP7I.js +0 -116
- package/assets/styles-c10674c1-cccyjRUz.js +0 -116
- package/assets/tool-windows-CtLXQDGF.js +0 -2847
- package/assets/ttd-dialog-BRg3XE5k.js +0 -99
- package/assets/use-runtime-models-BH9r4Yc1.js +0 -1
- package/assets/use-runtime-models-BgWWl4Ng.css +0 -1
- package/assets/useWorkflowSubmission-BeJQ3BuO.js +0 -70
- package/assets/video-analyze-aDVIfgUi.js +0 -1
- package/assets/video-recovery-service-Dy0xiPr8.js +0 -1
- package/assets/workflow-generation-utils-CpMilOwA.js +0 -3
- package/assets/workflow-submission-service-CmBBMIis.js +0 -4
package/sw.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var sw=(function(D){"use strict";var pe=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(pe||{});pe.IMAGE+"",pe.VIDEO+"",pe.AUDIO+"",pe.CHARACTER+"",pe.INSPIRATION_BOARD+"",pe.CHAT+"";function oe(n){return n instanceof Error?n.name||"Error":"Unknown error"}const yt="sw-task-queue",hn=3,_="tasks",z="config",B="workflows",x="chat-workflows",M="pending-tool-requests",P="pending-dom-operations",N="task-step-mappings",$="pending-canvas-operations",ks=[_,z,B,x,M,P,N,$];function Os(){return new Promise(n=>{const e=indexedDB.open(yt);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,hn))},e.onerror=()=>{n(hn)}})}function Ws(n){const e=[];for(const t of ks)n.objectStoreNames.contains(t)||e.push(t);return e}function Bs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(yt,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;gn(a)}})}function gn(n){if(!n.objectStoreNames.contains(_)){const e=n.createObjectStore(_,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("type","type",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(z)||n.createObjectStore(z,{keyPath:"key"}),!n.objectStoreNames.contains(B)){const e=n.createObjectStore(B,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(x)){const e=n.createObjectStore(x,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(M)||n.createObjectStore(M,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(P)){const e=n.createObjectStore(P,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(N)||n.createObjectStore(N,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains($)||n.createObjectStore($,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function xs(){const n=await Os();return new Promise((e,t)=>{const s=indexedDB.open(yt,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=Ws(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),Bs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;gn(o)}})}class Ns{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=xs()),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(_,"readwrite"),i=a.objectStore(_);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(_,"readwrite").objectStore(_).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(_,"readonly").objectStore(_).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(_,"readonly").objectStore(_).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(_,"readonly").objectStore(_).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 f=i.transaction(_,"readonly").objectStore(_).index("createdAt"),p=a==="desc"?"prev":"next",g=f.openCursor(null,p),m=[];let d=0,b=0;g.onerror=()=>l(g.error),g.onsuccess=S=>{const E=S.target.result;if(!E){c({tasks:m,total:b,hasMore:b>t+m.length});return}const A=E.value,q=!r||A.status===r,re=!o||A.type===o;q&&re&&(b++,d<t?d++:m.length<s&&m.push(A)),E.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(_,"readwrite").objectStore(_).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(z,"readonly").objectStore(z).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:",oe(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const a=s.transaction(z,"readwrite");a.objectStore(z).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:",oe(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(z,"readwrite");o.objectStore(z).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(z,"readonly").objectStore(z).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(B,"readwrite").objectStore(B).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(B,"readonly").objectStore(B).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(B,"readonly").objectStore(B).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(B,"readonly").objectStore(B).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(B,"readwrite").objectStore(B).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(x,"readwrite").objectStore(x).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(x,"readonly").objectStore(x).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(x,"readonly").objectStore(x).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(x,"readonly").objectStore(x).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(x,"readwrite").objectStore(x).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(M,"readwrite").objectStore(M).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(M,"readonly").objectStore(M).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(M,"readonly").objectStore(M).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(M,"readonly").objectStore(M).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(M,"readwrite").objectStore(M).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(M,"readwrite"),c=a.objectStore(M).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(P,"readwrite").objectStore(P).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(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 pending DOM operations:",e),[]}}async getPendingDomOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(P,"readonly").objectStore(P).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by workflow:",t),[]}}async getPendingDomOperationsByChatId(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(P,"readonly").objectStore(P).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(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 pending DOM operation:",t),null}}async deletePendingDomOperation(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 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(N,"readwrite").objectStore(N).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(N,"readonly").objectStore(N).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(N,"readonly").objectStore(N).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(N,"readonly").objectStore(N).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(N,"readwrite").objectStore(N).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($,"readwrite").objectStore($).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($,"readonly").objectStore($).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($,"readonly").objectStore($).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending canvas operations by workflow:",t),[]}}async deletePendingCanvasOperation(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction($,"readwrite").objectStore($).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 f=t.transaction(_,"readonly").objectStore(_).index("createdAt"),p=[],g=f.openCursor(null,"next");g.onsuccess=()=>{const m=g.result;if(!m){c(p);return}const d=m.value;d.archived||p.push(d),m.continue()},g.onerror=()=>l(g.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(_,"readwrite"),h=u.objectStore(_);for(const f of a)f.archived=!0,f.updatedAt=i,h.put(f);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 fn=new Ns,Gs=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function St(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=>St(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();Gs.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=St(s)}return e}return n}let Ve=!1;const Fs=500,ae=[];let Ct=0;function pn(){return Ve}const mn=["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"],ke=new Map;function bn(n){const e=Ve;Ve=n,!n&&e&&(ae.length=0,ke.clear(),Ct=0)}function Et(){return Ve}function Us(n){if(!pn()||n==="unknown"||mn.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)),mn.includes(e))return!1}return!0}function Hs(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 Tt(n,e,t,s,r){if(r||!Us(n))return"";const o=Hs(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++Ct}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:wn(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(qs(i),zs(n)){const c=$s(e);c&&ke.set(c,{entry:i,startTime:Date.now()})}return a}function qs(n){ae.unshift(n),ae.length>Fs&&ae.pop()}function Dt(n,e,t,s){if(!pn())return"";const r=ke.get(n);if(r){r.entry.response=wn(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return ke.delete(n),o}return""}function Ke(){return[...ae]}function js(){ae.length=0,ke.clear(),Ct=0}function zs(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 $s(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function wn(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return St(e)}catch{return"[Non-serializable data]"}}function Vs(){const n={total:ae.length,sent:0,received:0,byType:{}};for(const e of ae)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const _t=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:js,getAllLogs:Ke,getLogStats:Vs,isPostMessageLoggerDebugMode:Et,logReceivedMessage:Tt,setPostMessageLoggerDebugMode:bn,updateRequestWithResponse:Dt},Symbol.toStringTag,{value:"Module"}));function Ks(){return typeof window<"u"?window:typeof self<"u"?self:{}}function Xs(n){return JSON.parse(JSON.stringify(n))}function yn(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 Ys="postmessage-duplex",Qs="1.2.0",Xe=Ks();var X,ie;Xe.__POSTMESSAGE_DUPLEX__||(Xe.__POSTMESSAGE_DUPLEX__={}),Xe.__POSTMESSAGE_DUPLEX__.version=Qs,Xe.__POSTMESSAGE_DUPLEX__.name=Ys,(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"})(X||(X={})),(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"})(ie||(ie={}));class ce 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,ce)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class Js{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 Zs{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 er{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 Sn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const J=n=>({valid:0,error:n});function tr(n){if(!Sn(n))return J("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"?J("requestId must be a string"):s&&typeof e.cmdname!="string"?J("cmdname must be a string"):r&&typeof e.msg!="string"?J("msg must be a string"):!o||typeof(a=e.ret)=="number"&&Object.values(X).includes(a)?"data"in e&&e.data!==void 0&&!Sn(e.data)?J("data must be an object"):"_senderKey"in e&&e._senderKey!==void 0&&typeof e._senderKey!="string"?J("_senderKey must be a string"):!("time"in e)||e.time===void 0||typeof e.time=="number"&&Number.isFinite(e.time)?{valid:1,message:e}:J("time must be a finite number"):J("ret must be a valid ReturnCode"):J("Message must have requestId, cmdname, or msg field");var a}function Ye(n){return"ret"in n&&typeof n.ret=="number"}function nr(n){return n.msg==="ready"}function sr(n){return n._broadcast==1&&typeof n.cmdname=="string"}function rr(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const Rt=[],Z=[];function Cn(n){Z.length>=200&&Z.shift(),Z.push(n)}function En(n,e){for(let t=Z.length-1;t>=0;t--)if(Z[t].requestId===n&&Z[t].status==="pending"){Z[t].status=e,Z[t].duration=Date.now()-Z[t].timestamp;break}}class or extends er{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 Js,this.rateLimiter=new Zs((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,Rt.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{Cn({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?En(i,"ok"):Cn({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{En(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=rr(e);if(t>this.maxMessageSize){const s=new ce(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ie.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):Ye(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=tr(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:Ye(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(!sr(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:X.Success,data:o})}catch(o){const a=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:X.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(!nr(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}),Ye(e)||this.sendMessage({requestId:t,ret:X.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Ye(e)&&(this.log("warn","No registered handler for:",s||t),this.sendMessage({requestId:t,ret:X.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 ce("Cannot publish: channel has been destroyed",ie.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:X.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=Rt.findIndex(r=>r.deref()===t);s!==-1&&Rt.splice(s,1)})(this);const e=new ce("Channel has been destroyed",ie.ConnectionDestroyed);for(const[t,s]of this.callbackMap)try{s.reject({ret:X.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 Y{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 Y.instance||(Y.instance=new Y),Y.instance}static resetInstance(){Y.instance&&(Y.instance.shutdown(),Y.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(Y,"instance",{enumerable:1,configurable:1,writable:1,value:null});class w extends or{static enableGlobalRouting(e){w.useGlobalRouting=1,w.unknownClientCallback=e??null,w.globalListenerSetup||(self.addEventListener("message",w.globalMessageHandler),w.globalListenerSetup=1)}static disableGlobalRouting(){w.useGlobalRouting=0,w.globalListenerSetup&&(self.removeEventListener("message",w.globalMessageHandler),w.globalListenerSetup=0)}static setupHub(e={}){if(w.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");w.hubOptions=e,w.hubInitialized=1,Y.getInstance().setup(e,s=>w.createFromWorker(s)),w.enableGlobalRouting((s,r)=>{const o=w.createFromWorker(s);w.setupChannelHandlers(o,s),o.handleMessage(r)}),w.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(w.cleanupIntervalId=setInterval(()=>w.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){w.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 w.clientMeta.set(t,s),(o=(r=w.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:w.clientMeta.size}}),w.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:w.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of w.globalSubscribeMap)e.subscribe(s,async o=>{const a=w.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 w.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:w.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 w.channelsByClientId)if(!r.has(o)){const a=w.channelsByClientId.get(o);a&&a.destroy(),w.clientMeta.delete(o),(t=(e=w.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!w.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=w.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(!w.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=w.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=w.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 w.clientMeta.get(e)}static getAllClients(){return new Map(w.clientMeta)}static getClientsByType(e){const t=[];for(const s of w.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.`),w.globalSubscribeMap.set(e,t);for(const[s,r]of w.channelsByClientId)r.subscribe(e,async o=>{const a=w.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){w.globalSubscribeMap.delete(e);for(const t of w.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&w.useGlobalRouting&&w.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&w.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return w.channelsByClientId.get(e)}static hasChannel(e){return w.channelsByClientId.has(e)}static getChannelCount(){return w.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=yn("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=yn("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(w.useGlobalRouting)return void(w.globalListenerSetup||(self.addEventListener("message",w.globalMessageHandler),w.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(w.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=Xs(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===X.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 ce("Heartbeat detection failed",ie.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 ce("All reconnection attempts failed",ie.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 ce("Handshake timeout",ie.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 w(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 w(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 w.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(w,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(w,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(w,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(w,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(w,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(w,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(w,"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=w.channelsByClientId.get(t);s?s.handleMessage(n):w.unknownClientCallback&&w.unknownClientCallback(t,n)}});function ar(n,e,t){return Promise.race([n,new Promise(s=>setTimeout(()=>s(t),e))])}const T={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"},G={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(),w.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 fn.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:w.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=Ke().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=Et()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=Tt(`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=Dt(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=Dt(i,null,Date.now()-a,String(u));h&&this.broadcastPostMessageLog(h)}throw u}}}createSubscribeMap(e){return{[T.THUMBNAIL_GENERATE]:this.wrapRpcHandler(T.THUMBNAIL_GENERATE,e,t=>this.handleThumbnailGenerate(t)),[T.CRASH_SNAPSHOT]:async t=>{const s=this.unwrapRpcData(t);return this.handleCrashSnapshot(s)},[T.CRASH_HEARTBEAT]:async t=>{const s=this.unwrapRpcData(t);return this.handleHeartbeat(s)},[T.CONSOLE_REPORT]:async t=>{const s=this.unwrapRpcData(t);return this.handleConsoleReport(s)},[T.DEBUG_GET_STATUS]:async()=>this.handleDebugGetStatus(),[T.DEBUG_ENABLE]:async()=>this.handleDebugEnable(),[T.DEBUG_DISABLE]:async()=>this.handleDebugDisable(),[T.DEBUG_GET_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLogs(s)},[T.DEBUG_CLEAR_LOGS]:async()=>this.handleDebugClearLogs(),[T.DEBUG_GET_CONSOLE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetConsoleLogs(s)},[T.DEBUG_CLEAR_CONSOLE_LOGS]:async()=>this.handleDebugClearConsoleLogs(),[T.DEBUG_GET_POSTMESSAGE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetPostMessageLogs(s)},[T.DEBUG_CLEAR_POSTMESSAGE_LOGS]:async()=>this.handleDebugClearPostMessageLogs(),[T.DEBUG_GET_CRASH_SNAPSHOTS]:async()=>this.handleDebugGetCrashSnapshots(),[T.DEBUG_CLEAR_CRASH_SNAPSHOTS]:async()=>this.handleDebugClearCrashSnapshots(),[T.DEBUG_GET_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogs(s)},[T.DEBUG_GET_LLM_API_LOG_BY_ID]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogById(s==null?void 0:s.logId)},[T.DEBUG_CLEAR_LLM_API_LOGS]:async()=>this.handleDebugClearLLMApiLogs(),[T.DEBUG_DELETE_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugDeleteLLMApiLogs(s)},[T.DEBUG_GET_CACHE_ENTRIES]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetCacheEntries(s)},[T.DEBUG_GET_CACHE_STATS]:async()=>this.handleDebugGetCacheStats(),[T.DEBUG_EXPORT_LOGS]:async()=>this.handleDebugExportLogs(),[T.CDN_GET_STATUS]:async()=>this.handleCDNGetStatus(),[T.CDN_RESET_STATUS]:async()=>this.handleCDNResetStatus(),[T.CDN_HEALTH_CHECK]:async()=>this.handleCDNHealthCheck(),[T.UPGRADE_GET_STATUS]:async()=>this.handleUpgradeGetStatus(),[T.UPGRADE_FORCE]:async()=>this.handleUpgradeForce(),[T.CACHE_DELETE]:async t=>{const s=this.unwrapRpcData(t);return this.handleCacheDelete(s)},[T.PING]:async()=>this.handlePing()}}async handleThumbnailGenerate(e){try{const{url:t,mediaType:s,blob:r,mimeType:o,sizes:a}=e,{generateThumbnailAsync:i}=await Promise.resolve().then(()=>H),c=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return i(c,t,s,a),{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(()=>R);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(()=>R),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(()=>R),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(()=>R);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(()=>R);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(()=>R),{limit:r=100,offset:o=0,filter:a}=e||{},i=s().map(f=>({...f,type:"fetch"})),c=t(),l=new Map;for(const f of c)l.set(f.id,f);for(const f of i)l.set(f.id,f);let u=Array.from(l.values()).sort((f,p)=>p.timestamp-f.timestamp);return a&&(a.type&&(u=u.filter(f=>f.type===a.type)),a.status&&(u=u.filter(f=>f.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(()=>R);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>R),{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(()=>R);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>_t),{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(()=>_t);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>R),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(()=>R);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(()=>Te);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(()=>Te);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(()=>Te);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(()=>Te);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(()=>R),{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 f=h.headers.get("sw-cache-date"),p=h.headers.get("sw-cache-created-at")||f,g=h.headers.get("sw-image-size")||h.headers.get("content-length");c.push({url:u.url,cacheDate:f?parseInt(f):void 0,cacheCreatedAt:p?parseInt(p):void 0,size:g?parseInt(g):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(()=>R),{getAllLogs:o}=await Promise.resolve().then(()=>_t),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(()=>R);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>R);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>R),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>R);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>R);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>R);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(G.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheDeleted(e){this.broadcastToAll(G.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(G.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(G.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(G.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(G.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(G.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(G.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(G.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(G.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(G.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(G.DEBUG_NEW_CRASH_SNAPSHOT,{snapshot:e})}async requestVideoThumbnail(e,t=3e4,s){const r=Array.from(this.channels.values()).sort((o,a)=>o.isDebugClient===a.isDebugClient?a.createdAt-o.createdAt:o.isDebugClient?1:-1);if(r.length===0)return null;for(const o of r)try{const a=await ar(o.channel.call("thumbnail:generate",{url:e,maxSize:s}),t,"Video thumbnail generation timeout");if(!a||a.ret!==0)continue;const i=a.data;if(i!=null&&i.error||!(i!=null&&i.thumbnailUrl))continue;return i.thumbnailUrl}catch{continue}return 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 Qe=De,Je=null;function Tn(n){return Je||(Je=Qe.getInstance(n)),Je}function O(){return Je}const ir=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:T,SWChannelManager:Qe,SW_EVENTS:G,getChannelManager:O,initChannelManager:Tn},Symbol.toStringTag,{value:"Module"}));function Ze(n){bn(n)}const cr=[];let Dn=!1;function Oe(n){Dn=n}function At(){return Dn}function Lt(){return[...cr]}const lr=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Lt,isDebugFetchEnabled:At,setDebugFetchEnabled:Oe},Symbol.toStringTag,{value:"Module"})),ur=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),W={packageName:"aitu-app",healthCheckInterval:300*1e3,degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500,backgroundFetchTimeout:8e3,localFetchTimeout:5e3,preferenceCacheExpiry:3600*1e3,preferenceCacheName:"drawnix-cdn-v1",preferenceCacheKey:typeof location<"u"?new URL("/__sw__/cdn-preference",location.origin).href:"https://opentu.local/__sw__/cdn-preference"},dr={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3},unpkg:{baseTimeout:600*1e3,maxTimeout:3600*1e3}},et=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1}],me=new Map;let ee=null,vt=!1,tt=null;function _n(n=!1){n&&me.clear(),et.forEach(e=>{me.has(e.name)||me.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}_n();function hr(n){return n==="jsdelivr"||n==="unpkg"||n==="local"}function Rn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!hr(t)||typeof s!="string"||s.trim()==="")return null;const r=Number(e.latency),o=Number(e.timestamp);return{cdn:t,version:s.trim(),latency:Number.isFinite(r)&&r>=0?r:0,timestamp:Number.isFinite(o)&&o>0?o:Date.now()}}function An(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=W.preferenceCacheExpiry}async function gr(){if(typeof caches>"u")return null;try{const e=await(await caches.open(W.preferenceCacheName)).match(W.preferenceCacheKey);return e!=null&&e.ok?Rn(await e.json()):null}catch(n){return console.warn("[CDN Fallback] Failed to read persisted CDN preference:",n),null}}async function Mt(){vt||(tt||(tt=(async()=>{ee=await gr(),vt=!0,tt=null})()),await tt)}async function Ln(n){if(ee=Rn(n),vt=!0,!(typeof caches>"u"))try{const e=await caches.open(W.preferenceCacheName);if(!ee){await e.delete(W.preferenceCacheKey);return}await e.put(W.preferenceCacheKey,new Response(JSON.stringify(ee),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}}))}catch(e){console.warn("[CDN Fallback] Failed to persist CDN preference:",e)}}function Pt(n){const e=me.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now(),e.lastFailureReason=void 0)}function le(n,e){const t=me.get(n);if(t)if(t.failCount++,t.lastCheckTime=Date.now(),t.lastFailureReason=e,t.failCount>=W.failThreshold){t.isHealthy=!1;const s=Mn(t);console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${t.failCount} failures, cooldown=${s.cooldownMs}ms, reason=${e??"unknown"}`)}else console.warn(`[CDN Fallback] ${n} failure count=${t.failCount}, reason=${e??"unknown"}`)}function vn(n,e){const t=dr[n]??{baseTimeout:W.degradeTimeout,maxTimeout:W.degradeTimeout},r=2**Math.max(0,e-W.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function Mn(n){const e=vn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function It(n,e={}){const t=me.get(n);if(!t)return!1;if(t.isHealthy)return!0;if(e.ignoreCooldown)return console.log(`[CDN Fallback] Ignoring cooldown for ${n}, probing CDN directly`),!0;const s=Date.now(),r=vn(n,t.failCount);return s-t.lastCheckTime>r?(console.log(`[CDN Fallback] Trying to recover ${n} after ${r}ms cooldown...`),!0):!1}function fr(n,e={}){const t=ee;return!t||!An(t,n)||t.cdn==="local"?null:It(t.cdn,e)?t.cdn:null}function Pn(n,e={}){const t=n?fr(n,e):null;return et.filter(s=>s.enabled&&It(s.name,e)).sort((s,r)=>t&&s.name===t&&r.name!==t?-1:t&&r.name===t&&s.name!==t?1:s.priority-r.priority)}function In(n){const e=String(n||"").trim();if(!e)return e;let t=e;try{if(/^https?:\/\//i.test(t)){const s=new URL(t);t=`${s.pathname}${s.search}`}}catch{}return t=t.replace(/^\/?npm\/aitu-app@[^/]+\//,"/").replace(/^\/?aitu-app@[^/]+\//,"/"),t}function kn(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function pr(n,e){const t=String(e||"").trim();if(!t)return null;let s=t;try{if(/^https?:\/\//i.test(s)){const o=new URL(s);s=`${o.pathname}${o.search}`}}catch{}const r=s.startsWith("/")?s:`/${s}`;return/^\/npm\/(?!aitu-app@)[^/]+@[^/]+\//.test(r)?n.name==="jsdelivr"?`https://cdn.jsdelivr.net${r}`:n.name==="unpkg"?`https://unpkg.com/${r.replace(/^\/npm\//,"")}`:null:null}function kt(n,e,t){const s=pr(n,t);if(s)return s;const r=In(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function Ot(n,e=W.fetchTimeout){const t=new AbortController,s=setTimeout(()=>t.abort(),e);try{return await fetch(n,{signal:t.signal,cache:"no-store"})}finally{clearTimeout(s)}}function Wt(n,e){const t=In(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function On(n,e,t){try{const s=Wt(e,n);console.log(`[CDN Fallback] Trying local server: ${s}`);const r=await Ot(s,t);return r.ok?(console.log("[CDN Fallback] Success from local server"),{response:r,source:"local"}):(console.warn(`[CDN Fallback] Local server returned ${r.status}`),null)}catch(s){return console.warn("[CDN Fallback] Local server failed:",s),null}}async function Wn(n,e,t,s){for(const r of n){const o=kt(r,e,t);try{console.log(`[CDN Fallback] Trying ${r.name}: ${o}`);const a=await Ot(o,s);if(!a.ok){le(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await mr(a,r.name))continue;return Pt(r.name),console.log(`[CDN Fallback] Success from ${r.name}`),{response:a,source:r.name,targetUrl:o}}catch(a){const i=a instanceof Error&&a.name==="AbortError"?"timeout":"network-error";le(r.name,i),console.warn(`[CDN Fallback] ${r.name} failed:`,a)}}return null}async function mr(n,e){var i;const t=n.headers.get("Content-Type")||"";if(!(t.includes("javascript")||t.includes("css")||t.includes("json")||t.includes("font")||t.includes("image")||t.includes("woff")||t.includes("application/octet-stream")))return le(e,`invalid-content-type:${t}`),console.warn(`[CDN Fallback] ${e} invalid Content-Type: ${t}`),!1;const r=parseInt(n.headers.get("Content-Length")||"0",10),o=t.includes("javascript")||t.includes("css")||t.includes("json");if(o&&r>0&&r<50)return le(e,`response-too-small:${r}`),console.warn(`[CDN Fallback] ${e} response too small: ${r} bytes`),!1;const a=n.clone();try{const c=(i=a.body)==null?void 0:i.getReader();if(c){const{value:l}=await c.read();if(c.cancel(),l){const u=new TextDecoder().decode(l.slice(0,200)),h=u.includes("<!DOCTYPE")||u.includes("<html")||u.includes("<HTML")||u.includes("Not Found")||u.includes("404");if(o&&h)return le(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function Bt(n,e,t,s={}){if(ur)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;await Mt();const{preferLocal:r=!1,localTimeout:o=W.localFetchTimeout,requestKind:a="interactive-runtime"}=s,i=a==="background-prefetch",c=s.cdnTimeout??(a==="background-prefetch"?W.backgroundFetchTimeout:W.fetchTimeout);if(r){const f=await On(n,t,o);if(f)return{...f,targetUrl:Wt(t,n)}}const l=Pn(e,{ignoreCooldown:i}),u=await Wn(l,e,n,c);if(u)return u;if(!r){const f=await On(n,t,o);if(f)return{...f,targetUrl:Wt(t,n)}}const h=et.filter(f=>f.enabled&&!l.some(p=>p.name===f.name));if(h.length>0){console.warn(`[CDN Fallback] Local origin failed, forcing CDN recovery probe for: ${n}`);const f=await Wn(h,e,n,c);if(f)return f}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function xt(n){await Mt();const e=new Map;for(const t of et){if(!t.enabled)continue;const s=kt(t,n,t.healthCheckPath);try{const r=await Ot(s,5e3),o=r.ok;e.set(t.name,o),o?Pt(t.name):le(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),le(t.name,"health-check-failed")}}return e}function nt(){const n=An(ee)?ee==null?void 0:ee.cdn:null;return Array.from(me.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...Mn(t)}))}function Nt(){_n(!0),console.log("[CDN Fallback] All CDN status reset")}const br=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:kt,ensureCDNPreferenceLoaded:Mt,extractVersionFromCDNPath:kn,fetchFromCDNWithFallback:Bt,getAvailableCDNs:Pn,getCDNStatusReport:nt,isCDNAvailable:It,markCDNFailure:le,markCDNSuccess:Pt,performHealthCheck:xt,resetCDNStatus:Nt,setCDNPreference:Ln},Symbol.toStringTag,{value:"Module"}));function Gt(n){return n==="/"||n==="/index.html"}const wr=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"];function yr(n,e){return Gt(e)?!0:n==="navigate"&&!e.endsWith(".html")}function Sr(n){return Gt(n)}function Bn(n){return Gt(n)?!0:wr.some(e=>n.endsWith(e))}function Cr(n){return!Bn(n)}const F=self;Tn(F).setDebugClientCountChangedCallback(Nr);const te={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function st(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 Er(){console.log=(...n)=>{te.log(...n),At()&&!st(n)&&rt("log",n)},console.info=(...n)=>{te.info(...n),At()&&!st(n)&&rt("info",n)},console.warn=(...n)=>{te.warn(...n),st(n)||rt("warn",n)},console.error=(...n)=>{te.error(...n),st(n)||rt("error",n)}}function Tr(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 rt(n,e){try{const{message:t,stack:s}=Tr(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Ft=="function"&&Ft({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){te.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Ft=null;Er(),Promise.resolve().then(()=>Te).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=O();t&&t.sendDebugLLMLog(e)})});const C="0.6.76",Ut=`drawnix-v${C}`,L="drawnix-images",_e=`drawnix-static-v${C}`,ot="drawnix-fonts",ne="sw-cache-date",be="sw-cache-created-at",Ht="x-sw-source",qt="x-sw-revision",jt="x-sw-app-version",xn="x-sw-fetch-target",Dr="ServiceWorkerDB",_r=2,Re="failedDomains",Ae="versionState",Nn="app-version-state",Gn="/__aitu_cache__/",Fn="/__aitu_generated__/audio/",Rr="/asset-library/",We=location.hostname==="localhost"||location.hostname==="127.0.0.1",Ar=[{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"}],Lr=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,vr=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,zt=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,Mr=new Set(["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","_poster_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 $t(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)Mr.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const j=new Map,we=new Map,Un=30*1e3,Be=new Map,U=new Map,Pr=300*1e3,Hn=10,Le=new Set,ve=new Set,Ir=3600*1e3,Vt=new Map;function qn(n){ve.add(n),Vt.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function kr(n){if(!ve.has(n))return!1;const e=Vt.get(n);return e&&Date.now()-e>Ir?(ve.delete(n),Vt.delete(n),!1):!0}const Q=[],jn=7,V=[],Or=500;let I=!1;function k(n){if(!I)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return V.unshift(t),V.length>Or&&V.pop(),zn(t),e}function v(n,e){if(!I||!n)return;const t=V.find(s=>s.id===n);t&&(Object.assign(t,e),zn(t))}function zn(n){const e=O();e&&e.sendDebugLog(n)}function at(){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 Wr(n){try{const e=await at(),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 $n(){try{await Vn();const n=await at(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-jn*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 Vn(){try{const n=await at(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-jn*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 Kn(){try{const n=await at(),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 Xn=500;function Kt(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(I||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};Wr(r),Q.unshift(r),Q.length>Xn&&(Q.length=Xn),I&&Br(r)}Ft=Kt;function Br(n){const e=O();e&&e.sendConsoleLog(n)}function xr(){let n=0;return U.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function Yn(){return{version:C,cacheNames:[Ut,L,_e,ot],pendingImageRequests:j.size,pendingVideoRequests:Be.size,videoBlobCacheSize:U.size,videoBlobCacheTotalBytes:xr(),completedImageRequestsSize:we.size,failedDomainsCount:Le.size,failedDomains:Array.from(Le),corsFailedDomainsCount:ve.size,corsFailedDomains:Array.from(ve),debugLogsCount:V.length,consoleLogsCount:Q.length,debugModeEnabled:I,memoryStats:{pendingRequestsMapSize:j.size,completedRequestsMapSize:we.size,videoBlobCacheMapSize:U.size,failedDomainsSetSize:Le.size,corsFailedDomainsSetSize:ve.size,debugLogsArraySize:V.length,consoleLogsArraySize:Q.length}}}function Xt(){return V}function Qn(){V.length=0}function Jn(){Q.length=0}function Yt(){I||(I=!0,Oe(!0),Ze(!0),te.log("Service Worker: Debug mode enabled (debug page connected)"))}function Qt(){I&&(I=!1,Oe(!1),Ze(!1),Q.length=0,V.length=0,te.log("Service Worker: Debug mode disabled (no debug pages)"))}function Nr(n){n>0?Yt():Qt()}function Zn(n){for(const e of Ar)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function Gr(n,e){return Lr.test(n.pathname)||e.destination==="image"||Zn(n)!==null}function Fr(n,e){return vr.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function Ur(n,e){return zt.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function Hr(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 qr(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function es(n){return`drawnix-static-v${n}`}function ts(){return{committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function ns(n){const e=n||{},t=typeof e.committedVersion=="string"&&e.committedVersion?e.committedVersion:C,s=typeof e.pendingVersion=="string"&&e.pendingVersion?e.pendingVersion:null,r=typeof e.pendingReadyAt=="number"&&Number.isFinite(e.pendingReadyAt)?e.pendingReadyAt:null,o=e.upgradeState==="prewarming"||e.upgradeState==="ready"||e.upgradeState==="committing"?e.upgradeState:"idle";return{committedVersion:t,pendingVersion:s,pendingReadyAt:r,upgradeState:o,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:Date.now()}}function it(){return new Promise((n,e)=>{const t=indexedDB.open(Dr,_r);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains(Re)||r.createObjectStore(Re,{keyPath:"domain"}),r.objectStoreNames.contains(Ae)||r.createObjectStore(Ae,{keyPath:"key"})}})}async function xe(){try{const n=await it();return await new Promise((e,t)=>{const o=n.transaction([Ae],"readonly").objectStore(Ae).get(Nn);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(ns((a==null?void 0:a.state)||ts()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),ts()}}async function jr(n){const e=ns(n);try{const t=await it();await new Promise((s,r)=>{const o=t.transaction([Ae],"readwrite");o.objectStore(Ae).put({key:Nn,state:e}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.warn("Service Worker: 无法写入版本状态:",t)}return e}async function ye(n){const e=await xe(),t=typeof n=="function"?n(e):n;return jr({...e,...t,updatedAt:Date.now()})}async function ue(n){const e=await xe(),t={type:"SW_VERSION_STATE",...e,swVersion:C};if(n)return n.postMessage(t),e;const s=await F.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of s)r.postMessage(t);return e}async function zr(){try{const n=await it();return await new Promise((e,t)=>{const o=n.transaction([Re],"readonly").objectStore(Re).getAll();o.onsuccess=()=>{o.result.forEach(i=>Le.add(i.domain)),e()},o.onerror=()=>t(o.error)})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function $r(n){try{const e=await it();return await new Promise((t,s)=>{const r=e.transaction([Re],"readwrite");r.objectStore(Re).put({domain:n,timestamp:Date.now()}),r.oncomplete=()=>t(),r.onerror=()=>s(r.error)})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function Vr(n){if(!n){await ye({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await ue();return}await ye(t=>({committedVersion:t.committedVersion||C,pendingVersion:C,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=O();e&&e.sendSWNewVersionReady(C),await ue()}async function Kr(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(ne),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)}}const ss=2,Jt=1500,Zt=2500,Xr=8e3,Yr=5e3,Qr=6e4,Se=5e3,Jr=600*1e3,Zr=["offline-static-assets"],eo="disabled-in-development";let Ne=0,rs=0;const Ge=new Set,Fe=new Set,Ue=new Set,ct=new Map;let os=Promise.resolve(),He=null,qe=0,de=!1,lt=!1;function y(n,e){if(e===void 0){console.info(`[SWDebug] ${n}`);return}console.info(`[SWDebug] ${n}`,e)}function as(){return nt().filter(n=>n.remainingCooldownMs>0&&!n.status.isHealthy).map(n=>({name:n.name,failCount:n.status.failCount,remainingCooldownMs:n.remainingCooldownMs,lastFailureReason:n.status.lastFailureReason}))}function is(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:as(),...t})}let en={phase:"idle",percent:0,completed:0,total:0,failed:0,version:C,updatedAt:Date.now()};async function cs(n){const e={type:"SW_BOOT_PROGRESS",...en};if(n){n.postMessage(e);return}const t=await F.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e)}function Ce(n,e){en={...en,...n,version:C,updatedAt:Date.now()},cs(e)}async function to(){try{const n=await fetch("./precache-manifest.json",{cache:"reload"});if(!n.ok)return y("loadPrecacheManifest: response not ok",{status:n.status,statusText:n.statusText}),null;const e=await n.json();return y("loadPrecacheManifest: loaded",{version:e.version,fileCount:e.files.length}),e.files}catch(n){return y("loadPrecacheManifest: failed",{error:oe(n)}),null}}let Me=null,Ee=0,he=null;function je(){return We}async function no(n,e=200){try{const t=(await n.text()).replace(/\s+/g," ").trim();return t?t.slice(0,e):void 0}catch{return}}async function so(){if(je())return y("loadIdlePrefetchManifest: skipped in development mode"),null;const n=new URL("/idle-prefetch-manifest.json",self.location.origin).href;try{const e=await fetch(n,{cache:"reload"}),t=e.headers.get("content-type")||"";if(!e.ok){const a=await no(e.clone());return y("loadIdlePrefetchManifest: response not ok",{manifestUrl:n,status:e.status,statusText:e.statusText,contentType:t,preview:a}),null}const s=await e.text(),r=s.replace(/\s+/g," ").trim().slice(0,200);if(t.includes("text/html")||/<!DOCTYPE|<html|<HTML/i.test(r))return y("loadIdlePrefetchManifest: html fallback detected",{manifestUrl:n,status:e.status,contentType:t,preview:r}),null;let o;try{o=JSON.parse(s)}catch(a){return y("loadIdlePrefetchManifest: invalid json",{manifestUrl:n,contentType:t,error:oe(a),preview:r}),null}return!o||typeof o!="object"||!o.groups?(y("loadIdlePrefetchManifest: invalid manifest shape",{manifestUrl:n,contentType:t,preview:r}),null):(y("loadIdlePrefetchManifest: loaded",{manifestUrl:n,version:o.version,defaults:o.defaults||[],groupEntryCounts:Object.fromEntries(Object.entries(o.groups).map(([a,i])=>[a,i.length]))}),o)}catch(e){return y("loadIdlePrefetchManifest: failed",{manifestUrl:n,error:oe(e)}),null}}async function ut(){if(je())return Ee=0,he=eo,Me=null,null;const n=Date.now();if(!Me){if(Ee>0&&n-Ee<Se){const e=Se-(n-Ee);return y("getIdlePrefetchManifest: retry cooldown active",{retryAfterMs:e,lastFailureReason:he}),null}Me=so().then(e=>e?(Ee=0,he=null,e):(Ee=Date.now(),he="manifest-missing-or-invalid",Me=null,null)).catch(e=>{throw Ee=Date.now(),he=oe(e),Me=null,e})}return Me}async function tn(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(Ue),version:C,updatedAt:Date.now()};if(n){y("broadcast idle prefetch status to target client",{clientId:n.id,completedGroups:e.completedGroups}),n.postMessage(e);return}const t=await F.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e);y("broadcast idle prefetch status to all clients",{clientCount:t.length,completedGroups:e.completedGroups})}function ro(n,e){return`${n}@${e}`}async function dt(n){try{return(await n.keys()).length}catch{return-1}}function ht(n,e){const t=os.catch(()=>{}).then(async()=>{y("idle prefetch task start",{label:n});try{await e()}finally{y("idle prefetch task done",{label:n})}});return os=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:oe(s)})}),t}function oo(n){return Math.min(Qr,Yr*2**Math.max(0,n-1))}function ls(n,e=[]){const t=[],s=new Set,r=o=>{!o||s.has(o)||(n.groups[o]||[]).length===0||(s.add(o),t.push(o))};return e.forEach(r),(n.defaults||[]).forEach(r),Zr.forEach(r),Object.keys(n.groups).forEach(r),t}function us(n,e){const t=Date.now(),s=new Map,r=[],o=[];let a=0,i=null;for(const c of e){const l=n.groups[c]||[];if(l.length===0)continue;let u=!1;for(const h of l){const f=ro(h.url,h.revision);if(Ge.has(f)||(u=!0,Fe.has(f)))continue;const p=ct.get(f);if(p&&p.nextRetryAt>t){a+=1;const g=Math.max(0,p.nextRetryAt-t);i=i===null?g:Math.min(i,g);continue}s.set(f,h)}u?o.push(c):r.push(c)}return{completedGroups:r,pendingGroups:o,queue:Array.from(s.entries()),coolingEntries:a,nextRetryDelayMs:i}}function nn(n,e=Zt){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(He!==null){if(qe<=s){y("scheduleIdlePrefetchSweep skipped: earlier timer already exists",{reason:n,scheduledInMs:Math.max(0,qe-Date.now()),requestedDelayMs:t});return}clearTimeout(He),He=null,qe=0}qe=s,He=self.setTimeout(()=>{He=null,qe=0,ht(`idle-sweep:${n}`,async()=>{await pt(`scheduled:${n}`)})},t),y("scheduleIdlePrefetchSweep queued",{reason:n,delayMs:t})}function ao(){return Ne===0?!1:Date.now()-Ne<Jt}function io(){if(Ne===0)return Promise.resolve();const n=Date.now()-Ne,e=Math.max(0,Jt-n)+100;return y("waitForIdlePrefetchWindow: delaying idle prefetch",{elapsedMs:n,waitMs:e,recentFetchWindowMs:Jt}),new Promise(t=>{setTimeout(t,e)})}function co(n,e){if(n.request.method!=="GET"||!n.clientId||e.origin!==self.location.origin||e.pathname.startsWith(Gn)||e.pathname.startsWith(Fn)||e.pathname==="/sw.js"||e.pathname==="/precache-manifest.json"||e.pathname==="/idle-prefetch-manifest.json")return!1;const t=Date.now();return t-rs<Xr?!1:(rs=t,!0)}function lo(n){return Bn(n)}function ds(n,e){return We||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||lo(e.pathname)?!1:!!(e.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|woff|woff2|ttf|eot|json|ico)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font")}function uo(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${e.replace(/^\/npm\/aitu-app@[^/]+\//,"/").replace(/^\/aitu-app@[^/]+\//,"/")}${t}`}function gt(n){const e=new URL(n,self.location.origin),t=uo(`${e.pathname}${e.search}`),s=new URL(t,self.location.origin);return{requestUrl:e,resourcePath:t,cacheKey:s.href,originFetchUrl:s.href}}function ze(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&ds(n,e)}function ho(n,e){const t=new Headers(n.headers);return t.set(Ht,e.source),t.set(qt,e.revision),t.set(jt,e.appVersion||C),e.fetchTarget&&t.set(xn,e.fetchTarget),t.set("x-sw-cached-at",new Date().toISOString()),new Response(n.body,{status:n.status,statusText:n.statusText,headers:t})}async function sn(n,e,t,s){const r=ho(t,s);return await n.put(e,r.clone()),r}async function ft(n,e=[]){const t=e.filter(r=>!!r&&r!==n.url),s=await caches.keys();for(const r of s)if(r.startsWith("drawnix-static-v"))try{const o=await caches.open(r),a=await o.match(n);if(a)return a;for(const i of t){const c=await o.match(i);if(c)return y("findStaticResponseInOldCaches: normalized key hit",{cacheName:r,requestUrl:n.url,normalizedCacheKey:i}),c}}catch{}return null}async function go(n,e=[]){const t=[n.url,...e].filter(Boolean);for(const s of t)try{const r=await fetch(s,{cache:"only-if-cached",mode:"same-origin"});if(r.ok)return r}catch{}return null}async function fo(n,e){const t=gt(e.url).cacheKey,s=await n.match(e);if(s)return{response:s,normalizedCacheKey:t,matchedBy:"request"};if(t!==e.url){const r=await n.match(t);if(r)return{response:r,normalizedCacheKey:t,matchedBy:"normalized"}}return{response:null,normalizedCacheKey:t,matchedBy:null}}async function po(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function hs(n,e,t){try{const s=gt(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(qt),l=r.headers.get(jt);if(c===t&&l===C)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(Cr(s.requestUrl.pathname)){const c=await Bt(s.resourcePath,C,location.origin,{preferLocal:!1,requestKind:"background-prefetch"});c!=null&&c.response.ok&&(o=c.response,a=c.source,i=c.targetUrl)}if(o||(o=await fetch(s.originFetchUrl,{cache:"reload"}),a="server",i=s.originFetchUrl),o.ok&&ze(new Request(s.cacheKey,{method:"GET"}),s.requestUrl,o))return{url:e,success:!1,status:404,error:"html-fallback-for-static-resource"};if(o.ok){if(await sn(n,s.cacheKey,o,{source:a,revision:t,fetchTarget:i,appVersion:C}),s.resourcePath==="/index.html"){const c=new URL("/",self.location.origin).href,l=await n.match(s.cacheKey);l&&await n.put(c,l.clone())}return{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 mo(n,e){const s=[],r=e.length;let o=0,a=0;const i=await dt(n);y("precacheStaticFiles start",{total:r,concurrency:6,cacheEntriesBefore:i,sampleUrls:e.slice(0,8).map(p=>p.url)}),Ce({phase:"precache",total:r,completed:0,failed:0,percent:r>0?0:100,message:r>0?`正在预热启动资源(0/${r})...`:"没有需要预热的启动资源"});for(let p=0;p<e.length;p+=6){const g=e.slice(p,p+6),m=await Promise.allSettled(g.map(({url:b,revision:S})=>hs(n,b,S))),d=[];for(const b of m)if(b.status==="fulfilled"){const S={url:b.value.url,success:b.value.success,skipped:b.value.skipped,source:b.value.source,status:b.value.status,error:b.value.error};s.push(S),d.push(S),o+=1,b.value.success||(a+=1)}else{const S={success:!1,error:String(b.reason)};s.push(S),d.push(S),o+=1,a+=1}y("precacheStaticFiles batch done",{completed:o,total:r,batchSize:g.length,batchSuccess:d.filter(b=>b.success).length,batchSkipped:d.filter(b=>b.skipped).length,batchFailed:d.filter(b=>!b.success).length,batchSources:Object.fromEntries(Array.from(d.reduce((b,S)=>{const E=S.source||"unknown";return b.set(E,(b.get(E)||0)+1),b},new Map))),batchErrors:d.filter(b=>!b.success).slice(0,5).map(b=>({url:b.url,status:b.status,error:b.error}))}),Ce({phase:"precache",total:r,completed:o,failed:a,percent:r>0?Math.round(o/r*100):100,message:r>0?`正在预热启动资源(${o}/${r}${a>0?`,${a} 项回退`:""})...`:"没有需要预热的启动资源"})}const c=s.filter(p=>p.success).length,l=s.length-c,u=s.filter(p=>p.success&&p.source&&p.source!=="server").length,h=s.filter(p=>p.success&&p.source==="server").length,f=await dt(n);return y("precacheStaticFiles finished",{total:r,successCount:c,failCount:l,cdnCount:u,serverCount:h,cacheEntriesBefore:i,cacheEntriesAfter:f}),{total:r,successCount:c,failCount:l,cdnCount:u,serverCount:h}}async function gs(n){if(y("prefetchIdleGroups start",{groupNames:n}),n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await ut();if(!e)return y("prefetchIdleGroups aborted: manifest missing"),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};y("prefetchIdleGroups manifest summary",{requestedGroups:n,groupEntryCounts:Object.fromEntries(n.map(u=>{var h;return[u,((h=e.groups[u])==null?void 0:h.length)||0]})),defaults:e.defaults||[]});const t=new Set(Ue),s=us(e,n);if(s.completedGroups.forEach(u=>Ue.add(u)),s.queue.length===0)return y("prefetchIdleGroups no ready files",{groupNames:n,completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs,completedEntries:Ge.size,activeEntries:Fe.size}),{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(_e),o=await dt(r),a=s.queue;y("prefetchIdleGroups queue prepared",{groupNames:n,totalCandidates:s.queue.length,queuedEntries:a.length,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,cacheEntriesBefore:o,sampleUrls:a.slice(0,8).map(([,u])=>u.url)});for(let u=0;u<a.length;u+=ss){for(;ao();)await io();const h=a.slice(u,u+ss);h.forEach(([g])=>Fe.add(g));const f=await Promise.allSettled(h.map(([,{url:g,revision:m}])=>hs(r,g,m))),p=[];f.forEach((g,m)=>{const[d]=h[m];if(Fe.delete(d),g.status==="fulfilled"&&g.value.success)ct.delete(d),Ge.add(d);else{const b=ct.get(d),S=((b==null?void 0:b.count)||0)+1,E=oo(S);ct.set(d,{count:S,nextRetryAt:Date.now()+E,lastError:g.status==="fulfilled"?g.value.error:String(g.reason),lastStatus:g.status==="fulfilled"?g.value.status:void 0})}g.status==="fulfilled"?p.push({url:g.value.url,success:g.value.success,skipped:g.value.skipped,source:g.value.source,status:g.value.status,error:g.value.error}):p.push({success:!1,error:String(g.reason)})}),y("prefetchIdleGroups batch done",{groupNames:n,batchStart:u,batchSize:h.length,batchSuccess:p.filter(g=>g.success).length,batchSkipped:p.filter(g=>g.skipped).length,batchFailed:p.filter(g=>!g.success).length,batchSources:Object.fromEntries(Array.from(p.reduce((g,m)=>{const d=m.source||"unknown";return g.set(d,(g.get(d)||0)+1),g},new Map))),batchErrors:p.filter(g=>!g.success).slice(0,5).map(g=>({url:g.url,status:g.status,error:g.error})),completedEntries:Ge.size,activeEntries:Fe.size})}const i=us(e,n),c=i.completedGroups.filter(u=>!t.has(u));c.forEach(u=>Ue.add(u));const l=await dt(r);return y("prefetchIdleGroups finished",{groupNames:n,newlyCompletedGroups:c,pendingGroups:i.pendingGroups,completedEntries:Ge.size,cacheEntriesBefore:o,cacheEntriesAfter:l,completedGroups:Array.from(Ue),coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}),{completedGroups:c,pendingGroups:i.pendingGroups,queuedEntries:a.length,coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}}async function pt(n,e=[]){if(je())return y("prefetchPendingIdleGroups skipped: disabled in development",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const t=await ut();if(!t)return nn(`${n}:manifest-missing`,Se),y("prefetchPendingIdleGroups skipped: manifest missing",{reason:n,preferredGroups:e,retryDelayMs:Se,lastFailureReason:he}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:Se};const s=ls(t,e);if(s.length===0)return y("prefetchPendingIdleGroups skipped: no groups",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};y("prefetchPendingIdleGroups start",{reason:n,preferredGroups:e,orderedGroups:s,groupEntryCounts:Object.fromEntries(s.map(o=>{var a;return[o,((a=t.groups[o])==null?void 0:a.length)||0]}))});const r=await gs(s);return r.completedGroups.length>0&&await tn(),r.pendingGroups.length>0&&nn(`${n}:pending`,r.nextRetryDelayMs??Zt),y("prefetchPendingIdleGroups done",{reason:n,preferredGroups:e,orderedGroups:s,summary:r}),r}async function bo(){var t;if(je()){y("prefetchDefaultIdleGroups skipped: disabled in development");return}const n=await ut();if(!n){nn("default-groups:manifest-missing",Se),y("prefetchDefaultIdleGroups skipped: manifest missing",{retryDelayMs:Se,lastFailureReason:he});return}const e=(t=n==null?void 0:n.defaults)==null?void 0:t.filter(s=>typeof s=="string"&&s.length>0);if(!e||e.length===0){y("prefetchDefaultIdleGroups skipped: no default groups");return}await pt("default-groups",e)}async function wo(){if(je()){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: disabled in development");return}const n=Date.now();let e=0,t=null;for(;;){if(!t){const a=await ut();if(!a){const i=Date.now()-n;y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: manifest unavailable",{elapsedMs:i,lastFailureReason:he});return}if(t=ls(a),t.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: no groups");return}}e+=1;const s=await gs(t);if(s.completedGroups.length>0&&await tn(),s.pendingGroups.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady complete",{orderedGroups:t,iteration:e,elapsedMs:Date.now()-n});return}const r=Date.now()-n;if(r>=Jr)throw new Error(`idle-prefetch incomplete after ${r}ms: pending groups ${s.pendingGroups.join(", ")}`);const o=Math.max(250,s.nextRetryDelayMs??(s.queuedEntries>0?Zt:1e3));y("prewarmAllIdlePrefetchGroupsForUpdateReady waiting next round",{orderedGroups:t,iteration:e,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,queuedEntries:s.queuedEntries,waitMs:o,elapsedMs:r}),await new Promise(a=>{setTimeout(a,o)})}}F.addEventListener("install",n=>{y("install event received",{version:C}),de=!!F.registration.active,lt=!de,de||F.skipWaiting(),Ce({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await zr(),await ye(e=>({committedVersion:e.committedVersion||C,pendingVersion:de?C:null,pendingReadyAt:null,upgradeState:de?"prewarming":"idle"})),await ue();try{const e=await to();if(e&&e.length>0){const t=await caches.open(_e),s=await mo(t,e);if(de&&s.failCount>0)throw new Error(`precache incomplete: ${s.failCount}/${s.total} files failed`)}else We&&Ce({phase:"development",percent:100,completed:0,total:0,failed:0,message:"开发模式下跳过静态预缓存"});de&&await wo(),await Vr(de)}catch(e){await ye(t=>({committedVersion:t.committedVersion||C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await ue(),Ce({phase:"error",message:`启动资源预热失败:${oe(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),F.addEventListener("activate",n=>{y("activate event received",{version:C}),Ce({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await xe(),await ye({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await ue();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>br);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}lt?(y("activate: before clients.claim"),await F.clients.claim(),y("activate: after clients.claim")):y("activate: skip clients.claim for staged update"),setTimeout(()=>{y("activate: scheduling default idle prefetch"),ht("default-groups",async()=>bo())},800);const e=O();e&&(e.sendSWActivated(C),y("activate: sent sw:activated broadcast")),Ce({phase:"activated",percent:100,message:"启动缓存服务已就绪"})})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(i=>i.startsWith("drawnix-images-v")&&i!==L);if(t.length>0){const i=await caches.open(L);for(const c of t)try{const l=await caches.open(c),u=await l.keys();for(const h of u){const f=await l.match(h);f&&await i.put(h,f)}await caches.delete(c)}catch(l){console.warn(`Failed to migrate cache ${c}:`,l)}}const s=await xe(),r=es(s.committedVersion||C),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==_e&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==Ut&&i!==L&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(_e);await Eo(i)}catch(i){console.warn("Failed to purge suspicious static cache entries:",i)}(o.length>0||a.length>0)&&setTimeout(async()=>{for(const i of[...o,...a])try{await caches.delete(i)}catch(c){console.warn("Failed to delete old cache:",i,c)}},3e4),Vn().catch(i=>{console.warn("Failed to cleanup expired console logs:",i)}),fn.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function yo(n){if(I){const e=O();e&&e.sendPostMessageLog(n)}}async function So(n,e,t,s){if(We)return null;try{const r=gt(e.url),o=await Bt(t,s,location.origin,{preferLocal:!1,requestKind:"interactive-runtime"});if(!(o!=null&&o.response.ok))return console.warn("[SW CDN] Static resource unavailable from all fallback sources",{requestUrl:e.url,resourcePath:t,appVersion:s,unavailableCDNs:as()}),null;const a=new URL(e.url);if(ze(e,a,o.response))return null;const i=await sn(n,r.cacheKey,o.response,{source:o.source,revision:"runtime",fetchTarget:o.targetUrl,appVersion:s});return r.cacheKey!==e.url&&y("tryFetchStaticResourceFromCDN: cached under normalized key",{requestUrl:e.url,normalizedCacheKey:r.cacheKey,resourcePath:t,source:o.source,fetchTarget:o.targetUrl}),i}catch(r){return console.warn("[SW CDN] CDN fallback failed:",r),null}}function Co(n){const e=n.headers.get(Ht)||void 0,t=n.headers.get(xn)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function fs(n,e,t=C){const s=e.headers.get(Ht),r=e.headers.get(qt),o=e.headers.get(jt);if(!s||!r||!o){const i=new URL(n.url);return!(e.ok&&!ze(n,i,e))}if(o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr"&&s!=="unpkg")return!0;const a=new URL(n.url);return ze(n,a,e)}async function Eo(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&fs(t,s)&&await n.delete(t)}catch(s){console.warn("Service Worker: Failed to inspect static cache entry:",s)}}F.addEventListener("message",n=>{var a,i,c,l,u,h,f,p,g,m;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=((f=n.data)==null?void 0:f.cmdname)||((p=n.data)==null?void 0:p.requestId)&&((g=n.data)==null?void 0:g.ret)!==void 0;let o="";if(Et()&&!r&&(o=Tt(e,n.data,t,s,(m=n.data)==null?void 0:m.__internal__),o&&I)){const b=Ke().find(S=>S.id===o);b&&yo(b)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:d,mediaType:b,blob:S,mimeType:E}=n.data;if(d&&b&&S){const A=new Blob([S],{type:E||(b==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:q}=await Promise.resolve().then(()=>H);q(A,d,b)})()}return}if(n.data&&n.data.type==="SW_CDN_SET_PREFERENCE"){n.waitUntil(Ln({cdn:n.data.cdn,latency:n.data.latency,timestamp:n.data.timestamp,version:n.data.version}));return}if(n.data&&n.data.type==="SW_BOOT_PROGRESS_GET"){const d=n.source;y("message: SW_BOOT_PROGRESS_GET",{clientId:(d==null?void 0:d.id)??null}),cs(d);return}if(n.data&&n.data.type==="GET_VERSION_STATE"){const d=n.source;y("message: GET_VERSION_STATE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil(ue(d));return}if(n.data&&n.data.type==="SW_IDLE_PREFETCH_STATUS_GET"){const d=n.source;y("message: SW_IDLE_PREFETCH_STATUS_GET",{clientId:(d==null?void 0:d.id)??null}),tn(d);return}if(n.data&&n.data.type==="SW_PREFETCH_GROUPS"){const d=Array.isArray(n.data.groups)?n.data.groups.filter(b=>typeof b=="string"):[];y("message: SW_PREFETCH_GROUPS",{groups:d}),n.waitUntil(ht(`message:${d.join(",")||"empty"}`,async()=>{await pt(`message:${d.join(",")||"empty"}`,d)}));return}if(n.data&&(n.data.type==="COMMIT_UPGRADE"||n.data.type==="SKIP_WAITING")){const d=n.source;y("message: COMMIT_UPGRADE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil((async()=>{lt=!0,await ye({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await ue(d),F.skipWaiting();const b=O();b&&b.sendSWUpdated(C)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{lt=!0,await ye({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await ue(n.source),F.skipWaiting();const d=O();d&&d.sendSWUpdated(C)})());else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:d}=n.data;d&&on(d).then(()=>{const b=O();b&&b.sendCacheDeleted(d)}).catch(b=>{console.error("Service Worker: Failed to delete cache:",b)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:d}=n.data;d&&Array.isArray(d)&&Ao(d).then(()=>{}).catch(b=>{console.error("Service Worker: Failed to batch delete caches:",b)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")Lo().then(()=>{}).catch(d=>{console.error("Service Worker: Failed to clear all cache:",d)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){I=!0,Oe(!0),Ze(!0),te.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const d=O();d&&d.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){I=!1,Oe(!1),Ze(!1),Q.length=0,V.length=0,te.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const d=O();d&&d.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:d}=await Promise.resolve().then(()=>Te),b=await d(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:b})}catch(d){console.error("[SW] Failed to get LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:d}=await Promise.resolve().then(()=>Te);await d();const b=n.source;b&&b.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(d){console.error("[SW] Failed to clear LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const d=n.source;d&&d.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:I,swVersion:C,logs:V.slice(-100),consoleLogs:Q.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:d}=await Promise.resolve().then(()=>lr),b=Xt(),S=d(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...b,...S.map(A=>({...A,type:"fetch"}))]})}catch(d){console.error("[SW] Failed to get fetch logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const d=n.source;d&&d.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:Q})}catch(d){console.error("[SW] Failed to get console logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const d=Ke(),b=n.source;b&&b.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:d})}catch(d){console.error("[SW] Failed to get postmessage logs:",d)}})();return}});const To="MemorySnapshotDB",ge="snapshots",ps=50;async function rn(){return new Promise((n,e)=>{const t=indexedDB.open(To,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(ge)){const o=r.createObjectStore(ge,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function ms(n){try{const e=await rn(),t=e.transaction(ge,"readwrite"),s=t.objectStore(ge);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>ps){const i=s.index("timestamp").openCursor();let c=0;const l=o-ps;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 bs(){try{const n=await rn(),s=n.transaction(ge,"readonly").objectStore(ge).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 ws(){try{const n=await rn(),e=n.transaction(ge,"readwrite");e.objectStore(ge).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 Do=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function _o(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Ro(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 f=u.objectStore(h),p=f.count();p.onsuccess=()=>{const g=p.result;if(o+=g,g>0){const m=f.openCursor();let d=0;m.onsuccess=b=>{const S=b.target.result;if(S&&d<l)a+=_o(S.value),i++,d++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,A=Math.round(E*o);e({count:o,totalSize:A})}},m.onerror=()=>{if(c++,c===r.length){s.close();const b=i>0?a/i:0,S=Math.round(b*o);e({count:o,totalSize:S})}}}else c++,c===r.length&&(s.close(),e({count:o,totalSize:0}))},p.onerror=()=>{if(c++,c===r.length){s.close();const g=i>0?a/i:0,m=Math.round(g*o);e({count:o,totalSize:m})}}}}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 ys(){const n={},e=[Ut,L,_e,ot];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 Do)try{const s=await Ro(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function on(n){try{await(await caches.open(L)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function Ao(n){try{const e=await caches.open(L);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 Lo(){try{const n=await caches.open(L),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 Ss(n,e,t){try{const s=O();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}async function vo(){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=O();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const se=new Map,Cs=300*1e3,Es=500;function Mo(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 Po(n){const e=se.get(n);return e?Date.now()-e>Cs?(se.delete(n),!1):!0:!1}function Ts(n){if(Mo(n)){if(se.size>=Es){const e=Date.now();for(const[t,s]of se)e-s>Cs&&se.delete(t);if(se.size>=Es){const t=Array.from(se.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)se.delete(r)}}se.set(n,Date.now())}}F.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(Ne=t,co(n,e)){const s=`${e.pathname}${e.search}`;y("fetch: enqueue idle prefetch recheck",{clientId:n.clientId,requestUrl:s}),n.waitUntil(ht(`fetch-recheck:${s}`,async()=>{await pt(`fetch:${s}`)}))}if(e.pathname.startsWith(Gn)||e.pathname.startsWith(Fn)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(ko(n.request).then(r=>(v(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw v(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(Rr)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Oo(n.request).then(r=>(v(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw v(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(kr(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&&Ur(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(Wo(n.request).then(a=>(v(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,cached:a.headers.has(ne),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 v(o,{error:String(a),duration:Date.now()-s}),a}));return}if(Fr(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(Bo(n.request).then(a=>(v(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 v(o,{error:String(a),duration:Date.now()-s}),a}));return}if(Hr(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(Io(n.request).then(o=>(v(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 v(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&Gr(e,n.request)){if(Po(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(Fo(n.request).then(o=>(o.status===404&&Ts(n.request.url),v(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 Ts(n.request.url),v(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(xo(n.request).then(i=>{const c=Co(i);return v(a,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-o,resourceSource:c.resourceSource,resourceFetchTarget:c.resourceFetchTarget,details:s?"Navigation request":[`Static resource (${n.request.destination})`,c.resourceSource?`来源: ${c.resourceSource}`:null,c.resourceFetchTarget?`实际拉取: ${c.resourceFetchTarget}`:null].filter(Boolean).join(`
|
|
2
|
-
`)}),i}).catch(i=>{throw v(a,{error:String(i),duration:Date.now()-o}),i}));return}}if(I){if(
|
|
1
|
+
var sw=(function(D){"use strict";var me=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(me||{});me.IMAGE+"",me.VIDEO+"",me.AUDIO+"",me.CHARACTER+"",me.INSPIRATION_BOARD+"",me.CHAT+"";function ae(n){return n instanceof Error?n.name||"Error":"Unknown error"}const Et="sw-task-queue",mn=3,_="tasks",$="config",x="workflows",N="chat-workflows",M="pending-tool-requests",P="pending-dom-operations",G="task-step-mappings",V="pending-canvas-operations",xs=[_,$,x,N,M,P,G,V];function Ns(){return new Promise(n=>{const e=indexedDB.open(Et);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,mn))},e.onerror=()=>{n(mn)}})}function Gs(n){const e=[];for(const t of xs)n.objectStoreNames.contains(t)||e.push(t);return e}function Fs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(Et,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;bn(a)}})}function bn(n){if(!n.objectStoreNames.contains(_)){const e=n.createObjectStore(_,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("type","type",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains($)||n.createObjectStore($,{keyPath:"key"}),!n.objectStoreNames.contains(x)){const e=n.createObjectStore(x,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(!n.objectStoreNames.contains(N)){const e=n.createObjectStore(N,{keyPath:"id"});e.createIndex("status","status",{unique:!1}),e.createIndex("createdAt","createdAt",{unique:!1})}if(n.objectStoreNames.contains(M)||n.createObjectStore(M,{keyPath:"requestId"}).createIndex("workflowId","workflowId",{unique:!1}),!n.objectStoreNames.contains(P)){const e=n.createObjectStore(P,{keyPath:"id"});e.createIndex("workflowId","workflowId",{unique:!1}),e.createIndex("chatId","chatId",{unique:!1})}n.objectStoreNames.contains(G)||n.createObjectStore(G,{keyPath:"taskId"}).createIndex("workflowId","workflowId",{unique:!1}),n.objectStoreNames.contains(V)||n.createObjectStore(V,{keyPath:"id"}).createIndex("workflowId","workflowId",{unique:!1})}async function Us(){const n=await Ns();return new Promise((e,t)=>{const s=indexedDB.open(Et,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=Gs(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),Fs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;bn(o)}})}class Hs{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=Us()),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(_,"readwrite"),i=a.objectStore(_);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(_,"readwrite").objectStore(_).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(_,"readonly").objectStore(_).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(_,"readonly").objectStore(_).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(_,"readonly").objectStore(_).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 f=i.transaction(_,"readonly").objectStore(_).index("createdAt"),b=a==="desc"?"prev":"next",h=f.openCursor(null,b),p=[];let d=0,m=0;h.onerror=()=>l(h.error),h.onsuccess=S=>{const E=S.target.result;if(!E){c({tasks:p,total:m,hasMore:m>t+p.length});return}const A=E.value,j=!r||A.status===r,oe=!o||A.type===o;j&&oe&&(m++,d<t?d++:p.length<s&&p.push(A)),E.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(_,"readwrite").objectStore(_).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($,"readonly").objectStore($).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:",ae(t)),null}}async saveConfig(e,t){try{const s=await this.getDB();return new Promise((r,o)=>{const a=s.transaction($,"readwrite");a.objectStore($).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:",ae(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($,"readwrite");o.objectStore($).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($,"readonly").objectStore($).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(x,"readwrite").objectStore(x).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(x,"readonly").objectStore(x).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(x,"readonly").objectStore(x).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(x,"readonly").objectStore(x).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(x,"readwrite").objectStore(x).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(N,"readwrite").objectStore(N).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(N,"readonly").objectStore(N).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(N,"readonly").objectStore(N).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(N,"readonly").objectStore(N).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(N,"readwrite").objectStore(N).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(M,"readwrite").objectStore(M).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(M,"readonly").objectStore(M).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(M,"readonly").objectStore(M).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(M,"readonly").objectStore(M).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(M,"readwrite").objectStore(M).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(M,"readwrite"),c=a.objectStore(M).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(P,"readwrite").objectStore(P).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(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 pending DOM operations:",e),[]}}async getPendingDomOperationsByWorkflow(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(P,"readonly").objectStore(P).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get pending DOM operations by workflow:",t),[]}}async getPendingDomOperationsByChatId(e){try{const t=await this.getDB();return new Promise((s,r)=>{const c=t.transaction(P,"readonly").objectStore(P).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(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 pending DOM operation:",t),null}}async deletePendingDomOperation(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 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(G,"readwrite").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readonly").objectStore(G).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(G,"readonly").objectStore(G).index("workflowId").getAll(e);c.onerror=()=>r(c.error),c.onsuccess=()=>s(c.result||[])})}catch(t){return console.error("[SWStorage] Failed to get task-step mappings by workflow:",t),[]}}async deleteTaskStepMapping(e){try{const t=await this.getDB();return new Promise((s,r)=>{const i=t.transaction(G,"readwrite").objectStore(G).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(V,"readwrite").objectStore(V).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(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 canvas operations:",e),[]}}async getPendingCanvasOperationsByWorkflow(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 canvas operations by workflow:",t),[]}}async deletePendingCanvasOperation(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 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 f=t.transaction(_,"readonly").objectStore(_).index("createdAt"),b=[],h=f.openCursor(null,"next");h.onsuccess=()=>{const p=h.result;if(!p){c(b);return}const d=p.value;d.archived||b.push(d),p.continue()},h.onerror=()=>l(h.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(_,"readwrite"),g=u.objectStore(_);for(const f of a)f.archived=!0,f.updatedAt=i,g.put(f);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 wn=new Hs,qs=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function Tt(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=>Tt(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();qs.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=Tt(s)}return e}return n}let Xe=!1;const js=500,ie=[];let Dt=0;function yn(){return Xe}const Sn=["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 Cn(n){const e=Xe;Xe=n,!n&&e&&(ie.length=0,We.clear(),Dt=0)}function _t(){return Xe}function zs(n){if(!yn()||n==="unknown"||Sn.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)),Sn.includes(e))return!1}return!0}function $s(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 Rt(n,e,t,s,r){if(r||!zs(n))return"";const o=$s(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++Dt}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:En(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Vs(i),Xs(n)){const c=Ys(e);c&&We.set(c,{entry:i,startTime:Date.now()})}return a}function Vs(n){ie.unshift(n),ie.length>js&&ie.pop()}function At(n,e,t,s){if(!yn())return"";const r=We.get(n);if(r){r.entry.response=En(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return We.delete(n),o}return""}function Ye(){return[...ie]}function Ks(){ie.length=0,We.clear(),Dt=0}function Xs(n){return n.startsWith("RPC:")&&!n.endsWith(":response")&&!n.endsWith(":error")?!0:["TASK_SUBMIT","TASK_CANCEL","TASK_RETRY","TASK_DELETE","TASK_GET_","WORKFLOW_SUBMIT","WORKFLOW_CANCEL","WORKFLOW_GET_","CHAT_START","MCP_TOOL_EXECUTE","MAIN_THREAD_TOOL_REQUEST"].some(t=>n.includes(t))}function Ys(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function En(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return Tt(e)}catch{return"[Non-serializable data]"}}function Qs(){const n={total:ie.length,sent:0,received:0,byType:{}};for(const e of ie)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const Lt=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Ks,getAllLogs:Ye,getLogStats:Qs,isPostMessageLoggerDebugMode:_t,logReceivedMessage:Rt,setPostMessageLoggerDebugMode:Cn,updateRequestWithResponse:At},Symbol.toStringTag,{value:"Module"}));function Js(){return typeof window<"u"?window:typeof self<"u"?self:{}}function Zs(n){return JSON.parse(JSON.stringify(n))}function Tn(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 er="postmessage-duplex",tr="1.2.0",Qe=Js();var Y,ce;Qe.__POSTMESSAGE_DUPLEX__||(Qe.__POSTMESSAGE_DUPLEX__={}),Qe.__POSTMESSAGE_DUPLEX__.version=tr,Qe.__POSTMESSAGE_DUPLEX__.name=er,(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"})(Y||(Y={})),(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"})(ce||(ce={}));class le 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,le)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class nr{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 sr{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 rr{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 Dn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const Z=n=>({valid:0,error:n});function or(n){if(!Dn(n))return Z("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"?Z("requestId must be a string"):s&&typeof e.cmdname!="string"?Z("cmdname must be a string"):r&&typeof e.msg!="string"?Z("msg must be a string"):!o||typeof(a=e.ret)=="number"&&Object.values(Y).includes(a)?"data"in e&&e.data!==void 0&&!Dn(e.data)?Z("data must be an object"):"_senderKey"in e&&e._senderKey!==void 0&&typeof e._senderKey!="string"?Z("_senderKey must be a string"):!("time"in e)||e.time===void 0||typeof e.time=="number"&&Number.isFinite(e.time)?{valid:1,message:e}:Z("time must be a finite number"):Z("ret must be a valid ReturnCode"):Z("Message must have requestId, cmdname, or msg field");var a}function Je(n){return"ret"in n&&typeof n.ret=="number"}function ar(n){return n.msg==="ready"}function ir(n){return n._broadcast==1&&typeof n.cmdname=="string"}function cr(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const vt=[],ee=[];function _n(n){ee.length>=200&&ee.shift(),ee.push(n)}function Rn(n,e){for(let t=ee.length-1;t>=0;t--)if(ee[t].requestId===n&&ee[t].status==="pending"){ee[t].status=e,ee[t].duration=Date.now()-ee[t].timestamp;break}}class lr extends rr{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 nr,this.rateLimiter=new sr((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,vt.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{_n({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?Rn(i,"ok"):_n({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{Rn(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=cr(e);if(t>this.maxMessageSize){const s=new le(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ce.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):Je(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=or(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:Je(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(!ir(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:Y.Success,data:o})}catch(o){const a=o instanceof Error?o.message:String(o);this.sendMessage({req:e,requestId:t,ret:Y.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(!ar(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}),Je(e)||this.sendMessage({requestId:t,ret:Y.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!Je(e)&&(this.log("warn","No registered handler for:",s||t),this.sendMessage({requestId:t,ret:Y.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 le("Cannot publish: channel has been destroyed",ce.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:Y.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=vt.findIndex(r=>r.deref()===t);s!==-1&&vt.splice(s,1)})(this);const e=new le("Channel has been destroyed",ce.ConnectionDestroyed);for(const[t,s]of this.callbackMap)try{s.reject({ret:Y.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 Q{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 Q.instance||(Q.instance=new Q),Q.instance}static resetInstance(){Q.instance&&(Q.instance.shutdown(),Q.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(Q,"instance",{enumerable:1,configurable:1,writable:1,value:null});class w extends lr{static enableGlobalRouting(e){w.useGlobalRouting=1,w.unknownClientCallback=e??null,w.globalListenerSetup||(self.addEventListener("message",w.globalMessageHandler),w.globalListenerSetup=1)}static disableGlobalRouting(){w.useGlobalRouting=0,w.globalListenerSetup&&(self.removeEventListener("message",w.globalMessageHandler),w.globalListenerSetup=0)}static setupHub(e={}){if(w.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");w.hubOptions=e,w.hubInitialized=1,Q.getInstance().setup(e,s=>w.createFromWorker(s)),w.enableGlobalRouting((s,r)=>{const o=w.createFromWorker(s);w.setupChannelHandlers(o,s),o.handleMessage(r)}),w.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(w.cleanupIntervalId=setInterval(()=>w.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){w.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 w.clientMeta.set(t,s),(o=(r=w.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:w.clientMeta.size}}),w.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:w.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of w.globalSubscribeMap)e.subscribe(s,async o=>{const a=w.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 w.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:w.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 w.channelsByClientId)if(!r.has(o)){const a=w.channelsByClientId.get(o);a&&a.destroy(),w.clientMeta.delete(o),(t=(e=w.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!w.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=w.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(!w.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=w.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=w.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 w.clientMeta.get(e)}static getAllClients(){return new Map(w.clientMeta)}static getClientsByType(e){const t=[];for(const s of w.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.`),w.globalSubscribeMap.set(e,t);for(const[s,r]of w.channelsByClientId)r.subscribe(e,async o=>{const a=w.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){w.globalSubscribeMap.delete(e);for(const t of w.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&w.useGlobalRouting&&w.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&w.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return w.channelsByClientId.get(e)}static hasChannel(e){return w.channelsByClientId.has(e)}static getChannelCount(){return w.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=Tn("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=Tn("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(w.useGlobalRouting)return void(w.globalListenerSetup||(self.addEventListener("message",w.globalMessageHandler),w.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(w.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=Zs(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===Y.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 le("Heartbeat detection failed",ce.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 le("All reconnection attempts failed",ce.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 le("Handshake timeout",ce.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 w(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 w(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 w.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(w,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(w,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(w,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(w,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(w,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(w,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(w,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(w,"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=w.channelsByClientId.get(t);s?s.handleMessage(n):w.unknownClientCallback&&w.unknownClientCallback(t,n)}});function ur(n,e,t){return Promise.race([n,new Promise(s=>setTimeout(()=>s(t),e))])}const T={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"},F={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"},_e=class _e{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(),w.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 wn.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 _e.instance||(_e.instance=new _e(e)),_e.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:w.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=Ye().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=_t()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=Rt(`RPC:${e}`,{params:o,requestId:i},t);this.broadcastPostMessageLog(u)}try{const u=await s(o);try{JSON.stringify(u)}catch(g){throw console.error(`[SW wrapRpcHandler] ${e} result serialization failed:`,g),new Error(`Result serialization failed: ${g}`)}if(c&&i){const g=At(i,{result:u},Date.now()-a);g&&this.broadcastPostMessageLog(g)}return u}catch(u){if(console.error(`[SW wrapRpcHandler] ${e} error:`,u),c&&i){const g=At(i,null,Date.now()-a,String(u));g&&this.broadcastPostMessageLog(g)}throw u}}}createSubscribeMap(e){return{[T.THUMBNAIL_GENERATE]:this.wrapRpcHandler(T.THUMBNAIL_GENERATE,e,t=>this.handleThumbnailGenerate(t)),[T.CRASH_SNAPSHOT]:async t=>{const s=this.unwrapRpcData(t);return this.handleCrashSnapshot(s)},[T.CRASH_HEARTBEAT]:async t=>{const s=this.unwrapRpcData(t);return this.handleHeartbeat(s)},[T.CONSOLE_REPORT]:async t=>{const s=this.unwrapRpcData(t);return this.handleConsoleReport(s)},[T.DEBUG_GET_STATUS]:async()=>this.handleDebugGetStatus(),[T.DEBUG_ENABLE]:async()=>this.handleDebugEnable(),[T.DEBUG_DISABLE]:async()=>this.handleDebugDisable(),[T.DEBUG_GET_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLogs(s)},[T.DEBUG_CLEAR_LOGS]:async()=>this.handleDebugClearLogs(),[T.DEBUG_GET_CONSOLE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetConsoleLogs(s)},[T.DEBUG_CLEAR_CONSOLE_LOGS]:async()=>this.handleDebugClearConsoleLogs(),[T.DEBUG_GET_POSTMESSAGE_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetPostMessageLogs(s)},[T.DEBUG_CLEAR_POSTMESSAGE_LOGS]:async()=>this.handleDebugClearPostMessageLogs(),[T.DEBUG_GET_CRASH_SNAPSHOTS]:async()=>this.handleDebugGetCrashSnapshots(),[T.DEBUG_CLEAR_CRASH_SNAPSHOTS]:async()=>this.handleDebugClearCrashSnapshots(),[T.DEBUG_GET_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogs(s)},[T.DEBUG_GET_LLM_API_LOG_BY_ID]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetLLMApiLogById(s==null?void 0:s.logId)},[T.DEBUG_CLEAR_LLM_API_LOGS]:async()=>this.handleDebugClearLLMApiLogs(),[T.DEBUG_DELETE_LLM_API_LOGS]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugDeleteLLMApiLogs(s)},[T.DEBUG_GET_CACHE_ENTRIES]:async t=>{const s=this.unwrapRpcData(t);return this.handleDebugGetCacheEntries(s)},[T.DEBUG_GET_CACHE_STATS]:async()=>this.handleDebugGetCacheStats(),[T.DEBUG_EXPORT_LOGS]:async()=>this.handleDebugExportLogs(),[T.CDN_GET_STATUS]:async()=>this.handleCDNGetStatus(),[T.CDN_RESET_STATUS]:async()=>this.handleCDNResetStatus(),[T.CDN_HEALTH_CHECK]:async()=>this.handleCDNHealthCheck(),[T.UPGRADE_GET_STATUS]:async()=>this.handleUpgradeGetStatus(),[T.UPGRADE_FORCE]:async()=>this.handleUpgradeForce(),[T.CACHE_DELETE]:async t=>{const s=this.unwrapRpcData(t);return this.handleCacheDelete(s)},[T.PING]:async()=>this.handlePing()}}async handleThumbnailGenerate(e){try{const{url:t,mediaType:s,blob:r,mimeType:o,sizes:a}=e,{generateThumbnailAsync:i}=await Promise.resolve().then(()=>q),c=new Blob([r],{type:o||(s==="video"?"video/mp4":"image/png")});return i(c,t,s,a),{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(()=>R);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(()=>R),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(()=>R),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(()=>R);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(()=>R);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(()=>R),{limit:r=100,offset:o=0,filter:a}=e||{},i=s().map(f=>({...f,type:"fetch"})),c=t(),l=new Map;for(const f of c)l.set(f.id,f);for(const f of i)l.set(f.id,f);let u=Array.from(l.values()).sort((f,b)=>b.timestamp-f.timestamp);return a&&(a.type&&(u=u.filter(f=>f.type===a.type)),a.status&&(u=u.filter(f=>f.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(()=>R);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>R),{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,g;return((u=l.logMessage)==null?void 0:u.toLowerCase().includes(c))||((g=l.logStack)==null?void 0:g.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(()=>R);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>Lt),{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 g;return(g=u.messageType)==null?void 0:g.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(()=>Lt);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>R),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(()=>R);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(()=>De);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(()=>De);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(()=>De);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(()=>De);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(()=>R),{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],g=await a.match(u);if(g){const f=g.headers.get("sw-cache-date"),b=g.headers.get("sw-cache-created-at")||f,h=g.headers.get("sw-image-size")||g.headers.get("content-length");c.push({url:u.url,cacheDate:f?parseInt(f):void 0,cacheCreatedAt:b?parseInt(b):void 0,size:h?parseInt(h):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 g=u.headers.get("content-length");g&&(c+=parseInt(g))}}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(()=>R),{getAllLogs:o}=await Promise.resolve().then(()=>Lt),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(()=>R);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>R);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>R),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>R);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>R);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>R);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(F.CACHE_IMAGE_CACHED,{url:e,size:t,thumbnailUrl:s})}sendCacheDeleted(e){this.broadcastToAll(F.CACHE_DELETED,{url:e})}sendCacheQuotaWarning(e,t,s){this.broadcastToAll(F.CACHE_QUOTA_WARNING,{usage:e,quota:t,percentUsed:s})}sendSWNewVersionReady(e){this.broadcastToAll(F.SW_NEW_VERSION_READY,{version:e})}sendSWActivated(e){this.broadcastToAll(F.SW_ACTIVATED,{version:e})}sendSWUpdated(e){this.broadcastToAll(F.SW_UPDATED,{version:e})}sendDebugStatusChanged(e){this.broadcastToAll(F.DEBUG_STATUS_CHANGED,{enabled:e})}sendDebugLog(e){this.broadcastToAll(F.DEBUG_LOG,{entry:e})}sendConsoleLog(e){this.broadcastToAll(F.CONSOLE_LOG,{entry:e})}sendDebugLLMLog(e){this.broadcastToAll(F.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(F.POSTMESSAGE_LOG_BATCH,{entries:e})}sendNewCrashSnapshot(e){this.broadcastToAll(F.DEBUG_NEW_CRASH_SNAPSHOT,{snapshot:e})}async requestVideoThumbnail(e,t=3e4,s){const r=Array.from(this.channels.values()).sort((o,a)=>o.isDebugClient===a.isDebugClient?a.createdAt-o.createdAt:o.isDebugClient?1:-1);if(r.length===0)return null;for(const o of r)try{const a=await ur(o.channel.call("thumbnail:generate",{url:e,maxSize:s}),t,"Video thumbnail generation timeout");if(!a||a.ret!==0)continue;const i=a.data;if(i!=null&&i.error||!(i!=null&&i.thumbnailUrl))continue;return i.thumbnailUrl}catch{continue}return 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()))}};_e.instance=null;let Ze=_e,et=null;function An(n){return et||(et=Ze.getInstance(n)),et}function O(){return et}const dr=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:T,SWChannelManager:Ze,SW_EVENTS:F,getChannelManager:O,initChannelManager:An},Symbol.toStringTag,{value:"Module"}));function tt(n){Cn(n)}const hr=[];let Ln=!1;function Be(n){Ln=n}function Mt(){return Ln}function Pt(){return[...hr]}const gr=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Pt,isDebugFetchEnabled:Mt,setDebugFetchEnabled:Be},Symbol.toStringTag,{value:"Module"})),fr=typeof location<"u"&&(location.hostname==="localhost"||location.hostname==="127.0.0.1"),W={packageName:"aitu-app",healthCheckInterval:300*1e3,degradeTimeout:60*1e3,failThreshold:3,fetchTimeout:1500,backgroundFetchTimeout:8e3,localFetchTimeout:5e3,preferenceCacheExpiry:3600*1e3,preferenceCacheName:"drawnix-cdn-v1",preferenceCacheKey:typeof location<"u"?new URL("/__sw__/cdn-preference",location.origin).href:"https://opentu.local/__sw__/cdn-preference"},pr={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3},unpkg:{baseTimeout:600*1e3,maxTimeout:3600*1e3}},nt=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1}],be=new Map;let te=null,It=!1,st=null;function vn(n=!1){n&&be.clear(),nt.forEach(e=>{be.has(e.name)||be.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}vn();function mr(n){return n==="jsdelivr"||n==="unpkg"||n==="local"}function Mn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!mr(t)||typeof s!="string"||s.trim()==="")return null;const r=Number(e.latency),o=Number(e.timestamp);return{cdn:t,version:s.trim(),latency:Number.isFinite(r)&&r>=0?r:0,timestamp:Number.isFinite(o)&&o>0?o:Date.now()}}function Pn(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=W.preferenceCacheExpiry}async function br(){if(typeof caches>"u")return null;try{const e=await(await caches.open(W.preferenceCacheName)).match(W.preferenceCacheKey);return e!=null&&e.ok?Mn(await e.json()):null}catch(n){return console.warn("[CDN Fallback] Failed to read persisted CDN preference:",n),null}}async function kt(){It||(st||(st=(async()=>{te=await br(),It=!0,st=null})()),await st)}async function In(n){if(te=Mn(n),It=!0,!(typeof caches>"u"))try{const e=await caches.open(W.preferenceCacheName);if(!te){await e.delete(W.preferenceCacheKey);return}await e.put(W.preferenceCacheKey,new Response(JSON.stringify(te),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}}))}catch(e){console.warn("[CDN Fallback] Failed to persist CDN preference:",e)}}function Ot(n){const e=be.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now(),e.lastFailureReason=void 0)}function ue(n,e){const t=be.get(n);if(t)if(t.failCount++,t.lastCheckTime=Date.now(),t.lastFailureReason=e,t.failCount>=W.failThreshold){t.isHealthy=!1;const s=On(t);console.warn(`[CDN Fallback] ${n} marked as unhealthy after ${t.failCount} failures, cooldown=${s.cooldownMs}ms, reason=${e??"unknown"}`)}else console.warn(`[CDN Fallback] ${n} failure count=${t.failCount}, reason=${e??"unknown"}`)}function kn(n,e){const t=pr[n]??{baseTimeout:W.degradeTimeout,maxTimeout:W.degradeTimeout},r=2**Math.max(0,e-W.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function On(n){const e=kn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function Wt(n,e={}){const t=be.get(n);if(!t)return!1;if(t.isHealthy)return!0;if(e.ignoreCooldown)return console.log(`[CDN Fallback] Ignoring cooldown for ${n}, probing CDN directly`),!0;const s=Date.now(),r=kn(n,t.failCount);return s-t.lastCheckTime>r?(console.log(`[CDN Fallback] Trying to recover ${n} after ${r}ms cooldown...`),!0):!1}function wr(n,e={}){const t=te;return!t||!Pn(t,n)||t.cdn==="local"?null:Wt(t.cdn,e)?t.cdn:null}function Wn(n,e={}){const t=n?wr(n,e):null;return nt.filter(s=>s.enabled&&Wt(s.name,e)).sort((s,r)=>t&&s.name===t&&r.name!==t?-1:t&&r.name===t&&s.name!==t?1:s.priority-r.priority)}function Bn(n){const e=String(n||"").trim();if(!e)return e;let t=e;try{if(/^https?:\/\//i.test(t)){const s=new URL(t);t=`${s.pathname}${s.search}`}}catch{}return t=t.replace(/^\/?npm\/aitu-app@[^/]+\//,"/").replace(/^\/?aitu-app@[^/]+\//,"/"),t}function xn(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function yr(n,e){const t=String(e||"").trim();if(!t)return null;let s=t;try{if(/^https?:\/\//i.test(s)){const o=new URL(s);s=`${o.pathname}${o.search}`}}catch{}const r=s.startsWith("/")?s:`/${s}`;return/^\/npm\/(?!aitu-app@)[^/]+@[^/]+\//.test(r)?n.name==="jsdelivr"?`https://cdn.jsdelivr.net${r}`:n.name==="unpkg"?`https://unpkg.com/${r.replace(/^\/npm\//,"")}`:null:null}function Bt(n,e,t){const s=yr(n,t);if(s)return s;const r=Bn(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function xt(n,e=W.fetchTimeout){const t=new AbortController,s=setTimeout(()=>t.abort(),e);try{return await fetch(n,{signal:t.signal,cache:"no-store"})}finally{clearTimeout(s)}}function Nt(n,e){const t=Bn(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function Nn(n,e,t){try{const s=Nt(e,n);console.log(`[CDN Fallback] Trying local server: ${s}`);const r=await xt(s,t);return r.ok?(console.log("[CDN Fallback] Success from local server"),{response:r,source:"local"}):(console.warn(`[CDN Fallback] Local server returned ${r.status}`),null)}catch(s){return console.warn("[CDN Fallback] Local server failed:",s),null}}async function Gn(n,e,t,s){for(const r of n){const o=Bt(r,e,t);try{console.log(`[CDN Fallback] Trying ${r.name}: ${o}`);const a=await xt(o,s);if(!a.ok){ue(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await Sr(a,r.name))continue;return Ot(r.name),console.log(`[CDN Fallback] Success from ${r.name}`),{response:a,source:r.name,targetUrl:o}}catch(a){const i=a instanceof Error&&a.name==="AbortError"?"timeout":"network-error";ue(r.name,i),console.warn(`[CDN Fallback] ${r.name} failed:`,a)}}return null}async function Sr(n,e){var i;const t=n.headers.get("Content-Type")||"";if(!(t.includes("javascript")||t.includes("css")||t.includes("json")||t.includes("font")||t.includes("image")||t.includes("woff")||t.includes("application/octet-stream")))return ue(e,`invalid-content-type:${t}`),console.warn(`[CDN Fallback] ${e} invalid Content-Type: ${t}`),!1;const r=parseInt(n.headers.get("Content-Length")||"0",10),o=t.includes("javascript")||t.includes("css")||t.includes("json");if(o&&r>0&&r<50)return ue(e,`response-too-small:${r}`),console.warn(`[CDN Fallback] ${e} response too small: ${r} bytes`),!1;const a=n.clone();try{const c=(i=a.body)==null?void 0:i.getReader();if(c){const{value:l}=await c.read();if(c.cancel(),l){const u=new TextDecoder().decode(l.slice(0,200)),g=u.includes("<!DOCTYPE")||u.includes("<html")||u.includes("<HTML")||u.includes("Not Found")||u.includes("404");if(o&&g)return ue(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function Gt(n,e,t,s={}){if(fr)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;await kt();const{preferLocal:r=!1,localTimeout:o=W.localFetchTimeout,requestKind:a="interactive-runtime"}=s,i=a==="background-prefetch",c=s.cdnTimeout??(a==="background-prefetch"?W.backgroundFetchTimeout:W.fetchTimeout);if(r){const f=await Nn(n,t,o);if(f)return{...f,targetUrl:Nt(t,n)}}const l=Wn(e,{ignoreCooldown:i}),u=await Gn(l,e,n,c);if(u)return u;if(!r){const f=await Nn(n,t,o);if(f)return{...f,targetUrl:Nt(t,n)}}const g=nt.filter(f=>f.enabled&&!l.some(b=>b.name===f.name));if(g.length>0){console.warn(`[CDN Fallback] Local origin failed, forcing CDN recovery probe for: ${n}`);const f=await Gn(g,e,n,c);if(f)return f}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function Ft(n){await kt();const e=new Map;for(const t of nt){if(!t.enabled)continue;const s=Bt(t,n,t.healthCheckPath);try{const r=await xt(s,5e3),o=r.ok;e.set(t.name,o),o?Ot(t.name):ue(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),ue(t.name,"health-check-failed")}}return e}function rt(){const n=Pn(te)?te==null?void 0:te.cdn:null;return Array.from(be.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...On(t)}))}function Ut(){vn(!0),console.log("[CDN Fallback] All CDN status reset")}const Cr=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Bt,ensureCDNPreferenceLoaded:kt,extractVersionFromCDNPath:xn,fetchFromCDNWithFallback:Gt,getAvailableCDNs:Wn,getCDNStatusReport:rt,isCDNAvailable:Wt,markCDNFailure:ue,markCDNSuccess:Ot,performHealthCheck:Ft,resetCDNStatus:Ut,setCDNPreference:In},Symbol.toStringTag,{value:"Module"}));function Ht(n){return n==="/"||n==="/index.html"}const Er=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"];function Tr(n,e){return Ht(e)?!0:n==="navigate"&&!e.endsWith(".html")}function Dr(n){return Ht(n)}function Fn(n){return Ht(n)?!0:Er.some(e=>n.endsWith(e))}function _r(n){return!Fn(n)}const U=self;An(U).setDebugClientCountChangedCallback(Hr);const ne={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function ot(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 Rr(){console.log=(...n)=>{ne.log(...n),Mt()&&!ot(n)&&at("log",n)},console.info=(...n)=>{ne.info(...n),Mt()&&!ot(n)&&at("info",n)},console.warn=(...n)=>{ne.warn(...n),ot(n)||at("warn",n)},console.error=(...n)=>{ne.error(...n),ot(n)||at("error",n)}}function Ar(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 at(n,e){try{const{message:t,stack:s}=Ar(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof qt=="function"&&qt({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){ne.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let qt=null;Rr(),Promise.resolve().then(()=>De).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=O();t&&t.sendDebugLLMLog(e)})});const C="0.6.78",it=new URL("./",self.location.href),jt=it.pathname,zt=`drawnix-v${C}`,L="drawnix-images",Re=`drawnix-static-v${C}`,ct="drawnix-fonts",se="sw-cache-date",we="sw-cache-created-at",$t="x-sw-source",Vt="x-sw-revision",Kt="x-sw-app-version",Un="x-sw-fetch-target",Lr="ServiceWorkerDB",vr=2,Ae="failedDomains",Le="versionState",Hn="app-version-state",qn="/__aitu_cache__/",jn="/__aitu_generated__/audio/",Mr="/asset-library/",xe=location.hostname==="localhost"||location.hostname==="127.0.0.1";function B(n){return new URL(n.replace(/^\//,""),it)}function ve(n){return jt!=="/"&&n.startsWith(jt)?`/${n.slice(jt.length)}`:n}const Pr=[{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"}],Ir=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,kr=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Xt=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,Or=new Set(["_t","cache_buster","v","timestamp","nocache","_cb","t","retry","_retry","_poster_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 Yt(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)Or.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const z=new Map,ye=new Map,zn=30*1e3,Ne=new Map,H=new Map,Wr=300*1e3,$n=10,Me=new Set,Pe=new Set,Br=3600*1e3,Qt=new Map;function Vn(n){Pe.add(n),Qt.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function xr(n){if(!Pe.has(n))return!1;const e=Qt.get(n);return e&&Date.now()-e>Br?(Pe.delete(n),Qt.delete(n),!1):!0}const J=[],Kn=7,K=[],Nr=500;let I=!1;function k(n){if(!I)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return K.unshift(t),K.length>Nr&&K.pop(),Xn(t),e}function v(n,e){if(!I||!n)return;const t=K.find(s=>s.id===n);t&&(Object.assign(t,e),Xn(t))}function Xn(n){const e=O();e&&e.sendDebugLog(n)}function lt(){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 Gr(n){try{const e=await lt(),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 Yn(){try{await Qn();const n=await lt(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Kn*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 Qn(){try{const n=await lt(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Kn*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 Jn(){try{const n=await lt(),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 Zn=500;function Jt(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(I||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};Gr(r),J.unshift(r),J.length>Zn&&(J.length=Zn),I&&Fr(r)}qt=Jt;function Fr(n){const e=O();e&&e.sendConsoleLog(n)}function Ur(){let n=0;return H.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function es(){return{version:C,cacheNames:[zt,L,Re,ct],pendingImageRequests:z.size,pendingVideoRequests:Ne.size,videoBlobCacheSize:H.size,videoBlobCacheTotalBytes:Ur(),completedImageRequestsSize:ye.size,failedDomainsCount:Me.size,failedDomains:Array.from(Me),corsFailedDomainsCount:Pe.size,corsFailedDomains:Array.from(Pe),debugLogsCount:K.length,consoleLogsCount:J.length,debugModeEnabled:I,memoryStats:{pendingRequestsMapSize:z.size,completedRequestsMapSize:ye.size,videoBlobCacheMapSize:H.size,failedDomainsSetSize:Me.size,corsFailedDomainsSetSize:Pe.size,debugLogsArraySize:K.length,consoleLogsArraySize:J.length}}}function Zt(){return K}function ts(){K.length=0}function ns(){J.length=0}function en(){I||(I=!0,Be(!0),tt(!0),ne.log("Service Worker: Debug mode enabled (debug page connected)"))}function tn(){I&&(I=!1,Be(!1),tt(!1),J.length=0,K.length=0,ne.log("Service Worker: Debug mode disabled (no debug pages)"))}function Hr(n){n>0?en():tn()}function ss(n){for(const e of Pr)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function qr(n,e){return Ir.test(n.pathname)||e.destination==="image"||ss(n)!==null}function jr(n,e){return kr.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function zr(n,e){return Xt.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function $r(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 Vr(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function rs(n){return`drawnix-static-v${n}`}function os(){return{committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function as(n){const e=n||{},t=typeof e.committedVersion=="string"&&e.committedVersion?e.committedVersion:C,s=typeof e.pendingVersion=="string"&&e.pendingVersion?e.pendingVersion:null,r=typeof e.pendingReadyAt=="number"&&Number.isFinite(e.pendingReadyAt)?e.pendingReadyAt:null,o=e.upgradeState==="prewarming"||e.upgradeState==="ready"||e.upgradeState==="committing"?e.upgradeState:"idle";return{committedVersion:t,pendingVersion:s,pendingReadyAt:r,upgradeState:o,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:Date.now()}}function ut(){return new Promise((n,e)=>{const t=indexedDB.open(Lr,vr);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains(Ae)||r.createObjectStore(Ae,{keyPath:"domain"}),r.objectStoreNames.contains(Le)||r.createObjectStore(Le,{keyPath:"key"})}})}async function Ge(){try{const n=await ut();return await new Promise((e,t)=>{const o=n.transaction([Le],"readonly").objectStore(Le).get(Hn);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(as((a==null?void 0:a.state)||os()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),os()}}async function Kr(n){const e=as(n);try{const t=await ut();await new Promise((s,r)=>{const o=t.transaction([Le],"readwrite");o.objectStore(Le).put({key:Hn,state:e}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.warn("Service Worker: 无法写入版本状态:",t)}return e}async function Se(n){const e=await Ge(),t=typeof n=="function"?n(e):n;return Kr({...e,...t,updatedAt:Date.now()})}async function de(n){const e=await Ge(),t={type:"SW_VERSION_STATE",...e,swVersion:C};if(n)return n.postMessage(t),e;const s=await U.clients.matchAll({type:"window",includeUncontrolled:!0});for(const r of s)r.postMessage(t);return e}async function Xr(){try{const n=await ut();return await new Promise((e,t)=>{const o=n.transaction([Ae],"readonly").objectStore(Ae).getAll();o.onsuccess=()=>{o.result.forEach(i=>Me.add(i.domain)),e()},o.onerror=()=>t(o.error)})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function Yr(n){try{const e=await ut();return await new Promise((t,s)=>{const r=e.transaction([Ae],"readwrite");r.objectStore(Ae).put({domain:n,timestamp:Date.now()}),r.oncomplete=()=>t(),r.onerror=()=>s(r.error)})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function Qr(n){if(!n){await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();return}await Se(t=>({committedVersion:t.committedVersion||C,pendingVersion:C,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=O();e&&e.sendSWNewVersionReady(C),await de()}async function Jr(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(se),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)}}const is=2,nn=1500,sn=2500,Zr=8e3,eo=5e3,to=6e4,Ce=5e3,no=600*1e3,so=["offline-static-assets"],ro="disabled-in-development";let Fe=0,cs=0;const Ue=new Set,He=new Set,qe=new Set,dt=new Map;let ls=Promise.resolve(),je=null,ze=0,he=!1,ht=!1;function y(n,e){if(e===void 0){console.info(`[SWDebug] ${n}`);return}console.info(`[SWDebug] ${n}`,e)}function us(){return rt().filter(n=>n.remainingCooldownMs>0&&!n.status.isHealthy).map(n=>({name:n.name,failCount:n.status.failCount,remainingCooldownMs:n.remainingCooldownMs,lastFailureReason:n.status.lastFailureReason}))}function ds(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:us(),...t})}let rn={phase:"idle",percent:0,completed:0,total:0,failed:0,version:C,updatedAt:Date.now()};async function hs(n){const e={type:"SW_BOOT_PROGRESS",...rn};if(n){n.postMessage(e);return}const t=await U.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e)}function Ee(n,e){rn={...rn,...n,version:C,updatedAt:Date.now()},hs(e)}async function oo(){try{const n=await fetch(B("precache-manifest.json").href,{cache:"reload"});if(!n.ok)return y("loadPrecacheManifest: response not ok",{status:n.status,statusText:n.statusText}),null;const e=await n.json();return y("loadPrecacheManifest: loaded",{version:e.version,fileCount:e.files.length}),e.version&&e.version!==C?(y("loadPrecacheManifest: version mismatch",{manifestVersion:e.version,workerVersion:C}),null):e.files}catch(n){return y("loadPrecacheManifest: failed",{error:ae(n)}),null}}let Ie=null,Te=0,ge=null;function $e(){return xe}async function ao(n,e=200){try{const t=(await n.text()).replace(/\s+/g," ").trim();return t?t.slice(0,e):void 0}catch{return}}async function io(){if($e())return y("loadIdlePrefetchManifest: skipped in development mode"),null;const n=B("idle-prefetch-manifest.json").href;try{const e=await fetch(n,{cache:"reload"}),t=e.headers.get("content-type")||"";if(!e.ok){const a=await ao(e.clone());return y("loadIdlePrefetchManifest: response not ok",{manifestUrl:n,status:e.status,statusText:e.statusText,contentType:t,preview:a}),null}const s=await e.text(),r=s.replace(/\s+/g," ").trim().slice(0,200);if(t.includes("text/html")||/<!DOCTYPE|<html|<HTML/i.test(r))return y("loadIdlePrefetchManifest: html fallback detected",{manifestUrl:n,status:e.status,contentType:t,preview:r}),null;let o;try{o=JSON.parse(s)}catch(a){return y("loadIdlePrefetchManifest: invalid json",{manifestUrl:n,contentType:t,error:ae(a),preview:r}),null}return!o||typeof o!="object"||!o.groups?(y("loadIdlePrefetchManifest: invalid manifest shape",{manifestUrl:n,contentType:t,preview:r}),null):o.version&&o.version!==C?(y("loadIdlePrefetchManifest: version mismatch",{manifestUrl:n,manifestVersion:o.version,workerVersion:C}),null):(y("loadIdlePrefetchManifest: loaded",{manifestUrl:n,version:o.version,defaults:o.defaults||[],groupEntryCounts:Object.fromEntries(Object.entries(o.groups).map(([a,i])=>[a,i.length]))}),o)}catch(e){return y("loadIdlePrefetchManifest: failed",{manifestUrl:n,error:ae(e)}),null}}async function gt(){if($e())return Te=0,ge=ro,Ie=null,null;const n=Date.now();if(!Ie){if(Te>0&&n-Te<Ce){const e=Ce-(n-Te);return y("getIdlePrefetchManifest: retry cooldown active",{retryAfterMs:e,lastFailureReason:ge}),null}Ie=io().then(e=>e?(Te=0,ge=null,e):(Te=Date.now(),ge="manifest-missing-or-invalid",Ie=null,null)).catch(e=>{throw Te=Date.now(),ge=ae(e),Ie=null,e})}return Ie}async function on(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(qe),version:C,updatedAt:Date.now()};if(n){y("broadcast idle prefetch status to target client",{clientId:n.id,completedGroups:e.completedGroups}),n.postMessage(e);return}const t=await U.clients.matchAll({type:"window",includeUncontrolled:!0});for(const s of t)s.postMessage(e);y("broadcast idle prefetch status to all clients",{clientCount:t.length,completedGroups:e.completedGroups})}function co(n,e){return`${n}@${e}`}async function ft(n){try{return(await n.keys()).length}catch{return-1}}function pt(n,e){const t=ls.catch(()=>{}).then(async()=>{y("idle prefetch task start",{label:n});try{await e()}finally{y("idle prefetch task done",{label:n})}});return ls=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:ae(s)})}),t}function lo(n){return Math.min(to,eo*2**Math.max(0,n-1))}function gs(n,e=[]){const t=[],s=new Set,r=o=>{!o||s.has(o)||(n.groups[o]||[]).length===0||(s.add(o),t.push(o))};return e.forEach(r),(n.defaults||[]).forEach(r),so.forEach(r),Object.keys(n.groups).forEach(r),t}function fs(n,e){const t=Date.now(),s=new Map,r=[],o=[];let a=0,i=null;for(const c of e){const l=n.groups[c]||[];if(l.length===0)continue;let u=!1;for(const g of l){const f=co(g.url,g.revision);if(Ue.has(f)||(u=!0,He.has(f)))continue;const b=dt.get(f);if(b&&b.nextRetryAt>t){a+=1;const h=Math.max(0,b.nextRetryAt-t);i=i===null?h:Math.min(i,h);continue}s.set(f,g)}u?o.push(c):r.push(c)}return{completedGroups:r,pendingGroups:o,queue:Array.from(s.entries()),coolingEntries:a,nextRetryDelayMs:i}}function an(n,e=sn){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(je!==null){if(ze<=s){y("scheduleIdlePrefetchSweep skipped: earlier timer already exists",{reason:n,scheduledInMs:Math.max(0,ze-Date.now()),requestedDelayMs:t});return}clearTimeout(je),je=null,ze=0}ze=s,je=self.setTimeout(()=>{je=null,ze=0,pt(`idle-sweep:${n}`,async()=>{await wt(`scheduled:${n}`)})},t),y("scheduleIdlePrefetchSweep queued",{reason:n,delayMs:t})}function uo(){return Fe===0?!1:Date.now()-Fe<nn}function ho(){if(Fe===0)return Promise.resolve();const n=Date.now()-Fe,e=Math.max(0,nn-n)+100;return y("waitForIdlePrefetchWindow: delaying idle prefetch",{elapsedMs:n,waitMs:e,recentFetchWindowMs:nn}),new Promise(t=>{setTimeout(t,e)})}function go(n,e){const t=ve(e.pathname);if(n.request.method!=="GET"||!n.clientId||e.origin!==self.location.origin||e.pathname.startsWith(qn)||e.pathname.startsWith(jn)||t==="/sw.js"||t==="/precache-manifest.json"||t==="/idle-prefetch-manifest.json")return!1;const s=Date.now();return s-cs<Zr?!1:(cs=s,!0)}function fo(n){return Fn(ve(n))}function ps(n,e){return xe||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||fo(e.pathname)?!1:!!(e.pathname.match(/\.(js|css|png|jpg|jpeg|gif|webp|svg|woff|woff2|ttf|eot|json|ico)$/i)||n.destination==="script"||n.destination==="style"||n.destination==="image"||n.destination==="font")}function po(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${e.replace(/^\/npm\/aitu-app@[^/]+\//,"/").replace(/^\/aitu-app@[^/]+\//,"/")}${t}`}function mo(n){const[e,t=""]=n.split(/([?#].*)/,2);return`${ve(e)}${t}`}function mt(n){const e=new URL(n,self.location.origin),t=po(mo(`${e.pathname}${e.search}`)),s=B(t);return{requestUrl:e,resourcePath:t,cacheKey:s.href,originFetchUrl:s.href}}function Ve(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&ps(n,e)}function bo(n,e){const t=new Headers(n.headers);return t.set($t,e.source),t.set(Vt,e.revision),t.set(Kt,e.appVersion||C),e.fetchTarget&&t.set(Un,e.fetchTarget),t.set("x-sw-cached-at",new Date().toISOString()),new Response(n.body,{status:n.status,statusText:n.statusText,headers:t})}async function cn(n,e,t,s){const r=bo(t,s);return await n.put(e,r.clone()),r}async function bt(n,e=[]){const t=e.filter(r=>!!r&&r!==n.url),s=await caches.keys();for(const r of s)if(r.startsWith("drawnix-static-v"))try{const o=await caches.open(r),a=await o.match(n);if(a)return a;for(const i of t){const c=await o.match(i);if(c)return y("findStaticResponseInOldCaches: normalized key hit",{cacheName:r,requestUrl:n.url,normalizedCacheKey:i}),c}}catch{}return null}async function wo(n,e=[]){const t=[n.url,...e].filter(Boolean);for(const s of t)try{const r=await fetch(s,{cache:"only-if-cached",mode:"same-origin"});if(r.ok)return r}catch{}return null}async function yo(n,e){const t=mt(e.url).cacheKey,s=await n.match(e);if(s)return{response:s,normalizedCacheKey:t,matchedBy:"request"};if(t!==e.url){const r=await n.match(t);if(r)return{response:r,normalizedCacheKey:t,matchedBy:"normalized"}}return{response:null,normalizedCacheKey:t,matchedBy:null}}async function So(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function ms(n,e,t){try{const s=mt(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(Vt),l=r.headers.get(Kt);if(c===t&&l===C)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(_r(ve(s.requestUrl.pathname))){const c=await Gt(s.resourcePath,C,it.href.replace(/\/$/,""),{preferLocal:!1,requestKind:"background-prefetch"});c!=null&&c.response.ok&&(o=c.response,a=c.source,i=c.targetUrl)}if(o||(o=await fetch(s.originFetchUrl,{cache:"reload"}),a="server",i=s.originFetchUrl),o.ok&&Ve(new Request(s.cacheKey,{method:"GET"}),s.requestUrl,o))return{url:e,success:!1,status:404,error:"html-fallback-for-static-resource"};if(o.ok){if(await cn(n,s.cacheKey,o,{source:a,revision:t,fetchTarget:i,appVersion:C}),s.resourcePath==="/index.html"){const c=B("/").href,l=await n.match(s.cacheKey);l&&await n.put(c,l.clone())}return{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 Co(n,e){const s=[],r=e.length;let o=0,a=0;const i=await ft(n);y("precacheStaticFiles start",{total:r,concurrency:6,cacheEntriesBefore:i,sampleUrls:e.slice(0,8).map(b=>b.url)}),Ee({phase:"precache",total:r,completed:0,failed:0,percent:r>0?0:100,message:r>0?`正在预热启动资源(0/${r})...`:"没有需要预热的启动资源"});for(let b=0;b<e.length;b+=6){const h=e.slice(b,b+6),p=await Promise.allSettled(h.map(({url:m,revision:S})=>ms(n,m,S))),d=[];for(const m of p)if(m.status==="fulfilled"){const S={url:m.value.url,success:m.value.success,skipped:m.value.skipped,source:m.value.source,status:m.value.status,error:m.value.error};s.push(S),d.push(S),o+=1,m.value.success||(a+=1)}else{const S={success:!1,error:String(m.reason)};s.push(S),d.push(S),o+=1,a+=1}y("precacheStaticFiles batch done",{completed:o,total:r,batchSize:h.length,batchSuccess:d.filter(m=>m.success).length,batchSkipped:d.filter(m=>m.skipped).length,batchFailed:d.filter(m=>!m.success).length,batchSources:Object.fromEntries(Array.from(d.reduce((m,S)=>{const E=S.source||"unknown";return m.set(E,(m.get(E)||0)+1),m},new Map))),batchErrors:d.filter(m=>!m.success).slice(0,5).map(m=>({url:m.url,status:m.status,error:m.error}))}),Ee({phase:"precache",total:r,completed:o,failed:a,percent:r>0?Math.round(o/r*100):100,message:r>0?`正在预热启动资源(${o}/${r}${a>0?`,${a} 项回退`:""})...`:"没有需要预热的启动资源"})}const c=s.filter(b=>b.success).length,l=s.length-c,u=s.filter(b=>b.success&&b.source&&b.source!=="server").length,g=s.filter(b=>b.success&&b.source==="server").length,f=await ft(n);return y("precacheStaticFiles finished",{total:r,successCount:c,failCount:l,cdnCount:u,serverCount:g,cacheEntriesBefore:i,cacheEntriesAfter:f}),{total:r,successCount:c,failCount:l,cdnCount:u,serverCount:g}}async function bs(n){if(y("prefetchIdleGroups start",{groupNames:n}),n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await gt();if(!e)return y("prefetchIdleGroups aborted: manifest missing"),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};y("prefetchIdleGroups manifest summary",{requestedGroups:n,groupEntryCounts:Object.fromEntries(n.map(u=>{var g;return[u,((g=e.groups[u])==null?void 0:g.length)||0]})),defaults:e.defaults||[]});const t=new Set(qe),s=fs(e,n);if(s.completedGroups.forEach(u=>qe.add(u)),s.queue.length===0)return y("prefetchIdleGroups no ready files",{groupNames:n,completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs,completedEntries:Ue.size,activeEntries:He.size}),{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(Re),o=await ft(r),a=s.queue;y("prefetchIdleGroups queue prepared",{groupNames:n,totalCandidates:s.queue.length,queuedEntries:a.length,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,cacheEntriesBefore:o,sampleUrls:a.slice(0,8).map(([,u])=>u.url)});for(let u=0;u<a.length;u+=is){for(;uo();)await ho();const g=a.slice(u,u+is);g.forEach(([h])=>He.add(h));const f=await Promise.allSettled(g.map(([,{url:h,revision:p}])=>ms(r,h,p))),b=[];f.forEach((h,p)=>{const[d]=g[p];if(He.delete(d),h.status==="fulfilled"&&h.value.success)dt.delete(d),Ue.add(d);else{const m=dt.get(d),S=((m==null?void 0:m.count)||0)+1,E=lo(S);dt.set(d,{count:S,nextRetryAt:Date.now()+E,lastError:h.status==="fulfilled"?h.value.error:String(h.reason),lastStatus:h.status==="fulfilled"?h.value.status:void 0})}h.status==="fulfilled"?b.push({url:h.value.url,success:h.value.success,skipped:h.value.skipped,source:h.value.source,status:h.value.status,error:h.value.error}):b.push({success:!1,error:String(h.reason)})}),y("prefetchIdleGroups batch done",{groupNames:n,batchStart:u,batchSize:g.length,batchSuccess:b.filter(h=>h.success).length,batchSkipped:b.filter(h=>h.skipped).length,batchFailed:b.filter(h=>!h.success).length,batchSources:Object.fromEntries(Array.from(b.reduce((h,p)=>{const d=p.source||"unknown";return h.set(d,(h.get(d)||0)+1),h},new Map))),batchErrors:b.filter(h=>!h.success).slice(0,5).map(h=>({url:h.url,status:h.status,error:h.error})),completedEntries:Ue.size,activeEntries:He.size})}const i=fs(e,n),c=i.completedGroups.filter(u=>!t.has(u));c.forEach(u=>qe.add(u));const l=await ft(r);return y("prefetchIdleGroups finished",{groupNames:n,newlyCompletedGroups:c,pendingGroups:i.pendingGroups,completedEntries:Ue.size,cacheEntriesBefore:o,cacheEntriesAfter:l,completedGroups:Array.from(qe),coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}),{completedGroups:c,pendingGroups:i.pendingGroups,queuedEntries:a.length,coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}}async function wt(n,e=[]){if($e())return y("prefetchPendingIdleGroups skipped: disabled in development",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const t=await gt();if(!t)return an(`${n}:manifest-missing`,Ce),y("prefetchPendingIdleGroups skipped: manifest missing",{reason:n,preferredGroups:e,retryDelayMs:Ce,lastFailureReason:ge}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:Ce};const s=gs(t,e);if(s.length===0)return y("prefetchPendingIdleGroups skipped: no groups",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};y("prefetchPendingIdleGroups start",{reason:n,preferredGroups:e,orderedGroups:s,groupEntryCounts:Object.fromEntries(s.map(o=>{var a;return[o,((a=t.groups[o])==null?void 0:a.length)||0]}))});const r=await bs(s);return r.completedGroups.length>0&&await on(),r.pendingGroups.length>0&&an(`${n}:pending`,r.nextRetryDelayMs??sn),y("prefetchPendingIdleGroups done",{reason:n,preferredGroups:e,orderedGroups:s,summary:r}),r}async function Eo(){var t;if($e()){y("prefetchDefaultIdleGroups skipped: disabled in development");return}const n=await gt();if(!n){an("default-groups:manifest-missing",Ce),y("prefetchDefaultIdleGroups skipped: manifest missing",{retryDelayMs:Ce,lastFailureReason:ge});return}const e=(t=n==null?void 0:n.defaults)==null?void 0:t.filter(s=>typeof s=="string"&&s.length>0);if(!e||e.length===0){y("prefetchDefaultIdleGroups skipped: no default groups");return}await wt("default-groups",e)}async function To(){if($e()){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: disabled in development");return}const n=Date.now();let e=0,t=null;for(;;){if(!t){const a=await gt();if(!a){const i=Date.now()-n;y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: manifest unavailable",{elapsedMs:i,lastFailureReason:ge});return}if(t=gs(a),t.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: no groups");return}}e+=1;const s=await bs(t);if(s.completedGroups.length>0&&await on(),s.pendingGroups.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady complete",{orderedGroups:t,iteration:e,elapsedMs:Date.now()-n});return}const r=Date.now()-n;if(r>=no)throw new Error(`idle-prefetch incomplete after ${r}ms: pending groups ${s.pendingGroups.join(", ")}`);const o=Math.max(250,s.nextRetryDelayMs??(s.queuedEntries>0?sn:1e3));y("prewarmAllIdlePrefetchGroupsForUpdateReady waiting next round",{orderedGroups:t,iteration:e,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,queuedEntries:s.queuedEntries,waitMs:o,elapsedMs:r}),await new Promise(a=>{setTimeout(a,o)})}}U.addEventListener("install",n=>{y("install event received",{version:C}),he=!!U.registration.active,ht=!he,he||U.skipWaiting(),Ee({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await Xr(),await Se(e=>({committedVersion:e.committedVersion||C,pendingVersion:he?C:null,pendingReadyAt:null,upgradeState:he?"prewarming":"idle"})),await de();try{const e=await oo();if(e&&e.length>0){const t=await caches.open(Re),s=await Co(t,e);if(he&&s.failCount>0)throw new Error(`precache incomplete: ${s.failCount}/${s.total} files failed`)}else xe&&Ee({phase:"development",percent:100,completed:0,total:0,failed:0,message:"开发模式下跳过静态预缓存"});he&&await To(),await Qr(he)}catch(e){await Se(t=>({committedVersion:t.committedVersion||C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await de(),Ee({phase:"error",message:`启动资源预热失败:${ae(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),U.addEventListener("activate",n=>{y("activate event received",{version:C}),Ee({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await Ge(),await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await de();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>Cr);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}ht?(y("activate: before clients.claim"),await U.clients.claim(),y("activate: after clients.claim")):y("activate: skip clients.claim for staged update"),setTimeout(()=>{y("activate: scheduling default idle prefetch"),pt("default-groups",async()=>Eo())},800);const e=O();e&&(e.sendSWActivated(C),y("activate: sent sw:activated broadcast")),Ee({phase:"activated",percent:100,message:"启动缓存服务已就绪"})})()),n.waitUntil(caches.keys().then(async e=>{const t=e.filter(i=>i.startsWith("drawnix-images-v")&&i!==L);if(t.length>0){const i=await caches.open(L);for(const c of t)try{const l=await caches.open(c),u=await l.keys();for(const g of u){const f=await l.match(g);f&&await i.put(g,f)}await caches.delete(c)}catch(l){console.warn(`Failed to migrate cache ${c}:`,l)}}const s=await Ge(),r=rs(s.committedVersion||C),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==Re&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==zt&&i!==L&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(Re);await Ao(i)}catch(i){console.warn("Failed to purge suspicious static cache entries:",i)}(o.length>0||a.length>0)&&setTimeout(async()=>{for(const i of[...o,...a])try{await caches.delete(i)}catch(c){console.warn("Failed to delete old cache:",i,c)}},3e4),Qn().catch(i=>{console.warn("Failed to cleanup expired console logs:",i)}),wn.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function Do(n){if(I){const e=O();e&&e.sendPostMessageLog(n)}}async function _o(n,e,t,s){if(xe)return null;try{const r=mt(e.url),o=await Gt(t,s,it.href.replace(/\/$/,""),{preferLocal:!1,requestKind:"interactive-runtime"});if(!(o!=null&&o.response.ok))return console.warn("[SW CDN] Static resource unavailable from all fallback sources",{requestUrl:e.url,resourcePath:t,appVersion:s,unavailableCDNs:us()}),null;const a=new URL(e.url);if(Ve(e,a,o.response))return null;const i=await cn(n,r.cacheKey,o.response,{source:o.source,revision:"runtime",fetchTarget:o.targetUrl,appVersion:s});return r.cacheKey!==e.url&&y("tryFetchStaticResourceFromCDN: cached under normalized key",{requestUrl:e.url,normalizedCacheKey:r.cacheKey,resourcePath:t,source:o.source,fetchTarget:o.targetUrl}),i}catch(r){return console.warn("[SW CDN] CDN fallback failed:",r),null}}function Ro(n){const e=n.headers.get($t)||void 0,t=n.headers.get(Un)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function ws(n,e,t=C){const s=e.headers.get($t),r=e.headers.get(Vt),o=e.headers.get(Kt);if(!s||!r||!o){const i=new URL(n.url);return!(e.ok&&!Ve(n,i,e))}if(o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr"&&s!=="unpkg")return!0;const a=new URL(n.url);return Ve(n,a,e)}async function Ao(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&ws(t,s)&&await n.delete(t)}catch(s){console.warn("Service Worker: Failed to inspect static cache entry:",s)}}U.addEventListener("message",n=>{var a,i,c,l,u,g,f,b,h,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=((g=n.source)==null?void 0:g.url)||"",r=((f=n.data)==null?void 0:f.cmdname)||((b=n.data)==null?void 0:b.requestId)&&((h=n.data)==null?void 0:h.ret)!==void 0;let o="";if(_t()&&!r&&(o=Rt(e,n.data,t,s,(p=n.data)==null?void 0:p.__internal__),o&&I)){const m=Ye().find(S=>S.id===o);m&&Do(m)}if(n.data&&n.data.type==="GENERATE_THUMBNAIL"){const{url:d,mediaType:m,blob:S,mimeType:E}=n.data;if(d&&m&&S){const A=new Blob([S],{type:E||(m==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:j}=await Promise.resolve().then(()=>q);j(A,d,m)})()}return}if(n.data&&n.data.type==="SW_CDN_SET_PREFERENCE"){n.waitUntil(In({cdn:n.data.cdn,latency:n.data.latency,timestamp:n.data.timestamp,version:n.data.version}));return}if(n.data&&n.data.type==="SW_BOOT_PROGRESS_GET"){const d=n.source;y("message: SW_BOOT_PROGRESS_GET",{clientId:(d==null?void 0:d.id)??null}),hs(d);return}if(n.data&&n.data.type==="GET_VERSION_STATE"){const d=n.source;y("message: GET_VERSION_STATE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil(de(d));return}if(n.data&&n.data.type==="SW_IDLE_PREFETCH_STATUS_GET"){const d=n.source;y("message: SW_IDLE_PREFETCH_STATUS_GET",{clientId:(d==null?void 0:d.id)??null}),on(d);return}if(n.data&&n.data.type==="SW_PREFETCH_GROUPS"){const d=Array.isArray(n.data.groups)?n.data.groups.filter(m=>typeof m=="string"):[];y("message: SW_PREFETCH_GROUPS",{groups:d}),n.waitUntil(pt(`message:${d.join(",")||"empty"}`,async()=>{await wt(`message:${d.join(",")||"empty"}`,d)}));return}if(n.data&&(n.data.type==="COMMIT_UPGRADE"||n.data.type==="SKIP_WAITING")){const d=n.source;y("message: COMMIT_UPGRADE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil((async()=>{ht=!0,await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(d),U.skipWaiting();const m=O();m&&m.sendSWUpdated(C)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{ht=!0,await Se({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await de(n.source),U.skipWaiting();const d=O();d&&d.sendSWUpdated(C)})());else if(n.data&&n.data.type==="DELETE_CACHE"){const{url:d}=n.data;d&&un(d).then(()=>{const m=O();m&&m.sendCacheDeleted(d)}).catch(m=>{console.error("Service Worker: Failed to delete cache:",m)})}else if(n.data&&n.data.type==="DELETE_CACHE_BATCH"){const{urls:d}=n.data;d&&Array.isArray(d)&&Io(d).then(()=>{}).catch(m=>{console.error("Service Worker: Failed to batch delete caches:",m)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")ko().then(()=>{}).catch(d=>{console.error("Service Worker: Failed to clear all cache:",d)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){I=!0,Be(!0),tt(!0),ne.log("Service Worker: Debug mode enabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_ENABLED"});const d=O();d&&d.sendDebugStatusChanged(!0)}else if(n.data&&n.data.type==="SW_DEBUG_DISABLE"){I=!1,Be(!1),tt(!1),J.length=0,K.length=0,ne.log("Service Worker: Debug mode disabled"),n.source&&n.source.postMessage({type:"SW_DEBUG_DISABLED"});const d=O();d&&d.sendDebugStatusChanged(!1)}if(n.data&&n.data.type==="SW_DEBUG_GET_LLM_API_LOGS"){(async()=>{try{const{getAllLLMApiLogs:d}=await Promise.resolve().then(()=>De),m=await d(),S=n.source;S&&S.postMessage({type:"SW_DEBUG_LLM_API_LOGS",logs:m})}catch(d){console.error("[SW] Failed to get LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_CLEAR_LLM_API_LOGS"){(async()=>{try{const{clearAllLLMApiLogs:d}=await Promise.resolve().then(()=>De);await d();const m=n.source;m&&m.postMessage({type:"SW_DEBUG_LLM_API_LOGS_CLEARED"})}catch(d){console.error("[SW] Failed to clear LLM API logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_STATUS"){const d=n.source;d&&d.postMessage({type:"SW_DEBUG_STATUS",debugModeEnabled:I,swVersion:C,logs:K.slice(-100),consoleLogs:J.slice(-100)});return}if(n.data&&n.data.type==="SW_DEBUG_GET_LOGS"){(async()=>{try{const{getInternalFetchLogs:d}=await Promise.resolve().then(()=>gr),m=Zt(),S=d(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...m,...S.map(A=>({...A,type:"fetch"}))]})}catch(d){console.error("[SW] Failed to get fetch logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_CONSOLE_LOGS"){(async()=>{try{const d=n.source;d&&d.postMessage({type:"SW_DEBUG_CONSOLE_LOGS",logs:J})}catch(d){console.error("[SW] Failed to get console logs:",d)}})();return}if(n.data&&n.data.type==="SW_DEBUG_GET_POSTMESSAGE_LOGS"){(async()=>{try{const d=Ye(),m=n.source;m&&m.postMessage({type:"SW_DEBUG_POSTMESSAGE_LOGS",logs:d})}catch(d){console.error("[SW] Failed to get postmessage logs:",d)}})();return}});const Lo="MemorySnapshotDB",fe="snapshots",ys=50;async function ln(){return new Promise((n,e)=>{const t=indexedDB.open(Lo,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(fe)){const o=r.createObjectStore(fe,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function Ss(n){try{const e=await ln(),t=e.transaction(fe,"readwrite"),s=t.objectStore(fe);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>ys){const i=s.index("timestamp").openCursor();let c=0;const l=o-ys;i.onsuccess=u=>{const g=u.target.result;g&&c<l&&(s.delete(g.value.id),c++,g.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 Cs(){try{const n=await ln(),s=n.transaction(fe,"readonly").objectStore(fe).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 Es(){try{const n=await ln(),e=n.transaction(fe,"readwrite");e.objectStore(fe).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 vo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function Mo(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function Po(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 g of r){const f=u.objectStore(g),b=f.count();b.onsuccess=()=>{const h=b.result;if(o+=h,h>0){const p=f.openCursor();let d=0;p.onsuccess=m=>{const S=m.target.result;if(S&&d<l)a+=Mo(S.value),i++,d++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,A=Math.round(E*o);e({count:o,totalSize:A})}},p.onerror=()=>{if(c++,c===r.length){s.close();const m=i>0?a/i:0,S=Math.round(m*o);e({count:o,totalSize:S})}}}else c++,c===r.length&&(s.close(),e({count:o,totalSize:0}))},b.onerror=()=>{if(c++,c===r.length){s.close();const h=i>0?a/i:0,p=Math.round(h*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 Ts(){const n={},e=[zt,L,Re,ct];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 vo)try{const s=await Po(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function un(n){try{await(await caches.open(L)).delete(n)}catch(e){throw console.error("Service Worker: Failed to delete cache entry:",n,e),e}}async function Io(n){try{const e=await caches.open(L);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 ko(){try{const n=await caches.open(L),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 Ds(n,e,t){try{const s=O();s&&s.sendCacheImageCached(n,e)}catch(s){console.warn("Service Worker: Failed to notify image cached:",s)}}async function Oo(){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=O();r&&r.sendCacheQuotaWarning(e,t,s)}}}catch(n){console.warn("Service Worker: Failed to check storage quota:",n)}}const re=new Map,_s=300*1e3,Rs=500;function Wo(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 Bo(n){const e=re.get(n);return e?Date.now()-e>_s?(re.delete(n),!1):!0:!1}function As(n){if(Wo(n)){if(re.size>=Rs){const e=Date.now();for(const[t,s]of re)e-s>_s&&re.delete(t);if(re.size>=Rs){const t=Array.from(re.entries());t.sort((r,o)=>r[1]-o[1]);const s=t.slice(0,Math.floor(t.length/2));for(const[r]of s)re.delete(r)}}re.set(n,Date.now())}}U.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(Fe=t,go(n,e)){const s=`${e.pathname}${e.search}`;y("fetch: enqueue idle prefetch recheck",{clientId:n.clientId,requestUrl:s}),n.waitUntil(pt(`fetch-recheck:${s}`,async()=>{await wt(`fetch:${s}`)}))}if(e.pathname.startsWith(qn)||e.pathname.startsWith(jn)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(No(n.request).then(r=>(v(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw v(s,{error:String(r),duration:Date.now()-t}),r}));return}if(e.pathname.startsWith(Mr)){const s=k({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Go(n.request).then(r=>(v(s,{status:r.status,statusText:r.statusText,responseType:r.type,duration:Date.now()-t,cached:r.status===200}),r)).catch(r=>{throw v(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(xr(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&&zr(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(Fo(n.request).then(a=>(v(o,{status:a.status,statusText:a.statusText,responseType:a.type,duration:Date.now()-s,cached:a.headers.has(se),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 v(o,{error:String(a),duration:Date.now()-s}),a}));return}if(jr(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(Uo(n.request).then(a=>(v(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 v(o,{error:String(a),duration:Date.now()-s}),a}));return}if($r(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(xo(n.request).then(o=>(v(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 v(r,{error:String(o),duration:Date.now()-s}),o}));return}if(e.origin!==location.origin&&qr(e,n.request)){if(Bo(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(zo(n.request).then(o=>(o.status===404&&As(n.request.url),v(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 As(n.request.url),v(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(Ho(n.request).then(i=>{const c=Ro(i);return v(a,{status:i.status,statusText:i.statusText,responseType:i.type,duration:Date.now()-o,resourceSource:c.resourceSource,resourceFetchTarget:c.resourceFetchTarget,details:s?"Navigation request":[`Static resource (${n.request.destination})`,c.resourceSource?`来源: ${c.resourceSource}`:null,c.resourceFetchTarget?`实际拉取: ${c.resourceFetchTarget}`:null].filter(Boolean).join(`
|
|
2
|
+
`)}),i}).catch(i=>{throw v(a,{error:String(i),duration:Date.now()-o}),i}));return}}if(I){if(Vr(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((g,f)=>{a[f]=g}),["POST","PUT","PATCH"].includes(n.request.method))try{const g=n.request.headers.get("content-type")||"";g.includes("application/json")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):g.includes("application/x-www-form-urlencoded")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):o=`[${g||"binary data"}]`}catch{o="[unable to read body]"}v(s,{headers:a,details:o?`XHR/API request (${n.request.method})
|
|
3
3
|
|
|
4
4
|
Request Body:
|
|
5
|
-
${o}`:`XHR/API request (${n.request.method})`});const i=await fetch(n.request),c=i.clone();let l;const u={};i.headers.forEach((
|
|
5
|
+
${o}`:`XHR/API request (${n.request.method})`});const i=await fetch(n.request),c=i.clone();let l;const u={};i.headers.forEach((g,f)=>{u[f]=g});try{const g=i.headers.get("content-type")||"";g.includes("application/json")||g.includes("text/")?(l=await c.text(),l.length>5e3&&(l=l.substring(0,5e3)+"... (truncated)")):l=`[${g||"binary data"}] (${i.headers.get("content-length")||"unknown"} bytes)`}catch{l="[unable to read response body]"}return v(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})
|
|
6
6
|
|
|
7
7
|
Request Body:
|
|
8
8
|
${o}
|
|
@@ -11,7 +11,7 @@ Response Body:
|
|
|
11
11
|
${l}`:`XHR/API request (${n.request.method})
|
|
12
12
|
|
|
13
13
|
Response Body:
|
|
14
|
-
${l}`}),i}catch(r){throw v(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function Io(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(ot),s=await t.match(n);if(s)return s;const r=await fetch(n);if(r&&r.status===200){const o=r.clone(),a=new Headers(o.headers),i=Date.now().toString();a.set(ne,i),a.set(be,i);const c=new Response(o.body,{status:o.status,statusText:o.statusText,headers:a});t.put(n,c).catch(l=>{console.warn(`Service Worker [Font-${e}]: 缓存字体失败:`,l)})}return r}catch(t){console.error(`Service Worker [Font-${e}]: 字体请求失败:`,t);const r=await(await caches.open(ot)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function an(n,e={}){return fetch(n,e)}async function ko(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname.includes("/audio/")||zt.test(t.pathname),o=t.pathname.includes("/video/")||/\.(mp4|webm|mov)$/i.test(t.pathname),a=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),c=t.searchParams.has("thumbnail")&&!a&&!i;if(c){const l=t.searchParams.get("thumbnail")||"small",u=new URL(t.toString());u.searchParams.delete("thumbnail"),u.searchParams.delete("bypass_sw"),u.searchParams.delete("direct_fetch"),u.searchParams.delete("_retry");const{findThumbnailWithFallback:h,createThumbnailResponse:f}=await Promise.resolve().then(()=>H),p=await h(u.toString(),l,[t.pathname]);if(p){const g=await p.response.blob();return f(g)}}try{const l=await caches.open(L);let u=await l.match(n.url);if(u||(u=await l.match(t.pathname)),u){const h=await u.blob();if(c&&!o){const{generateThumbnailAsync:f}=await Promise.resolve().then(()=>H);f(h,t.pathname,"image")}return o?Pe(h,s,e):r?$e(h,s,e):new Response(h,{status:200,statusText:"OK",headers:{"Content-Type":h.type||"image/png","Content-Length":h.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error("Service Worker: Media not found in cache:",{fullUrl:n.url,pathname:t.pathname}),new Response("Media not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(l){return console.error("Service Worker: Error handling cache URL request:",l),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Oo(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname,o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),a=t.searchParams.has("_retry"),i=t.searchParams.has("thumbnail")&&!o&&!a;if(i){const c=t.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:l,createThumbnailResponse:u}=await Promise.resolve().then(()=>H),h=await l(r,c,[r]);if(h){const f=await h.response.blob();return u(f)}}try{const l=await(await caches.open(L)).match(r);if(l){const u=await l.blob(),h=t.pathname.match(/\.(mp4|webm|mov)$/i),f=zt.test(t.pathname);if(i&&!h){const{generateThumbnailAsync:p}=await Promise.resolve().then(()=>H);p(u,r,"image")}return h&&s?Pe(u,s,e):f?$e(u,s,e):new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":u.type||"application/octet-stream","Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error(`Service Worker [Asset-${e}]: Asset not found in cache:`,r),new Response("Asset not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error(`Service Worker [Asset-${e}]: Error handling asset library request:`,c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Wo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10),s=n.headers.get("range"),o=$t(e).toString();try{const a=await caches.open(L);let i=await a.match(o);if(!i&&o!==n.url&&(i=await a.match(n.url)),i)try{const g=await i.clone().blob();return $e(g,s,t)}catch{return i}const c=new Headers(n.headers);c.delete("range");const l=await fetch(o,{method:"GET",headers:c,mode:n.mode,credentials:n.credentials,cache:"no-store",referrerPolicy:n.referrerPolicy||"no-referrer"});if(!l.ok)return l;if(l.type==="opaque")return a.put(o,l.clone()).catch(g=>{console.warn(`Service Worker [Audio-${t}]: Failed to cache opaque audio response:`,g)}),l;const u=await l.blob(),h=l.headers.get("Content-Type")||u.type||"audio/mpeg",f=Date.now().toString(),p=new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":h,"Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length",[ne]:f,[be]:f,"sw-image-size":u.size.toString()}});return await a.put(o,p.clone()),$e(u,s,t,h)}catch(a){console.error(`Service Worker [Audio-${t}]: Audio loading failed:`,a);const i=await caches.open(L);let c=await i.match(o);if(!c&&o!==n.url&&(c=await i.match(n.url)),c)try{const l=await c.clone().blob();return $e(l,s,t)}catch{return c}return new Response("Audio loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const mt=Symbol("VIDEO_LOAD_ERROR");async function Bo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10);try{const s=n.headers.get("range"),r=e.searchParams.has("bypass_sw")||e.searchParams.has("direct_fetch"),o=e.searchParams.has("_retry"),a=e.searchParams.has("thumbnail")&&!r&&!o,i=$t(e),c=i.toString();if(a){const f=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:p,createThumbnailResponse:g}=await Promise.resolve().then(()=>H),m=await p(c,f);if(m){const d=await m.response.blob();return g(d)}return(async()=>{try{const{generateThumbnailAsync:d}=await Promise.resolve().then(()=>H);d(new Blob([],{type:"video/mp4"}),c,"video",[f])}catch{return}})(),new Response("Thumbnail not ready",{status:404,statusText:"Thumbnail Not Ready",headers:{"Content-Type":"text/plain","Cache-Control":"no-store"}})}const l=Be.get(c);if(l){l.count=(l.count||1)+1;const f=await l.promise;if(f===mt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(f===null){const p={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,p)}return Pe(f,s,t)}if(U.has(c)){const f=U.get(c);if(f)return f.timestamp=Date.now(),Pe(f.blob,s,t)}try{const p=await(await caches.open(L)).match(c);if(p){const g=await p.blob();return g.size/(1024*1024)<50&&U.set(c,{blob:g,timestamp:Date.now()}),Pe(g,s,t)}}catch{}const u=(async()=>{try{const f={method:"GET",mode:"cors",credentials:"omit",cache:"default"},p=new URL(i),g=await fetch(p,f);if(!g.ok)return mt;if(g.status===206)return null;const m=await g.blob();if(m.size/(1024*1024)<50){U.set(c,{blob:m,timestamp:Date.now()});try{const b=await caches.open(L),S=new Response(m,{headers:{"Content-Type":m.type||"video/mp4","Content-Length":m.size.toString(),[ne]:Date.now().toString(),[be]:Date.now().toString(),"sw-video-size":m.size.toString()}});await b.put(c,S);const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>H);E(m,c,"video")}catch{}}return m}catch{return mt}})();Be.set(c,{promise:u,timestamp:Date.now(),count:1,requestId:t}),u.finally(()=>{Be.get(c)&&Be.delete(c)});const h=await u;if(h===mt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(h===null){const f={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,f)}return Pe(h,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function Pe(n,e,t){return Ds(n,e,t,n.type||"video/mp4")}function $e(n,e,t,s){return Ds(n,e,t,s||n.type||"audio/mpeg")}function Ds(n,e,t,s){const r=n.size;if(!e)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Content-Length":r.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}});const o=e.match(/bytes=(\d+)-(\d*)/);if(!o)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Accept-Ranges":"bytes"}});const a=parseInt(o[1],10),i=o[2]?parseInt(o[2],10):r-1,c=n.slice(a,i+1),l=i-a+1;return new Response(c,{status:206,statusText:"Partial Content",headers:{"Content-Type":s,"Content-Range":`bytes ${a}-${i}/${r}`,"Content-Length":l.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}})}async function xo(n){const e=new URL(n.url),t=gt(n.url),s=t.cacheKey,r=yr(n.mode,e.pathname),a=(await xe()).committedVersion||C,i=es(a),c=await caches.open(i);if(We)try{const p=await an(n);if(p&&p.status===200&&n.url.startsWith("http"))return c.put(n,p.clone()),p;if(!p.ok){let g=await c.match(n);return!g&&r&&(g=await c.match("/"),g||(g=await c.match("/index.html"))),g||p}return p}catch{let g=await c.match(n);return!g&&r&&(g=await c.match("/"),g||(g=await c.match("/index.html"))),g||(r?_s():new Response("Resource unavailable",{status:503}))}if(r){let p=await c.match(n);if(p||(p=await c.match("/")),p||(p=await c.match("/index.html")),!p){const g=await caches.keys();for(const m of g)if(m.startsWith("drawnix-static-v"))try{const d=await caches.open(m);if(p=await d.match(n)||await d.match("/")||await d.match("/index.html"),p)break}catch{}}if(p)return p;try{const g=await an(n,{cache:"reload"});if(g&&g.status===200&&n.url.startsWith("http")&&a===C){c.put(n,g.clone());const m=new URL(n.url);if(Sr(m.pathname)){const d=new URL("/",m.origin).href,b=new URL("/index.html",m.origin).href;n.url!==d&&c.put(d,g.clone()),n.url!==b&&c.put(b,g.clone())}return g}return g}catch{return _s()}}const{response:l,matchedBy:u}=await fo(c,n);if(l){if(!fs(n,l,a))return u==="normalized"&&y("handleStaticRequest: normalized static cache hit",{requestUrl:n.url,normalizedCacheKey:s}),l;await po(c,n,s)}const h=t.resourcePath;if(ds(n,e)){n.url!==s&&y("handleStaticRequest: cross-origin static cache miss",{requestUrl:n.url,normalizedCacheKey:s,resourcePath:h,committedVersion:a});const p=await ft(n,[s]);if(p)return p;const g=await go(n,[s]);if(g)return g;const m=kn(e.pathname),d=m||a,b=await So(c,n,h,d);return b||(is("smart-cdn-resource-failed",n,{resourcePath:h,committedVersion:a,hasEmbeddedVersion:!!m,attemptedVersion:d}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const p=await an(n);if(ze(n,e,p)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const m=await ft(n,[s]);return m||new Response("Resource not found",{status:404,statusText:"Not Found"})}if(p&&p.status===200&&n.url.startsWith("http")&&a===C)return await sn(c,n,p,{source:"server",revision:"runtime",appVersion:a});if(p.status>=400){const m=await ft(n,[s]);if(m)return m}return p}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const g=await ft(n,[s]);return g||(is("origin-fetch-exception",n,{resourcePath:h,committedVersion:a}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}}function _s(){return new Response(`<!DOCTYPE html>
|
|
14
|
+
${l}`}),i}catch(r){throw v(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function xo(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(ct),s=await t.match(n);if(s)return s;const r=await fetch(n);if(r&&r.status===200){const o=r.clone(),a=new Headers(o.headers),i=Date.now().toString();a.set(se,i),a.set(we,i);const c=new Response(o.body,{status:o.status,statusText:o.statusText,headers:a});t.put(n,c).catch(l=>{console.warn(`Service Worker [Font-${e}]: 缓存字体失败:`,l)})}return r}catch(t){console.error(`Service Worker [Font-${e}]: 字体请求失败:`,t);const r=await(await caches.open(ct)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function dn(n,e={}){return fetch(n,e)}async function No(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname.includes("/audio/")||Xt.test(t.pathname),o=t.pathname.includes("/video/")||/\.(mp4|webm|mov)$/i.test(t.pathname),a=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),i=t.searchParams.has("_retry"),c=t.searchParams.has("thumbnail")&&!a&&!i;if(c){const l=t.searchParams.get("thumbnail")||"small",u=new URL(t.toString());u.searchParams.delete("thumbnail"),u.searchParams.delete("bypass_sw"),u.searchParams.delete("direct_fetch"),u.searchParams.delete("_retry");const{findThumbnailWithFallback:g,createThumbnailResponse:f}=await Promise.resolve().then(()=>q),b=await g(u.toString(),l,[t.pathname]);if(b){const h=await b.response.blob();return f(h)}}try{const l=await caches.open(L);let u=await l.match(n.url);if(u||(u=await l.match(t.pathname)),u){const g=await u.blob();if(c&&!o){const{generateThumbnailAsync:f}=await Promise.resolve().then(()=>q);f(g,t.pathname,"image")}return o?ke(g,s,e):r?Ke(g,s,e):new Response(g,{status:200,statusText:"OK",headers:{"Content-Type":g.type||"image/png","Content-Length":g.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error("Service Worker: Media not found in cache:",{fullUrl:n.url,pathname:t.pathname}),new Response("Media not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(l){return console.error("Service Worker: Error handling cache URL request:",l),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Go(n){const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=n.headers.get("range"),r=t.pathname,o=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),a=t.searchParams.has("_retry"),i=t.searchParams.has("thumbnail")&&!o&&!a;if(i){const c=t.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:l,createThumbnailResponse:u}=await Promise.resolve().then(()=>q),g=await l(r,c,[r]);if(g){const f=await g.response.blob();return u(f)}}try{const l=await(await caches.open(L)).match(r);if(l){const u=await l.blob(),g=t.pathname.match(/\.(mp4|webm|mov)$/i),f=Xt.test(t.pathname);if(i&&!g){const{generateThumbnailAsync:b}=await Promise.resolve().then(()=>q);b(u,r,"image")}return g&&s?ke(u,s,e):f?Ke(u,s,e):new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":u.type||"application/octet-stream","Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}return console.error(`Service Worker [Asset-${e}]: Asset not found in cache:`,r),new Response("Asset not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain"}})}catch(c){return console.error(`Service Worker [Asset-${e}]: Error handling asset library request:`,c),new Response("Internal error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}async function Fo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10),s=n.headers.get("range"),o=Yt(e).toString();try{const a=await caches.open(L);let i=await a.match(o);if(!i&&o!==n.url&&(i=await a.match(n.url)),i)try{const h=await i.clone().blob();return Ke(h,s,t)}catch{return i}const c=new Headers(n.headers);c.delete("range");const l=await fetch(o,{method:"GET",headers:c,mode:n.mode,credentials:n.credentials,cache:"no-store",referrerPolicy:n.referrerPolicy||"no-referrer"});if(!l.ok)return l;if(l.type==="opaque")return a.put(o,l.clone()).catch(h=>{console.warn(`Service Worker [Audio-${t}]: Failed to cache opaque audio response:`,h)}),l;const u=await l.blob(),g=l.headers.get("Content-Type")||u.type||"audio/mpeg",f=Date.now().toString(),b=new Response(u,{status:200,statusText:"OK",headers:{"Content-Type":g,"Content-Length":u.size.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length",[se]:f,[we]:f,"sw-image-size":u.size.toString()}});return await a.put(o,b.clone()),Ke(u,s,t,g)}catch(a){console.error(`Service Worker [Audio-${t}]: Audio loading failed:`,a);const i=await caches.open(L);let c=await i.match(o);if(!c&&o!==n.url&&(c=await i.match(n.url)),c)try{const l=await c.clone().blob();return Ke(l,s,t)}catch{return c}return new Response("Audio loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const yt=Symbol("VIDEO_LOAD_ERROR");async function Uo(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10);try{const s=n.headers.get("range"),r=e.searchParams.has("bypass_sw")||e.searchParams.has("direct_fetch"),o=e.searchParams.has("_retry"),a=e.searchParams.has("thumbnail")&&!r&&!o,i=Yt(e),c=i.toString();if(a){const f=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:b,createThumbnailResponse:h}=await Promise.resolve().then(()=>q),p=await b(c,f);if(p){const d=await p.response.blob();return h(d)}return(async()=>{try{const{generateThumbnailAsync:d}=await Promise.resolve().then(()=>q);d(new Blob([],{type:"video/mp4"}),c,"video",[f])}catch{return}})(),new Response("Thumbnail not ready",{status:404,statusText:"Thumbnail Not Ready",headers:{"Content-Type":"text/plain","Cache-Control":"no-store"}})}const l=Ne.get(c);if(l){l.count=(l.count||1)+1;const f=await l.promise;if(f===yt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(f===null){const b={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,b)}return ke(f,s,t)}if(H.has(c)){const f=H.get(c);if(f)return f.timestamp=Date.now(),ke(f.blob,s,t)}try{const b=await(await caches.open(L)).match(c);if(b){const h=await b.blob();return h.size/(1024*1024)<50&&H.set(c,{blob:h,timestamp:Date.now()}),ke(h,s,t)}}catch{}const u=(async()=>{try{const f={method:"GET",mode:"cors",credentials:"omit",cache:"default"},b=new URL(i),h=await fetch(b,f);if(!h.ok)return yt;if(h.status===206)return null;const p=await h.blob();if(p.size/(1024*1024)<50){H.set(c,{blob:p,timestamp:Date.now()});try{const m=await caches.open(L),S=new Response(p,{headers:{"Content-Type":p.type||"video/mp4","Content-Length":p.size.toString(),[se]:Date.now().toString(),[we]:Date.now().toString(),"sw-video-size":p.size.toString()}});await m.put(c,S);const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(p,c,"video")}catch{}}return p}catch{return yt}})();Ne.set(c,{promise:u,timestamp:Date.now(),count:1,requestId:t}),u.finally(()=>{Ne.get(c)&&Ne.delete(c)});const g=await u;if(g===yt)return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}});if(g===null){const f={method:"GET",headers:new Headers(n.headers),mode:"cors",credentials:"omit"};return await fetch(e,f)}return ke(g,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function ke(n,e,t){return Ls(n,e,t,n.type||"video/mp4")}function Ke(n,e,t,s){return Ls(n,e,t,s||n.type||"audio/mpeg")}function Ls(n,e,t,s){const r=n.size;if(!e)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Content-Length":r.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}});const o=e.match(/bytes=(\d+)-(\d*)/);if(!o)return new Response(n,{status:200,statusText:"OK",headers:{"Content-Type":s,"Accept-Ranges":"bytes"}});const a=parseInt(o[1],10),i=o[2]?parseInt(o[2],10):r-1,c=n.slice(a,i+1),l=i-a+1;return new Response(c,{status:206,statusText:"Partial Content",headers:{"Content-Type":s,"Content-Range":`bytes ${a}-${i}/${r}`,"Content-Length":l.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Content-Range, Accept-Ranges, Content-Length"}})}async function Ho(n){const e=new URL(n.url),t=mt(n.url),s=t.cacheKey,r=ve(e.pathname),o=Tr(n.mode,r),i=(await Ge()).committedVersion||C,c=rs(i),l=await caches.open(c);if(xe)try{const h=await dn(n);if(h&&h.status===200&&n.url.startsWith("http"))return l.put(n,h.clone()),h;if(!h.ok){let p=await l.match(n);return!p&&o&&(p=await l.match(B("/").href),p||(p=await l.match(B("index.html").href))),p||h}return h}catch{let p=await l.match(n);return!p&&o&&(p=await l.match(B("/").href),p||(p=await l.match(B("index.html").href))),p||(o?vs():new Response("Resource unavailable",{status:503}))}if(o){let h=await l.match(n);if(h||(h=await l.match(B("/").href)),h||(h=await l.match(B("index.html").href)),!h){const p=await caches.keys();for(const d of p)if(d.startsWith("drawnix-static-v"))try{const m=await caches.open(d);if(h=await m.match(n)||await m.match(B("/").href)||await m.match(B("index.html").href),h)break}catch{}}if(h)return h;try{const p=await dn(n,{cache:"reload"});if(p&&p.status===200&&n.url.startsWith("http")&&i===C){l.put(n,p.clone());const d=new URL(n.url);if(Dr(ve(d.pathname))){const m=B("/").href,S=B("index.html").href;n.url!==m&&l.put(m,p.clone()),n.url!==S&&l.put(S,p.clone())}return p}return p}catch{return vs()}}const{response:u,matchedBy:g}=await yo(l,n);if(u){if(!ws(n,u,i))return g==="normalized"&&y("handleStaticRequest: normalized static cache hit",{requestUrl:n.url,normalizedCacheKey:s}),u;await So(l,n,s)}const f=t.resourcePath;if(ps(n,e)){n.url!==s&&y("handleStaticRequest: cross-origin static cache miss",{requestUrl:n.url,normalizedCacheKey:s,resourcePath:f,committedVersion:i});const h=await bt(n,[s]);if(h)return h;const p=await wo(n,[s]);if(p)return p;const d=xn(e.pathname),m=d||i,S=await _o(l,n,f,m);return S||(ds("smart-cdn-resource-failed",n,{resourcePath:f,committedVersion:i,hasEmbeddedVersion:!!d,attemptedVersion:m}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const h=await dn(n);if(Ve(n,e,h)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const d=await bt(n,[s]);return d||new Response("Resource not found",{status:404,statusText:"Not Found"})}if(h&&h.status===200&&n.url.startsWith("http")&&i===C)return await cn(l,n,h,{source:"server",revision:"runtime",appVersion:i});if(h.status>=400){const d=await bt(n,[s]);if(d)return d}return h}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const p=await bt(n,[s]);return p||(ds("origin-fetch-exception",n,{resourcePath:f,committedVersion:i}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}}function vs(){return new Response(`<!DOCTYPE html>
|
|
15
15
|
<html lang="zh-CN">
|
|
16
16
|
<head>
|
|
17
17
|
<meta charset="UTF-8">
|
|
@@ -52,4 +52,4 @@ ${l}`}),i}catch(r){throw v(s,{error:String(r),duration:Date.now()-t}),r}})());re
|
|
|
52
52
|
<p>Opentu 是一个以画布工作区为底座的 AI 应用平台,当前无法访问时请检查网络或稍后再试。</p>
|
|
53
53
|
<button onclick="location.reload()">重试</button>
|
|
54
54
|
</body>
|
|
55
|
-
</html>`,{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}const cn=15e3,Rs=3e4;function As(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function No(){const n=Date.now(),e=[];if(U.forEach((t,s)=>{n-t.timestamp>Pr&&e.push(s)}),e.length>0&&e.forEach(t=>U.delete(t)),U.size>Hn){const t=Array.from(U.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=U.size-Hn,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>U.delete(o))}}function Go(){const n=Date.now(),e=[];j.forEach((s,r)=>{n-s.timestamp>Rs&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>j.delete(s)));const t=[];we.forEach((s,r)=>{n-s.timestamp>Un&&t.push(r)}),t.length>0&&t.forEach(s=>we.delete(s)),No()}async function Fo(n){try{const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),r=t.searchParams.has("_retry"),o=t.searchParams.has("thumbnail")&&!s&&!r,a=o&&t.searchParams.get("thumbnail")||"small",i=$t(t),c=new Request(i.toString(),{method:n.method,headers:n.headers,mode:n.mode,credentials:n.credentials}),l=i.toString();if(o){const{findThumbnailWithFallback:f,createThumbnailResponse:p}=await Promise.resolve().then(()=>H),g=await f(l,a,[n.url,c.url]);if(g){const m=await g.response.blob();return p(m)}}const u=we.get(l);if(u){if(Date.now()-u.timestamp<Un)return u.response.clone();we.delete(l)}if(j.has(l)){const f=j.get(l);if(f){const p=Date.now()-f.timestamp;if(p>Rs)console.warn(`Service Worker [${e}]: 发现过期的 pending 请求 (${p}ms),清理并重新发起:`,l),j.delete(l);else{f.count=(f.count||1)+1,f.duplicateRequestIds=f.duplicateRequestIds||[],f.duplicateRequestIds.push(e);try{const g=await As(f.promise,cn,"Image request timeout");return g&&g.clone?g.clone():g}catch(g){if(g.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),j.delete(l),Ls(n.url,e);throw g}}}}Go();const h=Uo(c,n.url,l,e,s,o?a:void 0);j.set(l,{promise:h,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),h.then(f=>{f&&f.ok&&we.set(l,{response:f.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{j.get(l)&&j.delete(l)});try{return await As(h,cn,"Image request timeout")}catch(f){if(f.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${cn}ms),清理并返回超时响应让前端直接加载:`,n.url),j.delete(l),Ls(n.url,e);throw f}}catch(e){throw e}}function Ls(n,e){return new Response("Image request timeout - use direct load",{status:504,statusText:"Gateway Timeout",headers:{"Content-Type":"text/plain","X-SW-Timeout":"true","X-SW-Original-URL":n,"Access-Control-Allow-Origin":"*"}})}async function Uo(n,e,t,s,r=!1,o){try{const a=await caches.open(L);if(!r){let m=await a.match(n);if(m||(m=await a.match(n.url)),!m&&e!==n.url&&(m=await a.match(e)),m||(m=await a.match(t)),m){const b=await m.clone().blob();if(b.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await a.delete(n);else{if(o){const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>H);E(b,n.url,"image")}const S=m.headers.get(ne);if(S){const E=Date.now(),A=m.headers.get(be)||S,q=new Response(b,{status:m.status,statusText:m.statusText,headers:{...Object.fromEntries(m.headers.entries()),[ne]:E.toString(),[be]:A}});return n.url.startsWith("http")&&(await a.put(t,q.clone()),e!==t&&await a.delete(e)),q}else{const E=new Response(b,{status:m.status,statusText:m.statusText,headers:{...Object.fromEntries(m.headers.entries()),[ne]:Date.now().toString(),[be]:Date.now().toString()}});return n.url.startsWith("http")&&(await a.put(t,E.clone()),e!==t&&await a.delete(e)),E}}}}const i=new URL(e),c=Zn(i);let l=null,u=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),Le.has(c.hostname)&&(u=!0));let h;const f=[{method:"GET",mode:"cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"},{method:"GET",cache:"no-cache"},{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"}];let p;u?p=[l]:(p=[e],l&&p.push(l));let g=null;for(let m=0;m<p.length;m++){const d=p[m],b=m>0;for(const S of f)try{let E,A=!1;for(let q=0;q<=2;q++)try{if(h=await fetch(d,S),h&&(h.status!==0||h.type==="opaque"))break}catch(re){E=re;const Ie=re.message||"";if(Ie.includes("CORS")||Ie.includes("cross-origin")||Ie.includes("Access-Control-Allow-Origin")||Ie.includes("Failed to fetch")||Ie.includes("NetworkError")||Ie.includes("TypeError")){A=!0;break}q<2&&await new Promise(oa=>setTimeout(oa,Math.pow(2,q)*1e3))}if(A){const q=new URL(d).hostname;qn(q);try{const re=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(re.type==="opaque")return re}catch(re){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,re)}return new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(h&&(h.status!==0||h.type==="opaque"))break;E&&(g=E)}catch(E){g=E;continue}if(h&&(h.status!==0||h.type==="opaque"))break;c&&c.fallbackDomain&&m===0&&!u&&(Le.add(c.hostname),$r(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!h||h.status===0&&h.type!=="opaque"){let m="All fetch attempts failed";return c&&c.fallbackDomain&&(u?m=`备用域名${c.fallbackDomain}也失败了`:m=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${m}`,g),new Response("Image load failed after all attempts",{status:404,statusText:"Image Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*"}})}if(h.type==="opaque"){const m=new URL(e).hostname;return qn(m),h}if(h.ok){const d=await h.clone().blob(),b=d.size/(1024*1024),S=new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":h.headers.get("Content-Type")||"image/png","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*","Cache-Control":"max-age=3153600000",[ne]:Date.now().toString(),[be]:Date.now().toString(),"sw-image-size":d.size.toString()}});try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Ss(t,d.size,d.type),await vo();const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>H);E(d,t,"image")}}catch(E){console.warn(`Service Worker: Failed to cache normal response (${b.toFixed(2)}MB, 可能超出存储限制):`,E),await Kr(a);try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Ss(t,d.size,d.type);const{generateThumbnailAsync:A}=await Promise.resolve().then(()=>H);A(d,t,"image")}}catch(A){console.error("Service Worker: Still failed to cache after cleanup:",A)}}return S}throw new Error(`HTTP ${h.status}: ${h.statusText}`)}catch(a){const i=new URL(e);return a.message.includes("SSL_PROTOCOL_ERROR")||a.message.includes("ERR_SSL_PROTOCOL_ERROR")||a.message.includes("net::ERR_CERT")||a.message.includes("ERR_INSECURE_RESPONSE")?(console.warn("Service Worker: 检测到SSL/证书错误,尝试跳过Service Worker处理"),fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit"}).catch(()=>new Response("SSL Error - Image not accessible",{status:404,statusText:"SSL Protocol Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}))):i.pathname.match(/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i)||i.searchParams.has("_t")||i.searchParams.has("cache_buster")||i.searchParams.has("timestamp")?new Response("Image not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}):new Response(`Network Error: ${a.message}`,{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})}}const R=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:C,IMAGE_CACHE_NAME:L,addConsoleLog:Kt,clearAllConsoleLogs:Kn,clearConsoleLogs:Jn,clearCrashSnapshots:ws,clearDebugLogs:Qn,deleteCacheByUrl:on,disableDebugMode:Qt,enableDebugMode:Yt,getCDNStatusReport:nt,getCacheStats:ys,getCrashSnapshots:bs,getDebugLogs:Xt,getDebugStatus:Yn,getInternalFetchLogs:Lt,loadConsoleLogsFromDB:$n,performHealthCheck:xt,resetCDNStatus:Nt,saveCrashSnapshot:ms},Symbol.toStringTag,{value:"Module"})),bt="drawnix-images-thumb",vs=128,ln=400,Ho=.8;function qo(n,e,t){const s=n/e;let r=t,o=t;return s>1?o=t/s:r=t*s,{width:Math.round(r),height:Math.round(o)}}function un(n,e){try{let t;try{t=new URL(n)}catch{t=new URL(n,self.location.origin)}return t.searchParams.delete("thumbnail"),t.searchParams.set("_thumb",e),t.toString()}catch{const t=n.includes("?")?"&":"?";return`${n.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/,"")}${t}_thumb=${e}`}}async function Ms(n,e,t=["small","large"]){try{for(const s of t)await jo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function jo(n,e,t){try{const s=t==="large"?ln:vs,r=un(e,t),o=await caches.open(bt);let a=await o.match(r);if(!a){const d=new Request(r,{method:"GET"});a=await o.match(d)}if(!a)try{const d=new URL(r);a=await o.match(d.pathname)}catch{}if(a||n.size===0)return;const i=(n.type||"").toLowerCase();if(!i.startsWith("image/")&&i!=="")return;let c;try{c=await createImageBitmap(n)}catch(d){if(d instanceof Error&&d.name==="InvalidStateError")return;throw d}const{width:l,height:u}=qo(c.width,c.height,s),h=new OffscreenCanvas(l,u),f=h.getContext("2d");if(!f){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{f.drawImage(c,0,0,l,u)}finally{c.close()}const p=await h.convertToBlob({type:"image/jpeg",quality:Ho}),g=()=>new Response(p,{headers:{"Content-Type":"image/jpeg","Content-Length":p.size.toString()}}),m=new Request(r,{method:"GET"});await o.put(m,g()),await o.put(r,g());try{const d=new URL(r);(d.pathname.startsWith("/__aitu_cache__/")||d.pathname.startsWith("/asset-library/"))&&await o.put(r,g())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Ps(n,e,t=["small","large"]){try{for(const s of t)await zo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function zo(n,e,t){try{const s=un(e,t),r=await caches.open(bt);let o=await r.match(s);if(!o){const u=new Request(s,{method:"GET"});o=await r.match(u)}if(!o)try{const u=new URL(s);o=await r.match(u.pathname)}catch{}if(o)return;const i=await $o(e,n,t==="large"?ln:vs);if(!i){console.warn(`[ThumbnailUtils] Failed to generate ${t} video thumbnail from main thread`);return}const c=()=>new Response(i,{headers:{"Content-Type":"image/jpeg","Content-Length":i.size.toString()}}),l=new Request(s,{method:"GET"});await r.put(l,c()),await r.put(s,c());try{const u=new URL(s);(u.pathname.startsWith("/__aitu_cache__/")||u.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function $o(n,e,t=ln){const{getChannelManager:s}=await Promise.resolve().then(()=>ir),r=s();if(!r||r.getConnectedClientCount()===0)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const o=await r.requestVideoThumbnail(n,3e4,t);if(!o)return null;try{return await(await fetch(o)).blob()}catch(a){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",a),null}}async function dn(n,e,t){try{const s=await caches.open(bt),r=un(n,e);let o=await s.match(r);if(!o){const a=new Request(r,{method:"GET"});o=await s.match(a)}if(!o&&t)for(const a of t){const i=await s.match(a);if(i){o=i;break}}return o||null}catch(s){return console.warn("[ThumbnailUtils] Error finding thumbnail:",s),null}}async function Vo(n,e,t){let s=await dn(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await dn(n,r,t),s?{response:s,size:r}:null}function Ko(n){return new Response(n,{status:200,headers:{"Content-Type":"image/jpeg","Content-Length":n.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}function Xo(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await Ms(n,e,s):await Ps(n,e,s)}catch(r){console.warn(`[ThumbnailUtils] Failed to generate ${t} thumbnail:`,r)}})()}const H=Object.freeze(Object.defineProperty({__proto__:null,IMAGE_CACHE_NAME_THUMB:bt,createThumbnailResponse:Ko,findThumbnail:dn,findThumbnailWithFallback:Vo,generateImageThumbnail:Ms,generateThumbnailAsync:Xo,generateVideoThumbnail:Ps},Symbol.toStringTag,{value:"Module"})),fe=[],Yo="llm-api-logs",Qo=4,K="logs";function wt(){return new Promise((n,e)=>{const t=indexedDB.open(Yo,Qo);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result,o=s.oldVersion;let a;if(!r.objectStoreNames.contains(K))a=r.createObjectStore(K,{keyPath:"id"}),a.createIndex("timestamp","timestamp",{unique:!1}),a.createIndex("taskType","taskType",{unique:!1}),a.createIndex("status","status",{unique:!1}),a.createIndex("taskId","taskId",{unique:!1});else{const i=s.target.transaction;i&&(a=i.objectStore(K),o<4&&!a.indexNames.contains("taskId")&&(a.createIndex("taskId","taskId",{unique:!1}),console.log("[LLMApiLogger] Created taskId index during upgrade to v4")))}}})}async function Is(){try{const s=(await wt()).transaction(K,"readonly").objectStore(K).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{const i=a.result.reverse();r(i)},a.onerror=()=>{o(a.error)}})}catch(n){return console.warn("[LLMApiLogger] Failed to get logs from DB:",n),fe}}function Jo(n){return{id:n.id,timestamp:n.timestamp,endpoint:n.endpoint,model:n.model,taskType:n.taskType,taskId:n.taskId,prompt:n.prompt?n.prompt.length>200?n.prompt.substring(0,200)+"...":n.prompt:void 0,status:n.status,httpStatus:n.httpStatus,duration:n.duration,errorMessage:n.errorMessage,hasReferenceImages:n.hasReferenceImages,referenceImageCount:n.referenceImageCount,resultType:n.resultType,resultCount:n.resultCount,resultUrl:n.resultUrl}}function Zo(n,e){if(!e)return!0;const t=n.taskType==="audio"&&(n.resultType==="lyrics"||/\/lyrics(?:\/|$)/i.test(n.endpoint||""));return e==="lyrics"?t:e==="audio"?n.taskType==="audio"&&!t:n.taskType===e}async function ea(n=1,e=20,t){let s=await Is();t!=null&&t.taskType&&(s=s.filter(c=>Zo(c,t.taskType))),t!=null&&t.status&&(s=s.filter(c=>c.status===t.status));const r=s.length,o=Math.ceil(r/e),a=(n-1)*e;return{logs:s.slice(a,a+e).map(Jo),total:r,page:n,pageSize:e,totalPages:o}}async function ta(n){const e=fe.find(t=>t.id===n);if(e)return e;try{const r=(await wt()).transaction(K,"readonly").objectStore(K);return new Promise((o,a)=>{const i=r.get(n);i.onsuccess=()=>{o(i.result||null)},i.onerror=()=>{a(i.error)}})}catch(t){return console.warn("[LLMApiLogger] Failed to get log by id:",t),null}}async function na(){fe.length=0;try{const e=(await wt()).transaction(K,"readwrite");e.objectStore(K).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{s()},e.onerror=()=>{r(e.error)}})}catch(n){console.warn("[LLMApiLogger] Failed to clear logs from DB:",n)}}async function sa(n){if(!n||n.length===0)return 0;const e=new Set(n),t=fe.length;for(let r=fe.length-1;r>=0;r--)e.has(fe[r].id)&&fe.splice(r,1);const s=t-fe.length;try{const o=(await wt()).transaction(K,"readwrite"),a=o.objectStore(K);for(const i of n)a.delete(i);await new Promise((i,c)=>{o.oncomplete=()=>{i()},o.onerror=()=>{c(o.error)}})}catch(r){console.warn("[LLMApiLogger] Failed to delete logs from DB:",r)}return s}function ra(n){}const Te=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:na,deleteLLMApiLogs:sa,getAllLLMApiLogs:Is,getLLMApiLogById:ta,getLLMApiLogsPaginated:ea,setLLMApiLogBroadcast:ra},Symbol.toStringTag,{value:"Module"}));return D.APP_VERSION=C,D.IMAGE_CACHE_NAME=L,D.addConsoleLog=Kt,D.clearAllConsoleLogs=Kn,D.clearConsoleLogs=Jn,D.clearCrashSnapshots=ws,D.clearDebugLogs=Qn,D.deleteCacheByUrl=on,D.disableDebugMode=Qt,D.enableDebugMode=Yt,D.getCDNStatusReport=nt,D.getCacheStats=ys,D.getCrashSnapshots=bs,D.getDebugLogs=Xt,D.getDebugStatus=Yn,D.getInternalFetchLogs=Lt,D.loadConsoleLogsFromDB=$n,D.performHealthCheck=xt,D.resetCDNStatus=Nt,D.saveCrashSnapshot=ms,Object.defineProperty(D,Symbol.toStringTag,{value:"Module"}),D})({});
|
|
55
|
+
</html>`,{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}const hn=15e3,Ms=3e4;function Ps(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function qo(){const n=Date.now(),e=[];if(H.forEach((t,s)=>{n-t.timestamp>Wr&&e.push(s)}),e.length>0&&e.forEach(t=>H.delete(t)),H.size>$n){const t=Array.from(H.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=H.size-$n,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>H.delete(o))}}function jo(){const n=Date.now(),e=[];z.forEach((s,r)=>{n-s.timestamp>Ms&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>z.delete(s)));const t=[];ye.forEach((s,r)=>{n-s.timestamp>zn&&t.push(r)}),t.length>0&&t.forEach(s=>ye.delete(s)),qo()}async function zo(n){try{const e=Math.random().toString(36).substring(2,10),t=new URL(n.url),s=t.searchParams.has("bypass_sw")||t.searchParams.has("direct_fetch"),r=t.searchParams.has("_retry"),o=t.searchParams.has("thumbnail")&&!s&&!r,a=o&&t.searchParams.get("thumbnail")||"small",i=Yt(t),c=new Request(i.toString(),{method:n.method,headers:n.headers,mode:n.mode,credentials:n.credentials}),l=i.toString();if(o){const{findThumbnailWithFallback:f,createThumbnailResponse:b}=await Promise.resolve().then(()=>q),h=await f(l,a,[n.url,c.url]);if(h){const p=await h.response.blob();return b(p)}}const u=ye.get(l);if(u){if(Date.now()-u.timestamp<zn)return u.response.clone();ye.delete(l)}if(z.has(l)){const f=z.get(l);if(f){const b=Date.now()-f.timestamp;if(b>Ms)console.warn(`Service Worker [${e}]: 发现过期的 pending 请求 (${b}ms),清理并重新发起:`,l),z.delete(l);else{f.count=(f.count||1)+1,f.duplicateRequestIds=f.duplicateRequestIds||[],f.duplicateRequestIds.push(e);try{const h=await Ps(f.promise,hn,"Image request timeout");return h&&h.clone?h.clone():h}catch(h){if(h.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),z.delete(l),Is(n.url,e);throw h}}}}jo();const g=$o(c,n.url,l,e,s,o?a:void 0);z.set(l,{promise:g,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),g.then(f=>{f&&f.ok&&ye.set(l,{response:f.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{z.get(l)&&z.delete(l)});try{return await Ps(g,hn,"Image request timeout")}catch(f){if(f.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${hn}ms),清理并返回超时响应让前端直接加载:`,n.url),z.delete(l),Is(n.url,e);throw f}}catch(e){throw e}}function Is(n,e){return new Response("Image request timeout - use direct load",{status:504,statusText:"Gateway Timeout",headers:{"Content-Type":"text/plain","X-SW-Timeout":"true","X-SW-Original-URL":n,"Access-Control-Allow-Origin":"*"}})}async function $o(n,e,t,s,r=!1,o){try{const a=await caches.open(L);if(!r){let p=await a.match(n);if(p||(p=await a.match(n.url)),!p&&e!==n.url&&(p=await a.match(e)),p||(p=await a.match(t)),p){const m=await p.clone().blob();if(m.size===0)console.warn(`Service Worker [${s}]: 检测到空缓存,删除并重新获取:`,e),await a.delete(n);else{if(o){const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(m,n.url,"image")}const S=p.headers.get(se);if(S){const E=Date.now(),A=p.headers.get(we)||S,j=new Response(m,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),[se]:E.toString(),[we]:A}});return n.url.startsWith("http")&&(await a.put(t,j.clone()),e!==t&&await a.delete(e)),j}else{const E=new Response(m,{status:p.status,statusText:p.statusText,headers:{...Object.fromEntries(p.headers.entries()),[se]:Date.now().toString(),[we]:Date.now().toString()}});return n.url.startsWith("http")&&(await a.put(t,E.clone()),e!==t&&await a.delete(e)),E}}}}const i=new URL(e),c=ss(i);let l=null,u=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),Me.has(c.hostname)&&(u=!0));let g;const f=[{method:"GET",mode:"cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"},{method:"GET",cache:"no-cache"},{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit",referrerPolicy:"no-referrer"}];let b;u?b=[l]:(b=[e],l&&b.push(l));let h=null;for(let p=0;p<b.length;p++){const d=b[p],m=p>0;for(const S of f)try{let E,A=!1;for(let j=0;j<=2;j++)try{if(g=await fetch(d,S),g&&(g.status!==0||g.type==="opaque"))break}catch(oe){E=oe;const Oe=oe.message||"";if(Oe.includes("CORS")||Oe.includes("cross-origin")||Oe.includes("Access-Control-Allow-Origin")||Oe.includes("Failed to fetch")||Oe.includes("NetworkError")||Oe.includes("TypeError")){A=!0;break}j<2&&await new Promise(ua=>setTimeout(ua,Math.pow(2,j)*1e3))}if(A){const j=new URL(d).hostname;Vn(j);try{const oe=await fetch(e,{mode:"no-cors",credentials:"omit",referrerPolicy:"no-referrer"});if(oe.type==="opaque")return oe}catch(oe){console.warn(`Service Worker [${s}]: no-cors 模式也失败:`,oe)}return new Response(null,{status:200,headers:{"Content-Type":"image/png","X-SW-CORS-Bypass":"true"}})}if(g&&(g.status!==0||g.type==="opaque"))break;E&&(h=E)}catch(E){h=E;continue}if(g&&(g.status!==0||g.type==="opaque"))break;c&&c.fallbackDomain&&p===0&&!u&&(Me.add(c.hostname),Yr(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!g||g.status===0&&g.type!=="opaque"){let p="All fetch attempts failed";return c&&c.fallbackDomain&&(u?p=`备用域名${c.fallbackDomain}也失败了`:p=`All fetch attempts failed for both ${c.hostname} and ${c.fallbackDomain} domains`),console.error(`Service Worker [${s}]: ${p}`,h),new Response("Image load failed after all attempts",{status:404,statusText:"Image Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*"}})}if(g.type==="opaque"){const p=new URL(e).hostname;return Vn(p),g}if(g.ok){const d=await g.clone().blob(),m=d.size/(1024*1024),S=new Response(d,{status:200,statusText:"OK",headers:{"Content-Type":g.headers.get("Content-Type")||"image/png","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"*","Cache-Control":"max-age=3153600000",[se]:Date.now().toString(),[we]:Date.now().toString(),"sw-image-size":d.size.toString()}});try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Ds(t,d.size,d.type),await Oo();const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(d,t,"image")}}catch(E){console.warn(`Service Worker: Failed to cache normal response (${m.toFixed(2)}MB, 可能超出存储限制):`,E),await Jr(a);try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await Ds(t,d.size,d.type);const{generateThumbnailAsync:A}=await Promise.resolve().then(()=>q);A(d,t,"image")}}catch(A){console.error("Service Worker: Still failed to cache after cleanup:",A)}}return S}throw new Error(`HTTP ${g.status}: ${g.statusText}`)}catch(a){const i=new URL(e);return a.message.includes("SSL_PROTOCOL_ERROR")||a.message.includes("ERR_SSL_PROTOCOL_ERROR")||a.message.includes("net::ERR_CERT")||a.message.includes("ERR_INSECURE_RESPONSE")?(console.warn("Service Worker: 检测到SSL/证书错误,尝试跳过Service Worker处理"),fetch(e,{method:"GET",mode:"no-cors",cache:"no-cache",credentials:"omit"}).catch(()=>new Response("SSL Error - Image not accessible",{status:404,statusText:"SSL Protocol Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}))):i.pathname.match(/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i)||i.searchParams.has("_t")||i.searchParams.has("cache_buster")||i.searchParams.has("timestamp")?new Response("Image not found",{status:404,statusText:"Not Found",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}}):new Response(`Network Error: ${a.message}`,{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}})}}const R=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:C,IMAGE_CACHE_NAME:L,addConsoleLog:Jt,clearAllConsoleLogs:Jn,clearConsoleLogs:ns,clearCrashSnapshots:Es,clearDebugLogs:ts,deleteCacheByUrl:un,disableDebugMode:tn,enableDebugMode:en,getCDNStatusReport:rt,getCacheStats:Ts,getCrashSnapshots:Cs,getDebugLogs:Zt,getDebugStatus:es,getInternalFetchLogs:Pt,loadConsoleLogsFromDB:Yn,performHealthCheck:Ft,resetCDNStatus:Ut,saveCrashSnapshot:Ss},Symbol.toStringTag,{value:"Module"})),St="drawnix-images-thumb",ks=128,gn=400,Vo=.8;function Ko(n,e,t){const s=n/e;let r=t,o=t;return s>1?o=t/s:r=t*s,{width:Math.round(r),height:Math.round(o)}}function fn(n,e){try{let t;try{t=new URL(n)}catch{t=new URL(n,self.location.origin)}return t.searchParams.delete("thumbnail"),t.searchParams.set("_thumb",e),t.toString()}catch{const t=n.includes("?")?"&":"?";return`${n.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/,"")}${t}_thumb=${e}`}}async function Os(n,e,t=["small","large"]){try{for(const s of t)await Xo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Xo(n,e,t){try{const s=t==="large"?gn:ks,r=fn(e,t),o=await caches.open(St);let a=await o.match(r);if(!a){const d=new Request(r,{method:"GET"});a=await o.match(d)}if(!a)try{const d=new URL(r);a=await o.match(d.pathname)}catch{}if(a||n.size===0)return;const i=(n.type||"").toLowerCase();if(!i.startsWith("image/")&&i!=="")return;let c;try{c=await createImageBitmap(n)}catch(d){if(d instanceof Error&&d.name==="InvalidStateError")return;throw d}const{width:l,height:u}=Ko(c.width,c.height,s),g=new OffscreenCanvas(l,u),f=g.getContext("2d");if(!f){console.warn("[ThumbnailUtils] Failed to get canvas context");return}try{f.drawImage(c,0,0,l,u)}finally{c.close()}const b=await g.convertToBlob({type:"image/jpeg",quality:Vo}),h=()=>new Response(b,{headers:{"Content-Type":"image/jpeg","Content-Length":b.size.toString()}}),p=new Request(r,{method:"GET"});await o.put(p,h()),await o.put(r,h());try{const d=new URL(r);(d.pathname.startsWith("/__aitu_cache__/")||d.pathname.startsWith("/asset-library/"))&&await o.put(r,h())}catch{}}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Ws(n,e,t=["small","large"]){try{for(const s of t)await Yo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function Yo(n,e,t){try{const s=fn(e,t),r=await caches.open(St);let o=await r.match(s);if(!o){const u=new Request(s,{method:"GET"});o=await r.match(u)}if(!o)try{const u=new URL(s);o=await r.match(u.pathname)}catch{}if(o)return;const i=await Qo(e,n,t==="large"?gn:ks);if(!i){console.warn(`[ThumbnailUtils] Failed to generate ${t} video thumbnail from main thread`);return}const c=()=>new Response(i,{headers:{"Content-Type":"image/jpeg","Content-Length":i.size.toString()}}),l=new Request(s,{method:"GET"});await r.put(l,c()),await r.put(s,c());try{const u=new URL(s);(u.pathname.startsWith("/__aitu_cache__/")||u.pathname.startsWith("/asset-library/"))&&await r.put(s,c())}catch{}}catch(s){console.warn(`[ThumbnailUtils] ❌ Failed to generate ${t} video thumbnail:`,s)}}async function Qo(n,e,t=gn){const{getChannelManager:s}=await Promise.resolve().then(()=>dr),r=s();if(!r||r.getConnectedClientCount()===0)return console.warn("[ThumbnailUtils] No connected clients for video thumbnail generation"),null;const o=await r.requestVideoThumbnail(n,3e4,t);if(!o)return null;try{return await(await fetch(o)).blob()}catch(a){return console.warn("[ThumbnailUtils] Failed to convert thumbnail URL to blob:",a),null}}async function pn(n,e,t){try{const s=await caches.open(St),r=fn(n,e);let o=await s.match(r);if(!o){const a=new Request(r,{method:"GET"});o=await s.match(a)}if(!o&&t)for(const a of t){const i=await s.match(a);if(i){o=i;break}}return o||null}catch(s){return console.warn("[ThumbnailUtils] Error finding thumbnail:",s),null}}async function Jo(n,e,t){let s=await pn(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await pn(n,r,t),s?{response:s,size:r}:null}function Zo(n){return new Response(n,{status:200,headers:{"Content-Type":"image/jpeg","Content-Length":n.size.toString(),"Access-Control-Allow-Origin":"*","Cache-Control":"max-age=31536000"}})}function ea(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await Os(n,e,s):await Ws(n,e,s)}catch(r){console.warn(`[ThumbnailUtils] Failed to generate ${t} thumbnail:`,r)}})()}const q=Object.freeze(Object.defineProperty({__proto__:null,IMAGE_CACHE_NAME_THUMB:St,createThumbnailResponse:Zo,findThumbnail:pn,findThumbnailWithFallback:Jo,generateImageThumbnail:Os,generateThumbnailAsync:ea,generateVideoThumbnail:Ws},Symbol.toStringTag,{value:"Module"})),pe=[],ta="llm-api-logs",na=4,X="logs";function Ct(){return new Promise((n,e)=>{const t=indexedDB.open(ta,na);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result,o=s.oldVersion;let a;if(!r.objectStoreNames.contains(X))a=r.createObjectStore(X,{keyPath:"id"}),a.createIndex("timestamp","timestamp",{unique:!1}),a.createIndex("taskType","taskType",{unique:!1}),a.createIndex("status","status",{unique:!1}),a.createIndex("taskId","taskId",{unique:!1});else{const i=s.target.transaction;i&&(a=i.objectStore(X),o<4&&!a.indexNames.contains("taskId")&&(a.createIndex("taskId","taskId",{unique:!1}),console.log("[LLMApiLogger] Created taskId index during upgrade to v4")))}}})}async function Bs(){try{const s=(await Ct()).transaction(X,"readonly").objectStore(X).index("timestamp");return new Promise((r,o)=>{const a=s.getAll();a.onsuccess=()=>{const i=a.result.reverse();r(i)},a.onerror=()=>{o(a.error)}})}catch(n){return console.warn("[LLMApiLogger] Failed to get logs from DB:",n),pe}}function sa(n){return{id:n.id,timestamp:n.timestamp,endpoint:n.endpoint,model:n.model,taskType:n.taskType,taskId:n.taskId,prompt:n.prompt?n.prompt.length>200?n.prompt.substring(0,200)+"...":n.prompt:void 0,status:n.status,httpStatus:n.httpStatus,duration:n.duration,errorMessage:n.errorMessage,hasReferenceImages:n.hasReferenceImages,referenceImageCount:n.referenceImageCount,resultType:n.resultType,resultCount:n.resultCount,resultUrl:n.resultUrl}}function ra(n,e){if(!e)return!0;const t=n.taskType==="audio"&&(n.resultType==="lyrics"||/\/lyrics(?:\/|$)/i.test(n.endpoint||""));return e==="lyrics"?t:e==="audio"?n.taskType==="audio"&&!t:n.taskType===e}async function oa(n=1,e=20,t){let s=await Bs();t!=null&&t.taskType&&(s=s.filter(c=>ra(c,t.taskType))),t!=null&&t.status&&(s=s.filter(c=>c.status===t.status));const r=s.length,o=Math.ceil(r/e),a=(n-1)*e;return{logs:s.slice(a,a+e).map(sa),total:r,page:n,pageSize:e,totalPages:o}}async function aa(n){const e=pe.find(t=>t.id===n);if(e)return e;try{const r=(await Ct()).transaction(X,"readonly").objectStore(X);return new Promise((o,a)=>{const i=r.get(n);i.onsuccess=()=>{o(i.result||null)},i.onerror=()=>{a(i.error)}})}catch(t){return console.warn("[LLMApiLogger] Failed to get log by id:",t),null}}async function ia(){pe.length=0;try{const e=(await Ct()).transaction(X,"readwrite");e.objectStore(X).clear(),await new Promise((s,r)=>{e.oncomplete=()=>{s()},e.onerror=()=>{r(e.error)}})}catch(n){console.warn("[LLMApiLogger] Failed to clear logs from DB:",n)}}async function ca(n){if(!n||n.length===0)return 0;const e=new Set(n),t=pe.length;for(let r=pe.length-1;r>=0;r--)e.has(pe[r].id)&&pe.splice(r,1);const s=t-pe.length;try{const o=(await Ct()).transaction(X,"readwrite"),a=o.objectStore(X);for(const i of n)a.delete(i);await new Promise((i,c)=>{o.oncomplete=()=>{i()},o.onerror=()=>{c(o.error)}})}catch(r){console.warn("[LLMApiLogger] Failed to delete logs from DB:",r)}return s}function la(n){}const De=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:ia,deleteLLMApiLogs:ca,getAllLLMApiLogs:Bs,getLLMApiLogById:aa,getLLMApiLogsPaginated:oa,setLLMApiLogBroadcast:la},Symbol.toStringTag,{value:"Module"}));return D.APP_VERSION=C,D.IMAGE_CACHE_NAME=L,D.addConsoleLog=Jt,D.clearAllConsoleLogs=Jn,D.clearConsoleLogs=ns,D.clearCrashSnapshots=Es,D.clearDebugLogs=ts,D.deleteCacheByUrl=un,D.disableDebugMode=tn,D.enableDebugMode=en,D.getCDNStatusReport=rt,D.getCacheStats=Ts,D.getCrashSnapshots=Cs,D.getDebugLogs=Zt,D.getDebugStatus=es,D.getInternalFetchLogs=Pt,D.loadConsoleLogsFromDB=Yn,D.performHealthCheck=Ft,D.resetCDNStatus=Ut,D.saveCrashSnapshot=Ss,Object.defineProperty(D,Symbol.toStringTag,{value:"Module"}),D})({});
|