aitu-app 0.6.71 → 0.6.72
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-BxZowfRq.js → CanvasAudioPlayer-C4pqPNnG.js} +1 -1
- package/assets/{ChatDrawer-BGK5A7Rf.js → ChatDrawer-9XDg_01o.js} +2 -2
- package/assets/{ChatMessagesArea-CuPP1K-H.js → ChatMessagesArea-MrSlzXfd.js} +2 -2
- package/assets/{DeferredAIInputBar-jZEz3pqU.js → DeferredAIInputBar-rlzvr9H5.js} +2 -2
- package/assets/{DrawnixDeferredFeatures-DRggo5l2.js → DrawnixDeferredFeatures-6BN6HsXW.js} +1 -1
- package/assets/{KnowledgeBaseContent-C1xFBdX9.js → KnowledgeBaseContent-DJnJZh6i.js} +3 -3
- package/assets/{MVCreator-D3rDT4pv.js → MVCreator-BVXIEkng.js} +1 -1
- package/assets/{ModelBenchmarkWorkbench-DrHfXMOC.js → ModelBenchmarkWorkbench-DV6h0r-O.js} +1 -1
- package/assets/{ModelDropdown-CErXiJel.js → ModelDropdown-iU3c5Z_N.js} +1 -1
- package/assets/{MusicAnalyzer-DNVsOB04.js → MusicAnalyzer-D9rIcu4x.js} +1 -1
- package/assets/{MusicAnalyzer-q0eIxKqJ.js → MusicAnalyzer-ghn7zFIt.js} +1 -1
- package/assets/{ResizableDivider-XFJLfAwc.js → ResizableDivider-C6Z5EQJ_.js} +1 -1
- package/assets/{TaskQueuePanel-zmK3r_Sy.js → TaskQueuePanel-NAYUh8lN.js} +1 -1
- package/assets/{VideoAnalyzer-IiMRyspL.js → VideoAnalyzer-VjFOqpZU.js} +1 -1
- package/assets/{ai-generation-preferences-service-DheS7yb2.js → ai-generation-preferences-service-BuQhsO32.js} +1 -1
- package/assets/{arc-AunKa7Be.js → arc-CCorIawr.js} +1 -1
- package/assets/{arc-CxS0h6XE.js → arc-OsezXT79.js} +1 -1
- package/assets/{batch-image-generation-BTo-Hh2f.js → batch-image-generation-BM3dGGpo.js} +1 -1
- package/assets/{blockDiagram-38ab4fdb-BOwTTQqR.js → blockDiagram-38ab4fdb-DUFnN1Ei.js} +1 -1
- package/assets/{blockDiagram-38ab4fdb-B9BxtRcE.js → blockDiagram-38ab4fdb-DWGlT04d.js} +1 -1
- package/assets/{browser-CK6xKVG3.js → browser-BlDolpRT.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-l1vuEfws.js → c4Diagram-3d4e48cf-D4FViX2F.js} +1 -1
- package/assets/{c4Diagram-3d4e48cf-B7o3_NGM.js → c4Diagram-3d4e48cf-D6HbI2bj.js} +1 -1
- package/assets/{canvas-insertion-6qsJRfKC.js → canvas-insertion-BZAyMFnR.js} +1 -1
- package/assets/channel-DHHHwu9d.js +1 -0
- package/assets/channel-DbaY041U.js +1 -0
- package/assets/{classDiagram-70f12bd4-BxdM_ZFq.js → classDiagram-70f12bd4-BJiXLgfR.js} +1 -1
- package/assets/{classDiagram-70f12bd4-C5PI5m3K.js → classDiagram-70f12bd4-P5-MZZHm.js} +1 -1
- package/assets/{classDiagram-v2-f2320105-D2WGupMF.js → classDiagram-v2-f2320105-BckUVKrQ.js} +1 -1
- package/assets/{classDiagram-v2-f2320105-CRLBLeIT.js → classDiagram-v2-f2320105-BlMVbuKh.js} +1 -1
- package/assets/{clipper-D9tfnKC1.js → clipper-BkGBD2Ma.js} +1 -1
- package/assets/clone-B9352qPQ.js +1 -0
- package/assets/{createText-2e5e7dd3-B8mv8HgF.js → createText-2e5e7dd3-BLEzJgyq.js} +1 -1
- package/assets/{createText-2e5e7dd3-CWQBEaI7.js → createText-2e5e7dd3-_0asARpb.js} +1 -1
- package/assets/{edges-e0da2a9e-CW611sej.js → edges-e0da2a9e-BvNEeRN2.js} +1 -1
- package/assets/{edges-e0da2a9e-CiSIgajX.js → edges-e0da2a9e-Su9We6Oe.js} +1 -1
- package/assets/{erDiagram-9861fffd-B60hPtiy.js → erDiagram-9861fffd-B-TnweRY.js} +1 -1
- package/assets/{erDiagram-9861fffd-Bq-lh9QY.js → erDiagram-9861fffd-ChF_4VVA.js} +1 -1
- package/assets/{flowDb-956e92f1-Bz6i22S1.js → flowDb-956e92f1-BklqjU-F.js} +1 -1
- package/assets/{flowDb-956e92f1-CVT7Imrs.js → flowDb-956e92f1-CpHT5-s-.js} +1 -1
- package/assets/{flowDiagram-66a62f08-e10-kMn8.js → flowDiagram-66a62f08-BW0lq2iO.js} +1 -1
- package/assets/{flowDiagram-66a62f08-CRiWeGax.js → flowDiagram-66a62f08-CM-ufoRy.js} +1 -1
- package/assets/flowDiagram-v2-96b9c2cf-CXd4cAmC.js +1 -0
- package/assets/flowDiagram-v2-96b9c2cf-WaERXGrn.js +1 -0
- package/assets/{flowchart-elk-definition-4a651766-CBnyqo_M.js → flowchart-elk-definition-4a651766-BHXMQM8F.js} +1 -1
- package/assets/{flowchart-elk-definition-4a651766-DKGRcOAx.js → flowchart-elk-definition-4a651766-BNNCQnvT.js} +1 -1
- package/assets/{ganttDiagram-c361ad54-mhde3_of.js → ganttDiagram-c361ad54-BMznP5js.js} +1 -1
- package/assets/{ganttDiagram-c361ad54-D19CTSCa.js → ganttDiagram-c361ad54-Cn_w4SQu.js} +1 -1
- package/assets/{gitGraphDiagram-72cf32ee-BTRFRUeL.js → gitGraphDiagram-72cf32ee-CcqxYifa.js} +1 -1
- package/assets/{gitGraphDiagram-72cf32ee-BPmLlXIw.js → gitGraphDiagram-72cf32ee-HNSkomMm.js} +1 -1
- package/assets/{graph-DIg8rY1E.js → graph-2O9SKVX0.js} +1 -1
- package/assets/{graph-B1ieZuJT.js → graph-D24U5F9b.js} +1 -1
- package/assets/{index-3862675e-CAW4PMyX.js → index-3862675e-kPXP30L6.js} +1 -1
- package/assets/{index-3862675e-BFVjQZrI.js → index-3862675e-wtTLssRq.js} +1 -1
- package/assets/{index-o4MkHJtB.js → index-7Yy5taJZ.js} +1 -1
- package/assets/{index-D0pBPzvH.js → index-9lQYp-F3.js} +1 -1
- package/assets/{index-cFN27HDb.js → index-BCZHTjCF.js} +1 -1
- package/assets/{index-zNq6WR1M.js → index-BELf2XK1.js} +1 -1
- package/assets/{index-CAmlVCIf.js → index-BJiKHIU5.js} +1 -1
- package/assets/{index-sZWFW1o8.js → index-BfJrMjzE.js} +1 -1
- package/assets/{index-Dszi0QdY.js → index-BgTSdPjs.js} +1 -1
- package/assets/{index-A3FZLzj3.js → index-BnBH1zrC.js} +1 -1
- package/assets/{index-Byg7B0_b.js → index-BnuBC6-d.js} +1 -1
- package/assets/{index-DLYbtrPe.js → index-BvjfhvDI.js} +1 -1
- package/assets/{index-BVd4ZdJq.js → index-C66Oc7kp.js} +1 -1
- package/assets/{index-B5h3vVYf.js → index-C8BMcDy_.js} +1 -1
- package/assets/{index-O1yzWoAv.js → index-CD0uXSEJ.js} +1 -1
- package/assets/{index-Dsn0zIY5.js → index-CDI7kJJr.js} +1 -1
- package/assets/{index-Cxhc7DpJ.js → index-CHYWTMjD.js} +1 -1
- package/assets/{index-BnOaEPvW.js → index-CIR5517N.js} +1 -1
- package/assets/{index-DsQmr35F.js → index-CSh9cI-m.js} +1 -1
- package/assets/{index-sq_FndL-.js → index-Cdm1s3zH.js} +1 -1
- package/assets/{index-Cs7bP6R-.js → index-Ce_zjJd0.js} +1 -1
- package/assets/{index-DXVriIPX.js → index-Cf-6nhZx.js} +3 -3
- package/assets/{index-DCn6TEiD.js → index-CszzzzlU.js} +3 -3
- package/assets/{index-LfJyON59.js → index-D057A5AW.js} +1 -1
- package/assets/{index-BwMXzWpM.js → index-D0nupp1L.js} +1 -1
- package/assets/{index-BYfSEJIM.js → index-D5ni4ZMT.js} +2 -2
- package/assets/{index-BRccxBUA.js → index-DKZkufa4.js} +1 -1
- package/assets/{index-WDtJA1fY.js → index-Duz4qBVw.js} +1 -1
- package/assets/{index-Dtw21-1a.js → index-DxlqWfyM.js} +1 -1
- package/assets/{index-DUi1yiuN.js → index-DzSyiFE3.js} +1 -1
- package/assets/{index-Cgt6J1qz.js → index-ESZ1UttR.js} +1 -1
- package/assets/{index-CysE-UTz.js → index-oiyTGfuR.js} +1 -1
- package/assets/{index-u7vr_P_s.js → index-q9Vudaup.js} +1 -1
- package/assets/{index-C3HRC3b5.js → index-te4VWNfY.js} +1 -1
- package/assets/{infoDiagram-f8f76790-Dmv1egEN.js → infoDiagram-f8f76790-CQWNDm6d.js} +1 -1
- package/assets/{infoDiagram-f8f76790-C9LQ9jd5.js → infoDiagram-f8f76790-D4GOLEO3.js} +1 -1
- package/assets/{journeyDiagram-49397b02-8CnesQvB.js → journeyDiagram-49397b02-2ir0vod-.js} +1 -1
- package/assets/{journeyDiagram-49397b02-LV1k8ByA.js → journeyDiagram-49397b02-BIR-UXT9.js} +1 -1
- package/assets/{layout-3nkAix10.js → layout-CYzCl7YP.js} +1 -1
- package/assets/{layout-BW8C-Xw4.js → layout-Cjlcubqs.js} +1 -1
- package/assets/{line-DDWqaSCo.js → line-B6TatEZ8.js} +1 -1
- package/assets/{line-U1joDaO1.js → line-qfwz7WRO.js} +1 -1
- package/assets/{linear-D8frs5RT.js → linear-GuBoF0OP.js} +1 -1
- package/assets/{linear-3k1Xl9ve.js → linear-ssbBIRl5.js} +1 -1
- package/assets/{main-hjIskWwz.js → main-B6qbLicq.js} +8 -8
- package/assets/{mermaid.core-BlObAm7H.js → mermaid.core-DOJyKoHR.js} +3 -3
- package/assets/{mindmap-definition-fc14e90a-go-0aDNp.js → mindmap-definition-fc14e90a-BN4fqdNM.js} +1 -1
- package/assets/{mindmap-definition-fc14e90a-DRTqIBGi.js → mindmap-definition-fc14e90a-qPR072_x.js} +1 -1
- package/assets/{model-benchmark-launcher-Dhybe1Ps.js → model-benchmark-launcher-CUPxnAZr.js} +1 -1
- package/assets/{model-benchmark-service-BlgtfJ25.js → model-benchmark-service-C3taFBGp.js} +1 -1
- package/assets/{model-selection-C9DVcl8A.js → model-selection-Da4xzp54.js} +1 -1
- package/assets/{photo-wall-splitter-BSRMMrLk.js → photo-wall-splitter-DN8Hms8E.js} +1 -1
- package/assets/{pieDiagram-8a3498a8-OgnCNkdZ.js → pieDiagram-8a3498a8-6gjBTuiK.js} +1 -1
- package/assets/{pieDiagram-8a3498a8-DsU04FDA.js → pieDiagram-8a3498a8-B_B-oMBm.js} +1 -1
- package/assets/{quadrantDiagram-120e2f19-CAKix819.js → quadrantDiagram-120e2f19-CGIYsVeK.js} +1 -1
- package/assets/{quadrantDiagram-120e2f19-B-qdqCsc.js → quadrantDiagram-120e2f19-DQlP5fyR.js} +1 -1
- package/assets/{requirementDiagram-deff3bca-BFiAHorQ.js → requirementDiagram-deff3bca-BhadGJas.js} +1 -1
- package/assets/{requirementDiagram-deff3bca-DCvuwhP4.js → requirementDiagram-deff3bca-CZrZs6WH.js} +1 -1
- package/assets/{sankeyDiagram-04a897e0-CW0FxDIH.js → sankeyDiagram-04a897e0-CYbsYQIC.js} +1 -1
- package/assets/{sankeyDiagram-04a897e0-DynB_N5t.js → sankeyDiagram-04a897e0-DLMtKqV7.js} +1 -1
- package/assets/{sequenceDiagram-704730f1-C3kzvK6i.js → sequenceDiagram-704730f1-CnMi1-vV.js} +1 -1
- package/assets/{sequenceDiagram-704730f1-iLPkDpBi.js → sequenceDiagram-704730f1-D5_Tbq78.js} +1 -1
- package/assets/{settings-dialog-CcLfJFr_.js → settings-dialog-BVG80WDy.js} +1 -1
- package/assets/{skill-dsl-parser-DrFEUbDY.js → skill-dsl-parser-C252Shcy.js} +1 -1
- package/assets/{stateDiagram-587899a1-fLTDppNO.js → stateDiagram-587899a1-BStwFkNh.js} +1 -1
- package/assets/{stateDiagram-587899a1-DbwUO5DV.js → stateDiagram-587899a1-DYdXq59h.js} +1 -1
- package/assets/{stateDiagram-v2-d93cdb3a-DzR2PasK.js → stateDiagram-v2-d93cdb3a--y2o64Ew.js} +1 -1
- package/assets/{stateDiagram-v2-d93cdb3a-aZJTxhK8.js → stateDiagram-v2-d93cdb3a-IdPKDi36.js} +1 -1
- package/assets/{styles-6aaf32cf-C_VEAaHX.js → styles-6aaf32cf-4WFibVVF.js} +1 -1
- package/assets/{styles-6aaf32cf-C5JfMGYv.js → styles-6aaf32cf-Cm63YNOe.js} +1 -1
- package/assets/{styles-9a916d00-BYSJ54L0.js → styles-9a916d00-B49ieQxk.js} +1 -1
- package/assets/{styles-9a916d00-C3gY_lFJ.js → styles-9a916d00-D3LwlgPD.js} +1 -1
- package/assets/{styles-c10674c1-ANPmaoE9.js → styles-c10674c1-DJhcCs3x.js} +1 -1
- package/assets/{styles-c10674c1-DXxQEnvg.js → styles-c10674c1-cbwmIB4x.js} +1 -1
- package/assets/{svgDrawCommon-08f97a94-c2dOJxSO.js → svgDrawCommon-08f97a94-C5ek8a-c.js} +1 -1
- package/assets/{svgDrawCommon-08f97a94-BVjA84-b.js → svgDrawCommon-08f97a94-c77e0hhb.js} +1 -1
- package/assets/{timeline-definition-85554ec2-6QIdYNFS.js → timeline-definition-85554ec2-7ZMOJP7x.js} +1 -1
- package/assets/{timeline-definition-85554ec2-BST8-Dw9.js → timeline-definition-85554ec2-BIhOlyVe.js} +1 -1
- package/assets/{tool-windows-Bd5iqcJh.js → tool-windows-BTXOQvEU.js} +10 -10
- package/assets/{ttd-dialog-Chz4Dc5q.js → ttd-dialog-CMzq1PeM.js} +4 -4
- package/assets/{use-runtime-models-NPMCne8X.js → use-runtime-models-C_YMetmY.js} +1 -1
- package/assets/{useCharacters-Yt_yZunw.js → useCharacters-6F7LfBD2.js} +1 -1
- package/assets/{useWorkflowSubmission-DNz90nBd.js → useWorkflowSubmission-B-0oH5Q6.js} +2 -2
- package/assets/{video-analyze-cG43kQp7.js → video-analyze-gJnLIFVx.js} +1 -1
- package/assets/{video-generation-CY32Hcvy.js → video-generation-D0RudPQ8.js} +1 -1
- package/assets/{video-recovery-service-DqRVY2GL.js → video-recovery-service-CRZVLLWA.js} +1 -1
- package/assets/{workflow-generation-utils-CqQgPCFy.js → workflow-generation-utils-5aqKk8qR.js} +2 -2
- package/assets/{workflow-submission-service-C55NPNuz.js → workflow-submission-service-C9Ph3Y2w.js} +1 -1
- package/assets/{xychartDiagram-e933f94c-DY34Q03N.js → xychartDiagram-e933f94c-9bdjNrcG.js} +1 -1
- package/assets/{xychartDiagram-e933f94c-DD9JQg-b.js → xychartDiagram-e933f94c-D6a2PcvQ.js} +1 -1
- package/changelog.json +15 -0
- package/idle-prefetch-manifest.json +302 -302
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +6 -6
- package/sw.js +5 -5
- package/version.json +6 -3
- package/assets/channel-Dx9ePqRL.js +0 -1
- package/assets/channel-YfSSwDXj.js +0 -1
- package/assets/clone-DSiLnhfM.js +0 -1
- package/assets/flowDiagram-v2-96b9c2cf-Bqr3L3y4.js +0 -1
- package/assets/flowDiagram-v2-96b9c2cf-gCWf76DS.js +0 -1
package/sw.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var sw=(function(D){"use strict";var he=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(he||{});he.IMAGE+"",he.VIDEO+"",he.AUDIO+"",he.CHARACTER+"",he.INSPIRATION_BOARD+"",he.CHAT+"";function Se(n){return n instanceof Error?n.name||"Error":"Unknown error"}const gt="sw-task-queue",rn=3,_="tasks",z="config",B="workflows",x="chat-workflows",M="pending-tool-requests",P="pending-dom-operations",N="task-step-mappings",$="pending-canvas-operations",As=[_,z,B,x,M,P,N,$];function Rs(){return new Promise(n=>{const e=indexedDB.open(gt);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,rn))},e.onerror=()=>{n(rn)}})}function Ls(n){const e=[];for(const t of As)n.objectStoreNames.contains(t)||e.push(t);return e}function vs(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(gt,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;on(a)}})}function on(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 Ms(){const n=await Rs();return new Promise((e,t)=>{const s=indexedDB.open(gt,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=Ls(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),vs(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;on(o)}})}class Ps{constructor(){this.dbPromise=null,this.pendingTaskSaves=new Map,this.batchSaveTimer=null,this.batchSavePromises=new Map,this.BATCH_SAVE_DELAY=50}async getDB(){return this.dbPromise||(this.dbPromise=Ms()),this.dbPromise}async flushPendingTaskSaves(){this.batchSaveTimer&&(clearTimeout(this.batchSaveTimer),this.batchSaveTimer=null);const e=Array.from(this.pendingTaskSaves.values()),t=new Map(this.batchSavePromises);if(this.pendingTaskSaves.clear(),this.batchSavePromises.clear(),e.length!==0)try{const s=await this.getDB();await new Promise((r,o)=>{const a=s.transaction(_,"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",h=f.openCursor(null,p),m=[];let d=0,b=0;h.onerror=()=>l(h.error),h.onsuccess=S=>{const E=S.target.result;if(!E){c({tasks:m,total:b,hasMore:b>t+m.length});return}const R=E.value,q=!r||R.status===r,re=!o||R.type===o;q&&re&&(b++,d<t?d++:m.length<s&&m.push(R)),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:",Se(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:",Se(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=[],h=f.openCursor(null,"next");h.onsuccess=()=>{const m=h.result;if(!m){c(p);return}const d=m.value;d.archived||p.push(d),m.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 an=new Ps,ks=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function ft(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=>ft(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();ks.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=ft(s)}return e}return n}let Fe=!1;const Is=500,oe=[];let pt=0;function cn(){return Fe}const ln=["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"],ve=new Map;function un(n){const e=Fe;Fe=n,!n&&e&&(oe.length=0,ve.clear(),pt=0)}function mt(){return Fe}function Os(n){if(!cn()||n==="unknown"||ln.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)),ln.includes(e))return!1}return!0}function Ws(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 bt(n,e,t,s,r){if(r||!Os(n))return"";const o=Ws(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++pt}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:dn(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Bs(i),Ns(n)){const c=Gs(e);c&&ve.set(c,{entry:i,startTime:Date.now()})}return a}function Bs(n){oe.unshift(n),oe.length>Is&&oe.pop()}function yt(n,e,t,s){if(!cn())return"";const r=ve.get(n);if(r){r.entry.response=dn(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return ve.delete(n),o}return""}function Ue(){return[...oe]}function xs(){oe.length=0,ve.clear(),pt=0}function Ns(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 Gs(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function dn(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return ft(e)}catch{return"[Non-serializable data]"}}function Fs(){const n={total:oe.length,sent:0,received:0,byType:{}};for(const e of oe)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const wt=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:xs,getAllLogs:Ue,getLogStats:Fs,isPostMessageLoggerDebugMode:mt,logReceivedMessage:bt,setPostMessageLoggerDebugMode:un,updateRequestWithResponse:yt},Symbol.toStringTag,{value:"Module"}));function Us(){return typeof window<"u"?window:typeof self<"u"?self:{}}function Hs(n){return JSON.parse(JSON.stringify(n))}function hn(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 qs="postmessage-duplex",js="1.2.0",He=Us();var X,ae;He.__POSTMESSAGE_DUPLEX__||(He.__POSTMESSAGE_DUPLEX__={}),He.__POSTMESSAGE_DUPLEX__.version=js,He.__POSTMESSAGE_DUPLEX__.name=qs,(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"})(ae||(ae={}));class ie 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,ie)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class zs{constructor(){Object.defineProperty(this,"timeouts",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(this,"timer",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(this,"nextDeadline",{enumerable:1,configurable:1,writable:1,value:1/0}),Object.defineProperty(this,"destroyed",{enumerable:1,configurable:1,writable:1,value:0})}add(e,t,s){if(this.destroyed)return;const r=Date.now()+t;this.timeouts.set(e,{deadline:r,callback:s}),r<this.nextDeadline&&this.reschedule(r)}remove(e){return this.timeouts.delete(e)}has(e){return this.timeouts.has(e)}get size(){return this.timeouts.size}reschedule(e){this.timer!==null&&clearTimeout(this.timer),this.nextDeadline=e;const t=Math.max(0,e-Date.now());this.timer=setTimeout(()=>this.processTimeouts(),t)}processTimeouts(){if(this.destroyed)return;const e=Date.now(),t=[];for(const[s,{deadline:r,callback:o}]of this.timeouts)r<=e&&(t.push(o),this.timeouts.delete(s));for(const s of t)try{s()}catch(r){console.error("[TimeoutManager] Callback error:",r)}this.scheduleNext()}scheduleNext(){if(this.timeouts.size===0)return this.nextDeadline=1/0,void(this.timer=null);let e=1/0;for(const{deadline:t}of this.timeouts.values())t<e&&(e=t);e<1/0&&this.reschedule(e)}destroy(){this.destroyed=1,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.timeouts.clear(),this.nextDeadline=1/0}}class $s{constructor(e,t=1e3){Object.defineProperty(this,"limit",{enumerable:1,configurable:1,writable:1,value:e}),Object.defineProperty(this,"windowMs",{enumerable:1,configurable:1,writable:1,value:t}),Object.defineProperty(this,"timestamps",{enumerable:1,configurable:1,writable:1,value:void 0}),Object.defineProperty(this,"head",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"tail",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"count",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(this,"enabled",{enumerable:1,configurable:1,writable:1,value:void 0}),this.enabled=e>0,this.timestamps=this.enabled?new Array(e).fill(0):[]}tryAcquire(){if(!this.enabled)return 1;const e=Date.now(),t=e-this.windowMs;for(;this.count>0&&this.timestamps[this.head]<=t;)this.head=(this.head+1)%this.limit,this.count--;return this.count>=this.limit?0:(this.timestamps[this.tail]=e,this.tail=(this.tail+1)%this.limit,this.count++,1)}getCurrentCount(){if(!this.enabled)return 0;const e=Date.now()-this.windowMs;let t=0,s=this.head;for(let r=0;r<this.count;r++)this.timestamps[s]>e&&t++,s=(s+1)%this.limit;return t}getRemainingCapacity(){return this.enabled?Math.max(0,this.limit-this.getCurrentCount()):1/0}getTimeUntilAvailable(){if(!this.enabled||this.count<this.limit)return 0;const e=Date.now()-this.windowMs;let t=this.head;for(;t!==this.tail;){if(this.timestamps[t]>e)return this.timestamps[t]-e;t=(t+1)%this.limit}return 0}isLimited(){return this.enabled?this.getCurrentCount()>=this.limit:0}reset(){this.head=0,this.tail=0,this.count=0,this.enabled&&this.timestamps.fill(0)}getLimit(){return this.limit}getWindowMs(){return this.windowMs}isEnabled(){return this.enabled}}class Vs{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 gn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const J=n=>({valid:0,error:n});function Ks(n){if(!gn(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&&!gn(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 qe(n){return"ret"in n&&typeof n.ret=="number"}function Xs(n){return n.msg==="ready"}function Ys(n){return n._broadcast==1&&typeof n.cmdname=="string"}function Qs(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const St=[],Z=[];function fn(n){Z.length>=200&&Z.shift(),Z.push(n)}function pn(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 Js extends Vs{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 zs,this.rateLimiter=new $s((e==null?void 0:e.rateLimit)??100,1e3),e==null?void 0:e.subscribeMap)for(const s in e.subscribeMap)this.subscribeMap.set(s,e.subscribeMap[s]);var t;this.bindOnMessage=this.onMessage.bind(this),t=this,St.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{fn({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?pn(i,"ok"):fn({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{pn(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=Qs(e);if(t>this.maxMessageSize){const s=new ie(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ae.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):qe(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=Ks(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:qe(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(!Ys(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(!Xs(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}),qe(e)||this.sendMessage({requestId:t,ret:X.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!qe(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 ie("Cannot publish: channel has been destroyed",ae.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=St.findIndex(r=>r.deref()===t);s!==-1&&St.splice(s,1)})(this);const e=new ie("Channel has been destroyed",ae.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 y extends Js{static enableGlobalRouting(e){y.useGlobalRouting=1,y.unknownClientCallback=e??null,y.globalListenerSetup||(self.addEventListener("message",y.globalMessageHandler),y.globalListenerSetup=1)}static disableGlobalRouting(){y.useGlobalRouting=0,y.globalListenerSetup&&(self.removeEventListener("message",y.globalMessageHandler),y.globalListenerSetup=0)}static setupHub(e={}){if(y.hubInitialized)return void console.warn("[ServiceWorkerChannel] Hub already initialized");y.hubOptions=e,y.hubInitialized=1,Y.getInstance().setup(e,s=>y.createFromWorker(s)),y.enableGlobalRouting((s,r)=>{const o=y.createFromWorker(s);y.setupChannelHandlers(o,s),o.handleMessage(r)}),y.registerBuiltInHandlers();const t=e.cleanupInterval??3e4;t>0&&(y.cleanupIntervalId=setInterval(()=>y.cleanupInactiveClients(),t))}static registerBuiltInHandlers(){y.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 y.clientMeta.set(t,s),(o=(r=y.hubOptions).onClientConnect)==null||o.call(r,t,s),{success:1,clientId:t,totalClients:y.clientMeta.size}}),y.globalSubscribeMap.set("__ping__",({clientId:e})=>({pong:1,timestamp:Date.now(),clientId:e,activeClients:y.channelsByClientId.size}))}static setupChannelHandlers(e,t){for(const[s,r]of y.globalSubscribeMap)e.subscribe(s,async o=>{const a=y.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 y.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:y.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 y.channelsByClientId)if(!r.has(o)){const a=y.channelsByClientId.get(o);a&&a.destroy(),y.clientMeta.delete(o),(t=(e=y.hubOptions).onClientDisconnect)==null||t.call(e,o)}}catch(s){console.error("[ServiceWorkerChannel] Cleanup error:",s)}}static async broadcastToAll(e,t,s){if(!y.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=y.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(!y.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=y.clientMeta.get(i.id);if(!c||c.appType!==e)continue;const l=y.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 y.clientMeta.get(e)}static getAllClients(){return new Map(y.clientMeta)}static getClientsByType(e){const t=[];for(const s of y.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.`),y.globalSubscribeMap.set(e,t);for(const[s,r]of y.channelsByClientId)r.subscribe(e,async o=>{const a=y.clientMeta.get(s);return t({data:o.data||{},clientId:s,clientMeta:a})})}static unsubscribeGlobal(e){y.globalSubscribeMap.delete(e);for(const t of y.channelsByClientId.values())t.unSubscribe(e)}registerInGlobalRouter(){this.isWorkerSide&&this.clientId&&y.useGlobalRouting&&y.channelsByClientId.set(this.clientId,this)}unregisterFromGlobalRouter(){this.isWorkerSide&&this.clientId&&y.channelsByClientId.delete(this.clientId)}static getChannelByClientId(e){return y.channelsByClientId.get(e)}static hasChannel(e){return y.channelsByClientId.has(e)}static getChannelCount(){return y.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=hn("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=hn("page_")}this.log("log","baseKey",this.baseKey,this.isWorkerSide?"worker":"page"),this.registerInGlobalRouter(),this.init()}setupMessageListener(){var e;if(this.isWorkerSide){if(y.useGlobalRouting)return void(y.globalListenerSetup||(self.addEventListener("message",y.globalMessageHandler),y.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(y.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=Hs(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 ie("Heartbeat detection failed",ae.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 ie("All reconnection attempts failed",ae.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 ie("Handshake timeout",ae.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 y(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 y(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 y.createFromWorker(s.id,t)}destroy(){this.stopHeartbeat(),this.removeSwLifecycleListeners(),this.l!=="connected"&&this.l!=="reconnecting"||(this.l="disconnected"),super.destroy()}}Object.defineProperty(y,"channelsByClientId",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(y,"globalListenerSetup",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(y,"unknownClientCallback",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(y,"useGlobalRouting",{enumerable:1,configurable:1,writable:1,value:1}),Object.defineProperty(y,"clientMeta",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(y,"globalSubscribeMap",{enumerable:1,configurable:1,writable:1,value:new Map}),Object.defineProperty(y,"hubInitialized",{enumerable:1,configurable:1,writable:1,value:0}),Object.defineProperty(y,"hubOptions",{enumerable:1,configurable:1,writable:1,value:{}}),Object.defineProperty(y,"cleanupIntervalId",{enumerable:1,configurable:1,writable:1,value:null}),Object.defineProperty(y,"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=y.channelsByClientId.get(t);s?s.handleMessage(n):y.unknownClientCallback&&y.unknownClientCallback(t,n)}});function Zs(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"},we=class we{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(),y.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 an.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 we.instance||(we.instance=new we(e)),we.instance}ensureChannel(e){let t=this.channels.get(e);return t||(t={channel:y.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=Ue().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=mt()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=bt(`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=yt(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=yt(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(()=>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(()=>A);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(()=>A),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(()=>A),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(()=>A);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(()=>A);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(()=>A),{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(()=>A);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>A),{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(()=>A);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>wt),{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(()=>wt);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>A),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(()=>A);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(()=>ye);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(()=>ye);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(()=>ye);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(()=>ye);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(()=>A),{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"),p=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:p?parseInt(p):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(()=>A),{getAllLogs:o}=await Promise.resolve().then(()=>wt),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(()=>A);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>A);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>A),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>A);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>A);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>A);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 Zs(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()))}};we.instance=null;let je=we,ze=null;function mn(n){return ze||(ze=je.getInstance(n)),ze}function O(){return ze}const er=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:T,SWChannelManager:je,SW_EVENTS:G,getChannelManager:O,initChannelManager:mn},Symbol.toStringTag,{value:"Module"}));function $e(n){un(n)}const tr=[];let bn=!1;function Me(n){bn=n}function Ct(){return bn}function Et(){return[...tr]}const nr=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Et,isDebugFetchEnabled:Ct,setDebugFetchEnabled:Me},Symbol.toStringTag,{value:"Module"})),sr=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"},rr={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3},unpkg:{baseTimeout:600*1e3,maxTimeout:3600*1e3}},Ve=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1}],ge=new Map;let ee=null,Tt=!1,Ke=null;function yn(n=!1){n&&ge.clear(),Ve.forEach(e=>{ge.has(e.name)||ge.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}yn();function or(n){return n==="jsdelivr"||n==="unpkg"||n==="local"}function wn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!or(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 Sn(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=W.preferenceCacheExpiry}async function ar(){if(typeof caches>"u")return null;try{const e=await(await caches.open(W.preferenceCacheName)).match(W.preferenceCacheKey);return e!=null&&e.ok?wn(await e.json()):null}catch(n){return console.warn("[CDN Fallback] Failed to read persisted CDN preference:",n),null}}async function Dt(){Tt||(Ke||(Ke=(async()=>{ee=await ar(),Tt=!0,Ke=null})()),await Ke)}async function Cn(n){if(ee=wn(n),Tt=!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 _t(n){const e=ge.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now(),e.lastFailureReason=void 0)}function ce(n,e){const t=ge.get(n);if(t)if(t.failCount++,t.lastCheckTime=Date.now(),t.lastFailureReason=e,t.failCount>=W.failThreshold){t.isHealthy=!1;const s=Tn(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 En(n,e){const t=rr[n]??{baseTimeout:W.degradeTimeout,maxTimeout:W.degradeTimeout},r=2**Math.max(0,e-W.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function Tn(n){const e=En(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function At(n,e={}){const t=ge.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=En(n,t.failCount);return s-t.lastCheckTime>r?(console.log(`[CDN Fallback] Trying to recover ${n} after ${r}ms cooldown...`),!0):!1}function ir(n,e={}){const t=ee;return!t||!Sn(t,n)||t.cdn==="local"?null:At(t.cdn,e)?t.cdn:null}function Dn(n,e={}){const t=n?ir(n,e):null;return Ve.filter(s=>s.enabled&&At(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 _n(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 An(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function cr(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 Rt(n,e,t){const s=cr(n,t);if(s)return s;const r=_n(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function Lt(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 vt(n,e){const t=_n(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function Rn(n,e,t){try{const s=vt(e,n);console.log(`[CDN Fallback] Trying local server: ${s}`);const r=await Lt(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 Ln(n,e,t,s){for(const r of n){const o=Rt(r,e,t);try{console.log(`[CDN Fallback] Trying ${r.name}: ${o}`);const a=await Lt(o,s);if(!a.ok){ce(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await lr(a,r.name))continue;return _t(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";ce(r.name,i),console.warn(`[CDN Fallback] ${r.name} failed:`,a)}}return null}async function lr(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 ce(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 ce(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 ce(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function Mt(n,e,t,s={}){if(sr)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;await Dt();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 Rn(n,t,o);if(f)return{...f,targetUrl:vt(t,n)}}const l=Dn(e,{ignoreCooldown:i}),u=await Ln(l,e,n,c);if(u)return u;if(!r){const f=await Rn(n,t,o);if(f)return{...f,targetUrl:vt(t,n)}}const g=Ve.filter(f=>f.enabled&&!l.some(p=>p.name===f.name));if(g.length>0){console.warn(`[CDN Fallback] Local origin failed, forcing CDN recovery probe for: ${n}`);const f=await Ln(g,e,n,c);if(f)return f}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function Pt(n){await Dt();const e=new Map;for(const t of Ve){if(!t.enabled)continue;const s=Rt(t,n,t.healthCheckPath);try{const r=await Lt(s,5e3),o=r.ok;e.set(t.name,o),o?_t(t.name):ce(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),ce(t.name,"health-check-failed")}}return e}function Xe(){const n=Sn(ee)?ee==null?void 0:ee.cdn:null;return Array.from(ge.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,...Tn(t)}))}function kt(){yn(!0),console.log("[CDN Fallback] All CDN status reset")}const ur=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Rt,ensureCDNPreferenceLoaded:Dt,extractVersionFromCDNPath:An,fetchFromCDNWithFallback:Mt,getAvailableCDNs:Dn,getCDNStatusReport:Xe,isCDNAvailable:At,markCDNFailure:ce,markCDNSuccess:_t,performHealthCheck:Pt,resetCDNStatus:kt,setCDNPreference:Cn},Symbol.toStringTag,{value:"Module"}));function It(n){return n==="/"||n==="/index.html"}const dr=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"];function hr(n,e){return It(e)?!0:n==="navigate"&&!e.endsWith(".html")}function gr(n){return It(n)}function vn(n){return It(n)?!0:dr.some(e=>n.endsWith(e))}function fr(n){return!vn(n)}const F=self;mn(F).setDebugClientCountChangedCallback(Pr);const te={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function Ye(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 pr(){console.log=(...n)=>{te.log(...n),Ct()&&!Ye(n)&&Qe("log",n)},console.info=(...n)=>{te.info(...n),Ct()&&!Ye(n)&&Qe("info",n)},console.warn=(...n)=>{te.warn(...n),Ye(n)||Qe("warn",n)},console.error=(...n)=>{te.error(...n),Ye(n)||Qe("error",n)}}function mr(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 Qe(n,e){try{const{message:t,stack:s}=mr(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Ot=="function"&&Ot({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){te.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Ot=null;pr(),Promise.resolve().then(()=>ye).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=O();t&&t.sendDebugLLMLog(e)})});const C="0.6.71",Wt=`drawnix-v${C}`,L="drawnix-images",Ce=`drawnix-static-v${C}`,Je="drawnix-fonts",ne="sw-cache-date",fe="sw-cache-created-at",Bt="x-sw-source",xt="x-sw-revision",Nt="x-sw-app-version",Mn="x-sw-fetch-target",br="ServiceWorkerDB",yr=2,Ee="failedDomains",Te="versionState",Pn="app-version-state",kn="/__aitu_cache__/",In="/__aitu_generated__/audio/",wr="/asset-library/",Ze=location.hostname==="localhost"||location.hostname==="127.0.0.1",Sr=[{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"}],Cr=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Er=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Gt=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,Tr=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 Ft(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)Tr.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const j=new Map,pe=new Map,On=30*1e3,Pe=new Map,U=new Map,Dr=300*1e3,Wn=10,De=new Set,_e=new Set,_r=3600*1e3,Ut=new Map;function Bn(n){_e.add(n),Ut.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function Ar(n){if(!_e.has(n))return!1;const e=Ut.get(n);return e&&Date.now()-e>_r?(_e.delete(n),Ut.delete(n),!1):!0}const Q=[],xn=7,V=[],Rr=500;let k=!1;function I(n){if(!k)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return V.unshift(t),V.length>Rr&&V.pop(),Nn(t),e}function v(n,e){if(!k||!n)return;const t=V.find(s=>s.id===n);t&&(Object.assign(t,e),Nn(t))}function Nn(n){const e=O();e&&e.sendDebugLog(n)}function et(){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 Lr(n){try{const e=await et(),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 Gn(){try{await Fn();const n=await et(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-xn*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 Fn(){try{const n=await et(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-xn*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 Un(){try{const n=await et(),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 Hn=500;function Ht(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(k||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};Lr(r),Q.unshift(r),Q.length>Hn&&(Q.length=Hn),k&&vr(r)}Ot=Ht;function vr(n){const e=O();e&&e.sendConsoleLog(n)}function Mr(){let n=0;return U.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function qn(){return{version:C,cacheNames:[Wt,L,Ce,Je],pendingImageRequests:j.size,pendingVideoRequests:Pe.size,videoBlobCacheSize:U.size,videoBlobCacheTotalBytes:Mr(),completedImageRequestsSize:pe.size,failedDomainsCount:De.size,failedDomains:Array.from(De),corsFailedDomainsCount:_e.size,corsFailedDomains:Array.from(_e),debugLogsCount:V.length,consoleLogsCount:Q.length,debugModeEnabled:k,memoryStats:{pendingRequestsMapSize:j.size,completedRequestsMapSize:pe.size,videoBlobCacheMapSize:U.size,failedDomainsSetSize:De.size,corsFailedDomainsSetSize:_e.size,debugLogsArraySize:V.length,consoleLogsArraySize:Q.length}}}function qt(){return V}function jn(){V.length=0}function zn(){Q.length=0}function jt(){k||(k=!0,Me(!0),$e(!0),te.log("Service Worker: Debug mode enabled (debug page connected)"))}function zt(){k&&(k=!1,Me(!1),$e(!1),Q.length=0,V.length=0,te.log("Service Worker: Debug mode disabled (no debug pages)"))}function Pr(n){n>0?jt():zt()}function $n(n){for(const e of Sr)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function kr(n,e){return Cr.test(n.pathname)||e.destination==="image"||$n(n)!==null}function Ir(n,e){return Er.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function Or(n,e){return Gt.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function Wr(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 Br(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function Vn(n){return`drawnix-static-v${n}`}function Kn(){return{committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function Xn(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 tt(){return new Promise((n,e)=>{const t=indexedDB.open(br,yr);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains(Ee)||r.createObjectStore(Ee,{keyPath:"domain"}),r.objectStoreNames.contains(Te)||r.createObjectStore(Te,{keyPath:"key"})}})}async function ke(){try{const n=await tt();return await new Promise((e,t)=>{const o=n.transaction([Te],"readonly").objectStore(Te).get(Pn);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(Xn((a==null?void 0:a.state)||Kn()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),Kn()}}async function xr(n){const e=Xn(n);try{const t=await tt();await new Promise((s,r)=>{const o=t.transaction([Te],"readwrite");o.objectStore(Te).put({key:Pn,state:e}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.warn("Service Worker: 无法写入版本状态:",t)}return e}async function me(n){const e=await ke(),t=typeof n=="function"?n(e):n;return xr({...e,...t,updatedAt:Date.now()})}async function le(n){const e=await ke(),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 Nr(){try{const n=await tt();return await new Promise((e,t)=>{const o=n.transaction([Ee],"readonly").objectStore(Ee).getAll();o.onsuccess=()=>{o.result.forEach(i=>De.add(i.domain)),e()},o.onerror=()=>t(o.error)})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function Gr(n){try{const e=await tt();return await new Promise((t,s)=>{const r=e.transaction([Ee],"readwrite");r.objectStore(Ee).put({domain:n,timestamp:Date.now()}),r.oncomplete=()=>t(),r.onerror=()=>s(r.error)})}catch(e){console.warn("Service Worker: 无法保存失败域名:",e)}}async function Fr(n){if(!n){await me({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await le();return}await me(t=>({committedVersion:t.committedVersion||C,pendingVersion:C,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=O();e&&e.sendSWNewVersionReady(C),await le()}async function Ur(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 Yn=2,$t=1500,Qn=2500,Hr=8e3,qr=5e3,jr=6e4,zr=["offline-static-assets"];let Ie=0,Jn=0;const Oe=new Set,We=new Set,Be=new Set,nt=new Map;let Zn=Promise.resolve(),xe=null,Ne=0,Ae=!1,st=!1;function w(n,e){if(e===void 0){console.info(`[SWDebug] ${n}`);return}console.info(`[SWDebug] ${n}`,e)}function es(){return Xe().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 ts(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:es(),...t})}let Vt={phase:"idle",percent:0,completed:0,total:0,failed:0,version:C,updatedAt:Date.now()};async function ns(n){const e={type:"SW_BOOT_PROGRESS",...Vt};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 be(n,e){Vt={...Vt,...n,version:C,updatedAt:Date.now()},ns(e)}async function $r(){try{const n=await fetch("./precache-manifest.json",{cache:"reload"});if(!n.ok)return w("loadPrecacheManifest: response not ok",{status:n.status,statusText:n.statusText}),null;const e=await n.json();return w("loadPrecacheManifest: loaded",{version:e.version,fileCount:e.files.length}),e.files}catch(n){return w("loadPrecacheManifest: failed",{error:Se(n)}),null}}let Kt=null;async function Vr(){try{const n=await fetch("./idle-prefetch-manifest.json",{cache:"reload"});if(!n.ok)return w("loadIdlePrefetchManifest: response not ok",{status:n.status,statusText:n.statusText}),null;const e=await n.json();return w("loadIdlePrefetchManifest: loaded",{version:e.version,defaults:e.defaults||[],groupEntryCounts:Object.fromEntries(Object.entries(e.groups).map(([t,s])=>[t,s.length]))}),e}catch(n){return w("loadIdlePrefetchManifest: failed",{error:Se(n)}),null}}async function Xt(){return Kt||(Kt=Vr()),Kt}async function ss(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(Be),version:C,updatedAt:Date.now()};if(n){w("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);w("broadcast idle prefetch status to all clients",{clientCount:t.length,completedGroups:e.completedGroups})}function Kr(n,e){return`${n}@${e}`}async function rt(n){try{return(await n.keys()).length}catch{return-1}}function ot(n,e){const t=Zn.catch(()=>{}).then(async()=>{w("idle prefetch task start",{label:n});try{await e()}finally{w("idle prefetch task done",{label:n})}});return Zn=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:Se(s)})}),t}function Xr(n){return Math.min(jr,qr*2**Math.max(0,n-1))}function Yr(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 rs(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=Kr(g.url,g.revision);if(Oe.has(f)||(u=!0,We.has(f)))continue;const p=nt.get(f);if(p&&p.nextRetryAt>t){a+=1;const h=Math.max(0,p.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 Qr(n,e=Qn){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(xe!==null){if(Ne<=s){w("scheduleIdlePrefetchSweep skipped: earlier timer already exists",{reason:n,scheduledInMs:Math.max(0,Ne-Date.now()),requestedDelayMs:t});return}clearTimeout(xe),xe=null,Ne=0}Ne=s,xe=self.setTimeout(()=>{xe=null,Ne=0,ot(`idle-sweep:${n}`,async()=>{await lt(`scheduled:${n}`)})},t),w("scheduleIdlePrefetchSweep queued",{reason:n,delayMs:t})}function Jr(){return Ie===0?!1:Date.now()-Ie<$t}function Zr(){if(Ie===0)return Promise.resolve();const n=Date.now()-Ie,e=Math.max(0,$t-n)+100;return w("waitForIdlePrefetchWindow: delaying idle prefetch",{elapsedMs:n,waitMs:e,recentFetchWindowMs:$t}),new Promise(t=>{setTimeout(t,e)})}function eo(n,e){if(n.request.method!=="GET"||!n.clientId||e.origin!==self.location.origin||e.pathname.startsWith(kn)||e.pathname.startsWith(In)||e.pathname==="/sw.js"||e.pathname==="/precache-manifest.json"||e.pathname==="/idle-prefetch-manifest.json")return!1;const t=Date.now();return t-Jn<Hr?!1:(Jn=t,!0)}function to(n){return vn(n)}function os(n,e){return Ze||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||to(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 at(n){const e=new URL(n,self.location.origin),t=new URL(`${e.pathname}${e.search}`,self.location.origin);return{requestUrl:e,resourcePath:`${e.pathname}${e.search}`,cacheKey:t.href,originFetchUrl:t.href}}function it(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&os(n,e)}function no(n,e){const t=new Headers(n.headers);return t.set(Bt,e.source),t.set(xt,e.revision),t.set(Nt,e.appVersion||C),e.fetchTarget&&t.set(Mn,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 Yt(n,e,t,s){const r=no(t,s);return await n.put(e,r.clone()),r}async function ct(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 w("findStaticResponseInOldCaches: normalized key hit",{cacheName:r,requestUrl:n.url,normalizedCacheKey:i}),c}}catch{}return null}async function so(n,e){const t=at(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 ro(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function as(n,e,t){try{const s=at(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(xt),l=r.headers.get(Nt);if(c===t&&l===C)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(fr(s.requestUrl.pathname)){const c=await Mt(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&&it(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 Yt(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 oo(n,e){const s=[],r=e.length;let o=0,a=0;const i=await rt(n);w("precacheStaticFiles start",{total:r,concurrency:6,cacheEntriesBefore:i,sampleUrls:e.slice(0,8).map(p=>p.url)}),be({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 h=e.slice(p,p+6),m=await Promise.allSettled(h.map(({url:b,revision:S})=>as(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}w("precacheStaticFiles batch done",{completed:o,total:r,batchSize:h.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}))}),be({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,g=s.filter(p=>p.success&&p.source==="server").length,f=await rt(n);w("precacheStaticFiles finished",{total:r,successCount:c,failCount:l,cdnCount:u,serverCount:g,cacheEntriesBefore:i,cacheEntriesAfter:f})}async function ao(n){if(w("prefetchIdleGroups start",{groupNames:n}),n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await Xt();if(!e)return w("prefetchIdleGroups aborted: manifest missing"),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};w("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(Be),s=rs(e,n);if(s.completedGroups.forEach(u=>Be.add(u)),s.queue.length===0)return w("prefetchIdleGroups no ready files",{groupNames:n,completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs,completedEntries:Oe.size,activeEntries:We.size}),{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(Ce),o=await rt(r),a=s.queue;w("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+=Yn){for(;Jr();)await Zr();const g=a.slice(u,u+Yn);g.forEach(([h])=>We.add(h));const f=await Promise.allSettled(g.map(([,{url:h,revision:m}])=>as(r,h,m))),p=[];f.forEach((h,m)=>{const[d]=g[m];if(We.delete(d),h.status==="fulfilled"&&h.value.success)nt.delete(d),Oe.add(d);else{const b=nt.get(d),S=((b==null?void 0:b.count)||0)+1,E=Xr(S);nt.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"?p.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}):p.push({success:!1,error:String(h.reason)})}),w("prefetchIdleGroups batch done",{groupNames:n,batchStart:u,batchSize:g.length,batchSuccess:p.filter(h=>h.success).length,batchSkipped:p.filter(h=>h.skipped).length,batchFailed:p.filter(h=>!h.success).length,batchSources:Object.fromEntries(Array.from(p.reduce((h,m)=>{const d=m.source||"unknown";return h.set(d,(h.get(d)||0)+1),h},new Map))),batchErrors:p.filter(h=>!h.success).slice(0,5).map(h=>({url:h.url,status:h.status,error:h.error})),completedEntries:Oe.size,activeEntries:We.size})}const i=rs(e,n),c=i.completedGroups.filter(u=>!t.has(u));c.forEach(u=>Be.add(u));const l=await rt(r);return w("prefetchIdleGroups finished",{groupNames:n,newlyCompletedGroups:c,pendingGroups:i.pendingGroups,completedEntries:Oe.size,cacheEntriesBefore:o,cacheEntriesAfter:l,completedGroups:Array.from(Be),coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}),{completedGroups:c,pendingGroups:i.pendingGroups,queuedEntries:a.length,coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}}async function lt(n,e=[]){const t=await Xt();if(!t)return w("prefetchPendingIdleGroups skipped: manifest missing",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const s=Yr(t,e);if(s.length===0)return w("prefetchPendingIdleGroups skipped: no groups",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};w("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 ao(s);return r.completedGroups.length>0&&await ss(),r.pendingGroups.length>0&&Qr(`${n}:pending`,r.nextRetryDelayMs??Qn),w("prefetchPendingIdleGroups done",{reason:n,preferredGroups:e,orderedGroups:s,summary:r}),r}async function io(){var t;const n=await Xt(),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){w("prefetchDefaultIdleGroups skipped: no default groups");return}await lt("default-groups",e)}F.addEventListener("install",n=>{w("install event received",{version:C}),Ae=!!F.registration.active,st=!Ae,Ae||F.skipWaiting(),be({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await Nr(),await me(e=>({committedVersion:e.committedVersion||C,pendingVersion:Ae?C:null,pendingReadyAt:null,upgradeState:Ae?"prewarming":"idle"})),await le();try{const e=await $r();if(e&&e.length>0){const t=await caches.open(Ce);await oo(t,e)}else Ze&&be({phase:"development",percent:100,completed:0,total:0,failed:0,message:"开发模式下跳过静态预缓存"});await Fr(Ae)}catch(e){await me(t=>({committedVersion:t.committedVersion||C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await le(),be({phase:"error",message:`启动资源预热失败:${Se(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),F.addEventListener("activate",n=>{w("activate event received",{version:C}),be({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await ke(),await me({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await le();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>ur);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}st?(w("activate: before clients.claim"),await F.clients.claim(),w("activate: after clients.claim")):w("activate: skip clients.claim for staged update"),setTimeout(()=>{w("activate: scheduling default idle prefetch"),ot("default-groups",async()=>io())},800);const e=O();e&&(e.sendSWActivated(C),w("activate: sent sw:activated broadcast")),be({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 ke(),r=Vn(s.committedVersion||C),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==Ce&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==Wt&&i!==L&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(Ce);await ho(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),Fn().catch(i=>{console.warn("Failed to cleanup expired console logs:",i)}),an.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function co(n){if(k){const e=O();e&&e.sendPostMessageLog(n)}}async function lo(n,e,t,s){if(Ze)return null;try{const r=at(e.url),o=await Mt(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:es()}),null;const a=new URL(e.url);if(it(e,a,o.response))return null;const i=await Yt(n,r.cacheKey,o.response,{source:o.source,revision:"runtime",fetchTarget:o.targetUrl,appVersion:s});return r.cacheKey!==e.url&&w("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 uo(n){const e=n.headers.get(Bt)||void 0,t=n.headers.get(Mn)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function is(n,e,t=C){const s=e.headers.get(Bt),r=e.headers.get(xt),o=e.headers.get(Nt);if(!s||!r||!o||o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr"&&s!=="unpkg")return!0;const a=new URL(n.url);return it(n,a,e)}async function ho(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&is(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,g,f,p,h,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=((g=n.source)==null?void 0:g.url)||"",r=((f=n.data)==null?void 0:f.cmdname)||((p=n.data)==null?void 0:p.requestId)&&((h=n.data)==null?void 0:h.ret)!==void 0;let o="";if(mt()&&!r&&(o=bt(e,n.data,t,s,(m=n.data)==null?void 0:m.__internal__),o&&k)){const b=Ue().find(S=>S.id===o);b&&co(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 R=new Blob([S],{type:E||(b==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:q}=await Promise.resolve().then(()=>H);q(R,d,b)})()}return}if(n.data&&n.data.type==="SW_CDN_SET_PREFERENCE"){n.waitUntil(Cn({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;w("message: SW_BOOT_PROGRESS_GET",{clientId:(d==null?void 0:d.id)??null}),ns(d);return}if(n.data&&n.data.type==="GET_VERSION_STATE"){const d=n.source;w("message: GET_VERSION_STATE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil(le(d));return}if(n.data&&n.data.type==="SW_IDLE_PREFETCH_STATUS_GET"){const d=n.source;w("message: SW_IDLE_PREFETCH_STATUS_GET",{clientId:(d==null?void 0:d.id)??null}),ss(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"):[];w("message: SW_PREFETCH_GROUPS",{groups:d}),n.waitUntil(ot(`message:${d.join(",")||"empty"}`,async()=>{await lt(`message:${d.join(",")||"empty"}`,d)}));return}if(n.data&&(n.data.type==="COMMIT_UPGRADE"||n.data.type==="SKIP_WAITING")){const d=n.source;w("message: COMMIT_UPGRADE",{clientId:(d==null?void 0:d.id)??null}),n.waitUntil((async()=>{st=!0,await me({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await le(d),F.skipWaiting();const b=O();b&&b.sendSWUpdated(C)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{st=!0,await me({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await le(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&&Jt(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)&&bo(d).then(()=>{}).catch(b=>{console.error("Service Worker: Failed to batch delete caches:",b)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")yo().then(()=>{}).catch(d=>{console.error("Service Worker: Failed to clear all cache:",d)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){k=!0,Me(!0),$e(!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"){k=!1,Me(!1),$e(!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(()=>ye),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(()=>ye);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:k,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(()=>nr),b=qt(),S=d(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...b,...S.map(R=>({...R,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=Ue(),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 go="MemorySnapshotDB",ue="snapshots",cs=50;async function Qt(){return new Promise((n,e)=>{const t=indexedDB.open(go,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(ue)){const o=r.createObjectStore(ue,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function ls(n){try{const e=await Qt(),t=e.transaction(ue,"readwrite"),s=t.objectStore(ue);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>cs){const i=s.index("timestamp").openCursor();let c=0;const l=o-cs;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 us(){try{const n=await Qt(),s=n.transaction(ue,"readonly").objectStore(ue).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 ds(){try{const n=await Qt(),e=n.transaction(ue,"readwrite");e.objectStore(ue).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 fo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function po(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function mo(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),p=f.count();p.onsuccess=()=>{const h=p.result;if(o+=h,h>0){const m=f.openCursor();let d=0;m.onsuccess=b=>{const S=b.target.result;if(S&&d<l)a+=po(S.value),i++,d++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,R=Math.round(E*o);e({count:o,totalSize:R})}},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 h=i>0?a/i:0,m=Math.round(h*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 hs(){const n={},e=[Wt,L,Ce,Je];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 fo)try{const s=await mo(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function Jt(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 bo(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 yo(){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 gs(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 wo(){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,fs=300*1e3,ps=500;function So(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 Co(n){const e=se.get(n);return e?Date.now()-e>fs?(se.delete(n),!1):!0:!1}function ms(n){if(So(n)){if(se.size>=ps){const e=Date.now();for(const[t,s]of se)e-s>fs&&se.delete(t);if(se.size>=ps){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:"){I({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(Ie=t,eo(n,e)){const s=`${e.pathname}${e.search}`;w("fetch: enqueue idle prefetch recheck",{clientId:n.clientId,requestUrl:s}),n.waitUntil(ot(`fetch-recheck:${s}`,async()=>{await lt(`fetch:${s}`)}))}if(e.pathname.startsWith(kn)||e.pathname.startsWith(In)){const s=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(To(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(wr)){const s=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Do(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"){I({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")){I({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")){I({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(Ar(e.hostname)){I({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&&Or(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=I({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(_o(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(Ir(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=I({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(Ao(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(Wr(e,n.request)){const s=Date.now(),r=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(Eo(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&&kr(e,n.request)){if(Co(n.request.url)){I({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=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(Mo(n.request).then(o=>(o.status===404&&ms(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 ms(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=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(Ro(n.request).then(i=>{const c=uo(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(k){if(
|
|
1
|
+
var sw=(function(D){"use strict";var ge=(n=>(n.IMAGE="image",n.VIDEO="video",n.AUDIO="audio",n.CHARACTER="character",n.INSPIRATION_BOARD="inspiration_board",n.CHAT="chat",n))(ge||{});ge.IMAGE+"",ge.VIDEO+"",ge.AUDIO+"",ge.CHARACTER+"",ge.INSPIRATION_BOARD+"",ge.CHAT+"";function Ce(n){return n instanceof Error?n.name||"Error":"Unknown error"}const ft="sw-task-queue",an=3,_="tasks",z="config",B="workflows",x="chat-workflows",M="pending-tool-requests",P="pending-dom-operations",N="task-step-mappings",$="pending-canvas-operations",Ls=[_,z,B,x,M,P,N,$];function vs(){return new Promise(n=>{const e=indexedDB.open(ft);e.onsuccess=()=>{const t=e.result,s=t.version;t.close(),n(Math.max(s,an))},e.onerror=()=>{n(an)}})}function Ms(n){const e=[];for(const t of Ls)n.objectStoreNames.contains(t)||e.push(t);return e}function Ps(n){return new Promise((e,t)=>{const s=n+1,r=indexedDB.open(ft,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;cn(a)}})}function cn(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 ks(){const n=await vs();return new Promise((e,t)=>{const s=indexedDB.open(ft,n);s.onerror=()=>{console.error("[SWStorage] Failed to open DB:",s.error),t(s.error)},s.onsuccess=()=>{const r=s.result,o=Ms(r);if(o.length>0){console.warn(`[SWStorage] Missing object stores: ${o.join(", ")}. Repairing...`),r.close(),Ps(r.version).then(e).catch(t);return}e(r)},s.onupgradeneeded=r=>{const o=r.target.result;cn(o)}})}class Is{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=ks()),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 R=E.value,H=!r||R.status===r,re=!o||R.type===o;H&&re&&(b++,d<t?d++:m.length<s&&m.push(R)),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:",Ce(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:",Ce(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 ln=new Is,Os=["apikey","api_key","password","token","secret","authorization","bearer","credential","key"];function pt(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=>pt(e));if(typeof n=="object"){const e={};for(const[t,s]of Object.entries(n)){const r=t.toLowerCase();Os.some(o=>r.includes(o))?e[t]="[REDACTED]":e[t]=pt(s)}return e}return n}let Fe=!1;const Ws=500,oe=[];let mt=0;function un(){return Fe}const dn=["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"],ve=new Map;function hn(n){const e=Fe;Fe=n,!n&&e&&(oe.length=0,ve.clear(),mt=0)}function bt(){return Fe}function Bs(n){if(!un()||n==="unknown"||dn.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)),dn.includes(e))return!1}return!0}function xs(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 wt(n,e,t,s,r){if(r||!Bs(n))return"";const o=xs(s);if(o.clientType==="debug")return"";const a=`pm-recv-${Date.now()}-${++mt}`,i={id:a,timestamp:Date.now(),direction:"receive",messageType:n,data:gn(e),clientId:t,clientUrl:o.clientUrl,clientType:o.clientType};if(Ns(i),Fs(n)){const c=Us(e);c&&ve.set(c,{entry:i,startTime:Date.now()})}return a}function Ns(n){oe.unshift(n),oe.length>Ws&&oe.pop()}function yt(n,e,t,s){if(!un())return"";const r=ve.get(n);if(r){r.entry.response=gn(e),r.entry.duration=t,s&&(r.entry.error=s);const o=r.entry.id;return ve.delete(n),o}return""}function Ue(){return[...oe]}function Gs(){oe.length=0,ve.clear(),mt=0}function Fs(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 Us(n){if(!n||typeof n!="object")return null;const e=n;return e.requestId||e.taskId||e.workflowId||e.chatId||null}function gn(n){if(!n)return n;try{const e=JSON.parse(JSON.stringify(n));return pt(e)}catch{return"[Non-serializable data]"}}function qs(){const n={total:oe.length,sent:0,received:0,byType:{}};for(const e of oe)e.direction==="send"?n.sent++:n.received++,n.byType[e.messageType]||(n.byType[e.messageType]=0),n.byType[e.messageType]++;return n}const St=Object.freeze(Object.defineProperty({__proto__:null,clearLogs:Gs,getAllLogs:Ue,getLogStats:qs,isPostMessageLoggerDebugMode:bt,logReceivedMessage:wt,setPostMessageLoggerDebugMode:hn,updateRequestWithResponse:yt},Symbol.toStringTag,{value:"Module"}));function Hs(){return typeof window<"u"?window:typeof self<"u"?self:{}}function js(n){return JSON.parse(JSON.stringify(n))}function fn(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 zs="postmessage-duplex",$s="1.2.0",qe=Hs();var X,ae;qe.__POSTMESSAGE_DUPLEX__||(qe.__POSTMESSAGE_DUPLEX__={}),qe.__POSTMESSAGE_DUPLEX__.version=$s,qe.__POSTMESSAGE_DUPLEX__.name=zs,(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"})(ae||(ae={}));class ie 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,ie)}toJSON(){return{name:this.name,message:this.message,code:this.code,details:this.details,stack:this.stack}}}class Vs{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 Ks{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 Xs{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 pn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const J=n=>({valid:0,error:n});function Ys(n){if(!pn(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&&!pn(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 He(n){return"ret"in n&&typeof n.ret=="number"}function Qs(n){return n.msg==="ready"}function Js(n){return n._broadcast==1&&typeof n.cmdname=="string"}function Zs(n){try{const e=JSON.stringify(n);return typeof Blob<"u"?new Blob([e]).size:2*e.length}catch{return 1/0}}const Ct=[],Z=[];function mn(n){Z.length>=200&&Z.shift(),Z.push(n)}function bn(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 er extends Xs{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 Vs,this.rateLimiter=new Ks((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,Ct.push(new WeakRef(t)),t.on("message:sent",({cmdname:s,requestId:r})=>{mn({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?bn(i,"ok"):mn({direction:"receive",cmdname:a,requestId:i,status:"ok",timestamp:Date.now(),dataSummary:""})}),t.on("timeout",({cmdname:s,requestId:r})=>{bn(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=Zs(e);if(t>this.maxMessageSize){const s=new ie(`Message size (${t} bytes) exceeds limit (${this.maxMessageSize} bytes)`,ae.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):He(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=Ys(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:He(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(!Js(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(!Qs(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}),He(e)||this.sendMessage({requestId:t,ret:X.Success,msg:"ready"}),1}handleUnhandledMessage(e,t,s){t&&!He(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 ie("Cannot publish: channel has been destroyed",ae.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=Ct.findIndex(r=>r.deref()===t);s!==-1&&Ct.splice(s,1)})(this);const e=new ie("Channel has been destroyed",ae.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 er{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=fn("sw_")}else{if(!e||typeof e=="string")throw new Error("页面端必须传入有效的 ServiceWorker 实例");this.worker=e,this.swContainer=navigator.serviceWorker,this.baseKey=fn("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=js(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 ie("Heartbeat detection failed",ae.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 ie("All reconnection attempts failed",ae.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 ie("Handshake timeout",ae.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 tr(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"},Se=class Se{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 ln.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 Se.instance||(Se.instance=new Se(e)),Se.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=Ue().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=bt()&&!(((l=this.channels.get(t))==null?void 0:l.isDebugClient)??!1);if(c){const u=wt(`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=yt(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=yt(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(()=>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(()=>A);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(()=>A),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(()=>A),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(()=>A);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(()=>A);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(()=>A),{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(()=>A);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetConsoleLogs(e){try{const{loadConsoleLogsFromDB:t}=await Promise.resolve().then(()=>A),{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(()=>A);return e(),await t(),{success:!0}}catch{return{success:!1}}}async handleDebugGetPostMessageLogs(e){try{const{getAllLogs:t,getLogStats:s}=await Promise.resolve().then(()=>St),{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(()=>St);return e(),{success:!0}}catch{return{success:!1}}}async handleDebugGetCrashSnapshots(){try{const{getCrashSnapshots:e}=await Promise.resolve().then(()=>A),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(()=>A);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(()=>ye);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(()=>ye);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(()=>ye);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(()=>ye);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(()=>A),{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(()=>A),{getAllLogs:o}=await Promise.resolve().then(()=>St),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(()=>A);return{status:e()}}catch{return{status:{}}}}async handleCDNResetStatus(){try{const{resetCDNStatus:e}=await Promise.resolve().then(()=>A);return e(),{success:!0}}catch{return{success:!1}}}async handleCDNHealthCheck(){try{const{performHealthCheck:e,APP_VERSION:t}=await Promise.resolve().then(()=>A),s=await e(t);return{results:Object.fromEntries(s)}}catch{return{results:{}}}}async handleUpgradeGetStatus(){try{const{APP_VERSION:e}=await Promise.resolve().then(()=>A);return{version:e}}catch{return{version:"unknown"}}}async handleUpgradeForce(){try{self.skipWaiting();const{APP_VERSION:t}=await Promise.resolve().then(()=>A);return this.sendSWUpdated(t),{success:!0}}catch{return{success:!1}}}async handleCacheDelete(e){try{const{deleteCacheByUrl:t}=await Promise.resolve().then(()=>A);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 tr(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()))}};Se.instance=null;let je=Se,ze=null;function wn(n){return ze||(ze=je.getInstance(n)),ze}function O(){return ze}const nr=Object.freeze(Object.defineProperty({__proto__:null,RPC_METHODS:T,SWChannelManager:je,SW_EVENTS:G,getChannelManager:O,initChannelManager:wn},Symbol.toStringTag,{value:"Module"}));function $e(n){hn(n)}const sr=[];let yn=!1;function Me(n){yn=n}function Et(){return yn}function Tt(){return[...sr]}const rr=Object.freeze(Object.defineProperty({__proto__:null,getInternalFetchLogs:Tt,isDebugFetchEnabled:Et,setDebugFetchEnabled:Me},Symbol.toStringTag,{value:"Module"})),or=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"},ar={jsdelivr:{baseTimeout:60*1e3,maxTimeout:300*1e3},unpkg:{baseTimeout:600*1e3,maxTimeout:3600*1e3}},Ve=[{name:"jsdelivr",urlTemplate:"https://cdn.jsdelivr.net/npm/aitu-app@{version}/{path}",healthCheckPath:"version.json",enabled:!0,priority:1}],fe=new Map;let ee=null,Dt=!1,Ke=null;function Sn(n=!1){n&&fe.clear(),Ve.forEach(e=>{fe.has(e.name)||fe.set(e.name,{name:e.name,isHealthy:!0,lastCheckTime:0,failCount:0,lastSuccessTime:Date.now()})})}Sn();function ir(n){return n==="jsdelivr"||n==="unpkg"||n==="local"}function Cn(n){if(!n||typeof n!="object")return null;const e=n,t=e.cdn,s=e.version;if(!ir(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 En(n,e){return!n||e&&n.version!==e?!1:Date.now()-n.timestamp<=W.preferenceCacheExpiry}async function cr(){if(typeof caches>"u")return null;try{const e=await(await caches.open(W.preferenceCacheName)).match(W.preferenceCacheKey);return e!=null&&e.ok?Cn(await e.json()):null}catch(n){return console.warn("[CDN Fallback] Failed to read persisted CDN preference:",n),null}}async function _t(){Dt||(Ke||(Ke=(async()=>{ee=await cr(),Dt=!0,Ke=null})()),await Ke)}async function Tn(n){if(ee=Cn(n),Dt=!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 At(n){const e=fe.get(n);e&&(e.isHealthy=!0,e.failCount=0,e.lastSuccessTime=Date.now(),e.lastCheckTime=Date.now(),e.lastFailureReason=void 0)}function ce(n,e){const t=fe.get(n);if(t)if(t.failCount++,t.lastCheckTime=Date.now(),t.lastFailureReason=e,t.failCount>=W.failThreshold){t.isHealthy=!1;const s=_n(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 Dn(n,e){const t=ar[n]??{baseTimeout:W.degradeTimeout,maxTimeout:W.degradeTimeout},r=2**Math.max(0,e-W.failThreshold);return Math.min(t.baseTimeout*r,t.maxTimeout)}function _n(n){const e=Dn(n.name,n.failCount),t=n.lastCheckTime+e;return{cooldownMs:e,cooldownUntil:t,remainingCooldownMs:Math.max(0,t-Date.now())}}function Rt(n,e={}){const t=fe.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=Dn(n,t.failCount);return s-t.lastCheckTime>r?(console.log(`[CDN Fallback] Trying to recover ${n} after ${r}ms cooldown...`),!0):!1}function lr(n,e={}){const t=ee;return!t||!En(t,n)||t.cdn==="local"?null:Rt(t.cdn,e)?t.cdn:null}function An(n,e={}){const t=n?lr(n,e):null;return Ve.filter(s=>s.enabled&&Rt(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 Rn(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 Ln(n){const e=n.match(/(?:^|\/)(?:npm\/)?aitu-app@([^/]+)\//);return e?e[1]:null}function ur(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 Lt(n,e,t){const s=ur(n,t);if(s)return s;const r=Rn(t);return n.urlTemplate.replace("{version}",e).replace("{path}",r.startsWith("/")?r.slice(1):r)}async function vt(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 Mt(n,e){const t=Rn(e);return`${n}/${t.startsWith("/")?t.slice(1):t}`}async function vn(n,e,t){try{const s=Mt(e,n);console.log(`[CDN Fallback] Trying local server: ${s}`);const r=await vt(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 Mn(n,e,t,s){for(const r of n){const o=Lt(r,e,t);try{console.log(`[CDN Fallback] Trying ${r.name}: ${o}`);const a=await vt(o,s);if(!a.ok){ce(r.name,`status:${a.status}`),console.warn(`[CDN Fallback] ${r.name} returned ${a.status}`);continue}if(!await dr(a,r.name))continue;return At(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";ce(r.name,i),console.warn(`[CDN Fallback] ${r.name} failed:`,a)}}return null}async function dr(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 ce(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 ce(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 ce(e,"html-error-page"),console.warn(`[CDN Fallback] ${e} returned HTML instead of ${t}`),!1}}}catch{}return!0}async function Pt(n,e,t,s={}){if(or)return console.log("[CDN Fallback] 开发模式,跳过 CDN 回退"),null;await _t();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 vn(n,t,o);if(f)return{...f,targetUrl:Mt(t,n)}}const l=An(e,{ignoreCooldown:i}),u=await Mn(l,e,n,c);if(u)return u;if(!r){const f=await vn(n,t,o);if(f)return{...f,targetUrl:Mt(t,n)}}const h=Ve.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 Mn(h,e,n,c);if(f)return f}return console.error(`[CDN Fallback] All sources failed for: ${n}`),null}async function kt(n){await _t();const e=new Map;for(const t of Ve){if(!t.enabled)continue;const s=Lt(t,n,t.healthCheckPath);try{const r=await vt(s,5e3),o=r.ok;e.set(t.name,o),o?At(t.name):ce(t.name,`status:${r.status}`)}catch{e.set(t.name,!1),ce(t.name,"health-check-failed")}}return e}function Xe(){const n=En(ee)?ee==null?void 0:ee.cdn:null;return Array.from(fe.entries()).map(([e,t])=>({name:e,status:t,preferred:n===e,..._n(t)}))}function It(){Sn(!0),console.log("[CDN Fallback] All CDN status reset")}const hr=Object.freeze(Object.defineProperty({__proto__:null,buildCDNUrl:Lt,ensureCDNPreferenceLoaded:_t,extractVersionFromCDNPath:Ln,fetchFromCDNWithFallback:Pt,getAvailableCDNs:An,getCDNStatusReport:Xe,isCDNAvailable:Rt,markCDNFailure:ce,markCDNSuccess:At,performHealthCheck:kt,resetCDNStatus:It,setCDNPreference:Tn},Symbol.toStringTag,{value:"Module"}));function Ot(n){return n==="/"||n==="/index.html"}const gr=["/version.json","/manifest.json","/sw.js","/precache-manifest.json","/idle-prefetch-manifest.json"];function fr(n,e){return Ot(e)?!0:n==="navigate"&&!e.endsWith(".html")}function pr(n){return Ot(n)}function Pn(n){return Ot(n)?!0:gr.some(e=>n.endsWith(e))}function mr(n){return!Pn(n)}const F=self;wn(F).setDebugClientCountChangedCallback(Ir);const te={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};function Ye(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 br(){console.log=(...n)=>{te.log(...n),Et()&&!Ye(n)&&Qe("log",n)},console.info=(...n)=>{te.info(...n),Et()&&!Ye(n)&&Qe("info",n)},console.warn=(...n)=>{te.warn(...n),Ye(n)||Qe("warn",n)},console.error=(...n)=>{te.error(...n),Ye(n)||Qe("error",n)}}function wr(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 Qe(n,e){try{const{message:t,stack:s}=wr(e),r=t.startsWith("[SW]")||t.startsWith("[SW-")?t:`[SW] ${t}`;typeof Wt=="function"&&Wt({logLevel:n,logMessage:r,logStack:s,logSource:"service-worker"})}catch(t){te.error("[SW Console Capture] forwardSWConsoleLog failed:",t)}}let Wt=null;br(),Promise.resolve().then(()=>ye).then(({setLLMApiLogBroadcast:n})=>{n(e=>{const t=O();t&&t.sendDebugLLMLog(e)})});const C="0.6.72",Bt=`drawnix-v${C}`,L="drawnix-images",Ee=`drawnix-static-v${C}`,Je="drawnix-fonts",ne="sw-cache-date",pe="sw-cache-created-at",xt="x-sw-source",Nt="x-sw-revision",Gt="x-sw-app-version",kn="x-sw-fetch-target",yr="ServiceWorkerDB",Sr=2,Te="failedDomains",De="versionState",In="app-version-state",On="/__aitu_cache__/",Wn="/__aitu_generated__/audio/",Cr="/asset-library/",Ze=location.hostname==="localhost"||location.hostname==="127.0.0.1",Er=[{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"}],Tr=/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i,Dr=/\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i,Ft=/\.(mp3|wav|ogg|oga|m4a|aac|flac|opus)$/i,_r=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 Ut(n){const e=new URL(typeof n=="string"?n:n.toString()),t=Array.from(e.searchParams.keys());for(const s of t)_r.has(s.toLowerCase())&&e.searchParams.delete(s);return e}const j=new Map,me=new Map,Bn=30*1e3,Pe=new Map,U=new Map,Ar=300*1e3,xn=10,_e=new Set,Ae=new Set,Rr=3600*1e3,qt=new Map;function Nn(n){Ae.add(n),qt.set(n,Date.now()),console.warn(`Service Worker: 标记 ${n} 为 CORS 问题域名,后续请求将跳过 SW`)}function Lr(n){if(!Ae.has(n))return!1;const e=qt.get(n);return e&&Date.now()-e>Rr?(Ae.delete(n),qt.delete(n),!1):!0}const Q=[],Gn=7,V=[],vr=500;let k=!1;function I(n){if(!k)return"";const e=Math.random().toString(36).substring(2,10),t={...n,id:e,timestamp:Date.now()};return V.unshift(t),V.length>vr&&V.pop(),Fn(t),e}function v(n,e){if(!k||!n)return;const t=V.find(s=>s.id===n);t&&(Object.assign(t,e),Fn(t))}function Fn(n){const e=O();e&&e.sendDebugLog(n)}function et(){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 Mr(n){try{const e=await et(),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 Un(){try{await qn();const n=await et(),s=n.transaction(["logs"],"readonly").objectStore("logs").index("timestamp"),r=Date.now()-Gn*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 et(),s=n.transaction(["logs"],"readwrite").objectStore("logs").index("timestamp"),r=Date.now()-Gn*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 Hn(){try{const n=await et(),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 jn=500;function Ht(n){const e=n.logLevel==="warn"||n.logLevel==="error";if(!(k||e))return;const r={id:Math.random().toString(36).substring(2,10),timestamp:Date.now(),type:"console",...n};Mr(r),Q.unshift(r),Q.length>jn&&(Q.length=jn),k&&Pr(r)}Wt=Ht;function Pr(n){const e=O();e&&e.sendConsoleLog(n)}function kr(){let n=0;return U.forEach(e=>{e.blob&&(n+=e.blob.size)}),n}function zn(){return{version:C,cacheNames:[Bt,L,Ee,Je],pendingImageRequests:j.size,pendingVideoRequests:Pe.size,videoBlobCacheSize:U.size,videoBlobCacheTotalBytes:kr(),completedImageRequestsSize:me.size,failedDomainsCount:_e.size,failedDomains:Array.from(_e),corsFailedDomainsCount:Ae.size,corsFailedDomains:Array.from(Ae),debugLogsCount:V.length,consoleLogsCount:Q.length,debugModeEnabled:k,memoryStats:{pendingRequestsMapSize:j.size,completedRequestsMapSize:me.size,videoBlobCacheMapSize:U.size,failedDomainsSetSize:_e.size,corsFailedDomainsSetSize:Ae.size,debugLogsArraySize:V.length,consoleLogsArraySize:Q.length}}}function jt(){return V}function $n(){V.length=0}function Vn(){Q.length=0}function zt(){k||(k=!0,Me(!0),$e(!0),te.log("Service Worker: Debug mode enabled (debug page connected)"))}function $t(){k&&(k=!1,Me(!1),$e(!1),Q.length=0,V.length=0,te.log("Service Worker: Debug mode disabled (no debug pages)"))}function Ir(n){n>0?zt():$t()}function Kn(n){for(const e of Er)if(n.hostname===e.hostname&&n.pathname.includes(e.pathPattern))return e;return null}function Or(n,e){return Tr.test(n.pathname)||e.destination==="image"||Kn(n)!==null}function Wr(n,e){return Dr.test(n.pathname)||e.destination==="video"||n.pathname.includes("/video/")||n.hash.startsWith("#merged-video-")||n.hash.includes("video")}function Br(n,e){return Ft.test(n.pathname)||e.destination==="audio"||n.pathname.includes("/audio/")}function xr(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 Nr(n){return n.pathname.includes(":generateContent")||n.pathname.includes(":streamGenerateContent")}function Xn(n){return`drawnix-static-v${n}`}function Yn(){return{committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle",updatedAt:Date.now()}}function Qn(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 tt(){return new Promise((n,e)=>{const t=indexedDB.open(yr,Sr);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;r.objectStoreNames.contains(Te)||r.createObjectStore(Te,{keyPath:"domain"}),r.objectStoreNames.contains(De)||r.createObjectStore(De,{keyPath:"key"})}})}async function ke(){try{const n=await tt();return await new Promise((e,t)=>{const o=n.transaction([De],"readonly").objectStore(De).get(In);o.onerror=()=>t(o.error),o.onsuccess=()=>{const a=o.result;e(Qn((a==null?void 0:a.state)||Yn()))}})}catch(n){return console.warn("Service Worker: 无法读取版本状态:",n),Yn()}}async function Gr(n){const e=Qn(n);try{const t=await tt();await new Promise((s,r)=>{const o=t.transaction([De],"readwrite");o.objectStore(De).put({key:In,state:e}),o.oncomplete=()=>s(),o.onerror=()=>r(o.error)})}catch(t){console.warn("Service Worker: 无法写入版本状态:",t)}return e}async function be(n){const e=await ke(),t=typeof n=="function"?n(e):n;return Gr({...e,...t,updatedAt:Date.now()})}async function le(n){const e=await ke(),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 Fr(){try{const n=await tt();return await new Promise((e,t)=>{const o=n.transaction([Te],"readonly").objectStore(Te).getAll();o.onsuccess=()=>{o.result.forEach(i=>_e.add(i.domain)),e()},o.onerror=()=>t(o.error)})}catch(n){console.warn("Service Worker: 无法加载失败域名列表:",n)}}async function Ur(n){try{const e=await tt();return await new Promise((t,s)=>{const r=e.transaction([Te],"readwrite");r.objectStore(Te).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 be({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await le();return}await be(t=>({committedVersion:t.committedVersion||C,pendingVersion:C,pendingReadyAt:Date.now(),upgradeState:"ready"}));const e=O();e&&e.sendSWNewVersionReady(C),await le()}async function Hr(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 Jn=2,Vt=1500,Kt=2500,jr=8e3,zr=5e3,$r=6e4,Vr=600*1e3,Kr=["offline-static-assets"];let Ie=0,Zn=0;const Oe=new Set,We=new Set,Be=new Set,nt=new Map;let es=Promise.resolve(),xe=null,Ne=0,ue=!1,st=!1;function y(n,e){if(e===void 0){console.info(`[SWDebug] ${n}`);return}console.info(`[SWDebug] ${n}`,e)}function ts(){return Xe().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 ns(n,e,t){console.warn("[SW Static 503]",{stage:n,requestUrl:e.url,destination:e.destination,mode:e.mode,unavailableCDNs:ts(),...t})}let Xt={phase:"idle",percent:0,completed:0,total:0,failed:0,version:C,updatedAt:Date.now()};async function ss(n){const e={type:"SW_BOOT_PROGRESS",...Xt};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 we(n,e){Xt={...Xt,...n,version:C,updatedAt:Date.now()},ss(e)}async function Xr(){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:Ce(n)}),null}}let Yt=null;async function Yr(){try{const n=await fetch("./idle-prefetch-manifest.json",{cache:"reload"});if(!n.ok)return y("loadIdlePrefetchManifest: response not ok",{status:n.status,statusText:n.statusText}),null;const e=await n.json();return y("loadIdlePrefetchManifest: loaded",{version:e.version,defaults:e.defaults||[],groupEntryCounts:Object.fromEntries(Object.entries(e.groups).map(([t,s])=>[t,s.length]))}),e}catch(n){return y("loadIdlePrefetchManifest: failed",{error:Ce(n)}),null}}async function rt(){return Yt||(Yt=Yr()),Yt}async function Qt(n){const e={type:"SW_IDLE_PREFETCH_STATUS",completedGroups:Array.from(Be),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 Qr(n,e){return`${n}@${e}`}async function ot(n){try{return(await n.keys()).length}catch{return-1}}function at(n,e){const t=es.catch(()=>{}).then(async()=>{y("idle prefetch task start",{label:n});try{await e()}finally{y("idle prefetch task done",{label:n})}});return es=t.catch(s=>{console.warn("[SWDebug] idle prefetch task failed",{label:n,error:Ce(s)})}),t}function Jr(n){return Math.min($r,zr*2**Math.max(0,n-1))}function rs(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),Kr.forEach(r),Object.keys(n.groups).forEach(r),t}function os(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=Qr(h.url,h.revision);if(Oe.has(f)||(u=!0,We.has(f)))continue;const p=nt.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 Zr(n,e=Kt){const t=Math.max(0,Math.round(e)),s=Date.now()+t;if(xe!==null){if(Ne<=s){y("scheduleIdlePrefetchSweep skipped: earlier timer already exists",{reason:n,scheduledInMs:Math.max(0,Ne-Date.now()),requestedDelayMs:t});return}clearTimeout(xe),xe=null,Ne=0}Ne=s,xe=self.setTimeout(()=>{xe=null,Ne=0,at(`idle-sweep:${n}`,async()=>{await ut(`scheduled:${n}`)})},t),y("scheduleIdlePrefetchSweep queued",{reason:n,delayMs:t})}function eo(){return Ie===0?!1:Date.now()-Ie<Vt}function to(){if(Ie===0)return Promise.resolve();const n=Date.now()-Ie,e=Math.max(0,Vt-n)+100;return y("waitForIdlePrefetchWindow: delaying idle prefetch",{elapsedMs:n,waitMs:e,recentFetchWindowMs:Vt}),new Promise(t=>{setTimeout(t,e)})}function no(n,e){if(n.request.method!=="GET"||!n.clientId||e.origin!==self.location.origin||e.pathname.startsWith(On)||e.pathname.startsWith(Wn)||e.pathname==="/sw.js"||e.pathname==="/precache-manifest.json"||e.pathname==="/idle-prefetch-manifest.json")return!1;const t=Date.now();return t-Zn<jr?!1:(Zn=t,!0)}function so(n){return Pn(n)}function as(n,e){return Ze||n.method!=="GET"||n.mode==="navigate"||n.destination==="document"||so(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 it(n){const e=new URL(n,self.location.origin),t=new URL(`${e.pathname}${e.search}`,self.location.origin);return{requestUrl:e,resourcePath:`${e.pathname}${e.search}`,cacheKey:t.href,originFetchUrl:t.href}}function ct(n,e,t){const s=t.headers.get("Content-Type")||"";return t.status===200&&s.includes("text/html")&&as(n,e)}function ro(n,e){const t=new Headers(n.headers);return t.set(xt,e.source),t.set(Nt,e.revision),t.set(Gt,e.appVersion||C),e.fetchTarget&&t.set(kn,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 Jt(n,e,t,s){const r=ro(t,s);return await n.put(e,r.clone()),r}async function lt(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 oo(n,e){const t=it(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 ao(n,e,t){await n.delete(e),t!==e.url&&await n.delete(t)}async function is(n,e,t){try{const s=it(e),r=await n.match(s.cacheKey);if(r){const c=r.headers.get(Nt),l=r.headers.get(Gt);if(c===t&&l===C)return{url:e,success:!0,skipped:!0}}let o=null,a="server",i=s.originFetchUrl;if(mr(s.requestUrl.pathname)){const c=await Pt(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&&ct(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 Jt(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 io(n,e){const s=[],r=e.length;let o=0,a=0;const i=await ot(n);y("precacheStaticFiles start",{total:r,concurrency:6,cacheEntriesBefore:i,sampleUrls:e.slice(0,8).map(p=>p.url)}),we({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})=>is(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}))}),we({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 ot(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 cs(n){if(y("prefetchIdleGroups start",{groupNames:n}),n.length===0)return{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const e=await rt();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(Be),s=os(e,n);if(s.completedGroups.forEach(u=>Be.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:Oe.size,activeEntries:We.size}),{completedGroups:s.completedGroups,pendingGroups:s.pendingGroups,queuedEntries:0,coolingEntries:s.coolingEntries,nextRetryDelayMs:s.nextRetryDelayMs};const r=await caches.open(Ee),o=await ot(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+=Jn){for(;eo();)await to();const h=a.slice(u,u+Jn);h.forEach(([g])=>We.add(g));const f=await Promise.allSettled(h.map(([,{url:g,revision:m}])=>is(r,g,m))),p=[];f.forEach((g,m)=>{const[d]=h[m];if(We.delete(d),g.status==="fulfilled"&&g.value.success)nt.delete(d),Oe.add(d);else{const b=nt.get(d),S=((b==null?void 0:b.count)||0)+1,E=Jr(S);nt.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:Oe.size,activeEntries:We.size})}const i=os(e,n),c=i.completedGroups.filter(u=>!t.has(u));c.forEach(u=>Be.add(u));const l=await ot(r);return y("prefetchIdleGroups finished",{groupNames:n,newlyCompletedGroups:c,pendingGroups:i.pendingGroups,completedEntries:Oe.size,cacheEntriesBefore:o,cacheEntriesAfter:l,completedGroups:Array.from(Be),coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}),{completedGroups:c,pendingGroups:i.pendingGroups,queuedEntries:a.length,coolingEntries:i.coolingEntries,nextRetryDelayMs:i.nextRetryDelayMs}}async function ut(n,e=[]){const t=await rt();if(!t)return y("prefetchPendingIdleGroups skipped: manifest missing",{reason:n,preferredGroups:e}),{completedGroups:[],pendingGroups:[],queuedEntries:0,coolingEntries:0,nextRetryDelayMs:null};const s=rs(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 cs(s);return r.completedGroups.length>0&&await Qt(),r.pendingGroups.length>0&&Zr(`${n}:pending`,r.nextRetryDelayMs??Kt),y("prefetchPendingIdleGroups done",{reason:n,preferredGroups:e,orderedGroups:s,summary:r}),r}async function co(){var t;const n=await rt(),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 ut("default-groups",e)}async function lo(){const n=await rt();if(!n){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: manifest missing");return}const e=rs(n);if(e.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady skipped: no groups");return}const t=Date.now();let s=0;for(;;){s+=1;const r=await cs(e);if(r.completedGroups.length>0&&await Qt(),r.pendingGroups.length===0){y("prewarmAllIdlePrefetchGroupsForUpdateReady complete",{orderedGroups:e,iteration:s,elapsedMs:Date.now()-t});return}const o=Date.now()-t;if(o>=Vr)throw new Error(`idle-prefetch incomplete after ${o}ms: pending groups ${r.pendingGroups.join(", ")}`);const a=Math.max(250,r.nextRetryDelayMs??(r.queuedEntries>0?Kt:1e3));y("prewarmAllIdlePrefetchGroupsForUpdateReady waiting next round",{orderedGroups:e,iteration:s,pendingGroups:r.pendingGroups,coolingEntries:r.coolingEntries,queuedEntries:r.queuedEntries,waitMs:a,elapsedMs:o}),await new Promise(i=>{setTimeout(i,a)})}}F.addEventListener("install",n=>{y("install event received",{version:C}),ue=!!F.registration.active,st=!ue,ue||F.skipWaiting(),we({phase:"installing",percent:0,completed:0,total:0,failed:0,message:"正在读取启动资源清单..."}),n.waitUntil((async()=>{await Fr(),await be(e=>({committedVersion:e.committedVersion||C,pendingVersion:ue?C:null,pendingReadyAt:null,upgradeState:ue?"prewarming":"idle"})),await le();try{const e=await Xr();if(e&&e.length>0){const t=await caches.open(Ee),s=await io(t,e);if(ue&&s.failCount>0)throw new Error(`precache incomplete: ${s.failCount}/${s.total} files failed`)}else Ze&&we({phase:"development",percent:100,completed:0,total:0,failed:0,message:"开发模式下跳过静态预缓存"});ue&&await lo(),await qr(ue)}catch(e){await be(t=>({committedVersion:t.committedVersion||C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"})),await le(),we({phase:"error",message:`启动资源预热失败:${Ce(e)}`}),console.warn("Service Worker: Precache failed:",e)}})())}),F.addEventListener("activate",n=>{y("activate event received",{version:C}),we({phase:"activating",percent:100,message:"启动缓存服务正在接管页面..."}),n.waitUntil((async()=>{await ke(),await be({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"idle"}),await le();try{const{ensureCDNPreferenceLoaded:t}=await Promise.resolve().then(()=>hr);await t()}catch(t){console.warn("Failed to load persisted CDN preference:",t)}st?(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"),at("default-groups",async()=>co())},800);const e=O();e&&(e.sendSWActivated(C),y("activate: sent sw:activated broadcast")),we({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 ke(),r=Xn(s.committedVersion||C),o=e.filter(i=>i.startsWith("drawnix-static-v")&&i!==Ee&&i!==r),a=e.filter(i=>i.startsWith("drawnix-v")&&i!==Bt&&i!==L&&!i.startsWith("drawnix-static-v"));try{const i=await caches.open(Ee);await fo(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)}),ln.archiveOldTasks(100).catch(i=>{console.warn("Failed to archive old tasks:",i)})}))});function uo(n){if(k){const e=O();e&&e.sendPostMessageLog(n)}}async function ho(n,e,t,s){if(Ze)return null;try{const r=it(e.url),o=await Pt(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:ts()}),null;const a=new URL(e.url);if(ct(e,a,o.response))return null;const i=await Jt(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 go(n){const e=n.headers.get(xt)||void 0,t=n.headers.get(kn)||void 0;return{resourceSource:e,resourceFetchTarget:t}}function ls(n,e,t=C){const s=e.headers.get(xt),r=e.headers.get(Nt),o=e.headers.get(Gt);if(!s||!r||!o||o!==t||s!=="server"&&s!=="local"&&s!=="jsdelivr"&&s!=="unpkg")return!0;const a=new URL(n.url);return ct(n,a,e)}async function fo(n){const e=await n.keys();for(const t of e)try{const s=await n.match(t);s&&ls(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(bt()&&!r&&(o=wt(e,n.data,t,s,(m=n.data)==null?void 0:m.__internal__),o&&k)){const b=Ue().find(S=>S.id===o);b&&uo(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 R=new Blob([S],{type:E||(b==="video"?"video/mp4":"image/png")});(async()=>{const{generateThumbnailAsync:H}=await Promise.resolve().then(()=>q);H(R,d,b)})()}return}if(n.data&&n.data.type==="SW_CDN_SET_PREFERENCE"){n.waitUntil(Tn({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}),ss(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(le(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}),Qt(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(at(`message:${d.join(",")||"empty"}`,async()=>{await ut(`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()=>{st=!0,await be({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await le(d),F.skipWaiting();const b=O();b&&b.sendSWUpdated(C)})())}else if(n.data&&n.data.type==="FORCE_UPGRADE")n.waitUntil((async()=>{st=!0,await be({committedVersion:C,pendingVersion:null,pendingReadyAt:null,upgradeState:"committing"}),await le(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&&en(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)&&yo(d).then(()=>{}).catch(b=>{console.error("Service Worker: Failed to batch delete caches:",b)})}else if(n.data&&n.data.type==="CLEAR_ALL_CACHE")So().then(()=>{}).catch(d=>{console.error("Service Worker: Failed to clear all cache:",d)});else if(n.data&&n.data.type==="SW_DEBUG_ENABLE"){k=!0,Me(!0),$e(!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"){k=!1,Me(!1),$e(!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(()=>ye),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(()=>ye);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:k,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(()=>rr),b=jt(),S=d(),E=n.source;E&&E.postMessage({type:"SW_DEBUG_LOGS",logs:[...b,...S.map(R=>({...R,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=Ue(),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 po="MemorySnapshotDB",de="snapshots",us=50;async function Zt(){return new Promise((n,e)=>{const t=indexedDB.open(po,1);t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result),t.onupgradeneeded=s=>{const r=s.target.result;if(!r.objectStoreNames.contains(de)){const o=r.createObjectStore(de,{keyPath:"id"});o.createIndex("timestamp","timestamp",{unique:!1}),o.createIndex("type","type",{unique:!1})}}})}async function ds(n){try{const e=await Zt(),t=e.transaction(de,"readwrite"),s=t.objectStore(de);s.put(n);const r=s.count();r.onsuccess=()=>{const o=r.result;if(o>us){const i=s.index("timestamp").openCursor();let c=0;const l=o-us;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 hs(){try{const n=await Zt(),s=n.transaction(de,"readonly").objectStore(de).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 gs(){try{const n=await Zt(),e=n.transaction(de,"readwrite");e.objectStore(de).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 mo=["ConsoleLogDB","ServiceWorkerDB","sw-task-queue","aitu-workspace","drawnix-unified-cache","drawnix-kv-storage","drawnix-prompts","drawnix-chat-db","MemorySnapshotDB"];function bo(n){try{const e=JSON.stringify(n);return new Blob([e]).size}catch{return 0}}async function wo(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+=bo(S.value),i++,d++,S.continue();else if(c++,c===r.length){s.close();const E=i>0?a/i:0,R=Math.round(E*o);e({count:o,totalSize:R})}},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 fs(){const n={},e=[Bt,L,Ee,Je];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 mo)try{const s=await wo(t);s.count>0&&(n[`[IDB] ${t}`]={...s,type:"indexeddb"})}catch{}return n}async function en(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 yo(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 So(){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 ps(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 Co(){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,ms=300*1e3,bs=500;function Eo(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 To(n){const e=se.get(n);return e?Date.now()-e>ms?(se.delete(n),!1):!0:!1}function ws(n){if(Eo(n)){if(se.size>=bs){const e=Date.now();for(const[t,s]of se)e-s>ms&&se.delete(t);if(se.size>=bs){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:"){I({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(Ie=t,no(n,e)){const s=`${e.pathname}${e.search}`;y("fetch: enqueue idle prefetch recheck",{clientId:n.clientId,requestUrl:s}),n.waitUntil(at(`fetch-recheck:${s}`,async()=>{await ut(`fetch:${s}`)}))}if(e.pathname.startsWith(On)||e.pathname.startsWith(Wn)){const s=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"cache-url",details:"Intercepting cache URL request"});n.respondWith(_o(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(Cr)){const s=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"asset-library",details:"Intercepting asset library request"});n.respondWith(Ao(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"){I({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")){I({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")){I({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(Lr(e.hostname)){I({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&&Br(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=I({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(Ro(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(Wr(e,n.request)){const s=Date.now(),r=n.request.headers.get("range"),o=I({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(Lo(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(xr(e,n.request)){const s=Date.now(),r=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"font",details:"Font request"});n.respondWith(Do(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&&Or(e,n.request)){if(To(n.request.url)){I({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=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"image",details:"External image request"});n.respondWith(ko(n.request).then(o=>(o.status===404&&ws(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 ws(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=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"static",details:s?"Navigation request":`Static resource (${n.request.destination})`});n.respondWith(vo(n.request).then(i=>{const c=go(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(k){if(Nr(e)){I({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=I({type:"fetch",url:n.request.url,method:n.request.method,requestType:"xhr",details:`XHR/API request (${n.request.method})`});n.respondWith((async()=>{try{const r=n.request.clone();let o;const a={};if(n.request.headers.forEach((h,f)=>{a[f]=h}),["POST","PUT","PATCH"].includes(n.request.method))try{const h=n.request.headers.get("content-type")||"";h.includes("application/json")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):h.includes("application/x-www-form-urlencoded")?(o=await r.text(),o.length>2e3&&(o=o.substring(0,2e3)+"... (truncated)")):o=`[${h||"binary data"}]`}catch{o="[unable to read body]"}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((h,f)=>{u[f]=h});try{const h=i.headers.get("content-type")||"";h.includes("application/json")||h.includes("text/")?(l=await c.text(),l.length>5e3&&(l=l.substring(0,5e3)+"... (truncated)")):l=`[${h||"binary data"}] (${i.headers.get("content-length")||"unknown"} bytes)`}catch{l="[unable to read response body]"}return 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 Eo(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(Je),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(fe,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(Je)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function Zt(n,e={}){return fetch(n,e)}async function To(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/")||Gt.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(()=>H),p=await g(u.toString(),l,[t.pathname]);if(p){const h=await p.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(()=>H);f(g,t.pathname,"image")}return o?Re(g,s,e):r?Ge(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 Do(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),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=Gt.test(t.pathname);if(i&&!g){const{generateThumbnailAsync:p}=await Promise.resolve().then(()=>H);p(u,r,"image")}return g&&s?Re(u,s,e):f?Ge(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 _o(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10),s=n.headers.get("range"),o=Ft(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 Ge(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(),p=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",[ne]:f,[fe]:f,"sw-image-size":u.size.toString()}});return await a.put(o,p.clone()),Ge(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 Ge(l,s,t)}catch{return c}return new Response("Audio loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const ut=Symbol("VIDEO_LOAD_ERROR");async function Ao(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=Ft(e),c=i.toString();if(a){const f=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:p,createThumbnailResponse:h}=await Promise.resolve().then(()=>H),m=await p(c,f);if(m){const d=await m.response.blob();return h(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=Pe.get(c);if(l){l.count=(l.count||1)+1;const f=await l.promise;if(f===ut)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 Re(f,s,t)}if(U.has(c)){const f=U.get(c);if(f)return f.timestamp=Date.now(),Re(f.blob,s,t)}try{const p=await(await caches.open(L)).match(c);if(p){const h=await p.blob();return h.size/(1024*1024)<50&&U.set(c,{blob:h,timestamp:Date.now()}),Re(h,s,t)}}catch{}const u=(async()=>{try{const f={method:"GET",mode:"cors",credentials:"omit",cache:"default"},p=new URL(i),h=await fetch(p,f);if(!h.ok)return ut;if(h.status===206)return null;const m=await h.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(),[fe]: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 ut}})();Pe.set(c,{promise:u,timestamp:Date.now(),count:1,requestId:t}),u.finally(()=>{Pe.get(c)&&Pe.delete(c)});const g=await u;if(g===ut)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 Re(g,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function Re(n,e,t){return bs(n,e,t,n.type||"video/mp4")}function Ge(n,e,t,s){return bs(n,e,t,s||n.type||"audio/mpeg")}function bs(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 Ro(n){const e=new URL(n.url),t=at(n.url),s=t.cacheKey,r=hr(n.mode,e.pathname),a=(await ke()).committedVersion||C,i=Vn(a),c=await caches.open(i);if(Ze)try{const p=await Zt(n);if(p&&p.status===200&&n.url.startsWith("http"))return c.put(n,p.clone()),p;if(!p.ok){let h=await c.match(n);return!h&&r&&(h=await c.match("/"),h||(h=await c.match("/index.html"))),h||p}return p}catch{let h=await c.match(n);return!h&&r&&(h=await c.match("/"),h||(h=await c.match("/index.html"))),h||(r?ys():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 h=await caches.keys();for(const m of h)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 h=await Zt(n,{cache:"reload"});if(h&&h.status===200&&n.url.startsWith("http")&&a===C){c.put(n,h.clone());const m=new URL(n.url);if(gr(m.pathname)){const d=new URL("/",m.origin).href,b=new URL("/index.html",m.origin).href;n.url!==d&&c.put(d,h.clone()),n.url!==b&&c.put(b,h.clone())}return h}return h}catch{return ys()}}const{response:l,matchedBy:u}=await so(c,n);if(l){if(!is(n,l,a))return u==="normalized"&&w("handleStaticRequest: normalized static cache hit",{requestUrl:n.url,normalizedCacheKey:s}),l;await ro(c,n,s)}const g=t.resourcePath;if(os(n,e)){n.url!==s&&w("handleStaticRequest: cross-origin static cache miss",{requestUrl:n.url,normalizedCacheKey:s,resourcePath:g,committedVersion:a});const p=await ct(n,[s]);if(p)return p;const h=An(e.pathname),m=h||a,d=await lo(c,n,g,m);return d||(ts("smart-cdn-resource-failed",n,{resourcePath:g,committedVersion:a,hasEmbeddedVersion:!!h,attemptedVersion:m}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const p=await Zt(n);if(it(n,e,p)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const m=await ct(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 Yt(c,n,p,{source:"server",revision:"runtime",appVersion:a});if(p.status>=400){const m=await ct(n,[s]);if(m)return m}return p}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const h=await ct(n,[s]);return h||(ts("origin-fetch-exception",n,{resourcePath:g,committedVersion:a}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}}function ys(){return new Response(`<!DOCTYPE html>
|
|
14
|
+
${l}`}),i}catch(r){throw v(s,{error:String(r),duration:Date.now()-t}),r}})());return}}}});async function Do(n){new URL(n.url);const e=Math.random().toString(36).substring(2,10);try{const t=await caches.open(Je),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(pe,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(Je)).match(n);return r||new Response("Font loading failed",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}})}}async function tn(n,e={}){return fetch(n,e)}async function _o(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/")||Ft.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(()=>q),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(()=>q);f(h,t.pathname,"image")}return o?Re(h,s,e):r?Ge(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 Ao(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),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=Ft.test(t.pathname);if(i&&!h){const{generateThumbnailAsync:p}=await Promise.resolve().then(()=>q);p(u,r,"image")}return h&&s?Re(u,s,e):f?Ge(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 Ro(n){const e=new URL(n.url),t=Math.random().toString(36).substring(2,10),s=n.headers.get("range"),o=Ut(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 Ge(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,[pe]:f,"sw-image-size":u.size.toString()}});return await a.put(o,p.clone()),Ge(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 Ge(l,s,t)}catch{return c}return new Response("Audio loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}const dt=Symbol("VIDEO_LOAD_ERROR");async function Lo(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=Ut(e),c=i.toString();if(a){const f=e.searchParams.get("thumbnail")||"small",{findThumbnailWithFallback:p,createThumbnailResponse:g}=await Promise.resolve().then(()=>q),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(()=>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=Pe.get(c);if(l){l.count=(l.count||1)+1;const f=await l.promise;if(f===dt)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 Re(f,s,t)}if(U.has(c)){const f=U.get(c);if(f)return f.timestamp=Date.now(),Re(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()}),Re(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 dt;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(),[pe]:Date.now().toString(),"sw-video-size":m.size.toString()}});await b.put(c,S);const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(m,c,"video")}catch{}}return m}catch{return dt}})();Pe.set(c,{promise:u,timestamp:Date.now(),count:1,requestId:t}),u.finally(()=>{Pe.get(c)&&Pe.delete(c)});const h=await u;if(h===dt)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 Re(h,s,t)}catch{return new Response("Video loading error",{status:500,statusText:"Internal Server Error",headers:{"Content-Type":"text/plain"}})}}function Re(n,e,t){return ys(n,e,t,n.type||"video/mp4")}function Ge(n,e,t,s){return ys(n,e,t,s||n.type||"audio/mpeg")}function ys(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 vo(n){const e=new URL(n.url),t=it(n.url),s=t.cacheKey,r=fr(n.mode,e.pathname),a=(await ke()).committedVersion||C,i=Xn(a),c=await caches.open(i);if(Ze)try{const p=await tn(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?Ss():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 tn(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(pr(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 Ss()}}const{response:l,matchedBy:u}=await oo(c,n);if(l){if(!ls(n,l,a))return u==="normalized"&&y("handleStaticRequest: normalized static cache hit",{requestUrl:n.url,normalizedCacheKey:s}),l;await ao(c,n,s)}const h=t.resourcePath;if(as(n,e)){n.url!==s&&y("handleStaticRequest: cross-origin static cache miss",{requestUrl:n.url,normalizedCacheKey:s,resourcePath:h,committedVersion:a});const p=await lt(n,[s]);if(p)return p;const g=Ln(e.pathname),m=g||a,d=await ho(c,n,h,m);return d||(ns("smart-cdn-resource-failed",n,{resourcePath:h,committedVersion:a,hasEmbeddedVersion:!!g,attemptedVersion:m}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}try{const p=await tn(n);if(ct(n,e,p)){console.warn("Service Worker: HTML response for static resource (404 fallback), trying old caches:",n.url);const m=await lt(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 Jt(c,n,p,{source:"server",revision:"runtime",appVersion:a});if(p.status>=400){const m=await lt(n,[s]);if(m)return m}return p}catch{console.warn("[SW] Network failed, trying old caches:",n.url);const g=await lt(n,[s]);return g||(ns("origin-fetch-exception",n,{resourcePath:h,committedVersion:a}),new Response("Resource unavailable offline",{status:503,statusText:"Service Unavailable",headers:{"Content-Type":"text/plain"}}))}}function Ss(){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 en=15e3,ws=3e4;function Ss(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function Lo(){const n=Date.now(),e=[];if(U.forEach((t,s)=>{n-t.timestamp>Dr&&e.push(s)}),e.length>0&&e.forEach(t=>U.delete(t)),U.size>Wn){const t=Array.from(U.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=U.size-Wn,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>U.delete(o))}}function vo(){const n=Date.now(),e=[];j.forEach((s,r)=>{n-s.timestamp>ws&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>j.delete(s)));const t=[];pe.forEach((s,r)=>{n-s.timestamp>On&&t.push(r)}),t.length>0&&t.forEach(s=>pe.delete(s)),Lo()}async function Mo(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=Ft(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),h=await f(l,a,[n.url,c.url]);if(h){const m=await h.response.blob();return p(m)}}const u=pe.get(l);if(u){if(Date.now()-u.timestamp<On)return u.response.clone();pe.delete(l)}if(j.has(l)){const f=j.get(l);if(f){const p=Date.now()-f.timestamp;if(p>ws)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 h=await Ss(f.promise,en,"Image request timeout");return h&&h.clone?h.clone():h}catch(h){if(h.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 重复请求等待超时,清理并返回超时响应让前端直接加载`),j.delete(l),Cs(n.url,e);throw h}}}}vo();const g=Po(c,n.url,l,e,s,o?a:void 0);j.set(l,{promise:g,timestamp:Date.now(),count:1,originalRequestId:e,duplicateRequestIds:[]}),g.then(f=>{f&&f.ok&&pe.set(l,{response:f.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{j.get(l)&&j.delete(l)});try{return await Ss(g,en,"Image request timeout")}catch(f){if(f.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${en}ms),清理并返回超时响应让前端直接加载:`,n.url),j.delete(l),Cs(n.url,e);throw f}}catch(e){throw e}}function Cs(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 Po(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(),R=m.headers.get(fe)||S,q=new Response(b,{status:m.status,statusText:m.statusText,headers:{...Object.fromEntries(m.headers.entries()),[ne]:E.toString(),[fe]:R}});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(),[fe]: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=$n(i);let l=null,u=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),De.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 p;u?p=[l]:(p=[e],l&&p.push(l));let h=null;for(let m=0;m<p.length;m++){const d=p[m],b=m>0;for(const S of f)try{let E,R=!1;for(let q=0;q<=2;q++)try{if(g=await fetch(d,S),g&&(g.status!==0||g.type==="opaque"))break}catch(re){E=re;const Le=re.message||"";if(Le.includes("CORS")||Le.includes("cross-origin")||Le.includes("Access-Control-Allow-Origin")||Le.includes("Failed to fetch")||Le.includes("NetworkError")||Le.includes("TypeError")){R=!0;break}q<2&&await new Promise(Xo=>setTimeout(Xo,Math.pow(2,q)*1e3))}if(R){const q=new URL(d).hostname;Bn(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(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&&m===0&&!u&&(De.add(c.hostname),Gr(c.hostname).catch(S=>{console.warn("Service Worker: 保存失败域名到数据库时出错:",S)}))}if(!g||g.status===0&&g.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}`,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 m=new URL(e).hostname;return Bn(m),g}if(g.ok){const d=await g.clone().blob(),b=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",[ne]:Date.now().toString(),[fe]: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 gs(t,d.size,d.type),await wo();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 Ur(a);try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await gs(t,d.size,d.type);const{generateThumbnailAsync:R}=await Promise.resolve().then(()=>H);R(d,t,"image")}}catch(R){console.error("Service Worker: Still failed to cache after cleanup:",R)}}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 A=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:C,IMAGE_CACHE_NAME:L,addConsoleLog:Ht,clearAllConsoleLogs:Un,clearConsoleLogs:zn,clearCrashSnapshots:ds,clearDebugLogs:jn,deleteCacheByUrl:Jt,disableDebugMode:zt,enableDebugMode:jt,getCDNStatusReport:Xe,getCacheStats:hs,getCrashSnapshots:us,getDebugLogs:qt,getDebugStatus:qn,getInternalFetchLogs:Et,loadConsoleLogsFromDB:Gn,performHealthCheck:Pt,resetCDNStatus:kt,saveCrashSnapshot:ls},Symbol.toStringTag,{value:"Module"})),dt="drawnix-images-thumb",Es=128,tn=400,ko=.8;function Io(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 nn(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 Ts(n,e,t=["small","large"]){try{for(const s of t)await Oo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Oo(n,e,t){try{const s=t==="large"?tn:Es,r=nn(e,t),o=await caches.open(dt);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}=Io(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 p=await g.convertToBlob({type:"image/jpeg",quality:ko}),h=()=>new Response(p,{headers:{"Content-Type":"image/jpeg","Content-Length":p.size.toString()}}),m=new Request(r,{method:"GET"});await o.put(m,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 Ds(n,e,t=["small","large"]){try{for(const s of t)await Wo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function Wo(n,e,t){try{const s=nn(e,t),r=await caches.open(dt);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 Bo(e,n,t==="large"?tn:Es);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 Bo(n,e,t=tn){const{getChannelManager:s}=await Promise.resolve().then(()=>er),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 sn(n,e,t){try{const s=await caches.open(dt),r=nn(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 xo(n,e,t){let s=await sn(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await sn(n,r,t),s?{response:s,size:r}:null}function No(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 Go(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await Ts(n,e,s):await Ds(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:dt,createThumbnailResponse:No,findThumbnail:sn,findThumbnailWithFallback:xo,generateImageThumbnail:Ts,generateThumbnailAsync:Go,generateVideoThumbnail:Ds},Symbol.toStringTag,{value:"Module"})),de=[],Fo="llm-api-logs",Uo=4,K="logs";function ht(){return new Promise((n,e)=>{const t=indexedDB.open(Fo,Uo);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 _s(){try{const s=(await ht()).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),de}}function Ho(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 qo(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 jo(n=1,e=20,t){let s=await _s();t!=null&&t.taskType&&(s=s.filter(c=>qo(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(Ho),total:r,page:n,pageSize:e,totalPages:o}}async function zo(n){const e=de.find(t=>t.id===n);if(e)return e;try{const r=(await ht()).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 $o(){de.length=0;try{const e=(await ht()).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 Vo(n){if(!n||n.length===0)return 0;const e=new Set(n),t=de.length;for(let r=de.length-1;r>=0;r--)e.has(de[r].id)&&de.splice(r,1);const s=t-de.length;try{const o=(await ht()).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 Ko(n){}const ye=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:$o,deleteLLMApiLogs:Vo,getAllLLMApiLogs:_s,getLLMApiLogById:zo,getLLMApiLogsPaginated:jo,setLLMApiLogBroadcast:Ko},Symbol.toStringTag,{value:"Module"}));return D.APP_VERSION=C,D.IMAGE_CACHE_NAME=L,D.addConsoleLog=Ht,D.clearAllConsoleLogs=Un,D.clearConsoleLogs=zn,D.clearCrashSnapshots=ds,D.clearDebugLogs=jn,D.deleteCacheByUrl=Jt,D.disableDebugMode=zt,D.enableDebugMode=jt,D.getCDNStatusReport=Xe,D.getCacheStats=hs,D.getCrashSnapshots=us,D.getDebugLogs=qt,D.getDebugStatus=qn,D.getInternalFetchLogs=Et,D.loadConsoleLogsFromDB=Gn,D.performHealthCheck=Pt,D.resetCDNStatus=kt,D.saveCrashSnapshot=ls,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 nn=15e3,Cs=3e4;function Es(n,e,t){return Promise.race([n,new Promise((s,r)=>{setTimeout(()=>r(new Error(t)),e)})])}function Mo(){const n=Date.now(),e=[];if(U.forEach((t,s)=>{n-t.timestamp>Ar&&e.push(s)}),e.length>0&&e.forEach(t=>U.delete(t)),U.size>xn){const t=Array.from(U.entries()).sort((o,a)=>o[1].timestamp-a[1].timestamp),s=U.size-xn,r=t.slice(0,s);r.length>0&&r.forEach(([o])=>U.delete(o))}}function Po(){const n=Date.now(),e=[];j.forEach((s,r)=>{n-s.timestamp>Cs&&e.push(r)}),e.length>0&&(console.warn(`Service Worker: 清理 ${e.length} 个过期的 pending 请求`),e.forEach(s=>j.delete(s)));const t=[];me.forEach((s,r)=>{n-s.timestamp>Bn&&t.push(r)}),t.length>0&&t.forEach(s=>me.delete(s)),Mo()}async function ko(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=Ut(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(()=>q),g=await f(l,a,[n.url,c.url]);if(g){const m=await g.response.blob();return p(m)}}const u=me.get(l);if(u){if(Date.now()-u.timestamp<Bn)return u.response.clone();me.delete(l)}if(j.has(l)){const f=j.get(l);if(f){const p=Date.now()-f.timestamp;if(p>Cs)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 Es(f.promise,nn,"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),Ts(n.url,e);throw g}}}}Po();const h=Io(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&&me.set(l,{response:f.clone(),timestamp:Date.now()})}).catch(()=>{}).finally(()=>{j.get(l)&&j.delete(l)});try{return await Es(h,nn,"Image request timeout")}catch(f){if(f.message==="Image request timeout")return console.warn(`Service Worker [${e}]: 图片请求超时(${nn}ms),清理并返回超时响应让前端直接加载:`,n.url),j.delete(l),Ts(n.url,e);throw f}}catch(e){throw e}}function Ts(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 Io(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(()=>q);E(b,n.url,"image")}const S=m.headers.get(ne);if(S){const E=Date.now(),R=m.headers.get(pe)||S,H=new Response(b,{status:m.status,statusText:m.statusText,headers:{...Object.fromEntries(m.headers.entries()),[ne]:E.toString(),[pe]:R}});return n.url.startsWith("http")&&(await a.put(t,H.clone()),e!==t&&await a.delete(e)),H}else{const E=new Response(b,{status:m.status,statusText:m.statusText,headers:{...Object.fromEntries(m.headers.entries()),[ne]:Date.now().toString(),[pe]: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=Kn(i);let l=null,u=!1;c&&c.fallbackDomain&&(l=e.replace(c.hostname,c.fallbackDomain),_e.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,R=!1;for(let H=0;H<=2;H++)try{if(h=await fetch(d,S),h&&(h.status!==0||h.type==="opaque"))break}catch(re){E=re;const Le=re.message||"";if(Le.includes("CORS")||Le.includes("cross-origin")||Le.includes("Access-Control-Allow-Origin")||Le.includes("Failed to fetch")||Le.includes("NetworkError")||Le.includes("TypeError")){R=!0;break}H<2&&await new Promise(Qo=>setTimeout(Qo,Math.pow(2,H)*1e3))}if(R){const H=new URL(d).hostname;Nn(H);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&&(_e.add(c.hostname),Ur(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 Nn(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(),[pe]: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 ps(t,d.size,d.type),await Co();const{generateThumbnailAsync:E}=await Promise.resolve().then(()=>q);E(d,t,"image")}}catch(E){console.warn(`Service Worker: Failed to cache normal response (${b.toFixed(2)}MB, 可能超出存储限制):`,E),await Hr(a);try{if(n.url.startsWith("http")){await a.put(t,S.clone()),e!==t&&await a.delete(e),await ps(t,d.size,d.type);const{generateThumbnailAsync:R}=await Promise.resolve().then(()=>q);R(d,t,"image")}}catch(R){console.error("Service Worker: Still failed to cache after cleanup:",R)}}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 A=Object.freeze(Object.defineProperty({__proto__:null,APP_VERSION:C,IMAGE_CACHE_NAME:L,addConsoleLog:Ht,clearAllConsoleLogs:Hn,clearConsoleLogs:Vn,clearCrashSnapshots:gs,clearDebugLogs:$n,deleteCacheByUrl:en,disableDebugMode:$t,enableDebugMode:zt,getCDNStatusReport:Xe,getCacheStats:fs,getCrashSnapshots:hs,getDebugLogs:jt,getDebugStatus:zn,getInternalFetchLogs:Tt,loadConsoleLogsFromDB:Un,performHealthCheck:kt,resetCDNStatus:It,saveCrashSnapshot:ds},Symbol.toStringTag,{value:"Module"})),ht="drawnix-images-thumb",Ds=128,sn=400,Oo=.8;function Wo(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 rn(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 _s(n,e,t=["small","large"]){try{for(const s of t)await Bo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate image thumbnail:",s)}}async function Bo(n,e,t){try{const s=t==="large"?sn:Ds,r=rn(e,t),o=await caches.open(ht);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}=Wo(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:Oo}),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 As(n,e,t=["small","large"]){try{for(const s of t)await xo(n,e,s)}catch(s){console.warn("[ThumbnailUtils] Failed to generate video thumbnail:",s)}}async function xo(n,e,t){try{const s=rn(e,t),r=await caches.open(ht);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 No(e,n,t==="large"?sn:Ds);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 No(n,e,t=sn){const{getChannelManager:s}=await Promise.resolve().then(()=>nr),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 on(n,e,t){try{const s=await caches.open(ht),r=rn(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 Go(n,e,t){let s=await on(n,e,t);if(s)return{response:s,size:e};const r=e==="small"?"large":"small";return s=await on(n,r,t),s?{response:s,size:r}:null}function Fo(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 Uo(n,e,t,s=["small","large"]){(async()=>{try{t==="image"?await _s(n,e,s):await As(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:ht,createThumbnailResponse:Fo,findThumbnail:on,findThumbnailWithFallback:Go,generateImageThumbnail:_s,generateThumbnailAsync:Uo,generateVideoThumbnail:As},Symbol.toStringTag,{value:"Module"})),he=[],qo="llm-api-logs",Ho=4,K="logs";function gt(){return new Promise((n,e)=>{const t=indexedDB.open(qo,Ho);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 Rs(){try{const s=(await gt()).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),he}}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 $o(n=1,e=20,t){let s=await Rs();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 Vo(n){const e=he.find(t=>t.id===n);if(e)return e;try{const r=(await gt()).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 Ko(){he.length=0;try{const e=(await gt()).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 Xo(n){if(!n||n.length===0)return 0;const e=new Set(n),t=he.length;for(let r=he.length-1;r>=0;r--)e.has(he[r].id)&&he.splice(r,1);const s=t-he.length;try{const o=(await gt()).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 Yo(n){}const ye=Object.freeze(Object.defineProperty({__proto__:null,clearAllLLMApiLogs:Ko,deleteLLMApiLogs:Xo,getAllLLMApiLogs:Rs,getLLMApiLogById:Vo,getLLMApiLogsPaginated:$o,setLLMApiLogBroadcast:Yo},Symbol.toStringTag,{value:"Module"}));return D.APP_VERSION=C,D.IMAGE_CACHE_NAME=L,D.addConsoleLog=Ht,D.clearAllConsoleLogs=Hn,D.clearConsoleLogs=Vn,D.clearCrashSnapshots=gs,D.clearDebugLogs=$n,D.deleteCacheByUrl=en,D.disableDebugMode=$t,D.enableDebugMode=zt,D.getCDNStatusReport=Xe,D.getCacheStats=fs,D.getCrashSnapshots=hs,D.getDebugLogs=jt,D.getDebugStatus=zn,D.getInternalFetchLogs=Tt,D.loadConsoleLogsFromDB=Un,D.performHealthCheck=kt,D.resetCDNStatus=It,D.saveCrashSnapshot=ds,Object.defineProperty(D,Symbol.toStringTag,{value:"Module"}),D})({});
|